nemar-cli 0.10.4-PR1411.bc2413e → 0.10.4-PR1411.fda7839

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +7 -6
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -99,7 +99,7 @@ ${t}`,T2e,N2e,j2e=(e,t,r)=>{let n=r===""?"":`with ${r.trim()}() `,o=I2e.bind(nul
99
99
  `)}var ZD=!1;var{spawn:yMe}=globalThis.Bun;async function C(e,t={}){let r={...process.env,GIT_TERMINAL_PROMPT:"0",...t.env};for(let u of t.unsetEnv??[])delete r[u];let n=yMe({cmd:e,cwd:t.cwd,...t.stdin===void 0?{}:{stdin:new TextEncoder().encode(t.stdin)},stdout:"pipe",stderr:"pipe",env:r}),o=!1,i;if(t.timeout)i=setTimeout(()=>{o=!0,n.kill()},t.timeout);if(QD()){let u=t.cwd?` (cwd=${t.cwd})`:"";Af(l.dim(`$ ${e.join(" ")}${u}`))}let s=await new Response(n.stdout).text(),a=await new Response(n.stderr).text(),c=await n.exited;if(i)clearTimeout(i);if(QD()){if(s.trim())Af(l.dim(s.trimEnd()));if(a.trim())Af(l.yellow(a.trimEnd()));Af(l.dim(`(exit ${c})`))}if(o)return{stdout:s,stderr:a||`Command timed out after ${Math.round(t.timeout/1000)}s`,exitCode:c??1,timedOut:!0};return{stdout:s,stderr:a,exitCode:c,timedOut:!1}}var At=O(()=>{Xe()});function bMe(){if(process.platform==="darwin")return"macos";if(process.platform==="win32")return"windows";return"linux"}function PK(e,t=bMe()){return e.installInstructions[t]}function _Me(e){let t=e.match(/(\d+\.\d+(?:\.\d+)?)/);return t?t[1]:void 0}function wMe(){let e=Number(process.env.TEST_PROBE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:vMe}async function IK(e){try{let{exitCode:t,stdout:r,timedOut:n}=await C(e.cmd,{timeout:wMe()});if(n)return{available:!1,timedOut:!0};if(t!==0)return{available:!1};return{available:!0,version:_Me(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 Of(){let e=Object.entries(FK);return Promise.all(e.map(async([t,r])=>{let{available:n,version:o,timedOut:i}=await IK(r);return{key:t,name:r.name,purpose:r.purpose,required:r.required,available:n,version:o,timedOut:i,installInstruction:PK(r)}}))}async function TK(){let t=(await Of()).filter((r)=>r.required&&!r.available);if(t.length===0)return[];console.warn(`
100
100
  Heads up: some tools NEMAR needs for uploading/validating aren't installed yet:`);for(let r of t)console.warn(` - ${r.name} (${r.purpose})`),console.warn(` Install: ${r.installInstruction}`);return console.warn("Run `nemar doctor` anytime to re-check. You can finish signup without them.\n"),t}async function Sa(e){let r=xMe[e].map((s)=>FK[s]).filter(Boolean),n=await Promise.all(r.map(async(s)=>{let a=await IK(s);return{check:s,available:a.available,timedOut:a.timedOut}}));for(let s of n)if(s.timedOut&&s.check.required)console.warn(`Warning: ${s.check.name} did not respond to a version check in time; continuing anyway.`);let o=n.filter((s)=>!s.available&&!s.timedOut&&s.check.required).map((s)=>({tool:s.check.name,installInstruction:PK(s.check)}));if(o.length===0)return;let i=[`
101
101
  Missing required tools:`];for(let s of o)i.push(` ${s.tool} not installed`),i.push(` Install: ${s.installInstruction}`);throw Error(i.join(`
102
- `))}var FK,xMe,vMe=4000;var Ff=O(()=>{At();FK={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)"}}},xMe={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 jK;var NK=O(()=>{jK={name:"nemar-cli",version:"0.10.4-PR1411.bc2413e",description:"CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",type:"module",main:"dist/index.js",bin:{nemar:"dist/index.js"},scripts:{dev:"bun run src/index.ts",build:"bun build src/index.ts --outdir dist --target bun --minify && sed '1s|#!/usr/bin/env node|#!/usr/bin/env bun|' dist/index.js > dist/index.js.tmp && mv dist/index.js.tmp dist/index.js",test:"bun test",lint:"biome check src/","migrations:d1-check":"bun run scripts/d1-migration-check.ts","zarr:geometry-check":"bun run backend/scripts/zarr-geometry-conformance.ts","lint:fix":"biome check --fix src/",format:"biome format --write src/",typecheck:"tsc --noEmit && tsc --noEmit -p backend","generate-openapi":"bun run scripts/generate-openapi.ts",prepublishOnly:"bun run build",prepare:"husky",postinstall:"bun scripts/postinstall-check.mjs",deploy:"wrangler deploy",preview:"wrangler dev"},keywords:["nemar","bids","neuroimaging","eeg","emg","datalad","cli"],author:"NEMAR Team",license:"CC-BY-NC-ND-4.0",repository:{type:"git",url:"git+https://github.com/nemarOrg/nemar-cli.git"},bugs:{url:"https://github.com/nemarOrg/nemar-cli/issues"},homepage:"https://docs.nemar.org",engines:{bun:">=1.0.0"},files:["dist","scripts/postinstall-check.mjs","scripts/recover-datasets.json","scripts/withdrawn-datasets.json","README.md","LICENSE"],dependencies:{chalk:"^5.3.0",commander:"^12.1.0",conf:"^13.0.1",inquirer:"^9.2.15",ora:"^8.0.1",semver:"^7.8.5",zod:"^3.23.8"},"lint-staged":{"src/**/*.{ts,tsx}":["biome check --fix"],"backend/src/**/*.{ts,tsx}":["biome check --fix"]},devDependencies:{"@asteasolutions/zod-to-openapi":"^7.3.4","@biomejs/biome":"1.9.4","@types/bun":"latest","@types/inquirer":"^9.0.7","@types/semver":"^7.8.0",ajv:"^8.20.0","ajv-formats":"^3.0.1",bcryptjs:"^3.0.3",husky:"^9.1.7","lint-staged":"^16.3.2",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var bi;var Pf=O(()=>{NK();bi=jK.version});import{mkdirSync as EMe,readdirSync as SMe,unlinkSync as $Me,writeFileSync as CMe}from"fs";import{join as eE}from"path";function zK(){El=!0}function $a(){return El}function VK(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function Tf(e){UK=e,$r(`Step: ${e}`)}function Nf(){LK=!0}function GK(){return LK}function rE(){BK=!0}function HK(){return BK}function $r(e){if(El)process.stderr.write(`[debug] ${e}
102
+ `))}var FK,xMe,vMe=4000;var Ff=O(()=>{At();FK={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)"}}},xMe={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 jK;var NK=O(()=>{jK={name:"nemar-cli",version:"0.10.4-PR1411.fda7839",description:"CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",type:"module",main:"dist/index.js",bin:{nemar:"dist/index.js"},scripts:{dev:"bun run src/index.ts",build:"bun build src/index.ts --outdir dist --target bun --minify && sed '1s|#!/usr/bin/env node|#!/usr/bin/env bun|' dist/index.js > dist/index.js.tmp && mv dist/index.js.tmp dist/index.js",test:"bun test",lint:"biome check src/","migrations:d1-check":"bun run scripts/d1-migration-check.ts","zarr:geometry-check":"bun run backend/scripts/zarr-geometry-conformance.ts","lint:fix":"biome check --fix src/",format:"biome format --write src/",typecheck:"tsc --noEmit && tsc --noEmit -p backend","generate-openapi":"bun run scripts/generate-openapi.ts",prepublishOnly:"bun run build",prepare:"husky",postinstall:"bun scripts/postinstall-check.mjs",deploy:"wrangler deploy",preview:"wrangler dev"},keywords:["nemar","bids","neuroimaging","eeg","emg","datalad","cli"],author:"NEMAR Team",license:"CC-BY-NC-ND-4.0",repository:{type:"git",url:"git+https://github.com/nemarOrg/nemar-cli.git"},bugs:{url:"https://github.com/nemarOrg/nemar-cli/issues"},homepage:"https://docs.nemar.org",engines:{bun:">=1.0.0"},files:["dist","scripts/postinstall-check.mjs","scripts/recover-datasets.json","scripts/withdrawn-datasets.json","README.md","LICENSE"],dependencies:{chalk:"^5.3.0",commander:"^12.1.0",conf:"^13.0.1",inquirer:"^9.2.15",ora:"^8.0.1",semver:"^7.8.5",zod:"^3.23.8"},"lint-staged":{"src/**/*.{ts,tsx}":["biome check --fix"],"backend/src/**/*.{ts,tsx}":["biome check --fix"]},devDependencies:{"@asteasolutions/zod-to-openapi":"^7.3.4","@biomejs/biome":"1.9.4","@types/bun":"latest","@types/inquirer":"^9.0.7","@types/semver":"^7.8.0",ajv:"^8.20.0","ajv-formats":"^3.0.1",bcryptjs:"^3.0.3",husky:"^9.1.7","lint-staged":"^16.3.2",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var bi;var Pf=O(()=>{NK();bi=jK.version});import{mkdirSync as EMe,readdirSync as SMe,unlinkSync as $Me,writeFileSync as CMe}from"fs";import{join as eE}from"path";function zK(){El=!0}function $a(){return El}function VK(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function Tf(e){UK=e,$r(`Step: ${e}`)}function Nf(){LK=!0}function GK(){return LK}function rE(){BK=!0}function HK(){return BK}function $r(e){if(El)process.stderr.write(`[debug] ${e}
103
103
  `)}function OMe(e){let t={};for(let[r,n]of Object.entries(e))t[r]=AMe.has(r.toLowerCase())?"[REDACTED]":n;return t}function KK(e){let t=e.indexOf("@");if(t<=0)return"***";return`${e[0]}***${e.slice(t)}`}function tE(e,t,r=0){if(r>PMe)return"[REDACTED: depth]";if(Array.isArray(t))return t.map((n)=>tE(e,n,r+1));if(t&&typeof t==="object"){let n={};for(let[o,i]of Object.entries(t))n[o]=tE(o,i,r+1);return n}if(typeof t==="string"){if(FMe.test(e))return"[REDACTED]";return t.replace(WK,KK)}return t}function nE(e){return e.replace(IMe,"Bearer [REDACTED]").replace(TMe,"[REDACTED_AWS_KEY]").replace(NMe,"$1[REDACTED]").replace(jMe,"$1$2=[REDACTED]").replace(WK,KK)}function qMe(e){return nE(e)}function qK(e,t=RMe){if(e===void 0)return;let r=e;try{let n=JSON.parse(e);r=JSON.stringify(tE("",n))}catch{}if(r=nE(r),Buffer.byteLength(r,"utf8")>t)r=`${Buffer.from(r,"utf8").subarray(0,t).toString("utf8")}... [truncated]`;return r}function w0(e){if(!El)return;let t=qMe(e.url);try{let r={...e,url:t,requestHeaders:e.requestHeaders?OMe(e.requestHeaders):void 0,requestBody:qK(e.requestBody),responseBody:qK(e.responseBody)};v0.push(r),$r(`${e.method} ${t} -> ${e.status??"ERROR"} (${e.durationMs}ms)`)}catch(r){let n=T(r);v0.push({method:e.method,url:t,status:e.status,durationMs:e.durationMs,note:`redaction failed: ${n}`}),$r(`redaction failed for ${e.method} ${t}: ${n}`)}}async function MMe(){let e=[];try{let t=process.versions.bun?`Bun ${process.versions.bun}`:`Node ${process.version}`;e.push(`CLI version: ${bi}`),e.push(`OS/Arch: ${process.platform}/${process.arch}`),e.push(`Runtime: ${t}`)}catch(t){e.push(`(could not read CLI/OS/runtime info: ${T(t)})`)}e.push(""),e.push("Active account:");try{let t=ot();if(t.apiKey){if(t.username)e.push(` Username: ${t.username}`);if(e.push(` API URL: ${t.apiUrl}`),t.role)e.push(` Role: ${t.role}`);e.push(` Sandbox completed: ${!!t.sandboxCompleted}`)}else e.push(" (not authenticated)")}catch(t){e.push(` (could not read account config: ${T(t)})`)}e.push(""),e.push("External tools:");try{let t=await Of();for(let r of t){let n=r.available?r.version??"installed":r.timedOut?"(timed out)":"not installed";e.push(` ${r.name}: ${n}`)}}catch(t){e.push(` (could not probe external tools: ${T(t)})`)}return e}async function oE(){return(await MMe()).join(`
104
104
  `)}async function YK(){if(!El||_0!==void 0)return;try{_0=await oE()}catch(e){let t=T(e);_0=`(could not build environment report: ${t})`,$r(`environment snapshot failed: ${t}`)}}function JK(e){if(MK.has(e))return{flag:e};for(let t of MK){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 LMe(e){let t=[];for(let r=0;r<e.length;r++){let n=e[r],o=JK(n);if(!o){t.push(n);continue}if(o.kind==="long-eq")t.push(`${o.flag}=[REDACTED]`);else if(o.kind==="short-attached")t.push(`${o.flag}[REDACTED]`);else if(t.push(n),r+1<e.length)t.push("[REDACTED]"),r++}return t}function BMe(e){let t=[];for(let r=0;r<e.length;r++){let n=e[r],o=JK(n);if(!o){t.push(n);continue}if(!o.kind&&r+1<e.length)r++}return t}function UMe(e){let t=[];for(let n of BMe(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 zMe(e,t){let r=[];if(r.push("NEMAR CLI Debug Log"),r.push(`Generated: ${new Date().toISOString()}`),r.push(`Command: nemar ${nE(LMe(e).join(" "))}`),r.push(""),r.push(_0??"(environment snapshot unavailable)"),r.push(""),r.push("HTTP requests:"),v0.length===0)r.push(" (none)");else v0.forEach((n,o)=>{if(r.push(` [${o+1}] ${n.method} ${n.url} -> ${n.status??"ERROR"} (${n.durationMs}ms)`),n.error)r.push(` Error: ${n.error}`);if(n.note)r.push(` Note: ${n.note}`);if(n.requestHeaders)r.push(` Request headers: ${JSON.stringify(n.requestHeaders)}`);if(n.requestBody)r.push(` Request body: ${n.requestBody}`);if(n.responseBody)r.push(` Response body: ${n.responseBody}`)});return r.push(""),r.push(`Failing step: ${UK??"(none recorded)"}`),r.push(`Exit code: ${t}`),`${r.join(`
105
105
  `)}
@@ -175,17 +175,18 @@ Import and publish complete: ${e} -> ${n}`)),console.log(l.dim(` GitHub: https:
175
175
  `)[0]||void 0;return o.exitCode===0?{present:a,absent:c,unconfirmed:[],method:n,detail:u}:{present:a,absent:[],unconfirmed:c,method:n,detail:u}}}async function _Ge(e){let t=[];for(let r of["main","git-annex"]){let n=await C(["git","rev-parse","--verify","--quiet",`refs/heads/${r}`],{cwd:e});if(n.exitCode!==0)continue;let o=await C(["git","rev-parse","--verify","--quiet",`refs/remotes/origin/${r}`],{cwd:e});if(o.exitCode!==0||n.stdout.trim()!==o.stdout.trim())t.push(r)}return t}async function vGe(e,t){let{stdout:r,exitCode:n}=await C(["git","show","git-annex:remote.log"],{cwd:e});if(n!==0)return null;for(let o of r.split(`
176
176
  `)){if(!o.includes(`name=${t}`))continue;let i=o.split(/\s+/)[0];if(/^[0-9a-f-]{36}$/.test(i))return i}return null}function wGe(e){return async({datasetPath:t,files:r})=>{let n=Oa(e.workDir,"upload-staging");lee(n,{recursive:!0,force:!0}),pGe(n,{recursive:!0});try{let o=new Set;for(let d of r){if(o.has(d.key))continue;o.add(d.key);let f=await C(["git","annex","contentlocation",d.key],{cwd:t});if(f.exitCode!==0||!f.stdout.trim())throw Error(`git-annex cannot locate the content it just took for ${d.path} (${d.key}). Not uploading: the key would be registered with nothing behind it.`);let m=await C(["ln",Oa(t,f.stdout.trim()),Oa(n,d.key)],{});if(m.exitCode!==0)throw Error(`Could not stage ${d.key} for upload: ${m.stderr.trim()}`)}let i=`s3://${e.bucket}/${e.datasetId}/objects/`,s=await C(["aws","s3","sync",n,i,"--region",e.region,"--size-only","--only-show-errors"],{});if(s.exitCode!==0)throw Error(`aws s3 sync to ${i} failed: ${(s.stderr||s.stdout).trim().slice(0,600)}. Not committing: the pushed tree would name keys with no content behind them.`);let a=await Ps(t,r.map((d)=>d.key),e.remoteUuid);if(a.failed>0)throw Error(`Uploaded ${r.length} object(s) but ${a.failed} key registration(s) failed. Not committing: clones could not find content that is actually there.`);let c=await $i(e.bucket,`${e.datasetId}/objects/`,e.region),u=r.filter((d)=>!Hl(d.key,c));if(u.length>0)throw Error(`${u.length} of ${r.length} object(s) are absent from ${i} or the wrong size (${u.slice(0,3).map((d)=>d.path).join(", ")}${u.length>3?", ...":""}). Not committing.`);return{copied:r.length}}finally{lee(n,{recursive:!0,force:!0})}}}var uee="nemar-s3";var x2=O(()=>{wi();Nl();Mo();At();Ei();eo();uy();ip();np()});import{cpSync as DGe,existsSync as w2,mkdirSync as EGe,mkdtempSync as pee,readFileSync as SGe,rmSync as b2,writeFileSync as _2}from"fs";import{tmpdir as mee}from"os";import{join as ki,resolve as v2}from"path";function mr(e,...t){if(e.verbose)console.log(" ",...t)}async function gee(e,t){let r=performance.now();try{return await t(),{name:e,passed:!0,duration_ms:Math.round(performance.now()-r)}}catch(n){let o=n instanceof Error?n.message:String(n);return{name:e,passed:!1,duration_ms:Math.round(performance.now()-r),error:o}}}async function $Ge(e){let t=[];for(let{name:r,fn:n}of e){let o=await gee(r,n);if(t.push(o),!o.passed)break}return t}function rn(e,t){if(!e.success)throw Error(`${t}: ${e.error}`)}function hee(e){if(!e.creds)throw Error("credentials not yet fetched");return e.creds}function CGe(){let e=[v2(__dirname,"../../test/fixtures/bids-minimal"),v2(__dirname,"../test/fixtures/bids-minimal"),v2(process.cwd(),"test/fixtures/bids-minimal")];for(let t of e)if(w2(t))return t;throw Error("Could not find test/fixtures/bids-minimal. Run from the nemar-cli root directory.")}async function yee(e){let t=e.verbose??!1,r=performance.now(),n=pee(ki(mee(),"nemar-e2e-upload-")),o=pee(ki(mee(),"nemar-e2e-clone-")),i={uploadDir:n,cloneDir:o,verbose:t},s=[];if(!e.skipReset)s.push({name:"Reset nm099999",fn:async()=>{let c=await DY(Fa);if(mr(i,`S3 objects deleted: ${c.steps.s3_deleted}`),mr(i,`GitHub recreated: ${c.steps.github_recreated}`),mr(i,`D1 cleaned: ${c.steps.d1_cleaned}`),!c.success){let u=[];if(!c.steps.github_recreated)u.push("GitHub");if(!c.steps.d1_cleaned)u.push("D1");throw Error(`Reset partially failed: ${u.join(", ")}`)}}});s.push({name:"Prepare upload",fn:async()=>{let c=CGe();DGe(c,n,{recursive:!0});for(let u of[".git",".nemar",".gitattributes"]){let d=ki(n,u);if(w2(d)){let f=await C(["chmod","-R","u+w",d]);if(f.exitCode!==0)console.warn(`chmod failed for ${d} (exit ${f.exitCode}): ${f.stderr}`);b2(d,{recursive:!0,force:!0})}}mr(i,`Copied fixtures to ${n}`)}},{name:"Init git + annex",fn:async()=>{rn(await Bl(n,{force:!0}),"initDataset"),rn(await Os(n),"configureLargefiles"),mr(i,"Git + git-annex initialized")}},{name:"Configure remotes",fn:async()=>{i.creds=await dr(Fa),mr(i,`S3 prefix: ${i.creds.s3.prefix}`),rn(await kr(n,{name:"nemar-s3",bucket:i.creds.s3.bucket,prefix:`${Fa}/objects`,region:i.creds.s3.region,publicUrl:`https://${i.creds.s3.bucket}.s3.${i.creds.s3.region}.amazonaws.com/${Fa}/objects`},Mt(i.creds.credentials)),"configureS3Remote");let c=`git@github.com:nemarDatasets/${Fa}.git`;rn(await No(n,c),"configureGitHubRemote"),mr(i,"S3 + GitHub remotes configured")}},{name:"Upload to S3",fn:async()=>{rn(await Si(n),"gitAnnexAdd"),rn(await Di(n,"Initial BIDS dataset"),"saveDataset");let c=await Bo(n,"nemar-s3",4,Mt(hee(i).credentials));rn(c,"copyToAnnexRemote"),mr(i,`Files copied to S3: ${c.filesCopied}`),await pr(n)}},{name:"Push to GitHub",fn:async()=>{let c=await jt(n);if(rn(c,"pushToGitHub"),c.warning)mr(i,`Warning: ${c.warning}`);mr(i,"Pushed to GitHub (main + git-annex branches)")}},{name:"Clone fresh",fn:async()=>{let c=`git@github.com:nemarDatasets/${Fa}.git`;rn(await fr(c,o),"cloneDataset");let u=await jl(o,"nemar-s3");if(!u.success)throw Error(`enableS3Remote: ${u.error}`);mr(i,`Clone at ${o}, S3 remote enabled: ${u.enabled}`)}},{name:"Download + verify",fn:async()=>{let c=Mt(hee(i).credentials),u={AWS_ACCESS_KEY_ID:c.accessKeyId,AWS_SECRET_ACCESS_KEY:c.secretAccessKey};if(c.sessionToken)u.AWS_SESSION_TOKEN=c.sessionToken;let{stdout:d,stderr:f,exitCode:m}=await C(["git","annex","get","."],{cwd:o,env:u});if(m!==0)throw Error(`getDatasetData: ${f.trim()}`);let p=d.match(/^get .+ ok$/gm);mr(i,`Files downloaded: ${p?p.length:0}`);let g=ki(o,"sub-01/eeg/sub-01_task-rest_eeg.edf");if(!w2(g))throw Error("EDF file not found after download");let{size:y}=Bun.file(g);if(y<512)throw Error(`EDF file too small: ${y} bytes`);mr(i,`EDF file verified: ${y} bytes`)}},{name:"Update cycle",fn:async()=>{let c=ki(o,"sub-02/eeg");EGe(c,{recursive:!0});let u=Buffer.alloc(1024);u.write("0".padEnd(8),0,"ascii"),_2(ki(c,"sub-02_task-rest_eeg.edf"),u),_2(ki(c,"sub-02_task-rest_eeg.json"),JSON.stringify({TaskName:"rest",SamplingFrequency:256}));let d=SGe(ki(o,"participants.tsv"),"utf-8");_2(ki(o,"participants.tsv"),`${d.trimEnd()}
177
177
  sub-02 30 F
178
- `);let f=`e2e-update-${Date.now()}`,{exitCode:m}=await C(["git","checkout","-b",f],{cwd:o});if(m!==0)throw Error("Failed to create update branch");rn(await Si(o),"gitAnnexAdd (update)"),rn(await Di(o,"Add sub-02"),"saveDataset (update)"),i.creds=await dr(Fa);let p=await Bo(o,"nemar-s3",4,Mt(i.creds.credentials));rn(p,"copyToAnnexRemote (update)"),mr(i,`Update files copied to S3: ${p.filesCopied}`),await pr(o);let g=await jt(o,"origin",f);rn(g,"pushToGitHub (update branch)");let{exitCode:y,stderr:x}=await C(["git","push","origin","git-annex"],{cwd:o});if(y!==0)throw Error(`Failed to push git-annex branch: ${x.trim()}`);mr(i,`Update pushed to branch: ${f}`)}});let a=await $Ge(s);if(!e.skipCleanup&&a.every((c)=>c.passed))a.push(await gee("Cleanup",async()=>{await C(["chmod","-R","u+w",n]),await C(["chmod","-R","u+w",o]),b2(n,{recursive:!0,force:!0}),b2(o,{recursive:!0,force:!0}),mr(i,"Temp directories cleaned up")}));return kGe(a,r,n,o,e.skipCleanup)}function kGe(e,t,r,n,o){let i={passed:e.every((s)=>s.passed),steps:e,total_duration_ms:Math.round(performance.now()-t)};if(o)i.upload_dir=r,i.clone_dir=n;return i}var __dirname="/home/runner/work/nemar-cli/nemar-cli/src/lib",Fa="nm099999";var xee=O(()=>{Rl();wi();Mo();jo();Aa();At();Ei();eo()});import{existsSync as RGe,mkdtempSync as AGe,readFileSync as _ee,writeFileSync as OGe}from"fs";import{tmpdir as FGe}from"os";import{join as xy}from"path";function PGe(e){let t=typeof e.Name==="string"?e.Name:"",{DatasetDOI:r,...n}=e;return{...n,Name:`[TEST COPY] ${t}`}}function IGe(e,t,r){let n=`${t}/`;if(!e.startsWith(n))throw Error(`Key "${e}" does not start with expected source prefix "${n}"`);return`${r}/${e.slice(n.length)}`}function TGe(e){if(!Array.isArray(e))throw Error("Exemplar fleet file must be a JSON array");return e.map((t,r)=>{if(typeof t!=="object"||t===null)throw Error(`Fleet entry ${r} is not an object`);let{xx_id:n,source_id:o,modality:i,note:s}=t;if(typeof n!=="string"||!wee.test(n))throw Error(`Fleet entry ${r}: xx_id "${n}" must match xx099900-xx099999`);if(typeof o!=="string"||!Dee.test(o))throw Error(`Fleet entry ${r} (${n}): source_id "${o}" must be an nm/on dataset id`);if(typeof i!=="string"||i.length===0)throw Error(`Fleet entry ${r} (${n}): modality is required`);if(s!==void 0&&typeof s!=="string")throw Error(`Fleet entry ${r} (${n}): note must be a string when present`);return{xx_id:n,source_id:o,modality:i,...s!==void 0?{note:s}:{}}})}function cp(e){let t;try{t=JSON.parse(_ee(e,"utf-8"))}catch(r){throw Error(`Failed to read/parse exemplar fleet file at ${e}: ${r instanceof Error?r.message:String(r)}`)}return TGe(t)}function NGe(){let e=process.env.AWS_ACCESS_KEY_ID,t=process.env.AWS_SECRET_ACCESS_KEY;if(!e||!t)throw Error("AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY must be set in environment for S3 operations");return{accessKeyId:e,secretAccessKey:t,sessionToken:process.env.AWS_SESSION_TOKEN}}function jGe(e){let t=xy(e,"dataset_description.json");if(!RGe(t))throw Error(`dataset_description.json not found at ${t}`);try{return JSON.parse(_ee(t,"utf-8"))}catch(r){throw Error(`Failed to parse dataset_description.json at ${t}: ${r instanceof Error?r.message:String(r)}`)}}async function qGe(e){let{stdout:t,exitCode:r}=await C(["git","tag","-l"],{cwd:e});if(r!==0)return;let n=t.trim().split(`
178
+ `);let f=`e2e-update-${Date.now()}`,{exitCode:m}=await C(["git","checkout","-b",f],{cwd:o});if(m!==0)throw Error("Failed to create update branch");rn(await Si(o),"gitAnnexAdd (update)"),rn(await Di(o,"Add sub-02"),"saveDataset (update)"),i.creds=await dr(Fa);let p=await Bo(o,"nemar-s3",4,Mt(i.creds.credentials));rn(p,"copyToAnnexRemote (update)"),mr(i,`Update files copied to S3: ${p.filesCopied}`),await pr(o);let g=await jt(o,"origin",f);rn(g,"pushToGitHub (update branch)");let{exitCode:y,stderr:x}=await C(["git","push","origin","git-annex"],{cwd:o});if(y!==0)throw Error(`Failed to push git-annex branch: ${x.trim()}`);mr(i,`Update pushed to branch: ${f}`)}});let a=await $Ge(s);if(!e.skipCleanup&&a.every((c)=>c.passed))a.push(await gee("Cleanup",async()=>{await C(["chmod","-R","u+w",n]),await C(["chmod","-R","u+w",o]),b2(n,{recursive:!0,force:!0}),b2(o,{recursive:!0,force:!0}),mr(i,"Temp directories cleaned up")}));return kGe(a,r,n,o,e.skipCleanup)}function kGe(e,t,r,n,o){let i={passed:e.every((s)=>s.passed),steps:e,total_duration_ms:Math.round(performance.now()-t)};if(o)i.upload_dir=r,i.clone_dir=n;return i}var __dirname="/home/runner/work/nemar-cli/nemar-cli/src/lib",Fa="nm099999";var xee=O(()=>{Rl();wi();Mo();jo();Aa();At();Ei();eo()});import{existsSync as RGe,mkdtempSync as AGe,readFileSync as _ee,writeFileSync as OGe}from"fs";import{tmpdir as FGe}from"os";import{join as xy}from"path";function PGe(e){let t=typeof e.Name==="string"?e.Name:"",{DatasetDOI:r,...n}=e;return{...n,Name:`[TEST COPY] ${t}`}}function IGe(e,t,r){let n=`${t}/`;if(!e.startsWith(n))throw Error(`Key "${e}" does not start with expected source prefix "${n}"`);return`${r}/${e.slice(n.length)}`}function TGe(e){if(!Array.isArray(e))throw Error("Exemplar fleet file must be a JSON array");let t=e.map((n,o)=>{if(typeof n!=="object"||n===null)throw Error(`Fleet entry ${o} is not an object`);let{xx_id:i,source_id:s,modality:a,note:c}=n;if(typeof i!=="string"||!wee.test(i))throw Error(`Fleet entry ${o}: xx_id "${i}" must match xx099900-xx099999`);if(typeof s!=="string"||!Dee.test(s))throw Error(`Fleet entry ${o} (${i}): source_id "${s}" must be an nm/on dataset id`);if(typeof a!=="string"||a.length===0)throw Error(`Fleet entry ${o} (${i}): modality is required`);if(c!==void 0&&typeof c!=="string")throw Error(`Fleet entry ${o} (${i}): note must be a string when present`);let{anonymous:u}=n;if(u!==void 0&&u!==!0)throw Error(`Fleet entry ${o} (${i}): anonymous must be omitted or literally true, not ${JSON.stringify(u)}`);return{xx_id:i,source_id:s,modality:a,...u===!0?{anonymous:!0}:{},...c!==void 0?{note:c}:{}}}),r=t.filter((n)=>n.anonymous);if(r.length>1)throw Error(`Fleet declares ${r.length} anonymous exemplars (${r.map((n)=>n.xx_id).join(", ")}); exactly one is allowed`);return t}function cp(e){let t;try{t=JSON.parse(_ee(e,"utf-8"))}catch(r){throw Error(`Failed to read/parse exemplar fleet file at ${e}: ${r instanceof Error?r.message:String(r)}`)}return TGe(t)}function NGe(){let e=process.env.AWS_ACCESS_KEY_ID,t=process.env.AWS_SECRET_ACCESS_KEY;if(!e||!t)throw Error("AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY must be set in environment for S3 operations");return{accessKeyId:e,secretAccessKey:t,sessionToken:process.env.AWS_SESSION_TOKEN}}function jGe(e){let t=xy(e,"dataset_description.json");if(!RGe(t))throw Error(`dataset_description.json not found at ${t}`);try{return JSON.parse(_ee(t,"utf-8"))}catch(r){throw Error(`Failed to parse dataset_description.json at ${t}: ${r instanceof Error?r.message:String(r)}`)}}async function qGe(e){let{stdout:t,exitCode:r}=await C(["git","tag","-l"],{cwd:e});if(r!==0)return;let n=t.trim().split(`
179
179
  `).filter(Boolean);if(n.length===0)return;let o=await C(["git","tag","-d",...n],{cwd:e});if(o.exitCode!==0)console.warn(l.yellow(` Warning: failed to strip local tags: ${o.stderr.trim()}`))}function LGe(e){return e!==MGe}async function Eee(e,t,r){let n=`${e}/${r}`;return[...(await $i(bee,n,Pa)).keys()].filter(LGe).map((i)=>{let s=`${n}${i}`,a=IGe(s,e,t);return{key:i,source:{bucket:bee,key:s,region:Pa},httpUrl:null,destUri:`s3://${ap}/${a}`}})}function BGe(e,t){return fy(e,t,py(e))}async function D2(e,t,r,n){let o=await Eee(e,t,r);if(o.length===0)return console.log(l.dim(` [${n}] nothing to copy`)),[];let i=await $i(ap,`${t}/${r}`,Pa),{toCopy:s,skipped:a}=BGe(o,i);if(s.length===0)return console.log(l.green(` [${n}] nothing to copy (all ${a.length} present)`)),o.map((d)=>d.key);let c=D(`[${n}] copying ${s.length} files...`).start(),u=await rp(s,Pa,vee,(d,f)=>{c.text=`[${n}] ${d}/${f}`});if(u.failed.length>0){c.fail(`[${n}] ${u.failed.length} of ${s.length} files failed`);for(let d of u.failed.slice(0,5))console.error(l.red(` ${d.key}: ${d.error}`));throw console.error(l.red(`Re-run to resume [${n}] (already-copied objects are skipped).`)),Error(`[${n}] ${u.failed.length} of ${s.length} files failed to copy: ${u.failed.slice(0,5).map((d)=>`${d.key}: ${d.error}`).join("; ")}`)}return c.succeed(`[${n}] copied ${u.copied}, skipped ${a.length}`),o.map((d)=>d.key)}async function UGe(e,t,r={}){if(!wee.test(e))throw Error(`Invalid exemplar id "${e}". Expected xx099900-xx099999.`);if(!Dee.test(t))throw Error(`Invalid source id "${t}". Expected an nm/on dataset id.`);let n=r.workDir||AGe(xy(FGe(),`nemar-exemplar-${e}-`)),o=xy(n,e);console.log(l.cyan(`
180
180
  [prepare] ${t} -> ${e}
181
181
  `)),console.log(l.dim(`Working directory: ${n}`));let i=D(`Cloning ${t}...`).start(),s=`https://github.com/${sp}/${t}.git`,a=await fr(s,o);if(!a.success){let I=`Failed to clone: ${a.error}`;throw i.fail(I),Error(I)}i.succeed(`Cloned ${t}`),await qGe(o);let c=D("Scrubbing dataset_description.json...").start(),u=jGe(o),d=PGe(u);OGe(xy(o,"dataset_description.json"),`${JSON.stringify(d,null,2)}
182
- `);let f=await C(["git","add","dataset_description.json"],{cwd:o});if(f.exitCode!==0){let I=`Failed to stage scrubbed metadata: ${f.stderr.trim()}`;throw c.fail(I),Error(I)}let m=await C(["git","commit","-m",`Scrub dataset_description.json for exemplar clone (source: ${t})`],{cwd:o});if(m.exitCode!==0&&!m.stdout.includes("nothing to commit")){let I=`Failed to commit scrubbed metadata: ${m.stderr.trim()}`;throw c.fail(I),Error(I)}c.succeed("Scrubbed dataset_description.json");let p=r.name||(typeof d.Name==="string"?d.Name:void 0),g=D("Creating exemplar dataset record...").start();try{let I=await CY({dataset_id:e,source_id:t,name:p,description:r.description});g.succeed(`Created ${I.dataset_id} (${I.github_repo})`)}catch(I){let L=I instanceof Error?I.message:String(I),G=I instanceof q&&I.statusCode===409;if(G&&L.includes("Dataset"))g.warn(`Exemplar ${e} already exists, continuing...`);else if(G){let ie=`GitHub repo for ${e} exists but has no dataset record \u2014 a previous run failed between repo creation and the D1 insert. Delete the orphan with 'nemar admin delete-dataset ${e}' (or remove the repo manually) and re-run. Original: ${L}`;throw g.fail(ie),Error(ie)}else{let ie=`Failed to create exemplar: ${L}`;throw g.fail(ie),Error(ie)}}await ny(o,(I,L)=>{console.log(l.yellow(` Warning: could not mark ${I} as annex-ignore (${L}). Run 'git config remote.${I}.annex-ignore true' manually.`))},["nemar-s3"]);let y=D("Configuring nemar-s3-dev remote...").start(),x=NGe(),_=await kr(o,{name:"nemar-s3-dev",bucket:ap,prefix:`${e}/objects`,region:Pa},x);if(!_.success){let I=`Failed to configure nemar-s3-dev: ${_.error}`;throw y.fail(I),Error(I)}let w=await Fs(o,"nemar-s3-dev");if(!w)throw y.fail("Failed to get nemar-s3-dev remote UUID"),Error("Failed to get nemar-s3-dev remote UUID");y.succeed("Configured nemar-s3-dev remote");let S=D("Configuring NEMAR remote...").start(),A=await C(["git","remote","remove","origin"],{cwd:o});if(A.exitCode!==0&&!A.stderr.includes("No such remote")){let I=`Failed to remove source remote: ${A.stderr.trim()}`;throw S.fail(I),Error(I)}let E=`git@github.com:${sp}/${e}.git`,F=await No(o,E,"origin");if(!F.success){let I=`Failed to configure remote: ${F.error}`;throw S.fail(I),Error(I)}S.succeed("Configured NEMAR remote");let k=D(`Pushing to ${sp}...`).start(),M=await jt(o,"origin");if(!M.success){let I=`Failed to push: ${M.error}`;throw k.fail(I),Error(I)}if(M.warning){let I=`Pushed main but git-annex branch failed: ${M.warning}. Aborting \u2014 the exemplar would be uncloneable.`;throw k.fail(I),Error(I)}return k.succeed(`Pushed to ${sp}`),console.log(l.green(`[prepare] done: ${e}`)),{datasetPath:o,xxId:e,sourceId:t,nemarS3DevUuid:w}}async function zGe(e,t={}){let{xxId:r,sourceId:n}=e;console.log(l.cyan(`
182
+ `);let f=await C(["git","add","dataset_description.json"],{cwd:o});if(f.exitCode!==0){let I=`Failed to stage scrubbed metadata: ${f.stderr.trim()}`;throw c.fail(I),Error(I)}let m=await C(["git","commit","-m",`Scrub dataset_description.json for exemplar clone (source: ${t})`],{cwd:o});if(m.exitCode!==0&&!m.stdout.includes("nothing to commit")){let I=`Failed to commit scrubbed metadata: ${m.stderr.trim()}`;throw c.fail(I),Error(I)}c.succeed("Scrubbed dataset_description.json");let p=r.name||(typeof d.Name==="string"?d.Name:void 0),g=D("Creating exemplar dataset record...").start();try{let I=await CY({dataset_id:e,source_id:t,name:p,description:r.description,...r.anonymous?{anonymous:!0}:{}});g.succeed(`Created ${I.dataset_id} (${I.github_repo})`)}catch(I){let L=I instanceof Error?I.message:String(I),G=I instanceof q&&I.statusCode===409;if(G&&L.includes("Dataset"))g.warn(`Exemplar ${e} already exists, continuing...`);else if(G){let ie=`GitHub repo for ${e} exists but has no dataset record \u2014 a previous run failed between repo creation and the D1 insert. Delete the orphan with 'nemar admin delete-dataset ${e}' (or remove the repo manually) and re-run. Original: ${L}`;throw g.fail(ie),Error(ie)}else{let ie=`Failed to create exemplar: ${L}`;throw g.fail(ie),Error(ie)}}await ny(o,(I,L)=>{console.log(l.yellow(` Warning: could not mark ${I} as annex-ignore (${L}). Run 'git config remote.${I}.annex-ignore true' manually.`))},["nemar-s3"]);let y=D("Configuring nemar-s3-dev remote...").start(),x=NGe(),_=await kr(o,{name:"nemar-s3-dev",bucket:ap,prefix:`${e}/objects`,region:Pa},x);if(!_.success){let I=`Failed to configure nemar-s3-dev: ${_.error}`;throw y.fail(I),Error(I)}let w=await Fs(o,"nemar-s3-dev");if(!w)throw y.fail("Failed to get nemar-s3-dev remote UUID"),Error("Failed to get nemar-s3-dev remote UUID");y.succeed("Configured nemar-s3-dev remote");let S=D("Configuring NEMAR remote...").start(),A=await C(["git","remote","remove","origin"],{cwd:o});if(A.exitCode!==0&&!A.stderr.includes("No such remote")){let I=`Failed to remove source remote: ${A.stderr.trim()}`;throw S.fail(I),Error(I)}let E=`git@github.com:${sp}/${e}.git`,F=await No(o,E,"origin");if(!F.success){let I=`Failed to configure remote: ${F.error}`;throw S.fail(I),Error(I)}S.succeed("Configured NEMAR remote");let k=D(`Pushing to ${sp}...`).start(),M=await jt(o,"origin");if(!M.success){let I=`Failed to push: ${M.error}`;throw k.fail(I),Error(I)}if(M.warning){let I=`Pushed main but git-annex branch failed: ${M.warning}. Aborting \u2014 the exemplar would be uncloneable.`;throw k.fail(I),Error(I)}return k.succeed(`Pushed to ${sp}`),console.log(l.green(`[prepare] done: ${e}`)),{datasetPath:o,xxId:e,sourceId:t,nemarS3DevUuid:w}}async function zGe(e,t={}){let{xxId:r,sourceId:n}=e;console.log(l.cyan(`
183
183
  [copy] ${n} -> ${r}
184
184
  `));let o=await D2(n,r,"objects/","objects");if(t.includeDerived){await D2(n,r,"zarr/","zarr"),await D2(n,r,"archives/","archives");let s=(await Eee(n,r,"version/")).filter((a)=>a.key.endsWith("-records.json"));if(s.length>0){let a=D(`[records.json] copying ${s.length} file(s)...`).start(),c=await rp(s,Pa,vee);if(c.failed.length>0)throw a.fail(`[records.json] ${c.failed.length} of ${s.length} failed`),Error(`[records.json] ${c.failed.length} of ${s.length} file(s) failed to copy: ${c.failed.slice(0,5).map((u)=>`${u.key}: ${u.error}`).join("; ")}`);a.succeed(`[records.json] copied ${c.copied}`)}}return{keys:o}}function VGe(e,t){return e.filter((r)=>!Hl(r,t))}async function GGe(e,t,r={}){let{datasetPath:n,xxId:o,sourceId:i,nemarS3DevUuid:s}=e;if(console.log(l.cyan(`
185
185
  [finalize] ${i} -> ${o}
186
- `)),t.keys.length>0){let w=D("Verifying copied data...").start(),S=await $i(ap,`${o}/objects/`,Pa),A=VGe(t.keys,S);if(A.length>0){let L=`${A.length} of ${t.keys.length} objects missing at s3://${ap}/${o}/objects/. Re-run the copy phase before finalizing.`;throw w.fail(L),Error(L)}w.succeed(`Verified ${t.keys.length} objects present`);let E=await Fs(n,"nemar-s3-dev");if(E!==s){let L=`nemar-s3-dev uuid drifted (prepare=${s} now=${E}). Aborting before registering keys against the wrong remote.`;throw console.error(l.red(L)),Error(L)}let F=D("Registering files in git-annex...").start(),k=await Ps(n,t.keys,s);if(k.failed>0){let L=`${k.failed} of ${t.keys.length} git-annex key registrations are not in the location log (e.g. ${k.missing.slice(0,3).join(", ")}). Re-run finalize to retry.`;throw F.fail(L),Error(L)}F.succeed(`Registered ${k.success} files in git-annex`);let M=D("Pushing git-annex branch...").start(),I=await jt(n,"origin");if(!I.success){let L=`Failed to push git-annex branch: ${I.error}`;throw M.fail(L),Error(L)}if(I.warning){let L=`git-annex branch push failed: ${I.warning}`;throw M.fail(L),Error(L)}M.succeed("Pushed git-annex branch")}let a=!1,c=D("Deploying CI workflows...").start();try{await vi(o),c.succeed("CI workflows deployed (BIDS validation, LLM enrichment, archive generation)"),a=!0}catch(w){let S=w instanceof Error?w.message:String(w);c.fail(`CI deployment failed: ${S}`),console.log(l.dim(` After fixing the deploy failure, run 'nemar admin ci add ${o}'.`))}if(a){let w=D("Waiting for BIDS validation run to register...").start(),S=await p2(o,w);if(S.kind==="found")w.succeed("BIDS validation run registered");else if(S.kind==="timeout")w.warn("BIDS validation run did not register within 120s; continuing (ci_check retries at approval).");else{let A=S.lastError instanceof Error?S.lastError.message:String(S.lastError);w.fail(`BIDS validation polls failed: ${A}`)}}let u=!1,d=D("Refreshing metadata + LLM enrichment...").start();try{let w=await Cl(o),S=w.enrichment?.status==="ok",A=w.sync?.metadata_columns_written===!0;if(u=S&&A,u)d.succeed("Refreshed enrichment + metadata columns");else d.warn(`Partial reindex (run 'nemar admin reindex ${o}' to retry)`)}catch(w){let S=w instanceof Error?w.message:String(w);d.warn(`Reindex failed (non-fatal): ${S}`)}if(!r.publish){console.log(l.green(`
186
+ `)),t.keys.length>0){let w=D("Verifying copied data...").start(),S=await $i(ap,`${o}/objects/`,Pa),A=VGe(t.keys,S);if(A.length>0){let L=`${A.length} of ${t.keys.length} objects missing at s3://${ap}/${o}/objects/. Re-run the copy phase before finalizing.`;throw w.fail(L),Error(L)}w.succeed(`Verified ${t.keys.length} objects present`);let E=await Fs(n,"nemar-s3-dev");if(E!==s){let L=`nemar-s3-dev uuid drifted (prepare=${s} now=${E}). Aborting before registering keys against the wrong remote.`;throw console.error(l.red(L)),Error(L)}let F=D("Registering files in git-annex...").start(),k=await Ps(n,t.keys,s);if(k.failed>0){let L=`${k.failed} of ${t.keys.length} git-annex key registrations are not in the location log (e.g. ${k.missing.slice(0,3).join(", ")}). Re-run finalize to retry.`;throw F.fail(L),Error(L)}F.succeed(`Registered ${k.success} files in git-annex`);let M=D("Pushing git-annex branch...").start(),I=await jt(n,"origin");if(!I.success){let L=`Failed to push git-annex branch: ${I.error}`;throw M.fail(L),Error(L)}if(I.warning){let L=`git-annex branch push failed: ${I.warning}`;throw M.fail(L),Error(L)}M.succeed("Pushed git-annex branch")}let a=!1,c=D("Deploying CI workflows...").start();try{await vi(o),c.succeed("CI workflows deployed (BIDS validation, LLM enrichment, archive generation)"),a=!0}catch(w){let S=w instanceof Error?w.message:String(w);c.fail(`CI deployment failed: ${S}`),console.log(l.dim(` After fixing the deploy failure, run 'nemar admin ci add ${o}'.`))}if(a){let w=D("Waiting for BIDS validation run to register...").start(),S=await p2(o,w);if(S.kind==="found")w.succeed("BIDS validation run registered");else if(S.kind==="timeout")w.warn("BIDS validation run did not register within 120s; continuing (ci_check retries at approval).");else{let A=S.lastError instanceof Error?S.lastError.message:String(S.lastError);w.fail(`BIDS validation polls failed: ${A}`)}}let u=!1,d=D("Refreshing metadata + LLM enrichment...").start();try{let w=await Cl(o),S=w.enrichment?.status==="ok",A=w.sync?.metadata_columns_written===!0;if(u=S&&A,u)d.succeed("Refreshed enrichment + metadata columns");else d.warn(`Partial reindex (run 'nemar admin reindex ${o}' to retry)`)}catch(w){let S=w instanceof Error?w.message:String(w);d.warn(`Reindex failed (non-fatal): ${S}`)}if(r.anonymous){console.log(l.green(`
187
+ Exemplar clone complete: ${i} -> ${o} (anonymous deposit; never published).`));return}if(!r.publish){console.log(l.green(`
187
188
  Exemplar clone complete: ${i} -> ${o} (not published; re-run with --publish).`));return}if(!u)throw Error(`Refusing to publish ${o}: metadata reindex did not fully succeed, so .nemar/metadata.json may still carry the source dataset's real identity. Re-run 'nemar admin reindex ${o}' until it succeeds, then 'nemar admin publish request/approve ${o}' to publish manually.`);let f=5,m=300000,p=D("Requesting publication...").start(),g=!1;for(let w=1;w<=f;w++)try{await Ol(o),g=!0;break}catch(S){let A=S instanceof Error?S.message:String(S);if(!A.includes("BIDS validation is currently running")){let E=`Failed to request publication: ${A}`;throw p.fail(E),Error(E)}if(w===f){let E=`BIDS validation still running after ${f} attempts. Re-run 'nemar admin publish request/approve ${o}' once validation completes.`;throw p.fail(E),Error(E)}p.text=`Waiting for BIDS validation to complete... (attempt ${w}/${f})`,await new Promise((E)=>setTimeout(E,m))}if(g)p.succeed("Publication requested");let y=D("Approving publication (sandbox DOI)...").start(),x=10,_=!1;for(let w=1;w<=x;w++)try{await Fl(o,w>1,!0),_=!0;break}catch(S){let A=S instanceof Error?S.message:String(S);if(w<x)y.text=`Approving publication... (attempt ${w+1}/${x})`,await new Promise((E)=>setTimeout(E,3000));else{let E=`Failed to approve publication after ${x} attempts: ${A}`;throw y.fail(E),Error(E)}}if(_)y.succeed("Publication approved (sandbox DOI)");console.log(l.green(`
188
- Exemplar clone + publish complete: ${i} -> ${o}`)),console.log(l.dim(` GitHub: https://github.com/${sp}/${o}`))}async function E2(e){let t=await UGe(e.xxId,e.sourceId,{workDir:e.workDir,name:e.name,description:e.description}),r=await zGe(t,{includeDerived:e.includeDerived});await GGe(t,r,{publish:e.publish})}var sp="nemarDatasets",bee="nemar",ap="nemar-dev",Pa="us-east-2",vee=16,wee,Dee,MGe="annex-uuid";var S2=O(()=>{Xe();Nn();Rl();Pt();Uf();Mo();jo();At();Ei();eo();ip();np();wee=/^xx0999\d{2}$/,Dee=/^(nm|on)\d{6}$/});import{rmSync as HGe}from"fs";function lp(e){let t=!$2(e),r=e.gitResidentData.length>0;if(t&&r)return"policy-and-data";if(r)return"data";if(t)return"policy";return"compliant"}function KGe(e){let t=new Map;for(let n of e.split(`
189
+ Exemplar clone + publish complete: ${i} -> ${o}`)),console.log(l.dim(` GitHub: https://github.com/${sp}/${o}`))}async function E2(e){let t=await UGe(e.xxId,e.sourceId,{workDir:e.workDir,name:e.name,description:e.description,...e.anonymous?{anonymous:!0}:{}}),r=await zGe(t,{includeDerived:e.includeDerived});await GGe(t,r,{publish:e.publish,...e.anonymous?{anonymous:!0}:{}})}var sp="nemarDatasets",bee="nemar",ap="nemar-dev",Pa="us-east-2",vee=16,wee,Dee,MGe="annex-uuid";var S2=O(()=>{Xe();Nn();Rl();Pt();Uf();Mo();jo();At();Ei();eo();ip();np();wee=/^xx0999\d{2}$/,Dee=/^(nm|on)\d{6}$/});import{rmSync as HGe}from"fs";function lp(e){let t=!$2(e),r=e.gitResidentData.length>0;if(t&&r)return"policy-and-data";if(r)return"data";if(t)return"policy";return"compliant"}function KGe(e){let t=new Map;for(let n of e.split(`
189
190
  `)){let o=n.match(/^(\d+(?:\.\d+)?)s\s+(\S+)\s*(.*)$/);if(!o)continue;let[,i,s,a]=o,c=Number(i),u=a.trim(),d=t.get(s);if(!d||d.at<=c)t.set(s,{at:c,value:u})}let r=new Map;for(let[n,{value:o}]of t)if(o!=="")r.set(n,o);return r}function YGe(e){let t=[];for(let[s,a]of e.attributeContents){let c=ep(a);if(c.stripped===0&&c.skipped.length===0)continue;t.push({path:s,rulesRemoved:c.stripped,declined:c.skipped})}t.sort((s,a)=>s.path.localeCompare(a.path));let n=(e.configLog?KGe(e.configLog):new Map).get("annex.largefiles")??null,o=[],i=[];for(let s of e.entries){if(s.mode!=="100644"&&s.mode!=="100755")continue;let a=s.size??Number.POSITIVE_INFINITY;if(!Ml(s.path,a))continue;if(a<=C2){i.push(s.path);continue}o.push({path:s.path,size:a})}return{datasetId:e.datasetId,attributeFiles:t,policyConfigured:n===ql(),configuredExpression:n,gitResidentData:o,pointerSuspects:i,treeTruncated:e.treeTruncated}}function JGe(e){return e.filter((t)=>t.path===".gitattributes"||t.path.endsWith("/.gitattributes")).map((t)=>t.path).sort()}async function Cee(e={}){let t=e.baseUrl??"https://api.github.com",r=process.env.GH_TOKEN?.trim()||process.env.GITHUB_TOKEN?.trim()||"";if(!r){let{stdout:n,exitCode:o,stderr:i}=await C(["gh","auth","token"]);if(o!==0||!n.trim())throw Error(`No GitHub token available: set GH_TOKEN, or run \`gh auth login\` (gh said: ${i.trim()||`exit ${o}`}). A sweep of the fleet cannot run on the anonymous rate limit.`);r=n.trim()}return{async get(n){let o=`${t}/${n.replace(/^\//,"")}`,i="";for(let s=0;s<3;s++){let a;try{a=await fetch(o,{headers:{Authorization:`Bearer ${r}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"nemar-cli fleet annex-policy sweep"}})}catch(c){i=c instanceof Error?c.message:String(c),await new Promise((u)=>setTimeout(u,500*(s+1)));continue}if(a.status===403||a.status===429){let c=a.headers.get("x-ratelimit-remaining"),u=a.headers.get("x-ratelimit-reset");if(c==="0"){let d=u?new Date(Number(u)*1000).toISOString():"unknown";throw new Uo(`GitHub rate limit exhausted; it resets at ${d}. Re-run the sweep after that, or narrow it with --limit.`,a.status,!0)}}if(a.status>=500||a.status===429){i=`HTTP ${a.status}`,await new Promise((c)=>setTimeout(c,500*(s+1)));continue}return{status:a.status,body:await a.text()}}throw new Uo(`GET ${n} failed after 3 attempts: ${i}`,0)}}}function See(e,t){let r=JSON.parse(e);if(r.encoding!=="base64"||typeof r.content!=="string")throw Error(`${t}: expected a base64 blob, got encoding=${r.encoding}`);return Buffer.from(r.content.replace(/\n/g,""),"base64").toString("utf8")}async function by(e,t,r={}){let n=r.branch??"main",o=`repos/${WGe}/${e}`,i=await t.get(`${o}/git/trees/${n}?recursive=1`);if(i.status!==200)throw new Uo(`Could not read ${e}'s ${n} tree: HTTP ${i.status}`,i.status);let s=JSON.parse(i.body),a=(s.tree??[]).filter((m)=>m.type==="blob"),c=a.map((m)=>({path:m.path,mode:m.mode,size:m.size})),u=new Map;for(let m of JGe(c)){let p=a.find((y)=>y.path===m)?.sha;if(!p)continue;let g=await t.get(`${o}/git/blobs/${p}`);if(g.status!==200)throw new Uo(`Could not read ${e}:${m} (blob ${p.slice(0,8)}): HTTP ${g.status}`,g.status);u.set(m,See(g.body,`${e}:${m}`))}let d=await t.get(`${o}/contents/config.log?ref=git-annex`),f=null;if(d.status===200)f=See(d.body,`${e}:git-annex:config.log`);else if(d.status!==404)throw new Uo(`Could not read ${e}'s git-annex config.log: HTTP ${d.status}`,d.status);return YGe({datasetId:e,entries:c,treeTruncated:Boolean(s.truncated),attributeContents:u,configLog:f})}async function XGe(e){await C(["chmod","-R","u+w",e]),HGe(e,{recursive:!0,force:!0})}async function kee(e,t,r){let n=await by(e,t),o=lp(n);if(o==="compliant")return{datasetId:e,before:n,action:"compliant"};if((o==="data"||o==="policy-and-data")&&!r.includeData)return{datasetId:e,before:n,action:"skipped-has-data",notes:[`${n.gitResidentData.length} file(s) NEMAR policy calls data are in git; that needs the S3 leg (nemar admin annex-normalize ${e})`]};let i=`${r.workRoot.replace(/\/$/,"")}/${e}`;try{let s=await gy(e,{workDir:r.workRoot,originUrl:r.originUrl});if(s.files.length>0&&!r.includeData)return{datasetId:e,before:n,action:"skipped-has-data",notes:[`the clone found ${s.files.length} data file(s) in git that the tree listing did not; re-run with --include-data or use nemar admin annex-normalize ${e}`]};let a=await yy(s,{push:r.push!==!1,credentials:r.credentials,maxBytes:r.maxBytes});if(!a.committed&&!a.pushed)return{datasetId:e,before:n,action:"compliant",committed:!1,pushed:!1,notes:[...a.notes,"the clone found nothing to change"]};let c;if(r.push!==!1)try{c=await ZGe(e,t)}catch(d){if(d instanceof Uo&&d.fatal)throw d;return{datasetId:e,before:n,action:"unverified",committed:a.committed,pushed:a.pushed,notes:[...a.notes,`pushed, but the read-back could not be completed: ${d instanceof Error?d.message:String(d)}. Re-run the read-only report for this dataset to confirm.`]}}let u=[...a.notes];if(c?.remainingDeclined.length)u.push(`left alone: ${c.remainingDeclined.join(", ")} (a quoted pattern the strip will not split; fix by hand)`);return{datasetId:e,before:n,action:c===void 0||c.landed?"applied":"unverified",committed:a.committed,pushed:a.pushed,notes:u,after:c?.state}}catch(s){return{datasetId:e,before:n,action:"failed",error:s instanceof Error?s.message:String(s)}}finally{if(!r.keepClone)try{await XGe(i)}catch{}}}async function ZGe(e,t,r={}){let n=r.attempts??3,o=r.delayMs??3000,i=await by(e,t);for(let s=1;s<n;s++){if($2(i))break;await new Promise((a)=>setTimeout(a,o)),i=await by(e,t)}return{landed:$2(i),state:i,remainingDeclined:i.attributeFiles.filter((s)=>s.declined.length>0).map((s)=>s.path)}}function $2(e){if(e.treeTruncated)return!1;return e.policyConfigured&&e.attributeFiles.every((t)=>t.rulesRemoved===0)}function $ee(e){let t={compliant:[],policy:[],"policy-and-data":[],data:[]},r=[],n=[],o=[];for(let i of e)if(i.state){if(n.push(i.state),t[lp(i.state)].push(i.datasetId),i.state.treeTruncated)o.push(i.datasetId)}else if(i.error)r.push({datasetId:i.datasetId,error:i.error});return{scanned:n.length,byLabel:t,truncated:o,failed:r,states:n}}async function Ree(e,t,r={}){let n=[];await QGe(e,r.concurrency??4,async(i)=>{try{let s=await by(i,t);r.onResult?.({datasetId:i,state:s}),n.push({datasetId:i,state:s})}catch(s){if(s instanceof Uo&&s.fatal)throw new _y(s,$ee(n));let a=s instanceof Error?s.message:String(s);r.onResult?.({datasetId:i,error:a}),n.push({datasetId:i,error:a})}});let o=new Map(e.map((i,s)=>[i,s]));return n.sort((i,s)=>(o.get(i.datasetId)??0)-(o.get(s.datasetId)??0)),$ee(n)}function Aee(e,t){let r=t.prefix??"on",n=t.exclude??new Set,o=e.map((i)=>i.dataset_id).filter((i)=>i.startsWith(r)).filter((i)=>t.force||!n.has(i)).sort();return t.limit!==void 0?o.slice(0,t.limit):o}async function QGe(e,t,r){let n=Array(e.length),o=0,i=Array.from({length:Math.max(1,Math.min(t,e.length))},()=>(async()=>{while(!0){let s=o++;if(s>=e.length)return;n[s]=await r(e[s],s)}})());return await Promise.all(i),n}var WGe="nemarDatasets",C2=256,Uo,_y;var vy=O(()=>{Ll();At();uy();x2();Uo=class Uo extends Error{status;fatal;constructor(e,t,r=!1){super(e);this.status=t;this.fatal=r;this.name="GitHubReadError"}};_y=class _y extends Error{cause;partial;constructor(e,t){super(e.message);this.cause=e;this.partial=t;this.name="FleetSweepAborted"}}});import{rmSync as k2}from"fs";import{join as eHe}from"path";function Oee(){return async(e)=>{let t=await dr(e);return uQ({credentials:t.credentials,bucket:t.s3.bucket,region:t.s3.region,prefix:t.s3.prefix})}}async function rHe(e,t){let r;if(/^https:\/\/github\.com\//.test(e)){let i=process.env.GH_TOKEN?.trim()||(await ka()).token;if(i&&!/[\s']/.test(i))r={GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"credential.https://github.com.helper",GIT_CONFIG_VALUE_0:kE(i)}}let n=await C(["git","clone","--quiet","--filter=blob:none",e,t],r?{env:r}:{});if(n.exitCode!==0)return n.stderr.trim()||`git clone exited ${n.exitCode}`;if(r)await C(["git","config","credential.https://github.com.helper",r.GIT_CONFIG_VALUE_0],{cwd:t});await C(["git","config","user.email","nemar-bot@nemar.org"],{cwd:t}),await C(["git","config","user.name","NEMAR"],{cwd:t});let o=await C(["git","annex","init","--quiet","fleet-key-registration"],{cwd:t});if(o.exitCode!==0)return`git annex init failed: ${o.stderr.trim()||`exit ${o.exitCode}`}`;return}async function nHe(e){let{stdout:t,stderr:r,exitCode:n}=await C(["git","annex","find","--include","*","--format=${key}\n"],{cwd:e});if(n!==0)throw Error(`git annex find failed: ${r.trim()||`exit ${n}`}`);return[...new Set(t.split(`
190
191
  `).filter(Boolean))].sort()}async function Fee(e,t){let{stdout:r,stderr:n,exitCode:o}=await C(["git","annex","find","--include","*","--in",t,"--format=${key}\n"],{cwd:e});if(o!==0)throw Error(`git annex find --in ${t} failed: ${n.trim()||`exit ${o}`}`);return[...new Set(r.split(`
191
192
  `).filter(Boolean))].sort()}async function oHe(e,t=R2){let{stdout:r,exitCode:n}=await C(["git","show","git-annex:remote.log"],{cwd:e});if(n!==0)return null;for(let o of r.split(`
@@ -543,7 +544,7 @@ Warning: failed to set dispatch cooldown (${T(x)}); the retry cron may briefly r
543
544
  ${m.length} target(s) skipped (verify failed):`));for(let x of m)console.log(l.red(` ${x.dataset_id}: ${x.error}`))}}if(t.json)console.log(JSON.stringify({dispatched:f,skipped:m,dispatch:g,cooldown:y},null,2));if(m.length>0)process.exit(1)});var Nee=O2.command("status").description("Report data_complete/bytes_present progress for recover targets").argument("[ids...]","Dataset id(s) to check (omit when using --all)").option("--all","Check every entry in the checked-in recover-datasets list").option("--recover-file <path>","Path to the recover-datasets JSON (default: scripts/recover-datasets.json)").option("--json","Output raw JSON");Nee.action(async(e)=>{let t=Nee.optsWithGlobals();if(!Z())return;if(e.length===0&&!t.all)console.log(l.red("Error: provide dataset id(s) or use --all")),process.exit(1);if(e.length>0&&t.all)console.log(l.red("Error: provide dataset id(s) OR --all, not both")),process.exit(1);let r=t.recoverFile||Wee(),n;try{n=HE(r)}catch(a){console.error(l.red(`Failed to load recover-datasets file: ${T(a)}`)),process.exit(1)}let o=t.all?n.map((a)=>a.dataset_id):e,i=[];for(let a of o)try{let c=await It(a);i.push({dataset_id:a,data_complete:c.data_complete??null,bytes_present:c.bytes_present??null,file_size:c.file_size??null})}catch(c){i.push({dataset_id:a,data_complete:null,bytes_present:null,file_size:null,error:T(c)})}if(t.json){console.log(JSON.stringify(i,null,2));return}console.log(l.bold(`
544
545
  Recover status (${i.length})
545
546
  `));let s=0;for(let a of i){if(a.error){console.log(` ${a.dataset_id.padEnd(10)} ${l.red(`error: ${a.error}`)}`);continue}if(a.data_complete===1)s++;let c=a.data_complete===1?l.green("complete"):a.data_complete===0?l.red("incomplete"):l.dim("unaudited"),u=a.bytes_present!=null&&a.file_size!=null?` ${Qe(a.bytes_present)}/${Qe(a.file_size)}`:"";console.log(` ${a.dataset_id.padEnd(10)} ${c}${u}`)}console.log(l.bold(`
546
- ${s}/${i.length} data_complete`))});ue.addCommand(O2);var mHe=/^xx0999\d{2}$/,hHe=/^(nm|on)\d{6}$/;function Kee(){return Ns(import.meta.dir,"..","..","scripts","exemplar-fleet.json")}var Ry=new ae("exemplar").description("Clone public nm/on datasets into staging exemplars (xx099900-xx099999)");Ry.command("create").description("Clone a public NEMAR dataset into a staging exemplar").argument("[xx-id]","Exemplar dataset id (e.g., xx099900); omit with --all").option("--source <id>","Source nm/on dataset id to clone (overrides the fleet file)").option("--all","Clone every entry in the fleet file").option("--fleet-file <path>","Path to the fleet JSON (default: scripts/exemplar-fleet.json)").option("--publish","Request and approve publication after data lands (mints a sandbox DOI)").option("--include-derived","Also copy zarr/, archives/, and records.json derived artifacts").action(async(e,t)=>{if(!Z())return;await Promise.resolve().then(() => S2());let o=t.fleetFile||Kee(),i={publish:t.publish,includeDerived:t.includeDerived};if(t.all){if(e||t.source)console.error(l.red("--all cannot be combined with an xx-id or --source")),process.exit(1);let a;try{a=cp(o)}catch(u){console.error(l.red(`Failed to load fleet file: ${T(u)}`)),process.exit(1)}let c=0;for(let u of a){if(u.source_id==="nm000000"){console.log(l.yellow(`Skipping ${u.xx_id}: placeholder source_id not yet finalized`));continue}try{await E2({xxId:u.xx_id,sourceId:u.source_id,...i})}catch(d){c++,console.error(l.red(`${u.xx_id} failed: ${T(d)}`))}}if(c>0)console.error(l.red(`
547
+ ${s}/${i.length} data_complete`))});ue.addCommand(O2);var mHe=/^xx0999\d{2}$/,hHe=/^(nm|on)\d{6}$/;function Kee(){return Ns(import.meta.dir,"..","..","scripts","exemplar-fleet.json")}var Ry=new ae("exemplar").description("Clone public nm/on datasets into staging exemplars (xx099900-xx099999)");Ry.command("create").description("Clone a public NEMAR dataset into a staging exemplar").argument("[xx-id]","Exemplar dataset id (e.g., xx099900); omit with --all").option("--source <id>","Source nm/on dataset id to clone (overrides the fleet file)").option("--all","Clone every entry in the fleet file").option("--fleet-file <path>","Path to the fleet JSON (default: scripts/exemplar-fleet.json)").option("--publish","Request and approve publication after data lands (mints a sandbox DOI)").option("--include-derived","Also copy zarr/, archives/, and records.json derived artifacts").action(async(e,t)=>{if(!Z())return;await Promise.resolve().then(() => S2());let o=t.fleetFile||Kee(),i={publish:t.publish,includeDerived:t.includeDerived};if(t.all){if(e||t.source)console.error(l.red("--all cannot be combined with an xx-id or --source")),process.exit(1);let a;try{a=cp(o)}catch(u){console.error(l.red(`Failed to load fleet file: ${T(u)}`)),process.exit(1)}let c=0;for(let u of a){if(u.source_id==="nm000000"){console.log(l.yellow(`Skipping ${u.xx_id}: placeholder source_id not yet finalized`));continue}try{await E2({xxId:u.xx_id,sourceId:u.source_id,...i,...u.anonymous?{anonymous:!0}:{}})}catch(d){c++,console.error(l.red(`${u.xx_id} failed: ${T(d)}`))}}if(c>0)console.error(l.red(`
547
548
  ${c} of ${a.length} fleet entries failed`)),process.exit(1);return}if(!e)console.error(l.red("An xx-id argument is required unless --all is passed")),process.exit(1);if(!mHe.test(e))console.error(l.red(`Invalid exemplar id "${e}". Expected xx099900-xx099999.`)),process.exit(1);let s=t.source;if(!s)try{s=cp(o).find((c)=>c.xx_id===e)?.source_id}catch(a){console.error(l.red(`Failed to load fleet file: ${T(a)}`)),process.exit(1)}if(!s)console.error(l.red(`No source dataset for ${e}. Pass --source <nm/on id> or add it to the fleet file.`)),process.exit(1);if(!hHe.test(s))console.error(l.red(`Invalid source id "${s}". Expected an nm/on dataset id.`)),process.exit(1);try{await E2({xxId:e,sourceId:s,...i})}catch(a){console.error(l.red(`
548
549
  Exemplar clone failed: ${T(a)}`)),process.exit(1)}});Ry.command("status").description("Show which fleet entries have been cloned and their current state").option("--fleet-file <path>","Path to the fleet JSON (default: scripts/exemplar-fleet.json)").action(async(e)=>{if(!Z())return;await Promise.resolve().then(() => S2());let r=e.fleetFile||Kee(),n;try{n=cp(r)}catch(o){console.error(l.red(`Failed to load fleet file: ${T(o)}`)),process.exit(1)}console.log(l.bold(`
549
550
  Exemplar Fleet (${n.length})
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nemar-cli",
3
- "version": "0.10.4-PR1411.bc2413e",
3
+ "version": "0.10.4-PR1411.fda7839",
4
4
  "description": "CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",