nemar-cli 0.10.39-dev.4765 → 0.10.40-PR2304.2ba3060

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,19 +23,19 @@ ${t}`,QM,ZM,eL=(e,t,r)=>{let n=r===""?"":`with ${r.trim()}() `,s=JM.bind(null,n,
23
23
  `)}var Vl=!1;var{spawn:nV}=globalThis.Bun;function zl(e,t=[]){let r=e.replace(sV,'("$1","<redacted>")');for(let n of t)if(n.length>=oV)r=r.split(n).join("<redacted>");return r}function iV(e){let t=["AWS_SESSION_TOKEN","AWS_SECRET_ACCESS_KEY","AWS_ACCESS_KEY_ID"],r=new Set;for(let n of[process.env,e??{}])for(let s of t){let o=n[s];if(typeof o==="string"&&o.length>0)r.add(o)}return[...r]}async function hE(e,t){let r=e.getReader(),n=new TextDecoder,s="";while(!0){let{done:o,value:a}=await r.read();if(o)break;if(a.byteLength===0)continue;t(),s+=n.decode(a,{stream:!0})}return s+n.decode()}async function gE(e,t={}){let r={...process.env,GIT_TERMINAL_PROMPT:"0",...t.env};for(let y of t.unsetEnv??[])delete r[y];let n=nV({cmd:e,cwd:t.cwd,...t.stdin===void 0?{}:{stdin:new TextEncoder().encode(t.stdin)},stdout:"pipe",stderr:"pipe",env:r}),s=!1,o,a,i=performance.now(),c=()=>{if(a!==void 0)clearTimeout(a),a=void 0},u=()=>{if(!t.onInactivityWarning)return;c(),a=setTimeout(()=>{a=void 0;try{t.onInactivityWarning?.(performance.now()-i)}catch{console.error("Could not display subprocess inactivity warning; the child result is unaffected.")}},t.inactivityWarningAfterMs??aV)};if(u(),t.timeout)o=setTimeout(()=>{s=!0,c(),n.kill()},t.timeout);let l=cc()?[...iV(r),...t.redact??[]]:[];if(cc()){let y=t.cwd?` (cwd=${t.cwd})`:"";Ls(Pt.dim(zl(`$ ${e.join(" ")}${y}`,l)))}let d=()=>{i=performance.now(),u()},m,f,p,h=n.exited.then((y)=>(c(),y));try{[m,f,p]=await Promise.all([hE(n.stdout,d),hE(n.stderr,d),h])}finally{if(c(),o)clearTimeout(o)}if(cc()){if(t.sensitiveOutput)Ls(Pt.dim("[sensitive subprocess output suppressed]"));else{if(m.trim())Ls(Pt.dim(zl(m.trimEnd(),l)));if(f.trim())Ls(Pt.yellow(zl(f.trimEnd(),l)))}Ls(Pt.dim(`(exit ${p})`))}if(s)return{stdout:m,stderr:f||`Command timed out after ${Math.round(t.timeout/1000)}s`,exitCode:p??1,timedOut:!0};return{stdout:m,stderr:f,exitCode:p,timedOut:!1}}var sV,oV=8,aV=120000;var yE=L(()=>{Fl();sV=/\(\s*"((?:x-amz-)[^"]*|authorization|proxy-authorization)"\s*,\s*"[^"]*"\s*\)/gi});function uV(){if(process.platform==="darwin")return"macos";if(process.platform==="win32")return"windows";return"linux"}function vE(e,t=uV()){return e.installInstructions[t]}function lV(e){let t=e.match(/(\d+\.\d+(?:\.\d+)?)/);return t?t[1]:void 0}function fV(){let e=Number(process.env.TEST_PROBE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:dV}async function bE(e){try{let{exitCode:t,stdout:r,timedOut:n}=await gE(e.cmd,{timeout:fV()});if(n)return{available:!1,timedOut:!0};if(t!==0)return{available:!1};return{available:!0,version:lV(r)}}catch(t){let r=t instanceof Error?t.message:String(t);if(!r.includes("ENOENT")&&!r.includes("not found"))console.error(` Warning: ${e.name} check failed unexpectedly: ${r}`);return{available:!1}}}async function Gl(){let e=Object.entries(_E);return Promise.all(e.map(async([t,r])=>{let{available:n,version:s,timedOut:o}=await bE(r);return{key:t,name:r.name,purpose:r.purpose,required:r.required,available:n,version:s,timedOut:o,installInstruction:vE(r)}}))}async function bB(){let t=(await Gl()).filter((r)=>r.required&&!r.available);if(t.length===0)return[];console.warn(`
24
24
  Heads up: some tools NEMAR needs for uploading/validating aren't installed yet:`);for(let r of t)console.warn(` - ${r.name} (${r.purpose})`),console.warn(` Install: ${r.installInstruction}`);return console.warn("Run `nemar doctor` anytime to re-check. You can finish signup without them.\n"),t}async function wB(e){let r=cV[e].map((a)=>_E[a]).filter(Boolean),n=await Promise.all(r.map(async(a)=>{let i=await bE(a);return{check:a,available:i.available,timedOut:i.timedOut}}));for(let a of n)if(a.timedOut&&a.check.required)console.warn(`Warning: ${a.check.name} did not respond to a version check in time; continuing anyway.`);let s=n.filter((a)=>!a.available&&!a.timedOut&&a.check.required).map((a)=>({tool:a.check.name,installInstruction:vE(a.check)}));if(s.length===0)return;let o=[`
25
25
  Missing required tools:`];for(let a of s)o.push(` ${a.tool} not installed`),o.push(` Install: ${a.installInstruction}`);throw Error(o.join(`
26
- `))}var _E,cV,dV=4000;var wE=L(()=>{yE();_E={git:{name:"git",purpose:"version control for dataset metadata",cmd:["git","--version"],required:!0,installInstructions:{macos:"brew install git (or install Xcode Command Line Tools)",linux:"sudo apt-get install git OR sudo dnf install git",windows:"winget install Git.Git (or https://git-scm.com/download/win)"}},"git-annex":{name:"git-annex",purpose:"large-file data transfer (upload/download)",cmd:["git-annex","version"],required:!0,installInstructions:{macos:"brew install git-annex",linux:"sudo apt-get install git-annex OR sudo dnf install git-annex",windows:"Download the installer from https://git-annex.branchable.com/install/Windows/"}},gh:{name:"GitHub CLI (gh)",purpose:"GitHub authentication + repository operations",cmd:["gh","--version"],required:!0,installInstructions:{macos:"brew install gh",linux:"See https://cli.github.com/manual/installation",windows:"winget install GitHub.cli (or: scoop install gh)"}},aws:{name:"AWS CLI",purpose:"S3 data upload/download",cmd:["aws","--version"],required:!0,installInstructions:{macos:"brew install awscli",linux:"pip install awscli OR sudo snap install aws-cli --classic",windows:"winget install Amazon.AWSCLI (or the MSI from https://aws.amazon.com/cli/)"}},deno:{name:"Deno",purpose:"BIDS validation",cmd:["deno","--version"],required:!0,installInstructions:{macos:"brew install deno (or: curl -fsSL https://deno.land/install.sh | sh)",linux:"curl -fsSL https://deno.land/install.sh | sh",windows:"winget install DenoLand.Deno (or: irm https://deno.land/install.ps1 | iex)"}}},cV={upload:["git-annex","gh","aws","deno"],download:["gh"],clone:["git","gh"],push:["git-annex","gh"],publish:["gh","aws"],update:["git","gh"],release:["git","gh"]}});var EE;var $E=L(()=>{EE={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.39-dev.4765",description:"CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",type:"module",main:"dist/index.js",bin:{nemar:"dist/index.js","git-annex-remote-nemar":"dist/git-annex-remote-nemar.js"},scripts:{dev:"bun run src/index.ts",build:"bun build src/index.ts src/git-annex-remote-nemar.ts --outdir dist --target bun --minify && sed '1s|#!/usr/bin/env node|#!/usr/bin/env bun|' dist/index.js > dist/index.js.tmp && mv dist/index.js.tmp dist/index.js",test:"bun test",lint:"biome check src/","lint:scrub":"biome check scripts/scrub shared/identifier-scrub.ts test/scrub","test:scrub":"bun test --preload ./test/scrub/helpers/temp-dirs-preload.ts --path-ignore-patterns='__run_every_scrub_suite__' test/scrub test/identifier-scan.test.ts test/identifier-scrub.test.ts test/identifier-dates.test.ts test/identifier-fleet.test.ts","migrations:d1-check":"bun run scripts/d1-migration-check.ts","zarr:geometry-check":"bun run backend/scripts/zarr-geometry-conformance.ts","lint:fix":"biome check --fix src/",format:"biome format --write src/",typecheck:"tsc --noEmit && tsc --noEmit -p backend","generate-openapi":"bun run scripts/generate-openapi.ts",prepublishOnly:"bun run build",prepare:"husky",postinstall:"bun scripts/postinstall-check.mjs",deploy:"wrangler deploy",preview:"wrangler dev"},keywords:["nemar","bids","neuroimaging","eeg","emg","datalad","cli"],author:"NEMAR Team",license:"CC-BY-NC-ND-4.0",repository:{type:"git",url:"git+https://github.com/nemarOrg/nemar-cli.git"},bugs:{url:"https://github.com/nemarOrg/nemar-cli/issues"},homepage:"https://docs.nemar.org",engines:{bun:">=1.0.0"},files:["dist","scripts/postinstall-check.mjs","scripts/recover-datasets.json","scripts/withdrawn-datasets.json","README.md","LICENSE"],dependencies:{chalk:"^5.3.0",commander:"^12.1.0",conf:"^13.0.1",inquirer:"^9.2.15",ora:"^8.0.1",semver:"^7.8.5",zod:"^3.23.8"},"lint-staged":{"src/**/*.{ts,tsx}":["biome check --fix"],"backend/src/**/*.{ts,tsx}":["biome check --fix"]},trustedDependencies:["@biomejs/biome"],devDependencies:{"@anthropic-ai/sdk":"^0.132.1","@asteasolutions/zod-to-openapi":"^7.3.4","@biomejs/biome":"1.9.4","@types/bun":"latest","@types/inquirer":"^9.0.7","@types/semver":"^7.8.0",ajv:"^8.20.0","ajv-formats":"^3.0.1",husky:"^9.1.7",jose:"6.2.12","lint-staged":"^16.3.2",oauth4webapi:"3.8.8","openid-client":"6.8.9",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var uc;var Kl=L(()=>{$E();uc=EE.version});import{mkdirSync as mV,readdirSync as hV,unlinkSync as gV,writeFileSync as yV}from"fs";import{join as Hl}from"path";function PB(){Us=!0}function fc(){return Us}function CB(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function IB(e){TE=e,mr(`Step: ${e}`)}function jB(){RE=!0}function qB(){return RE}function DB(){if(kE)return;Wl=!0}function MB(){Wl=!1,kE=!0}function LB(){return Wl}function mr(e){if(Us)process.stderr.write(`[debug] ${e}
26
+ `))}var _E,cV,dV=4000;var wE=L(()=>{yE();_E={git:{name:"git",purpose:"version control for dataset metadata",cmd:["git","--version"],required:!0,installInstructions:{macos:"brew install git (or install Xcode Command Line Tools)",linux:"sudo apt-get install git OR sudo dnf install git",windows:"winget install Git.Git (or https://git-scm.com/download/win)"}},"git-annex":{name:"git-annex",purpose:"large-file data transfer (upload/download)",cmd:["git-annex","version"],required:!0,installInstructions:{macos:"brew install git-annex",linux:"sudo apt-get install git-annex OR sudo dnf install git-annex",windows:"Download the installer from https://git-annex.branchable.com/install/Windows/"}},gh:{name:"GitHub CLI (gh)",purpose:"GitHub authentication + repository operations",cmd:["gh","--version"],required:!0,installInstructions:{macos:"brew install gh",linux:"See https://cli.github.com/manual/installation",windows:"winget install GitHub.cli (or: scoop install gh)"}},aws:{name:"AWS CLI",purpose:"S3 data upload/download",cmd:["aws","--version"],required:!0,installInstructions:{macos:"brew install awscli",linux:"pip install awscli OR sudo snap install aws-cli --classic",windows:"winget install Amazon.AWSCLI (or the MSI from https://aws.amazon.com/cli/)"}},deno:{name:"Deno",purpose:"BIDS validation",cmd:["deno","--version"],required:!0,installInstructions:{macos:"brew install deno (or: curl -fsSL https://deno.land/install.sh | sh)",linux:"curl -fsSL https://deno.land/install.sh | sh",windows:"winget install DenoLand.Deno (or: irm https://deno.land/install.ps1 | iex)"}}},cV={upload:["git-annex","gh","aws","deno"],download:["gh"],clone:["git","gh"],push:["git-annex","gh"],publish:["gh","aws"],update:["git","gh"],release:["git","gh"]}});var EE;var $E=L(()=>{EE={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.40-PR2304.2ba3060",description:"CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",type:"module",main:"dist/index.js",bin:{nemar:"dist/index.js","git-annex-remote-nemar":"dist/git-annex-remote-nemar.js"},scripts:{dev:"bun run src/index.ts",build:"bun build src/index.ts src/git-annex-remote-nemar.ts --outdir dist --target bun --minify && sed '1s|#!/usr/bin/env node|#!/usr/bin/env bun|' dist/index.js > dist/index.js.tmp && mv dist/index.js.tmp dist/index.js",test:"bun test",lint:"biome check src/","lint:scrub":"biome check scripts/scrub shared/identifier-scrub.ts test/scrub","test:scrub":"bun test --preload ./test/scrub/helpers/temp-dirs-preload.ts --path-ignore-patterns='__run_every_scrub_suite__' test/scrub test/identifier-scan.test.ts test/identifier-scrub.test.ts test/identifier-dates.test.ts test/identifier-fleet.test.ts","migrations:d1-check":"bun run scripts/d1-migration-check.ts","zarr:geometry-check":"bun run backend/scripts/zarr-geometry-conformance.ts","lint:fix":"biome check --fix src/",format:"biome format --write src/",typecheck:"tsc --noEmit && tsc --noEmit -p backend","generate-openapi":"bun run scripts/generate-openapi.ts",prepublishOnly:"bun run build",prepare:"husky",postinstall:"bun scripts/postinstall-check.mjs",deploy:"wrangler deploy",preview:"wrangler dev"},keywords:["nemar","bids","neuroimaging","eeg","emg","datalad","cli"],author:"NEMAR Team",license:"CC-BY-NC-ND-4.0",repository:{type:"git",url:"git+https://github.com/nemarOrg/nemar-cli.git"},bugs:{url:"https://github.com/nemarOrg/nemar-cli/issues"},homepage:"https://docs.nemar.org",engines:{bun:">=1.0.0"},files:["dist","scripts/postinstall-check.mjs","scripts/recover-datasets.json","scripts/withdrawn-datasets.json","README.md","LICENSE"],dependencies:{chalk:"^5.3.0",commander:"^12.1.0",conf:"^13.0.1",inquirer:"^9.2.15",ora:"^8.0.1",semver:"^7.8.5",zod:"^3.23.8"},"lint-staged":{"src/**/*.{ts,tsx}":["biome check --fix"],"backend/src/**/*.{ts,tsx}":["biome check --fix"]},trustedDependencies:["@biomejs/biome"],devDependencies:{"@anthropic-ai/sdk":"^0.132.1","@asteasolutions/zod-to-openapi":"^7.3.4","@biomejs/biome":"1.9.4","@types/bun":"latest","@types/inquirer":"^9.0.7","@types/semver":"^7.8.0",ajv:"^8.20.0","ajv-formats":"^3.0.1",husky:"^9.1.7",jose:"6.2.12","lint-staged":"^16.3.2",oauth4webapi:"3.8.8","openid-client":"6.8.9",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var uc;var Kl=L(()=>{$E();uc=EE.version});import{mkdirSync as mV,readdirSync as hV,unlinkSync as gV,writeFileSync as yV}from"fs";import{join as Hl}from"path";function PB(){Us=!0}function fc(){return Us}function CB(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function IB(e){TE=e,mr(`Step: ${e}`)}function jB(){RE=!0}function qB(){return RE}function DB(){if(kE)return;Wl=!0}function MB(){Wl=!1,kE=!0}function LB(){return Wl}function mr(e){if(Us)process.stderr.write(`[debug] ${e}
27
27
  `)}function wV(e){let t={};for(let[r,n]of Object.entries(e))t[r]=bV.has(r.toLowerCase())?"[REDACTED]":n;return t}function OE(e){let t=e.indexOf("@");if(t<=0)return"***";return`${e[0]}***${e.slice(t)}`}function Bl(e,t,r=0){if(r>EV)return"[REDACTED: depth]";if(Array.isArray(t))return t.map((n)=>Bl(e,n,r+1));if(t&&typeof t==="object"){let n={};for(let[s,o]of Object.entries(t))n[s]=Bl(s,o,r+1);return n}if(typeof t==="string"){if($V.test(e))return"[REDACTED]";return t.replace(AE,OE)}return t}function Yl(e){return e.replace(SV,"Bearer [REDACTED]").replace(xV,"[REDACTED_AWS_KEY]").replace(RV,"$1[REDACTED]").replace(kV,"$1$2=[REDACTED]").replace(AE,OE)}function TV(e){return Yl(e)}function SE(e,t=vV){if(e===void 0)return;let r=e;try{let n=JSON.parse(e);r=JSON.stringify(Bl("",n))}catch{}if(r=Yl(r),Buffer.byteLength(r,"utf8")>t)r=`${Buffer.from(r,"utf8").subarray(0,t).toString("utf8")}... [truncated]`;return r}function pc(e){if(!Us)return;let t=TV(e.url);try{let r={...e,url:t,requestHeaders:e.requestHeaders?wV(e.requestHeaders):void 0,requestBody:SE(e.requestBody),responseBody:SE(e.responseBody)};dc.push(r),mr(`${e.method} ${t} -> ${e.status??"ERROR"} (${e.durationMs}ms)`)}catch(r){let n=fr(r);dc.push({method:e.method,url:t,status:e.status,durationMs:e.durationMs,note:`redaction failed: ${n}`}),mr(`redaction failed for ${e.method} ${t}: ${n}`)}}async function AV(){let e=[];try{let t=process.versions.bun?`Bun ${process.versions.bun}`:`Node ${process.version}`;e.push(`CLI version: ${uc}`),e.push(`OS/Arch: ${process.platform}/${process.arch}`),e.push(`Runtime: ${t}`)}catch(t){e.push(`(could not read CLI/OS/runtime info: ${fr(t)})`)}e.push(""),e.push("Active account:");try{let t=vn();if(t.apiKey){if(t.username)e.push(` Username: ${t.username}`);if(e.push(` API URL: ${t.apiUrl}`),t.role)e.push(` Role: ${t.role}`);e.push(` Sandbox completed: ${!!t.sandboxCompleted}`)}else e.push(" (not authenticated)")}catch(t){e.push(` (could not read account config: ${fr(t)})`)}e.push(""),e.push("External tools:");try{let t=await Gl();for(let r of t){let n=r.available?r.version??"installed":r.timedOut?"(timed out)":"not installed";e.push(` ${r.name}: ${n}`)}}catch(t){e.push(` (could not probe external tools: ${fr(t)})`)}return e}async function OV(){return(await AV()).join(`
28
28
  `)}async function UB(){if(!Us||lc!==void 0)return;try{lc=await OV()}catch(e){let t=fr(e);lc=`(could not build environment report: ${t})`,mr(`environment snapshot failed: ${t}`)}}function NE(e){if(xE.has(e))return{flag:e};for(let t of xE){if(!e.startsWith(t)||e.length<=t.length)continue;if(t.length===2)return{flag:t,kind:"short-attached"};if(e[t.length]==="=")return{flag:t,kind:"long-eq"}}return null}function NV(e){let t=[];for(let r=0;r<e.length;r++){let n=e[r],s=NE(n);if(!s){t.push(n);continue}if(s.kind==="long-eq")t.push(`${s.flag}=[REDACTED]`);else if(s.kind==="short-attached")t.push(`${s.flag}[REDACTED]`);else if(t.push(n),r+1<e.length)t.push("[REDACTED]"),r++}return t}function PV(e){let t=[];for(let r=0;r<e.length;r++){let n=e[r],s=NE(n);if(!s){t.push(n);continue}if(!s.kind&&r+1<e.length)r++}return t}function CV(e){let t=[];for(let n of PV(e)){if(n.startsWith("-"))continue;if(t.push(n),t.length===2)break}return(t.length>0?t.join("-"):"nemar").replace(/[^a-zA-Z0-9_-]/g,"_")}function IV(e,t){let r=[];if(r.push("NEMAR CLI Debug Log"),r.push(`Generated: ${new Date().toISOString()}`),r.push(`Command: nemar ${Yl(NV(e).join(" "))}`),r.push(""),r.push(lc??"(environment snapshot unavailable)"),r.push(""),r.push("HTTP requests:"),dc.length===0)r.push(" (none)");else dc.forEach((n,s)=>{if(r.push(` [${s+1}] ${n.method} ${n.url} -> ${n.status??"ERROR"} (${n.durationMs}ms)`),n.error)r.push(` Error: ${n.error}`);if(n.note)r.push(` Note: ${n.note}`);if(n.requestHeaders)r.push(` Request headers: ${JSON.stringify(n.requestHeaders)}`);if(n.requestBody)r.push(` Request body: ${n.requestBody}`);if(n.responseBody)r.push(` Response body: ${n.responseBody}`)});return r.push(""),r.push(`Failing step: ${TE??"(none recorded)"}`),r.push(`Exit code: ${t}`),`${r.join(`
29
29
  `)}
30
30
  `}function jV(e,t){let r;try{r=hV(e).filter((s)=>s.startsWith("nemar-")&&s.endsWith(".log"))}catch(s){if(s.code!=="ENOENT")mr(`could not list ${e} for log rotation: ${fr(s)}`);return}r.sort();let n=r.length-t;for(let s=0;s<n;s++)try{gV(Hl(e,r[s]))}catch(o){if(o.code!=="ENOENT")mr(`could not remove old log ${r[s]}: ${fr(o)}`)}}function FB(){return Go}function VB(e,t){if(!Us)return null;let r=Hl(Jl(),"logs");try{mV(r,{recursive:!0})}catch(a){return Go=fr(a),mr(`could not create log directory ${r}: ${Go}`),null}let s=`nemar-${new Date().toISOString().replace(/[:.]/g,"-")}-${CV(e)}.log`,o=Hl(r,s);try{yV(o,IV(e,t),"utf8")}catch(a){return Go=fr(a),mr(`could not write log file ${o}: ${Go}`),null}return jV(r,_V),o}var _V=10,vV=2048,Us=!1,RE=!1,Wl=!1,kE=!1,TE,lc,dc,bV,$V,AE,EV=32,SV,xV,RV,kV,xE,Go;var Xl=L(()=>{jl();mc();wE();Kl();dc=[];bV=new Set(["authorization","cookie","set-cookie","x-api-key","x-approval-dispatch-token"]);$V=/^(api[_-]?key|apikey|password|token|secret|access[_-]?key(_id)?|secret[_-]?access[_-]?key|session|session[_-]?token|authorization|ssh[_-]?key|private[_-]?key|device[_-]?code|dispatch[_-]?token|client[_-]?secret)$/i,AE=/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;SV=/Bearer\s+[A-Za-z0-9\-._~+/=]+/gi,xV=/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,RV=/((?:aws_)?secret_access_key["']?\s*[:=]\s*["']?)[A-Za-z0-9/+=]{20,}/gi,kV=/([?&])(X-Amz-Signature|X-Amz-Security-Token|X-Amz-Credential|Signature|AWSAccessKeyId)=[^&\s"']+/gi;xE=new Set(["-k","--key","--password","--api-key"])});import{chmodSync as qV,copyFileSync as DV,existsSync as Ql,mkdirSync as MV,statSync as LV}from"fs";import{homedir as hc}from"os";import{join as Fs}from"path";function FV(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 Jl(){return process.env.NEMAR_CONFIG_DIR||Fs(hc(),".config","nemar")}function zV(e){if(process.env.NEMAR_CONFIG_DIR)return;let t=Fs(e,"config.json");if(Ql(t))return;let r=[];if(process.platform==="darwin")r.push(Fs(hc(),"Library","Preferences","nemar-nodejs","config.json"));if(process.platform==="win32"){let n=process.env.APPDATA||Fs(hc(),"AppData","Roaming");r.push(Fs(n,"nemar-nodejs","config.json"))}r.push(Fs(hc(),".config","nemar-nodejs","config.json"));for(let n of r)if(Ql(n))try{MV(e,{recursive:!0}),DV(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=Jl();if(Ko&&PE===e)return Ko;if(zV(e),Ko=new Bi({projectName:"nemar",configFileMode:Zl,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}),PE=e,!CE.has(e))CE.add(e),GV(Ko.path),HV(),BV();return Ko}function GV(e){if(process.platform==="win32")return;if(!Ql(e))return;try{if((LV(e).mode&511)!==Zl)qV(e,Zl)}catch(t){console.error(`[nemar] could not secure config file permissions for ${e}:`,t)}}function HV(){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 a of KV){let i=e.get(a);if(i!==void 0)o[a]=i}e.store={activeAccount:s,accounts:{[s]:o}}}catch(s){console.error("Config migration failed (legacy config preserved):",s)}}function BV(){let e=St(),t=e.store,r=t.accounts,n=!1;if(r)for(let[o,a]of Object.entries(r)){let i=a?.apiUrl;if(!i)continue;if(UV.has(FV(i)))r[o]={...a,apiUrl:Vs},console.error(`[nemar] migrated stored apiUrl for account "${o}": ${i} -> ${Vs}`),n=!0}let s=t.apiUrl;if(r&&Object.keys(r).length>0&&s!==void 0){let{apiUrl:o,...a}=t;try{e.store=a,console.error(`[nemar] removed stale top-level apiUrl from config (was: ${s})`),n=!1}catch(i){console.error("API URL cleanup failed (config file unchanged):",i)}}if(n)try{e.store={...e.store,accounts:r}}catch(o){console.error("API URL migration failed (config file unchanged):",o)}}function Ho(){return St().get("activeAccount")}function bn(){return St().get("accounts")||{}}function vn(){let e={apiUrl:Vs},t=Ho();if(!t)return e;return bn()[t]||e}function QB(e,t){let r=St(),n=r.get("activeAccount")||"default",s=r.get("accounts")||{};if(!s[n])s[n]={apiUrl:Vs};s[n][e]=t,r.store={...r.store,accounts:s,activeAccount:n}}function ZB(e){let t=Ho();if(!t)return;let r=bn();if(r[t])delete r[t][e],St().set("accounts",r)}function e6(){let e=St(),t=Ho();if(!t){e.clear();return}let r=bn();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 t6(){St().clear()}function r6(){return!!vn().apiKey}function n6(){return St().path}function s6(){let e=bn(),t=Ho();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 o6(e){return e.username?.trim()||e.email}function WV(e){let t=e.trim().toLowerCase();if(!t)return;let r=Object.entries(bn()).filter(([,n])=>n.email&&n.email.toLowerCase()===t).map(([n])=>n);if(r.length>1){mr(`findAccountKeyByEmail: ${r.length} accounts share email ${t}: ${r.join(", ")}`);return}return r[0]}function a6(e,t){let r=St(),n=bn(),s;if(n[e])s=e;else if(t.email)s=WV(t.email);let o=s?n[s]:void 0,a={...o??{apiUrl:Vs},...t};if(s&&s!==e)delete n[s];return n[e]=a,r.store={...r.store,accounts:n,activeAccount:e},{key:e,previous:o}}function i6(e){let t=e.trim();if(!t)return"unchanged";let r=St(),n=Ho();if(!n||n===t)return"unchanged";let s=bn(),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 c6(e){let t=St(),r=bn();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 Vs="https://nemar-api-dev.sccn-org.workers.dev",Zl=384,UV,VV,JB,Ko=null,PE=null,CE,KV;var mc=L(()=>{V$();_n();oc();Xl();UV=new Set(["https://api.osc.earth/nemar","https://nemar-api.neuromechanist.workers.dev","https://nemar-api-dev.shirazi-10f.workers.dev"]);VV=Z({field:_(),blocks:Ye(_()).optional(),set_on:Ye(_()).optional()}).passthrough(),JB=Z({apiKey:_().optional(),apiUrl:_().url().default(Vs),username:_().optional(),email:_().email().optional(),githubUsername:_().optional(),sandboxCompleted:Ie().optional(),sandboxDatasetId:_().optional(),dismissedNoticeIds:Ye(ne()).optional(),serviceAccess:Ie().optional(),profileGaps:Ye(VV).optional(),orcidVerified:Ie().optional(),role:_().optional(),accountKind:Mn.optional(),pendingEmailChange:_().email().optional()});CE=new Set;KV=["apiKey","apiUrl","username","email","githubUsername","sandboxCompleted","sandboxDatasetId","dismissedNoticeIds"]});var YV,XV,f6,JV,p6,QV,IE,m6,h6=8,g6=100,jE,y6,ZV,_6;var qE=L(()=>{_n();oc();YV=["given_name","family_name","affiliation","city","country"],XV=["username","github_username","email","orcid"],f6=[...YV,...XV],JV={given_name:_().max(200).optional(),family_name:_().max(200).optional(),affiliation:_().max(500).optional(),city:_().max(200).optional(),country:_().max(200).optional(),username:_().max(100).optional(),github_username:_().max(100).optional(),email:_().max(320).optional(),orcid:_().max(40).optional()},p6=Z(JV),QV=Fe(["field_not_editable","owner_only_field","edit_own_account","owner_account","system_account","invalid_edit","orcid_already_proven","invalid_search","invalid_user_id"]),IE=QV.options,m6=["exact","name","prefix","substring","fuzzy"],jE=Z({id:ne().int(),username:_().nullable(),email:_(),github_username:_().nullable(),status:_(),role:_().nullable(),account_kind:Mn.optional(),email_verified:ne().int().nullable().optional(),orcid:_().nullable().optional(),orcid_verified:ne().int().nullable().optional(),given_name:_().nullable().optional(),family_name:_().nullable().optional(),affiliation:_().nullable().optional(),city:_().nullable().optional(),country:_().nullable().optional(),description:_().nullable().optional(),signup_source:_().nullable().optional(),created_at:_(),updated_at:_().nullable().optional(),approved_at:_().nullable().optional(),revoked_at:_().nullable().optional(),deleted_at:_().nullable().optional(),service_access:ne().int().nullable().optional(),service_access_granted_at:_().nullable().optional(),service_access_granted_by:ne().int().nullable().optional(),upload_access_requested_at:_().nullable().optional(),upload_access_notified_at:_().nullable().optional(),compute_access:_().optional(),compute_access_requested_at:_().nullable().optional(),compute_access_notified_at:_().nullable().optional(),compute_access_granted_at:_().nullable().optional(),compute_access_granted_by:ne().int().nullable().optional(),compute_terms_version:_().nullable().optional(),compute_terms_accepted_at:_().nullable().optional(),identity_conflict:ne().int().nullable().optional(),username_auto_assigned:ne().int().nullable().optional(),sandbox_completed:ne().int().nullable().optional(),sandbox_completed_at:_().nullable().optional(),sandbox_dataset_id:_().nullable().optional(),aws_iam_username:_().nullable().optional(),dataset_count:ne().int().optional(),active_tokens:ne().int().optional(),linked_identities:Ye(_()).optional()}).passthrough(),y6=Z({user:jE}).passthrough(),ZV=Z({from:_().nullable(),to:_().nullable()}),_6=Z({message:_(),changed:NF(_(),ZV),notes:Ye(_()).optional(),old_address_notified:Ie().optional(),user:jE}).passthrough()});function t9(e){for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r<32&&r!==9&&r!==10||r===127)return!0}return!1}function x6(e,t){let r=s9[e];if(r==="refused")return t===void 0?null:"notice_refused";let n=t?.trim()??"";if(n==="")return r==="required"?"notice_required":null;if([...n].length>ME)return"notice_too_long";if(t9(n))return"notice_control_char";return null}var w6=20,e9=1000,$6,r9,DE,E6,n9=500,S6=200,ME=1000,s9,R6,LE,k6,o9,T6;var UE=L(()=>{_n();$6=Z({purpose:_().max(e9*4).optional().default(""),accept_terms_version:_().max(64).optional().default("")}),r9=Fe(["purpose_required","terms_not_accepted","email_not_verified","orcid_not_proven","profile_incomplete","access_closed","already_active","terms_unpublished"]),DE=r9.options,E6=Z({ok:gn(!0),already_requested:Ie(),requested_at:_().nullable().optional(),email_sent:Ie().optional(),admins_notified:ne().int().nullable().optional()}).passthrough(),s9={grant:"refused",deny:"optional",suspend:"required",revoke:"required"};R6={reason:_().max(n9).optional(),notice:_().max(ME*4,{message:"notice_too_long"}).optional()},LE=Z({id:ne().int(),username:_().nullable(),email:_(),given_name:_().nullable().optional(),family_name:_().nullable().optional(),affiliation:_().nullable().optional(),city:_().nullable().optional(),country:_().nullable().optional(),orcid:_().nullable().optional(),account_kind:_().optional(),compute_access:_(),compute_access_requested_at:_().nullable().optional(),compute_access_notified_at:_().nullable().optional(),compute_access_granted_at:_().nullable().optional(),compute_access_granted_by:ne().int().nullable().optional(),compute_purpose:_().nullable().optional(),compute_terms_version:_().nullable().optional(),compute_terms_accepted_at:_().nullable().optional()}).passthrough(),k6=Z({accounts:Ye(LE),next_after:ne().int().nullable().optional()}).passthrough(),o9=Z({granted:Ie(),cpu_milli:ne().int(),gpu_milli:ne().int(),reason:_().nullable().optional(),policy_version:ne().int().nullable().optional()}).passthrough(),T6=Z({decision:_(),from:_(),to:_(),account:LE,allocation:o9.optional(),email_sent:Ie().optional()}).passthrough()});var N6=120,P6=64,C6="unnamed machine",a9=25,FE,I6,zs,VE,j6,q6,D6,i9,c9,M6,ed,L6,U6,F6,V6,z6;var zE=L(()=>{_n();FE=Fe(["authorization_pending","slow_down","expired_token","access_denied","invalid_grant"]),I6={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."},zs=Fe(["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"]),VE=zs.options,j6={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 ${a9} 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."},q6=Z({error:zs,message:_()}).passthrough(),D6=Z({device_code:_(),user_code:_(),verification_uri:_(),verification_uri_complete:_(),expires_in:ne().int(),interval:ne().int()}).passthrough(),i9=X$("error",[Z({error:gn("authorization_pending"),message:_()}).passthrough(),Z({error:gn("slow_down"),message:_()}).passthrough()]),c9=X$("error",[Z({error:gn("expired_token"),reason:zs,message:_()}).passthrough(),Z({error:gn("access_denied"),reason:zs,message:_()}).passthrough(),Z({error:gn("invalid_grant"),reason:zs,message:_()}).passthrough()]),M6=OF([i9,c9]),ed=Z({id:ne().int(),name:_().nullable(),prefix:_(),created_at:_(),last_used_at:_().nullable(),current:Ie()}).passthrough(),L6=Z({api_key:_(),key:ed,user:Z({username:_().nullable(),email:_(),github_username:_().nullable(),role:_(),sandbox_completed:Ie(),sandbox_dataset_id:_().nullable()}).passthrough()}).passthrough(),U6=Z({user_code:_(),machine_name:_(),requested_at:_(),expires_in:ne().int(),account:Z({username:_().nullable(),email_masked:_()}).passthrough(),refusal:Z({code:zs,message:_()}).passthrough().nullable()}).passthrough(),F6=Z({ok:gn(!0),machine_name:_()}).passthrough(),V6=Z({keys:Ye(ed)}).passthrough(),z6=Z({api_key:_(),key:ed}).passthrough()});var u9,GE,Bo="https://nemar.org/settings",H6,l9,d9,f9,B6,W6;var KE=L(()=>{_n();u9=Fe(["orcid_in_use","orcid_already_linked","orcid_linked_other","email_in_use","github_in_use","identity_conflict_remains"]),GE=u9.options,H6={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, ${Bo}).`,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, ${Bo}).`,orcid_linked_other:`That ORCID iD is linked to a different NEMAR account. Unlink it there first (Settings, ${Bo}), 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, ${Bo}).`,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, ${Bo}).`,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."},l9=Fe(["orcid","email","github"]),d9=Z({id:ne().int(),username:_().nullable(),email:_(),created_at:_(),has_oauth_identity:Ie(),dataset_count:ne().int(),identity_conflict:ne().int(),canonical:Ie()}).passthrough(),f9=Z({kind:l9,value:_(),canonical_user_id:ne().int(),accounts:Ye(d9)}).passthrough(),B6=Z({groups:Ye(f9),group_count:ne().int(),flagged_count:ne().int()}).passthrough(),W6=Z({ok:gn(!0),id:ne().int(),cleared:Ie()}).passthrough()});function X6(e){return Wo[e]}function J6(e,t){return e.replace(/\{(\w+)\}/g,(r,n)=>Object.hasOwn(t,n)?t[n]:r)}var Wo;var HE=L(()=>{Wo={"tier.unverified.label":"Email not verified","tier.base.label":"Base access","tier.upload.label":"Upload access","tier.unverified.lede":"Verify your email address to activate your account.","upload_access.section.title":"Upload access","upload_access.section.lede":"A one-time admin grant. Reviewed against export-control and local-jurisdiction rules.","upload_access.state.granted":"Granted","upload_access.state.requested":"Requested","upload_access.state.not_requested":"Not requested","upload_access.invite.title":"Want to contribute a dataset?","upload_access.invite.body":"Browsing, searching and downloading are open to your account already. Uploading, or being added as a collaborator on someone else\u2019s dataset, needs one extra grant: an admin checks your GitHub handle and location against export-control and local-jurisdiction rules, once. Your email address must be verified first.","upload_access.gate.title":"Ask for upload access first","upload_access.gate.body":"Your account can browse, search and download everything public already. Uploading, or being added as a collaborator on someone else\u2019s dataset, needs one extra grant, and your email address must be verified first: an admin checks your GitHub handle and where you\u2019re based against export-control and local-jurisdiction rules. You ask once, and it is answered by email.","upload_access.request.cta":"Request upload access","upload_access.request.form_body":"Tell us what you plan to deposit, or which dataset you want to collaborate on. An admin reviews this alongside your name, username, GitHub handle and location, then grants access once.","upload_access.request.why_label":"What do you intend to upload?","upload_access.request.why_hint":"Describe what you intend to upload in 20-500 characters","upload_access.requested.title":"Your request is with an admin","upload_access.requested.lede":"An admin is reviewing your request.","upload_access.requested.lede_dated":"An admin is reviewing your request from {date}.","upload_access.requested.body.upload":"We\u2019ll email you when there\u2019s a decision, and this page will let you upload as soon as it\u2019s granted.","upload_access.requested.body":"We\u2019ll email you when there\u2019s a decision. Everything else on your account keeps working in the meantime.","upload_access.requested.cta":"See the request","upload_access.granted.body":"You can upload datasets from the upload page. Publishing one is a separate, per-dataset review you start from your dashboard.","upload_access.unverified.body":"Verify your email address first \u2014 the review happens over email.","upload_access.docs_link":"How upload access works","compute_access.section.title":"Compute access","compute_access.section.lede":"A separate grant from upload access. An admin reviews each request against export-control and local-jurisdiction rules and the purpose you state, and a grant lets you use compute within the limits an administrator sets.","compute_access.state.none":"Not requested","compute_access.state.requested":"Requested","compute_access.state.active":"Active","compute_access.state.suspended":"Suspended","compute_access.state.denied":"Not granted","compute_access.state.revoked":"Ended","compute_access.request.cta":"Request compute access","compute_access.request.form_body":"Tell us what you plan to compute. An admin reviews this alongside your name, affiliation and location, then answers once. You also accept the compute terms.","compute_access.request.purpose_label":"What do you intend to compute?","compute_access.request.purpose_hint":"Describe what you intend to compute in 20-1000 characters","compute_access.request.terms_label":"I accept the compute terms","compute_access.requested.title":"Your compute request is with an admin","compute_access.requested.lede":"An admin is reviewing your request.","compute_access.requested.lede_dated":"An admin is reviewing your request from {date}.","compute_access.requested.body":"We\u2019ll email you when there\u2019s a decision. Everything else on your account keeps working in the meantime.","compute_access.granted.body":"Compute access is active. Your balances are on your compute page, and you submit jobs with the `nemar compute` command line.","compute_access.granted.link":"Open your compute page","compute_access.closed.body":"This request has been answered and cannot be asked again. If you think that is a mistake, contact support and an admin will take another look.","compute_access.suspended.body":"Your compute access is paused. Contact support to find out why or to ask for it to be lifted.","compute_access.terms_unpublished.body":"Compute access is not open yet: the compute terms are not published. Please check back later.","compute_access.docs_link":"How compute access works","compute_page.frozen.body":"Your pools are frozen, so new jobs are refused. Contact support to find out why.","compute_page.units_note":"Amounts are service units (SU).","compute_page.available_note":"Available is granted minus held minus charged and can be negative after an overrun.","compute_page.queue_note":"It describes the queue of the whole platform, not yours, and it is a recent average, not a promise.","compute_page.usage_note":"Net charge by UTC day of the charge, not the day a job was created. A day with no charge has no bar.","compute_page.unreported_note":"NEMAR has not heard from the cluster about this job for a while. It may still finish.","compute_admin.page.title":"Compute","compute_admin.page.lede":"Compute access requests, and a read-only view of pools, usage, flagged jobs and reconciliation. A grant opens an allocation the person can spend, so each request is decided by a person, one at a time.","compute_admin.page.cli_note":"Owner policy, legal holds, record reads, moving a charge, pool grants and adjustments, and canceling a job are done with the nemar admin compute command in the command line, not here.","compute_admin.page.order_note":"Accounts are listed in the order they were created, not the order they asked in.","compute_admin.view.nav":"Compute views","compute_admin.view.requests":"Requests","compute_admin.view.pools":"Pools","compute_admin.view.usage":"Usage","compute_admin.view.flagged":"Flagged jobs","compute_admin.view.drift":"Reconciliation","compute_admin.state.nav":"Filter requests by state","compute_admin.state.requested":"Requested","compute_admin.state.active":"Active","compute_admin.state.suspended":"Suspended","compute_admin.state.denied":"Denied","compute_admin.state.revoked":"Revoked","compute_admin.state.all":"All","compute_admin.requests.none":"No accounts in this view.","compute_admin.pager.next":"Next page","compute_admin.pager.first":"First page","compute_admin.row.not_set":"not set","compute_admin.row.no_username":"no username","compute_admin.row.account_kind":"{kind} account","compute_admin.row.stated_country":"Stated country","compute_admin.row.stated_country_hint":"Check this against the export-control rules before granting. This page does not rule on it.","compute_admin.row.city":"City","compute_admin.row.affiliation":"Affiliation","compute_admin.row.email":"Email","compute_admin.row.orcid":"ORCID iD","compute_admin.row.requested":"Requested","compute_admin.row.terms":"Terms accepted","compute_admin.row.terms_value":"{version}, {date}","compute_admin.row.purpose":"Stated purpose","compute_admin.row.show_full_purpose":"Show full purpose","compute_admin.row.granted":"Granted {date} by account #{id}","compute_admin.row.not_notified":"No administrator has been emailed about this request yet.","compute_admin.row.open_in_users":"Open in Users","compute_admin.action.grant":"Grant","compute_admin.action.grant_again":"Grant again","compute_admin.action.lift_suspension":"Lift suspension","compute_admin.action.deny":"Deny","compute_admin.action.suspend":"Suspend","compute_admin.action.revoke":"Revoke","compute_admin.self_grant.disabled":"You cannot grant your own compute access. Ask another administrator or an owner.","compute_admin.dialog.title.grant":"Grant compute access?","compute_admin.dialog.title.deny":"Deny this request?","compute_admin.dialog.title.suspend":"Suspend compute access?","compute_admin.dialog.title.revoke":"Revoke compute access?","compute_admin.dialog.consequence.grant":"Opens the owner\u2019s default allocation once for this account (a repeat grant adds nothing), unfreezes the account\u2019s pools, and allows the person to use compute when it is available. The person is emailed when they have an email address that can receive it.","compute_admin.dialog.consequence.deny":"Closes this request. The person cannot ask again; only an administrator can grant later. The person is emailed when they have an email address that can receive it.","compute_admin.dialog.consequence.suspend":"Freezes the account\u2019s pools, cancels its live jobs and ends its compute sign-ins. A partner reservation that has no job reported under it is not canceled here: it is released after it expires, and a job reported under it is refused. A grant lifts the suspension. The person is emailed when they have an email address that can receive it.","compute_admin.dialog.consequence.revoke":"Freezes the account\u2019s pools, cancels its live jobs and ends its compute sign-ins. A partner reservation that has no job reported under it is not canceled here: it is released after it expires, and a job reported under it is refused. Only a new grant restores access. The person is emailed when they have an email address that can receive it.","compute_admin.dialog.reason_label":"Reason (optional)","compute_admin.dialog.reason_hint":"Recorded in the audit log. The person is not sent it.","compute_admin.dialog.reason_count":"{count} of {max}","compute_admin.dialog.notice_label":"Notice to the person","compute_admin.dialog.notice_label_optional":"Notice to the person (optional)","compute_admin.dialog.notice_help":"Emailed to the person under a fixed heading, with how to ask for a review. Write it for them. It is not the reason, which stays in the audit log.","compute_admin.dialog.notice_required_hint":"A suspension or a revocation tells the person why. Write the notice to confirm.","compute_admin.dialog.ack_export_review":"Confirm that you have reviewed this person\u2019s name, affiliation and stated country against the export-control rules","compute_admin.dialog.type_word":"Type {word} to confirm","compute_admin.dialog.cancel":"Cancel","compute_admin.result.working":"Working","compute_admin.result.granted":"Granted.","compute_admin.result.granted_opened":"Granted. Opened {cpu} CPU SU and {gpu} GPU SU.","compute_admin.result.granted_zero_default":"Granted. The owner\u2019s default allocation is zero, so nothing was opened.","compute_admin.result.granted_already":"Granted. An earlier grant already opened the default allocation, so nothing more was opened.","compute_admin.result.granted_other":"Granted. The allocation answered: {reason}.","compute_admin.result.denied":"Denied.","compute_admin.result.suspended":"Suspended. The account\u2019s pools are frozen and its live jobs are being canceled. A partner reservation with no job reported under it is left to expire.","compute_admin.result.revoked":"Revoked. The account\u2019s pools are frozen and its live jobs are being canceled. A partner reservation with no job reported under it is left to expire.","compute_admin.result.email_not_sent":"The decision stands, but the person could not be emailed. Tell them.","compute_admin.result.state_changed":"Someone else may have decided this first. The row shows the current state.","compute_admin.result.unconfirmed":"The result is not confirmed. The row shows what the server says now.","compute_admin.result.check_email":"The decision is in place, but the answer was lost, so check that the person was emailed and tell them if not.","compute_admin.result.stale":"This account was not found. Reload the page.","compute_admin.result.reread_failed":"The current state could not be read. Reload the page before deciding again.","compute_admin.result.signed_out":"You are signed out. Sign in again, then retry.","compute_admin.error.malformed":"The server sent an answer this page could not read.","compute_admin.error.unreachable":"The server could not be reached. Check your connection and try again.","compute_admin.error.redirect":"The server answered in a way this page cannot follow. Try again later.","compute_admin.error.origin":"This page was not accepted as the source of the request. Reload and try again.","compute_admin.error.rate_limited":"Too many requests. Wait a moment, then try again.","compute_admin.error.timeout":"The server did not answer in time. Try again.","compute_admin.error.failed":"The request failed ({status}). Try again.","compute_admin.error.generic":"Something went wrong. Try again.","compute_admin.error.bad_id":"That is not an account id.","compute_admin.error.bad_decision":"That is not a decision.","compute_admin.error.reason_too_long":"A reason is at most {max} characters.","compute_admin.error.notice_required":"This decision needs a notice to the person.","compute_admin.error.notice_refused":"A grant does not take a notice to the person.","compute_admin.error.notice_too_long":"A notice is at most {max} characters.","compute_admin.error.notice_control_char":"A notice may not contain control characters other than newline and tab.","compute_admin.error.bad_quarter":"A quarter is written like 2026Q4.","compute_admin.section.failed":"Could not load {what}: {reason}","compute_admin.col.holder":"Holder","compute_admin.col.pool":"Pool","compute_admin.col.granted":"Granted (SU)","compute_admin.col.held":"Held (SU)","compute_admin.col.charged":"Charged (SU)","compute_admin.col.available":"Available (SU)","compute_admin.col.frozen":"Frozen","compute_admin.col.updated":"Updated","compute_admin.col.partition":"Partition","compute_admin.col.source":"Front door","compute_admin.col.users":"Distinct people","compute_admin.col.jobs":"Jobs","compute_admin.col.job":"Job","compute_admin.col.account":"Account","compute_admin.col.state":"State","compute_admin.col.flags":"Flags","compute_admin.col.failure":"Failure","compute_admin.col.created":"Created","compute_admin.col.ended":"Ended","compute_admin.col.slurm":"Scheduler job","compute_admin.col.elapsed":"Elapsed (s)","compute_admin.col.resources":"Nodes, CPUs, GPUs","compute_admin.col.ingested":"Ingested","compute_admin.ref.account":"account #{id}","compute_admin.ref.no_account":"no account","compute_admin.pools.platform":"Platform budgets","compute_admin.pools.partner":"Partner pools","compute_admin.pools.account":"Account pools","compute_admin.pools.none_platform":"No platform budgets are recorded.","compute_admin.pools.none":"No pools are recorded in this group.","compute_admin.pools.truncated":"Showing the first {shown} pools of this group; more exist.","compute_admin.pools.frozen":"Frozen","compute_admin.pools.open":"Open","compute_admin.usage.quarter":"Quarter","compute_admin.usage.counts_note":"These are counts of people and jobs, not service units. A person is counted once however many jobs they ran, and jobs that skipped the reservation or could not be attributed are left out.","compute_admin.usage.totals":"Total","compute_admin.usage.none":"No jobs were recorded in this quarter.","compute_admin.flag.nav":"Filter jobs by flag","compute_admin.flag.unreserved":"Unreserved","compute_admin.flag.unattributed":"Unattributed","compute_admin.flag.mismatch":"Mismatch","compute_admin.flag.overrun":"Overrun","compute_admin.flag.meaning.unreserved":"The job skipped the reservation. Its charge went to a partner pool and not to a person.","compute_admin.flag.meaning.unattributed":"The job skipped the reservation and its owner maps to no active account.","compute_admin.flag.meaning.mismatch":"NEMAR\u2019s record and the scheduler\u2019s accounting disagree for this job, or a partner\u2019s report for it was refused or could not be checked, or a partner job used more than its hold and was capped.","compute_admin.flag.meaning.overrun":"The job used more than its hold, and the excess is recorded as an overrun in the ledger.","compute_admin.flag.followup":"Moving the charge of an unreserved job to a person is an owner action in the command line.","compute_admin.flagged.none":"No jobs carry this flag. That is a fact about this read only.","compute_admin.flagged.platform_failure":"NEMAR\u2019s fault","compute_admin.flagged.partner":"Partner: {state}, {flag}","compute_admin.drift.paused":"Reconciliation is paused while compute is off. An empty list below does not mean nothing is unmatched.","compute_admin.drift.pause_unknown":"Whether reconciliation is running is not known, so an empty list does not mean nothing is unmatched.","compute_admin.drift.status":"Status","compute_admin.drift.compute_on":"Compute is on.","compute_admin.drift.compute_off":"Compute is off.","compute_admin.drift.tapis":"Scheduler gateway: token {token}, health {health}.","compute_admin.drift.attention":"Needs a person to look","compute_admin.drift.attention_none":"No attention count is positive.","compute_admin.drift.unmatched":"Accounting rows no job claims","compute_admin.drift.unmatched_shown":"Showing the newest {shown} of {total}.","compute_admin.drift.unmatched_none":"No accounting rows are waiting for a job.","compute_admin.drift.not_priced":"not priced","compute_admin.drift.mismatch":"Jobs flagged mismatch","compute_admin.drift.mismatch_more":"See the Flagged jobs view for the rest","compute_admin.unavailable.title":"Not available yet","compute_admin.unavailable.usage_by_day":"Service units charged by day, partition and front door across the platform are not served by any admin read yet.","compute_admin.unavailable.drift_difference":"The difference between NEMAR\u2019s ledger and the supercomputer\u2019s accounting, per job or per day, and the tolerance it is measured against are not served by any admin read yet. No row is marked over tolerance because this page has no tolerance to apply.","compute_admin.unavailable.link":"Tracking issue","compute_admin.badge.awaiting_decision":"awaiting decision","gap.sentence":"{label} is missing: needed {blocks}.","gap.set_on.both":"Set it in {web} or run `{cli}`.","gap.set_on.web":"Set it in {web}.","gap.blocks.verified":"to activate your account","gap.blocks.upload_access":"to request upload access","gap.blocks.compute_access":"to request compute access","gap.blocks.publication":"to publish a dataset","gap.blocks.unknown":"to finish setting up your account","gap.blocks.noun.verified":"account activation","gap.blocks.noun.upload_access":"upload access","gap.blocks.noun.compute_access":"compute access","gap.blocks.noun.publication":"publication","gap.set_on.default_web":"Settings","gap.field.email_verified.label":"A verified email address","gap.field.username.label":"Username","gap.field.given_name.label":"Given name","gap.field.family_name.label":"Family name","gap.field.orcid_verified.label":"Verified ORCID iD","gap.field.github_username.label":"GitHub handle","gap.field.city.label":"City","gap.field.country.label":"Country","gap.field.affiliation.label":"Affiliation","gap.field.why.label":"A description of what you intend to upload","gap.field.email_verified.set_on.web":"the verify step on your dashboard","gap.field.email_verified.set_on.cli":"nemar auth resend-verification","gap.field.username.set_on.web":"Settings","gap.field.username.set_on.cli":"nemar auth profile set-username","gap.field.given_name.set_on.web":"Settings","gap.field.given_name.set_on.cli":"nemar auth profile set-name","gap.field.family_name.set_on.web":"Settings","gap.field.family_name.set_on.cli":"nemar auth profile set-name","gap.field.given_name.set_on.web.orcid":"your ORCID record at orcid.org, then sign in again","gap.field.family_name.set_on.web.orcid":"your ORCID record at orcid.org, then sign in again","gap.field.orcid_verified.set_on.web":"Settings","gap.field.orcid_verified.set_on.cli":"nemar auth profile orcid link","gap.field.github_username.set_on.web":"Settings","gap.field.github_username.set_on.cli":"nemar auth profile set-github","gap.field.city.set_on.web":"Settings","gap.field.city.set_on.cli":"nemar auth profile set-location","gap.field.country.set_on.web":"Settings","gap.field.country.set_on.cli":"nemar auth profile set-location","gap.field.affiliation.set_on.web":"Settings","gap.field.affiliation.set_on.cli":"nemar auth profile set-affiliation","gap.field.why.set_on.web":"the request form in Settings","gap.field.why.set_on.cli":"nemar auth request-upload-access","gaps.title":"What is still missing","gaps.none":"Nothing outstanding \u2014 every field NEMAR needs is filled in.","gaps.nudge.title":"Your profile isn\u2019t finished yet","gaps.nudge.cta":"Complete your profile","gaps.upload.title":"Before you can ask, your account still needs:","gaps.request.title":"Finish these first:","gaps.admin.title":"Still missing","gaps.admin.item":"{label} \u2014 blocks {blocks}","gaps.admin.none":"Nothing missing \u2014 every field the request needs is filled in.","gaps.admin.not_loaded":"Not loaded \u2014 open the user page to see what is still missing.","onboarding.username.auto_assigned.title":"We chose your username from your name","onboarding.username.auto_assigned.body":"Your account needed a username to be listed as a dataset owner, so one was made from your name when you signed in. You can change it once, here, until an admin grants you upload access.","welcome.unverified.title":"Verify your email address","welcome.unverified.body":"Authorizing with ORCID created your NEMAR account and signed you in. One step left: enter the 6-digit code we emailed you. That activates the account \u2014 no admin approval is involved.","welcome.active.title":"Your account is active","welcome.active.body":"Authorizing with ORCID created your NEMAR account and signed you in. There is no separate sign-up step and no approval queue: browse, search, and your dashboard all work right now.","welcome.upload_access.title":"Ask for upload access when you\u2019re ready to contribute","welcome.upload_access.body":"Reading is open to every verified account. Uploading and compute need one extra grant, because an admin has to check your GitHub handle and location against export-control and local-jurisdiction rules first. You ask once, from Settings.","oidc.consent.title":"{client} wants to use your NEMAR account","oidc.consent.acts_as_you":"If you allow it, {client} can act as you on NEMAR in the ways listed below.","oidc.consent.compute_spend":"If you sign in and run compute with this app, it counts against your NEMAR compute allocation.","oidc.consent.scopes_title":"It is asking to:","oidc.consent.scope.openid":"Know which NEMAR account is yours","oidc.consent.scope.profile":"See your name","oidc.consent.scope.email":"See your email address","oidc.consent.scope.orcid":"See your ORCID iD, and whether you proved it by signing in with ORCID","oidc.consent.scope.nemar.account":"See your account type, status and access level","oidc.consent.scope.offline_access":"Keep this access when you are not using it","oidc.consent.scope.compute.read":"See your compute access, balances, usage and jobs","oidc.consent.scope.compute.reserve":"Reserve compute time, report jobs and release reservations for you","oidc.consent.scope.compute.submit":"Submit compute jobs that NEMAR runs for you","oidc.consent.redirect_host":"Either answer sends you to {redirect_host}.","oidc.consent.allow":"Allow","oidc.consent.deny":"Deny","oidc.rule.title":"You can\u2019t sign in to {client} with this account","oidc.rule.account_inactive":"Your NEMAR account is not active.","oidc.rule.account_not_person":"{client} is only for personal accounts, and this account is not one.","oidc.rule.orcid_not_proven":"{client} needs an ORCID iD you proved by signing in to NEMAR with ORCID. Link your ORCID iD in Settings, then try again.","oidc.rule.return":"Return to {client}","oidc.error.title":"This sign-in can\u2019t continue","oidc.error.invalid_client":"The site that sent you here is not one NEMAR signs people in to.","oidc.error.invalid_redirect_uri":"The site that sent you here asked NEMAR to send you to an address it has not registered, so NEMAR will not send you there.","oidc.error.invalid_request":"The sign-in request is incomplete or malformed. Go back to the site you came from and start again.","oidc.error.consent_invalid":"This page has expired. Go back to the site you came from and start again.","oidc.error.unavailable":"NEMAR could not complete this sign-in right now. Try again in a moment.","oidc.error.rate_limited":"Too many sign-in attempts. Try again in a minute.","mail.category.news.label":"News","mail.category.news.description":"New features, data and events.","mail.category.rfcs.label":"Requests for comments","mail.category.rfcs.description":"A new NEMAR request for comments is open for discussion.","mail.category.maintenance.label":"Maintenance","mail.category.maintenance.description":"Planned downtime and changes to the service.","mail.category.recall.label":"Recalls","mail.category.recall.description":"A dataset, release or credential NEMAR distributed has a problem you need to act on.","mail.recall.why":"Recalls cannot be turned off: they tell you to stop using, delete or replace something NEMAR distributed or issued, because continuing to use it can cause harm.","cli.gaps.section.title":"Profile","cli.gaps.unknown":"not checked: run 'nemar auth status --refresh'","cli.gaps.unreported":"not reported by this backend","cli.gap.set_on.cli_only":"Run `{cli}`.","cli.gap.field.sandbox.label":"Sandbox training","cli.gap.blocks.sandbox":"to upload a dataset from the CLI","cli.gap.field.sandbox.set_on.cli":"nemar sandbox","cli.gaps.sandbox_unchecked":"Sandbox training could not be confirmed with the server. Run `nemar sandbox status --refresh`, then `nemar sandbox` if it is still outstanding.","cli.upload.preflight.title":"Upload access is not granted yet","cli.upload.preflight.body":"Browsing, searching and downloading are open to your account already. Uploading, or being added as a collaborator on someone else\u2019s dataset, needs one extra grant: an admin checks your GitHub handle and location against export-control and local-jurisdiction rules, once. Your email address must be verified first.","cli.upload_access.cta":"Ask for it with `nemar auth request-upload-access`.","cli.compute_access.cta":"Ask for it with `nemar compute request-access`.","cli.upload.preflight.unchecked":"Upload access could not be checked ({reason}); continuing.","cli.upload.preflight.gaps_unknown":"Could not determine what is still missing; run `nemar auth profile` for the list.","cli.upload.preflight.dry_run":"Continuing anyway: --dry-run uploads nothing."}});function tW(e){return typeof e==="string"&&p9.includes(e)}function rW(e){return typeof e==="string"&&BE.includes(e)}function nW(e){return Wo[`mail.category.${e}.label`]}function sW(e){return Wo[`mail.category.${e}.description`]}function oW(){return Wo["mail.recall.why"]}function h9(e){return e.replace(/\r\n?/g,`
32
+ [nemar] You can manually copy ${n} to ${t}`)}}function St(){let e=Jl();if(Ko&&PE===e)return Ko;if(zV(e),Ko=new Bi({projectName:"nemar",configFileMode:Zl,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}),PE=e,!CE.has(e))CE.add(e),GV(Ko.path),HV(),BV();return Ko}function GV(e){if(process.platform==="win32")return;if(!Ql(e))return;try{if((LV(e).mode&511)!==Zl)qV(e,Zl)}catch(t){console.error(`[nemar] could not secure config file permissions for ${e}:`,t)}}function HV(){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 a of KV){let i=e.get(a);if(i!==void 0)o[a]=i}e.store={activeAccount:s,accounts:{[s]:o}}}catch(s){console.error("Config migration failed (legacy config preserved):",s)}}function BV(){let e=St(),t=e.store,r=t.accounts,n=!1;if(r)for(let[o,a]of Object.entries(r)){let i=a?.apiUrl;if(!i)continue;if(UV.has(FV(i)))r[o]={...a,apiUrl:Vs},console.error(`[nemar] migrated stored apiUrl for account "${o}": ${i} -> ${Vs}`),n=!0}let s=t.apiUrl;if(r&&Object.keys(r).length>0&&s!==void 0){let{apiUrl:o,...a}=t;try{e.store=a,console.error(`[nemar] removed stale top-level apiUrl from config (was: ${s})`),n=!1}catch(i){console.error("API URL cleanup failed (config file unchanged):",i)}}if(n)try{e.store={...e.store,accounts:r}}catch(o){console.error("API URL migration failed (config file unchanged):",o)}}function Ho(){return St().get("activeAccount")}function bn(){return St().get("accounts")||{}}function vn(){let e={apiUrl:Vs},t=Ho();if(!t)return e;return bn()[t]||e}function QB(e,t){let r=St(),n=r.get("activeAccount")||"default",s=r.get("accounts")||{};if(!s[n])s[n]={apiUrl:Vs};s[n][e]=t,r.store={...r.store,accounts:s,activeAccount:n}}function ZB(e){let t=Ho();if(!t)return;let r=bn();if(r[t])delete r[t][e],St().set("accounts",r)}function e6(){let e=St(),t=Ho();if(!t){e.clear();return}let r=bn();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 t6(){St().clear()}function r6(){return!!vn().apiKey}function n6(){return St().path}function s6(){let e=bn(),t=Ho();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 o6(e){return e.username?.trim()||e.email}function WV(e){let t=e.trim().toLowerCase();if(!t)return;let r=Object.entries(bn()).filter(([,n])=>n.email&&n.email.toLowerCase()===t).map(([n])=>n);if(r.length>1){mr(`findAccountKeyByEmail: ${r.length} accounts share email ${t}: ${r.join(", ")}`);return}return r[0]}function a6(e,t){let r=St(),n=bn(),s;if(n[e])s=e;else if(t.email)s=WV(t.email);let o=s?n[s]:void 0,a={...o??{apiUrl:Vs},...t};if(s&&s!==e)delete n[s];return n[e]=a,r.store={...r.store,accounts:n,activeAccount:e},{key:e,previous:o}}function i6(e){let t=e.trim();if(!t)return"unchanged";let r=St(),n=Ho();if(!n||n===t)return"unchanged";let s=bn(),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 c6(e){let t=St(),r=bn();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 Vs="https://api.nemar.org",Zl=384,UV,VV,JB,Ko=null,PE=null,CE,KV;var mc=L(()=>{V$();_n();oc();Xl();UV=new Set(["https://api.osc.earth/nemar","https://nemar-api.neuromechanist.workers.dev","https://nemar-api-dev.shirazi-10f.workers.dev"]);VV=Z({field:_(),blocks:Ye(_()).optional(),set_on:Ye(_()).optional()}).passthrough(),JB=Z({apiKey:_().optional(),apiUrl:_().url().default(Vs),username:_().optional(),email:_().email().optional(),githubUsername:_().optional(),sandboxCompleted:Ie().optional(),sandboxDatasetId:_().optional(),dismissedNoticeIds:Ye(ne()).optional(),serviceAccess:Ie().optional(),profileGaps:Ye(VV).optional(),orcidVerified:Ie().optional(),role:_().optional(),accountKind:Mn.optional(),pendingEmailChange:_().email().optional()});CE=new Set;KV=["apiKey","apiUrl","username","email","githubUsername","sandboxCompleted","sandboxDatasetId","dismissedNoticeIds"]});var YV,XV,f6,JV,p6,QV,IE,m6,h6=8,g6=100,jE,y6,ZV,_6;var qE=L(()=>{_n();oc();YV=["given_name","family_name","affiliation","city","country"],XV=["username","github_username","email","orcid"],f6=[...YV,...XV],JV={given_name:_().max(200).optional(),family_name:_().max(200).optional(),affiliation:_().max(500).optional(),city:_().max(200).optional(),country:_().max(200).optional(),username:_().max(100).optional(),github_username:_().max(100).optional(),email:_().max(320).optional(),orcid:_().max(40).optional()},p6=Z(JV),QV=Fe(["field_not_editable","owner_only_field","edit_own_account","owner_account","system_account","invalid_edit","orcid_already_proven","invalid_search","invalid_user_id"]),IE=QV.options,m6=["exact","name","prefix","substring","fuzzy"],jE=Z({id:ne().int(),username:_().nullable(),email:_(),github_username:_().nullable(),status:_(),role:_().nullable(),account_kind:Mn.optional(),email_verified:ne().int().nullable().optional(),orcid:_().nullable().optional(),orcid_verified:ne().int().nullable().optional(),given_name:_().nullable().optional(),family_name:_().nullable().optional(),affiliation:_().nullable().optional(),city:_().nullable().optional(),country:_().nullable().optional(),description:_().nullable().optional(),signup_source:_().nullable().optional(),created_at:_(),updated_at:_().nullable().optional(),approved_at:_().nullable().optional(),revoked_at:_().nullable().optional(),deleted_at:_().nullable().optional(),service_access:ne().int().nullable().optional(),service_access_granted_at:_().nullable().optional(),service_access_granted_by:ne().int().nullable().optional(),upload_access_requested_at:_().nullable().optional(),upload_access_notified_at:_().nullable().optional(),compute_access:_().optional(),compute_access_requested_at:_().nullable().optional(),compute_access_notified_at:_().nullable().optional(),compute_access_granted_at:_().nullable().optional(),compute_access_granted_by:ne().int().nullable().optional(),compute_terms_version:_().nullable().optional(),compute_terms_accepted_at:_().nullable().optional(),identity_conflict:ne().int().nullable().optional(),username_auto_assigned:ne().int().nullable().optional(),sandbox_completed:ne().int().nullable().optional(),sandbox_completed_at:_().nullable().optional(),sandbox_dataset_id:_().nullable().optional(),aws_iam_username:_().nullable().optional(),dataset_count:ne().int().optional(),active_tokens:ne().int().optional(),linked_identities:Ye(_()).optional()}).passthrough(),y6=Z({user:jE}).passthrough(),ZV=Z({from:_().nullable(),to:_().nullable()}),_6=Z({message:_(),changed:NF(_(),ZV),notes:Ye(_()).optional(),old_address_notified:Ie().optional(),user:jE}).passthrough()});function t9(e){for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r<32&&r!==9&&r!==10||r===127)return!0}return!1}function x6(e,t){let r=s9[e];if(r==="refused")return t===void 0?null:"notice_refused";let n=t?.trim()??"";if(n==="")return r==="required"?"notice_required":null;if([...n].length>ME)return"notice_too_long";if(t9(n))return"notice_control_char";return null}var w6=20,e9=1000,$6,r9,DE,E6,n9=500,S6=200,ME=1000,s9,R6,LE,k6,o9,T6;var UE=L(()=>{_n();$6=Z({purpose:_().max(e9*4).optional().default(""),accept_terms_version:_().max(64).optional().default("")}),r9=Fe(["purpose_required","terms_not_accepted","email_not_verified","orcid_not_proven","profile_incomplete","access_closed","already_active","terms_unpublished"]),DE=r9.options,E6=Z({ok:gn(!0),already_requested:Ie(),requested_at:_().nullable().optional(),email_sent:Ie().optional(),admins_notified:ne().int().nullable().optional()}).passthrough(),s9={grant:"refused",deny:"optional",suspend:"required",revoke:"required"};R6={reason:_().max(n9).optional(),notice:_().max(ME*4,{message:"notice_too_long"}).optional()},LE=Z({id:ne().int(),username:_().nullable(),email:_(),given_name:_().nullable().optional(),family_name:_().nullable().optional(),affiliation:_().nullable().optional(),city:_().nullable().optional(),country:_().nullable().optional(),orcid:_().nullable().optional(),account_kind:_().optional(),compute_access:_(),compute_access_requested_at:_().nullable().optional(),compute_access_notified_at:_().nullable().optional(),compute_access_granted_at:_().nullable().optional(),compute_access_granted_by:ne().int().nullable().optional(),compute_purpose:_().nullable().optional(),compute_terms_version:_().nullable().optional(),compute_terms_accepted_at:_().nullable().optional()}).passthrough(),k6=Z({accounts:Ye(LE),next_after:ne().int().nullable().optional()}).passthrough(),o9=Z({granted:Ie(),cpu_milli:ne().int(),gpu_milli:ne().int(),reason:_().nullable().optional(),policy_version:ne().int().nullable().optional()}).passthrough(),T6=Z({decision:_(),from:_(),to:_(),account:LE,allocation:o9.optional(),email_sent:Ie().optional()}).passthrough()});var N6=120,P6=64,C6="unnamed machine",a9=25,FE,I6,zs,VE,j6,q6,D6,i9,c9,M6,ed,L6,U6,F6,V6,z6;var zE=L(()=>{_n();FE=Fe(["authorization_pending","slow_down","expired_token","access_denied","invalid_grant"]),I6={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."},zs=Fe(["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"]),VE=zs.options,j6={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 ${a9} 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."},q6=Z({error:zs,message:_()}).passthrough(),D6=Z({device_code:_(),user_code:_(),verification_uri:_(),verification_uri_complete:_(),expires_in:ne().int(),interval:ne().int()}).passthrough(),i9=X$("error",[Z({error:gn("authorization_pending"),message:_()}).passthrough(),Z({error:gn("slow_down"),message:_()}).passthrough()]),c9=X$("error",[Z({error:gn("expired_token"),reason:zs,message:_()}).passthrough(),Z({error:gn("access_denied"),reason:zs,message:_()}).passthrough(),Z({error:gn("invalid_grant"),reason:zs,message:_()}).passthrough()]),M6=OF([i9,c9]),ed=Z({id:ne().int(),name:_().nullable(),prefix:_(),created_at:_(),last_used_at:_().nullable(),current:Ie()}).passthrough(),L6=Z({api_key:_(),key:ed,user:Z({username:_().nullable(),email:_(),github_username:_().nullable(),role:_(),sandbox_completed:Ie(),sandbox_dataset_id:_().nullable()}).passthrough()}).passthrough(),U6=Z({user_code:_(),machine_name:_(),requested_at:_(),expires_in:ne().int(),account:Z({username:_().nullable(),email_masked:_()}).passthrough(),refusal:Z({code:zs,message:_()}).passthrough().nullable()}).passthrough(),F6=Z({ok:gn(!0),machine_name:_()}).passthrough(),V6=Z({keys:Ye(ed)}).passthrough(),z6=Z({api_key:_(),key:ed}).passthrough()});var u9,GE,Bo="https://nemar.org/settings",H6,l9,d9,f9,B6,W6;var KE=L(()=>{_n();u9=Fe(["orcid_in_use","orcid_already_linked","orcid_linked_other","email_in_use","github_in_use","identity_conflict_remains"]),GE=u9.options,H6={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, ${Bo}).`,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, ${Bo}).`,orcid_linked_other:`That ORCID iD is linked to a different NEMAR account. Unlink it there first (Settings, ${Bo}), 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, ${Bo}).`,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, ${Bo}).`,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."},l9=Fe(["orcid","email","github"]),d9=Z({id:ne().int(),username:_().nullable(),email:_(),created_at:_(),has_oauth_identity:Ie(),dataset_count:ne().int(),identity_conflict:ne().int(),canonical:Ie()}).passthrough(),f9=Z({kind:l9,value:_(),canonical_user_id:ne().int(),accounts:Ye(d9)}).passthrough(),B6=Z({groups:Ye(f9),group_count:ne().int(),flagged_count:ne().int()}).passthrough(),W6=Z({ok:gn(!0),id:ne().int(),cleared:Ie()}).passthrough()});function X6(e){return Wo[e]}function J6(e,t){return e.replace(/\{(\w+)\}/g,(r,n)=>Object.hasOwn(t,n)?t[n]:r)}var Wo;var HE=L(()=>{Wo={"tier.unverified.label":"Email not verified","tier.base.label":"Base access","tier.upload.label":"Upload access","tier.unverified.lede":"Verify your email address to activate your account.","upload_access.section.title":"Upload access","upload_access.section.lede":"A one-time admin grant. Reviewed against export-control and local-jurisdiction rules.","upload_access.state.granted":"Granted","upload_access.state.requested":"Requested","upload_access.state.not_requested":"Not requested","upload_access.invite.title":"Want to contribute a dataset?","upload_access.invite.body":"Browsing, searching and downloading are open to your account already. Uploading, or being added as a collaborator on someone else\u2019s dataset, needs one extra grant: an admin checks your GitHub handle and location against export-control and local-jurisdiction rules, once. Your email address must be verified first.","upload_access.gate.title":"Ask for upload access first","upload_access.gate.body":"Your account can browse, search and download everything public already. Uploading, or being added as a collaborator on someone else\u2019s dataset, needs one extra grant, and your email address must be verified first: an admin checks your GitHub handle and where you\u2019re based against export-control and local-jurisdiction rules. You ask once, and it is answered by email.","upload_access.request.cta":"Request upload access","upload_access.request.form_body":"Tell us what you plan to deposit, or which dataset you want to collaborate on. An admin reviews this alongside your name, username, GitHub handle and location, then grants access once.","upload_access.request.why_label":"What do you intend to upload?","upload_access.request.why_hint":"Describe what you intend to upload in 20-500 characters","upload_access.requested.title":"Your request is with an admin","upload_access.requested.lede":"An admin is reviewing your request.","upload_access.requested.lede_dated":"An admin is reviewing your request from {date}.","upload_access.requested.body.upload":"We\u2019ll email you when there\u2019s a decision, and this page will let you upload as soon as it\u2019s granted.","upload_access.requested.body":"We\u2019ll email you when there\u2019s a decision. Everything else on your account keeps working in the meantime.","upload_access.requested.cta":"See the request","upload_access.granted.body":"You can upload datasets from the upload page. Publishing one is a separate, per-dataset review you start from your dashboard.","upload_access.unverified.body":"Verify your email address first \u2014 the review happens over email.","upload_access.docs_link":"How upload access works","compute_access.section.title":"Compute access","compute_access.section.lede":"A separate grant from upload access. An admin reviews each request against export-control and local-jurisdiction rules and the purpose you state, and a grant lets you use compute within the limits an administrator sets.","compute_access.state.none":"Not requested","compute_access.state.requested":"Requested","compute_access.state.active":"Active","compute_access.state.suspended":"Suspended","compute_access.state.denied":"Not granted","compute_access.state.revoked":"Ended","compute_access.request.cta":"Request compute access","compute_access.request.form_body":"Tell us what you plan to compute. An admin reviews this alongside your name, affiliation and location, then answers once. You also accept the compute terms.","compute_access.request.purpose_label":"What do you intend to compute?","compute_access.request.purpose_hint":"Describe what you intend to compute in 20-1000 characters","compute_access.request.terms_label":"I accept the compute terms","compute_access.requested.title":"Your compute request is with an admin","compute_access.requested.lede":"An admin is reviewing your request.","compute_access.requested.lede_dated":"An admin is reviewing your request from {date}.","compute_access.requested.body":"We\u2019ll email you when there\u2019s a decision. Everything else on your account keeps working in the meantime.","compute_access.granted.body":"Compute access is active. Your balances are on your compute page, and you submit jobs with the `nemar compute` command line.","compute_access.granted.link":"Open your compute page","compute_access.closed.body":"This request has been answered and cannot be asked again. If you think that is a mistake, contact support and an admin will take another look.","compute_access.suspended.body":"Your compute access is paused. Contact support to find out why or to ask for it to be lifted.","compute_access.terms_unpublished.body":"Compute access is not open yet: the compute terms are not published. Please check back later.","compute_access.docs_link":"How compute access works","compute_page.frozen.body":"Your pools are frozen, so new jobs are refused. Contact support to find out why.","compute_page.units_note":"Amounts are service units (SU).","compute_page.available_note":"Available is granted minus held minus charged and can be negative after an overrun.","compute_page.queue_note":"It describes the queue of the whole platform, not yours, and it is a recent average, not a promise.","compute_page.usage_note":"Net charge by UTC day of the charge, not the day a job was created. A day with no charge has no bar.","compute_page.unreported_note":"NEMAR has not heard from the cluster about this job for a while. It may still finish.","compute_admin.page.title":"Compute","compute_admin.page.lede":"Compute access requests, and a read-only view of pools, usage, flagged jobs and reconciliation. A grant opens an allocation the person can spend, so each request is decided by a person, one at a time.","compute_admin.page.cli_note":"Owner policy, legal holds, record reads, moving a charge, pool grants and adjustments, and canceling a job are done with the nemar admin compute command in the command line, not here.","compute_admin.page.order_note":"Accounts are listed in the order they were created, not the order they asked in.","compute_admin.view.nav":"Compute views","compute_admin.view.requests":"Requests","compute_admin.view.pools":"Pools","compute_admin.view.usage":"Usage","compute_admin.view.flagged":"Flagged jobs","compute_admin.view.drift":"Reconciliation","compute_admin.state.nav":"Filter requests by state","compute_admin.state.requested":"Requested","compute_admin.state.active":"Active","compute_admin.state.suspended":"Suspended","compute_admin.state.denied":"Denied","compute_admin.state.revoked":"Revoked","compute_admin.state.all":"All","compute_admin.requests.none":"No accounts in this view.","compute_admin.pager.next":"Next page","compute_admin.pager.first":"First page","compute_admin.row.not_set":"not set","compute_admin.row.no_username":"no username","compute_admin.row.account_kind":"{kind} account","compute_admin.row.stated_country":"Stated country","compute_admin.row.stated_country_hint":"Check this against the export-control rules before granting. This page does not rule on it.","compute_admin.row.city":"City","compute_admin.row.affiliation":"Affiliation","compute_admin.row.email":"Email","compute_admin.row.orcid":"ORCID iD","compute_admin.row.requested":"Requested","compute_admin.row.terms":"Terms accepted","compute_admin.row.terms_value":"{version}, {date}","compute_admin.row.purpose":"Stated purpose","compute_admin.row.show_full_purpose":"Show full purpose","compute_admin.row.granted":"Granted {date} by account #{id}","compute_admin.row.not_notified":"No administrator has been emailed about this request yet.","compute_admin.row.open_in_users":"Open in Users","compute_admin.action.grant":"Grant","compute_admin.action.grant_again":"Grant again","compute_admin.action.lift_suspension":"Lift suspension","compute_admin.action.deny":"Deny","compute_admin.action.suspend":"Suspend","compute_admin.action.revoke":"Revoke","compute_admin.self_grant.disabled":"You cannot grant your own compute access. Ask another administrator or an owner.","compute_admin.dialog.title.grant":"Grant compute access?","compute_admin.dialog.title.deny":"Deny this request?","compute_admin.dialog.title.suspend":"Suspend compute access?","compute_admin.dialog.title.revoke":"Revoke compute access?","compute_admin.dialog.consequence.grant":"Opens the owner\u2019s default allocation once for this account (a repeat grant adds nothing), unfreezes the account\u2019s pools, and allows the person to use compute when it is available. The person is emailed when they have an email address that can receive it.","compute_admin.dialog.consequence.deny":"Closes this request. The person cannot ask again; only an administrator can grant later. The person is emailed when they have an email address that can receive it.","compute_admin.dialog.consequence.suspend":"Freezes the account\u2019s pools, cancels its live jobs and ends its compute sign-ins. A partner reservation that has no job reported under it is not canceled here: it is released after it expires, and a job reported under it is refused. A grant lifts the suspension. The person is emailed when they have an email address that can receive it.","compute_admin.dialog.consequence.revoke":"Freezes the account\u2019s pools, cancels its live jobs and ends its compute sign-ins. A partner reservation that has no job reported under it is not canceled here: it is released after it expires, and a job reported under it is refused. Only a new grant restores access. The person is emailed when they have an email address that can receive it.","compute_admin.dialog.reason_label":"Reason (optional)","compute_admin.dialog.reason_hint":"Recorded in the audit log. The person is not sent it.","compute_admin.dialog.reason_count":"{count} of {max}","compute_admin.dialog.notice_label":"Notice to the person","compute_admin.dialog.notice_label_optional":"Notice to the person (optional)","compute_admin.dialog.notice_help":"Emailed to the person under a fixed heading, with how to ask for a review. Write it for them. It is not the reason, which stays in the audit log.","compute_admin.dialog.notice_required_hint":"A suspension or a revocation tells the person why. Write the notice to confirm.","compute_admin.dialog.ack_export_review":"Confirm that you have reviewed this person\u2019s name, affiliation and stated country against the export-control rules","compute_admin.dialog.type_word":"Type {word} to confirm","compute_admin.dialog.cancel":"Cancel","compute_admin.result.working":"Working","compute_admin.result.granted":"Granted.","compute_admin.result.granted_opened":"Granted. Opened {cpu} CPU SU and {gpu} GPU SU.","compute_admin.result.granted_zero_default":"Granted. The owner\u2019s default allocation is zero, so nothing was opened.","compute_admin.result.granted_already":"Granted. An earlier grant already opened the default allocation, so nothing more was opened.","compute_admin.result.granted_other":"Granted. The allocation answered: {reason}.","compute_admin.result.denied":"Denied.","compute_admin.result.suspended":"Suspended. The account\u2019s pools are frozen and its live jobs are being canceled. A partner reservation with no job reported under it is left to expire.","compute_admin.result.revoked":"Revoked. The account\u2019s pools are frozen and its live jobs are being canceled. A partner reservation with no job reported under it is left to expire.","compute_admin.result.email_not_sent":"The decision stands, but the person could not be emailed. Tell them.","compute_admin.result.state_changed":"Someone else may have decided this first. The row shows the current state.","compute_admin.result.unconfirmed":"The result is not confirmed. The row shows what the server says now.","compute_admin.result.check_email":"The decision is in place, but the answer was lost, so check that the person was emailed and tell them if not.","compute_admin.result.stale":"This account was not found. Reload the page.","compute_admin.result.reread_failed":"The current state could not be read. Reload the page before deciding again.","compute_admin.result.signed_out":"You are signed out. Sign in again, then retry.","compute_admin.error.malformed":"The server sent an answer this page could not read.","compute_admin.error.unreachable":"The server could not be reached. Check your connection and try again.","compute_admin.error.redirect":"The server answered in a way this page cannot follow. Try again later.","compute_admin.error.origin":"This page was not accepted as the source of the request. Reload and try again.","compute_admin.error.rate_limited":"Too many requests. Wait a moment, then try again.","compute_admin.error.timeout":"The server did not answer in time. Try again.","compute_admin.error.failed":"The request failed ({status}). Try again.","compute_admin.error.generic":"Something went wrong. Try again.","compute_admin.error.bad_id":"That is not an account id.","compute_admin.error.bad_decision":"That is not a decision.","compute_admin.error.reason_too_long":"A reason is at most {max} characters.","compute_admin.error.notice_required":"This decision needs a notice to the person.","compute_admin.error.notice_refused":"A grant does not take a notice to the person.","compute_admin.error.notice_too_long":"A notice is at most {max} characters.","compute_admin.error.notice_control_char":"A notice may not contain control characters other than newline and tab.","compute_admin.error.bad_quarter":"A quarter is written like 2026Q4.","compute_admin.section.failed":"Could not load {what}: {reason}","compute_admin.col.holder":"Holder","compute_admin.col.pool":"Pool","compute_admin.col.granted":"Granted (SU)","compute_admin.col.held":"Held (SU)","compute_admin.col.charged":"Charged (SU)","compute_admin.col.available":"Available (SU)","compute_admin.col.frozen":"Frozen","compute_admin.col.updated":"Updated","compute_admin.col.partition":"Partition","compute_admin.col.source":"Front door","compute_admin.col.users":"Distinct people","compute_admin.col.jobs":"Jobs","compute_admin.col.job":"Job","compute_admin.col.account":"Account","compute_admin.col.state":"State","compute_admin.col.flags":"Flags","compute_admin.col.failure":"Failure","compute_admin.col.created":"Created","compute_admin.col.ended":"Ended","compute_admin.col.slurm":"Scheduler job","compute_admin.col.elapsed":"Elapsed (s)","compute_admin.col.resources":"Nodes, CPUs, GPUs","compute_admin.col.ingested":"Ingested","compute_admin.ref.account":"account #{id}","compute_admin.ref.no_account":"no account","compute_admin.pools.platform":"Platform budgets","compute_admin.pools.partner":"Partner pools","compute_admin.pools.account":"Account pools","compute_admin.pools.none_platform":"No platform budgets are recorded.","compute_admin.pools.none":"No pools are recorded in this group.","compute_admin.pools.truncated":"Showing the first {shown} pools of this group; more exist.","compute_admin.pools.frozen":"Frozen","compute_admin.pools.open":"Open","compute_admin.usage.quarter":"Quarter","compute_admin.usage.counts_note":"These are counts of people and jobs, not service units. A person is counted once however many jobs they ran, and jobs that skipped the reservation or could not be attributed are left out.","compute_admin.usage.totals":"Total","compute_admin.usage.none":"No jobs were recorded in this quarter.","compute_admin.flag.nav":"Filter jobs by flag","compute_admin.flag.unreserved":"Unreserved","compute_admin.flag.unattributed":"Unattributed","compute_admin.flag.mismatch":"Mismatch","compute_admin.flag.overrun":"Overrun","compute_admin.flag.meaning.unreserved":"The job skipped the reservation. Its charge went to a partner pool and not to a person.","compute_admin.flag.meaning.unattributed":"The job skipped the reservation and its owner maps to no active account.","compute_admin.flag.meaning.mismatch":"NEMAR\u2019s record and the scheduler\u2019s accounting disagree for this job, or a partner\u2019s report for it was refused or could not be checked, or a partner job used more than its hold and was capped.","compute_admin.flag.meaning.overrun":"The job used more than its hold, and the excess is recorded as an overrun in the ledger.","compute_admin.flag.followup":"Moving the charge of an unreserved job to a person is an owner action in the command line.","compute_admin.flagged.none":"No jobs carry this flag. That is a fact about this read only.","compute_admin.flagged.platform_failure":"NEMAR\u2019s fault","compute_admin.flagged.partner":"Partner: {state}, {flag}","compute_admin.drift.paused":"Reconciliation is paused while compute is off. An empty list below does not mean nothing is unmatched.","compute_admin.drift.pause_unknown":"Whether reconciliation is running is not known, so an empty list does not mean nothing is unmatched.","compute_admin.drift.status":"Status","compute_admin.drift.compute_on":"Compute is on.","compute_admin.drift.compute_off":"Compute is off.","compute_admin.drift.tapis":"Scheduler gateway: token {token}, health {health}.","compute_admin.drift.attention":"Needs a person to look","compute_admin.drift.attention_none":"No attention count is positive.","compute_admin.drift.unmatched":"Accounting rows no job claims","compute_admin.drift.unmatched_shown":"Showing the newest {shown} of {total}.","compute_admin.drift.unmatched_none":"No accounting rows are waiting for a job.","compute_admin.drift.not_priced":"not priced","compute_admin.drift.mismatch":"Jobs flagged mismatch","compute_admin.drift.mismatch_more":"See the Flagged jobs view for the rest","compute_admin.unavailable.title":"Not available yet","compute_admin.unavailable.usage_by_day":"Service units charged by day, partition and front door across the platform are not served by any admin read yet.","compute_admin.unavailable.drift_difference":"The difference between NEMAR\u2019s ledger and the supercomputer\u2019s accounting, per job or per day, and the tolerance it is measured against are not served by any admin read yet. No row is marked over tolerance because this page has no tolerance to apply.","compute_admin.unavailable.link":"Tracking issue","compute_admin.badge.awaiting_decision":"awaiting decision","gap.sentence":"{label} is missing: needed {blocks}.","gap.set_on.both":"Set it in {web} or run `{cli}`.","gap.set_on.web":"Set it in {web}.","gap.blocks.verified":"to activate your account","gap.blocks.upload_access":"to request upload access","gap.blocks.compute_access":"to request compute access","gap.blocks.publication":"to publish a dataset","gap.blocks.unknown":"to finish setting up your account","gap.blocks.noun.verified":"account activation","gap.blocks.noun.upload_access":"upload access","gap.blocks.noun.compute_access":"compute access","gap.blocks.noun.publication":"publication","gap.set_on.default_web":"Settings","gap.field.email_verified.label":"A verified email address","gap.field.username.label":"Username","gap.field.given_name.label":"Given name","gap.field.family_name.label":"Family name","gap.field.orcid_verified.label":"Verified ORCID iD","gap.field.github_username.label":"GitHub handle","gap.field.city.label":"City","gap.field.country.label":"Country","gap.field.affiliation.label":"Affiliation","gap.field.why.label":"A description of what you intend to upload","gap.field.email_verified.set_on.web":"the verify step on your dashboard","gap.field.email_verified.set_on.cli":"nemar auth resend-verification","gap.field.username.set_on.web":"Settings","gap.field.username.set_on.cli":"nemar auth profile set-username","gap.field.given_name.set_on.web":"Settings","gap.field.given_name.set_on.cli":"nemar auth profile set-name","gap.field.family_name.set_on.web":"Settings","gap.field.family_name.set_on.cli":"nemar auth profile set-name","gap.field.given_name.set_on.web.orcid":"your ORCID record at orcid.org, then sign in again","gap.field.family_name.set_on.web.orcid":"your ORCID record at orcid.org, then sign in again","gap.field.orcid_verified.set_on.web":"Settings","gap.field.orcid_verified.set_on.cli":"nemar auth profile orcid link","gap.field.github_username.set_on.web":"Settings","gap.field.github_username.set_on.cli":"nemar auth profile set-github","gap.field.city.set_on.web":"Settings","gap.field.city.set_on.cli":"nemar auth profile set-location","gap.field.country.set_on.web":"Settings","gap.field.country.set_on.cli":"nemar auth profile set-location","gap.field.affiliation.set_on.web":"Settings","gap.field.affiliation.set_on.cli":"nemar auth profile set-affiliation","gap.field.why.set_on.web":"the request form in Settings","gap.field.why.set_on.cli":"nemar auth request-upload-access","gaps.title":"What is still missing","gaps.none":"Nothing outstanding \u2014 every field NEMAR needs is filled in.","gaps.nudge.title":"Your profile isn\u2019t finished yet","gaps.nudge.cta":"Complete your profile","gaps.upload.title":"Before you can ask, your account still needs:","gaps.request.title":"Finish these first:","gaps.admin.title":"Still missing","gaps.admin.item":"{label} \u2014 blocks {blocks}","gaps.admin.none":"Nothing missing \u2014 every field the request needs is filled in.","gaps.admin.not_loaded":"Not loaded \u2014 open the user page to see what is still missing.","onboarding.username.auto_assigned.title":"We chose your username from your name","onboarding.username.auto_assigned.body":"Your account needed a username to be listed as a dataset owner, so one was made from your name when you signed in. You can change it once, here, until an admin grants you upload access.","welcome.unverified.title":"Verify your email address","welcome.unverified.body":"Authorizing with ORCID created your NEMAR account and signed you in. One step left: enter the 6-digit code we emailed you. That activates the account \u2014 no admin approval is involved.","welcome.active.title":"Your account is active","welcome.active.body":"Authorizing with ORCID created your NEMAR account and signed you in. There is no separate sign-up step and no approval queue: browse, search, and your dashboard all work right now.","welcome.upload_access.title":"Ask for upload access when you\u2019re ready to contribute","welcome.upload_access.body":"Reading is open to every verified account. Uploading and compute need one extra grant, because an admin has to check your GitHub handle and location against export-control and local-jurisdiction rules first. You ask once, from Settings.","oidc.consent.title":"{client} wants to use your NEMAR account","oidc.consent.acts_as_you":"If you allow it, {client} can act as you on NEMAR in the ways listed below.","oidc.consent.compute_spend":"If you sign in and run compute with this app, it counts against your NEMAR compute allocation.","oidc.consent.scopes_title":"It is asking to:","oidc.consent.scope.openid":"Know which NEMAR account is yours","oidc.consent.scope.profile":"See your name","oidc.consent.scope.email":"See your email address","oidc.consent.scope.orcid":"See your ORCID iD, and whether you proved it by signing in with ORCID","oidc.consent.scope.nemar.account":"See your account type, status and access level","oidc.consent.scope.offline_access":"Keep this access when you are not using it","oidc.consent.scope.compute.read":"See your compute access, balances, usage and jobs","oidc.consent.scope.compute.reserve":"Reserve compute time, report jobs and release reservations for you","oidc.consent.scope.compute.submit":"Submit compute jobs that NEMAR runs for you","oidc.consent.redirect_host":"Either answer sends you to {redirect_host}.","oidc.consent.allow":"Allow","oidc.consent.deny":"Deny","oidc.rule.title":"You can\u2019t sign in to {client} with this account","oidc.rule.account_inactive":"Your NEMAR account is not active.","oidc.rule.account_not_person":"{client} is only for personal accounts, and this account is not one.","oidc.rule.orcid_not_proven":"{client} needs an ORCID iD you proved by signing in to NEMAR with ORCID. Link your ORCID iD in Settings, then try again.","oidc.rule.return":"Return to {client}","oidc.error.title":"This sign-in can\u2019t continue","oidc.error.invalid_client":"The site that sent you here is not one NEMAR signs people in to.","oidc.error.invalid_redirect_uri":"The site that sent you here asked NEMAR to send you to an address it has not registered, so NEMAR will not send you there.","oidc.error.invalid_request":"The sign-in request is incomplete or malformed. Go back to the site you came from and start again.","oidc.error.consent_invalid":"This page has expired. Go back to the site you came from and start again.","oidc.error.unavailable":"NEMAR could not complete this sign-in right now. Try again in a moment.","oidc.error.rate_limited":"Too many sign-in attempts. Try again in a minute.","mail.category.news.label":"News","mail.category.news.description":"New features, data and events.","mail.category.rfcs.label":"Requests for comments","mail.category.rfcs.description":"A new NEMAR request for comments is open for discussion.","mail.category.maintenance.label":"Maintenance","mail.category.maintenance.description":"Planned downtime and changes to the service.","mail.category.recall.label":"Recalls","mail.category.recall.description":"A dataset, release or credential NEMAR distributed has a problem you need to act on.","mail.recall.why":"Recalls cannot be turned off: they tell you to stop using, delete or replace something NEMAR distributed or issued, because continuing to use it can cause harm.","cli.gaps.section.title":"Profile","cli.gaps.unknown":"not checked: run 'nemar auth status --refresh'","cli.gaps.unreported":"not reported by this backend","cli.gap.set_on.cli_only":"Run `{cli}`.","cli.gap.field.sandbox.label":"Sandbox training","cli.gap.blocks.sandbox":"to upload a dataset from the CLI","cli.gap.field.sandbox.set_on.cli":"nemar sandbox","cli.gaps.sandbox_unchecked":"Sandbox training could not be confirmed with the server. Run `nemar sandbox status --refresh`, then `nemar sandbox` if it is still outstanding.","cli.upload.preflight.title":"Upload access is not granted yet","cli.upload.preflight.body":"Browsing, searching and downloading are open to your account already. Uploading, or being added as a collaborator on someone else\u2019s dataset, needs one extra grant: an admin checks your GitHub handle and location against export-control and local-jurisdiction rules, once. Your email address must be verified first.","cli.upload_access.cta":"Ask for it with `nemar auth request-upload-access`.","cli.compute_access.cta":"Ask for it with `nemar compute request-access`.","cli.upload.preflight.unchecked":"Upload access could not be checked ({reason}); continuing.","cli.upload.preflight.gaps_unknown":"Could not determine what is still missing; run `nemar auth profile` for the list.","cli.upload.preflight.dry_run":"Continuing anyway: --dry-run uploads nothing."}});function tW(e){return typeof e==="string"&&p9.includes(e)}function rW(e){return typeof e==="string"&&BE.includes(e)}function nW(e){return Wo[`mail.category.${e}.label`]}function sW(e){return Wo[`mail.category.${e}.description`]}function oW(){return Wo["mail.recall.why"]}function h9(e){return e.replace(/\r\n?/g,`
33
33
  `).trim().split(/\n{2,}/).map((t)=>t.trim()).filter((t)=>t!=="")}function g9(e){let t=/^(#{1,3})\s+(.+)$/.exec(e);if(!t)return null;return{level:t[1].length,text:t[2]}}function aW(e){let t=new Set(h9(e).map((r)=>g9(r)?.text.trim().toLowerCase()).filter((r)=>Boolean(r)));return m9.filter((r)=>!t.has(r.toLowerCase()))}function iW(e){let t=e.trim(),r=y9.exec(t);if(r)return{kind:"dataset",datasetId:r[1],version:r[2]??null,text:t};if(_9.test(t))return{kind:"github",url:t,text:t};return null}var BE,p9,eW="recall",WE,m9,y9,_9,cW="A recall needs a reference: a dataset id with an optional version (nm000104 or nm000104@v1.2.0), or a nemarOrg or nemarDatasets issue, pull request or security advisory URL.";var YE=L(()=>{HE();BE=["news","rfcs","maintenance"],p9=[...BE,"recall"];WE=["recall_cannot_be_turned_off","admin_alert_not_self_service","unknown_mail_preference","invalid_mail_preference"];m9=["What is affected","What to do"];y9=/^([a-z]{2}\d{6})(?:@v?(\d+\.\d+\.\d+))?$/,_9=/^https:\/\/github\.com\/(?:nemarOrg|nemarDatasets)\/[A-Za-z0-9._-]+\/(?:(?:issues|pull)\/\d{1,9}|security\/advisories\/GHSA(?:-[a-z0-9]{4}){3})$/});function mW(e){return typeof e==="string"&&b9.includes(e)}var v9,dW,fW,pW,b9,w9="ci_check_unavailable",XE,JE,QE,hW="X-Approval-Dispatch-Token",gW,yW="Search reflects this at once; the public dataset page and catalog list are cached at the edge and can keep showing the dataset for several minutes.";var ZE=L(()=>{_n();v9=/^\d{4}-\d{4}-\d{4}-\d{3}[\dX]$/,dW=_().regex(v9,"ORCID must be in format 0000-0000-0000-000X"),fW=Fe(["found","no_public_name","lookup_failed"]),pW=Fe(["bids_validation_failed","bids_validation_pending","bids_validation_in_progress","prescreen_failed","min_requirements_failed","owner_name_missing","identifier_screen_findings"]),b9=["bids_validation_pending","bids_validation_in_progress"];XE=[w9],JE=["identifier_screen_pending","identifier_screen_not_clear","identifier_screen_not_applicable"],QE=["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"],gW=Fe(["filled","would_fill","no_public_name","lookup_failed","write_failed"])});function tS(e){if(eS)return;eS=!0;let t=Pt.yellow("\u2500".repeat(60)),r=Pt.yellow.bold("[MAINTENANCE]"),n=Pt.dim(`mode: ${e.mode}`),s=e.eta?`
34
34
  ${Pt.dim(`eta: ${e.eta}`)}`:"";process.stderr.write(`${t}
35
35
  ${r} ${e.message}
36
36
  ${n}${s}
37
37
  ${t}
38
- `)}var eS=!1;var rS=L(()=>{Fl()});function nS(){if(process.env.TEST_API_URL)return process.env.TEST_API_URL;if(rd)return td;return vn().apiUrl||td}async function CW(e,t={},r=!1,n,s="json",o){let a=`${nS()}${e}`,i={"Content-Type":"application/json","X-CLI-Version":uc,...t.headers};if(r){let p=vn();if(!p.apiKey&&r===!0)throw new pr(401,"Not authenticated. Run 'nemar auth login' first.");if(p.apiKey)i.Authorization=`Bearer ${p.apiKey}`}let c=t.method||"GET",u=typeof t.body==="string"?t.body:void 0,l=Date.now(),d;try{let p=[...t.signal?[t.signal]:[],...o===void 0?[]:[AbortSignal.timeout(o)]];d=await fetch(a,{...t,headers:i,...p.length===0?{}:{signal:p.length===1?p[0]:AbortSignal.any(p)}})}catch(p){if(fc())pc({method:c,url:a,status:null,durationMs:Date.now()-l,requestHeaders:i,requestBody:u,error:p instanceof Error?p.message:String(p)});throw new pr(0,`Network error: Could not connect to ${nS()}`,{originalError:p instanceof Error?p.message:String(p)})}let m;try{m=await d.text()}catch(p){if(fc())pc({method:c,url:a,status:d.status,durationMs:Date.now()-l,requestHeaders:i,requestBody:u,error:p instanceof Error?p.message:String(p)});throw new pr(0,"Failed to read response body",{httpStatus:d.status,originalError:p instanceof Error?p.message:String(p)})}if(fc())pc({method:c,url:a,status:d.status,durationMs:Date.now()-l,requestHeaders:i,requestBody:u,responseBody:m});if(s==="text"&&d.ok)return{text:m,headers:d.headers};let f;try{f=JSON.parse(m)}catch{throw new pr(d.status,`Invalid response from server (status ${d.status})`)}if(!d.ok){if(d.status===503&&(f.mode==="read-only"||f.mode==="full")){let hr=typeof f.message==="string"?f.message:"NEMAR is in maintenance mode. Please retry shortly.",wn=typeof f.eta==="string"?f.eta:null,Ln=new Il(f.mode,hr,wn,f.details);throw tS(Ln),Ln}let p=typeof f.block_reason==="string",h=Array.isArray(f.missing)?f.missing.filter((hr)=>typeof hr==="string"):void 0,y=typeof f.error==="string"&&(tE.includes(f.error)||GE.includes(f.error)),v=typeof f.error==="string"&&(FE.options.includes(f.error)||VE.includes(f.error)),A=typeof f.error==="string"&&Q$.includes(f.error),k=typeof f.error==="string"&&IE.includes(f.error),M=typeof f.error==="string"&&JE.includes(f.error),S=typeof f.error==="string"&&XE.includes(f.error),$e=typeof f.error==="string"&&QE.includes(f.error),je=typeof f.error==="string"&&WE.includes(f.error),It=p||je||S||$e||y||v||A||k||M||h!==void 0&&typeof f.error==="string"&&eE.includes(f.error)||h!==void 0&&typeof f.error==="string"&&DE.includes(f.error)?f.message||f.error:f.error||f.message;if(d.status===404&&f.error==="Not Found"&&typeof f.message==="string")It=`${f.message}. This NEMAR backend does not support this command yet.`;let Ve=new pr(d.status,It||"Request failed",f.details,typeof f.step==="string"?f.step:void 0,p?f.block_reason:void 0,h);if(typeof f.error==="string")Ve.code=f.error;if(typeof f.reason==="string")Ve.reason=f.reason;Ve.rawBody=f;let xt=Number(d.headers.get("retry-after"));if(d.headers.get("retry-after")!==null&&Number.isFinite(xt)&&xt>=0)Ve.retryAfterSeconds=xt;throw Ve}if(n){let p=n.safeParse(f);if(!p.success)throw new pr(d.status,`Response for ${e} did not match the expected NEMAR contract`,{issues:p.error.issues});return p.data}return f}var td="https://nemar-api-dev.sccn-org.workers.dev",rd;var sS=L(()=>{qE();UE();zE();KE();YE();ZE();oc();mc();Xl();rS();Kl();jl();rd=td.includes("workers.dev")});mc();import{open as A9,rm as O9}from"fs/promises";sS();var oS="NEMAR_DATA_HOSTS",$9="NEMAR_DATA_HOSTS_ONLY",E9="https://private.nemar.org",S9="https://private-test.nemar.org",x9=/^[a-z]{2,3}[0-9]{6}$/;function aS(e){return x9.test(e)}function R9(e){return e}function iS(e){return e==="127.0.0.1"||e==="localhost"||e==="[::1]"}function cS(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:"&&iS(r.hostname))return r.origin;return null}function uS(e){let t=[],r=[];for(let n of(e??"").split(",")){let s=n.trim();if(s==="")continue;let o=cS(s);if(o===null)r.push(s);else if(!t.includes(o))t.push(o)}return{origins:t,rejected:r}}function lS(e){return e.env??process.env}function k9(e={}){let t=lS(e),r=e.isDevBuild??rd,n=t[$9]==="1"?[]:[r?S9:E9],{origins:s}=uS(t[oS]);return[...n,...s.filter((o)=>!n.includes(o))].map(R9)}function qW(e={}){return uS(lS(e)[oS]).rejected}function gc(e,t={}){let r=cS(e);if(r===null)return null;return k9(t).find((n)=>n===r)??null}function dS(e,t={}){return gc(e,t)!==null}function DW(e,t={}){let r;try{r=new URL(e)}catch{return null}if(r.username!==""||r.password!=="")return null;return gc(r.origin,t)}function fS(e,t){if(e.protocol==="https:")return!0;return e.protocol==="http:"&&iS(e.hostname)&&new URL(t).protocol==="http:"}var T9="NEMAR_DATA_HOST_TIMEOUT_MS";function nd(e,t=process.env){let r=t[T9];if(r===void 0||!/^[0-9]+$/.test(r))return e;let n=Number(r);return n>0&&n<e?n:e}function sd(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 pS=3,hS=60000,N9=262144,gS=255,yS=/^[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 _S(e){return e.length<=gS&&yS.test(e)}function P9(e){if(e.length>gS)return null;let t=yS.exec(e);if(!t||t[2]!==void 0)return null;let r=Number(t[1]);return Number.isSafeInteger(r)?r:null}function C9(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(!aS(t))return{ok:!1,message:"The dataset setting is not a dataset id (two or three letters and six digits)."};let n=gc(e,r);if(n===null)return{ok:!1,message:`The host setting ${Ct(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 Ct(e,t=200){let r=e.replace(/[^\x20-\x7e]/g,"?");return r.length>t?`${r.slice(0,t)}...`:r}function I9(e,t){return new URL(`${e.origin}/o/${encodeURIComponent(e.dataset)}/${encodeURIComponent(t)}`)}function vS(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 bS(e,t,r,n,s,o){if(!dS(e.origin,e.options))return{kind:"failed",message:"The host is not on this CLI's list of data hosts."};let a=I9(e,t),i=!1;for(let c=0;;c++){let u={"Accept-Encoding":"identity"};if(a.origin===e.origin)u.Authorization=`Bearer ${r}`;let l;try{l=await fetch(a,{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 (${sd(f)}).`}}if(l.status<300||l.status>=400)return{kind:"response",response:l,redirected:i};if(await l.body?.cancel().catch(()=>{}),!s)return{kind:"response",response:l,redirected:i};if(c>=pS)return{kind:"failed",message:`More than ${pS} redirects.`};let d=l.headers.get("location");if(!d)return{kind:"failed",message:"A redirect named no address."};let m;try{m=new URL(d,a)}catch{return{kind:"failed",message:"A redirect named an address that is not a URL."}}if(!fS(m,e.origin))return{kind:"failed",message:"A redirect named an address that is not https."};a=m,i=!0}}async function wS(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 j9(e,t,r,n,s){if(!_S(t))return{ok:!1,message:"The key is not one a data host serves."};let o=P9(t);return wS(nd(hS,e.options?.env),async(a,i)=>{let c=await bS(e,t,r,"GET",!0,a);if(c.kind==="failed")return{ok:!1,message:c.message};let{response:u,redirected:l}=c;if(u.status!==200||!u.body)return await u.body?.cancel().catch(()=>{}),{ok:!1,message:vS(u.status,l)};let d=u.headers.get("content-length");if(o!==null&&d!==null&&Number(d)!==o)return await u.body.cancel().catch(()=>{}),{ok:!1,message:`The object is ${Ct(d,20)} bytes but its key says ${o}.`};i();let m,f=0,p=0;try{m=await A9(n,"w");let h=u.body.getReader();while(!0){let{done:y,value:v}=await h.read();if(y)break;if(i(),f+=v.byteLength,o!==null&&f>o)throw await h.cancel().catch(()=>{}),new yc(`More bytes arrived than the key's ${o}.`);if(await m.write(v),f-p>=N9)p=f,s(f)}if(await m.close(),m=void 0,o!==null&&f!==o)throw new yc(`The object ended after ${f} bytes; its key says ${o}.`);if(f!==p)s(f);return{ok:!0,bytes:f}}catch(h){if(await m?.close().catch(()=>{}),await O9(n,{force:!0}).catch(()=>{}),h instanceof yc)return{ok:!1,message:h.message};if(a.aborted)return{ok:!1,message:"The transfer stalled and timed out."};return{ok:!1,message:`The transfer failed (${sd(h)}).`}}})}class yc extends Error{constructor(e){super(e);this.name="SizeError"}}async function q9(e,t,r){if(!_S(t))return{state:"unknown",message:"The key is not one a data host serves."};return wS(nd(hS,e.options?.env),async(n)=>{let s=await bS(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:vS(o,!1)}})}class _c extends Error{constructor(e){super(e);this.name="ProtocolAbort"}}async function $S(e,t){let r=e.lines[Symbol.asyncIterator](),n=[],s=null,o=null,a=async()=>{let l=n.shift();if(l!==void 0)return l;let d=await r.next();return d.done?null:d.value},i=async(l)=>{await e.send(`GETCONFIG ${l}`);while(!0){let d=await r.next();if(d.done)throw new _c("git-annex closed the connection");let m=d.value;if(m==="VALUE"||m.startsWith("VALUE ")){let f=m.slice(5).trimStart();return f===""?void 0:f}if(m.startsWith("ERROR"))throw new _c(m);n.push(m)}},c=async()=>{let l=await i("host"),d=await i("dataset");return C9(l,d,t.options)},u=async(l,d)=>{if(!s||!o){await e.send(`TRANSFER-FAILURE RETRIEVE ${Ct(l)} The remote has not been prepared.`);return}let m=Promise.resolve(),f=await j9(s,l,o,d,(p)=>{m=m.then(()=>e.send(`PROGRESS ${p}`))});if(await m,f.ok)await e.send(`TRANSFER-SUCCESS RETRIEVE ${l}`);else await e.send(`TRANSFER-FAILURE RETRIEVE ${Ct(l)} ${Ct(f.message)}`)};await e.send("VERSION 1");while(!0){let l=await a();if(l===null)return 0;if(l.trim()==="")continue;let[d,...m]=mS(l,1),f=m[0]??"";try{switch(d){case"EXTENSIONS":await e.send("EXTENSIONS");break;case"INITREMOTE":{let p=await c();await e.send(p.ok?"INITREMOTE-SUCCESS":`INITREMOTE-FAILURE ${Ct(p.message)}`);break}case"PREPARE":{let p=await c();if(!p.ok){s=null,await e.send(`PREPARE-FAILURE ${Ct(p.message)}`);break}let h=t.loadApiKey();if(!h){s=null,await e.send("PREPARE-FAILURE No NEMAR API key is stored. Run 'nemar auth login' first.");break}s=p.settings,o=h,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[p,h,...y]=mS(f,2);if(p==="STORE")await e.send(`TRANSFER-FAILURE STORE ${Ct(h??"")} This remote is read-only for now.`);else if(p==="RETRIEVE"&&h&&y[0])await u(h,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 ${Ct(f)} The remote has not been prepared.`);break}let p=await q9(s,f,o);if(p.state==="present")await e.send(`CHECKPRESENT-SUCCESS ${f}`);else if(p.state==="absent")await e.send(`CHECKPRESENT-FAILURE ${f}`);else await e.send(`CHECKPRESENT-UNKNOWN ${Ct(f)} ${p.message}`);break}case"REMOVE":await e.send(`REMOVE-FAILURE ${Ct(f)} This remote is read-only for now.`);break;case"ERROR":return 1;case"VALUE":break;default:await e.send("UNSUPPORTED-REQUEST")}}catch(p){if(p instanceof _c)return 1;throw p}}}function mS(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*D9(){let e=new TextDecoder,t="";for await(let r of Bun.stdin.stream()){t+=e.decode(r,{stream:!0});let n=t.indexOf(`
38
+ `)}var eS=!1;var rS=L(()=>{Fl()});function nS(){if(process.env.TEST_API_URL)return process.env.TEST_API_URL;if(rd)return td;return vn().apiUrl||td}async function CW(e,t={},r=!1,n,s="json",o){let a=`${nS()}${e}`,i={"Content-Type":"application/json","X-CLI-Version":uc,...t.headers};if(r){let p=vn();if(!p.apiKey&&r===!0)throw new pr(401,"Not authenticated. Run 'nemar auth login' first.");if(p.apiKey)i.Authorization=`Bearer ${p.apiKey}`}let c=t.method||"GET",u=typeof t.body==="string"?t.body:void 0,l=Date.now(),d;try{let p=[...t.signal?[t.signal]:[],...o===void 0?[]:[AbortSignal.timeout(o)]];d=await fetch(a,{...t,headers:i,...p.length===0?{}:{signal:p.length===1?p[0]:AbortSignal.any(p)}})}catch(p){if(fc())pc({method:c,url:a,status:null,durationMs:Date.now()-l,requestHeaders:i,requestBody:u,error:p instanceof Error?p.message:String(p)});throw new pr(0,`Network error: Could not connect to ${nS()}`,{originalError:p instanceof Error?p.message:String(p)})}let m;try{m=await d.text()}catch(p){if(fc())pc({method:c,url:a,status:d.status,durationMs:Date.now()-l,requestHeaders:i,requestBody:u,error:p instanceof Error?p.message:String(p)});throw new pr(0,"Failed to read response body",{httpStatus:d.status,originalError:p instanceof Error?p.message:String(p)})}if(fc())pc({method:c,url:a,status:d.status,durationMs:Date.now()-l,requestHeaders:i,requestBody:u,responseBody:m});if(s==="text"&&d.ok)return{text:m,headers:d.headers};let f;try{f=JSON.parse(m)}catch{throw new pr(d.status,`Invalid response from server (status ${d.status})`)}if(!d.ok){if(d.status===503&&(f.mode==="read-only"||f.mode==="full")){let hr=typeof f.message==="string"?f.message:"NEMAR is in maintenance mode. Please retry shortly.",wn=typeof f.eta==="string"?f.eta:null,Ln=new Il(f.mode,hr,wn,f.details);throw tS(Ln),Ln}let p=typeof f.block_reason==="string",h=Array.isArray(f.missing)?f.missing.filter((hr)=>typeof hr==="string"):void 0,y=typeof f.error==="string"&&(tE.includes(f.error)||GE.includes(f.error)),v=typeof f.error==="string"&&(FE.options.includes(f.error)||VE.includes(f.error)),A=typeof f.error==="string"&&Q$.includes(f.error),k=typeof f.error==="string"&&IE.includes(f.error),M=typeof f.error==="string"&&JE.includes(f.error),S=typeof f.error==="string"&&XE.includes(f.error),$e=typeof f.error==="string"&&QE.includes(f.error),je=typeof f.error==="string"&&WE.includes(f.error),It=p||je||S||$e||y||v||A||k||M||h!==void 0&&typeof f.error==="string"&&eE.includes(f.error)||h!==void 0&&typeof f.error==="string"&&DE.includes(f.error)?f.message||f.error:f.error||f.message;if(d.status===404&&f.error==="Not Found"&&typeof f.message==="string")It=`${f.message}. This NEMAR backend does not support this command yet.`;let Ve=new pr(d.status,It||"Request failed",f.details,typeof f.step==="string"?f.step:void 0,p?f.block_reason:void 0,h);if(typeof f.error==="string")Ve.code=f.error;if(typeof f.reason==="string")Ve.reason=f.reason;Ve.rawBody=f;let xt=Number(d.headers.get("retry-after"));if(d.headers.get("retry-after")!==null&&Number.isFinite(xt)&&xt>=0)Ve.retryAfterSeconds=xt;throw Ve}if(n){let p=n.safeParse(f);if(!p.success)throw new pr(d.status,`Response for ${e} did not match the expected NEMAR contract`,{issues:p.error.issues});return p.data}return f}var td="https://api.nemar.org",rd;var sS=L(()=>{qE();UE();zE();KE();YE();ZE();oc();mc();Xl();rS();Kl();jl();rd=td.includes("workers.dev")});mc();import{open as A9,rm as O9}from"fs/promises";sS();var oS="NEMAR_DATA_HOSTS",$9="NEMAR_DATA_HOSTS_ONLY",E9="https://private.nemar.org",S9="https://private-test.nemar.org",x9=/^[a-z]{2,3}[0-9]{6}$/;function aS(e){return x9.test(e)}function R9(e){return e}function iS(e){return e==="127.0.0.1"||e==="localhost"||e==="[::1]"}function cS(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:"&&iS(r.hostname))return r.origin;return null}function uS(e){let t=[],r=[];for(let n of(e??"").split(",")){let s=n.trim();if(s==="")continue;let o=cS(s);if(o===null)r.push(s);else if(!t.includes(o))t.push(o)}return{origins:t,rejected:r}}function lS(e){return e.env??process.env}function k9(e={}){let t=lS(e),r=e.isDevBuild??rd,n=t[$9]==="1"?[]:[r?S9:E9],{origins:s}=uS(t[oS]);return[...n,...s.filter((o)=>!n.includes(o))].map(R9)}function qW(e={}){return uS(lS(e)[oS]).rejected}function gc(e,t={}){let r=cS(e);if(r===null)return null;return k9(t).find((n)=>n===r)??null}function dS(e,t={}){return gc(e,t)!==null}function DW(e,t={}){let r;try{r=new URL(e)}catch{return null}if(r.username!==""||r.password!=="")return null;return gc(r.origin,t)}function fS(e,t){if(e.protocol==="https:")return!0;return e.protocol==="http:"&&iS(e.hostname)&&new URL(t).protocol==="http:"}var T9="NEMAR_DATA_HOST_TIMEOUT_MS";function nd(e,t=process.env){let r=t[T9];if(r===void 0||!/^[0-9]+$/.test(r))return e;let n=Number(r);return n>0&&n<e?n:e}function sd(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 pS=3,hS=60000,N9=262144,gS=255,yS=/^[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 _S(e){return e.length<=gS&&yS.test(e)}function P9(e){if(e.length>gS)return null;let t=yS.exec(e);if(!t||t[2]!==void 0)return null;let r=Number(t[1]);return Number.isSafeInteger(r)?r:null}function C9(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(!aS(t))return{ok:!1,message:"The dataset setting is not a dataset id (two or three letters and six digits)."};let n=gc(e,r);if(n===null)return{ok:!1,message:`The host setting ${Ct(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 Ct(e,t=200){let r=e.replace(/[^\x20-\x7e]/g,"?");return r.length>t?`${r.slice(0,t)}...`:r}function I9(e,t){return new URL(`${e.origin}/o/${encodeURIComponent(e.dataset)}/${encodeURIComponent(t)}`)}function vS(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 bS(e,t,r,n,s,o){if(!dS(e.origin,e.options))return{kind:"failed",message:"The host is not on this CLI's list of data hosts."};let a=I9(e,t),i=!1;for(let c=0;;c++){let u={"Accept-Encoding":"identity"};if(a.origin===e.origin)u.Authorization=`Bearer ${r}`;let l;try{l=await fetch(a,{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 (${sd(f)}).`}}if(l.status<300||l.status>=400)return{kind:"response",response:l,redirected:i};if(await l.body?.cancel().catch(()=>{}),!s)return{kind:"response",response:l,redirected:i};if(c>=pS)return{kind:"failed",message:`More than ${pS} redirects.`};let d=l.headers.get("location");if(!d)return{kind:"failed",message:"A redirect named no address."};let m;try{m=new URL(d,a)}catch{return{kind:"failed",message:"A redirect named an address that is not a URL."}}if(!fS(m,e.origin))return{kind:"failed",message:"A redirect named an address that is not https."};a=m,i=!0}}async function wS(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 j9(e,t,r,n,s){if(!_S(t))return{ok:!1,message:"The key is not one a data host serves."};let o=P9(t);return wS(nd(hS,e.options?.env),async(a,i)=>{let c=await bS(e,t,r,"GET",!0,a);if(c.kind==="failed")return{ok:!1,message:c.message};let{response:u,redirected:l}=c;if(u.status!==200||!u.body)return await u.body?.cancel().catch(()=>{}),{ok:!1,message:vS(u.status,l)};let d=u.headers.get("content-length");if(o!==null&&d!==null&&Number(d)!==o)return await u.body.cancel().catch(()=>{}),{ok:!1,message:`The object is ${Ct(d,20)} bytes but its key says ${o}.`};i();let m,f=0,p=0;try{m=await A9(n,"w");let h=u.body.getReader();while(!0){let{done:y,value:v}=await h.read();if(y)break;if(i(),f+=v.byteLength,o!==null&&f>o)throw await h.cancel().catch(()=>{}),new yc(`More bytes arrived than the key's ${o}.`);if(await m.write(v),f-p>=N9)p=f,s(f)}if(await m.close(),m=void 0,o!==null&&f!==o)throw new yc(`The object ended after ${f} bytes; its key says ${o}.`);if(f!==p)s(f);return{ok:!0,bytes:f}}catch(h){if(await m?.close().catch(()=>{}),await O9(n,{force:!0}).catch(()=>{}),h instanceof yc)return{ok:!1,message:h.message};if(a.aborted)return{ok:!1,message:"The transfer stalled and timed out."};return{ok:!1,message:`The transfer failed (${sd(h)}).`}}})}class yc extends Error{constructor(e){super(e);this.name="SizeError"}}async function q9(e,t,r){if(!_S(t))return{state:"unknown",message:"The key is not one a data host serves."};return wS(nd(hS,e.options?.env),async(n)=>{let s=await bS(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:vS(o,!1)}})}class _c extends Error{constructor(e){super(e);this.name="ProtocolAbort"}}async function $S(e,t){let r=e.lines[Symbol.asyncIterator](),n=[],s=null,o=null,a=async()=>{let l=n.shift();if(l!==void 0)return l;let d=await r.next();return d.done?null:d.value},i=async(l)=>{await e.send(`GETCONFIG ${l}`);while(!0){let d=await r.next();if(d.done)throw new _c("git-annex closed the connection");let m=d.value;if(m==="VALUE"||m.startsWith("VALUE ")){let f=m.slice(5).trimStart();return f===""?void 0:f}if(m.startsWith("ERROR"))throw new _c(m);n.push(m)}},c=async()=>{let l=await i("host"),d=await i("dataset");return C9(l,d,t.options)},u=async(l,d)=>{if(!s||!o){await e.send(`TRANSFER-FAILURE RETRIEVE ${Ct(l)} The remote has not been prepared.`);return}let m=Promise.resolve(),f=await j9(s,l,o,d,(p)=>{m=m.then(()=>e.send(`PROGRESS ${p}`))});if(await m,f.ok)await e.send(`TRANSFER-SUCCESS RETRIEVE ${l}`);else await e.send(`TRANSFER-FAILURE RETRIEVE ${Ct(l)} ${Ct(f.message)}`)};await e.send("VERSION 1");while(!0){let l=await a();if(l===null)return 0;if(l.trim()==="")continue;let[d,...m]=mS(l,1),f=m[0]??"";try{switch(d){case"EXTENSIONS":await e.send("EXTENSIONS");break;case"INITREMOTE":{let p=await c();await e.send(p.ok?"INITREMOTE-SUCCESS":`INITREMOTE-FAILURE ${Ct(p.message)}`);break}case"PREPARE":{let p=await c();if(!p.ok){s=null,await e.send(`PREPARE-FAILURE ${Ct(p.message)}`);break}let h=t.loadApiKey();if(!h){s=null,await e.send("PREPARE-FAILURE No NEMAR API key is stored. Run 'nemar auth login' first.");break}s=p.settings,o=h,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[p,h,...y]=mS(f,2);if(p==="STORE")await e.send(`TRANSFER-FAILURE STORE ${Ct(h??"")} This remote is read-only for now.`);else if(p==="RETRIEVE"&&h&&y[0])await u(h,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 ${Ct(f)} The remote has not been prepared.`);break}let p=await q9(s,f,o);if(p.state==="present")await e.send(`CHECKPRESENT-SUCCESS ${f}`);else if(p.state==="absent")await e.send(`CHECKPRESENT-FAILURE ${f}`);else await e.send(`CHECKPRESENT-UNKNOWN ${Ct(f)} ${p.message}`);break}case"REMOVE":await e.send(`REMOVE-FAILURE ${Ct(f)} This remote is read-only for now.`);break;case"ERROR":return 1;case"VALUE":break;default:await e.send("UNSUPPORTED-REQUEST")}}catch(p){if(p instanceof _c)return 1;throw p}}}function mS(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*D9(){let e=new TextDecoder,t="";for await(let r of Bun.stdin.stream()){t+=e.decode(r,{stream:!0});let n=t.indexOf(`
39
39
  `);while(n>=0)yield t.slice(0,n).replace(/\r$/,""),t=t.slice(n+1),n=t.indexOf(`
40
40
  `)}if(t+=e.decode(),t!=="")yield t}var od=Bun.stdout.writer(),M9=await $S({lines:D9(),send:async(e)=>{od.write(`${e}
41
41
  `),await od.flush()}},{loadApiKey:()=>vn().apiKey||void 0});await od.end();process.exit(M9);
package/dist/index.js CHANGED
@@ -100,18 +100,18 @@ ${t}`,Pnt,Nnt,Int=(e,t,n)=>{let r=n===""?"":`with ${n.trim()}() `,o=Tnt.bind(nul
100
100
  `)}var Hj=!1;var{spawn:oSt}=globalThis.Bun;function Vf(e,t=[]){let n=e.replace(sSt,'("$1","<redacted>")');for(let r of t)if(r.length>=iSt)n=n.split(r).join("<redacted>");return n}function Q$(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 zbe(e,t){let n=e.getReader(),r=new TextDecoder,o="";while(!0){let{done:s,value:i}=await n.read();if(s)break;if(i.byteLength===0)continue;t(),o+=r.decode(i,{stream:!0})}return o+r.decode()}async function T(e,t={}){let n={...process.env,GIT_TERMINAL_PROMPT:"0",...t.env};for(let y of t.unsetEnv??[])delete n[y];let r=oSt({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??aSt)};if(l(),t.timeout)s=setTimeout(()=>{o=!0,c(),r.kill()},t.timeout);let d=ky()?[...Q$(n),...t.redact??[]]:[];if(ky()){let y=t.cwd?` (cwd=${t.cwd})`:"";lp(u.dim(Vf(`$ ${e.join(" ")}${y}`,d)))}let p=()=>{a=performance.now(),l()},f,m,h,g=r.exited.then((y)=>(c(),y));try{[f,m,h]=await Promise.all([zbe(r.stdout,p),zbe(r.stderr,p),g])}finally{if(c(),s)clearTimeout(s)}if(ky()){if(t.sensitiveOutput)lp(u.dim("[sensitive subprocess output suppressed]"));else{if(f.trim())lp(u.dim(Vf(f.trimEnd(),d)));if(m.trim())lp(u.yellow(Vf(m.trimEnd(),d)))}lp(u.dim(`(exit ${h})`))}if(o)return{stdout:f,stderr:m||`Command timed out after ${Math.round(t.timeout/1000)}s`,exitCode:h??1,timedOut:!0};return{stdout:f,stderr:m,exitCode:h,timedOut:!1}}var sSt,iSt=8,aSt=120000;var Wt=z(()=>{He();sSt=/\(\s*"((?:x-amz-)[^"]*|authorization|proxy-authorization)"\s*,\s*"[^"]*"\s*\)/gi});function lSt(){if(process.platform==="darwin")return"macos";if(process.platform==="win32")return"windows";return"linux"}function Vbe(e,t=lSt()){return e.installInstructions[t]}function uSt(e){let t=e.match(/(\d+\.\d+(?:\.\d+)?)/);return t?t[1]:void 0}function pSt(){let e=Number(process.env.TEST_PROBE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:dSt}async function Wbe(e){try{let{exitCode:t,stdout:n,timedOut:r}=await T(e.cmd,{timeout:pSt()});if(r)return{available:!1,timedOut:!0};if(t!==0)return{available:!1};return{available:!0,version:uSt(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 P_(){let e=Object.entries(Gbe);return Promise.all(e.map(async([t,n])=>{let{available:r,version:o,timedOut:s}=await Wbe(n);return{key:t,name:n.name,purpose:n.purpose,required:n.required,available:r,version:o,timedOut:s,installInstruction:Vbe(n)}}))}async function Kbe(){let t=(await P_()).filter((n)=>n.required&&!n.available);if(t.length===0)return[];console.warn(`
101
101
  Heads up: some tools NEMAR needs for uploading/validating aren't installed yet:`);for(let n of t)console.warn(` - ${n.name} (${n.purpose})`),console.warn(` Install: ${n.installInstruction}`);return console.warn("Run `nemar doctor` anytime to re-check. You can finish signup without them.\n"),t}async function Wf(e){let n=cSt[e].map((i)=>Gbe[i]).filter(Boolean),r=await Promise.all(n.map(async(i)=>{let a=await Wbe(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:Vbe(i.check)}));if(o.length===0)return;let s=[`
102
102
  Missing required tools:`];for(let i of o)s.push(` ${i.tool} not installed`),s.push(` Install: ${i.installInstruction}`);throw Error(s.join(`
103
- `))}var Gbe,cSt,dSt=4000;var N_=z(()=>{Wt();Gbe={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)"}}},cSt={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 Ybe;var Jbe=z(()=>{Ybe={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.39-dev.4765",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 Qs;var Kf=z(()=>{Jbe();Qs=Ybe.version});import{mkdirSync as mSt,readdirSync as hSt,unlinkSync as gSt,writeFileSync as ySt}from"fs";import{join as zj}from"path";function n0e(){Ry=!0}function eu(){return Ry}function r0e(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function F_(e){t0e=e,Ln(`Step: ${e}`)}function ts(){Qbe=!0}function o0e(){return Qbe}function ue(){if(e0e)return;Vj=!0}function up(){Vj=!1,e0e=!0}function s0e(){return Vj}function Ln(e){if(Ry)process.stderr.write(`[debug] ${e}
103
+ `))}var Gbe,cSt,dSt=4000;var N_=z(()=>{Wt();Gbe={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)"}}},cSt={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 Ybe;var Jbe=z(()=>{Ybe={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.40-PR2304.2ba3060",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 Qs;var Kf=z(()=>{Jbe();Qs=Ybe.version});import{mkdirSync as mSt,readdirSync as hSt,unlinkSync as gSt,writeFileSync as ySt}from"fs";import{join as zj}from"path";function n0e(){Ry=!0}function eu(){return Ry}function r0e(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function F_(e){t0e=e,Ln(`Step: ${e}`)}function ts(){Qbe=!0}function o0e(){return Qbe}function ue(){if(e0e)return;Vj=!0}function up(){Vj=!1,e0e=!0}function s0e(){return Vj}function Ln(e){if(Ry)process.stderr.write(`[debug] ${e}
104
104
  `)}function xSt(e){let t={};for(let[n,r]of Object.entries(e))t[n]=_St.has(n.toLowerCase())?"[REDACTED]":r;return t}function a0e(e){let t=e.indexOf("@");if(t<=0)return"***";return`${e[0]}***${e.slice(t)}`}function Gj(e,t,n=0){if(n>ESt)return"[REDACTED: depth]";if(Array.isArray(t))return t.map((r)=>Gj(e,r,n+1));if(t&&typeof t==="object"){let r={};for(let[o,s]of Object.entries(t))r[o]=Gj(o,s,n+1);return r}if(typeof t==="string"){if(vSt.test(e))return"[REDACTED]";return t.replace(i0e,a0e)}return t}function Wj(e){return e.replace(SSt,"Bearer [REDACTED]").replace(kSt,"[REDACTED_AWS_KEY]").replace(RSt,"$1[REDACTED]").replace($St,"$1$2=[REDACTED]").replace(i0e,a0e)}function DSt(e){return Wj(e)}function Xbe(e,t=wSt){if(e===void 0)return;let n=e;try{let r=JSON.parse(e);n=JSON.stringify(Gj("",r))}catch{}if(n=Wj(n),Buffer.byteLength(n,"utf8")>t)n=`${Buffer.from(n,"utf8").subarray(0,t).toString("utf8")}... [truncated]`;return n}function nD(e){if(!Ry)return;let t=DSt(e.url);try{let n={...e,url:t,requestHeaders:e.requestHeaders?xSt(e.requestHeaders):void 0,requestBody:Xbe(e.requestBody),responseBody:Xbe(e.responseBody)};tD.push(n),Ln(`${e.method} ${t} -> ${e.status??"ERROR"} (${e.durationMs}ms)`)}catch(n){let r=W(n);tD.push({method:e.method,url:t,status:e.status,durationMs:e.durationMs,note:`redaction failed: ${r}`}),Ln(`redaction failed for ${e.method} ${t}: ${r}`)}}async function CSt(){let e=[];try{let t=process.versions.bun?`Bun ${process.versions.bun}`:`Node ${process.version}`;e.push(`CLI version: ${Qs}`),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=Kt();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 P_();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 Kj(){return(await CSt()).join(`
105
105
  `)}async function c0e(){if(!Ry||eD!==void 0)return;try{eD=await Kj()}catch(e){let t=W(e);eD=`(could not build environment report: ${t})`,Ln(`environment snapshot failed: ${t}`)}}function l0e(e){if(Zbe.has(e))return{flag:e};for(let t of Zbe){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 ASt(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n],o=l0e(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 OSt(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n],o=l0e(r);if(!o){t.push(r);continue}if(!o.kind&&n+1<e.length)n++}return t}function TSt(e){let t=[];for(let r of OSt(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 PSt(e,t){let n=[];if(n.push("NEMAR CLI Debug Log"),n.push(`Generated: ${new Date().toISOString()}`),n.push(`Command: nemar ${Wj(ASt(e).join(" "))}`),n.push(""),n.push(eD??"(environment snapshot unavailable)"),n.push(""),n.push("HTTP requests:"),tD.length===0)n.push(" (none)");else tD.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: ${t0e??"(none recorded)"}`),n.push(`Exit code: ${t}`),`${n.join(`
106
106
  `)}
107
107
  `}function NSt(e,t){let n;try{n=hSt(e).filter((o)=>o.startsWith("nemar-")&&o.endsWith(".log"))}catch(o){if(o.code!=="ENOENT")Ln(`could not list ${e} for log rotation: ${W(o)}`);return}n.sort();let r=n.length-t;for(let o=0;o<r;o++)try{gSt(zj(e,n[o]))}catch(s){if(s.code!=="ENOENT")Ln(`could not remove old log ${n[o]}: ${W(s)}`)}}function u0e(){return I_}function d0e(e,t){if(!Ry)return null;let n=zj(lr(),"logs");try{mSt(n,{recursive:!0})}catch(i){return I_=W(i),Ln(`could not create log directory ${n}: ${I_}`),null}let o=`nemar-${new Date().toISOString().replace(/[:.]/g,"-")}-${TSt(e)}.log`,s=zj(n,o);try{ySt(s,PSt(e,t),"utf8")}catch(i){return I_=W(i),Ln(`could not write log file ${s}: ${I_}`),null}return NSt(n,bSt),s}var bSt=10,wSt=2048,Ry=!1,Qbe=!1,Vj=!1,e0e=!1,t0e,eD,tD,_St,vSt,i0e,ESt=32,SSt,kSt,RSt,$St,Zbe,I_;var wn=z(()=>{Ue();kr();N_();Kf();tD=[];_St=new Set(["authorization","cookie","set-cookie","x-api-key","x-approval-dispatch-token"]);vSt=/^(api[_-]?key|apikey|password|token|secret|access[_-]?key(_id)?|secret[_-]?access[_-]?key|session|session[_-]?token|authorization|ssh[_-]?key|private[_-]?key|device[_-]?code|dispatch[_-]?token|client[_-]?secret)$/i,i0e=/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;SSt=/Bearer\s+[A-Za-z0-9\-._~+/=]+/gi,kSt=/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,RSt=/((?:aws_)?secret_access_key["']?\s*[:=]\s*["']?)[A-Za-z0-9/+=]{20,}/gi,$St=/([?&])(X-Amz-Signature|X-Amz-Security-Token|X-Amz-Credential|Signature|AWSAccessKeyId)=[^&\s"']+/gi;Zbe=new Set(["-k","--key","--password","--api-key"])});import{chmodSync as ISt,copyFileSync as FSt,existsSync as Jj,mkdirSync as MSt,statSync as jSt}from"fs";import{homedir as rD}from"os";import{join as $y}from"path";function USt(e){let t=e.trim().replace(/\/+$/,"");try{let n=new URL(t);return n.protocol=n.protocol.toLowerCase(),n.host=n.host.toLowerCase(),n.toString().replace(/\/+$/,"")}catch{return console.error(`[nemar] could not parse stored apiUrl ${JSON.stringify(e)}; leaving as-is`),t}}function lr(){return process.env.NEMAR_CONFIG_DIR||$y(rD(),".config","nemar")}function BSt(e){if(process.env.NEMAR_CONFIG_DIR)return;let t=$y(e,"config.json");if(Jj(t))return;let n=[];if(process.platform==="darwin")n.push($y(rD(),"Library","Preferences","nemar-nodejs","config.json"));if(process.platform==="win32"){let r=process.env.APPDATA||$y(rD(),"AppData","Roaming");n.push($y(r,"nemar-nodejs","config.json"))}n.push($y(rD(),".config","nemar-nodejs","config.json"));for(let r of n)if(Jj(r))try{MSt(e,{recursive:!0}),FSt(r,t),console.error(`[nemar] Config migrated from ${r} to ${t}
108
108
  [nemar] You can safely remove the old file.`);return}catch(o){console.error(`[nemar] Failed to migrate config from ${r}:`,o,`
109
- [nemar] You can manually copy ${r} to ${t}`)}}function Ni(){let e=lr();if(M_&&p0e===e)return M_;if(BSt(e),M_=new Z$({projectName:"nemar",configFileMode:Yj,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}),p0e=e,!f0e.has(e))f0e.add(e),HSt(M_.path),GSt(),VSt();return M_}function HSt(e){if(process.platform==="win32")return;if(!Jj(e))return;try{if((jSt(e).mode&511)!==Yj)ISt(e,Yj)}catch(t){console.error(`[nemar] could not secure config file permissions for ${e}:`,t)}}function GSt(){let e=Ni(),t=e.get("accounts");if(t&&Object.keys(t).length>0)return;let n=e.get("apiKey"),r=e.get("username");if(!n&&!r)return;try{let o=r||"default",s={};for(let i of zSt){let a=e.get(i);if(a!==void 0)s[i]=a}e.store={activeAccount:o,accounts:{[o]:s}}}catch(o){console.error("Config migration failed (legacy config preserved):",o)}}function VSt(){let e=Ni(),t=e.store,n=t.accounts,r=!1;if(n)for(let[s,i]of Object.entries(n)){let a=i?.apiUrl;if(!a)continue;if(LSt.has(USt(a)))n[s]={...i,apiUrl:Dy},console.error(`[nemar] migrated stored apiUrl for account "${s}": ${a} -> ${Dy}`),r=!0}let o=t.apiUrl;if(n&&Object.keys(n).length>0&&o!==void 0){let{apiUrl:s,...i}=t;try{e.store=i,console.error(`[nemar] removed stale top-level apiUrl from config (was: ${o})`),r=!1}catch(a){console.error("API URL cleanup failed (config file unchanged):",a)}}if(r)try{e.store={...e.store,accounts:n}}catch(s){console.error("API URL migration failed (config file unchanged):",s)}}function j_(){return Ni().get("activeAccount")}function dp(){return Ni().get("accounts")||{}}function Kt(){let e={apiUrl:Dy},t=j_();if(!t)return e;return dp()[t]||e}function Vn(e,t){let n=Ni(),r=n.get("activeAccount")||"default",o=n.get("accounts")||{};if(!o[r])o[r]={apiUrl:Dy};o[r][e]=t,n.store={...n.store,accounts:o,activeAccount:r}}function L_(e){let t=j_();if(!t)return;let n=dp();if(n[t])delete n[t][e],Ni().set("accounts",n)}function m0e(){let e=Ni(),t=j_();if(!t){e.clear();return}let n=dp();delete n[t];let r=Object.keys(n);if(r.length>0)e.store={...e.store,accounts:n,activeAccount:r[0]};else e.clear()}function h0e(){Ni().clear()}function tt(){return!!Kt().apiKey}function Xj(){return Ni().path}function U_(){let e=dp(),t=j_();return Object.entries(e).map(([n,r])=>({key:n,username:r.username,email:r.email,githubUsername:r.githubUsername,active:n===t,keySource:r.keySource}))}function g0e(e){return e.username?.trim()||e.email}function WSt(e){let t=e.trim().toLowerCase();if(!t)return;let n=Object.entries(dp()).filter(([,r])=>r.email&&r.email.toLowerCase()===t).map(([r])=>r);if(n.length>1){Ln(`findAccountKeyByEmail: ${n.length} accounts share email ${t}: ${n.join(", ")}`);return}return n[0]}function y0e(e,t){let n=Ni(),r=dp(),o;if(r[e])o=e;else if(t.email)o=WSt(t.email);let s=o?r[o]:void 0,i={...s??{apiUrl:Dy},...t};if(o&&o!==e)delete r[o];return r[e]=i,n.store={...n.store,accounts:r,activeAccount:e},{key:e,previous:s}}function b0e(e){let t=e.trim();if(!t)return"unchanged";let n=Ni(),r=j_();if(!r||r===t)return"unchanged";let o=dp(),s=o[r];if(!s)return"unchanged";if(o[t])return"key_taken";return delete o[r],o[t]={...s,username:t},n.store={...n.store,accounts:o,activeAccount:t},"renamed"}function Zj(e){let t=Ni(),n=dp();if(n[e])return t.store={...t.store,activeAccount:e},n[e];for(let[r,o]of Object.entries(n))if(o.githubUsername===e)return t.store={...t.store,activeAccount:r},o;return null}var Dy="https://nemar-api-dev.sccn-org.workers.dev",Yj=384,LSt,qSt,rdn,M_=null,p0e=null,f0e,zSt;var kr=z(()=>{Bbe();mn();pg();wn();LSt=new Set(["https://api.osc.earth/nemar","https://nemar-api.neuromechanist.workers.dev","https://nemar-api-dev.shirazi-10f.workers.dev"]);qSt=O({field:b(),blocks:Y(b()).optional(),set_on:Y(b()).optional()}).passthrough(),rdn=O({apiKey:b().optional(),apiUrl:b().url().default(Dy),username:b().optional(),email:b().email().optional(),githubUsername:b().optional(),sandboxCompleted:Q().optional(),sandboxDatasetId:b().optional(),dismissedNoticeIds:Y(D()).optional(),serviceAccess:Q().optional(),profileGaps:Y(qSt).optional(),orcidVerified:Q().optional(),role:b().optional(),accountKind:kf.optional(),pendingEmailChange:b().email().optional()});f0e=new Set;zSt=["apiKey","apiUrl","username","email","githubUsername","sandboxCompleted","sandboxDatasetId","dismissedNoticeIds"]});function oD(e){if(w0e)return;w0e=!0;let t=u.yellow("\u2500".repeat(60)),n=u.yellow.bold("[MAINTENANCE]"),r=u.dim(`mode: ${e.mode}`),o=e.eta?`
109
+ [nemar] You can manually copy ${r} to ${t}`)}}function Ni(){let e=lr();if(M_&&p0e===e)return M_;if(BSt(e),M_=new Z$({projectName:"nemar",configFileMode:Yj,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}),p0e=e,!f0e.has(e))f0e.add(e),HSt(M_.path),GSt(),VSt();return M_}function HSt(e){if(process.platform==="win32")return;if(!Jj(e))return;try{if((jSt(e).mode&511)!==Yj)ISt(e,Yj)}catch(t){console.error(`[nemar] could not secure config file permissions for ${e}:`,t)}}function GSt(){let e=Ni(),t=e.get("accounts");if(t&&Object.keys(t).length>0)return;let n=e.get("apiKey"),r=e.get("username");if(!n&&!r)return;try{let o=r||"default",s={};for(let i of zSt){let a=e.get(i);if(a!==void 0)s[i]=a}e.store={activeAccount:o,accounts:{[o]:s}}}catch(o){console.error("Config migration failed (legacy config preserved):",o)}}function VSt(){let e=Ni(),t=e.store,n=t.accounts,r=!1;if(n)for(let[s,i]of Object.entries(n)){let a=i?.apiUrl;if(!a)continue;if(LSt.has(USt(a)))n[s]={...i,apiUrl:Dy},console.error(`[nemar] migrated stored apiUrl for account "${s}": ${a} -> ${Dy}`),r=!0}let o=t.apiUrl;if(n&&Object.keys(n).length>0&&o!==void 0){let{apiUrl:s,...i}=t;try{e.store=i,console.error(`[nemar] removed stale top-level apiUrl from config (was: ${o})`),r=!1}catch(a){console.error("API URL cleanup failed (config file unchanged):",a)}}if(r)try{e.store={...e.store,accounts:n}}catch(s){console.error("API URL migration failed (config file unchanged):",s)}}function j_(){return Ni().get("activeAccount")}function dp(){return Ni().get("accounts")||{}}function Kt(){let e={apiUrl:Dy},t=j_();if(!t)return e;return dp()[t]||e}function Vn(e,t){let n=Ni(),r=n.get("activeAccount")||"default",o=n.get("accounts")||{};if(!o[r])o[r]={apiUrl:Dy};o[r][e]=t,n.store={...n.store,accounts:o,activeAccount:r}}function L_(e){let t=j_();if(!t)return;let n=dp();if(n[t])delete n[t][e],Ni().set("accounts",n)}function m0e(){let e=Ni(),t=j_();if(!t){e.clear();return}let n=dp();delete n[t];let r=Object.keys(n);if(r.length>0)e.store={...e.store,accounts:n,activeAccount:r[0]};else e.clear()}function h0e(){Ni().clear()}function tt(){return!!Kt().apiKey}function Xj(){return Ni().path}function U_(){let e=dp(),t=j_();return Object.entries(e).map(([n,r])=>({key:n,username:r.username,email:r.email,githubUsername:r.githubUsername,active:n===t,keySource:r.keySource}))}function g0e(e){return e.username?.trim()||e.email}function WSt(e){let t=e.trim().toLowerCase();if(!t)return;let n=Object.entries(dp()).filter(([,r])=>r.email&&r.email.toLowerCase()===t).map(([r])=>r);if(n.length>1){Ln(`findAccountKeyByEmail: ${n.length} accounts share email ${t}: ${n.join(", ")}`);return}return n[0]}function y0e(e,t){let n=Ni(),r=dp(),o;if(r[e])o=e;else if(t.email)o=WSt(t.email);let s=o?r[o]:void 0,i={...s??{apiUrl:Dy},...t};if(o&&o!==e)delete r[o];return r[e]=i,n.store={...n.store,accounts:r,activeAccount:e},{key:e,previous:s}}function b0e(e){let t=e.trim();if(!t)return"unchanged";let n=Ni(),r=j_();if(!r||r===t)return"unchanged";let o=dp(),s=o[r];if(!s)return"unchanged";if(o[t])return"key_taken";return delete o[r],o[t]={...s,username:t},n.store={...n.store,accounts:o,activeAccount:t},"renamed"}function Zj(e){let t=Ni(),n=dp();if(n[e])return t.store={...t.store,activeAccount:e},n[e];for(let[r,o]of Object.entries(n))if(o.githubUsername===e)return t.store={...t.store,activeAccount:r},o;return null}var Dy="https://api.nemar.org",Yj=384,LSt,qSt,rdn,M_=null,p0e=null,f0e,zSt;var kr=z(()=>{Bbe();mn();pg();wn();LSt=new Set(["https://api.osc.earth/nemar","https://nemar-api.neuromechanist.workers.dev","https://nemar-api-dev.shirazi-10f.workers.dev"]);qSt=O({field:b(),blocks:Y(b()).optional(),set_on:Y(b()).optional()}).passthrough(),rdn=O({apiKey:b().optional(),apiUrl:b().url().default(Dy),username:b().optional(),email:b().email().optional(),githubUsername:b().optional(),sandboxCompleted:Q().optional(),sandboxDatasetId:b().optional(),dismissedNoticeIds:Y(D()).optional(),serviceAccess:Q().optional(),profileGaps:Y(qSt).optional(),orcidVerified:Q().optional(),role:b().optional(),accountKind:kf.optional(),pendingEmailChange:b().email().optional()});f0e=new Set;zSt=["apiKey","apiUrl","username","email","githubUsername","sandboxCompleted","sandboxDatasetId","dismissedNoticeIds"]});function oD(e){if(w0e)return;w0e=!0;let t=u.yellow("\u2500".repeat(60)),n=u.yellow.bold("[MAINTENANCE]"),r=u.dim(`mode: ${e.mode}`),o=e.eta?`
110
110
  ${u.dim(`eta: ${e.eta}`)}`:"";process.stderr.write(`${t}
111
111
  ${n} ${e.message}
112
112
  ${r}${o}
113
113
  ${t}
114
- `)}var w0e=!1;var Qj=z(()=>{He()});function Xr(){if(process.env.TEST_API_URL)return process.env.TEST_API_URL;if(Jf)return e6;return Kt().apiUrl||e6}async function F(e,t={},n=!1,r,o="json",s){let i=`${Xr()}${e}`,a={"Content-Type":"application/json","X-CLI-Version":Qs,...t.headers};if(n){let h=Kt();if(!h.apiKey&&n===!0)throw new j(401,"Not authenticated. Run 'nemar auth login' first.");if(h.apiKey)a.Authorization=`Bearer ${h.apiKey}`}let c=t.method||"GET",l=typeof t.body==="string"?t.body:void 0,d=Date.now(),p;try{let h=[...t.signal?[t.signal]:[],...s===void 0?[]:[AbortSignal.timeout(s)]];p=await fetch(i,{...t,headers:a,...h.length===0?{}:{signal:h.length===1?h[0]:AbortSignal.any(h)}})}catch(h){if(eu())nD({method:c,url:i,status:null,durationMs:Date.now()-d,requestHeaders:a,requestBody:l,error:h instanceof Error?h.message:String(h)});throw new j(0,`Network error: Could not connect to ${Xr()}`,{originalError:h instanceof Error?h.message:String(h)})}let f;try{f=await p.text()}catch(h){if(eu())nD({method:c,url:i,status:p.status,durationMs:Date.now()-d,requestHeaders:a,requestBody:l,error:h instanceof Error?h.message:String(h)});throw new j(0,"Failed to read response body",{httpStatus:p.status,originalError:h instanceof Error?h.message:String(h)})}if(eu())nD({method:c,url:i,status:p.status,durationMs:Date.now()-d,requestHeaders:a,requestBody:l,responseBody:f});if(o==="text"&&p.ok)return{text:f,headers:p.headers};let m;try{m=JSON.parse(f)}catch{throw new j(p.status,`Invalid response from server (status ${p.status})`)}if(!p.ok){if(p.status===503&&(m.mode==="read-only"||m.mode==="full")){let G=typeof m.message==="string"?m.message:"NEMAR is in maintenance mode. Please retry shortly.",B=typeof m.eta==="string"?m.eta:null,M=new cc(m.mode,G,B,m.details);throw oD(M),M}let h=typeof m.block_reason==="string",g=Array.isArray(m.missing)?m.missing.filter((G)=>typeof G==="string"):void 0,y=typeof m.error==="string"&&(jre.includes(m.error)||noe.includes(m.error)),w=typeof m.error==="string"&&(wk.options.includes(m.error)||aoe.includes(m.error)),x=typeof m.error==="string"&&Tre.includes(m.error),v=typeof m.error==="string"&&Lre.includes(m.error),S=typeof m.error==="string"&&Zre.includes(m.error),E=typeof m.error==="string"&&Xre.includes(m.error),C=typeof m.error==="string"&&Qre.includes(m.error),I=typeof m.error==="string"&&boe.includes(m.error),P=h||I||E||C||y||w||x||v||S||g!==void 0&&typeof m.error==="string"&&Mre.includes(m.error)||g!==void 0&&typeof m.error==="string"&&xse.includes(m.error)?m.message||m.error:m.error||m.message;if(p.status===404&&m.error==="Not Found"&&typeof m.message==="string")P=`${m.message}. This NEMAR backend does not support this command yet.`;let U=new j(p.status,P||"Request failed",m.details,typeof m.step==="string"?m.step:void 0,h?m.block_reason:void 0,g);if(typeof m.error==="string")U.code=m.error;if(typeof m.reason==="string")U.reason=m.reason;U.rawBody=m;let q=Number(p.headers.get("retry-after"));if(p.headers.get("retry-after")!==null&&Number.isFinite(q)&&q>=0)U.retryAfterSeconds=q;throw U}if(r){let h=r.safeParse(m);if(!h.success)throw new j(p.status,`Response for ${e} did not match the expected NEMAR contract`,{issues:h.error.issues});return h.data}return m}var e6="https://nemar-api-dev.sccn-org.workers.dev",Jf;var yr=z(()=>{Tw();Tf();vk();FI();Fw();mg();pg();kr();wn();Qj();Kf();Ue();Jf=e6.includes("workers.dev")});async function Cy(e,t={}){return F(`/datasets/${e}/publish/request`,t.anonymous?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({anonymous:!0})}:{method:"POST"},!0)}async function Ay(e){return F(`/datasets/${e}/publish/status`,{},!0)}async function v0e(e){return F(`/datasets/${e}/publish/resend`,{method:"POST"},!0)}async function E0e(e){return F(`/datasets/${e}/publish/withdraw`,{method:"POST"},!0)}async function Yf(e={}){let{statuses:t,search:n}=typeof e==="string"?{statuses:e?[e]:[]}:e,r=await _0e(t,n),o=r;if(t!==void 0&&t.length>1&&r.requests.length===0){let s=[];for(let a of new Set(t))s.push(await _0e([a],n));let i=s.flatMap((a)=>a.requests).sort(S0e);o={...r,requests:i,count:i.length}}return n?KSt(o,n):o}function S0e(e,t){return e.requested_at<t.requested_at?1:e.requested_at>t.requested_at?-1:0}async function _0e(e,t){let n=new URLSearchParams;if(e&&e.length>0)n.set("status",e.join(","));if(t)n.set("search",t);let r=n.size>0?`?${n}`:"";return F(`/admin/publish/requests${r}`,{},!0)}function KSt(e,t){let n=e.requests.filter((s)=>aie(t,[s.dataset_id,s.requested_by_username,s.dataset_name])),r=(s)=>cie(s.dataset_id,t)?0:1,o=[...n].sort((s,i)=>r(s)-r(i)||S0e(s,i));return{...e,requests:o,count:o.length}}async function Oy(e,t,n){return F(`/admin/publish/${e}/deny`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:t,...n!==void 0?{request_id:n}:{}})},!0)}async function sD(e){return F(`/admin/publish/${e}/identifier-screen`,{method:"POST"},!0)}async function iD(e){return F(`/admin/publish/${e}/review`,{},!0)}async function k0e(e){return F(`/admin/publish/${e}/review/start`,{method:"POST"},!0)}async function R0e(e,t){let n={message:t};return F(`/admin/publish/${e}/comment`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},!0)}function Ty(e){if(!(e instanceof j))return;let t=e.rawBody;if(typeof t!=="object"||t===null||Array.isArray(t))return;let n=t.code;return typeof n==="string"?n:void 0}function JSt(e,t=[]){if(e){let n=lc.indexOf(e);if(n>=0)return n+1}return Math.min(t.length+1,lc.length)}function YSt(e){if(!(e instanceof j))return!1;if(e.statusCode===0)return!0;if(e.statusCode===429)return!0;if(e.statusCode>=500&&e.statusCode<600)return!0;if(e.statusCode===403&&/repository has been locked/i.test(e.message))return!0;return!1}function XSt(){let e=process.env.NEMAR_APPROVE_RETRY_DELAY_MS;if(e===void 0||!/^\d+$/.test(e))return Xk;let t=Number(e);return Number.isSafeInteger(t)&&t<=Xk?t:Xk}async function Py(e,t=!1,n=!1,r=!1,o,s,i,a,c){let d=XSt(),p,f,m=0,h=!1,g,y=t,w=[],x;function v(S,E,C,I){if(!s)return;s({step:S,stepIndex:JSt(S,E),stepTotal:lc.length,s3LockLocked:C,s3LockTotal:I,s3LockResumed:S==="s3_lock"&&h?!0:void 0})}for(let S=1;S<=5;S++)try{let E,C=!0;do{if(E=await F(`/admin/publish/${e}/approve`,{method:"POST",headers:{"Content-Type":"application/json",...c?.dispatchToken?{[eoe]:c.dispatchToken}:{}},body:JSON.stringify({resume:C?y:!0,sandbox:n,s3_lock_continuation_token:p,s3_lock_total:f,skip_ci_check:r,...i!==void 0?{acknowledge_identifier_screen:i}:{},...a!==void 0?{[oie]:a}:{},...c?.requestId!==void 0?{request_id:c.requestId}:{}})},!0),C=!1,E.step_results)w.push(...E.step_results);if(E.s3_lock_total!==void 0)f=E.s3_lock_total;if(E.s3_lock_batch_count!==void 0)m+=E.s3_lock_batch_count;let I=E.step??E.step_results?.[E.step_results.length-1]?.step;if(I&&(I!==g||I==="s3_lock"))v(I,E.steps_completed??[],I==="s3_lock"?m:void 0,I==="s3_lock"?f:void 0),g=I;if(E.hasMore&&E.s3_lock_continuation_token!==void 0)p=E.s3_lock_continuation_token;else break}while(E.hasMore);if(w.length>0)E.step_results=x0e(w);return E}catch(E){if(x=E,S===5||!YSt(E)){if(E instanceof j&&w.length>0)E.stepResults=x0e(w);throw E}let I=E;if(o?.({attempt:S,maxAttempts:5,delayMs:d,step:I.step,error:I.message}),await new Promise((H)=>setTimeout(H,d)),y=!0,p!==void 0)h=!0}throw x}function x0e(e){let t=new Map;for(let n of e)t.set(n.step,n);return Array.from(t.values())}var ya=z(()=>{Yk();mg();Qk();yr();Ue()});function lD(e){if(e.service_access===void 0||e.service_access===null)return"unknown";return e.service_access?"upload":"browse"}async function u6(e,t,n,r,o={}){let s=new URLSearchParams;if(e)s.set("status",e);if(t)s.set("role",t);if(n)s.set("awaiting_approval","1");if(r)s.set("kind",r);if(o.search!==void 0)s.set("q",o.search);if(o.includeDeleted)s.set("include_deleted","true");let i=s.toString()?`?${s.toString()}`:"";return F(`/admin/users${i}`,{},!0,Ire)}async function uD(e,t=!1){return F(`/admin/users/by-id/${e}${t?"?include_deleted=true":""}`,{},!0,Bre)}async function F0e(e,t){return F(`/admin/users/by-id/${e}`,{method:"PATCH",body:JSON.stringify(t)},!0,Hre)}async function M0e(e){return F(`/admin/approve/${e}`,{method:"POST"},!0)}async function j0e(e){return F(`/admin/approve/by-id/${e}`,{method:"POST"},!0)}async function L0e(e){return F(`/admin/revoke/${e}`,{method:"POST"},!0)}async function U0e(e){return F(`/admin/revoke/by-id/${e}`,{method:"POST"},!0)}async function q0e(e){return F(`/admin/users/by-id/${e}/verify`,{method:"POST"},!0)}async function B0e(e,t){return F(`/admin/users/${e}/role`,{method:"POST",body:JSON.stringify({role:t})},!0)}async function H0e(e,t){return F(`/admin/users/${e}/kind`,{method:"POST",body:JSON.stringify({kind:t})},!0)}async function dD(e){return F(`/admin/users/${encodeURIComponent(e)}`,{},!0)}async function z0e(e,t){return F(`/admin/users/${e}/keys`,{method:"POST",body:JSON.stringify({name:t})},!0,xk)}async function G0e(e){return F(`/admin/users/${e}/keys`,{},!0,_k)}async function V0e(e,t){return F(`/admin/users/${e}/keys/${t}`,{method:"DELETE"},!0)}async function W0e(e){return F(`/datasets/${e}/publish`,{method:"POST"},!0)}async function K0e(e){return F(`/admin/datasets/${e}/ci`,{},!0)}async function tu(e){return F(`/admin/datasets/${e}/ci`,{method:"POST"},!0)}async function d6(e){return F(`/admin/datasets/${e}/ci/validate`,{method:"POST"},!0)}async function p6(e){return F(`/admin/datasets/${e}/ci/sync`,{method:"POST"},!0)}async function J0e(e,t){return F(`/admin/datasets/${e}/doi/concept`,{method:"POST",body:JSON.stringify(t)},!0)}async function H_(e){return F(`/admin/datasets/${e}/doi`,{},!0)}async function f6(e,t){return F(`/admin/datasets/${e}/doi/update`,{method:"POST",body:JSON.stringify(t)},!0)}async function Y0e(e,t){return F(`/admin/datasets/${e}/withdraw`,{method:"POST",body:JSON.stringify({reason:t.reason,dry_run:t.dryRun})},!0)}async function X0e(e,t){return F(`/admin/datasets/${e}/restore`,{method:"POST",body:JSON.stringify({dry_run:t.dryRun})},!0)}async function Z0e(e,t){return F(`/admin/datasets/${e}/unpublish`,{method:"POST",body:JSON.stringify({reason:t.reason,dry_run:t.dryRun})},!0)}async function Q0e(e){return F(`/admin/datasets/${e}/reset`,{method:"POST"},!0)}async function ewe(e,t=!1){return F(`/admin/datasets/${e}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({force:t})},!0)}async function twe(e){return F("/admin/datasets/bulk-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dataset_ids:e})},!0)}async function nwe(e){return F("/admin/datasets/import",{method:"POST",body:JSON.stringify(e)},!0)}async function rwe(e){return F("/admin/datasets/exemplar",{method:"POST",body:JSON.stringify(e)},!0)}async function owe(e){return F(`/admin/datasets/${e}/exemplar/remint-dois`,{method:"POST"},!0)}async function m6(e,t){let n=new URLSearchParams;if(e)n.set("status",e);if(t!==void 0)n.set("blocklisted",t?"1":"0");let r=n.toString();return F(`/admin/imports${r?`?${r}`:""}`,{},!0)}async function swe(e){return F(`/admin/imports/${e}/rollback`,{method:"POST"},!0)}async function iwe(e){return F(`/admin/imports/${e}/retry`,{method:"POST"},!0)}async function h6(e){return F(`/admin/imports/${e}/verify`,{method:"POST"},!0)}async function awe(e){return F("/admin/imports/dispatch-cooldown",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dataset_ids:e})},!0)}async function Iy(e,t){return F(`/admin/datasets/${e}/reindex`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})},!0)}async function cwe(e,t){return F("/admin/datasets/reindex/bulk",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filter:e,...t??{}})},!0)}async function lwe(e){let t=e?.limit??15;return F(`/admin/datasets/hed-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function uwe(){return F("/admin/datasets/hed-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function dwe(e){let t=e?.limit??50;return F(`/admin/datasets/recording-stats-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function pwe(){return F("/admin/datasets/recording-stats-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function fwe(e){let t=e?.limit??15;return F(`/admin/datasets/signal-defaults-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function mwe(){return F("/admin/datasets/signal-defaults-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function hwe(e){let t=e?.limit??15,n=new URLSearchParams({limit:String(t)});if(e?.olderThan!=null)n.set("older-than",String(e.olderThan));if(e?.before!=null)n.set("before",e.before);return F(`/admin/datasets/data-integrity-sweep?${n.toString()}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function gwe(){return F("/admin/datasets/data-integrity-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function ywe(e,t){let n=t?.write?"":"?dry_run=1";return F(`/admin/datasets/${e}/availability-report${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function bwe(e){let t=e?.limit??30,n=new URLSearchParams({limit:String(t)});if(e?.missingOnly)n.set("missing-only","1");return F(`/admin/datasets/availability-report-sweep?${n.toString()}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function wwe(){return F("/admin/datasets/availability-report-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function _we(e){let t=new URLSearchParams;if(e?.prefix)t.set("prefix",e.prefix);if(e?.visibility)t.set("visibility",e.visibility);if(e?.limit)t.set("limit",String(e.limit));let n=t.toString()?`?${t.toString()}`:"";return F(`/admin/fleet/drift${n}`,{},!0)}async function Fy(e,t){return F(`/admin/datasets/${e}/enforce`,{method:"POST",body:JSON.stringify({dry_run:t})},!0)}async function xwe(e){return F("/admin/datasets/enforce/bulk",{method:"POST",body:JSON.stringify({prefix:e.prefix,visibility:e.visibility,limit:e.limit,dry_run:e.dryRun})},!0)}async function vwe(e,t){return F(`/admin/datasets/${e}/review-ruleset`,{method:"POST",body:JSON.stringify({dry_run:t.dryRun,remove:t.remove})},!0)}async function Ewe(e){return F("/admin/datasets/review-ruleset/bulk",{method:"POST",body:JSON.stringify({prefix:e.prefix,after:e.after,limit:e.limit,dry_run:e.dryRun,remove:e.remove})},!0)}async function Swe(e,t=!1){return F(`/admin/datasets/${e}/revalidate${t?"?force=true":""}`,{method:"POST"},!0)}async function kwe(e){let t=e?`?user=${encodeURIComponent(e)}`:"";return F(`/admin/email-preferences${t}`,{},!0)}async function Rwe(e,t){let n=t?`?user=${encodeURIComponent(t)}`:"";return F(`/admin/email-preferences${n}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)},!0)}async function g6(e){return F("/admin/notify",{method:"POST",body:JSON.stringify(e)},!0)}async function $we(e){return F(`/admin/notify/${e}`,{},!0)}async function Dwe(){return F("/admin/summary/coverage",{},!0)}async function Cwe(e,t,n){return F("/admin/manifest/dispatch",{method:"POST",body:JSON.stringify({dataset_id:e,version:t,skip_canary:n?.skipCanary??!1})},!0)}async function y6(e){return F("/admin/doctor/scan",{method:"POST",body:JSON.stringify({...e?.check&&{check:e.check},...e?.datasetId&&{dataset_id:e.datasetId}})},!0)}async function b6(e){return F("/admin/doctor/fix",{method:"POST",body:JSON.stringify({check:e.check,...e.datasetId&&{dataset_id:e.datasetId},...e.dryRun&&{dry_run:!0}})},!0)}async function Awe(){return F("/admin/zarr-catalog/publish",{method:"POST"},!0)}async function Owe(e){return F("/admin/neurobagel/regenerate",{method:"POST",body:JSON.stringify(e)},!0)}async function Twe(){return F("/admin/neurobagel/status",{method:"GET"},!0)}async function Pwe(){return F("/admin/neurobagel/verify",{method:"POST",body:"{}"},!0)}async function Nwe(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));let n=t.toString()?`?${t.toString()}`:"";return F(`/admin/datasets/zarr-fidelity-sweep${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Iwe(e){let t=new URLSearchParams;if(e?.execute)t.set("execute","1");if(e?.limit!=null)t.set("limit",String(e.limit));if(e?.after)t.set("after",e.after);let n=t.toString()?`?${t.toString()}`:"";try{return await F(`/admin/datasets/upstream-backfill${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}catch(r){let o=r instanceof j&&r.statusCode===502?r.rawBody:void 0;if(o&&typeof o==="object"&&"execute"in o&&"counts"in o)return{...o,ok:!1};throw r}}async function Fwe(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));if(e?.after)t.set("after",e.after);if(e?.dataset)t.set("dataset",e.dataset);let n=t.toString()?`?${t.toString()}`:"";try{return await F(`/admin/upstream-status${n}`,{method:"GET"},!0)}catch(r){let o=r instanceof j&&r.statusCode===502?r.rawBody:void 0;if(o&&typeof o==="object"&&"rows"in o&&"counts"in o)return{...o,ok:!1};throw r}}async function Mwe(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));if(e?.apply)t.set("apply","1");let n=t.toString()?`?${t.toString()}`:"";return F(`/admin/imports/issue-triage${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function jwe(e){let t=e?.apply?"?apply=1":"";return F(`/admin/imports/coverage-sweep${t}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Lwe(e){let t=e?.apply?"?apply=1":"";return F(`/admin/imports/weekly-summary${t}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Uwe(e){return F("/admin/users/backfill-names",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apply:e?.apply??!1,...e?.limit!=null?{limit:e.limit}:{}})},!0)}async function qwe(e){return F("/admin/users/backfill-usernames",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apply:e?.apply??!1,...e?.limit!=null?{limit:e.limit}:{}})},!0)}async function Bwe(){return F("/admin/users/duplicates",{},!0,roe)}async function Hwe(e){return F(`/admin/users/${e}/clear-identity-conflict`,{method:"POST"},!0,ooe)}async function zwe(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));let n=t.toString()?`?${t.toString()}`:"";return F(`/admin/datasets/anonymity-sweep${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Gwe(){return F("/admin/datasets/anonymity-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function z_(e){let t=new URLSearchParams;if(e.verdicts&&e.verdicts.length>0)t.set("verdict",e.verdicts.join(","));if(e.dataset)t.set("dataset",e.dataset);if(e.author)t.set("author",e.author);if(e.needsMe)t.set("needs_me","1");let n=t.toString()?`?${t.toString()}`:"";return F(`/admin/pr-reviews${n}`,{method:"GET"},!0)}async function My(e,t,n){let r=n?`?head=${encodeURIComponent(n)}`:"";return F(`/admin/pr-reviews/${encodeURIComponent(e)}/${t}${r}`,{method:"GET"},!0)}async function w6(e,t,n={}){let r=n.redo?"?redo=1":"";return F(`/admin/pr-reviews/${encodeURIComponent(e)}/${t}/start${r}`,{method:"POST"},!0)}async function Vwe(e){return F(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"GET"},!0)}async function Wwe(e,t,n){return F(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(n?{mode:t,reason:n}:{mode:t})},!0)}async function Kwe(e){return F(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"DELETE"},!0)}async function Jwe(e,t,n,r){return F(`/admin/pr-reviews/${encodeURIComponent(e)}/${t}/allow`,{method:"POST",body:JSON.stringify({reason:n,...r?{head_sha:r}:{}})},!0)}async function x6(e){let t=new URLSearchParams;for(let[r,o]of Object.entries(e))if(o!==void 0&&o!=="")t.set(r,String(o));let n=t.toString();return F(`/admin/mail/tickets${n?`?${n}`:""}`,{},!0)}async function v6(e){return F(`/admin/mail/tickets/${e}`,{},!0)}async function Ywe(e,t,n){let r={text:t};return F(`/admin/mail/tickets/${e}/reply`,mp(r,{"Idempotency-Key":n}),!0)}async function Xwe(e,t,n){let r={text:t};return F(`/admin/mail/tickets/${e}/note`,mp(r,{"Idempotency-Key":n}),!0)}async function Zwe(e,t){let n={user_id:t};return F(`/admin/mail/tickets/${e}/assign`,mp(n),!0)}async function Qwe(e,t){return F(`/admin/mail/tickets/${e}/status`,mp({status:t}),!0)}async function e_e(e,t){let n={summary:t};return F(`/admin/mail/tickets/${e}/summary`,_6(n),!0)}async function t_e(e,t){let n=t?{reason:t}:{};return F(`/admin/mail/tickets/${e}/escalate`,mp(n),!0)}async function n_e(e,t){return F(`/admin/mail/tickets/${e}/spam`,mp(t),!0)}async function r_e(e={}){let t=new URLSearchParams;for(let[r,o]of Object.entries(e))if(o!==void 0&&o!=="")t.set(r,String(o));let n=t.toString();return F(`/admin/mail/blocklist${n?`?${n}`:""}`,{},!0)}async function o_e(e){return F("/admin/mail/blocklist",mp(e),!0)}async function s_e(e){return F(`/admin/mail/blocklist/${e}`,{method:"DELETE"},!0)}async function i_e(){return F("/admin/mail/queues",{},!0)}async function a_e(e,t){return F(`/admin/mail/queues/${encodeURIComponent(e)}`,_6(t),!0)}async function c_e(e){return F(`/admin/mail/availability${e===void 0?"":`/${e}`}`,{},!0)}async function E6(e,t){return F(`/admin/mail/availability${t===void 0?"":`/${t}`}`,_6(e),!0)}async function l_e(e){return F("/admin/mail/reprocess",mp({raw_key:e}),!0)}async function u_e(e){return(await F(`/admin/users/by-id/${e}`,{},!0)).user.username}var mp=(e,t)=>({method:"POST",body:JSON.stringify(e),...t?{headers:t}:{}}),_6=(e)=>({method:"PUT",body:JSON.stringify(e)});var Lc=z(()=>{Tw();Og();yr();Ue()});async function bo(e,t){return F(`/datasets/${e}/upload-credentials`,{method:"POST",body:JSON.stringify({duration_seconds:t})},!0)}async function S6(e,t){return F(`/datasets/${e}/download-credentials`,{method:"POST",body:JSON.stringify({duration_seconds:t})},!0)}async function p_e(e){return F(`/admin/datasets/${e}/files`,{},!0)}async function f_e(e){let t,n=0,r=[],o=!0;while(o){let s=await F(`/admin/datasets/${e}/s3-lock`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({continuation_token:t})},!0);if(n+=s.locked,s.failed?.length)r.push(...s.failed);if(o=s.hasMore,t=s.continuation_token,o&&!t)throw new j(500,"S3 lock paginated response missing continuation_token; aborting to avoid infinite loop")}return{locked:n,failed:r}}async function m_e(e,t){let n=0,r=[],o=[];for(let s=0;s<t.length;s+=d_e){let i=t.slice(s,s+d_e),a=await F(`/admin/datasets/${e}/s3-lock`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({objects:i})},!0);if(!Array.isArray(a.objects))throw new j(500,"The s3-lock route did not name the objects it locked.");if(n+=a.objects.length,o.push(...a.objects),a.failed?.length)r.push(...a.failed)}return{locked:n,failed:r,objects:o}}var d_e=100;var Uc=z(()=>{yr();Ue()});async function fD(e){return F(`/datasets/${e}/ci/status`,{},!0)}async function h_e(e){return F(`/datasets/${e}/manifest`,{},!0)}async function mD(e,t){return F(`/datasets/${e}/manifest/${t}`,{},!0)}function g_e(e){let t=e;if(!t.status)t.status="active";else if(!["active","archived","deleted"].includes(t.status))throw Error(`Invalid dataset status: ${t.status}`);if(!t.visibility)t.visibility="private";else if(!["public","private"].includes(t.visibility))throw Error(`Invalid dataset visibility: ${t.visibility}`);return t}async function hp(e={}){let t=new URLSearchParams;if(e.mine)t.set("mine","true");if(e.search)t.set("search",e.search);if(e.modality)t.set("modality",e.modality);if(e.author)t.set("author",e.author);if(e.task)t.set("task",e.task);if(e.license)t.set("license",e.license);if(e.hasDoi)t.set("has_doi","true");if(e.hasHed)t.set("has_hed","1");if(e.hasZarr)t.set("has_zarr","1");if(e.hasZarrVerified)t.set("has_zarr_verified","1");if(e.dataComplete)t.set("data_complete","1");if(e.recent)t.set("recent",String(e.recent));if(e.sort)t.set("sort",e.sort);if(e.limit!=null)t.set("limit",String(e.limit));if(e.offset!=null)t.set("offset",String(e.offset));if(e.owner)t.set("owner",e.owner);if(e.facets)for(let[o,s]of Object.entries(e.facets))t.set(o,s);if(e.includeUnknown)t.set("include_unknown","1");let n=t.toString()?`?${t.toString()}`:"",r=await F(`/datasets${n}`,{},e.mine?!0:"optional");return r.datasets=r.datasets.map(g_e),r}async function y_e(e){return F(`/datasets/resolve/${e}`,{},"optional")}async function b_e(){return F("/datasets/facets",{signal:AbortSignal.timeout(5000)},"optional",yk)}async function w_e(e,t={}){let n=new URLSearchParams({q:e});if(t.modality)n.set("modality",t.modality);if(t.limit)n.set("limit",String(t.limit));if(t.hasHed)n.set("has_hed","1");if(t.hasZarr)n.set("has_zarr","1");if(t.hasZarrVerified)n.set("has_zarr_verified","1");if(t.author)n.set("author",t.author);if(t.task)n.set("task",t.task);if(t.license)n.set("license",t.license);if(t.hasDoi)n.set("has_doi","true");if(t.dataComplete)n.set("data_complete","1");if(t.recent)n.set("recent",String(t.recent));if(t.facets)for(let[o,s]of Object.entries(t.facets))n.set(o,s);if(t.includeUnknown)n.set("include_unknown","1");return await F(`/datasets/search?${n.toString()}`,{},"optional",Jre)}async function ur(e){let t=await F(`/datasets/${e}`,{},"optional");return g_e(t.dataset)}async function Qf(e){return F(`/datasets/${e}/versions`,{},!0)}async function __e(e){try{let t=await Qf(e);if(!Array.isArray(t.versions))throw Error(`GET /datasets/${e}/versions answered without a versions list`);return t.versions.length>0}catch(t){if(t instanceof j&&t.statusCode===404&&!Pg(t))return!1;throw t}}async function hD(e){return F("/datasets",{method:"POST",body:JSON.stringify(e)},!0)}async function x_e(e,t){return F(`/datasets/${e}/attestation`,{method:"PUT",body:JSON.stringify(t)},!0)}async function gD(e){return F(`/datasets/${e}/finalize`,{method:"POST"},!0)}async function k6(e){return F(`/datasets/${e}/request-access`,{method:"POST"},!0)}async function v_e(e,t){let n=t?`?status=${t}`:"";return F(`/datasets/${e}/access-requests${n}`,{},!0)}async function E_e(e,t){return F(`/datasets/${e}/access-requests/${t}/approve`,{method:"POST"},!0)}async function S_e(e,t){return F(`/datasets/${e}/access-requests/${t}/deny`,{method:"POST"},!0)}async function k_e(e,t){return F(`/datasets/${e}/invite`,{method:"POST",body:JSON.stringify({username:t})},!0)}async function R_e(e){return F(`/datasets/${e}/collaborators`,{},!0)}async function $_e(e,t){return F(`/admin/datasets/${e}/enrichment`,{method:"POST",body:JSON.stringify(t)},!0)}var pD;var qc=z(()=>{Og();yr();Ue();pD=/^\d{4}-\d{4}-\d{4}-\d{3}[\dX]$/});function exe(e,t){return e.filter((n)=>n.visibility==="public").map((n)=>n.dataset_id).filter((n)=>n.startsWith("nm")||n.startsWith("on")).filter((n)=>n!=="nm099999"&&!nu.has(n)).filter((n)=>t.prefix?n.startsWith(t.prefix):!0).sort()}var nu;var _D=z(()=>{nu=new Set(["nm000103","nm000104","nm000105","nm000106","nm000107"])});function _o(e){return e.replace(txe,nxe)}function nxe(e){if(e===`
114
+ `)}var w0e=!1;var Qj=z(()=>{He()});function Xr(){if(process.env.TEST_API_URL)return process.env.TEST_API_URL;if(Jf)return e6;return Kt().apiUrl||e6}async function F(e,t={},n=!1,r,o="json",s){let i=`${Xr()}${e}`,a={"Content-Type":"application/json","X-CLI-Version":Qs,...t.headers};if(n){let h=Kt();if(!h.apiKey&&n===!0)throw new j(401,"Not authenticated. Run 'nemar auth login' first.");if(h.apiKey)a.Authorization=`Bearer ${h.apiKey}`}let c=t.method||"GET",l=typeof t.body==="string"?t.body:void 0,d=Date.now(),p;try{let h=[...t.signal?[t.signal]:[],...s===void 0?[]:[AbortSignal.timeout(s)]];p=await fetch(i,{...t,headers:a,...h.length===0?{}:{signal:h.length===1?h[0]:AbortSignal.any(h)}})}catch(h){if(eu())nD({method:c,url:i,status:null,durationMs:Date.now()-d,requestHeaders:a,requestBody:l,error:h instanceof Error?h.message:String(h)});throw new j(0,`Network error: Could not connect to ${Xr()}`,{originalError:h instanceof Error?h.message:String(h)})}let f;try{f=await p.text()}catch(h){if(eu())nD({method:c,url:i,status:p.status,durationMs:Date.now()-d,requestHeaders:a,requestBody:l,error:h instanceof Error?h.message:String(h)});throw new j(0,"Failed to read response body",{httpStatus:p.status,originalError:h instanceof Error?h.message:String(h)})}if(eu())nD({method:c,url:i,status:p.status,durationMs:Date.now()-d,requestHeaders:a,requestBody:l,responseBody:f});if(o==="text"&&p.ok)return{text:f,headers:p.headers};let m;try{m=JSON.parse(f)}catch{throw new j(p.status,`Invalid response from server (status ${p.status})`)}if(!p.ok){if(p.status===503&&(m.mode==="read-only"||m.mode==="full")){let G=typeof m.message==="string"?m.message:"NEMAR is in maintenance mode. Please retry shortly.",B=typeof m.eta==="string"?m.eta:null,M=new cc(m.mode,G,B,m.details);throw oD(M),M}let h=typeof m.block_reason==="string",g=Array.isArray(m.missing)?m.missing.filter((G)=>typeof G==="string"):void 0,y=typeof m.error==="string"&&(jre.includes(m.error)||noe.includes(m.error)),w=typeof m.error==="string"&&(wk.options.includes(m.error)||aoe.includes(m.error)),x=typeof m.error==="string"&&Tre.includes(m.error),v=typeof m.error==="string"&&Lre.includes(m.error),S=typeof m.error==="string"&&Zre.includes(m.error),E=typeof m.error==="string"&&Xre.includes(m.error),C=typeof m.error==="string"&&Qre.includes(m.error),I=typeof m.error==="string"&&boe.includes(m.error),P=h||I||E||C||y||w||x||v||S||g!==void 0&&typeof m.error==="string"&&Mre.includes(m.error)||g!==void 0&&typeof m.error==="string"&&xse.includes(m.error)?m.message||m.error:m.error||m.message;if(p.status===404&&m.error==="Not Found"&&typeof m.message==="string")P=`${m.message}. This NEMAR backend does not support this command yet.`;let U=new j(p.status,P||"Request failed",m.details,typeof m.step==="string"?m.step:void 0,h?m.block_reason:void 0,g);if(typeof m.error==="string")U.code=m.error;if(typeof m.reason==="string")U.reason=m.reason;U.rawBody=m;let q=Number(p.headers.get("retry-after"));if(p.headers.get("retry-after")!==null&&Number.isFinite(q)&&q>=0)U.retryAfterSeconds=q;throw U}if(r){let h=r.safeParse(m);if(!h.success)throw new j(p.status,`Response for ${e} did not match the expected NEMAR contract`,{issues:h.error.issues});return h.data}return m}var e6="https://api.nemar.org",Jf;var yr=z(()=>{Tw();Tf();vk();FI();Fw();mg();pg();kr();wn();Qj();Kf();Ue();Jf=e6.includes("workers.dev")});async function Cy(e,t={}){return F(`/datasets/${e}/publish/request`,t.anonymous?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({anonymous:!0})}:{method:"POST"},!0)}async function Ay(e){return F(`/datasets/${e}/publish/status`,{},!0)}async function v0e(e){return F(`/datasets/${e}/publish/resend`,{method:"POST"},!0)}async function E0e(e){return F(`/datasets/${e}/publish/withdraw`,{method:"POST"},!0)}async function Yf(e={}){let{statuses:t,search:n}=typeof e==="string"?{statuses:e?[e]:[]}:e,r=await _0e(t,n),o=r;if(t!==void 0&&t.length>1&&r.requests.length===0){let s=[];for(let a of new Set(t))s.push(await _0e([a],n));let i=s.flatMap((a)=>a.requests).sort(S0e);o={...r,requests:i,count:i.length}}return n?KSt(o,n):o}function S0e(e,t){return e.requested_at<t.requested_at?1:e.requested_at>t.requested_at?-1:0}async function _0e(e,t){let n=new URLSearchParams;if(e&&e.length>0)n.set("status",e.join(","));if(t)n.set("search",t);let r=n.size>0?`?${n}`:"";return F(`/admin/publish/requests${r}`,{},!0)}function KSt(e,t){let n=e.requests.filter((s)=>aie(t,[s.dataset_id,s.requested_by_username,s.dataset_name])),r=(s)=>cie(s.dataset_id,t)?0:1,o=[...n].sort((s,i)=>r(s)-r(i)||S0e(s,i));return{...e,requests:o,count:o.length}}async function Oy(e,t,n){return F(`/admin/publish/${e}/deny`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:t,...n!==void 0?{request_id:n}:{}})},!0)}async function sD(e){return F(`/admin/publish/${e}/identifier-screen`,{method:"POST"},!0)}async function iD(e){return F(`/admin/publish/${e}/review`,{},!0)}async function k0e(e){return F(`/admin/publish/${e}/review/start`,{method:"POST"},!0)}async function R0e(e,t){let n={message:t};return F(`/admin/publish/${e}/comment`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},!0)}function Ty(e){if(!(e instanceof j))return;let t=e.rawBody;if(typeof t!=="object"||t===null||Array.isArray(t))return;let n=t.code;return typeof n==="string"?n:void 0}function JSt(e,t=[]){if(e){let n=lc.indexOf(e);if(n>=0)return n+1}return Math.min(t.length+1,lc.length)}function YSt(e){if(!(e instanceof j))return!1;if(e.statusCode===0)return!0;if(e.statusCode===429)return!0;if(e.statusCode>=500&&e.statusCode<600)return!0;if(e.statusCode===403&&/repository has been locked/i.test(e.message))return!0;return!1}function XSt(){let e=process.env.NEMAR_APPROVE_RETRY_DELAY_MS;if(e===void 0||!/^\d+$/.test(e))return Xk;let t=Number(e);return Number.isSafeInteger(t)&&t<=Xk?t:Xk}async function Py(e,t=!1,n=!1,r=!1,o,s,i,a,c){let d=XSt(),p,f,m=0,h=!1,g,y=t,w=[],x;function v(S,E,C,I){if(!s)return;s({step:S,stepIndex:JSt(S,E),stepTotal:lc.length,s3LockLocked:C,s3LockTotal:I,s3LockResumed:S==="s3_lock"&&h?!0:void 0})}for(let S=1;S<=5;S++)try{let E,C=!0;do{if(E=await F(`/admin/publish/${e}/approve`,{method:"POST",headers:{"Content-Type":"application/json",...c?.dispatchToken?{[eoe]:c.dispatchToken}:{}},body:JSON.stringify({resume:C?y:!0,sandbox:n,s3_lock_continuation_token:p,s3_lock_total:f,skip_ci_check:r,...i!==void 0?{acknowledge_identifier_screen:i}:{},...a!==void 0?{[oie]:a}:{},...c?.requestId!==void 0?{request_id:c.requestId}:{}})},!0),C=!1,E.step_results)w.push(...E.step_results);if(E.s3_lock_total!==void 0)f=E.s3_lock_total;if(E.s3_lock_batch_count!==void 0)m+=E.s3_lock_batch_count;let I=E.step??E.step_results?.[E.step_results.length-1]?.step;if(I&&(I!==g||I==="s3_lock"))v(I,E.steps_completed??[],I==="s3_lock"?m:void 0,I==="s3_lock"?f:void 0),g=I;if(E.hasMore&&E.s3_lock_continuation_token!==void 0)p=E.s3_lock_continuation_token;else break}while(E.hasMore);if(w.length>0)E.step_results=x0e(w);return E}catch(E){if(x=E,S===5||!YSt(E)){if(E instanceof j&&w.length>0)E.stepResults=x0e(w);throw E}let I=E;if(o?.({attempt:S,maxAttempts:5,delayMs:d,step:I.step,error:I.message}),await new Promise((H)=>setTimeout(H,d)),y=!0,p!==void 0)h=!0}throw x}function x0e(e){let t=new Map;for(let n of e)t.set(n.step,n);return Array.from(t.values())}var ya=z(()=>{Yk();mg();Qk();yr();Ue()});function lD(e){if(e.service_access===void 0||e.service_access===null)return"unknown";return e.service_access?"upload":"browse"}async function u6(e,t,n,r,o={}){let s=new URLSearchParams;if(e)s.set("status",e);if(t)s.set("role",t);if(n)s.set("awaiting_approval","1");if(r)s.set("kind",r);if(o.search!==void 0)s.set("q",o.search);if(o.includeDeleted)s.set("include_deleted","true");let i=s.toString()?`?${s.toString()}`:"";return F(`/admin/users${i}`,{},!0,Ire)}async function uD(e,t=!1){return F(`/admin/users/by-id/${e}${t?"?include_deleted=true":""}`,{},!0,Bre)}async function F0e(e,t){return F(`/admin/users/by-id/${e}`,{method:"PATCH",body:JSON.stringify(t)},!0,Hre)}async function M0e(e){return F(`/admin/approve/${e}`,{method:"POST"},!0)}async function j0e(e){return F(`/admin/approve/by-id/${e}`,{method:"POST"},!0)}async function L0e(e){return F(`/admin/revoke/${e}`,{method:"POST"},!0)}async function U0e(e){return F(`/admin/revoke/by-id/${e}`,{method:"POST"},!0)}async function q0e(e){return F(`/admin/users/by-id/${e}/verify`,{method:"POST"},!0)}async function B0e(e,t){return F(`/admin/users/${e}/role`,{method:"POST",body:JSON.stringify({role:t})},!0)}async function H0e(e,t){return F(`/admin/users/${e}/kind`,{method:"POST",body:JSON.stringify({kind:t})},!0)}async function dD(e){return F(`/admin/users/${encodeURIComponent(e)}`,{},!0)}async function z0e(e,t){return F(`/admin/users/${e}/keys`,{method:"POST",body:JSON.stringify({name:t})},!0,xk)}async function G0e(e){return F(`/admin/users/${e}/keys`,{},!0,_k)}async function V0e(e,t){return F(`/admin/users/${e}/keys/${t}`,{method:"DELETE"},!0)}async function W0e(e){return F(`/datasets/${e}/publish`,{method:"POST"},!0)}async function K0e(e){return F(`/admin/datasets/${e}/ci`,{},!0)}async function tu(e){return F(`/admin/datasets/${e}/ci`,{method:"POST"},!0)}async function d6(e){return F(`/admin/datasets/${e}/ci/validate`,{method:"POST"},!0)}async function p6(e){return F(`/admin/datasets/${e}/ci/sync`,{method:"POST"},!0)}async function J0e(e,t){return F(`/admin/datasets/${e}/doi/concept`,{method:"POST",body:JSON.stringify(t)},!0)}async function H_(e){return F(`/admin/datasets/${e}/doi`,{},!0)}async function f6(e,t){return F(`/admin/datasets/${e}/doi/update`,{method:"POST",body:JSON.stringify(t)},!0)}async function Y0e(e,t){return F(`/admin/datasets/${e}/withdraw`,{method:"POST",body:JSON.stringify({reason:t.reason,dry_run:t.dryRun})},!0)}async function X0e(e,t){return F(`/admin/datasets/${e}/restore`,{method:"POST",body:JSON.stringify({dry_run:t.dryRun})},!0)}async function Z0e(e,t){return F(`/admin/datasets/${e}/unpublish`,{method:"POST",body:JSON.stringify({reason:t.reason,dry_run:t.dryRun})},!0)}async function Q0e(e){return F(`/admin/datasets/${e}/reset`,{method:"POST"},!0)}async function ewe(e,t=!1){return F(`/admin/datasets/${e}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({force:t})},!0)}async function twe(e){return F("/admin/datasets/bulk-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dataset_ids:e})},!0)}async function nwe(e){return F("/admin/datasets/import",{method:"POST",body:JSON.stringify(e)},!0)}async function rwe(e){return F("/admin/datasets/exemplar",{method:"POST",body:JSON.stringify(e)},!0)}async function owe(e){return F(`/admin/datasets/${e}/exemplar/remint-dois`,{method:"POST"},!0)}async function m6(e,t){let n=new URLSearchParams;if(e)n.set("status",e);if(t!==void 0)n.set("blocklisted",t?"1":"0");let r=n.toString();return F(`/admin/imports${r?`?${r}`:""}`,{},!0)}async function swe(e){return F(`/admin/imports/${e}/rollback`,{method:"POST"},!0)}async function iwe(e){return F(`/admin/imports/${e}/retry`,{method:"POST"},!0)}async function h6(e){return F(`/admin/imports/${e}/verify`,{method:"POST"},!0)}async function awe(e){return F("/admin/imports/dispatch-cooldown",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dataset_ids:e})},!0)}async function Iy(e,t){return F(`/admin/datasets/${e}/reindex`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})},!0)}async function cwe(e,t){return F("/admin/datasets/reindex/bulk",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filter:e,...t??{}})},!0)}async function lwe(e){let t=e?.limit??15;return F(`/admin/datasets/hed-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function uwe(){return F("/admin/datasets/hed-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function dwe(e){let t=e?.limit??50;return F(`/admin/datasets/recording-stats-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function pwe(){return F("/admin/datasets/recording-stats-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function fwe(e){let t=e?.limit??15;return F(`/admin/datasets/signal-defaults-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function mwe(){return F("/admin/datasets/signal-defaults-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function hwe(e){let t=e?.limit??15,n=new URLSearchParams({limit:String(t)});if(e?.olderThan!=null)n.set("older-than",String(e.olderThan));if(e?.before!=null)n.set("before",e.before);return F(`/admin/datasets/data-integrity-sweep?${n.toString()}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function gwe(){return F("/admin/datasets/data-integrity-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function ywe(e,t){let n=t?.write?"":"?dry_run=1";return F(`/admin/datasets/${e}/availability-report${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function bwe(e){let t=e?.limit??30,n=new URLSearchParams({limit:String(t)});if(e?.missingOnly)n.set("missing-only","1");return F(`/admin/datasets/availability-report-sweep?${n.toString()}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function wwe(){return F("/admin/datasets/availability-report-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function _we(e){let t=new URLSearchParams;if(e?.prefix)t.set("prefix",e.prefix);if(e?.visibility)t.set("visibility",e.visibility);if(e?.limit)t.set("limit",String(e.limit));let n=t.toString()?`?${t.toString()}`:"";return F(`/admin/fleet/drift${n}`,{},!0)}async function Fy(e,t){return F(`/admin/datasets/${e}/enforce`,{method:"POST",body:JSON.stringify({dry_run:t})},!0)}async function xwe(e){return F("/admin/datasets/enforce/bulk",{method:"POST",body:JSON.stringify({prefix:e.prefix,visibility:e.visibility,limit:e.limit,dry_run:e.dryRun})},!0)}async function vwe(e,t){return F(`/admin/datasets/${e}/review-ruleset`,{method:"POST",body:JSON.stringify({dry_run:t.dryRun,remove:t.remove})},!0)}async function Ewe(e){return F("/admin/datasets/review-ruleset/bulk",{method:"POST",body:JSON.stringify({prefix:e.prefix,after:e.after,limit:e.limit,dry_run:e.dryRun,remove:e.remove})},!0)}async function Swe(e,t=!1){return F(`/admin/datasets/${e}/revalidate${t?"?force=true":""}`,{method:"POST"},!0)}async function kwe(e){let t=e?`?user=${encodeURIComponent(e)}`:"";return F(`/admin/email-preferences${t}`,{},!0)}async function Rwe(e,t){let n=t?`?user=${encodeURIComponent(t)}`:"";return F(`/admin/email-preferences${n}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)},!0)}async function g6(e){return F("/admin/notify",{method:"POST",body:JSON.stringify(e)},!0)}async function $we(e){return F(`/admin/notify/${e}`,{},!0)}async function Dwe(){return F("/admin/summary/coverage",{},!0)}async function Cwe(e,t,n){return F("/admin/manifest/dispatch",{method:"POST",body:JSON.stringify({dataset_id:e,version:t,skip_canary:n?.skipCanary??!1})},!0)}async function y6(e){return F("/admin/doctor/scan",{method:"POST",body:JSON.stringify({...e?.check&&{check:e.check},...e?.datasetId&&{dataset_id:e.datasetId}})},!0)}async function b6(e){return F("/admin/doctor/fix",{method:"POST",body:JSON.stringify({check:e.check,...e.datasetId&&{dataset_id:e.datasetId},...e.dryRun&&{dry_run:!0}})},!0)}async function Awe(){return F("/admin/zarr-catalog/publish",{method:"POST"},!0)}async function Owe(e){return F("/admin/neurobagel/regenerate",{method:"POST",body:JSON.stringify(e)},!0)}async function Twe(){return F("/admin/neurobagel/status",{method:"GET"},!0)}async function Pwe(){return F("/admin/neurobagel/verify",{method:"POST",body:"{}"},!0)}async function Nwe(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));let n=t.toString()?`?${t.toString()}`:"";return F(`/admin/datasets/zarr-fidelity-sweep${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Iwe(e){let t=new URLSearchParams;if(e?.execute)t.set("execute","1");if(e?.limit!=null)t.set("limit",String(e.limit));if(e?.after)t.set("after",e.after);let n=t.toString()?`?${t.toString()}`:"";try{return await F(`/admin/datasets/upstream-backfill${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}catch(r){let o=r instanceof j&&r.statusCode===502?r.rawBody:void 0;if(o&&typeof o==="object"&&"execute"in o&&"counts"in o)return{...o,ok:!1};throw r}}async function Fwe(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));if(e?.after)t.set("after",e.after);if(e?.dataset)t.set("dataset",e.dataset);let n=t.toString()?`?${t.toString()}`:"";try{return await F(`/admin/upstream-status${n}`,{method:"GET"},!0)}catch(r){let o=r instanceof j&&r.statusCode===502?r.rawBody:void 0;if(o&&typeof o==="object"&&"rows"in o&&"counts"in o)return{...o,ok:!1};throw r}}async function Mwe(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));if(e?.apply)t.set("apply","1");let n=t.toString()?`?${t.toString()}`:"";return F(`/admin/imports/issue-triage${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function jwe(e){let t=e?.apply?"?apply=1":"";return F(`/admin/imports/coverage-sweep${t}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Lwe(e){let t=e?.apply?"?apply=1":"";return F(`/admin/imports/weekly-summary${t}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Uwe(e){return F("/admin/users/backfill-names",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apply:e?.apply??!1,...e?.limit!=null?{limit:e.limit}:{}})},!0)}async function qwe(e){return F("/admin/users/backfill-usernames",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apply:e?.apply??!1,...e?.limit!=null?{limit:e.limit}:{}})},!0)}async function Bwe(){return F("/admin/users/duplicates",{},!0,roe)}async function Hwe(e){return F(`/admin/users/${e}/clear-identity-conflict`,{method:"POST"},!0,ooe)}async function zwe(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));let n=t.toString()?`?${t.toString()}`:"";return F(`/admin/datasets/anonymity-sweep${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Gwe(){return F("/admin/datasets/anonymity-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function z_(e){let t=new URLSearchParams;if(e.verdicts&&e.verdicts.length>0)t.set("verdict",e.verdicts.join(","));if(e.dataset)t.set("dataset",e.dataset);if(e.author)t.set("author",e.author);if(e.needsMe)t.set("needs_me","1");let n=t.toString()?`?${t.toString()}`:"";return F(`/admin/pr-reviews${n}`,{method:"GET"},!0)}async function My(e,t,n){let r=n?`?head=${encodeURIComponent(n)}`:"";return F(`/admin/pr-reviews/${encodeURIComponent(e)}/${t}${r}`,{method:"GET"},!0)}async function w6(e,t,n={}){let r=n.redo?"?redo=1":"";return F(`/admin/pr-reviews/${encodeURIComponent(e)}/${t}/start${r}`,{method:"POST"},!0)}async function Vwe(e){return F(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"GET"},!0)}async function Wwe(e,t,n){return F(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(n?{mode:t,reason:n}:{mode:t})},!0)}async function Kwe(e){return F(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"DELETE"},!0)}async function Jwe(e,t,n,r){return F(`/admin/pr-reviews/${encodeURIComponent(e)}/${t}/allow`,{method:"POST",body:JSON.stringify({reason:n,...r?{head_sha:r}:{}})},!0)}async function x6(e){let t=new URLSearchParams;for(let[r,o]of Object.entries(e))if(o!==void 0&&o!=="")t.set(r,String(o));let n=t.toString();return F(`/admin/mail/tickets${n?`?${n}`:""}`,{},!0)}async function v6(e){return F(`/admin/mail/tickets/${e}`,{},!0)}async function Ywe(e,t,n){let r={text:t};return F(`/admin/mail/tickets/${e}/reply`,mp(r,{"Idempotency-Key":n}),!0)}async function Xwe(e,t,n){let r={text:t};return F(`/admin/mail/tickets/${e}/note`,mp(r,{"Idempotency-Key":n}),!0)}async function Zwe(e,t){let n={user_id:t};return F(`/admin/mail/tickets/${e}/assign`,mp(n),!0)}async function Qwe(e,t){return F(`/admin/mail/tickets/${e}/status`,mp({status:t}),!0)}async function e_e(e,t){let n={summary:t};return F(`/admin/mail/tickets/${e}/summary`,_6(n),!0)}async function t_e(e,t){let n=t?{reason:t}:{};return F(`/admin/mail/tickets/${e}/escalate`,mp(n),!0)}async function n_e(e,t){return F(`/admin/mail/tickets/${e}/spam`,mp(t),!0)}async function r_e(e={}){let t=new URLSearchParams;for(let[r,o]of Object.entries(e))if(o!==void 0&&o!=="")t.set(r,String(o));let n=t.toString();return F(`/admin/mail/blocklist${n?`?${n}`:""}`,{},!0)}async function o_e(e){return F("/admin/mail/blocklist",mp(e),!0)}async function s_e(e){return F(`/admin/mail/blocklist/${e}`,{method:"DELETE"},!0)}async function i_e(){return F("/admin/mail/queues",{},!0)}async function a_e(e,t){return F(`/admin/mail/queues/${encodeURIComponent(e)}`,_6(t),!0)}async function c_e(e){return F(`/admin/mail/availability${e===void 0?"":`/${e}`}`,{},!0)}async function E6(e,t){return F(`/admin/mail/availability${t===void 0?"":`/${t}`}`,_6(e),!0)}async function l_e(e){return F("/admin/mail/reprocess",mp({raw_key:e}),!0)}async function u_e(e){return(await F(`/admin/users/by-id/${e}`,{},!0)).user.username}var mp=(e,t)=>({method:"POST",body:JSON.stringify(e),...t?{headers:t}:{}}),_6=(e)=>({method:"PUT",body:JSON.stringify(e)});var Lc=z(()=>{Tw();Og();yr();Ue()});async function bo(e,t){return F(`/datasets/${e}/upload-credentials`,{method:"POST",body:JSON.stringify({duration_seconds:t})},!0)}async function S6(e,t){return F(`/datasets/${e}/download-credentials`,{method:"POST",body:JSON.stringify({duration_seconds:t})},!0)}async function p_e(e){return F(`/admin/datasets/${e}/files`,{},!0)}async function f_e(e){let t,n=0,r=[],o=!0;while(o){let s=await F(`/admin/datasets/${e}/s3-lock`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({continuation_token:t})},!0);if(n+=s.locked,s.failed?.length)r.push(...s.failed);if(o=s.hasMore,t=s.continuation_token,o&&!t)throw new j(500,"S3 lock paginated response missing continuation_token; aborting to avoid infinite loop")}return{locked:n,failed:r}}async function m_e(e,t){let n=0,r=[],o=[];for(let s=0;s<t.length;s+=d_e){let i=t.slice(s,s+d_e),a=await F(`/admin/datasets/${e}/s3-lock`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({objects:i})},!0);if(!Array.isArray(a.objects))throw new j(500,"The s3-lock route did not name the objects it locked.");if(n+=a.objects.length,o.push(...a.objects),a.failed?.length)r.push(...a.failed)}return{locked:n,failed:r,objects:o}}var d_e=100;var Uc=z(()=>{yr();Ue()});async function fD(e){return F(`/datasets/${e}/ci/status`,{},!0)}async function h_e(e){return F(`/datasets/${e}/manifest`,{},!0)}async function mD(e,t){return F(`/datasets/${e}/manifest/${t}`,{},!0)}function g_e(e){let t=e;if(!t.status)t.status="active";else if(!["active","archived","deleted"].includes(t.status))throw Error(`Invalid dataset status: ${t.status}`);if(!t.visibility)t.visibility="private";else if(!["public","private"].includes(t.visibility))throw Error(`Invalid dataset visibility: ${t.visibility}`);return t}async function hp(e={}){let t=new URLSearchParams;if(e.mine)t.set("mine","true");if(e.search)t.set("search",e.search);if(e.modality)t.set("modality",e.modality);if(e.author)t.set("author",e.author);if(e.task)t.set("task",e.task);if(e.license)t.set("license",e.license);if(e.hasDoi)t.set("has_doi","true");if(e.hasHed)t.set("has_hed","1");if(e.hasZarr)t.set("has_zarr","1");if(e.hasZarrVerified)t.set("has_zarr_verified","1");if(e.dataComplete)t.set("data_complete","1");if(e.recent)t.set("recent",String(e.recent));if(e.sort)t.set("sort",e.sort);if(e.limit!=null)t.set("limit",String(e.limit));if(e.offset!=null)t.set("offset",String(e.offset));if(e.owner)t.set("owner",e.owner);if(e.facets)for(let[o,s]of Object.entries(e.facets))t.set(o,s);if(e.includeUnknown)t.set("include_unknown","1");let n=t.toString()?`?${t.toString()}`:"",r=await F(`/datasets${n}`,{},e.mine?!0:"optional");return r.datasets=r.datasets.map(g_e),r}async function y_e(e){return F(`/datasets/resolve/${e}`,{},"optional")}async function b_e(){return F("/datasets/facets",{signal:AbortSignal.timeout(5000)},"optional",yk)}async function w_e(e,t={}){let n=new URLSearchParams({q:e});if(t.modality)n.set("modality",t.modality);if(t.limit)n.set("limit",String(t.limit));if(t.hasHed)n.set("has_hed","1");if(t.hasZarr)n.set("has_zarr","1");if(t.hasZarrVerified)n.set("has_zarr_verified","1");if(t.author)n.set("author",t.author);if(t.task)n.set("task",t.task);if(t.license)n.set("license",t.license);if(t.hasDoi)n.set("has_doi","true");if(t.dataComplete)n.set("data_complete","1");if(t.recent)n.set("recent",String(t.recent));if(t.facets)for(let[o,s]of Object.entries(t.facets))n.set(o,s);if(t.includeUnknown)n.set("include_unknown","1");return await F(`/datasets/search?${n.toString()}`,{},"optional",Jre)}async function ur(e){let t=await F(`/datasets/${e}`,{},"optional");return g_e(t.dataset)}async function Qf(e){return F(`/datasets/${e}/versions`,{},!0)}async function __e(e){try{let t=await Qf(e);if(!Array.isArray(t.versions))throw Error(`GET /datasets/${e}/versions answered without a versions list`);return t.versions.length>0}catch(t){if(t instanceof j&&t.statusCode===404&&!Pg(t))return!1;throw t}}async function hD(e){return F("/datasets",{method:"POST",body:JSON.stringify(e)},!0)}async function x_e(e,t){return F(`/datasets/${e}/attestation`,{method:"PUT",body:JSON.stringify(t)},!0)}async function gD(e){return F(`/datasets/${e}/finalize`,{method:"POST"},!0)}async function k6(e){return F(`/datasets/${e}/request-access`,{method:"POST"},!0)}async function v_e(e,t){let n=t?`?status=${t}`:"";return F(`/datasets/${e}/access-requests${n}`,{},!0)}async function E_e(e,t){return F(`/datasets/${e}/access-requests/${t}/approve`,{method:"POST"},!0)}async function S_e(e,t){return F(`/datasets/${e}/access-requests/${t}/deny`,{method:"POST"},!0)}async function k_e(e,t){return F(`/datasets/${e}/invite`,{method:"POST",body:JSON.stringify({username:t})},!0)}async function R_e(e){return F(`/datasets/${e}/collaborators`,{},!0)}async function $_e(e,t){return F(`/admin/datasets/${e}/enrichment`,{method:"POST",body:JSON.stringify(t)},!0)}var pD;var qc=z(()=>{Og();yr();Ue();pD=/^\d{4}-\d{4}-\d{4}-\d{3}[\dX]$/});function exe(e,t){return e.filter((n)=>n.visibility==="public").map((n)=>n.dataset_id).filter((n)=>n.startsWith("nm")||n.startsWith("on")).filter((n)=>n!=="nm099999"&&!nu.has(n)).filter((n)=>t.prefix?n.startsWith(t.prefix):!0).sort()}var nu;var _D=z(()=>{nu=new Set(["nm000103","nm000104","nm000105","nm000106","nm000107"])});function _o(e){return e.replace(txe,nxe)}function nxe(e){if(e===`
115
115
  `)return"\\n";if(e==="\r")return"\\r";if(e==="\t")return"\\t";let t=e.codePointAt(0)??0;return t<=255?`\\x${t.toString(16).padStart(2,"0")}`:t<=65535?`\\u${t.toString(16).padStart(4,"0")}`:`\\u{${t.toString(16)}}`}function G_(e){return e.replace(txe,(t)=>t===`
116
116
  `||t==="\t"?t:nxe(t))}function xD(e,t=", "){return e.map(_o).join(t)}var txe,Bc=(e)=>_o(e)===e;var em=z(()=>{txe=/[\p{Cc}\p{Cf}\u2028\u2029\u034f\u115f\u1160\u3164\uffa0\ufe00-\ufe0f\u{e0100}-\u{e01ef}]/gu});async function lkt(){try{let{exitCode:e,stderr:t}=await T(["ssh","-T","-o","BatchMode=yes","-o","ConnectTimeout=5","git@github.com"]),n=t.includes("successfully authenticated");if(!n)console.warn("SSH test to github.com failed:",{exitCode:e,stderr:t.trim().slice(0,500)});return{works:n,error:n?void 0:t.trim().slice(0,500)}}catch(e){let t=e instanceof Error?e.message:String(e);return console.warn("SSH test exception:",t),{works:!1,error:t}}}async function tm(){try{let{stdout:e,exitCode:t,stderr:n}=await T(["gh","auth","token"],{sensitiveOutput:!0});if(t!==0)return console.warn("gh CLI returned non-zero exit code:",t),console.warn("stderr:",n),{token:null,error:`gh auth token failed: ${n.trim()||"unknown error"}`};if(!e.trim())return console.warn("gh auth token returned empty output"),{token:null,error:"gh CLI returned empty token"};return{token:e.trim()}}catch(e){let t=e instanceof Error?e.message:String(e);if(console.error("Failed to get GitHub token from gh CLI:",t),t.includes("ENOENT")||t.includes("not found"))return{token:null,error:"gh CLI not installed (command not found)"};return{token:null,error:`gh CLI error: ${t}`}}}async function vD(e){try{let{stdout:t,exitCode:n,stderr:r}=await T(["gh","api","user","--jq",".login"]);if(n!==0){if(r.includes("not logged in")||r.includes("auth login"))return{authenticated:!1,error:"gh CLI not authenticated. Run 'gh auth login' to authenticate."};return{authenticated:!1,error:`gh CLI error: ${r.trim()||"unknown error"}`}}let o=t.trim();if(!o)return{authenticated:!1,error:"gh CLI returned empty username"};if(e){let s=o.toLowerCase()===e.toLowerCase();return{authenticated:!0,username:o,matches:s,error:s?void 0:`gh CLI authenticated as '${o}', expected '${e}'`}}return{authenticated:!0,username:o}}catch(t){let n=t instanceof Error?t.message:String(t);if(n.includes("ENOENT")||n.includes("not found"))return{authenticated:!1,error:"gh CLI not installed. Install from https://cli.github.com/"};return{authenticated:!1,error:`Failed to verify gh CLI: ${n}`}}}async function ED(e){if(!/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(e))return{accepted:!1,error:`Invalid repository format: ${e}`};let{stdout:t,exitCode:n,stderr:r}=await T(["gh","api","/user/repository_invitations"]);if(n!==0){if(r.includes("not logged in")||r.includes("auth login"))return{accepted:!1,error:"gh CLI not authenticated. Run 'gh auth login' to authenticate."};if(r.includes("API rate limit")||r.includes("403"))return{accepted:!1,error:"GitHub API rate limit exceeded. Please try again in a few minutes."};if(r.includes("ENOENT")||r.includes("not found"))return{accepted:!1,error:"gh CLI not installed. Install from https://cli.github.com/"};return{accepted:!1,error:`Failed to list invitations: ${r.trim()||"unknown error"}`}}let o=null;try{o=JSON.parse(t||"[]").find((l)=>l.repository.full_name===e)?.id??null}catch(a){let c=a instanceof Error?a.message:String(a);return console.error("Failed to parse GitHub invitations response:",c),console.error(" Raw response (first 500 chars):",(t||"").slice(0,500)),{accepted:!1,error:`Failed to parse GitHub API response: ${c}`}}if(!o){let{exitCode:a}=await T(["gh","api",`/repos/${e}`,"--silent"]);if(a===0)return{accepted:!0,alreadyCollaborator:!0};return{accepted:!1,error:`No pending invitation found for ${e}. You may need to accept it manually via GitHub.`}}let{exitCode:s,stderr:i}=await T(["gh","api","--method","PATCH",`/user/repository_invitations/${o}`]);if(s!==0)return{accepted:!1,error:`Failed to accept invitation: ${i.trim()||"unknown error"}`};return{accepted:!0}}async function Hc(e,t,n="origin"){let r=t;if(process.env.GH_TOKEN&&t.startsWith("git@github.com:")){let o=process.env.GH_TOKEN.trim();if(!o||/\s/.test(o))return{success:!1,error:"GH_TOKEN environment variable is set but appears malformed (empty or contains whitespace)"};r=`https://github.com/${t.replace("git@github.com:","")}`,await T(["git","config","credential.https://github.com.helper",`!printf 'username=x-access-token\\npassword=${o}'`],{cwd:e,redact:[o]})}else if(t.startsWith("git@github.com:")){let o=t.replace("git@github.com:",""),s=await tm();if(s.token)r=`https://github.com/${o}`,await T(["git","config","credential.https://github.com.helper",`!printf 'username=x-access-token\\npassword=${s.token}'`],{cwd:e,redact:[s.token]});else{let i=await lkt();if(i.works)r=t;else return{success:!1,error:`GitHub authentication not configured.
117
117
 
@@ -826,7 +826,7 @@ which names the field and never repeats what was typed.
826
826
  Examples:
827
827
  nemar admin oidc clients add --name "Compute portal" --redirect-uri https://portal.example.org/cb \\
828
828
  --scopes openid,profile,orcid --grants authorization_code --sign-in-rule person_proven_orcid \\
829
- --audience https://nemar-api-dev.sccn-org.workers.dev
829
+ --audience https://api.nemar.org
830
830
 
831
831
  Exit codes:
832
832
  0 registered; the secret was printed.
@@ -1065,7 +1065,7 @@ ${w.message}`,r);if(x)return nn("message",`The squash message would not carry th
1065
1065
  `);let{phase:p,code:f}=d;e(`${cv("result",f===void 0?{phase:p}:{phase:p,code:f})}
1066
1066
  `);return}e(`${cv("result",{phase:"failed",code:"runner-failed"})}
1067
1067
  `)};k1={emit(d,p){if(d==="result")o=String(p?.phase??"failed");e(`${cv(d,p)}
1068
- `)},drop(){t++},dropped:()=>t,stored(d,p){s={phase:d,code:d==="refused"||d==="failed"?p:void 0}},time(d,p){i.set(d,p)},quietFields:a},process.on("exit",()=>{if(o===null)c()});let l=()=>{try{t++;let d=o;if(s?d!==s.phase:d===null||d==="planned"||d==="opened"||d==="finished")c()}finally{process.exit(1)}};return process.on("uncaughtException",l),process.on("unhandledRejection",l),k1}function F4(e){return e.some((t)=>t===COe||t.startsWith(`${COe}=`))}function u6t(e){let t=e.GITHUB_RUN_ID??"";if(e.GITHUB_SERVER_URL==="https://github.com"&&e.GITHUB_REPOSITORY==="nemarDatasets/.github"&&/^[0-9]{1,20}$/.test(t))return`https://github.com/nemarDatasets/.github/actions/runs/${t}`;return null}function POe(e,t,n){let r=I4(e);if(r===null)throw Ir("id on the command line");let o=i6t(t);if(o.dispatchId!==r)throw new L("dispatch-mismatch","The dispatch named on the command line is not the one the event delivered.");let s=t.RUNNER_TEMP;return{dispatch:o,runUrl:u6t(t),marker:s?Gp(s,"repull-reported"):null,sink:n}}var d6t="https://nemar-api-dev.sccn-org.workers.dev";function NOe(e){let t;try{t=new URL(e)}catch{return!1}if(t.username||t.password||t.search||t.hash||t.pathname!=="/"&&t.pathname!=="")return!1;if(t.protocol==="https:")return t.host===new URL(d6t).host;return t.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(t.hostname)}function M4(e,t){if(!t.some((n)=>n.includes(e.token)))return null;return new L("auto-token-on-argv","The dispatch token is on the command line, where the public log shows it.")}function IOe(e,t){let n=M4(e,t.argv);if(n)return n;let r=t.ownVersion??Qs;if((t.devBuild??Jf)||!ib.test(r)||r!==e.cliVersion)return new L("auto-cli-version","This CLI is not the release the dispatch names: an automatic run uses only that release.");if(t.verbose??(ky()||eu()||t.argv.includes("--verbose")||t.argv.includes("--debug")))return new L("auto-verbose","Verbose or debug output is on, and it prints what the run reads; an automatic run takes neither.");if(e.mode!==t.mode||e.datasetId!==t.datasetId)return new L("dispatch-mismatch","The command is not the one the dispatch asks for: another kind of run, or another dataset.");if(!t.env.GH_TOKEN?.trim())return new L("auto-no-app-token","GH_TOKEN is not set: an automatic run pushes and opens its pull request with the App token minted for this dataset.");if($1(t.env,t.nowMs??Date.now())===null)return new L("auto-token-clock",`${FOe} does not say when the App token was minted, so the run cannot keep its pushes inside the token's hour.`);return null}var FOe="NEMAR_REPULL_TOKEN_SINCE";function $1(e,t){let n=e[FOe]?.trim()??"";if(!/^[1-9][0-9]{0,11}$/.test(n))return null;let r=Number(n);return r*1000<=t+300000?r:null}function p6t(e,t){return(e+fx)*1000-t}function lv(e,t,n){let r=(n+gRe+nU)*1000;if(p6t(e,t)>=r)return null;return new L("auto-token-hour","What is left to do would pass the App token's usable hour, so the run stops before this step; the record, if there is one, stays where it stopped.")}function uv(e){let t=hl(e);return oU({bytes:t.copy_bytes??0,objects:t.copy_items??0})}function Wb(e,t){return new L("auto-option",t==="required"?`An automatic run needs ${e}.`:`An automatic run does not take ${e}.`)}function MOe(e){if(!e.executable)throw new L("not-executable","The plan is not executable.");D1(e.body)}function D1(e){let t=hl(e),n=mRe(e.planner,t);if(n)throw new L(n.code,n.message);if(t.copy_bytes_unknown!==0)throw new L("auto-copy-too-large","An automatic re-pull takes only a plan whose copy size is known for every key.");let{copy_bytes:r,copy_items:o,local_bytes:s,local_uploads:i}=t,a=f6t();if(r===void 0||o===void 0||s===void 0||i===void 0||t.local_bytes_unknown!==0||oU({bytes:r+s,objects:o+i})>a)throw new L("auto-copy-too-long",`An automatic re-pull takes only a plan whose copy, by its known size and count, fits ${Math.floor(a/60)} minutes: the App token that pushes it lasts an hour.`)}function C1(e){return`${e}.planner`}function jOe(e,t,n,r){Xjt(Gp(t,"computed"),{mode:448});for(let[s,i]of n)N4(Gp(t,"computed",s),i,{mode:384});N4(Gp(t,"digest"),`${r}
1068
+ `)},drop(){t++},dropped:()=>t,stored(d,p){s={phase:d,code:d==="refused"||d==="failed"?p:void 0}},time(d,p){i.set(d,p)},quietFields:a},process.on("exit",()=>{if(o===null)c()});let l=()=>{try{t++;let d=o;if(s?d!==s.phase:d===null||d==="planned"||d==="opened"||d==="finished")c()}finally{process.exit(1)}};return process.on("uncaughtException",l),process.on("unhandledRejection",l),k1}function F4(e){return e.some((t)=>t===COe||t.startsWith(`${COe}=`))}function u6t(e){let t=e.GITHUB_RUN_ID??"";if(e.GITHUB_SERVER_URL==="https://github.com"&&e.GITHUB_REPOSITORY==="nemarDatasets/.github"&&/^[0-9]{1,20}$/.test(t))return`https://github.com/nemarDatasets/.github/actions/runs/${t}`;return null}function POe(e,t,n){let r=I4(e);if(r===null)throw Ir("id on the command line");let o=i6t(t);if(o.dispatchId!==r)throw new L("dispatch-mismatch","The dispatch named on the command line is not the one the event delivered.");let s=t.RUNNER_TEMP;return{dispatch:o,runUrl:u6t(t),marker:s?Gp(s,"repull-reported"):null,sink:n}}var d6t="https://api.nemar.org";function NOe(e){let t;try{t=new URL(e)}catch{return!1}if(t.username||t.password||t.search||t.hash||t.pathname!=="/"&&t.pathname!=="")return!1;if(t.protocol==="https:")return t.host===new URL(d6t).host;return t.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(t.hostname)}function M4(e,t){if(!t.some((n)=>n.includes(e.token)))return null;return new L("auto-token-on-argv","The dispatch token is on the command line, where the public log shows it.")}function IOe(e,t){let n=M4(e,t.argv);if(n)return n;let r=t.ownVersion??Qs;if((t.devBuild??Jf)||!ib.test(r)||r!==e.cliVersion)return new L("auto-cli-version","This CLI is not the release the dispatch names: an automatic run uses only that release.");if(t.verbose??(ky()||eu()||t.argv.includes("--verbose")||t.argv.includes("--debug")))return new L("auto-verbose","Verbose or debug output is on, and it prints what the run reads; an automatic run takes neither.");if(e.mode!==t.mode||e.datasetId!==t.datasetId)return new L("dispatch-mismatch","The command is not the one the dispatch asks for: another kind of run, or another dataset.");if(!t.env.GH_TOKEN?.trim())return new L("auto-no-app-token","GH_TOKEN is not set: an automatic run pushes and opens its pull request with the App token minted for this dataset.");if($1(t.env,t.nowMs??Date.now())===null)return new L("auto-token-clock",`${FOe} does not say when the App token was minted, so the run cannot keep its pushes inside the token's hour.`);return null}var FOe="NEMAR_REPULL_TOKEN_SINCE";function $1(e,t){let n=e[FOe]?.trim()??"";if(!/^[1-9][0-9]{0,11}$/.test(n))return null;let r=Number(n);return r*1000<=t+300000?r:null}function p6t(e,t){return(e+fx)*1000-t}function lv(e,t,n){let r=(n+gRe+nU)*1000;if(p6t(e,t)>=r)return null;return new L("auto-token-hour","What is left to do would pass the App token's usable hour, so the run stops before this step; the record, if there is one, stays where it stopped.")}function uv(e){let t=hl(e);return oU({bytes:t.copy_bytes??0,objects:t.copy_items??0})}function Wb(e,t){return new L("auto-option",t==="required"?`An automatic run needs ${e}.`:`An automatic run does not take ${e}.`)}function MOe(e){if(!e.executable)throw new L("not-executable","The plan is not executable.");D1(e.body)}function D1(e){let t=hl(e),n=mRe(e.planner,t);if(n)throw new L(n.code,n.message);if(t.copy_bytes_unknown!==0)throw new L("auto-copy-too-large","An automatic re-pull takes only a plan whose copy size is known for every key.");let{copy_bytes:r,copy_items:o,local_bytes:s,local_uploads:i}=t,a=f6t();if(r===void 0||o===void 0||s===void 0||i===void 0||t.local_bytes_unknown!==0||oU({bytes:r+s,objects:o+i})>a)throw new L("auto-copy-too-long",`An automatic re-pull takes only a plan whose copy, by its known size and count, fits ${Math.floor(a/60)} minutes: the App token that pushes it lasts an hour.`)}function C1(e){return`${e}.planner`}function jOe(e,t,n,r){Xjt(Gp(t,"computed"),{mode:448});for(let[s,i]of n)N4(Gp(t,"computed",s),i,{mode:384});N4(Gp(t,"digest"),`${r}
1069
1069
  `,{mode:384});let o=C1(e);e6t(o,{recursive:!0,force:!0}),Qjt(t,o)}function LOe(e,t){let n=C1(e),r=Gp(n,"computed"),o=Gp(n,"digest");if(!T4(Gp(n,"upstream.git"))||!T4(r)||!T4(o)||P4(o,"utf8").trim()!==t)throw new L("not-planned","No handoff of this plan's own plan step is beside the plan file; an automatic execute plans nothing itself.");let s=new Map;for(let i of Zjt(r))s.set(i,P4(Gp(r,i)));return{workdir:n,computed:s}}function f6t(e=process.env){let t=e.NEMAR_REPULL_COPY_BUDGET_SECONDS?.trim()??"",n=/^\d{1,9}$/.test(t)?Number(t):Number.NaN;return Number.isFinite(n)&&n<rU?n:rU}async function UOe(e,t,n=fetch){let r=t.GH_TOKEN?.trim();if(!r)return!1;let o;try{o=Cn(t)}catch{return!1}try{let s=await n(`${o}/repos/nemarDatasets/${e}`,{redirect:"error",headers:{Authorization:`Bearer ${r}`,Accept:"application/vnd.github+json","User-Agent":"nemar-cli"},signal:AbortSignal.timeout(1e4)});return await s.body?.cancel().catch(()=>{return}),s.status===401}catch{return!1}}function A1(e,t){if(tU(e))return e;if(t===void 0)return"no-code";if(t==="prepare"&&CCe.includes(e??""))return"scrub-failed";return fRe[t]}var m6t=15000,OOe=["opened","finished","refused","failed"];async function j4(e,t,n={},r={}){let o={dispatch_id:e.dispatch.dispatchId,dataset_id:e.dispatch.datasetId,phase:t};if(t==="refused"||t==="failed")o.code=A1(n.code);if(t==="opened")o.repull_id=n.repullId;if(e.runUrl)o.workflow_run_url=e.runUrl;let s=r.fetchImpl??fetch,i=r.apiUrl??Xr(),a=Math.max(1,r.attempts??3),c={stored:!1,code:"report-unanswered"};for(let l=1;l<=a;l++){let d,p;try{let f=await s(`${i}/webhooks/repull-state`,{method:"POST",redirect:"error",headers:{"Content-Type":"application/json","X-Repull-Token":e.dispatch.token},body:JSON.stringify(o),signal:AbortSignal.timeout(r.timeoutMs??m6t)});d=f.status,p=(await f.json().catch(()=>null))?.code}catch{if(c={stored:!1,code:"report-unanswered"},l<a)await TOe(r.backoffMs??2000);continue}if(d===200){c={stored:!0};break}if(c={stored:!1,code:typeof p==="string"&&tU(p)?p:"report-unanswered"},d<500)break;if(l<a)await TOe(r.backoffMs??2000)}if(e.sink.emit("report",{phase:t,answer:c.stored?"stored":c.code}),c.stored&&OOe.includes(t))e.sink.stored(t,o.code);if(c.stored&&OOe.includes(t)&&e.marker)try{N4(e.marker,`${t}
1070
1070
  `,{mode:384})}catch{}return c}var TOe=(e)=>new Promise((t)=>setTimeout(t,e));pa();ko();yr();Ue();import{existsSync as gUt,readdirSync as yUt,rmdirSync as bUt}from"fs";import{dirname as bv,join as yv}from"path";kr();tl();to();Mp();Da();z1();pb();ko();Ue();import{dirname as TLt,join as PLt}from"path";kr();function ms(e,t){return new L(e,t)}var t3=["registered","pr_open","gates_clear"];async function _Te(e,t,n){let r=await Mb({token:e.token,base:e.base,datasetId:e.datasetId,state:"all",head:t});if(!r.ok)throw ms("github-unreadable",`GitHub's pull requests of ${t} could not be read whole (${Fb(r)}), so whether one merged is not known; nothing was closed.`);let o=new Set(r.pulls.filter((i)=>i.headRef===t).map((i)=>i.number));if(n!==null)o.add(n);let s=[];for(let i of[...o].sort((a,c)=>a-c)){let a=await ri(e.token,e.datasetId,i,e.base);if(!a.ok)throw ms("github-unreadable",`Pull request #${i} could not be read on GitHub (${a.reason}); nothing was closed.`);s.push({number:i,state:a.value.state,headSha:a.value.headSha})}return s}function NLt(e,t,n,r){return ms("foreign-pull-request-merged",`GitHub says pull request #${t} of ${n} merged, and it is not this re-pull's (it recorded #${r}): that version was released outside the re-pull, which resume does not record. Nothing was closed or ended; read the dataset's history on GitHub (nemarDatasets/${e.datasetId}) to see what merged before this record is ended.`)}function xTe(e,t,n,r){return r!==null&&t!==r?NLt(e,t,n,r):vTe(e,t)}function vTe(e,t,n=!1){return(n?at:ms)("pull-request-merged",`GitHub says pull request #${t} merged, so this re-pull is not ended: nemar admin repull resume ${e.datasetId} records the merge (a merge minted a DOI, and its release is recorded, not abandoned).`)}async function ILt(e,t){let n=(await ds(e,t)).filter((a)=>a.mode==="120000"||a.mode==="100644"||a.mode==="100755"),r=new Map;if(n.length>0){let a=await se(e,["cat-file","--batch-check"],{stdin:`${n.map((c)=>c.oid).join(`
1071
1071
  `)}
@@ -2917,7 +2917,7 @@ Stopped waiting. Job ${t} is still running and was not canceled.
2917
2917
  `)}}}mg();Ue();function DMe(e){return e instanceof j&&e.statusCode===422&&e.rawBody?.status==="blocked"&&bk(e.blockReason)}function CMe(e){let t=e.rawBody?.ci_url;return typeof t==="string"&&/^https:\/\/\S+$/.test(t)?t:void 0}function YB(e){return e==="bids_validation_in_progress"?"Request recorded: BIDS validation is still running.":"Request recorded: BIDS validation has not started yet."}function XB(e,t=!1){let n=`nemar dataset publish request ${e}${t?" --anonymous":""}`;return[" Your request is recorded. NEMAR re-checks it automatically and continues once validation passes.",` If you would rather not wait for that, check validation with: nemar dataset ci ${e}`,` Once it has passed, request again: ${n}`," If it says a request already exists, nothing more is needed."," If validation fails or a submission minimum fails, the request stays blocked and nothing is emailed:",` check nemar dataset ci ${e} or nemar dataset publish status ${e}.`]}Ue();kr();async function nT(){let e=Kt().sandboxCompleted;if(e!==void 0)return{status:e?"completed":"not_completed"};try{let t=await yD();if(Vn("sandboxCompleted",t.sandbox_completed),t.sandbox_dataset_id)Vn("sandboxDatasetId",t.sandbox_dataset_id);return t.sandbox_completed?{status:"completed"}:{status:"not_completed"}}catch(t){return{status:"unknown",reason:W(t)}}}He();Fi();aq();He();To();Lc();Ue();km();bA();em();Fi();Ii();vA();uq();Ip();Rm();import{existsSync as ZB,mkdirSync as MHt,readFileSync as jHt,statSync as LHt,writeFileSync as AMe}from"fs";import{join as UHt,resolve as QB}from"path";function OMe(e,t,n){if(!Ra(n,"metadata_write")){if(t)try{let r=QB(e,".nemar"),o=QB(r,"metadata.json");if(!ZB(o)){if(!ZB(r))MHt(r,{recursive:!0});AMe(o,JSON.stringify(t,null,2))}let s=QB(e,".bidsignore"),i="";if(ZB(s))i=jHt(s,"utf-8");if(!i.includes(".nemar/")){let a=i?`${i.trimEnd()}
2918
2918
  .nemar/
2919
2919
  `:`.nemar/
2920
- `;AMe(s,a)}console.log(u.dim(" Updated .bidsignore for NEMAR metadata"))}catch(r){console.log(u.yellow(` Warning: Could not update .bidsignore: ${W(r)}`)),console.log(u.dim(" Upload will continue without author enrichment."))}fu(n,"metadata_write"),ro(e,n)}else console.log(u.dim(" Metadata write already completed (skipping)"))}var TMe=1073741824;function qHt(e,t,n=TMe){let r=[],o=0;for(let s of t){let i=e.files[s];if(!i||i.mtimeMs===void 0)continue;r.push({path:s,size:i.size,mtimeMs:i.mtimeMs}),o+=i.size}return o>=n?r:null}function BHt(e,t){return t.filter((n)=>{try{return xo(n.path,LHt(UHt(e,n.path)).size)}catch{return!0}})}function HHt(e){let t=0;for(let n of Object.values(e.files))t+=n.size;return t}function zHt(e){return["Warning: saving dataset changes has produced no stdout or stderr for",`${EA(e)}. git add -A is still running.`,"Wait, or interrupt and rerun the upload; the save step will run again."].join(" ")}async function PMe(e,t,n,r={}){if(!Ra(n,"dataset_save")){let o=A({text:"Saving dataset changes...",...r.spinnerStream?{stream:r.spinnerStream}:{}}).start(),s=r.skipMinBytes??TMe,i=[];if(HHt(n)>=s){let c=r.annexedPaths??null;if(c===null)try{c=await Np(e)}catch(l){console.log(u.dim(` Could not list annexed files (${W(l)}); staging will re-read them`))}if(c!==null)i=BHt(e,qHt(n,c,s)??[])}let a=await ru(e,"Initial NEMAR dataset upload",t,{skipContentCheck:i,onInactivityWarning:(c)=>{o=Px(o,zHt(c))},...r.inactivityWarningAfterMs===void 0?{}:{inactivityWarningAfterMs:r.inactivityWarningAfterMs}});if(!a.success)return ro(e,n),qo(o,"Failed to save dataset",a.error),console.log(),console.log(u.yellow("Re-run the same command to resume from this step.")),Ge;if(r.verifyRemote){let c;try{c=await yq(e,r.verifyRemote)}catch(l){return ro(e,n),qo(o,"Could not confirm the saved files are at the S3 remote",l),console.log(),console.log(u.yellow("Re-run the same command to resume from this step.")),Ge}if(c.length>0){mu(n,"s3_upload"),ro(e,n);let l=xD(c.slice(0,5)),d=c.length>5?` (and ${c.length-5} more)`:"";return qo(o,"Saved files are not at the S3 remote",`${c.length} annexed file(s) in the commit are not recorded at the remote: ${l}${d}. The save itself annexed them, after the upload step had run.`),console.log(),console.log(u.yellow("Re-run the same command: it uploads them and saves again.")),Ge}}o.succeed("Dataset changes saved"),fu(n,"dataset_save"),ro(e,n)}else console.log(u.dim(" Dataset save already completed (skipping)"));return Rn()}async function NMe(e,t){if(!Ra(t,"github_push")){let n=A("Pushing metadata to GitHub...").start(),r=await Rr(e);if(!r.success)return ro(e,t),qo(n,"Failed to push to GitHub",r.error),console.log(),console.log(u.yellow("Re-run the same command to resume from this step.")),Ge;if(r.warning)n.warn("Metadata pushed to GitHub (with warning)"),console.log(u.yellow(` ${r.warning}`));else n.succeed("Metadata pushed to GitHub");fu(t,"github_push"),ro(e,t)}else console.log(u.dim(" GitHub push already completed (skipping)"));return Rn()}async function IMe(e,t,n){if(!Ra(n,"ci_deploy")){let r=A("Setting up BIDS validation CI...").start(),o="configured";try{await tu(t),r.succeed("BIDS validation CI configured")}catch(s){if(o="not-configured",s instanceof j&&s.statusCode===403)r.info("CI workflow will be configured by an admin");else{let i=s instanceof Error?s.message:String(s);r.warn(`Could not configure CI: ${i}`),console.log(u.dim(` An admin can add it later with: nemar admin ci add ${t}`))}}return fu(n,"ci_deploy"),ro(e,n),o}return console.log(u.dim(" CI deploy already completed (skipping)")),"unknown"}function GHt(e,t){let n=e.startsWith("xx");if(t==="not-configured"){if(n)return;console.log("BIDS validation is not set up yet."),console.log(` CI is set up when you request publication: ${u.cyan(`nemar dataset publish request ${e}`)}`),console.log();return}if(console.log("BIDS validation runs on GitHub after the upload."),console.log(` Check it with: ${u.cyan(`nemar dataset ci ${e}`)}`),!n)console.log(` Once it has passed, request publication: ${u.cyan(`nemar dataset publish request ${e}`)}`);console.log()}function FMe(e,t,n="unknown"){Tx(e),NDe(e),console.log(),console.log(u.green.bold("Upload complete!")),console.log(),console.log(` Dataset ID: ${u.cyan(t.dataset_id)}`),console.log(` GitHub: ${u.cyan(t.github_url)}`),console.log(),console.log(u.dim("To download this dataset:")),console.log(u.dim(` nemar dataset download ${t.dataset_id}`)),console.log(),GHt(t.dataset_id,n),console.log(u.yellow("Note: This dataset is private. Only the owner and designated collaborators can")),console.log(u.yellow("download it, and only through the NEMAR CLI (not direct git-annex commands).")),console.log(u.yellow("After publishing, the data will be publicly available for everyone."))}Ip();Rm();async function MMe(e,t={}){let n=await $xe(e.absolutePath);if(!n.success)return console.log(u.red(n.error)),console.log(u.yellow("Re-run the same command to retry.")),Ge;if(n.cleared>0)console.log(u.yellow(` Cleared ${n.cleared} assume-unchanged flag(s) an earlier, interrupted save left on annexed files`));let r=await UDe(e.absolutePath);if(r.status==="error")return console.log(u.red(r.error)),Ge;if(r.status==="warning")console.log(u.yellow(` ${r.warning}`));if(r.status==="restored")console.log(u.yellow(" Put back git-annex's filter process, which an earlier, interrupted upload had left out of this repository's configuration"));let o=await wCe(e.absolutePath,e.options,e.dataFiles,e.filesToUpload,e.uploadProgress,e.datasetInfo,{openRemote:t.openRemote,...t.primeMinBytes===void 0?{}:{primeMinBytes:t.primeMinBytes},...t.primeOnSuspended?{primeOnSuspended:t.primeOnSuspended}:{}});if(o.status==="fail")return Ge;let{progress:s,annexedPaths:i}=o.value;if(OMe(e.absolutePath,e.coAuthorEnrichment,s),(await(t.saveStep??PMe)(e.absolutePath,e.author,s,{annexedPaths:i,verifyRemote:il,...t.skipMinBytes===void 0?{}:{skipMinBytes:t.skipMinBytes},...t.saveInactivityWarningAfterMs===void 0?{}:{inactivityWarningAfterMs:t.saveInactivityWarningAfterMs},...t.saveSpinnerStream===void 0?{}:{spinnerStream:t.saveSpinnerStream}})).status==="fail")return Ge;return Rn(s)}He();du();qm();Dx();wn();Wt();import{randomBytes as $7t}from"crypto";import{constants as s8,accessSync as D7t,chmodSync as C7t,chownSync as A7t,closeSync as l8,copyFileSync as O7t,existsSync as cje,fsyncSync as lje,lstatSync as El,mkdirSync as T7t,mkdtempSync as P7t,openSync as u8,readSync as N7t,readdirSync as I7t,renameSync as F7t,rmSync as d8,rmdirSync as M7t,statSync as uje,writeSync as j7t}from"fs";import{tmpdir as L7t}from"os";import{dirname as lT,join as ja}from"path";He();import{lstatSync as w7t,readdirSync as _7t,statSync as YMe}from"fs";import{open as x7t}from"fs/promises";import{join as JMe}from"path";_s();To();du();var BMe="nemar-identifier-scan/1.0 (+https://docs.nemar.org/policies/takedown/)",VHt="https://nemar-api-dev.sccn-org.workers.dev",WHt="https://data.nemar.org",KHt="https://nemar.s3.us-east-2.amazonaws.com",JHt="https://api.github.com";function iT(e,t){if(!Number.isSafeInteger(t)||t<1)throw RangeError(`${e} must be a positive integer, got ${t}`)}async function rT(e,t,n){iT("pool size",t);let r=0,o=Array.from({length:Math.min(t,e.length)},async()=>{while(r<e.length){let a=e[r++];await n(a)}}),i=(await Promise.allSettled(o)).find((a)=>a.status==="rejected");if(i)throw i.reason}function YHt(e){iT("limit",e);let t=0,n=[];return async(r)=>{if(t>=e)await new Promise((o)=>n.push(o));else t++;try{return await r()}finally{let o=n.shift();if(o)o();else t--}}}class pr extends Error{cls;status;retryable;retryAfterMs;constructor(e,t={}){super(e);this.name="ReadFailure",this.cls=e,this.status=t.status,this.retryable=t.retryable??!1,this.retryAfterMs=t.retryAfterMs}}function XHt(e,t=Date.now()){let n=e?.trim();if(!n)return;if(/^\d+$/.test(n))return Number(n)*1000;let r=Date.parse(n);return Number.isNaN(r)?void 0:Math.max(0,r-t)}function ZHt(e,t){let n=e>=500||e===429;return new pr(`http-${e}`,{status:e,retryable:n,retryAfterMs:n?XHt(t):void 0})}class e8 extends Error{constructor(e){super(e);this.name="RunAborted"}}function QHt(e){iT("abort streak",e.streak);let t=e.now??Date.now,n={tripped:null},r=(o)=>{let s=0,i=0,a=(c)=>{throw n.tripped=new e8(c),n.tripped};return{check(){if(n.tripped)throw n.tripped},ok(){s=0},pausedUntilMs(){return i},observe(c){if(n.tripped)throw n.tripped;if(c.retryAfterMs!==void 0&&c.retryAfterMs>e.retryAfterCapMs)a(`${o} asked to wait ${Math.round(c.retryAfterMs/1000)} s (Retry-After), over the ${Math.round(e.retryAfterCapMs/1000)} s cap (${c.cls})`);if(c.retryAfterMs!==void 0)i=Math.max(i,t()+c.retryAfterMs);if(!c.retryable){s=0;return}if(s++,s>=e.streak)a(`${s} consecutive 429, 5xx, timeout or network failures from ${o} (last ${c.cls})`)}}};return{worker:r("the Worker"),direct:r("direct reads")}}function jMe(e){let t=e instanceof Error?e.name:"";return new pr(t==="TimeoutError"||t==="AbortError"?"timeout":"network",{retryable:!0})}function e7t(e){if(e instanceof pr)return e.cls;return`error-${e instanceof Error?e.name:"unknown"}`}async function t7t(e,t={}){let n=t.tries??3,r=t.baseMs??400,o=t.sleep??((s)=>new Promise((i)=>setTimeout(i,s)));iT("tries",n);for(let s=1;;s++)try{return await e()}catch(i){if(!(i instanceof pr&&i.retryable)||s>=n)throw i;let c=i.retryAfterMs??0;if(c>(t.retryAfterCapMs??30000))throw i;await o(Math.max(r*2**(s-1),c))}}async function n7t(e){await e.body?.cancel().catch(()=>{return})}async function r7t(e,t,n={}){let r;try{r=await fetch(e,{headers:{Range:`bytes=0-${t-1}`,"Accept-Encoding":"identity","User-Agent":n.userAgent??BMe},signal:AbortSignal.timeout(n.timeoutMs??30000)})}catch(a){throw jMe(a)}if(r.status!==200&&r.status!==206)throw await n7t(r),ZHt(r.status,r.headers.get("retry-after"));let o=r.body?.getReader();if(!o)throw new pr("no-body");let s=new Uint8Array(t),i=0;try{while(i<t){let{done:a,value:c}=await o.read();if(a||!c)break;let l=Math.min(c.length,t-i);s.set(c.subarray(0,l),i),i+=l}}catch(a){throw jMe(a)}finally{await o.cancel().catch(()=>{return})}if(i<(n.minBytes??0))throw new pr("short-body");return s.subarray(0,i)}var HMe={sideFileBytes:2097152,participantsBytes:16777216};function o7t(e,t){let n=/An error occurred \(([A-Za-z0-9]{1,40})\)/.exec(e)?.[1];if(n)return/^\d+$/.test(n)?`aws/http-${n}`:`aws/error-${n}`;return`aws/exit-${t}`}async function s7t(e,t,n={}){let r;try{let o=Bun.spawn(["aws","s3","cp",`s3://nemar/${e}/version/${t}.json`,"-"],{stdout:"pipe",stderr:"pipe",...n.env?{env:n.env}:{}}),s=!1;r=setTimeout(()=>{s=!0,o.kill("SIGKILL")},n.timeoutMs??600000);let[i,a,c]=await Promise.all([new Response(o.stdout).text(),new Response(o.stderr).text(),o.exited]);if(s)throw new pr("aws/timeout");if(c!==0)throw new pr(o7t(a,c));return i}catch(o){if(o instanceof pr)throw o;throw new pr("aws/unavailable")}finally{clearTimeout(r)}}function i7t(){let e;return async()=>{if(e!==void 0)return e;if(process.env.GITHUB_TOKEN)return e=process.env.GITHUB_TOKEN,e;try{let t=Bun.spawn(["gh","auth","token"],{stdout:"pipe",stderr:"ignore"}),n=(await new Response(t.stdout).text()).trim();e=n===""?null:n}catch{e=null}return e}}var oT=(e)=>e.replace(/\/+$/,"");function zMe(e={}){let t=e.retryAfterCapMs??30000,n=e.awsTimeoutMs??600000;return{api:oT(e.api??process.env.NEMAR_API_BASE??VHt),data:oT(e.data??process.env.NEMAR_DATA_BASE??WHt),s3Base:oT(e.s3Base??KHt),githubApi:oT(e.githubApi??JHt),userAgent:e.userAgent??BMe,fileConcurrency:e.fileConcurrency??24,workerLimit:YHt(e.workerConcurrency??6),timeoutMs:e.timeoutMs??30000,manifestTimeoutMs:e.manifestTimeoutMs??120000,retryBaseMs:e.retryBaseMs??400,sleep:e.sleep??((r)=>new Promise((o)=>setTimeout(o,r))),now:e.now??Date.now,retryAfterCapMs:t,breakers:QHt({streak:e.abortStreak??25,retryAfterCapMs:t,now:e.now??Date.now}),limits:{treeHeaderSample:300,scansTables:1,jsonFiles:300,textFiles:300,sideFileBytes:65536,participantsBytes:1048576,...e.limits},readVersionManifest:e.readVersionManifest??((r,o)=>s7t(r,o,{timeoutMs:n,env:e.awsEnv})),githubToken:e.githubToken??i7t(),...e.readEntryHead?{readEntryHead:e.readEntryHead}:{}}}var GMe=(e,t)=>t.startsWith(`${e.data}/`),a7t=(e,t)=>GMe(e,t)||t.startsWith(`${e.api}/`)?e.breakers.worker:e.breakers.direct;async function c7t(e,t,n){let r=a7t(e,t);r.check();let o=r.pausedUntilMs()-e.now();if(o>0)await e.sleep(o),r.check();try{let s=await n();return r.ok(),s}catch(s){if(s instanceof pr)r.observe(s);throw s}}var l7t=(e,t)=>({...t===void 0?{}:{tries:t},baseMs:e.retryBaseMs,sleep:e.sleep,retryAfterCapMs:e.retryAfterCapMs});var LMe=(e)=>/sub-([^/_]+)/.exec(e)?.[1]??"?";function UMe(e,t,n){if(t<1)return[];if(e.length<=t)return[...e];let r=new Map;for(let c of e){let l=n(c),d=r.get(l);if(d)d.push(c);else r.set(l,[c])}let o=[...r.entries()].sort(([c],[l])=>c<l?-1:c>l?1:0).map(([,c])=>c);if(o.length>t)return Array.from({length:t},(c,l)=>o[Math.floor((l+0.5)*o.length/t)][0]);let s=o.map((c,l)=>({list:c,index:l})).sort((c,l)=>c.list.length-l.list.length||c.index-l.index),i=t,a=[];return s.forEach(({list:c},l)=>{let d=Math.min(c.length,Math.ceil(i/(s.length-l)));for(let p=0;p<d;p++)a.push(c[Math.floor((p+0.5)*c.length/d)]);i-=d}),a}var u7t=(e)=>e.severity==="identifier"&&P$e.has(e.kind),d7t=(e)=>_m.has(e.kind);function VMe(e){return e.headerRead===e.edfCount&&e.incompleteReasons.length===0}function p7t(e){if(e.findings.some(u7t))return"direct-identifiers";if(e.findings.some((t)=>!d7t(t)))return"review";if(!VMe(e))return"unchecked";if(e.edfCount>0&&e.unscreenedCount>0)return"clean-edf-only-others-unscreened";if(e.edfCount===0)return e.unscreenedCount>0?"not-screened":"no-recordings";return e.findings.length>0?"dates-only":"clean"}var f7t=/\.(edf|bdf)$/i,m7t=(e)=>e.edf===!0||f7t.test(e.path);function h7t(e){return{edf:e.filter(m7t),participants:e.find((t)=>t.path==="participants.tsv"),scans:e.filter((t)=>t.path.endsWith("_scans.tsv")),json:e.filter((t)=>t.path.endsWith(".json")).filter((t)=>t.path.startsWith("sourcedata/")||!g7t.test(t.path)).filter((t)=>!y7t.test(t.path)),text:e.filter((t)=>b7t.test(t.path)).filter((t)=>t.path.startsWith("sourcedata/")||t.path.startsWith("code/"))}}var g7t=/_(eeg|ieeg|meg|emg|nirs|beh|events|channels|electrodes|coordsystem|scans|physio|stim|photo|T1w|bold)\.(json|tsv)$/,y7t=/(^|\/)(dataset_description|participants|genetic_info)\.json$/,b7t=/\.(py|m|r|txt|md|ya?ml|xml|iml|cfg|ini)$/i;function WMe(e,t,n,r=0){let o=()=>c7t(e,t.url,()=>{let s={minBytes:r,userAgent:e.userAgent,timeoutMs:e.timeoutMs};return e.readEntryHead?e.readEntryHead(t,n,s):r7t(t.url,n,s)});return t7t(()=>GMe(e,t.url)?e.workerLimit(o):o(),l7t(e))}async function sT(e,t,n){let r=await WMe(e,t,n),o=t.size===null?r.length>=n:t.size>n;return{text:new TextDecoder("utf-8",{fatal:!1}).decode(r),truncated:o}}function u0(e,t){for(let n of t)e.push(n)}var qMe="edf/superseded-absent";async function KMe(e,t,n,r,o,s={}){let i=r.map((Me)=>Me.path),a=o==="clone",c=(Me,De,An)=>a?[...Me]:UMe(Me,De,An),l=[...oA([...i,...s.extraPaths??[]])],d=z$e(i),p=Object.values(d.unscreened).reduce((Me,De)=>Me+De,0),f={},m=(Me,De)=>{if(De instanceof e8)throw De;let An=`${Me}/${e7t(De)}`;f[An]=(f[An]??0)+1},h=(Me)=>LMe(Me.path),g=h7t(r),y=new Set(s.supersededEdf??[]),w=[...g.edf,...y],{participants:x,scans:v,json:S,text:E}=g,C=o==="git-tree"?UMe(w,e.limits.treeHeaderSample,h):[...w],I=0,H=0,P=0,U=0,q={},G=new Set,B=new Set,M=new Set,N=new Set,V=new Set,ie=new Set;await rT(C,e.fileConcurrency,async(Me)=>{try{let De=await WMe(e,Me,Tt,Tt),An=Cp(De),{patient:p0}=nA(De);if(!An.some((hs)=>hs.kind==="edf-unreadable")){G.add(p0);let hs=p0.split(/\s+/);if(hs.length>=4)M.add(hs[0]),V.add(hs[2]),N.add(hs[3])}if(ie.add(LMe(Me.path)),An.some((hs)=>hs.severity==="identifier"))U++,B.add(p0);u0(l,An);for(let hs of new Set(An.map((nh)=>nh.kind)))q[hs]=(q[hs]??0)+1;I++}catch(De){if(y.has(Me)&&De instanceof pr&&De.status===404){P++,f[qMe]=(f[qMe]??0)+1;return}H++,m("edf",De)}});let Ae=w.length-P,Xt=!1,Qe=!1;if(x&&x.size!==0)try{let{text:Me,truncated:De}=await sT(e,x,e.limits.participantsBytes),An=Me.indexOf(`
2920
+ `;AMe(s,a)}console.log(u.dim(" Updated .bidsignore for NEMAR metadata"))}catch(r){console.log(u.yellow(` Warning: Could not update .bidsignore: ${W(r)}`)),console.log(u.dim(" Upload will continue without author enrichment."))}fu(n,"metadata_write"),ro(e,n)}else console.log(u.dim(" Metadata write already completed (skipping)"))}var TMe=1073741824;function qHt(e,t,n=TMe){let r=[],o=0;for(let s of t){let i=e.files[s];if(!i||i.mtimeMs===void 0)continue;r.push({path:s,size:i.size,mtimeMs:i.mtimeMs}),o+=i.size}return o>=n?r:null}function BHt(e,t){return t.filter((n)=>{try{return xo(n.path,LHt(UHt(e,n.path)).size)}catch{return!0}})}function HHt(e){let t=0;for(let n of Object.values(e.files))t+=n.size;return t}function zHt(e){return["Warning: saving dataset changes has produced no stdout or stderr for",`${EA(e)}. git add -A is still running.`,"Wait, or interrupt and rerun the upload; the save step will run again."].join(" ")}async function PMe(e,t,n,r={}){if(!Ra(n,"dataset_save")){let o=A({text:"Saving dataset changes...",...r.spinnerStream?{stream:r.spinnerStream}:{}}).start(),s=r.skipMinBytes??TMe,i=[];if(HHt(n)>=s){let c=r.annexedPaths??null;if(c===null)try{c=await Np(e)}catch(l){console.log(u.dim(` Could not list annexed files (${W(l)}); staging will re-read them`))}if(c!==null)i=BHt(e,qHt(n,c,s)??[])}let a=await ru(e,"Initial NEMAR dataset upload",t,{skipContentCheck:i,onInactivityWarning:(c)=>{o=Px(o,zHt(c))},...r.inactivityWarningAfterMs===void 0?{}:{inactivityWarningAfterMs:r.inactivityWarningAfterMs}});if(!a.success)return ro(e,n),qo(o,"Failed to save dataset",a.error),console.log(),console.log(u.yellow("Re-run the same command to resume from this step.")),Ge;if(r.verifyRemote){let c;try{c=await yq(e,r.verifyRemote)}catch(l){return ro(e,n),qo(o,"Could not confirm the saved files are at the S3 remote",l),console.log(),console.log(u.yellow("Re-run the same command to resume from this step.")),Ge}if(c.length>0){mu(n,"s3_upload"),ro(e,n);let l=xD(c.slice(0,5)),d=c.length>5?` (and ${c.length-5} more)`:"";return qo(o,"Saved files are not at the S3 remote",`${c.length} annexed file(s) in the commit are not recorded at the remote: ${l}${d}. The save itself annexed them, after the upload step had run.`),console.log(),console.log(u.yellow("Re-run the same command: it uploads them and saves again.")),Ge}}o.succeed("Dataset changes saved"),fu(n,"dataset_save"),ro(e,n)}else console.log(u.dim(" Dataset save already completed (skipping)"));return Rn()}async function NMe(e,t){if(!Ra(t,"github_push")){let n=A("Pushing metadata to GitHub...").start(),r=await Rr(e);if(!r.success)return ro(e,t),qo(n,"Failed to push to GitHub",r.error),console.log(),console.log(u.yellow("Re-run the same command to resume from this step.")),Ge;if(r.warning)n.warn("Metadata pushed to GitHub (with warning)"),console.log(u.yellow(` ${r.warning}`));else n.succeed("Metadata pushed to GitHub");fu(t,"github_push"),ro(e,t)}else console.log(u.dim(" GitHub push already completed (skipping)"));return Rn()}async function IMe(e,t,n){if(!Ra(n,"ci_deploy")){let r=A("Setting up BIDS validation CI...").start(),o="configured";try{await tu(t),r.succeed("BIDS validation CI configured")}catch(s){if(o="not-configured",s instanceof j&&s.statusCode===403)r.info("CI workflow will be configured by an admin");else{let i=s instanceof Error?s.message:String(s);r.warn(`Could not configure CI: ${i}`),console.log(u.dim(` An admin can add it later with: nemar admin ci add ${t}`))}}return fu(n,"ci_deploy"),ro(e,n),o}return console.log(u.dim(" CI deploy already completed (skipping)")),"unknown"}function GHt(e,t){let n=e.startsWith("xx");if(t==="not-configured"){if(n)return;console.log("BIDS validation is not set up yet."),console.log(` CI is set up when you request publication: ${u.cyan(`nemar dataset publish request ${e}`)}`),console.log();return}if(console.log("BIDS validation runs on GitHub after the upload."),console.log(` Check it with: ${u.cyan(`nemar dataset ci ${e}`)}`),!n)console.log(` Once it has passed, request publication: ${u.cyan(`nemar dataset publish request ${e}`)}`);console.log()}function FMe(e,t,n="unknown"){Tx(e),NDe(e),console.log(),console.log(u.green.bold("Upload complete!")),console.log(),console.log(` Dataset ID: ${u.cyan(t.dataset_id)}`),console.log(` GitHub: ${u.cyan(t.github_url)}`),console.log(),console.log(u.dim("To download this dataset:")),console.log(u.dim(` nemar dataset download ${t.dataset_id}`)),console.log(),GHt(t.dataset_id,n),console.log(u.yellow("Note: This dataset is private. Only the owner and designated collaborators can")),console.log(u.yellow("download it, and only through the NEMAR CLI (not direct git-annex commands).")),console.log(u.yellow("After publishing, the data will be publicly available for everyone."))}Ip();Rm();async function MMe(e,t={}){let n=await $xe(e.absolutePath);if(!n.success)return console.log(u.red(n.error)),console.log(u.yellow("Re-run the same command to retry.")),Ge;if(n.cleared>0)console.log(u.yellow(` Cleared ${n.cleared} assume-unchanged flag(s) an earlier, interrupted save left on annexed files`));let r=await UDe(e.absolutePath);if(r.status==="error")return console.log(u.red(r.error)),Ge;if(r.status==="warning")console.log(u.yellow(` ${r.warning}`));if(r.status==="restored")console.log(u.yellow(" Put back git-annex's filter process, which an earlier, interrupted upload had left out of this repository's configuration"));let o=await wCe(e.absolutePath,e.options,e.dataFiles,e.filesToUpload,e.uploadProgress,e.datasetInfo,{openRemote:t.openRemote,...t.primeMinBytes===void 0?{}:{primeMinBytes:t.primeMinBytes},...t.primeOnSuspended?{primeOnSuspended:t.primeOnSuspended}:{}});if(o.status==="fail")return Ge;let{progress:s,annexedPaths:i}=o.value;if(OMe(e.absolutePath,e.coAuthorEnrichment,s),(await(t.saveStep??PMe)(e.absolutePath,e.author,s,{annexedPaths:i,verifyRemote:il,...t.skipMinBytes===void 0?{}:{skipMinBytes:t.skipMinBytes},...t.saveInactivityWarningAfterMs===void 0?{}:{inactivityWarningAfterMs:t.saveInactivityWarningAfterMs},...t.saveSpinnerStream===void 0?{}:{spinnerStream:t.saveSpinnerStream}})).status==="fail")return Ge;return Rn(s)}He();du();qm();Dx();wn();Wt();import{randomBytes as $7t}from"crypto";import{constants as s8,accessSync as D7t,chmodSync as C7t,chownSync as A7t,closeSync as l8,copyFileSync as O7t,existsSync as cje,fsyncSync as lje,lstatSync as El,mkdirSync as T7t,mkdtempSync as P7t,openSync as u8,readSync as N7t,readdirSync as I7t,renameSync as F7t,rmSync as d8,rmdirSync as M7t,statSync as uje,writeSync as j7t}from"fs";import{tmpdir as L7t}from"os";import{dirname as lT,join as ja}from"path";He();import{lstatSync as w7t,readdirSync as _7t,statSync as YMe}from"fs";import{open as x7t}from"fs/promises";import{join as JMe}from"path";_s();To();du();var BMe="nemar-identifier-scan/1.0 (+https://docs.nemar.org/policies/takedown/)",VHt="https://api.nemar.org",WHt="https://data.nemar.org",KHt="https://nemar.s3.us-east-2.amazonaws.com",JHt="https://api.github.com";function iT(e,t){if(!Number.isSafeInteger(t)||t<1)throw RangeError(`${e} must be a positive integer, got ${t}`)}async function rT(e,t,n){iT("pool size",t);let r=0,o=Array.from({length:Math.min(t,e.length)},async()=>{while(r<e.length){let a=e[r++];await n(a)}}),i=(await Promise.allSettled(o)).find((a)=>a.status==="rejected");if(i)throw i.reason}function YHt(e){iT("limit",e);let t=0,n=[];return async(r)=>{if(t>=e)await new Promise((o)=>n.push(o));else t++;try{return await r()}finally{let o=n.shift();if(o)o();else t--}}}class pr extends Error{cls;status;retryable;retryAfterMs;constructor(e,t={}){super(e);this.name="ReadFailure",this.cls=e,this.status=t.status,this.retryable=t.retryable??!1,this.retryAfterMs=t.retryAfterMs}}function XHt(e,t=Date.now()){let n=e?.trim();if(!n)return;if(/^\d+$/.test(n))return Number(n)*1000;let r=Date.parse(n);return Number.isNaN(r)?void 0:Math.max(0,r-t)}function ZHt(e,t){let n=e>=500||e===429;return new pr(`http-${e}`,{status:e,retryable:n,retryAfterMs:n?XHt(t):void 0})}class e8 extends Error{constructor(e){super(e);this.name="RunAborted"}}function QHt(e){iT("abort streak",e.streak);let t=e.now??Date.now,n={tripped:null},r=(o)=>{let s=0,i=0,a=(c)=>{throw n.tripped=new e8(c),n.tripped};return{check(){if(n.tripped)throw n.tripped},ok(){s=0},pausedUntilMs(){return i},observe(c){if(n.tripped)throw n.tripped;if(c.retryAfterMs!==void 0&&c.retryAfterMs>e.retryAfterCapMs)a(`${o} asked to wait ${Math.round(c.retryAfterMs/1000)} s (Retry-After), over the ${Math.round(e.retryAfterCapMs/1000)} s cap (${c.cls})`);if(c.retryAfterMs!==void 0)i=Math.max(i,t()+c.retryAfterMs);if(!c.retryable){s=0;return}if(s++,s>=e.streak)a(`${s} consecutive 429, 5xx, timeout or network failures from ${o} (last ${c.cls})`)}}};return{worker:r("the Worker"),direct:r("direct reads")}}function jMe(e){let t=e instanceof Error?e.name:"";return new pr(t==="TimeoutError"||t==="AbortError"?"timeout":"network",{retryable:!0})}function e7t(e){if(e instanceof pr)return e.cls;return`error-${e instanceof Error?e.name:"unknown"}`}async function t7t(e,t={}){let n=t.tries??3,r=t.baseMs??400,o=t.sleep??((s)=>new Promise((i)=>setTimeout(i,s)));iT("tries",n);for(let s=1;;s++)try{return await e()}catch(i){if(!(i instanceof pr&&i.retryable)||s>=n)throw i;let c=i.retryAfterMs??0;if(c>(t.retryAfterCapMs??30000))throw i;await o(Math.max(r*2**(s-1),c))}}async function n7t(e){await e.body?.cancel().catch(()=>{return})}async function r7t(e,t,n={}){let r;try{r=await fetch(e,{headers:{Range:`bytes=0-${t-1}`,"Accept-Encoding":"identity","User-Agent":n.userAgent??BMe},signal:AbortSignal.timeout(n.timeoutMs??30000)})}catch(a){throw jMe(a)}if(r.status!==200&&r.status!==206)throw await n7t(r),ZHt(r.status,r.headers.get("retry-after"));let o=r.body?.getReader();if(!o)throw new pr("no-body");let s=new Uint8Array(t),i=0;try{while(i<t){let{done:a,value:c}=await o.read();if(a||!c)break;let l=Math.min(c.length,t-i);s.set(c.subarray(0,l),i),i+=l}}catch(a){throw jMe(a)}finally{await o.cancel().catch(()=>{return})}if(i<(n.minBytes??0))throw new pr("short-body");return s.subarray(0,i)}var HMe={sideFileBytes:2097152,participantsBytes:16777216};function o7t(e,t){let n=/An error occurred \(([A-Za-z0-9]{1,40})\)/.exec(e)?.[1];if(n)return/^\d+$/.test(n)?`aws/http-${n}`:`aws/error-${n}`;return`aws/exit-${t}`}async function s7t(e,t,n={}){let r;try{let o=Bun.spawn(["aws","s3","cp",`s3://nemar/${e}/version/${t}.json`,"-"],{stdout:"pipe",stderr:"pipe",...n.env?{env:n.env}:{}}),s=!1;r=setTimeout(()=>{s=!0,o.kill("SIGKILL")},n.timeoutMs??600000);let[i,a,c]=await Promise.all([new Response(o.stdout).text(),new Response(o.stderr).text(),o.exited]);if(s)throw new pr("aws/timeout");if(c!==0)throw new pr(o7t(a,c));return i}catch(o){if(o instanceof pr)throw o;throw new pr("aws/unavailable")}finally{clearTimeout(r)}}function i7t(){let e;return async()=>{if(e!==void 0)return e;if(process.env.GITHUB_TOKEN)return e=process.env.GITHUB_TOKEN,e;try{let t=Bun.spawn(["gh","auth","token"],{stdout:"pipe",stderr:"ignore"}),n=(await new Response(t.stdout).text()).trim();e=n===""?null:n}catch{e=null}return e}}var oT=(e)=>e.replace(/\/+$/,"");function zMe(e={}){let t=e.retryAfterCapMs??30000,n=e.awsTimeoutMs??600000;return{api:oT(e.api??process.env.NEMAR_API_BASE??VHt),data:oT(e.data??process.env.NEMAR_DATA_BASE??WHt),s3Base:oT(e.s3Base??KHt),githubApi:oT(e.githubApi??JHt),userAgent:e.userAgent??BMe,fileConcurrency:e.fileConcurrency??24,workerLimit:YHt(e.workerConcurrency??6),timeoutMs:e.timeoutMs??30000,manifestTimeoutMs:e.manifestTimeoutMs??120000,retryBaseMs:e.retryBaseMs??400,sleep:e.sleep??((r)=>new Promise((o)=>setTimeout(o,r))),now:e.now??Date.now,retryAfterCapMs:t,breakers:QHt({streak:e.abortStreak??25,retryAfterCapMs:t,now:e.now??Date.now}),limits:{treeHeaderSample:300,scansTables:1,jsonFiles:300,textFiles:300,sideFileBytes:65536,participantsBytes:1048576,...e.limits},readVersionManifest:e.readVersionManifest??((r,o)=>s7t(r,o,{timeoutMs:n,env:e.awsEnv})),githubToken:e.githubToken??i7t(),...e.readEntryHead?{readEntryHead:e.readEntryHead}:{}}}var GMe=(e,t)=>t.startsWith(`${e.data}/`),a7t=(e,t)=>GMe(e,t)||t.startsWith(`${e.api}/`)?e.breakers.worker:e.breakers.direct;async function c7t(e,t,n){let r=a7t(e,t);r.check();let o=r.pausedUntilMs()-e.now();if(o>0)await e.sleep(o),r.check();try{let s=await n();return r.ok(),s}catch(s){if(s instanceof pr)r.observe(s);throw s}}var l7t=(e,t)=>({...t===void 0?{}:{tries:t},baseMs:e.retryBaseMs,sleep:e.sleep,retryAfterCapMs:e.retryAfterCapMs});var LMe=(e)=>/sub-([^/_]+)/.exec(e)?.[1]??"?";function UMe(e,t,n){if(t<1)return[];if(e.length<=t)return[...e];let r=new Map;for(let c of e){let l=n(c),d=r.get(l);if(d)d.push(c);else r.set(l,[c])}let o=[...r.entries()].sort(([c],[l])=>c<l?-1:c>l?1:0).map(([,c])=>c);if(o.length>t)return Array.from({length:t},(c,l)=>o[Math.floor((l+0.5)*o.length/t)][0]);let s=o.map((c,l)=>({list:c,index:l})).sort((c,l)=>c.list.length-l.list.length||c.index-l.index),i=t,a=[];return s.forEach(({list:c},l)=>{let d=Math.min(c.length,Math.ceil(i/(s.length-l)));for(let p=0;p<d;p++)a.push(c[Math.floor((p+0.5)*c.length/d)]);i-=d}),a}var u7t=(e)=>e.severity==="identifier"&&P$e.has(e.kind),d7t=(e)=>_m.has(e.kind);function VMe(e){return e.headerRead===e.edfCount&&e.incompleteReasons.length===0}function p7t(e){if(e.findings.some(u7t))return"direct-identifiers";if(e.findings.some((t)=>!d7t(t)))return"review";if(!VMe(e))return"unchecked";if(e.edfCount>0&&e.unscreenedCount>0)return"clean-edf-only-others-unscreened";if(e.edfCount===0)return e.unscreenedCount>0?"not-screened":"no-recordings";return e.findings.length>0?"dates-only":"clean"}var f7t=/\.(edf|bdf)$/i,m7t=(e)=>e.edf===!0||f7t.test(e.path);function h7t(e){return{edf:e.filter(m7t),participants:e.find((t)=>t.path==="participants.tsv"),scans:e.filter((t)=>t.path.endsWith("_scans.tsv")),json:e.filter((t)=>t.path.endsWith(".json")).filter((t)=>t.path.startsWith("sourcedata/")||!g7t.test(t.path)).filter((t)=>!y7t.test(t.path)),text:e.filter((t)=>b7t.test(t.path)).filter((t)=>t.path.startsWith("sourcedata/")||t.path.startsWith("code/"))}}var g7t=/_(eeg|ieeg|meg|emg|nirs|beh|events|channels|electrodes|coordsystem|scans|physio|stim|photo|T1w|bold)\.(json|tsv)$/,y7t=/(^|\/)(dataset_description|participants|genetic_info)\.json$/,b7t=/\.(py|m|r|txt|md|ya?ml|xml|iml|cfg|ini)$/i;function WMe(e,t,n,r=0){let o=()=>c7t(e,t.url,()=>{let s={minBytes:r,userAgent:e.userAgent,timeoutMs:e.timeoutMs};return e.readEntryHead?e.readEntryHead(t,n,s):r7t(t.url,n,s)});return t7t(()=>GMe(e,t.url)?e.workerLimit(o):o(),l7t(e))}async function sT(e,t,n){let r=await WMe(e,t,n),o=t.size===null?r.length>=n:t.size>n;return{text:new TextDecoder("utf-8",{fatal:!1}).decode(r),truncated:o}}function u0(e,t){for(let n of t)e.push(n)}var qMe="edf/superseded-absent";async function KMe(e,t,n,r,o,s={}){let i=r.map((Me)=>Me.path),a=o==="clone",c=(Me,De,An)=>a?[...Me]:UMe(Me,De,An),l=[...oA([...i,...s.extraPaths??[]])],d=z$e(i),p=Object.values(d.unscreened).reduce((Me,De)=>Me+De,0),f={},m=(Me,De)=>{if(De instanceof e8)throw De;let An=`${Me}/${e7t(De)}`;f[An]=(f[An]??0)+1},h=(Me)=>LMe(Me.path),g=h7t(r),y=new Set(s.supersededEdf??[]),w=[...g.edf,...y],{participants:x,scans:v,json:S,text:E}=g,C=o==="git-tree"?UMe(w,e.limits.treeHeaderSample,h):[...w],I=0,H=0,P=0,U=0,q={},G=new Set,B=new Set,M=new Set,N=new Set,V=new Set,ie=new Set;await rT(C,e.fileConcurrency,async(Me)=>{try{let De=await WMe(e,Me,Tt,Tt),An=Cp(De),{patient:p0}=nA(De);if(!An.some((hs)=>hs.kind==="edf-unreadable")){G.add(p0);let hs=p0.split(/\s+/);if(hs.length>=4)M.add(hs[0]),V.add(hs[2]),N.add(hs[3])}if(ie.add(LMe(Me.path)),An.some((hs)=>hs.severity==="identifier"))U++,B.add(p0);u0(l,An);for(let hs of new Set(An.map((nh)=>nh.kind)))q[hs]=(q[hs]??0)+1;I++}catch(De){if(y.has(Me)&&De instanceof pr&&De.status===404){P++,f[qMe]=(f[qMe]??0)+1;return}H++,m("edf",De)}});let Ae=w.length-P,Xt=!1,Qe=!1;if(x&&x.size!==0)try{let{text:Me,truncated:De}=await sT(e,x,e.limits.participantsBytes),An=Me.indexOf(`
2921
2921
  `);if(An<0&&De)throw new pr("header-truncated");u0(l,U$e(An<0?Me:Me.slice(0,An))),u0(l,B$e(Me)),Qe=De}catch(Me){Xt=!0,m("participants",Me)}let $e=c(v,e.limits.scansTables,h),ae=0;await rT($e,e.fileConcurrency,async(Me)=>{if(Me.size===0){ae++;return}try{let{text:De}=await sT(e,Me,e.limits.sideFileBytes);u0(l,rA(De)),ae++}catch(De){m("scans",De)}});let Ve=e.limits.sideFileBytes,Oe=(Me)=>Me.size!==null&&Me.size>Ve,re=c(S.filter((Me)=>!Oe(Me)),e.limits.jsonFiles,h),et=c(E.filter((Me)=>!Oe(Me)),e.limits.textFiles,h),Je=0,X=0;await rT(re,e.fileConcurrency,async(Me)=>{if(Me.size===0){Je++;return}try{let{text:De}=await sT(e,Me,Ve),An;try{An=JSON.parse(De)}catch{throw new pr("json-parse")}u0(l,wm(An)),Je++}catch(De){m("json",De)}}),await rT(et,e.fileConcurrency,async(Me)=>{if(Me.size===0){X++;return}try{let{text:De}=await sT(e,Me,Ve);u0(l,H$e(De)),X++}catch(De){m("text",De)}});let Z={edf_headers:{candidates:Ae,oversize:0,selected:C.length-P,scanned:I},scans_tables:{candidates:v.length,oversize:0,selected:$e.length,scanned:ae},json_files:{candidates:S.length,oversize:S.filter(Oe).length,selected:re.length,scanned:Je},text_files:{candidates:E.length,oversize:E.filter(Oe).length,selected:et.length,scanned:X}},pe=new Set,be=(Me,De)=>{if(De.oversize>0)pe.add(`${Me}-oversize`);if(De.candidates-De.oversize>De.selected)pe.add(`${Me}-sampled`);if(De.scanned<De.selected)pe.add(`${Me}-unread`)};if(be("edf-headers",Z.edf_headers),be("json",Z.json_files),be("text",Z.text_files),Z.scans_tables.scanned<Z.scans_tables.selected)pe.add("scans-unread");if(Xt)pe.add("participants-unread");if(Qe)pe.add("participants-truncated");for(let Me of s.extraIncompleteReasons??[])pe.add(Me);let ft=[...pe].sort(),Nt={findings:l,edfCount:Ae,headerRead:I,unscreenedCount:p,incompleteReasons:ft},Fr=l.filter((Me)=>Me.severity==="identifier"),qs=Object.entries(f).filter(([Me])=>!Me.startsWith("edf/")).reduce((Me,[,De])=>Me+De,0);return{id:t,version:n,scanned_at:new Date().toISOString(),manifest_source:o,status:p7t(Nt),incomplete:!VMe(Nt),incomplete_reasons:ft,files:{total:r.length,edf_bdf:Ae,header_read:I,header_read_failed:H},sampling:Z,read_failures:f,edf_bdf_files_flagged:U,distinct_patient_field_values:G.size,distinct_subjects_with_edf_bdf:ie.size,distinct_patient_code_subfield:M.size,distinct_patient_name_subfield:N.size,distinct_patient_birth_subfield:V.size,distinct_patient_field_values_in_flagged_files:B.size,findings_by_kind:G$e(l),edf_bdf_files_by_kind:q,unscreened_formats:d.unscreened,side_reads_failed:qs,finding_fields:[...new Set(Fr.map((Me)=>`${Me.kind}:${Me.field}`))].sort()}}qm();wn();Kf();Rm();var Qm="--acknowledge-identifier-preflight",v7t=16,E7t="local:";function r8(e){let t=[],n=new Map,r=0,o=[""];while(o.length>0){let s=o.pop(),i;try{i=_7t(s===""?e:JMe(e,s),{withFileTypes:!0})}catch{r++;continue}i.sort((c,l)=>c.name<l.name?-1:c.name>l.name?1:0);let a=[];for(let c of i){let l=c.name;if(s===""&&(l===".git"||l===".nemar"))continue;let d=s===""?l:`${s}/${l}`;if(c.isDirectory()){a.push(d);continue}if(l===".gitattributes")continue;let p=`${E7t}${t.length}`,f=JMe(e,d),m=null;try{let h=YMe(f);if(h.isFile())m=h.size,n.set(p,f);else if(h.isDirectory()&&!w7t(f).isSymbolicLink()){a.push(d);continue}}catch{}t.push({path:d,size:m,url:p})}for(let c=a.length-1;c>=0;c--)o.push(a[c])}return{entries:t,readable:n,unlisted:r}}function S7t(e,t=new Map){return async(n,r,o)=>{let s=e.get(n.url);if(s===void 0)throw new pr("unreadable-entry");let i=t.get(s),a;try{a=await x7t(s,"r")}catch{throw new pr("unreadable-entry")}try{let c=n.size===null?r:Math.min(r,n.size),l=new Uint8Array(c),d=0;while(d<c){let{bytesRead:p}=await a.read(l,d,c-d,d);if(p===0)break;d+=p}if(d<o.minBytes)throw new pr("short-body");if(i)l.set(i.subarray(0,Math.min(d,i.length)),0);return l.subarray(0,d)}catch(c){if(c instanceof pr)throw c;throw new pr("unreadable-entry")}finally{await a.close().catch(()=>{return})}}}async function XMe(e,t){let n=r8(e),r=zMe({fileConcurrency:v7t,workerConcurrency:1,limits:{...HMe},readEntryHead:S7t(n.readable,t),githubToken:async()=>null,readVersionManifest:async()=>{throw new pr("unreadable-entry")},sleep:async()=>{return}}),o=await KMe(r,"local",null,n.entries,"clone",{extraIncompleteReasons:n.unlisted>0?["tree-truncated"]:[]}),s={scanned_at:o.scanned_at,status:o.status,incomplete:o.incomplete,incomplete_reasons:o.incomplete_reasons,files:o.files,findings_by_kind:o.findings_by_kind,edf_bdf_files_flagged:o.edf_bdf_files_flagged,unscreened_formats:o.unscreened_formats,read_failures:o.read_failures};return z4(XOe(ZOe(s)))}function cT(e){if(Vp(e.status)!=="acknowledge")return[];let t=new Set([e.status]);if(e.incomplete&&e.status!=="unchecked")t.add("unchecked");let n=Object.values(e.unscreened_formats).reduce((o,s)=>o+s,0),r=e.status==="not-screened"||e.status==="clean-edf-only-others-unscreened";if(n>0&&!r)t.add("not-screened");return[...t].sort()}var ZMe=(e,t)=>e.length===t.length&&e.every((n,r)=>n===t[r]);function QMe(e,t){let n=e.split(",").map((o)=>o.trim()).filter((o)=>o!==""),r=j1;if(n.length===0||!n.every((o)=>r.includes(o)))throw new Br(`Allowed verdicts are ${r.join(", ")}. Direct identifiers cannot be acknowledged.`);return[...t??[],...n]}function k7t(e,t){let n=Vp(e.status);if(n==="clear")return{action:"proceed",acknowledgedVia:null};if(n!=="acknowledge")return{action:"refuse"};if(t.acknowledge!==void 0){let r=[...new Set(t.acknowledge)].sort();return ZMe(r,cT(e))?{action:"proceed",acknowledgedVia:"flag"}:{action:"stop",why:"acknowledgment-mismatch"}}if(t.dryRun)return{action:"preview"};if(t.no)return{action:"stop",why:"declined"};if(t.isTty)return{action:"prompt"};return{action:"stop",why:"acknowledgment-required"}}var R7t={review:"the scanner found something a person should look at (the kinds are listed above)",unchecked:"the scanner could not read everything it should have (see Incomplete above)","not-screened":"some recordings are in formats the scanner cannot read, so their headers were not checked","clean-edf-only-others-unscreened":"the EDF/BDF headers are clean, but other recordings are in formats the scanner cannot read"},t8=(e)=>`${Qm} ${e.join(",")}`;function n8(e){console.log(u.yellow(" This does not stop an upload, but it needs your explicit acknowledgment of:"));for(let t of e)console.log(u.yellow(` ${t}: ${R7t[t]??"not clean"}.`));console.log(u.dim(" Your acknowledgment is recorded with your deposit attestation. NEMAR screens the dataset again when you request publication, and an administrator decides then."))}function eje(){console.log(),console.log(u.red(" Upload refused: the preflight found direct identifiers (a name, a birth date finer than the year, a record number, an age over 89, or an identifying column or key). Nothing was sent.")),console.log(u.red(" Remove them from the files (for EDF/BDF, the patient and recording fields of the header) and run the upload again.")),console.log(u.dim(` There is no override, and ${Qm} does not apply. If this is a false positive, please report it, so the scanner is fixed for every dataset. Terms: ${YO}`))}function tje(e){if(e instanceof I1)return`report-${e.message}`;let t=e instanceof Error&&/^[A-Za-z]{1,40}$/.test(e.name)?e.name:"unknown",n=e?.code;return typeof n==="string"&&/^E[A-Z0-9]{1,20}$/.test(n)?`${t} ${n}`:t}function nje(e,t){e.fail("Identifier preflight: DID NOT FINISH"),console.log(u.red(` The preflight could not produce a verdict, so nothing was uploaded (${tje(t)}).`)),console.log(u.dim(" Please report this: https://github.com/nemarOrg/nemar-cli/issues"))}function aT(e,t,n=""){let r=G4(t,null),o=`${r.headline}${n}`;if(r.tone==="ok")e.succeed(o);else if(r.tone==="stop")e.fail(o);else e.warn(o);for(let s of wl({state:t.status,...r},2).slice(1))console.log(s)}function rje(e,t){try{return Rn(QOe({version:N1,scanner:`nemar-cli@${Qs}`,scan:e,acknowledged_via:t}))}catch(n){return console.log(u.red(` The preflight's record did not fit the report contract (${tje(n)}), so nothing was uploaded.`)),Ge}}async function oje(e,t,n=process.stdin.isTTY===!0,r){let o=A("Screening for identifiers on this machine (nothing is sent)...").start(),s=!1;try{s=YMe(e).isDirectory()}catch{s=!1}if(!s)return o.fail("Identifier preflight: the dataset path is not a directory"),Ge;let i=new Map((r?.items??[]).map((f)=>[f.path,f.after])),a;try{a=await XMe(e,i)}catch(f){return nje(o,f),Ge}aT(o,a);let c=cT(a),l=k7t(a,{acknowledge:t.acknowledgeIdentifierPreflight,dryRun:t.dryRun,no:t.no,isTty:n}),d;switch(l.action){case"proceed":if(l.acknowledgedVia==="flag")console.log(u.dim(` Acknowledged with ${t8(c)}.`));else if(t.acknowledgeIdentifierPreflight!==void 0)console.log(u.dim(` Nothing to acknowledge; ${Qm} was not needed.`));d=l.acknowledgedVia;break;case"preview":return n8(c),console.log(u.yellow(` A real upload stops here until you acknowledge it: answer the prompt, or pass ${t8(c)}.`)),console.log(),Rn(null);case"prompt":{n8(c);let f=!1,m=()=>{console.log(u.red(`
2922
2922
  Upload cancelled. Nothing was sent.`)),ue(),process.exit(130)};process.once("SIGINT",m);let h=setInterval(()=>{return},1000);try{({acknowledged:f}=await Te.prompt([{type:"confirm",name:"acknowledged",message:"Upload anyway?",default:!1}]))}catch{f=!1}finally{clearInterval(h),process.off("SIGINT",m)}if(f!==!0)return console.log(u.red(" Upload cancelled. Nothing was sent.")),ue(),Ge;console.log(u.dim(" Acknowledged at the prompt.")),d="prompt";break}case"refuse":return eje(),ue(),Ge;case"stop":if(l.why==="acknowledgment-mismatch")console.log(u.red(` ${Qm} must name exactly what was found, which is: ${c.join(",")}. It does not acknowledge this scan. Nothing was sent.`));else n8(c),console.log(u.red(l.why==="declined"?" Declined (--no). Nothing was sent.":` No terminal to ask at: run interactively, or pass ${t8(c)}. --yes does not acknowledge a finding. Nothing was sent.`));return ue(),Ge}let p=rje(a,d);if(p.status==="ok")console.log();return p}async function sje(e,t){let n=A("Screening again, right before anything is sent...").start(),r;try{r=await XMe(e)}catch(a){return nje(n,a),Ge}let o=Vp(r.status);if(o!=="clear"&&o!=="acknowledge")return aT(n,r),eje(),ue(),Ge;let s=cT(t.scan),i=cT(r);if(!ZMe(s,i))return aT(n,r),console.log(u.red(` The files changed since the preflight, and so did what it found (acknowledged: ${s.join(",")||"nothing"}; now: ${i.join(",")}). Nothing was sent. Run the upload again.`)),ue(),Ge;if(F1(r.findings_by_kind)!==F1(t.scan.findings_by_kind))aT(n,r," (screened again)");else n.succeed(`${G4(r,null).headline} (screened again)`);return rje(r,t.acknowledged_via)}var U7t=/\.(edf|bdf)$/i,dje=ja(".nemar","date-normalization"),q7t=()=>({tracked:0,"nested-repository":0,ignored:0,"tracking-unknown":0,link:0,"not-writable":0,"other-filesystem":0,unverified:0});function B7t(){return{items:[],left:q7t()}}function H7t(e){if(process.env.GIT_DIR||process.env.GIT_WORK_TREE)return!0;for(let t=e;;t=lT(t)){if(cje(ja(t,".git")))return!0;if(lT(t)===t)return!1}}var i8=(e)=>e.normalize("NFC").toLowerCase();async function o8(e,t,n){try{let r=await T(e,{cwd:t,...n===void 0?{}:{stdin:n}});if(!(r.exitCode===0||e.includes("check-ignore")&&r.exitCode===1))return null;return new Set(r.stdout.split("\x00").filter(Boolean).map(i8))}catch{return null}}async function z7t(e,t){let n=`${t.join("\x00")}\x00`;if(H7t(e)){let o=await o8(["git","ls-files","-z"],e),s=await o8(["git","check-ignore","-z","--stdin"],e,n);return o&&s?{tracked:o,ignored:s}:null}let r=null;try{if(r=P7t(ja(L7t(),"nemar-ignore-")),(await T(["git","init","-q","--bare",r],{cwd:e})).exitCode!==0)return null;let s=await o8(["git",`--git-dir=${r}`,`--work-tree=${e}`,"check-ignore","--no-index","-z","--stdin"],e,n);return s?{tracked:new Set,ignored:s}:null}catch{return null}finally{if(r!==null)try{d8(r,{recursive:!0,force:!0})}catch{}}}function a8(e){let t;try{t=u8(e,"r")}catch{return null}try{let n=new Uint8Array(Tt),r=0;while(r<Tt){let o=N7t(t,n,r,Tt-r,r);if(o===0)break;r+=o}return r===Tt?n:null}catch{return null}finally{try{l8(t)}catch{}}}var ije=(e,t)=>e!==null&&e.length===t.length&&e.every((n,r)=>n===t[r]);function aje(e){try{return D7t(e,s8.W_OK),!0}catch{return!1}}function G7t(e,t,n){let r=t.split("/").slice(0,-1);for(let o=1;o<=r.length;o++){let s=r.slice(0,o).join("/"),i=n.get(s);if(i===void 0){i=cje(ja(e,s,".git"));try{i||=El(ja(e,s,".git")).isSymbolicLink()}catch{}n.set(s,i)}if(i)return!0}return!1}async function pje(e){let t=B7t();try{await V7t(e,t)}catch(n){Ln(`date normalization: planning stopped (${n instanceof Error?n.name:"unknown"})`)}return t}async function V7t(e,t){let n=uje(e).dev,r=r8(e),o=[];for(let c of r.entries){if(!U7t.test(c.path))continue;let l=r.readable.get(c.url);if(l===void 0)continue;let d=a8(l);if(d===null)continue;try{let p=XU(d);if(p.changed)o.push({path:l,rel:c.path,before:d,after:p.header})}catch(p){if(p instanceof Tp)continue;t.left.unverified++,Ln(`date normalization: a header was not planned (${p instanceof Error?p.name:"unknown"})`)}}if(o.length===0)return;let s=await z7t(e,o.map((c)=>c.rel)),i=new Map,a=typeof process.getuid==="function"?process.getuid():null;for(let c of o){if(s===null){t.left["tracking-unknown"]++;continue}if(s.tracked.has(i8(c.rel))){t.left.tracked++;continue}if(G7t(e,c.rel,i)){t.left["nested-repository"]++;continue}if(s.ignored.has(i8(c.rel))){t.left.ignored++;continue}let l;try{l=El(c.path)}catch{continue}if(l.isSymbolicLink()){t.left.link++;continue}if(!l.isFile())continue;if(l.dev!==n){t.left["other-filesystem"]++;continue}if(a!==null&&l.uid!==a||(l.mode&128)===0||!aje(c.path)||!aje(lT(c.path))){t.left["not-writable"]++;continue}t.items.push({path:c.path,rel:c.rel,dev:l.dev,ino:l.ino,size:l.size,mtimeMs:l.mtimeMs,mode:l.mode,gid:l.gid,before:c.before,after:c.after})}}var W7t=/^\d+-[0-9a-f]{16}$/;function K7t(e){try{let t=ja(e,dje);for(let n of[ja(e,".nemar"),t])if(!El(n).isDirectory())return;for(let n of I7t(t))if(W7t.test(n))d8(ja(t,n),{force:!0})}catch{}}function c8(e){for(let t of e)try{M7t(t)}catch{}}function J7t(e,t){let n=[],r=ja(e,dje);try{for(let o of[ja(e,".nemar"),r]){let s;try{s=El(o)}catch{T7t(o),n.push(o),s=El(o)}if(!s.isDirectory()||s.dev!==t)return c8([...n].reverse()),null}return{dir:r,made:n}}catch{return c8([...n].reverse()),null}}function Y7t(e){try{let t=u8(e,"r");try{lje(t)}finally{l8(t)}}catch{}}function X7t(e,t){let n=null;try{let r=(s)=>s.isFile()&&s.dev===e.dev&&s.ino===e.ino&&s.size===e.size&&s.mtimeMs===e.mtimeMs;if(!r(El(e.path))||!ije(a8(e.path),e.before))return null;if(n=ja(t,`${process.pid}-${$7t(8).toString("hex")}`),O7t(e.path,n,s8.COPYFILE_EXCL|s8.COPYFILE_FICLONE),El(n).gid!==e.gid)A7t(n,-1,e.gid);C7t(n,e.mode&4095);let o=u8(n,"r+");try{if(j7t(o,e.after,0,Tt,0)!==Tt)return null;lje(o)}finally{l8(o)}if(El(n).size!==e.size||!ije(a8(n),e.after))return null;if(!r(El(e.path)))return null;return F7t(n,e.path),n=null,Y7t(lT(e.path)),El(e.path).mtimeMs}catch(r){return Ln(`date normalization: a header was not set (${r instanceof Error?r.name:"unknown"})`),null}finally{if(n!==null)try{d8(n,{force:!0})}catch{}}}function fje(e,t){let n={set:0,left:0,mtimes:new Map};if(K7t(e),t.items.length===0)return n;let r=null;try{r=J7t(e,uje(e).dev)}catch{}if(r===null)return n.left=t.items.length,Ln("date normalization: no work directory, nothing set"),n;try{for(let o of t.items){let s=X7t(o,r.dir);if(s===null){n.left++;continue}n.set++,n.mtimes.set(o.rel,s)}}finally{c8([r.dir,...[...r.made].reverse().filter((o)=>o!==r.dir)])}if(n.set>0)console.log(u.dim(` ${KOe(n.set)}`));return n}He();_s();To();import{existsSync as tE,mkdirSync as gzt,readFileSync as nE,writeFileSync as Tje}from"fs";import{basename as yzt,resolve as eh}from"path";qc();Ue();to();_s();import{existsSync as uT,readFileSync as p8,writeFileSync as hje}from"fs";import{resolve as dT}from"path";var f8=[{spdxId:"CC0-1.0",name:"CC0 1.0 Universal (Public Domain)",description:"No rights reserved. Anyone can use the data for any purpose.",url:"https://creativecommons.org/publicdomain/zero/1.0/",allowsResearchUse:!0},{spdxId:"PDDL-1.0",name:"Open Data Commons Public Domain Dedication and License (PDDL)",description:"Database-specific public domain dedication.",url:"https://opendatacommons.org/licenses/pddl/1-0/",allowsResearchUse:!0},{spdxId:"CC-BY-4.0",name:"Creative Commons Attribution 4.0 International",description:"Attribution required. Free for any use including commercial.",url:"https://creativecommons.org/licenses/by/4.0/",allowsResearchUse:!0},{spdxId:"CC-BY-SA-4.0",name:"Creative Commons Attribution-ShareAlike 4.0 International",description:"Attribution + share-alike required. Derivatives must use same license.",url:"https://creativecommons.org/licenses/by-sa/4.0/",allowsResearchUse:!0},{spdxId:"CC-BY-NC-4.0",name:"Creative Commons Attribution-NonCommercial 4.0 International",description:"Attribution required. Non-commercial use only.",url:"https://creativecommons.org/licenses/by-nc/4.0/",allowsResearchUse:!0},{spdxId:"CC-BY-NC-SA-4.0",name:"Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International",description:"Attribution + non-commercial + share-alike required.",url:"https://creativecommons.org/licenses/by-nc-sa/4.0/",allowsResearchUse:!0},{spdxId:"ODC-By-1.0",name:"Open Data Commons Attribution License v1.0",description:"Database-specific attribution license.",url:"https://opendatacommons.org/licenses/by/1.0/",allowsResearchUse:!0},{spdxId:"ODbL-1.0",name:"Open Data Commons Open Database License v1.0",description:"Database attribution + share-alike. Produced works can be any license.",url:"https://opendatacommons.org/licenses/odbl/1.0/",allowsResearchUse:!0}],mje=new Set(["CC0-1.0","CC-BY-4.0","CC-BY-SA-4.0","CC-BY-NC-4.0","CC-BY-NC-SA-4.0","CC-BY-ND-4.0","CC-BY-NC-ND-4.0","PDDL-1.0","ODC-By-1.0","ODbL-1.0","MIT","Apache-2.0","GPL-2.0-only","GPL-2.0-or-later","GPL-3.0-only","GPL-3.0-or-later","LGPL-2.1-only","LGPL-2.1-or-later","LGPL-3.0-only","LGPL-3.0-or-later","BSD-2-Clause","BSD-3-Clause","ISC","Unlicense"]);function gje(e){let t=dT(e,"dataset_description.json");if(uT(t))try{let r=JSON.parse(p8(t,"utf-8"));if(typeof r.License==="string"&&r.License.trim())return{spdxId:r.License.trim(),source:"dataset_description"}}catch(r){if(r instanceof SyntaxError)console.warn(` Warning: dataset_description.json has invalid JSON: ${r.message}`);else console.warn(` Warning: Could not read dataset_description.json: ${r instanceof Error?r.message:String(r)}`)}let n=["LICENSE","LICENSE.txt","LICENSE.md","LICENCE","LICENCE.txt"];for(let r of n){let o=dT(e,r);if(uT(o)){try{let s=p8(o,"utf-8").toLowerCase();if(s.includes("cc0")||s.includes("public domain dedication"))return{spdxId:"CC0-1.0",source:"license_file"};if(s.includes("attribution-noncommercial-sharealike"))return{spdxId:"CC-BY-NC-SA-4.0",source:"license_file"};if(s.includes("attribution-noncommercial"))return{spdxId:"CC-BY-NC-4.0",source:"license_file"};if(s.includes("attribution-sharealike"))return{spdxId:"CC-BY-SA-4.0",source:"license_file"};if(s.includes("creativecommons")&&s.includes("attribution"))return{spdxId:"CC-BY-4.0",source:"license_file"};if(s.includes("open database license")||s.includes("odbl"))return{spdxId:"ODbL-1.0",source:"license_file"};if(s.includes("open data commons")&&s.includes("attribution"))return{spdxId:"ODC-By-1.0",source:"license_file"};if(s.includes("public domain dedication and license")||s.includes("pddl"))return{spdxId:"PDDL-1.0",source:"license_file"};if(s.includes("permission is hereby granted, free of charge")||s.includes("mit license"))return{spdxId:"MIT",source:"license_file"}}catch(s){console.warn(` Warning: Could not read ${r}: ${s instanceof Error?s.message:String(s)}`)}return{spdxId:void 0,source:"license_file"}}}return{spdxId:void 0,source:"none"}}async function m8(e){let t=f8.map((o)=>({name:`${o.spdxId.padEnd(22)} ${o.description}`,value:o.spdxId,short:o.spdxId}));t.push({name:"Other (enter SPDX ID manually)",value:"__custom__",short:"Custom"});let n=e?f8.find((o)=>o.spdxId===e)?.spdxId:void 0,{selected:r}=await Te.prompt([{type:"list",name:"selected",message:"Select a license for this dataset:",choices:t,default:n,pageSize:t.length}]);if(r==="__custom__"){let{customId:o}=await Te.prompt([{type:"input",name:"customId",message:"Enter SPDX license ID (e.g., MIT, Apache-2.0):",validate:(s)=>{if(!s.trim())return"License ID is required";return!0}}]);return o.trim()}return r}function yje(e){let t=e.toUpperCase().replace(/\s+/g,"-");if(mje.has(e))return!0;for(let n of mje)if(n.toUpperCase()===t)return!0;return!1}function Z7t(e){let t=f8.find((n)=>n.spdxId===e);if(t)return`${t.name}
2923
2923
 
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.39-dev.4765",
4
+ "version": "0.10.40-PR2304.2ba3060",
5
5
  "description": "CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",
6
6
  "type": "module",
7
7
  "main": "dist/index.js",