diff --git a/README.md b/README.md index c780488..1aae4b8 100644 --- a/README.md +++ b/README.md @@ -86,6 +86,26 @@ researcher's workspace from there. - **`bucket`**: a public bucket open for anonymous writes, named by `VITE_UPLOAD_BUCKET_URL`. Its CORS must allow PUT from this app's origin. Needs only the OSB login. +### Testing on a sandbox (local only) + +Deployments always use EMBER-DANDI. To test on a sandbox instead, add this to +`applications/idp-arc/frontend/.env.local` and restart `yarn start:dev`: + +```bash +# dandi-sandbox or ember-dandi-sandbox +VITE_DANDI_INSTANCE=dandi-sandbox +``` + +MAABCD copies then go to the protocol's dandiset for that sandbox in `src/data/protocols.json` +(none listed: nothing is shared). + +The sandboxes have no OAuth app for us, so also add your API key on that sandbox there. The dev +server signs DANDI calls with it, so it never reaches the browser, and `yarn build` ignores it: + +```bash +DANDI_SANDBOX_API_KEY= +``` + --- ## Docker (Local Build + Run) diff --git a/applications/idp-arc/frontend/package.json b/applications/idp-arc/frontend/package.json index d853039..fec8f60 100644 --- a/applications/idp-arc/frontend/package.json +++ b/applications/idp-arc/frontend/package.json @@ -18,6 +18,7 @@ "@emotion/styled": "^11.14.1", "@mui/icons-material": "^9.0.0", "@mui/material": "^9.0.0", + "fflate": "^0.8.2", "i18next": "^26.0.3", "keycloak-js": "^26.2.3", "react": "^19.2.0", @@ -42,4 +43,4 @@ "typescript-eslint": "^8.48.0", "vite": "^7.3.1" } -} \ No newline at end of file +} diff --git a/applications/idp-arc/frontend/src/app/container.ts b/applications/idp-arc/frontend/src/app/container.ts index f7edb18..37a6c38 100644 --- a/applications/idp-arc/frontend/src/app/container.ts +++ b/applications/idp-arc/frontend/src/app/container.ts @@ -22,7 +22,9 @@ import { PublicBucketObjectStore } from '../infra/publicBucketObjectStore' import { EmberOAuthClient, EMBER_CALLBACK_PATH } from '../infra/emberOAuthClient' import { EmberDandiDirectClient } from '../infra/emberDandiDirectClient' import { EmberUploadApiClient } from '../infra/emberUploadApiClient' -import { EMBER_API_ORIGIN, EMBER_WEB_ORIGIN } from '../infra/emberUrls' +import { dandiInstance } from '../core/dandiInstances' +import { SandboxApiKeyEmberAuth } from '../infra/sandboxApiKeyEmberAuth' +import type { IEmberAuth } from '../core/ports/IEmberAuth' import type { IObjectStore } from '../core/ports/IObjectStore' import { createEmberObjectStore } from '../core/use-cases/emberObjectStore' import { createProtocolDandisetsUseCases, type ProtocolDandiset } from '../core/use-cases/protocolDandisets' @@ -45,10 +47,14 @@ const OSB_WEB_ORIGIN = `${OSB_SCHEME}://www.${OSB_DOMAIN}` export type UploadBackend = 'ember' | 'bucket' /** VITE_UPLOAD_BACKEND: `bucket`, or EMBER-DANDI for anything else, unset included. */ export const UPLOAD_BACKEND: UploadBackend = import.meta.env.VITE_UPLOAD_BACKEND === 'bucket' ? 'bucket' : 'ember' +/** The DANDI instance in use: VITE_DANDI_INSTANCE in the dev server, EMBER-DANDI otherwise. Sets where + * the researcher's uploads go, and which of a protocol's MAABCD dandisets the copy goes to. */ +export const DANDI_INSTANCE = dandiInstance(import.meta.env.DEV ? import.meta.env.VITE_DANDI_INSTANCE : undefined) +const { api: EMBER_API_ORIGIN, web: EMBER_WEB_ORIGIN } = DANDI_INSTANCE /** The OSB (Keycloak) user whose key (user attribute `DANDI_API_KEY`) signs the copy into the - * protocol's MAABCD dandiset, and the DANDI deployment it goes to (dandi-cli's name). */ + * protocol's MAABCD dandiset, on the same instance (dandi-cli's name for it). */ const MAABCD_EMBER_USERNAME = 'maabcd-consortium' -const MAABCD_DANDI_INSTANCE = 'ember-dandi' +const MAABCD_DANDI_INSTANCE = DANDI_INSTANCE.name /** Same-origin path for the browser's own EMBER calls (Vite proxy in dev, nginx deployed): EMBER's * token response carries no CORS headers. */ const EMBER_FETCH_BASE = '/ember-proxy' @@ -67,12 +73,15 @@ const workspaceApi = new WorkspaceApiClient(WORKSPACES_API, WORKSPACES_LIST_URL) /** Signs the researcher in to EMBER-DANDI (OAuth in a popup, a full-page redirect if it is blocked); * their token stays in the browser. */ -export const emberAuth = new EmberOAuthClient({ - authOrigin: EMBER_API_ORIGIN, - apiBase: EMBER_FETCH_BASE, - clientId: import.meta.env.VITE_EMBER_CLIENT_ID ?? '', - redirectUri: `${window.location.origin}${EMBER_CALLBACK_PATH}`, -}) +export const emberAuth: IEmberAuth = __DANDI_SANDBOX_API_KEY__ + // Dev server only: the proxy signs every call with its DANDI_SANDBOX_API_KEY (vite.config.ts). + ? new SandboxApiKeyEmberAuth(EMBER_FETCH_BASE) + : new EmberOAuthClient({ + authOrigin: EMBER_API_ORIGIN, + apiBase: EMBER_FETCH_BASE, + clientId: import.meta.env.VITE_EMBER_CLIENT_ID ?? '', + redirectUri: `${window.location.origin}${EMBER_CALLBACK_PATH}`, + }) export { EMBER_CALLBACK_PATH } export { EmberPopupBlocked, EmberSignInCancelled } from '../infra/emberOAuthClient' const emberDirect = new EmberDandiDirectClient(EMBER_FETCH_BASE) @@ -83,7 +92,7 @@ const protocolDandisets = createProtocolDandisetsUseCases({ /** Where uploads go before OSB imports them (UPLOAD_BACKEND): EMBER-DANDI, or the public bucket. */ export const objectStore: IObjectStore = UPLOAD_BACKEND === 'ember' - ? createEmberObjectStore(authClient, emberAuth, emberDirect, new EmberUploadApiClient(WORKSPACES_API, MAABCD_DANDI_INSTANCE, MAABCD_EMBER_USERNAME), protocolDandisets, EMBER_API_ORIGIN) + ? createEmberObjectStore(authClient, emberAuth, emberDirect, new EmberUploadApiClient(WORKSPACES_API, MAABCD_DANDI_INSTANCE, MAABCD_EMBER_USERNAME), protocolDandisets, EMBER_API_ORIGIN, EMBER_WEB_ORIGIN) : new PublicBucketObjectStore(import.meta.env.VITE_UPLOAD_BUCKET_URL) // ─── Use-cases (injected with their concrete dependencies) ──────────────────── diff --git a/applications/idp-arc/frontend/src/components/BidsStructureButton.tsx b/applications/idp-arc/frontend/src/components/BidsStructureButton.tsx new file mode 100644 index 0000000..c48c64f --- /dev/null +++ b/applications/idp-arc/frontend/src/components/BidsStructureButton.tsx @@ -0,0 +1,66 @@ +import { useState } from 'react' +import { Box, IconButton, Popover, Tooltip, Typography } from '@mui/material' +import AccountTreeOutlinedIcon from '@mui/icons-material/AccountTreeOutlined' +import { contentSize, type OutputFile } from '../core/bids/convert' +import { fileTree } from '../core/bids/fileTree' +import { formatBytes } from '../core/formatBytes' + +/** Shows, in a popover, the folders and files the BIDS conversion of the picked file would produce. */ +export default function BidsStructureButton({ files }: { files: OutputFile[] }) { + const [anchor, setAnchor] = useState(null) + const sizes = new Map(files.map((f) => [f.path, contentSize(f.content)])) + const lines = fileTree(files.map((f) => f.path)) + // A line's full path, to look its size up: the folders above it, then its name. + const parents: string[] = [] + + return ( + <> + + { e.stopPropagation(); setAnchor(e.currentTarget) }}> + + + + setAnchor(null)} + onClick={(e) => e.stopPropagation()} + anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }} + transformOrigin={{ vertical: 'top', horizontal: 'center' }} + slotProps={{ + paper: { + sx: { + // Opaque, so the dialog underneath doesn't show through. + bgcolor: '#2A2A2A', + backgroundImage: 'none', + border: '1px solid', + borderColor: 'divider', + boxShadow: 12, + mt: 1, + }, + }, + }} + > + + + What would go to DANDI, worked out in your browser. Nothing has been uploaded. + + + {lines.map((line, i) => { + parents.length = line.depth + const path = [...parents, line.name].join('') + if (line.folder) parents.push(line.name) + const size = sizes.get(path) + return ( + + {' '.repeat(line.depth)}{line.name} + {size !== undefined && {` ${formatBytes(size)}`}} + + ) + })} + + + + + ) +} diff --git a/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx b/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx index 0593cee..ec025de 100644 --- a/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx +++ b/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx @@ -10,6 +10,7 @@ import { MenuItem, Select, Stack, + TextField, Typography, } from '@mui/material' import CloudUploadOutlinedIcon from '@mui/icons-material/CloudUploadOutlined' @@ -21,7 +22,8 @@ import OpenInNewIcon from '@mui/icons-material/OpenInNewOutlined' import ErrorOutlineIcon from '@mui/icons-material/ErrorOutlineOutlined' import HourglassEmptyIcon from '@mui/icons-material/HourglassEmpty' -import { emberAuth, getWorkspaceUrl, listProtocolDandisets, publishDandiset, recordedWorkspace, runProtocol, UPLOAD_BACKEND, type ProtocolDandiset } from '../app/container' +import { DANDI_INSTANCE, emberAuth, getWorkspaceUrl, listProtocolDandisets, publishDandiset, recordedWorkspace, runProtocol, UPLOAD_BACKEND, type ProtocolDandiset } from '../app/container' +import { maabcdDandisetFor } from '../core/dandiInstances' import { EMBER_SIGN_IN, UserFacingError, userMessage } from '../core/userMessages' import { withRunLock } from './runStorage' import { INITIAL_FORM, restoreSession, session } from './uploadSession' @@ -35,10 +37,16 @@ import { isNonBlocking, PUBLISH_STEP, PUBLISHING_LABEL, type RunProtocolInput } import { formatBytes } from '../core/formatBytes' import { templatesZipFileName, templatesZipHref } from '../core/protocolTemplates' import { SIGN_IN_AGAIN } from '../core/userMessages' +import type { BidsConfig } from '../core/bids/convert' +import { useBidsCheck } from './useBidsCheck' +import BidsStructureButton from './BidsStructureButton' import protocols from '../data/protocols.json' -/** Only protocols with an analysis repository can be run, so only those are offered. */ -const runnableProtocols = protocols.filter((p) => 'repoZipUrl' in p && p.repoZipUrl) +/** Only protocols with an analysis repository can be run, so only those are offered. Each carries + * its MAABCD dandiset on the DANDI instance in use (none: nothing is shared). */ +const runnableProtocols = protocols + .filter((p) => 'repoZipUrl' in p && p.repoZipUrl) + .map((p) => ({ ...p, maabcdAggregateDandisetId: maabcdDandisetFor(p, DANDI_INSTANCE.name) })) type RunnableProtocol = (typeof runnableProtocols)[number] export interface DataUploadDialogProps { @@ -69,7 +77,7 @@ const MIN_ATTEMPT_MS = 300 export default function DataUploadDialog({ open, initialProtocol, onClose, onAuthRequired }: DataUploadDialogProps) { const { tokenParsed } = useAppContext() const [form] = useSessionStore(session) - const { step, protocol, file, isDragging, uploadMessage, spawnedWorkspaceId, outputsDir, runSteps, dandisetId, shareWithMaabcd, doi, publishing, publishError, checkpoint } = form + const { step, protocol, file, isDragging, uploadMessage, spawnedWorkspaceId, outputsDir, runSteps, dandisetId, dandisetName, shareWithMaabcd, doi, publishing, publishError, checkpoint } = form // EMBER-DANDI: the upload goes to the researcher's own account. Choosing a protocol lists their // dandisets for it, each with the workspace it runs in, so choosing one chooses both. const usesEmber = UPLOAD_BACKEND === 'ember' @@ -81,6 +89,7 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut const workspaceLookup = useRef(0) const fileInputRef = useRef(null) const user = typeof tokenParsed?.sub === 'string' ? tokenParsed.sub : null + const researcher = typeof tokenParsed?.name === 'string' ? tokenParsed.name.trim() || undefined : undefined // Once the user is known, their run saved before a reload comes back. useEffect(() => { if (user) restoreSession(user) }, [user]) @@ -192,9 +201,14 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut const inputFormats = inputFormatsFor(selectedProtocol?.inputFormats) const templatesHref = templatesZipHref(selectedProtocol) const fileProblem = file ? inputFileProblem(file, selectedProtocol?.name ?? 'This protocol', selectedProtocol?.inputFormats) : null + // The file is converted to BIDS on pick, and its errors stop the upload. + const bidsConfig = selectedProtocol?.bids as BidsConfig | undefined + const bidsCheck = useBidsCheck(fileProblem ? null : file, bidsConfig, selectedProtocol?.name ?? '') + const bidsProblems = bidsCheck.result?.problems ?? [] + const bidsBlocks = bidsCheck.checking || bidsProblems.some((p) => p.level === 'error') const handleUpload = async () => { - if (fileProblem || !selectedProtocol) return + if (fileProblem || bidsBlocks || !selectedProtocol) return // Picked up after a reload: the file is needed again unless it was already uploaded. if (!file) { if (checkpoint?.stored) return runLocked(selectedProtocol, null) @@ -211,13 +225,16 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut /** What every attempt is given: it carries on from `checkpoint` where that applies. */ const inputFor = (selectedProtocol: RunnableProtocol, file: File | null): RunProtocolInput => ({ - protocol: selectedProtocol, + // protocols.json is typed by what it holds, so its rule types are plain strings here. + protocol: selectedProtocol as RunProtocolInput['protocol'], file, // `spawnedWorkspaceId` is set as soon as the run has a workspace, so a retry reuses it // instead of creating another one. workspaceId: spawnedWorkspaceId, workspaceName: selectedProtocol.name, dandisetId: dandisetId || undefined, + dandisetName: dandisetId ? undefined : dandisetName, + researcher, shareWithMaabcd, resume: checkpoint, }) @@ -308,7 +325,7 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut const stepIndex = step === 'select' ? 0 : 1 const canGoNext = !!protocol && (!usesEmber || (emberSignedIn && protocolDandisets !== null && !findingWorkspace)) - const canUpload = !!file && !fileProblem && emberSignedIn + const canUpload = !!file && !fileProblem && !bidsBlocks && emberSignedIn return ( )} + {emberSignedIn && protocolDandisets !== null && !dandisetId && ( + setForm((prev) => ({ ...prev, dandisetName: e.target.value }))} + slotProps={{ htmlInput: { style: { fontFamily: 'Inter, sans-serif', fontSize: '14px' } } }} + sx={{ mt: 1.5 }} + /> + )} )} + {usesEmber && selectedProtocol && 'maabcdAggregateDandisets' in selectedProtocol && !selectedProtocol.maabcdAggregateDandisetId && ( + + No MAABCD dandiset on {DANDI_INSTANCE.name} for this protocol, so nothing is shared with the consortium. + + )} {usesEmber && selectedProtocol?.maabcdAggregateDandisetId && ( - {dandisetId ? `Uploading into your dandiset ${dandisetId}` : 'Uploading into a new dandiset in your EMBER-DANDI account'} + {dandisetId ? `Uploading into your dandiset ${dandisetId}` : `Uploading into a new dandiset${dandisetName.trim() ? ` "${dandisetName.trim()}"` : ''} in your EMBER-DANDI account`} {spawnedWorkspaceId !== undefined ? `, analyzed in workspace ${spawnedWorkspaceId}.` : ', analyzed in a new workspace.'} )} @@ -554,6 +588,30 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut {fileProblem} )} + {bidsCheck.checking && ( + Checking the file… + )} + {bidsCheck.result && ( + e.stopPropagation()}> + {!bidsProblems.some((p) => p.level === 'error') && ( + + + Ready for DANDI: {bidsCheck.result.subjects.length === 1 ? '1 animal' : `${bidsCheck.result.subjects.length} animals`} ({bidsCheck.result.subjects.map((s) => s.id).join(', ')}),{' '} + {bidsCheck.result.files.filter((f) => f.path.startsWith('sub-') && f.path.endsWith('.tsv')).length} tables + + + + )} + {bidsProblems.slice(0, 8).map((p, i) => ( + + {p.message} + + ))} + {bidsProblems.length > 8 && ( + …and {bidsProblems.length - 8} more + )} + + )} ) : ( <> @@ -571,6 +629,11 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut Download an example input file for this protocol and fill in your data the same way. + {bidsConfig && ( + + Upload one filled reporting sheet per animal, or a zip of them. Other files in the zip, such as the weight log or the protocol PDFs, are kept with your data. + + )} diff --git a/applications/idp-arc/frontend/src/components/uploadSession.ts b/applications/idp-arc/frontend/src/components/uploadSession.ts index 271b68a..f1f766b 100644 --- a/applications/idp-arc/frontend/src/components/uploadSession.ts +++ b/applications/idp-arc/frontend/src/components/uploadSession.ts @@ -30,6 +30,8 @@ export interface FormState { runSteps: RunStep[] /** EMBER-DANDI only: the researcher's dandiset to upload into; empty creates a new one. */ dandisetId: string + /** The name of the new dandiset, when none is chosen; empty uses the protocol's name. */ + dandisetName: string /** Also upload into the protocol's MAABCD dandiset; on by default. */ shareWithMaabcd: boolean /** What the last attempt got done: a retry carries on from there (the run checks it still applies). */ @@ -50,13 +52,14 @@ export const INITIAL_FORM: FormState = { outputsDir: '', runSteps: [], dandisetId: '', + dandisetName: '', shareWithMaabcd: true, } export const session = createSessionStore(INITIAL_FORM) /** What is saved across a reload: the run, not the form around it. */ -type SavedRun = Pick const RUN_INTERRUPTED = 'The run stopped unexpectedly. Retry to carry on from where it stopped.' @@ -73,9 +76,9 @@ if (typeof window !== 'undefined') { session.subscribe(() => { if (!savingFor || leaving) return - const { step, protocol, dandisetId, spawnedWorkspaceId, shareWithMaabcd, checkpoint, runSteps, outputsDir, uploadMessage, resultSeen } = session.get() + const { step, protocol, dandisetId, dandisetName, spawnedWorkspaceId, shareWithMaabcd, checkpoint, runSteps, outputsDir, uploadMessage, resultSeen } = session.get() if (!checkpoint || resultSeen) return clearRun(savingFor) - const run: SavedRun = { step, protocol, dandisetId, spawnedWorkspaceId, shareWithMaabcd, checkpoint, runSteps, outputsDir, uploadMessage } + const run: SavedRun = { step, protocol, dandisetId, dandisetName, spawnedWorkspaceId, shareWithMaabcd, checkpoint, runSteps, outputsDir, uploadMessage } saveRun(savingFor, run) }) diff --git a/applications/idp-arc/frontend/src/components/useBidsCheck.ts b/applications/idp-arc/frontend/src/components/useBidsCheck.ts new file mode 100644 index 0000000..bb260d3 --- /dev/null +++ b/applications/idp-arc/frontend/src/components/useBidsCheck.ts @@ -0,0 +1,35 @@ +import { useEffect, useState } from 'react' +import { convertToBids, type BidsConfig, type BidsConversion } from '../core/bids/convert' + +export interface BidsCheck { + /** The file is being read and converted. */ + checking: boolean + /** The conversion of the current file, or null when there is nothing to check. */ + result: BidsConversion | null +} + +interface Done { + file: File + config: BidsConfig + datasetName: string + result: BidsConversion +} + +/** Converts the picked file to BIDS as soon as it is picked, so its problems show before upload. */ +export function useBidsCheck(file: File | null, config: BidsConfig | undefined, datasetName: string): BidsCheck { + const [done, setDone] = useState(null) + + useEffect(() => { + if (!file || !config) return + let current = true + convertToBids(file, config, { name: datasetName, protocol: { name: datasetName } }) + .catch((): BidsConversion => ({ files: [], subjects: [], problems: [{ level: 'error', message: `${file.name} could not be read.` }] })) + .then((result) => { if (current) setDone({ file, config, datasetName, result }) }) + return () => { current = false } + }, [file, config, datasetName]) + + if (!file || !config) return { checking: false, result: null } + // Still converting until the result is for exactly this file and settings. + if (done?.file !== file || done.config !== config || done.datasetName !== datasetName) return { checking: true, result: null } + return { checking: false, result: done.result } +} diff --git a/applications/idp-arc/frontend/src/core/bids/config.ts b/applications/idp-arc/frontend/src/core/bids/config.ts new file mode 100644 index 0000000..fbf50b0 --- /dev/null +++ b/applications/idp-arc/frontend/src/core/bids/config.ts @@ -0,0 +1,119 @@ +/** The `bids` block of protocols.json, the result of a conversion, and the state it builds up. */ +/** A column of the tables: what it means, for its JSON description. */ +export interface ColumnInfo { + Description?: string + Units?: string + /** What each value stands for, when there is a fixed set. */ + Levels?: Record +} + +/** The `bids` block of a protocol in protocols.json. */ +export interface BidsConfig { + /** BIDS task label, e.g. `fourchoice`. */ + task: string + /** Where a workbook holds the subject ID: the cell to the right of the cell reading `label`. */ + subjectId: { sheet: string; label: string } + /** Where a workbook holds the subject's sex, the same way; optional. */ + sex?: { sheet: string; label: string } + /** Where each table's sheet holds its date (the cell to the right of `label`): the session. */ + sessionDate?: { label: string } + /** Sheets that become behavioral tables: the header row is the row whose first cell is `header`. + * `filledBy`: the columns that show a row was recorded (a template may prefill others); default + * any column but the first. */ + tables: { sheet: string; acq: string; header: string; filledBy?: string[] }[] + /** Cells above each table (next to `label`) written, under `key`, to a JSON beside it; `list`: + * every cell right of the label, each `A: Anise`. */ + tableInfo?: { key: string; label: string; type?: 'date' | 'time' | 'list' }[] + /** Columns left out of every table, by the name they would get (`quadrant_chosen`). */ + skipColumns?: string[] + /** Each column, by the name it gets in the tables (`latency_s`), the same in every stage. */ + columns?: Record + /** participants.tsv: one row per subject, its species and sex, and these cells (next to `label`). */ + participants?: { species?: string; fields: (Field & { sheet: string })[] } + /** phenotype/.tsv: one row per subject from a sheet laid out sideways: the row whose first + * cell is `header` names one record per column (`Day 0`), each later row is a field (`label`). */ + phenotype?: { name: string; sheet: string; header: string; description?: string; fields: Field[] }[] +} + +/** A value written as one column: the cell next to (or, in a phenotype sheet, the row of) `label`. */ +export interface Field { + column: string + label: string + /** The column's name in the JSON sidecar; `label` when absent. */ + LongName?: string + Description: string + Units?: string + /** Written as `2026-09-02` or `09:02:00`, however the sheet stores it. */ + type?: 'date' | 'time' +} + +/** What describes the dataset as a whole. */ +export interface DatasetInfo { + name: string + /** The protocol: its name, and what the task is. */ + protocol: { name: string; description?: string; url?: string } + /** SPDX identifier, e.g. `CC-BY-4.0`. */ + license?: string + /** Who made the dataset, one name each. */ + authors?: string[] + /** Where the upload is in the dandiset, when it is known; else `sourcedata/`. */ + source?: string +} + +/** A file to write into the dandiset. */ +export interface OutputFile { + /** Path in the dandiset, `/`-separated. */ + path: string + /** The upload itself is its File, never read into memory. */ + content: string | Uint8Array | Blob +} + +/** An output file's size in bytes. */ +export function contentSize(content: OutputFile['content']): number { + return typeof content === 'string' ? new TextEncoder().encode(content).length : content instanceof Blob ? content.size : content.length +} + +/** Something wrong with the upload, shown to the researcher. */ +export interface Problem { + /** `error` stops the upload; `warning` is shown and the upload can go on. */ + level: 'error' | 'warning' + message: string +} + +/** One animal: a workbook with an Animal ID. */ +export interface Subject { + id: string + /** As written on the sheet. */ + sex?: string + /** The workbook it was read from. */ + source: string +} + +/** What `convertToBids` returns. */ +export interface BidsConversion { + files: OutputFile[] + subjects: Subject[] + problems: Problem[] +} + +/** Collects problems: only what stops the dataset being built (errors), or leaves part of it out. */ +export interface Report { + error(message: string): void + warn(message: string): void + failed(): boolean +} + +/** What a conversion builds up, workbook by workbook. */ +export interface Run { + config: BidsConfig + report: Report + files: OutputFile[] + subjects: Subject[] + /** The protocol documents that came in a zip, kept together in logs/. */ + logs: OutputFile[] + /** participants.tsv and each phenotype table, one row per subject. */ + participantRows: string[][] + phenotypeRows: Map + /** Each table's column descriptions: every workbook's columns, the first description of each. */ + columnsByAcq: Map> +} diff --git a/applications/idp-arc/frontend/src/core/bids/convert.ts b/applications/idp-arc/frontend/src/core/bids/convert.ts new file mode 100644 index 0000000..c1df552 --- /dev/null +++ b/applications/idp-arc/frontend/src/core/bids/convert.ts @@ -0,0 +1,65 @@ +/** + * A researcher's upload (an .xlsx, or a zip of them) as a BIDS dataset, in the browser. + * + * 1. Open the upload: its workbooks and PDFs; nothing else in a zip is read (upload.ts). + * 2. Each PDF goes to logs/; each workbook gives its animal, participants row, phenotype row and one table per stage (workbook.ts). + * 3. Write the files describing the whole dataset: stage JSONs, participants, phenotype, description, README (datasetFiles.ts). + * 4. Return every file, the upload itself first (sourcedata/), with the animals and the problems. + * + * What is read where is the protocol's `bids` block in protocols.json. + */ +import { pathSafe } from '../pathSafe' +import type { BidsConfig, BidsConversion, DatasetInfo, Problem, Report, Run } from './config' +import { openUpload } from './upload' +import { addWorkbook } from './workbook' +import { datasetFiles } from './datasetFiles' + +export type { BidsConfig, BidsConversion, ColumnInfo, DatasetInfo, Field, OutputFile, Problem, Subject } from './config' +export { contentSize } from './config' +export type { InputFile } from './upload' +export { BIDS_VERSION } from './datasetFiles' + +/** What a BIDS label (the task) may hold. */ +const LABEL = /^[A-Za-z0-9]+$/ + +/** The upload as BIDS files, the animals found, and any problems: steps 1–4 above. */ +export async function convertToBids(upload: File, config: BidsConfig, dataset: DatasetInfo): Promise { + if (!LABEL.test(config.task)) throw new Error(`bids.task must be letters and digits, got "${config.task}"`) + const problems: Problem[] = [] + const report: Report = { + error: (message) => problems.push({ level: 'error', message }), + warn: (message) => problems.push({ level: 'warning', message }), + failed: () => problems.some((p) => p.level === 'error'), + } + + // 1. Open the upload: its workbooks and PDFs (upload.ts). + const inputs = await openUpload(upload, report) + if (!inputs) return { files: [], subjects: [], problems } + + const source = dataset.source ?? `sourcedata/${pathSafe(upload.name)}` + const run: Run = { + config, report, files: [{ path: source, content: upload }], subjects: [], logs: [], + participantRows: [], phenotypeRows: new Map(), columnsByAcq: new Map(), + } + // 2. Each PDF to logs/; each workbook to its animal, rows and tables (workbook.ts). + for (const input of inputs) { + if (input.name.toLowerCase().endsWith('.pdf')) run.logs.push({ path: `logs/${pathSafe(input.name)}`, content: input.bytes }) + if (input.name.toLowerCase().endsWith('.xlsx')) addWorkbook(run, input) + } + checkSomethingConverted(run, upload.name) + // 3. The files describing the whole dataset (datasetFiles.ts). + run.files.push(...datasetFiles(run, dataset)) + // 4. Everything made, the animals found, and the problems. + return { files: run.files, subjects: run.subjects, problems } +} + +/** An error when the upload held no subject, or subjects with no trial at all. */ +function checkSomethingConverted(run: Run, uploadName: string) { + const { config, report } = run + if (report.failed()) return + if (!run.subjects.length) { + report.error(`No workbook with "${config.subjectId.label}" on a ${config.subjectId.sheet} sheet was found in ${uploadName}.`) + } else if (!run.files.some((f) => f.path.startsWith('sub-'))) { + report.error(`No trials are filled in: every ${config.tables.map((t) => t.sheet).join(', ')} sheet in ${uploadName} is empty or missing.`) + } +} diff --git a/applications/idp-arc/frontend/src/core/bids/datasetFiles.ts b/applications/idp-arc/frontend/src/core/bids/datasetFiles.ts new file mode 100644 index 0000000..4af154b --- /dev/null +++ b/applications/idp-arc/frontend/src/core/bids/datasetFiles.ts @@ -0,0 +1,107 @@ +/** Step 4: the files that describe the whole dataset, written once all workbooks are read. */ +import type { BidsConfig, DatasetInfo, Field, OutputFile, Run } from './config' +import { splitColumn } from './sheet' +import { json, tsvOf } from './values' + +/** The BIDS version the dataset follows (`dataset_description.json`). */ +export const BIDS_VERSION = '1.10.0' + +/** The dataset-level files: each table's column descriptions, participants, phenotype, the logs, + * dataset_description.json and the README. */ +export function datasetFiles(run: Run, dataset: DatasetInfo): OutputFile[] { + const { config } = run + const out: OutputFile[] = [] + for (const [acq, columns] of run.columnsByAcq) { + out.push({ path: `task-${config.task}_acq-${acq}_beh.json`, content: json({ + TaskName: config.task, + ...(dataset.protocol.description ? { TaskDescription: dataset.protocol.description } : {}), + ...describeColumns(columns, config.columns), + }) }) + } + if (config.participants && run.participantRows.length) { + const fields = config.participants.fields + const header = ['participant_id', ...(config.participants.species ? ['species'] : []), 'sex', ...fields.map((f) => f.column)] + out.push({ path: 'participants.tsv', content: tsvOf(header, run.participantRows) }) + out.push({ path: 'participants.json', content: json({ + ...(config.participants.species ? { species: { Description: 'Species, as its binomial name (NCBI Taxonomy).' } } : {}), + participant_id: { Description: `Animal ID from the ${config.subjectId.sheet} sheet ("${config.subjectId.label}"), letters and digits only.` }, + sex: { Description: 'Sex of the animal, as written on the sheet.' }, + ...describeFields(fields), + }) }) + } + for (const table of config.phenotype ?? []) { + const found = run.phenotypeRows.get(table.name) + if (!found) continue + out.push({ path: `phenotype/${table.name}.tsv`, content: tsvOf(['participant_id', ...found.columns], found.rows) }) + out.push({ path: `phenotype/${table.name}.json`, content: json({ + ...(table.description ? { MeasurementToolMetadata: { Description: table.description } } : {}), + ...Object.fromEntries(found.columns.map((c) => { + const [record, field] = splitColumn(c, table.fields) + return [c, { Description: `${record}: ${field.Description}`, ...(field.Units ? { Units: field.Units } : {}) }] + })), + }) }) + } + out.push(...run.logs) + out.push({ path: 'dataset_description.json', content: json(datasetDescription(dataset)) }) + out.push({ path: 'README.md', content: readme(dataset, config, run.logs.length > 0, run.participantRows.length > 0, [...run.phenotypeRows.keys()]) }) + return out +} + +/** The header-derived description of each column, with what the protocol says about it on top. */ +export function describeColumns(found: Record, known: BidsConfig['columns']) { + return Object.fromEntries(Object.entries(found).map(([name, column]) => { + const info = known?.[name] + const units = info?.Units ?? column.Units + return [name, { + LongName: column.LongName, + ...(info?.Description ? { Description: info.Description } : {}), + ...(units ? { Units: units } : {}), + ...(info?.Levels ? { Levels: info.Levels } : {}), + }] + })) +} + +/** dataset_description.json: name, version, license, authors, and what made it. */ +export function datasetDescription({ name, protocol, license, authors }: DatasetInfo) { + return { + Name: name, + BIDSVersion: BIDS_VERSION, + DatasetType: 'raw', + ...(license ? { License: license } : {}), + ...(authors?.length ? { Authors: authors } : {}), + ...(protocol.url ? { ReferencesAndLinks: [protocol.url] } : {}), + GeneratedBy: [{ + Name: `MAABCD ${protocol.name} upload`, + Description: 'Behavioral tables copied, unchanged, from the spreadsheets in sourcedata/, in the browser.', + }], + } +} + +/** The dataset's README.md: the protocol, and what each part of the layout holds. */ +export function readme({ name, protocol }: DatasetInfo, config: BidsConfig, hasLogs: boolean, hasParticipants: boolean, phenotypes: string[]): string { + return [ + `# ${name}`, + '', + `Protocol: ${protocol.name}`, + ...(protocol.url ? ['', `Analysis code: ${protocol.url}`] : []), + '', + ...(protocol.description ? [protocol.description, ''] : []), + '## Layout', + '', + `- \`sub-/${config.sessionDate ? 'ses-/' : ''}beh/\`: one table per animal and stage, rows as recorded.`, + `- \`task-${config.task}_acq-_beh.json\`: what each column of that stage's tables is.`, + ...(config.tableInfo?.length ? ['- Each table\'s own `.json`: the cells above the table on its sheet (' + config.tableInfo.map((f) => f.label.replace(/:$/, '')).join(', ') + ').'] : []), + ...(hasParticipants ? ['- `participants.tsv`: one row per animal (species, sex, and its details from the sheet).'] : []), + ...phenotypes.map((p) => `- \`phenotype/${p}.tsv\`: one row per animal, from the sheet's ${p} records.`), + '- `sourcedata/upload-/`: each upload, zipped with a README that links this dandiset; every file in it is the researcher\'s, unchanged.', + ...(hasLogs ? ['- `logs/`: the protocol documents that came with the upload.'] : []), + '', + 'A later upload of the same animal replaces its rows in `participants.tsv` and `phenotype/`, and its tables for the same testing date and stage; every upload stays in `sourcedata/`.', + '', + ].join('\n') +} + +/** The fields' column descriptions, for a JSON sidecar. */ +export function describeFields(fields: Field[]) { + return Object.fromEntries(fields.map((f) => [f.column, { LongName: f.LongName ?? f.label, Description: f.Description, ...(f.Units ? { Units: f.Units } : {}) }])) +} diff --git a/applications/idp-arc/frontend/src/core/bids/fileTree.ts b/applications/idp-arc/frontend/src/core/bids/fileTree.ts new file mode 100644 index 0000000..81453d2 --- /dev/null +++ b/applications/idp-arc/frontend/src/core/bids/fileTree.ts @@ -0,0 +1,33 @@ +/** One line of a folder tree: its depth, name, and whether it is a folder. */ +export interface TreeLine { + depth: number + name: string + folder: boolean +} + +/** `/`-separated paths as a sorted folder tree, folders before files at each level. */ +export function fileTree(paths: string[]): TreeLine[] { + interface Node { children: Map; file: boolean } + const root: Node = { children: new Map(), file: false } + for (const path of paths) { + let node = root + path.split('/').forEach((part, i, parts) => { + let child = node.children.get(part) + if (!child) node.children.set(part, child = { children: new Map(), file: false }) + if (i === parts.length - 1) child.file = true + node = child + }) + } + const lines: TreeLine[] = [] + const walk = (node: Node, depth: number) => { + const entries = [...node.children].sort(([a, x], [b, y]) => + Number(x.file && !x.children.size) - Number(y.file && !y.children.size) || a.localeCompare(b)) + for (const [name, child] of entries) { + const folder = child.children.size > 0 + lines.push({ depth, name: folder ? `${name}/` : name, folder }) + if (folder) walk(child, depth + 1) + } + } + walk(root, 0) + return lines +} diff --git a/applications/idp-arc/frontend/src/core/bids/merge.ts b/applications/idp-arc/frontend/src/core/bids/merge.ts new file mode 100644 index 0000000..8a9030f --- /dev/null +++ b/applications/idp-arc/frontend/src/core/bids/merge.ts @@ -0,0 +1,36 @@ +/** + * A re-upload into a dandiset that already holds BIDS data: the files with one row per animal + * (participants.tsv, phenotype/*.tsv) and their descriptions are merged with the draft's copies, + * so animals from earlier uploads stay. An animal in both keeps the new row. The stage JSONs + * (`task-_acq-_beh.json`) are merged too, so columns only earlier uploads had stay described. + */ + +/** The files merged with the draft's copy rather than replaced. */ +export function isMergedFile(path: string): boolean { + return /^(participants|phenotype\/[^/]+)\.(tsv|json)$/.test(path) || /^task-[^/]+_beh\.json$/.test(path) +} + +/** `incoming` merged into `existing`: rows by their first column (`participant_id`), descriptions by key. */ +export function mergeWithDraft(path: string, existing: string, incoming: string): string { + return path.endsWith('.json') ? mergeJson(existing, incoming) : mergeTsv(existing, incoming) +} + +/** Earlier rows keep their order and new ones follow; columns are the union, missing cells `n/a`. */ +function mergeTsv(existing: string, incoming: string): string { + const [oldHeader, ...oldRows] = lines(existing) + const [newHeader, ...newRows] = lines(incoming) + if (!oldHeader) return incoming + const header = [...newHeader, ...oldHeader.filter((c) => !newHeader.includes(c))] + const record = (columns: string[], row: string[]) => header.map((c) => (columns.includes(c) ? row[columns.indexOf(c)] ?? 'n/a' : 'n/a')) + const rows = new Map(oldRows.map((r) => [r[0], record(oldHeader, r)])) + for (const r of newRows) rows.set(r[0], record(newHeader, r)) + return [header, ...rows.values()].map((r) => r.join('\t')).join('\n') + '\n' +} + +function mergeJson(existing: string, incoming: string): string { + return JSON.stringify({ ...JSON.parse(existing), ...JSON.parse(incoming) }, null, 2) + '\n' +} + +function lines(tsv: string): string[][] { + return tsv.split('\n').filter((l) => l.trim() !== '').map((l) => l.split('\t')) +} diff --git a/applications/idp-arc/frontend/src/core/bids/sheet.ts b/applications/idp-arc/frontend/src/core/bids/sheet.ts new file mode 100644 index 0000000..0075265 --- /dev/null +++ b/applications/idp-arc/frontend/src/core/bids/sheet.ts @@ -0,0 +1,108 @@ +/** Finding things on a sheet: a labelled cell, a table under its header row, a sideways sheet. */ +import type { CellValue, Workbook } from './xlsxReader' +import type { BidsConfig, Field } from './config' +import { formatted, text, tsvCell } from './values' + +/** Where the first cell reading exactly `label` is, top to bottom: [row, column]. */ +export function findLabel(rows: CellValue[][], label: string): [number, number] | undefined { + for (let r = 0; r < rows.length; r++) { + const c = (rows[r] ?? []).findIndex((v) => text(v) === label) + if (c !== -1) return [r, c] + } + return undefined +} + +/** The cell right of `label` on `sheet`; null when absent or empty. */ +export function labelValue(workbook: Workbook, at: { sheet: string; label: string }): CellValue { + const rows = workbook.get(at.sheet) ?? [] + const found = findLabel(rows, at.label) + if (!found) return null + const value = rows[found[0]][found[1] + 1] ?? null + return text(value) === '' ? null : value +} + +/** The table under `headerRow`, and a description of each column from its header text. */ +export function tableToTsv(rows: CellValue[][], headerRow: number, filledBy?: string[], skip: string[] = []): Table | null { + const header = rows[headerRow] + let width = header.findIndex((c) => text(c) === '') + if (width === -1) width = header.length + const headers = header.slice(0, width).map((c) => String(c ?? '')) + const names = uniqueColumnNames(headers) + // A row counts only if one of its `filledBy` columns is filled (default: any but the first, as + // templates number every row). + const marks = filledBy ? names.flatMap((n, i) => filledBy.includes(n) ? [i] : []) : names.map((_, i) => i).slice(1) + const body = rows.slice(headerRow + 1).filter((cells) => cells && marks.some((i) => text(cells[i]) !== '')) + if (!body.length) return null + const kept = names.flatMap((n, i) => skip.includes(n) ? [] : [i]) + const line = (cells: string[]) => cells.join('\t') + const tsv = [line(kept.map((i) => names[i])), ...body.map((cells) => line(kept.map((i) => tsvCell(cells[i]))))].join('\n') + '\n' + const columns = Object.fromEntries(kept.map((i) => { + const longName = text(headers[i]) + const units = UNITS[/\((s|sec|seconds|ms|g|mg|kg|cm|mm)\)/i.exec(headers[i].split('\n')[0])?.[1].toLowerCase() ?? ''] + return [names[i], { LongName: longName, ...(units ? { Units: units } : {}) }] + })) + return { tsv, columns } +} + +/** A table read from a sheet: its TSV, and what its columns are. */ +export interface Table { + tsv: string + columns: Record +} + +/** A unit written in a column header, as BIDS writes it. */ +export const UNITS: Record = { s: 's', sec: 's', seconds: 's', ms: 'ms', g: 'g', mg: 'mg', kg: 'kg', cm: 'cm', mm: 'mm' } + +/** "Latency (s)" → `latency_s`; "Correct?" → `correct`; repeats get `_2`, `_3`. */ +export function uniqueColumnNames(headers: string[]): string[] { + const seen = new Map() + return headers.map((h, i) => { + const base = h.split('\n')[0].toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '') || `column_${i + 1}` + const n = (seen.get(base) ?? 0) + 1 + seen.set(base, n) + return n === 1 ? base : `${base}_${n}` + }) +} + +/** One record per column of a sideways sheet, flattened into one row: `day_0_weight`, `day_1_weight`… */ +export function sidewaysRow(rows: CellValue[][] | undefined, header: string, fields: Field[], date1904?: boolean): { columns: string[]; values: string[] } | null { + const at = rows?.findIndex((r) => text(r?.[0]) === header) ?? -1 + if (!rows || at === -1) return null + // Each record keeps its own column, so a blank header cell shifts nothing. + const records = rows[at].map((c, col) => ({ name: text(c), col })).slice(1).filter((r) => r.name) + const keys = uniqueColumnNames(records.map((r) => r.name)) + const columns: string[] = [], values: string[] = [] + keys.forEach((key, i) => { + for (const field of fields) { + const row = rows.slice(at + 1).find((r) => text(r?.[0]) === field.label) + columns.push(`${key}_${field.column}`) + values.push(formatted(row?.[records[i].col] ?? null, field.type, date1904)) + } + }) + return { columns, values } +} + +/** `day_0_weight` → ["Day 0"-like record key, the weight field]. */ +export function splitColumn(column: string, fields: Field[]): [string, Field] { + const field = fields.find((f) => column.endsWith(`_${f.column}`))! + return [column.slice(0, -field.column.length - 1).replace(/_/g, ' ').replace(/^./, (c) => c.toUpperCase()), field] +} + +/** The `tableInfo` cells of a sheet, by key; a cell left empty is left out. */ +export function tableInfo(rows: CellValue[][], fields: NonNullable, date1904?: boolean): Record { + const info: Record = {} + for (const { key, label, type } of fields) { + const found = findLabel(rows, label) + if (!found) continue + const [r, c] = found + if (type === 'list') { + const cells = (rows[r] ?? []).slice(c + 1).map((v) => text(v)).filter(Boolean) + const pairs = cells.map((t) => /^([^:]+?)\s*:\s*(.+)$/.exec(t)) + if (cells.length) info[key] = pairs.every(Boolean) ? Object.fromEntries(pairs.map((m) => [m![1], m![2]])) : cells + } else { + const value = formatted(rows[r][c + 1] ?? null, type, date1904) + if (value !== 'n/a') info[key] = value + } + } + return info +} diff --git a/applications/idp-arc/frontend/src/core/bids/upload.ts b/applications/idp-arc/frontend/src/core/bids/upload.ts new file mode 100644 index 0000000..af21a8d --- /dev/null +++ b/applications/idp-arc/frontend/src/core/bids/upload.ts @@ -0,0 +1,49 @@ +/** Step 1: the upload's workbooks and PDFs, from the file itself or from its zip. */ +import { readZipEntries } from '../zipStream' +import type { Report } from './config' + +/** A workbook or PDF from the upload, its name made path-safe. */ +export interface InputFile { + name: string + bytes: Uint8Array +} + +/** The files an upload is read for: workbooks are converted, PDFs go to logs/. */ +export const CONVERTED = /\.(xlsx|pdf)$/i + +/** The upload's workbooks and PDFs (itself, or a zip's), or null when it can't be opened. */ +export async function openUpload(upload: File, report: Report): Promise { + try { + return await filesOf(upload) + } catch { + report.error(`${upload.name} could not be opened. Is it a valid ${upload.name.toLowerCase().endsWith('.zip') ? 'zip' : 'Excel'} file?`) + return null + } +} + +/** The workbooks and PDFs: the uploaded file, or those in an uploaded zip (folders flattened, + * macOS metadata skipped). Nothing else is read, so a zip's videos never reach memory. */ +export async function filesOf(upload: File): Promise { + if (!upload.name.toLowerCase().endsWith('.zip')) { + return CONVERTED.test(upload.name) ? [{ name: safeName(upload.name), bytes: new Uint8Array(await upload.arrayBuffer()) }] : [] + } + const entries = await readZipEntries(upload, (path) => + CONVERTED.test(path) && !path.startsWith('__MACOSX/') && !baseName(path).startsWith('.')) + const taken = new Set() + return entries.map(({ name: path, bytes }) => { + let name = safeName(baseName(path)) + for (let n = 2; taken.has(name); n++) name = safeName(baseName(path)).replace(/(\.[^.]*)?$/, `-${n}$1`) + taken.add(name) + return { name, bytes } + }) +} + +/** `a/b/c.xlsx` → `c.xlsx`. */ +export function baseName(path: string): string { + return path.slice(path.lastIndexOf('/') + 1) +} + +/** A file name that is safe as one DANDI path segment, keeping the extension. */ +export function safeName(name: string): string { + return name.replace(/[^A-Za-z0-9._ -]+/g, '-').replace(/^[-. ]+/, '') || 'file' +} diff --git a/applications/idp-arc/frontend/src/core/bids/values.ts b/applications/idp-arc/frontend/src/core/bids/values.ts new file mode 100644 index 0000000..8be2d43 --- /dev/null +++ b/applications/idp-arc/frontend/src/core/bids/values.ts @@ -0,0 +1,54 @@ +/** One cell as BIDS text (`n/a`, dates, times), and the text of a TSV or JSON file. */ +import type { CellValue } from './xlsxReader' + +/** A cell as one line of TSV-safe text: tabs and line breaks become spaces, 3.0 becomes 3. */ +export function text(value: CellValue | undefined): string { + if (value === null || value === undefined) return '' + return String(value).replace(/[\t\r\n]+/g, ' ').trim() +} + +/** A cell as TSV text; empty and any spelling of `N/A` become BIDS's `n/a`. */ +export function tsvCell(value: CellValue | undefined): string { + const t = text(value) + return t === '' || /^n\/?a$/i.test(t) ? 'n/a' : t +} + +/** A cell as TSV text, dates and times in a standard form; `n/a` when empty. */ +export function formatted(value: CellValue, type?: 'date' | 'time', date1904?: boolean): string { + if (type === 'date') { + const date = sessionLabel(value, date1904) + if (date) return `${date.slice(0, 4)}-${date.slice(4, 6)}-${date.slice(6)}` + } + if (type === 'time' && typeof value === 'number' && value >= 0) { + // The time of day only, whether or not the cell also holds a date. + const seconds = Math.round((value - Math.floor(value)) * 86400) % 86400 + return [seconds / 3600, (seconds % 3600) / 60, seconds % 60].map((n) => String(Math.floor(n)).padStart(2, '0')).join(':') + } + return tsvCell(value) +} + +/** The session label for a sheet's date: `20260902`, from an Excel date or written-out text. */ +export function sessionLabel(value: CellValue, date1904?: boolean): string | null { + let date: Date | null = null + if (typeof value === 'number' && value > 20000 && value < 80000) { + // Excel's day count, from the workbook's date system; a time part is dropped. + date = new Date((date1904 ? Date.UTC(1904, 0, 1) : Date.UTC(1899, 11, 30)) + Math.floor(value) * 86400000) + } else if (typeof value === 'string') { + const iso = /^(\d{4})-(\d{1,2})-(\d{1,2})/.exec(value.trim()) + const us = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/.exec(value.trim()) // the template's mm/dd/yyyy + if (iso) date = new Date(Date.UTC(+iso[1], +iso[2] - 1, +iso[3])) + else if (us) date = new Date(Date.UTC(+us[3], +us[1] - 1, +us[2])) + } + if (!date || Number.isNaN(date.getTime())) return null + return date.toISOString().slice(0, 10).replace(/-/g, '') +} + +/** A JSON file's text. */ +export function json(value: unknown): string { + return JSON.stringify(value, null, 2) + '\n' +} + +/** A TSV file's text: the header, then one line per row. */ +export function tsvOf(header: string[], rows: string[][]): string { + return [header, ...rows].map((r) => r.join('\t')).join('\n') + '\n' +} diff --git a/applications/idp-arc/frontend/src/core/bids/workbook.ts b/applications/idp-arc/frontend/src/core/bids/workbook.ts new file mode 100644 index 0000000..703c3b1 --- /dev/null +++ b/applications/idp-arc/frontend/src/core/bids/workbook.ts @@ -0,0 +1,111 @@ +/** Step 2: one workbook into its animal, its participants and phenotype rows, and a table per stage. */ +import { readWorkbook, type Workbook } from './xlsxReader' +import type { BidsConfig, Run, Subject } from './config' +import type { InputFile } from './upload' +import { findLabel, labelValue, sidewaysRow, tableInfo, tableToTsv } from './sheet' +import { formatted, json, sessionLabel, text, tsvCell } from './values' + +/** One workbook: its subject, participants row, phenotype rows and tables. */ +export function addWorkbook(run: Run, input: InputFile) { + let workbook: Workbook + try { + workbook = readWorkbook(input.bytes) + } catch { + run.report.error(`${input.name} could not be read as an Excel workbook.`) + return + } + const { subjectId } = run.config + // Other spreadsheets (a weight log, a blank template) travel in sourcedata/ only. + if (!workbook.has(subjectId.sheet) || findLabel(workbook.get(subjectId.sheet)!, subjectId.label) === undefined) return + const subject = readSubject(run, input.name, workbook) + if (!subject) return + run.subjects.push(subject) + addParticipant(run, subject, workbook) + addPhenotypes(run, input.name, subject.id, workbook) + for (const table of run.config.tables) addTable(run, input.name, subject.id, workbook, table) +} + +/** The workbook's subject: its ID (which must be new) and sex, with the metadata rules checked. */ +export function readSubject(run: Run, file: string, workbook: Workbook): Subject | null { + const { config, report } = run + const rawId = labelValue(workbook, config.subjectId) + if (rawId === null) { + report.error(`${file}: "${config.subjectId.label}" on the ${config.subjectId.sheet} sheet is empty.`) + return null + } + const id = String(rawId).replace(/[^A-Za-z0-9]/g, '') + if (!id) { + report.error(`${file}: Animal ID "${rawId}" has no letters or digits.`) + return null + } + // BIDS labels must not differ only in case. + const same = run.subjects.find((s) => s.id.toLowerCase() === id.toLowerCase()) + if (same) { + report.error(same.id === id + ? `${file} and ${same.source} both have Animal ID ${id}.` + : `${file} (Animal ID ${id}) and ${same.source} (${same.id}) have the same Animal ID apart from upper/lower case.`) + return null + } + + const subject: Subject = { id, source: file } + const sex = config.sex ? text(labelValue(workbook, config.sex)) : '' + if (sex) subject.sex = sex + return subject +} + +/** The animal's participants.tsv row: species, sex, and the configured METADATA cells. */ +export function addParticipant(run: Run, subject: Subject, workbook: Workbook) { + const participants = run.config.participants + if (!participants) return + run.participantRows.push([`sub-${subject.id}`, ...(participants.species ? [participants.species] : []), + tsvCell(subject.sex), + ...participants.fields.map((f) => formatted(labelValue(workbook, f), f.type, workbook.date1904))]) +} + +/** The animal's row in each phenotype table, from its sideways sheet (WEIGHT). */ +export function addPhenotypes(run: Run, file: string, id: string, workbook: Workbook) { + for (const table of run.config.phenotype ?? []) { + const read = sidewaysRow(workbook.get(table.sheet), table.header, table.fields, workbook.date1904) + if (!read) { + run.report.warn(`${file}, ${table.sheet} sheet: no "${table.header}" row; left out of phenotype/${table.name}.tsv.`) + continue + } + // Columns are the union across workbooks; a column a workbook lacks is `n/a`. + const found = run.phenotypeRows.get(table.name) ?? { columns: [], rows: [] } + for (const column of read.columns) { + if (found.columns.includes(column)) continue + found.columns.push(column) + for (const row of found.rows) row.push('n/a') + } + found.rows.push([`sub-${id}`, ...found.columns.map((c) => read.values[read.columns.indexOf(c)] ?? 'n/a')]) + run.phenotypeRows.set(table.name, found) + } +} + +/** One configured sheet as `sub-/ses-/beh/..._acq-_beh.tsv`, its cells as they are. */ +export function addTable(run: Run, file: string, id: string, workbook: Workbook, table: BidsConfig['tables'][number]) { + const { config, report } = run + const rows = workbook.get(table.sheet) + const where = `${file}, ${table.sheet} sheet` + // A missing tab or header row is the researcher's to get right: that stage is simply left out. + if (!rows) return + const headerRow = rows.findIndex((r) => text(r[0]) === table.header) + if (headerRow === -1) return + const converted = tableToTsv(rows, headerRow, table.filledBy, config.skipColumns) + if (!converted) return report.warn(`${where}: no rows filled in; left out.`) + + let ses = '' + if (config.sessionDate) { + const date = sessionLabel(labelValue(workbook, { sheet: table.sheet, label: config.sessionDate.label }), workbook.date1904) + if (!date) return report.error(`${where}: "${config.sessionDate.label}" should be the testing date.`) + ses = `ses-${date}` + } + const dir = ses ? `sub-${id}/${ses}/beh` : `sub-${id}/beh` + const name = ['sub-' + id, ses, `task-${config.task}`, `acq-${table.acq}`, 'beh.tsv'].filter(Boolean).join('_') + if (run.files.some((f) => f.path === `${dir}/${name}`)) return report.error(`${where}: a second ${table.acq} table for animal ${id} on the same date.`) + run.files.push({ path: `${dir}/${name}`, content: converted.tsv }) + const info = tableInfo(rows, config.tableInfo ?? [], workbook.date1904) + if (Object.keys(info).length) run.files.push({ path: `${dir}/${name.replace(/\.tsv$/, '.json')}`, content: json(info) }) + const known = run.columnsByAcq.get(table.acq) ?? {} + run.columnsByAcq.set(table.acq, { ...known, ...Object.fromEntries(Object.entries(converted.columns).filter(([c]) => !(c in known))) }) +} diff --git a/applications/idp-arc/frontend/src/core/bids/xlsxReader.ts b/applications/idp-arc/frontend/src/core/bids/xlsxReader.ts new file mode 100644 index 0000000..b2fbbb4 --- /dev/null +++ b/applications/idp-arc/frontend/src/core/bids/xlsxReader.ts @@ -0,0 +1,89 @@ +/** + * Reads the cell values of an .xlsx workbook: just what the BIDS conversion needs, no styles. + * + * Values are what the file has saved. A formula whose result was never saved (the workbook was + * written by a script and never opened in Excel) reads as empty: formulas are never evaluated. + * Element names may carry a namespace prefix (``), as some writers produce. + */ +import { strFromU8, unzipSync } from 'fflate' + +/** A cell's saved value: text, a number (dates are Excel serial numbers), or null when empty. */ +export type CellValue = string | number | null + +/** Sheet name → rows → cells, both 0-based; rows and cells past the last value are left out. + * `date1904`: its date numbers count from 1904-01-01 (an old Mac Excel setting), not 1899-12-30. */ +export type Workbook = Map & { date1904?: boolean } + +export function readWorkbook(bytes: Uint8Array): Workbook { + const files = unzipSync(bytes, { filter: (f) => f.name.startsWith('xl/') && f.name.endsWith('.xml') || f.name.endsWith('.rels') }) + const text = (path: string) => (files[path] ? strFromU8(files[path]) : '') + const workbookXml = text('xl/workbook.xml') + if (!workbookXml) throw new Error('Not an Excel workbook (no xl/workbook.xml)') + + const targets = new Map() + for (const rel of text('xl/_rels/workbook.xml.rels').matchAll(/]*>/g)) { + const id = attr(rel[0], 'Id'), target = attr(rel[0], 'Target') + if (id && target) targets.set(id, target.startsWith('/') ? target.slice(1) : `xl/${target}`) + } + const shared = [...text('xl/sharedStrings.xml').matchAll(/<(?:\w+:)?si>([\s\S]*?)<\/(?:\w+:)?si>/g)].map((m) => textRuns(m[1])) + + const workbook: Workbook = new Map() + if (/<(?:\w+:)?workbookPr\b[^>]*\sdate1904="(1|true)"/.test(workbookXml)) workbook.date1904 = true + for (const sheet of workbookXml.matchAll(/<(?:\w+:)?sheet\b[^>]*>/g)) { + const name = attr(sheet[0], 'name'), path = targets.get(attr(sheet[0], 'r:id') ?? '') + if (name && path) workbook.set(decode(name), readSheet(text(path), shared)) + } + return workbook +} + +function readSheet(xml: string, shared: string[]): CellValue[][] { + const rows: CellValue[][] = [] + for (const cell of xml.matchAll(/<(?:\w+:)?c\b([^>]*?)(?:\/>|>([\s\S]*?)<\/(?:\w+:)?c>)/g)) { + const ref = attr(cell[1], 'r') + const value = cellValue(attr(cell[1], 't'), cell[2] ?? '', shared) + if (!ref || value === null) continue + const [col, row] = position(ref) + ;(rows[row] ??= [])[col] = value + } + // Fill the gaps the sparse assignment leaves, so every row and cell reads as an array value. + return Array.from(rows, (r) => Array.from(r ?? [], (c) => c ?? null)) +} + +function cellValue(type: string | undefined, body: string, shared: string[]): CellValue { + if (type === 'inlineStr') return emptyToNull(textRuns(body)) + const v = /<(?:\w+:)?v>([\s\S]*?)<\/(?:\w+:)?v>/.exec(body)?.[1] + if (v === undefined || v === '') return null + if (type === 's') return emptyToNull(shared[Number(v)] ?? '') + if (type === 'str' || type === 'e') return emptyToNull(decode(v)) + if (type === 'b') return v === '1' ? 'TRUE' : 'FALSE' + const n = Number(v) + return Number.isFinite(n) ? n : decode(v) +} + +/** "C10" → [2, 9]. */ +function position(ref: string): [number, number] { + const m = /^([A-Z]+)(\d+)$/.exec(ref) + if (!m) return [0, 0] + const col = [...m[1]].reduce((n, ch) => n * 26 + ch.charCodeAt(0) - 64, 0) + return [col - 1, Number(m[2]) - 1] +} + +/** All `` text in a string item, rich-text runs included. */ +function textRuns(xml: string): string { + return [...xml.matchAll(/<(?:\w+:)?t\b[^>]*>([\s\S]*?)<\/(?:\w+:)?t>/g)].map((m) => decode(m[1])).join('') +} + +function attr(tag: string, name: string): string | undefined { + return new RegExp(`\\s${name}="([^"]*)"`).exec(tag)?.[1] +} + +function emptyToNull(s: string): string | null { + return s === '' ? null : s +} + +const ENTITIES: Record = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'" } + +function decode(s: string): string { + return s.replace(/&(#x[0-9a-fA-F]+|#\d+|\w+);/g, (whole, e: string) => + e[0] === '#' ? String.fromCodePoint(Number(e[1] === 'x' ? `0${e.slice(1)}` : e.slice(1))) : ENTITIES[e] ?? whole) +} diff --git a/applications/idp-arc/frontend/src/core/dandiInstances.ts b/applications/idp-arc/frontend/src/core/dandiInstances.ts new file mode 100644 index 0000000..7b4012b --- /dev/null +++ b/applications/idp-arc/frontend/src/core/dandiInstances.ts @@ -0,0 +1,38 @@ +/** The DANDI deployments the app can use, by the name OSB and dandi-cli know them by: EMBER-DANDI, + * and the two sandboxes for local testing. */ +export const DANDI_INSTANCES = { + 'ember-dandi': { api: 'https://api-dandi.emberarchive.org', web: 'https://dandi.emberarchive.org' }, + 'ember-dandi-sandbox': { api: 'https://api-dandi.sandbox.emberarchive.org', web: 'https://dandi.sandbox.emberarchive.org' }, + 'dandi-sandbox': { api: 'https://api.sandbox.dandiarchive.org', web: 'https://sandbox.dandiarchive.org' }, +} as const + +export type DandiInstanceName = keyof typeof DANDI_INSTANCES + +export const DEFAULT_DANDI_INSTANCE: DandiInstanceName = 'ember-dandi' + +export interface DandiInstance { + name: DandiInstanceName + /** The API's origin, and the web UI's. */ + api: string + web: string +} + +export const isDandiInstanceName = (name: string): name is DandiInstanceName => Object.hasOwn(DANDI_INSTANCES, name) + +/** The instance VITE_DANDI_INSTANCE names; EMBER-DANDI when it is empty. Throws for any other name. */ +export function dandiInstance(configured?: string): DandiInstance { + const name = (configured ?? '').trim() || DEFAULT_DANDI_INSTANCE + if (!isDandiInstanceName(name)) { + throw new Error(`VITE_DANDI_INSTANCE "${name}" is not a DANDI instance; use one of: ${Object.keys(DANDI_INSTANCES).join(', ')}.`) + } + return { name, ...DANDI_INSTANCES[name] } +} + +/** The protocol's MAABCD dandiset on `instance` (protocols.json `maabcdAggregateDandisets`); + * undefined when it has none there. */ +export function maabcdDandisetFor( + protocol: { maabcdAggregateDandisets?: Readonly> }, + instance: DandiInstanceName, +): string | undefined { + return protocol.maabcdAggregateDandisets?.[instance] || undefined +} diff --git a/applications/idp-arc/frontend/src/core/dandisetLinks.ts b/applications/idp-arc/frontend/src/core/dandisetLinks.ts index b715e88..5f6d010 100644 --- a/applications/idp-arc/frontend/src/core/dandisetLinks.ts +++ b/applications/idp-arc/frontend/src/core/dandisetLinks.ts @@ -1,5 +1,5 @@ /** - * What an IDP dandiset is for, recorded in its own EMBER-DANDI metadata: the protocol it holds + * What a MAABCD dandiset is for, recorded in its own EMBER-DANDI metadata: the protocol it holds * data for, and the OSB workspace that data runs in. Choosing a protocol in the upload dialog lists * the researcher's dandisets for that protocol, and picking one picks its workspace too. * @@ -12,7 +12,7 @@ /** A dandiset's draft metadata document, exactly as EMBER returns it. Written back whole. */ export type DandisetMetadata = Record -const PROTOCOL_PREFIX = 'idp-protocol:' +const PROTOCOL_PREFIX = 'maabcd-protocol:' const WORKSPACE_PREFIX = 'osb-workspace' /** The identifier of a protocol's link, as recorded in the metadata (and found by EMBER's search). */ @@ -64,7 +64,7 @@ export function withProtocolLink( return withEntry(metadata, PROTOCOL_PREFIX, { schemaKey: 'Resource', identifier: protocolLinkId(protocol.id), - name: `IDP protocol: ${protocol.name}`, + name: `MAABCD protocol: ${protocol.name}`, ...(protocol.url ? { url: protocol.url } : {}), relation: 'dcite:IsDescribedBy', }) diff --git a/applications/idp-arc/frontend/src/core/dandisetReadme.ts b/applications/idp-arc/frontend/src/core/dandisetReadme.ts new file mode 100644 index 0000000..ba39ee7 --- /dev/null +++ b/applications/idp-arc/frontend/src/core/dandisetReadme.ts @@ -0,0 +1,65 @@ +/** + * The README that travels with an upload: it says which dandiset the data is in, so whoever opens + * the OSB workspace can find it. It goes inside the uploaded zip, which OSB's import unpacks next to + * the data; a plain file is zipped with it. Neither is loaded into memory, so any size works. + * + * The zip is the same bytes every time for the same file and README (its entries dated with the + * file's own modified date, no clock in the text): a retry recomputes the DANDI etag, and the upload + * checkpoint relies on it not changing. + */ +import { readZipIndex, withEntry, zipOf } from './zipStream' + + +export interface DandisetReadmeInput { + /** The dandiset's own name. */ + name: string + dandisetId: string + /** The dandiset's page on the archive's website. */ + dandisetUrl: string + protocol: { name: string; url?: string; description?: string } + /** The name of the file the researcher uploaded. */ + originalName: string + /** The dandiset folder the upload goes into, e.g. `sourcedata/upload-`. */ + folder: string +} + +export function dandisetReadme({ name, dandisetId, dandisetUrl, protocol, originalName, folder }: DandisetReadmeInput): string { + return [ + `# ${name}`, + '', + `Behavioral data from the ${protocol.name}.`, + '', + ...(protocol.description ? [protocol.description, ''] : []), + '## Files', + '', + `- \`${originalName}\`: the researcher's upload. Every file here except this README comes from it, unchanged.`, + '', + '## Where it is', + '', + `- Dandiset ${dandisetId}: ${dandisetUrl}`, + `- This upload: \`${folder}/\` in that dandiset.`, + '- The tables made from it: the dandiset\'s `sub-/` folders, described in its top-level `README.md`.', + '', + '## How to cite', + '', + `Cite a published version of dandiset ${dandisetId} by its DOI, listed on the dandiset's page. Uploads go to its draft, which has no DOI.`, + '', + ...(protocol.url ? ['## Analysis code', '', `- ${protocol.url}`, ''] : []), + ].join('\n') +} + +/** The file to upload: `file` with `readme` added (into it if it is a zip, else zipped together). + * A zip's own entries stay byte for byte, except a README.md of its own, which ours replaces. */ +export async function withReadme(file: File, readme: string): Promise { + // Every entry is dated when the researcher last saved the file. + const date = new Date(file.lastModified) + const data = new TextEncoder().encode(readme) + const index = file.name.toLowerCase().endsWith('.zip') ? await readZipIndex(file) : null + if (index) { + return new File([withEntry(file, index, { name: 'README.md', data, date })], file.name, { type: 'application/zip', lastModified: date.getTime() }) + } + // A single file, or a .zip that can't be read: carried inside a new zip, as it is. + const zipped = await zipOf([{ name: 'README.md', data, date }, { name: file.name, data: file, date }]) + const name = `${file.name.replace(/\.[^.]*$/, '') || file.name}.zip` + return new File([zipped], name, { type: 'application/zip', lastModified: date.getTime() }) +} diff --git a/applications/idp-arc/frontend/src/core/pathSafe.ts b/applications/idp-arc/frontend/src/core/pathSafe.ts new file mode 100644 index 0000000..33f847f --- /dev/null +++ b/applications/idp-arc/frontend/src/core/pathSafe.ts @@ -0,0 +1,9 @@ +/** One DANDI asset path segment: DANDI rejects `@` and the like, and `/` would add segments. + * Runs of other characters become one `-`; none is left dangling before the extension. */ +export function pathSafe(value: string): string { + return value + .replace(/[^A-Za-z0-9._-]+/g, '-') + .replace(/-{2,}/g, '-') + .replace(/-+(\.[A-Za-z0-9]+)?$/, '$1') + .replace(/^[-._]+|[-._]+$/g, '') || 'unknown' +} diff --git a/applications/idp-arc/frontend/src/core/ports/IDandiDirectApi.ts b/applications/idp-arc/frontend/src/core/ports/IDandiDirectApi.ts index b506e64..5f8e977 100644 --- a/applications/idp-arc/frontend/src/core/ports/IDandiDirectApi.ts +++ b/applications/idp-arc/frontend/src/core/ports/IDandiDirectApi.ts @@ -35,6 +35,8 @@ export interface DirectFinalizeInput { path: string parts: DirectUploadedPart[] blobId?: string + /** A file already at `path` with other content is replaced; by default it is kept. */ + replace?: boolean } /** An asset as registered in a dandiset's draft. */ @@ -129,4 +131,7 @@ export interface IDandiDirectApi { /** complete → validate → register the asset, all direct to EMBER. */ finalizeUpload(token: string, input: DirectFinalizeInput): Promise + + /** The content of the draft's file at `path`, as text; null when there is none. */ + readDraftFile(token: string, dandisetId: string, path: string): Promise } diff --git a/applications/idp-arc/frontend/src/core/ports/IObjectStore.ts b/applications/idp-arc/frontend/src/core/ports/IObjectStore.ts index 0f9a119..706c83f 100644 --- a/applications/idp-arc/frontend/src/core/ports/IObjectStore.ts +++ b/applications/idp-arc/frontend/src/core/ports/IObjectStore.ts @@ -1,3 +1,5 @@ +import type { BidsConfig } from '../bids/convert' + /** * Where a researcher's upload is stored before OSB imports it into the workspace: EMBER-DANDI * (emberObjectStore.ts) or a public bucket (publicBucketObjectStore.ts). The run doesn't know which. @@ -19,14 +21,24 @@ export interface ObjectUploadInput { user?: string newName?: string /** Recorded in the dandiset's metadata, with the workspace the run uses. */ - protocol?: { id: string; name: string; url?: string } - /** The protocol's MAABCD dandiset (protocols.json `maabcdAggregateDandisetId`), uploaded to through OSB. */ + protocol?: { id: string; name: string; url?: string; description?: string } + /** The protocol's MAABCD dandiset (protocols.json `maabcdAggregateDandisets`, for the instance in use), uploaded to through OSB. */ maabcd?: string } + /** How the file goes into the dandiset as BIDS (the protocol's `bids` block): the file itself in + * `sourcedata/`, the tables made from it beside it. EMBER-DANDI only; the bucket ignores it. */ + bids: { + config: BidsConfig + protocol: { name: string; description?: string; url?: string } + /** The dataset's authors when the EMBER-DANDI account has no name to give. */ + authors?: string[] + } /** From an earlier, interrupted put of the same file: what it already did is not done again. */ resume?: UploadCheckpoint /** Gets the checkpoint each time a part of the upload is done. */ onCheckpoint?: (checkpoint: UploadCheckpoint) => void + /** Called as each BIDS file made from the upload is written (after the file itself). */ + onBidsProgress?: (written: number, total: number) => void } /** An uploaded file, as plain data: kept with the run's checkpoint, which is saved across reloads. */ @@ -42,6 +54,8 @@ export interface StoredObject { dandisetId?: string /** EMBER-DANDI: the file's DANDI etag, so the MAABCD copy needs no file. */ etag?: string + /** EMBER-DANDI: the README packed into the upload (dandisetReadme.ts), to rebuild the same bytes from the file. */ + readme?: string } export interface IObjectStore { diff --git a/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts b/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts index 03bfef9..802b1b3 100644 --- a/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts +++ b/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts @@ -4,8 +4,13 @@ import type { IEmberAuth } from '../ports/IEmberAuth' import type { IEmberUploadApi } from '../ports/IEmberUploadApi' import type { IObjectStore, ObjectUploadInput, StoredObject } from '../ports/IObjectStore' import { computeDandiEtag, type PartPlan } from '../dandiEtag' +import { dandisetReadme, withReadme } from '../dandisetReadme' +import { convertToBids, type OutputFile } from '../bids/convert' +import { isMergedFile, mergeWithDraft } from '../bids/merge' +import { pathSafe } from '../pathSafe' +import { utcStamp } from '../workspaceLayout' import { EMBER_SIGN_IN, UserFacingError } from '../userMessages' -import type { ProtocolDandisets } from './protocolDandisets' +import { DANDISET_LICENSE, type ProtocolDandisets } from './protocolDandisets' export { EMBER_SIGN_IN } @@ -31,21 +36,27 @@ export interface EmberUploadCheckpoint { path?: string /** Their own copy, once registered. */ own?: { assetId: string; assetPath: string } + /** BIDS files made from it already in the dandiset, by path. */ + bidsDone?: string[] } +/** How many BIDS files are written at once: the browser opens at most ~6 connections per host. */ +export const BIDS_WRITES_AT_ONCE = 4 + export function createEmberObjectStore( osbAuth: Pick, - emberAuth: Pick, + emberAuth: Pick, direct: IDandiDirectApi, osb: IEmberUploadApi, dandisets: Pick, /** EMBER's public API origin (`https://api-dandi.emberarchive.org`): the download link has to * work from OSB's cluster, so never the browser's same-origin proxy. */ emberApiOrigin: string, + /** EMBER-DANDI's web origin (`https://dandi.emberarchive.org`): the dandiset page in the README. */ + emberWebOrigin: string, ): IObjectStore { return { async put(input: ObjectUploadInput, onProgress?: (sentBytes: number, totalBytes: number) => void): Promise { - const { file } = input const token = emberAuth.getToken() if (!token) throw new UserFacingError(EMBER_SIGN_IN, 'No EMBER-DANDI token (not signed in, or it expired)') const saved: EmberUploadCheckpoint = { ...(input.resume as EmberUploadCheckpoint | undefined) } @@ -54,18 +65,36 @@ export function createEmberObjectStore( input.onCheckpoint?.({ ...saved }) } + // What goes up is the file with the README packed in, once the dandiset (its link) is known. + let file = input.file const progress = (sent: number) => onProgress?.(Math.min(sent, file.size), file.size) progress(saved.own ? file.size : 0) // The researcher's own copy. const protocol = input.dandisets?.protocol ?? { id: input.protocolId, name: input.protocolId } const userDandisetId = saved.userDandisetId || input.dandisets?.user - || await dandisets.createForProtocol(input.dandisets?.newName || `IDP upload: ${protocol.name}`, protocol) + || await dandisets.createForProtocol(input.dandisets?.newName || protocol.name, protocol) if (saved.userDandisetId !== userDandisetId) save({ userDandisetId }) + // The dandiset's own name: a re-upload into an existing one keeps the name it has. + const name = await dandisetName(token, userDandisetId) || input.dandisets?.newName || protocol.name + // The upload is the dataset's source data, one folder per upload: BIDS leaves sourcedata/ unchecked. + const folder = saved.path ? saved.path.slice(0, saved.path.lastIndexOf('/')) : `sourcedata/upload-${utcStamp(new Date())}` + const readme = dandisetReadme({ + name, + dandisetId: userDandisetId, + dandisetUrl: `${emberWebOrigin.replace(/\/+$/, '')}/dandiset/${userDandisetId}`, + protocol, + originalName: input.file.name, + folder, + }) + file = await withReadme(input.file, readme) + const path = saved.path ?? `${folder}/${pathSafe(file.name)}` + // Converted and checked before anything is written, so a problem leaves the dandiset as it was. + const files = await bidsFilesFor(input.file, input.bids, { name, authors: await authorsOf(input.bids.authors) }, path) + await checkAnimalIds(token, userDandisetId, files) let asset = saved.own if (!asset) { const { etag, parts: plan } = await computeDandiEtag(file) - const path = saved.path ?? `${pathSafe(input.protocolId)}/${crypto.randomUUID()}/${pathSafe(file.name)}` save({ etag, path }) const init = await direct.initUpload(token, userDandisetId, file.size, etag) const uploaded = await putParts(init.parts, plan, file, progress) @@ -74,6 +103,7 @@ export function createEmberObjectStore( }) save({ own: { assetId: asset.assetId, assetPath: asset.assetPath } }) } + await putBidsFiles(token, userDandisetId, files, saved, save, input.onBidsProgress) progress(file.size) return { @@ -83,6 +113,7 @@ export function createEmberObjectStore( size: file.size, dandisetId: userDandisetId, etag: saved.etag, + readme, } }, @@ -90,7 +121,9 @@ export function createEmberObjectStore( if (stored.dandisetId) await dandisets.recordWorkspace(stored.dandisetId, workspaceId, protocol) }, - async shareWithMaabcd(stored, dandisetId, file) { + async shareWithMaabcd(stored, dandisetId, original) { + // The bytes of the researcher's copy: the same README packed in the same way. + const file = original && stored.readme ? await withReadme(original, stored.readme) : original const hashed = !stored.etag && file ? await computeDandiEtag(file) : undefined const etag = stored.etag ?? hashed?.etag if (!etag) throw new Error('The MAABCD copy needs the file\'s checksum, but no file is selected (the page was reloaded)') @@ -112,6 +145,94 @@ export function createEmberObjectStore( }, } + /** BIDS files from an upload's file, as put makes them; `source` is where the upload itself is. */ + async function bidsFilesFor(file: File, bids: ObjectUploadInput['bids'], made: { name: string; authors?: string[] }, + source: string): Promise { + const conversion = await convertToBids(file, bids.config, { + name: made.name, + protocol: bids.protocol, + license: DANDISET_LICENSE[0].replace(/^spdx:/, ''), + authors: made.authors, + source, + }) + const problem = conversion.problems.find((p) => p.level === 'error') + if (problem) throw new UserFacingError(problem.message) + // The upload itself is already in sourcedata/ (with its README): only what was made from it. + return conversion.files.filter((f) => !f.path.startsWith('sourcedata/')) + } + + /** Stops an Animal ID the dandiset already has in other upper/lower case: BIDS labels must not differ only in case. */ + async function checkAnimalIds(token: string, dandisetId: string, files: OutputFile[]) { + const incoming = files.find((f) => f.path === 'participants.tsv')?.content + if (typeof incoming !== 'string') return + const existing = await direct.readDraftFile(token, dandisetId, 'participants.tsv') + if (!existing) return + const ids = (tsv: string) => tsv.split('\n').slice(1).map((l) => l.split('\t')[0]).filter(Boolean) + const known = new Map(ids(existing).map((id) => [id.toLowerCase(), id])) + for (const id of ids(incoming)) { + const other = known.get(id.toLowerCase()) + if (other && other !== id) { + const [mine, theirs] = [id.replace(/^sub-/, ''), other.replace(/^sub-/, '')] + throw new UserFacingError(`Animal ID ${mine} is already in this dandiset as ${theirs}. Write it ${theirs} to update that animal, or use a different ID.`) + } + } + } + + /** `content`, merged with the dandiset's copy at `draftPath` when `path` is a per-animal file. */ + async function mergedWithDraft(token: string, dandisetId: string, path: string, draftPath: string, + content: OutputFile['content']): Promise { + const existing = isMergedFile(path) ? await direct.readDraftFile(token, dandisetId, draftPath) : null + if (existing === null) return content + const incoming = typeof content === 'string' ? content : content instanceof Blob ? await content.text() : new TextDecoder().decode(content) + return mergeWithDraft(path, existing, incoming) + } + + /** The EMBER-DANDI account's name, which the archive credits; `fallback` when it has none or can't be read. */ + async function authorsOf(fallback: string[] | undefined): Promise { + const account = await emberAuth.getAccount().catch(() => null) + const name = account?.name?.trim() + return name ? [name] : fallback + } + + async function dandisetName(token: string, dandisetId: string): Promise { + const { name } = await direct.getDraftMetadata(token, dandisetId) + return typeof name === 'string' && name.trim() ? name.trim() : undefined + } + + /** Each BIDS file into the dandiset, BIDS_WRITES_AT_ONCE at a time; one already there with other + * content is replaced (a shared description, or a corrected table), except the per-animal files, + * which are merged with it. Each is recorded, so a retry skips it. After a failure no new write + * starts; the running ones finish, then the failure is thrown. */ + async function putBidsFiles(token: string, dandisetId: string, files: OutputFile[], saved: EmberUploadCheckpoint, + save: (patch: EmberUploadCheckpoint) => void, onWritten?: (written: number, total: number) => void) { + const todo = files.filter((f) => !saved.bidsDone?.includes(f.path)) + let written = files.length - todo.length + onWritten?.(written, files.length) + let failure: { error: unknown } | undefined + const worker = async () => { + for (let next = todo.shift(); next && !failure; next = todo.shift()) { + try { + await putBidsFile(token, dandisetId, next) + save({ bidsDone: [...(saved.bidsDone ?? []), next.path] }) + onWritten?.(++written, files.length) + } catch (error) { + failure ??= { error } + } + } + } + await Promise.all(Array.from({ length: BIDS_WRITES_AT_ONCE }, worker)) + if (failure) throw failure.error + } + + async function putBidsFile(token: string, dandisetId: string, { path, content }: OutputFile) { + const merged = await mergedWithDraft(token, dandisetId, path, path, content) + const file = new File([merged as BlobPart], path.slice(path.lastIndexOf('/') + 1)) + const { etag, parts: plan } = await computeDandiEtag(file) + const init = await direct.initUpload(token, dandisetId, file.size, etag) + const uploaded = await putParts(init.parts, plan, file, () => {}) + await direct.finalizeUpload(token, { uploadId: init.uploadId, dandisetId, path, parts: uploaded, blobId: init.blobId, replace: true }) + } + async function putParts(parts: { partNumber: number; url: string }[], plan: PartPlan[], file: File, report: (sentInTransfer: number) => void) { // Every part or none (deduplicated): a shorter list would silently upload a truncated file. @@ -131,8 +252,3 @@ export function createEmberObjectStore( return result } } - -/** One asset path segment: DANDI rejects `@` and the like; also stops `/` adding segments. */ -function pathSafe(value: string): string { - return value.replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^[-._]+|[-._]+$/g, '') || 'unknown' -} diff --git a/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts b/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts index 55eec41..d7f7e77 100644 --- a/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts +++ b/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts @@ -4,6 +4,7 @@ import { RUN_STEP, type RunCheckpoint, type RunStep, type RunStepId } from '../t import type { IWorkspaceApi, WorkspaceResourceState } from '../ports/IWorkspaceApi' import { formatBytes } from '../formatBytes' import { inputFileProblem } from '../inputFormats' +import type { BidsConfig } from '../bids/convert' import { parseRepoZipUrl, repoPage } from '../protocolRepo' import { RUN_SETTINGS } from '../runSettings' import { DONE_EARLIER, UserFacingError, userMessage } from '../userMessages' @@ -29,9 +30,14 @@ export interface RunProtocolDefinition { /** The image the notebooks run in (their environment): an OSB application's name (e.g. `netpyne`) * or an image reference from a registry OSB allows. Without it, OSB's default (JupyterLab). */ image?: string - /** The protocol's MAABCD dandiset on EMBER-DANDI, which each upload is also copied into - * (through OSB). Empty or absent: no MAABCD copy. */ + /** The protocol's MAABCD dandiset on the DANDI instance in use (protocols.json + * `maabcdAggregateDandisets`), which each upload is also copied into (through OSB). Empty or + * absent: no MAABCD copy. */ maabcdAggregateDandisetId?: string + /** What the task is: the BIDS dataset's description. */ + description?: string + /** How the researcher's spreadsheets become BIDS. */ + bids: BidsConfig } export interface RunProtocolInput { @@ -45,6 +51,10 @@ export interface RunProtocolInput { /** The researcher's EMBER-DANDI dandiset to upload into; undefined creates one. The bucket * ignores it. */ dandisetId?: string + /** Name for the dandiset created when `dandisetId` is undefined; the protocol's name when empty. */ + dandisetName?: string + /** The researcher's OSB name: the author of the BIDS dataset when their EMBER-DANDI account has none. */ + researcher?: string /** Also upload into the protocol's MAABCD dandiset, when it has one (the default). */ shareWithMaabcd?: boolean /** From an earlier attempt that stopped: the run carries on from there when canResume allows. */ @@ -284,12 +294,15 @@ export function createRunProtocolUseCase( file, protocolId: protocol.id, userSub: userId, resume: checkpoint.upload, onCheckpoint: (upload) => save({ upload }), + // After the file itself, the BIDS files made from it go up one by one: shown, so it isn't taken for stuck. + onBidsProgress: (written, total) => progress.update(RUN_STEP.upload, `Writing BIDS files: ${written} of ${total}`, message), dandisets: { user: input.dandisetId, - newName: `${protocol.name} (IDP)`, - protocol: protocolRef(), + newName: input.dandisetName?.trim() || protocol.name, + protocol: { ...protocolRef(), description: protocol.description }, maabcd: input.shareWithMaabcd === false ? undefined : protocol.maabcdAggregateDandisetId, }, + bids: bidsInput(), }, (sent, total) => { if (Date.now() - lastReport < RUN_SETTINGS.uploadProgressMs && sent < total) return lastReport = Date.now() @@ -306,6 +319,15 @@ export function createRunProtocolUseCase( return { id: protocol.id, name: protocol.name, url: repoPage(protocol.repoZipUrl) } } + /** How the upload is put into the researcher's dandiset as BIDS (the MAABCD copy is the zip only). */ + function bidsInput() { + return { + config: protocol.bids, + protocol: { ...protocolRef(), description: protocol.description }, + ...(input.researcher ? { authors: [input.researcher] } : {}), + } + } + /** The MAABCD copy's step; a failure is left for its Retry. */ async function shareWithMaabcd(stored: StoredObject | null) { if (!stored || !objectStore.shareWithMaabcd) return progress.skip(RUN_STEP.maabcd) diff --git a/applications/idp-arc/frontend/src/core/workspaceLayout.ts b/applications/idp-arc/frontend/src/core/workspaceLayout.ts index f3c206a..392e7ca 100644 --- a/applications/idp-arc/frontend/src/core/workspaceLayout.ts +++ b/applications/idp-arc/frontend/src/core/workspaceLayout.ts @@ -22,10 +22,13 @@ const FAILED_SUFFIX = '.failed' /** The run task's log. */ const LOG_FILE = 'run.log' +/** A UTC time as a folder name: no `:` (not allowed on Windows or in macOS Finder); sorts in order. */ +export function utcStamp(at: Date): string { + return at.toISOString().replace(/\.\d+Z$/, 'Z').replace(/:/g, '-') +} + export function workspaceLayout(protocolId: string, startedAt: Date) { - // No `:` (not allowed in file names on Windows or in macOS Finder); sorts in run order. - const stamp = startedAt.toISOString().replace(/\.\d+Z$/, 'Z').replace(/:/g, '-') - const run = `${protocolId}/run-${protocolId}-${stamp}` + const run = `${protocolId}/run-${protocolId}-${utcStamp(startedAt)}` return { run, inputs: `${run}/${INPUTS_DIR}`, diff --git a/applications/idp-arc/frontend/src/core/zipStream.ts b/applications/idp-arc/frontend/src/core/zipStream.ts new file mode 100644 index 0000000..a3369cc --- /dev/null +++ b/applications/idp-arc/frontend/src/core/zipStream.ts @@ -0,0 +1,320 @@ +/** + * Zips read and written without loading them into memory, so an upload of any size works (a zip + * with videos, say). Reading goes through the zip's table of contents and slices out only the + * entries asked for; writing builds the new zip from slices of the old one, which the browser reads + * only when sent. ZIP64 (over 4 GB, or over 65,535 entries) is read and written. + */ +import { inflateSync } from 'fflate' + +export interface ZipEntry { + name: string + bytes: Uint8Array +} + +/** A file to put in a zip, stored as it is (no compression). */ +export interface NewEntry { + name: string + data: Blob | Uint8Array + date: Date +} + +/** The entries `keep` accepts, decompressed; the bytes of every other entry are never read. + * Throws when `zip` is not a readable zip, or a kept entry can't be decompressed. */ +export async function readZipEntries(zip: Blob, keep: (name: string) => boolean): Promise { + const index = await readZipIndex(zip) + if (!index) throw new Error('Not a readable zip') + const kept: ZipEntry[] = [] + for (const entry of index.entries) { + if (!keep(entry.name)) continue + const local = viewOf(await bytesOf(zip.slice(entry.localOffset, entry.localOffset + 30))) + if (local.byteLength < 30 || local.getUint32(0, true) !== LOCAL_SIG) throw new Error(`${entry.name}: no local header`) + const start = entry.localOffset + 30 + local.getUint16(26, true) + local.getUint16(28, true) + const raw = await bytesOf(zip.slice(start, start + entry.compressedSize)) + if (raw.length !== entry.compressedSize) throw new Error(`${entry.name}: truncated`) + if (entry.method === 0) kept.push({ name: entry.name, bytes: raw }) + else if (entry.method === 8) kept.push({ name: entry.name, bytes: inflateSync(raw, { out: new Uint8Array(entry.size) }) }) + else throw new Error(`${entry.name}: compression method ${entry.method} is not supported`) + } + return kept +} + +/** An entry as the table of contents lists it. */ +export interface IndexEntry { + name: string + method: number + compressedSize: number + size: number + localOffset: number + /** Where its record sits in the table of contents: [start, end), from the table's start. */ + record: [number, number] +} + +/** Where a zip's table of contents is, and what it lists. */ +export interface ZipIndex { + entries: IndexEntry[] + names: string[] + count: number + cdOffset: number + cdSize: number + comment: Uint8Array +} + +/** The zip's table of contents, read from its end; null when `zip` is not a readable zip. */ +export async function readZipIndex(zip: Blob): Promise { + const tailStart = Math.max(0, zip.size - (EOCD_SIZE + MAX16 + LOCATOR_SIZE)) + const tail = await bytesOf(zip.slice(tailStart)) + const view = viewOf(tail) + let at = -1 + for (let i = tail.length - EOCD_SIZE; i >= 0; i--) { + if (view.getUint32(i, true) === EOCD_SIG && i + EOCD_SIZE + view.getUint16(i + 20, true) === tail.length) { at = i; break } + } + if (at === -1) return null + let count = view.getUint16(at + 10, true) + let cdSize = view.getUint32(at + 12, true) + let cdOffset = view.getUint32(at + 16, true) + const comment = tail.slice(at + EOCD_SIZE) + let recordsStart = tailStart + at + // Maxed-out fields point to the ZIP64 records; a zip of exactly 65,535 entries may have none. + const hasZip64 = at >= LOCATOR_SIZE && view.getUint32(at - LOCATOR_SIZE, true) === LOCATOR_SIG + if ((count === MAX16 || cdSize === MAX32 || cdOffset === MAX32) && hasZip64) { + const zip64At = Number(view.getBigUint64(at - LOCATOR_SIZE + 8, true)) + if (zip64At + ZIP64_EOCD_SIZE > zip.size) return null + const zip64 = viewOf(await bytesOf(zip.slice(zip64At, zip64At + ZIP64_EOCD_SIZE))) + if (zip64.getUint32(0, true) !== ZIP64_EOCD_SIG) return null + count = Number(zip64.getBigUint64(32, true)) + cdSize = Number(zip64.getBigUint64(40, true)) + cdOffset = Number(zip64.getBigUint64(48, true)) + recordsStart = zip64At + } + if (cdOffset + cdSize > recordsStart) return null + const entries = centralEntries(await bytesOf(zip.slice(cdOffset, cdOffset + cdSize)), count) + return entries && { entries, names: entries.map((e) => e.name), count, cdOffset, cdSize, comment } +} + +/** `zip` with `entry` added, in place of any entry of the same name: the other entries stay byte + * for byte; the new one is listed first. */ +export function withEntry(zip: Blob, index: ZipIndex, entry: NewEntry & { data: Uint8Array }): Blob { + const header = { name: encode(entry.name), crc: crc32(0, entry.data), size: entry.data.length, date: entry.date, offset: index.cdOffset } + const local = localHeader(header) + const central = centralHeader(header) + const cdOffset = index.cdOffset + local.length + entry.data.length + // The table of contents without the replaced entries' records (their bytes stay, unlisted). + const kept = index.entries.filter((e) => e.name !== entry.name) + const records = kept.map((e) => zip.slice(index.cdOffset + e.record[0], index.cdOffset + e.record[1])) + const recordsSize = kept.reduce((n, e) => n + e.record[1] - e.record[0], 0) + return new Blob([ + zip.slice(0, index.cdOffset), local, entry.data, central, ...records, + endRecords(kept.length + 1, recordsSize + central.length, cdOffset, index.comment), + ] as BlobPart[]) +} + +/** A new zip of `entries`, in that order; a Blob entry is read in chunks for its checksum only. */ +export async function zipOf(entries: NewEntry[]): Promise { + const parts: BlobPart[] = [] + const centrals: Uint8Array[] = [] + let offset = 0 + for (const entry of entries) { + const crc = entry.data instanceof Blob ? await crcOf(entry.data) : crc32(0, entry.data) + const size = entry.data instanceof Blob ? entry.data.size : entry.data.length + const header = { name: encode(entry.name), crc, size, date: entry.date, offset } + const local = localHeader(header) + parts.push(local as BlobPart, entry.data as BlobPart) + centrals.push(centralHeader(header)) + offset += local.length + size + } + const cdSize = centrals.reduce((n, c) => n + c.length, 0) + return new Blob([...parts, ...centrals, endRecords(entries.length, cdSize, offset, new Uint8Array(0))] as BlobPart[]) +} + +const LOCAL_SIG = 0x04034b50 +const CENTRAL_SIG = 0x02014b50 +const EOCD_SIG = 0x06054b50 +const ZIP64_EOCD_SIG = 0x06064b50 +const LOCATOR_SIG = 0x07064b50 +const EOCD_SIZE = 22 +const ZIP64_EOCD_SIZE = 56 +const LOCATOR_SIZE = 20 +const MAX16 = 0xffff +const MAX32 = 0xffffffff +/** General-purpose flag: names are UTF-8. */ +const UTF8 = 0x0800 + +interface Header { + name: Uint8Array + crc: number + size: number + date: Date + offset: number +} + +function localHeader({ name, crc, size, date }: Header): Uint8Array { + const zip64 = size >= MAX32 + const out = new Uint8Array(30 + name.length + (zip64 ? 20 : 0)) + const v = viewOf(out) + v.setUint32(0, LOCAL_SIG, true) + v.setUint16(4, zip64 ? 45 : 20, true) + v.setUint16(6, UTF8, true) + v.setUint16(8, 0, true) // stored + v.setUint16(10, dosTime(zipDate(date)), true) + v.setUint16(12, dosDate(zipDate(date)), true) + v.setUint32(14, crc, true) + v.setUint32(18, zip64 ? MAX32 : size, true) + v.setUint32(22, zip64 ? MAX32 : size, true) + v.setUint16(26, name.length, true) + v.setUint16(28, zip64 ? 20 : 0, true) + out.set(name, 30) + if (zip64) { + const at = 30 + name.length + v.setUint16(at, 1, true) + v.setUint16(at + 2, 16, true) + v.setBigUint64(at + 4, BigInt(size), true) + v.setBigUint64(at + 12, BigInt(size), true) + } + return out +} + +function centralHeader({ name, crc, size, date, offset }: Header): Uint8Array { + // ZIP64 extra: only the fields too big for their own place, in this order. + const big = [size >= MAX32 ? size : null, size >= MAX32 ? size : null, offset >= MAX32 ? offset : null] + .filter((n): n is number => n !== null) + const extra = big.length ? 4 + 8 * big.length : 0 + const out = new Uint8Array(46 + name.length + extra) + const v = viewOf(out) + v.setUint32(0, CENTRAL_SIG, true) + v.setUint16(4, 45, true) // made by: spec version 4.5 + v.setUint16(6, big.length ? 45 : 20, true) + v.setUint16(8, UTF8, true) + v.setUint16(10, 0, true) // stored + v.setUint16(12, dosTime(zipDate(date)), true) + v.setUint16(14, dosDate(zipDate(date)), true) + v.setUint32(16, crc, true) + v.setUint32(20, Math.min(size, MAX32), true) + v.setUint32(24, Math.min(size, MAX32), true) + v.setUint16(28, name.length, true) + v.setUint16(30, extra, true) + v.setUint32(42, Math.min(offset, MAX32), true) + out.set(name, 46) + if (big.length) { + const at = 46 + name.length + v.setUint16(at, 1, true) + v.setUint16(at + 2, 8 * big.length, true) + big.forEach((n, i) => v.setBigUint64(at + 4 + 8 * i, BigInt(n), true)) + } + return out +} + +/** The end-of-zip records; the ZIP64 ones too when a count, size or offset needs them. */ +function endRecords(count: number, cdSize: number, cdOffset: number, comment: Uint8Array): Uint8Array { + const zip64 = count >= MAX16 || cdSize >= MAX32 || cdOffset >= MAX32 + const out = new Uint8Array((zip64 ? ZIP64_EOCD_SIZE + LOCATOR_SIZE : 0) + EOCD_SIZE + comment.length) + const v = viewOf(out) + let at = 0 + if (zip64) { + v.setUint32(0, ZIP64_EOCD_SIG, true) + v.setBigUint64(4, BigInt(ZIP64_EOCD_SIZE - 12), true) + v.setUint16(12, 45, true) + v.setUint16(14, 45, true) + v.setBigUint64(24, BigInt(count), true) + v.setBigUint64(32, BigInt(count), true) + v.setBigUint64(40, BigInt(cdSize), true) + v.setBigUint64(48, BigInt(cdOffset), true) + v.setUint32(56, LOCATOR_SIG, true) + v.setBigUint64(64, BigInt(cdOffset + cdSize), true) + v.setUint32(72, 1, true) + at = ZIP64_EOCD_SIZE + LOCATOR_SIZE + } + v.setUint32(at, EOCD_SIG, true) + v.setUint16(at + 8, Math.min(count, MAX16), true) + v.setUint16(at + 10, Math.min(count, MAX16), true) + v.setUint32(at + 12, Math.min(cdSize, MAX32), true) + v.setUint32(at + 16, Math.min(cdOffset, MAX32), true) + v.setUint16(at + 20, comment.length, true) + out.set(comment, at + EOCD_SIZE) + return out +} + +/** The entries in a table of contents, or null when it isn't `count` well-formed records. */ +function centralEntries(cd: Uint8Array, count: number): IndexEntry[] | null { + const v = viewOf(cd) + const entries: IndexEntry[] = [] + let at = 0 + for (let i = 0; i < count; i++) { + if (at + 46 > cd.length || v.getUint32(at, true) !== CENTRAL_SIG) return null + const nameLength = v.getUint16(at + 28, true) + const extraStart = at + 46 + nameLength + const extraEnd = extraStart + v.getUint16(at + 30, true) + const next = extraEnd + v.getUint16(at + 32, true) + if (next > cd.length) return null + // Names are UTF-8 when flagged, else the old DOS code page (read as Latin-1, as fflate does). + const decoder = new TextDecoder(v.getUint16(at + 8, true) & UTF8 ? 'utf-8' : 'latin1') + let size = v.getUint32(at + 24, true) + let compressedSize = v.getUint32(at + 20, true) + let localOffset = v.getUint32(at + 42, true) + // ZIP64 extra: the fields too big for their own place, in this order. + for (let e = extraStart; e + 4 <= extraEnd; e += 4 + v.getUint16(e + 2, true)) { + if (v.getUint16(e, true) !== 1) continue + let f = e + 4 + const next64 = () => { const n = f + 8 <= extraEnd ? Number(v.getBigUint64(f, true)) : NaN; f += 8; return n } + if (size === MAX32) size = next64() + if (compressedSize === MAX32) compressedSize = next64() + if (localOffset === MAX32) localOffset = next64() + } + if ([size, compressedSize, localOffset].some(Number.isNaN)) return null + entries.push({ name: decoder.decode(cd.subarray(at + 46, extraStart)), method: v.getUint16(at + 10, true), compressedSize, size, localOffset, record: [at, next] }) + at = next + } + return at === cd.length ? entries : null +} + +const CRC_TABLE = (() => { + const table = new Uint32Array(256) + for (let n = 0; n < 256; n++) { + let c = n + for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1 + table[n] = c + } + return table +})() + +/** CRC-32 of `data`, continuing from `crc` (0 to start). */ +function crc32(crc: number, data: Uint8Array): number { + let c = ~crc + for (let i = 0; i < data.length; i++) c = CRC_TABLE[(c ^ data[i]) & 0xff] ^ (c >>> 8) + return ~c >>> 0 +} + +async function crcOf(blob: Blob): Promise { + let crc = 0 + const reader = blob.stream().getReader() + for (;;) { + const { done, value } = await reader.read() + if (done) return crc + crc = crc32(crc, value) + } +} + +function dosTime(d: Date): number { + return (d.getHours() << 11) | (d.getMinutes() << 5) | (d.getSeconds() >> 1) +} + +function dosDate(d: Date): number { + return ((d.getFullYear() - 1980) << 9) | ((d.getMonth() + 1) << 5) | d.getDate() +} + +/** `date` within what a zip entry can hold: 1980 to 2107, clamped to the nearest end. */ +export function zipDate(date: Date): Date { + const first = new Date(1980, 0, 1), last = new Date(2107, 11, 31, 23, 59, 58) + return Number.isNaN(date.getTime()) || date < first ? first : date > last ? last : date +} + +function encode(text: string): Uint8Array { + return new TextEncoder().encode(text) +} + +async function bytesOf(blob: Blob): Promise { + return new Uint8Array(await blob.arrayBuffer()) +} + +function viewOf(bytes: Uint8Array): DataView { + return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength) +} diff --git a/applications/idp-arc/frontend/src/data/README.md b/applications/idp-arc/frontend/src/data/README.md index d62a129..9edff7a 100644 --- a/applications/idp-arc/frontend/src/data/README.md +++ b/applications/idp-arc/frontend/src/data/README.md @@ -1,7 +1,7 @@ # Protocols (`protocols.json`) One entry per behavioral task / protocol. It drives the Protocols page and the upload dialog, and -it tells IDP which analysis to run on a researcher's data and what input that analysis can read. +it tells IDP/MAABCD which analysis to run on a researcher's data and what input that analysis can read. Field names follow the MAABCD–OSB Integration design (`id`, `repoZipUrl`, `notebooksDir`). ## Fields @@ -13,10 +13,11 @@ Field names follow the MAABCD–OSB Integration design (`id`, `repoZipUrl`, `not | `description`, `imageUrl`, `videoUrl` | Protocols page | Text and media shown for the protocol. | | `repoZipUrl` | run | GitHub archive of the analysis repository, `https://codeload.github.com///zip/refs/heads/` (or `refs/tags/`, or `/zip/`). A **branch** follows the latest fixes; a **commit** freezes the code. An empty `repoZipUrl` = no analysis yet: the upload dialog doesn't offer the protocol. | | `notebooksDir` | run | Repository-relative folder of the notebooks (`notebooks`). | -| `maabcdAggregateDandisetId` | upload | The protocol's MAABCD consortium dandiset on EMBER-DANDI (`000607`): six digits, owned by the consortium account. When the researcher shares their upload, a copy goes there through OSB's `/dandi` endpoints, signed with that account's key. Leave it out and uploads for the protocol aren't shared. | +| `maabcdAggregateDandisets` | upload | The protocol's MAABCD consortium dandiset on each DANDI instance, by instance name (`{ "ember-dandi": "000607", "dandi-sandbox": "219158" }`; names in `src/core/dandiInstances.ts`, six digits each, owned by the consortium account there). The one for the instance in use (`VITE_DANDI_INSTANCE`) is where a shared copy goes, through OSB's `/dandi` endpoints, signed with that account's key. No entry for the instance, or no field: uploads for the protocol aren't shared there. | | `requirements`, `pythonPath`, `install` | run | Override the repository setup below (defaults in `REPOSITORY_SETUP`, runProtocol.ts: `requirements.txt`; `["scripts"]`; `["scripts/install.py", "scripts/setup.py", "scripts/pyproject.toml"]`). OSB applies only the ones the repository has. Leave them out for a repository that follows the contract. | | `templatesZipUrl` | Protocols page, dialog | Archive of the protocol's templates (data sheets, instructions), downloaded by the **Download** buttons on the Protocols page and in the dialog's upload step. A path relative to `public/` (`protocols_archives/4c.zip`) or an absolute URL. Missing or empty = both buttons disabled. | | `inputFormats` | dialog, run | Extensions the analysis code can actually read. The dialog refuses other files before anything starts. **Without it, any file is accepted** (except an empty one, always refused). | +| `bids` | dialog, upload | How the researcher's spreadsheets become a BIDS dataset in their dandiset (`core/bids/convert.ts`). **Required**: every upload goes up as BIDS. `task` is the BIDS task label (letters and digits). `subjectId`, `sex` and `sessionDate` say where a workbook holds them: the cell right of the one reading `label`, on `sheet` (the date on each table's own sheet). `tables` lists the sheets that become tables: `sheet`, `acq` (the stage's label) and `header` (the first cell of the header row). `columns` describes each column by the name it gets (`latency_s`): `Description`, and `Units` or `Levels` when there are any; it is the same in every stage. `filledBy` (per table) names the columns that mark a row as a trial, `skipColumns` the columns left out, and `tableInfo` the cells above each table written to a JSON beside it. The dialog converts the file when it is picked and stops only on what BIDS can't do without: no Animal ID, no testing date, or no trial filled in anywhere; a missing sheet or header just leaves that stage out. PDFs in an uploaded zip go to `logs/`. | ## Where uploads go @@ -24,12 +25,13 @@ Each upload goes to EMBER-DANDI, in up to two copies: | | Researcher's dandiset | MAABCD aggregate dandiset | |---|---|---| -| Dandiset | picked in the dialog, or a new one | `maabcdAggregateDandisetId`, if the researcher shares | -| Path | `//` | `//` | -| Built and signed by | IDP, with the researcher's EMBER login | OSB, with the consortium's `DANDI_API_KEY` | +| Dandiset | picked in the dialog, or a new one | `maabcdAggregateDandisets` (the instance's), if the researcher shares | +| Path | `sourcedata/upload-/.zip`, plus the BIDS files made from it | `//.zip` | +| Built and signed by | IDP/MAABCD, with the researcher's EMBER login | OSB, with the consortium's `DANDI_API_KEY` | -`` is a random UUID, so uploads never overwrite each other. OSB builds the MAABCD path -from the caller's login, so no one can write into another's folder. +Both copies are the same zip: the upload with a `README.md` added (`core/dandisetReadme.ts`) that +links the researcher's dandiset. Each upload gets its own folder, so uploads never overwrite each +other. OSB builds the MAABCD path from the caller's login, so no one can write into another's folder. ## What happens on "Upload and run" (core/use-cases/runProtocol.ts) @@ -43,11 +45,11 @@ protocol doesn't read. 2. OSB imports both into this run's folder (`POST /workspaceresource`; names in core/workspaceLayout.ts): `/run--/-/` for the code, fresh for every run, and `…/inputs/` for the upload (a `.zip` is unpacked there). -3. When the imports are done, IDP lists the notebooks OSB found in `notebooksDir` and sorts them. +3. When the imports are done, IDP/MAABCD lists the notebooks OSB found in `notebooksDir` and sorts them. It then asks OSB to run exactly those, in that order (`POST /workspace/{id}/run`, papermill in an Argo task), with the run's `inputs/` and `outputs/` as the notebooks' `INPUT_DIR` and `OUTPUT_DIR` parameters. OSB sets up `requirements.txt` and `scripts/` first; which notebooks run - and where they read and write is IDP's decision. + and where they read and write is IDP/MAABCD's decision. 4. Results, in the same run folder (e.g. `four-choice-reversal/run-four-choice-reversal-2026-10-05T10-54-43Z/`): `inputs/` (the upload), `outputs/` (what the notebooks wrote), the executed notebooks and `run.log`. The run task removes the code once it has copied it, so the next run gets the current code. @@ -64,8 +66,8 @@ protocol doesn't read. ## What a protocol repository must look like -Agreed with the protocol authors on 30 Sep 2026. These conventions live in IDP (`REPOSITORY_SETUP` -and `notebooksDir`): IDP tells OSB which notebooks to run, in what order, and which setup files to +Agreed with the protocol authors on 30 Sep 2026. These conventions live in IDP/MAABCD (`REPOSITORY_SETUP` +and `notebooksDir`): IDP/MAABCD tells OSB which notebooks to run, in what order, and which setup files to use; OSB applies the ones the repository has. 1. `requirements.txt` at the root — **optional**, installed first. Pin versions: the task image @@ -79,7 +81,7 @@ use; OSB applies the ones the repository has. `2_x`), each with its own folder as working directory. The first failing notebook stops the run. 4. **Input and output: a cell tagged `parameters`** (papermill's convention) in every notebook, setting `INPUT_DIR` and `OUTPUT_DIR` to its own defaults (e.g. its example data). The notebooks read from - `INPUT_DIR` and write everything they produce to `OUTPUT_DIR`; for a run, IDP passes the run's + `INPUT_DIR` and write everything they produce to `OUTPUT_DIR`; for a run, IDP/MAABCD passes the run's `inputs/` and `outputs/`. A run stops at the first notebook without that cell. ## Per protocol diff --git a/applications/idp-arc/frontend/src/data/protocols.json b/applications/idp-arc/frontend/src/data/protocols.json index 5f3d3f3..0dbc05b 100644 --- a/applications/idp-arc/frontend/src/data/protocols.json +++ b/applications/idp-arc/frontend/src/data/protocols.json @@ -4,9 +4,246 @@ "name": "Four-choice reversal digging task", "repoZipUrl": "https://codeload.github.com/maracbaylis/four-choice-example/zip/refs/heads/main", "notebooksDir": "notebooks", - "maabcdAggregateDandisetId": "000607", + "maabcdAggregateDandisets": { + "ember-dandi": "000607", + "dandi-sandbox": "219158" + }, "inputFormats": [".xlsx", ".zip"], "templatesZipUrl": "protocols_archives/4c.zip", + "bids": { + "task": "fourchoice", + "subjectId": { + "sheet": "METADATA", + "label": "Animal ID: (XXX001)" + }, + "sex": { + "sheet": "METADATA", + "label": "Sex (M/F)" + }, + "sessionDate": { + "label": "Date:" + }, + "tables": [ + { + "sheet": "ACCLIM", + "acq": "acclimation", + "header": "Round" + }, + { + "sheet": "SHAPE", + "acq": "shaping", + "header": "Trial", + "filledBy": [ + "time_to_dig_s", + "time_to_eat_s", + "notes" + ] + }, + { + "sheet": "DISC", + "acq": "discrimination", + "header": "Trial", + "filledBy": [ + "odor_chosen", + "latency_s", + "entry_sequence", + "notes" + ] + }, + { + "sheet": "RECALL", + "acq": "recall", + "header": "Trial", + "filledBy": [ + "odor_chosen", + "latency_s", + "entry_sequence", + "notes" + ] + }, + { + "sheet": "REV", + "acq": "reversal", + "header": "Trial", + "filledBy": [ + "odor_chosen", + "latency_s", + "entry_sequence", + "error_type", + "notes" + ] + } + ], + "participants": { + "species": "mus musculus", + "fields": [ + { + "column": "strain", + "sheet": "METADATA", + "label": "Strain", + "Description": "Strain of the mouse, e.g. C57BL/6." + }, + { + "column": "genotype", + "sheet": "METADATA", + "label": "Genotype", + "Description": "Genotype: WT, HET or KO, for example." + }, + { + "column": "dob", + "sheet": "METADATA", + "label": "DOB (mm/dd/yyyy)", + "LongName": "Date of birth", + "Description": "Date of birth.", + "type": "date" + }, + { + "column": "experiment_cohort", + "sheet": "METADATA", + "label": "Experiment Cohort", + "Description": "Cohort the mouse was run in, e.g. MAABCD_2026." + }, + { + "column": "experimental_group", + "sheet": "METADATA", + "label": "Experimental Group", + "Description": "Control, or the experimental group." + }, + { + "column": "adversity_condition", + "sheet": "METADATA", + "label": "Adversity Condition", + "Description": "Model of adversity or stress tested, e.g. Food Insecurity." + }, + { + "column": "adversity_age_range", + "sheet": "METADATA", + "label": "Adversity Age Range (PXX-XX)", + "Description": "Postnatal age range of the adversity, e.g. P21-40." + }, + { + "column": "source", + "sheet": "METADATA", + "label": "Bred On Site or Shipped", + "Description": "Whether the mouse was bred on site or shipped." + }, + { + "column": "vendor", + "sheet": "METADATA", + "label": "Vendor", + "Description": "Vendor, when shipped, e.g. Jackson." + }, + { + "column": "mice_in_homecage", + "sheet": "METADATA", + "label": "# Of Mice In Homecage At Testing", + "Description": "Number of mice in the homecage at testing." + }, + { + "column": "lab", + "sheet": "METADATA", + "label": "Lab and Institution", + "Description": "Lab and institution." + } + ] + }, + "phenotype": [ + { + "name": "weight", + "sheet": "WEIGHT", + "header": "Experimental Day", + "description": "Weight tracking from the WEIGHT tab of the 4C Digging Reversal Reporting Sheet, one group of columns per experimental day.", + "fields": [ + { + "column": "stage", + "label": "Stage", + "Description": "Stage of the protocol that day." + }, + { + "column": "date", + "label": "Date", + "Description": "Date of the weighing.", + "type": "date" + }, + { + "column": "time", + "label": "Time", + "Description": "Time the mouse was weighed.", + "type": "time" + }, + { + "column": "age", + "label": "Age (P)", + "Description": "Postnatal age.", + "Units": "day" + }, + { + "column": "weight", + "label": "Weight (g)", + "Description": "Body weight.", + "Units": "g" + }, + { + "column": "fraction_of_baseline", + "label": "% from baseline", + "Description": "That day's weight divided by the Day 1 reference ad libitum weight." + } + ] + } + ], + "skipColumns": ["quadrant_chosen"], + "tableInfo": [ + { "key": "Experimenter", "label": "Experimenter:" }, + { "key": "StartTime", "label": "Start time:", "type": "time" }, + { "key": "EndTime", "label": "End time:", "type": "time" }, + { "key": "Rewarded", "label": "Rewarded:" }, + { "key": "Odors", "label": "Odors:", "type": "list" } + ], + "columns": { + "round": { "Description": "Acclimation round (Round 1 to 3)." }, + "time_to_eat_nw_1": { + "Description": "Time the mouse took to start eating the plain pellet in the northwest quadrant (1).", + "Units": "s" + }, + "time_to_eat_ne_2": { + "Description": "Time the mouse took to start eating the plain pellet in the northeast quadrant (2).", + "Units": "s" + }, + "time_to_eat_sw_3": { + "Description": "Time the mouse took to start eating the plain pellet in the southwest quadrant (3).", + "Units": "s" + }, + "time_to_eat_se_4": { + "Description": "Time the mouse took to start eating the plain pellet in the southeast quadrant (4).", + "Units": "s" + }, + "number_of_pellets_eaten": { "Description": "Pellets eaten in the round." }, + "bedding_level": { "Description": "Amount of shavings in the ramekin; it increases with each shaping trial." }, + "ramekin_position": { "Description": "Quadrant the ramekin was placed in: NW, NE, SW or SE." }, + "time_to_dig_s": { + "Description": "Time until the mouse purposefully touched the pellet or the shavings.", + "Units": "s" + }, + "time_to_eat_s": { + "Description": "Time until the mouse started eating the pellet.", + "Units": "s" + }, + "trial": { "Description": "Trial number within the session." }, + "ramekin_order": { + "Description": "Order of the four odor ramekins by position (northwest, northeast, southwest, southeast), written as the odor letters A to D listed at the top of the sheet." + }, + "odor_chosen": { "Description": "Odor the mouse chose." }, + "correct": { "Description": "Whether the choice was the rewarded odor." }, + "latency_s": { + "Description": "Time the mouse took to dig, in seconds (written as mm:ss on the testing sheet and converted for the reporting sheet).", + "Units": "s" + }, + "entry_sequence": { "Description": "Order in which the quadrants were entered: 1 = northwest, 2 = northeast, 3 = southwest, 4 = southeast." }, + "odor_sequences": { "Description": "The odor of each quadrant entered, in order: the entry sequence read through the ramekin order." }, + "error_type": { "Description": "Kind of error made in the reversal stage; the protocol's types are Reversal, Perseverative, Regressive, Novel and Irrelevant." }, + "notes": { "Description": "Free-text notes from the experimenter: grooming, jumping, climbing, sleeping or chewing for 5 seconds (tick marks count repeats), the time to dig and time to eat of a reminder trial after two omissions, and a 15-minute break." } + } + }, "description": "In the four choice reversal digging task mice must identify the single rewarded option and update their choice when a previously unrewarded option becomes rewarded. The reversal phase in this task is sensitive to orbitofrontal and dorsomedial prefrontal cortex function and the 2-day version used here provides a metric of recall on the 2nd day of testing before reversal.", "imageUrls": ["assets/four_choice_graphic.jpeg"], "videoUrl": "https://storage.googleapis.com/maabcd/tutorial.mp4", diff --git a/applications/idp-arc/frontend/src/globals.d.ts b/applications/idp-arc/frontend/src/globals.d.ts new file mode 100644 index 0000000..421d75b --- /dev/null +++ b/applications/idp-arc/frontend/src/globals.d.ts @@ -0,0 +1,2 @@ +/** True only in the Vite dev server on a sandbox with DANDI_SANDBOX_API_KEY set (vite.config.ts `define`). */ +declare const __DANDI_SANDBOX_API_KEY__: boolean diff --git a/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts b/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts index d2dc359..70f0937 100644 --- a/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts +++ b/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts @@ -79,7 +79,7 @@ export class EmberDandiDirectClient implements IDandiDirectApi { body: JSON.stringify({ name, metadata: { - description: 'Created by IDP to hold this researcher’s uploaded data.', + description: 'Created by MAABCD to hold this researcher’s uploaded data.', ...metadata, }, }), @@ -172,6 +172,7 @@ export class EmberDandiDirectClient implements IDandiDirectApi { dandisetId: string, path: string, blobId: string, + replace = false, ): Promise { const res = await fetch( `${this.baseUrl}/api/dandisets/${dandisetId}/versions/draft/assets/`, @@ -186,27 +187,55 @@ export class EmberDandiDirectClient implements IDandiDirectApi { }), }, ) - // Already registered at this path: a re-upload of the same file. Reuse it. + // Already registered at this path: a re-upload of the same file reuses it; with `replace`, + // different content takes its place. if (res.status === 409) { - return { assetPath: path, assetId: await this.findDraftAssetId(token, dandisetId, path) } + const existing = await this.findDraftAsset(token, dandisetId, path) + if (!replace || existing.blob === blobId) return { assetPath: path, assetId: existing.asset_id } + return this.replaceAsset(token, dandisetId, existing.asset_id, path, blobId) } if (!res.ok) await this.fail(res, 'register_asset') const body = await res.json() return { assetPath: body.path ?? path, assetId: body.asset_id } } - /** The 409 above carries no asset id, so look the existing asset up by path. EMBER's `path` - * filter matches by prefix, hence the exact comparison. */ - private async findDraftAssetId(token: string, dandisetId: string, path: string): Promise { + /** `PUT …/assets/{id}/`: the asset at `path` gets the new content (DANDI makes it a new asset). */ + private async replaceAsset(token: string, dandisetId: string, assetId: string, path: string, blobId: string): Promise { + const res = await fetch(`${this.baseUrl}/api/dandisets/${dandisetId}/versions/draft/assets/${assetId}/`, { + method: 'PUT', + headers: this.headers(token, true), + body: JSON.stringify({ metadata: { path, schemaKey: 'Asset', encodingFormat: guessContentType(path) }, blob_id: blobId }), + }) + if (!res.ok) await this.fail(res, 'replace_asset') + const body = await res.json() + return { assetPath: body.path ?? path, assetId: body.asset_id } + } + + /** The 409 above carries no asset id, so look the existing asset up by path. */ + private async findDraftAsset(token: string, dandisetId: string, path: string): Promise<{ asset_id: string; blob?: string }> { + const asset = await this.draftAssetAt(token, dandisetId, path) + if (!asset) throw new Error(`EMBER reported ${path} as already registered but has no such asset`) + return asset + } + + /** EMBER's `path` filter matches by prefix, hence the exact comparison. */ + private async draftAssetAt(token: string, dandisetId: string, path: string): Promise<{ asset_id: string; blob?: string } | undefined> { const res = await fetch( `${this.baseUrl}/api/dandisets/${dandisetId}/versions/draft/assets/?path=${encodeURIComponent(path)}`, { headers: this.headers(token) }, ) if (!res.ok) await this.fail(res, 'asset lookup') const body = await res.json() - const asset = (body.results ?? []).find((a: { path: string }) => a.path === path) - if (!asset) throw new Error(`EMBER reported ${path} as already registered but has no such asset`) - return asset.asset_id + return (body.results ?? []).find((a: { path: string }) => a.path === path) + } + + async readDraftFile(token: string, dandisetId: string, path: string): Promise { + const asset = await this.draftAssetAt(token, dandisetId, path) + if (!asset) return null + // Redirects to the file's S3 URL; the browser drops the Authorization header on the way. + const res = await fetch(`${this.baseUrl}/api/assets/${asset.asset_id}/download/`, { headers: this.headers(token) }) + if (!res.ok) await this.fail(res, `download of ${path}`) + return res.text() } async initUpload( @@ -301,7 +330,7 @@ export class EmberDandiDirectClient implements IDandiDirectApi { } if (!blobId) throw new Error('No blob to register: neither an upload nor a dedup hit.') - return this.registerAsset(token, input.dandisetId, input.path, blobId) + return this.registerAsset(token, input.dandisetId, input.path, blobId, input.replace) } } @@ -312,6 +341,8 @@ function guessContentType(path: string): string { csv: 'text/csv', tsv: 'text/tab-separated-values', json: 'application/json', + md: 'text/markdown', + zip: 'application/zip', nwb: 'application/x-nwb', txt: 'text/plain', xls: 'application/vnd.ms-excel', diff --git a/applications/idp-arc/frontend/src/infra/emberUrls.ts b/applications/idp-arc/frontend/src/infra/emberUrls.ts deleted file mode 100644 index a5ce025..0000000 --- a/applications/idp-arc/frontend/src/infra/emberUrls.ts +++ /dev/null @@ -1,3 +0,0 @@ -/** EMBER-DANDI's API and web UI. Production only: the proxies and OSB's MAABCD copy use it too. */ -export const EMBER_API_ORIGIN = 'https://api-dandi.emberarchive.org' -export const EMBER_WEB_ORIGIN = 'https://dandi.emberarchive.org' diff --git a/applications/idp-arc/frontend/src/infra/sandboxApiKeyEmberAuth.ts b/applications/idp-arc/frontend/src/infra/sandboxApiKeyEmberAuth.ts new file mode 100644 index 0000000..732fe93 --- /dev/null +++ b/applications/idp-arc/frontend/src/infra/sandboxApiKeyEmberAuth.ts @@ -0,0 +1,55 @@ +import type { IEmberAuth } from '../core/ports/IEmberAuth' + +/** Sent instead of a token; the dev proxy replaces it with the DANDI_SANDBOX_API_KEY it holds. */ +const PLACEHOLDER_TOKEN = 'sandbox-proxy-api-key' + +/** + * Local development only: always "signed in", as the owner of DANDI_SANDBOX_API_KEY. The key stays in + * the Vite dev server, which sets `Authorization: token ` on every proxied DANDI call + * (vite.config.ts); the browser never sees it. For the sandboxes, which have no OAuth app for us. + */ +export class SandboxApiKeyEmberAuth implements IEmberAuth { + readonly expiresAt = Number.MAX_SAFE_INTEGER + private readonly apiBase: string + + constructor(apiBase: string) { + this.apiBase = apiBase + } + + isConnected(): boolean { + return true + } + + getToken(): string { + return PLACEHOLDER_TOKEN + } + + async getAccount(): Promise<{ username: string; name: string | null }> { + const res = await fetch(`${this.apiBase}/api/users/me/`, { headers: { Authorization: `Bearer ${PLACEHOLDER_TOKEN}` } }) + if (!res.ok) throw new Error(`Could not read the DANDI account of DANDI_SANDBOX_API_KEY (HTTP ${res.status}).`) + const body = await res.json() + return { username: body.username, name: body.name ?? null } + } + + connect(): Promise { + return Promise.reject(new Error('Signed in through DANDI_SANDBOX_API_KEY; there is no sign-in flow.')) + } + + connectInPopup(): { done: Promise; cancel: () => void } { + return { done: Promise.resolve(), cancel: () => {} } + } + + relayPopupCallback(): boolean { + return false + } + + takeReturnTo(): string | null { + return null + } + + async handleCallback(): Promise { + return null + } + + disconnect(): void {} +} diff --git a/applications/idp-arc/frontend/src/locales/en/landingPage.json b/applications/idp-arc/frontend/src/locales/en/landingPage.json index e1fc2ec..e9a2a90 100644 --- a/applications/idp-arc/frontend/src/locales/en/landingPage.json +++ b/applications/idp-arc/frontend/src/locales/en/landingPage.json @@ -86,7 +86,7 @@ "osbWaiting": "Sign in in the Open Source Brain window…", "osbUnreachable": "Can't reach Open Source Brain's sign-in. Check your connection and try again.", "finishingSignIn": "Finishing sign in…", - "closeWindow": "You can close this window and go back to IDP.", + "closeWindow": "You can close this window and go back to MAABCD.", "cancel": "Cancel", "close": "Close" } diff --git a/applications/idp-arc/frontend/src/pages/EmberCallback.tsx b/applications/idp-arc/frontend/src/pages/EmberCallback.tsx index baeb535..ccb6d18 100644 --- a/applications/idp-arc/frontend/src/pages/EmberCallback.tsx +++ b/applications/idp-arc/frontend/src/pages/EmberCallback.tsx @@ -38,7 +38,7 @@ export default function EmberCallback() { return ( {inPopup ? ( - You can close this window and go back to IDP. + You can close this window and go back to MAABCD. ) : error ? ( <> diff --git a/applications/idp-arc/frontend/tests/unit/bidsConvert.test.ts b/applications/idp-arc/frontend/tests/unit/bidsConvert.test.ts new file mode 100644 index 0000000..57a1e07 --- /dev/null +++ b/applications/idp-arc/frontend/tests/unit/bidsConvert.test.ts @@ -0,0 +1,442 @@ +// Spreadsheets → minimal BIDS (core/bids). Run: yarn test:unit +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import { strFromU8, strToU8, unzipSync, zipSync } from 'fflate' +import { readWorkbook } from '../../src/core/bids/xlsxReader' +import { reporting, undecodable, xlsx, type Row } from './xlsxFixture' +import { convertToBids, type BidsConfig, type DatasetInfo } from '../../src/core/bids/convert' + +const CONFIG: BidsConfig = { + task: 'fourchoice', + subjectId: { sheet: 'METADATA', label: 'Animal ID: (XXX001)' }, + sex: { sheet: 'METADATA', label: 'Sex (M/F)' }, + sessionDate: { label: 'Date:' }, + tables: [ + { sheet: 'DISC', acq: 'discrimination', header: 'Trial' }, + { sheet: 'REV', acq: 'reversal', header: 'Trial' }, + ], +} + +const upload = (name: string, bytes: Uint8Array) => new File([bytes as BlobPart], name) + +const tsvOf = (result: Awaited>, path: string) => { + const f = result.files.find((x) => x.path === path) + return typeof f?.content === 'string' ? f.content : undefined +} + +test('reads shared, rich-text and inline strings, numbers, entities; unsaved formulas are empty', async () => { + const wb = readWorkbook(reporting('ABC001')) + assert.deepEqual([...wb.keys()], ['METADATA', 'DISC', 'REV']) + assert.equal(wb.get('METADATA')![0][0], 'SECTION 1 — Animal Info') // rich text, joined + const disc = wb.get('DISC')! + assert.deepEqual(disc[4], [1, 'ABCD', null, 29]) + assert.deepEqual(disc[5], [2, 'BCDA', null, 3.5, 'tab\there\r\nnext & ']) +}) + +test('reads a workbook whose elements carry a namespace prefix, with absolute relationship targets', async () => { + const prefixed = (xml: Uint8Array) => { + const files = unzipSync(xml) + const add = (s: string) => s.replace(/<(\/?)(sst|si|t|worksheet|sheetData|row|c|v|is|workbook|sheets|sheet)\b/g, '<$1x:$2') + for (const f of ['xl/workbook.xml', 'xl/sharedStrings.xml', 'xl/worksheets/sheet1.xml', 'xl/worksheets/sheet2.xml', 'xl/worksheets/sheet3.xml']) { + if (files[f]) files[f] = strToU8(add(strFromU8(files[f]))) + } + files['xl/_rels/workbook.xml.rels'] = strToU8(strFromU8(files['xl/_rels/workbook.xml.rels']).replace(/Target="worksheets/g, 'Target="/xl/worksheets')) + return zipSync(files) + } + const wb = readWorkbook(prefixed(reporting('ABC001'))) + assert.deepEqual([...wb.keys()], ['METADATA', 'DISC', 'REV']) + assert.deepEqual(wb.get('DISC')![4], [1, 'ABCD', null, 29]) +}) + +const DATASET: DatasetInfo = { + name: 'Four-choice test', + protocol: { name: 'Four-choice reversal digging task', description: 'Mice dig for a reward.', url: 'https://github.com/x/y' }, + license: 'CC-BY-4.0', +} + +test('a workbook: a table per configured sheet in the session of its date, described once at the top', async () => { + const result = await convertToBids(upload('Lab_ABC001.xlsx', reporting('ABC-001')), CONFIG, DATASET) + assert.deepEqual(result.problems, []) + assert.deepEqual(result.subjects, [{ id: 'ABC001', sex: 'M', source: 'Lab_ABC001.xlsx' }]) + assert.deepEqual(result.files.map((f) => f.path), [ + 'sourcedata/Lab_ABC001.xlsx', + 'sub-ABC001/ses-20260902/beh/sub-ABC001_ses-20260902_task-fourchoice_acq-discrimination_beh.tsv', + 'sub-ABC001/ses-20260903/beh/sub-ABC001_ses-20260903_task-fourchoice_acq-reversal_beh.tsv', + 'task-fourchoice_acq-discrimination_beh.json', + 'task-fourchoice_acq-reversal_beh.json', + 'dataset_description.json', + 'README.md', + ]) + assert.equal(tsvOf(result, 'sub-ABC001/ses-20260902/beh/sub-ABC001_ses-20260902_task-fourchoice_acq-discrimination_beh.tsv'), + 'trial\tramekin_order\tcorrect\tlatency_s\tnotes\n' + + '1\tABCD\tn/a\t29\tn/a\n' + + '2\tBCDA\tn/a\t3.5\ttab here next & \n') + assert.deepEqual(JSON.parse(tsvOf(result, 'task-fourchoice_acq-discrimination_beh.json')!), { + TaskName: 'fourchoice', + TaskDescription: 'Mice dig for a reward.', + trial: { LongName: 'Trial' }, + ramekin_order: { LongName: 'Ramekin Order (NW, NE, SW, SE)' }, + correct: { LongName: 'Correct?' }, + latency_s: { LongName: 'Latency (s)', Units: 's' }, + notes: { LongName: 'Notes' }, + }) + assert.deepEqual(JSON.parse(tsvOf(result, 'dataset_description.json')!), { + Name: 'Four-choice test', BIDSVersion: '1.10.0', DatasetType: 'raw', License: 'CC-BY-4.0', + ReferencesAndLinks: ['https://github.com/x/y'], + GeneratedBy: [{ Name: 'MAABCD Four-choice reversal digging task upload', Description: 'Behavioral tables copied, unchanged, from the spreadsheets in sourcedata/, in the browser.' }], + }) + assert.match(tsvOf(result, 'README.md')!, /^# Four-choice test\n\nProtocol: Four-choice reversal digging task\n\nAnalysis code: https:\/\/github.com\/x\/y\n/) +}) + +test('authors, the upload\'s real path, and what the protocol says about each column', async () => { + const columns: BidsConfig['columns'] = { + latency_s: { Description: 'Time to choose.', Units: 's' }, + correct: { Description: 'Rewarded choice?', Levels: { Correct: 'the rewarded odor', Incorrect: 'any other' } }, + } + const result = await convertToBids(upload('Lab ABC001 -2-.xlsx', reporting('ABC001')), { ...CONFIG, columns }, + { ...DATASET, authors: ['Ada Lovelace'], source: 'sourcedata/0b1f/Lab-ABC001-2.xlsx' }) + assert.equal(result.files[0].path, 'sourcedata/0b1f/Lab-ABC001-2.xlsx') + const description = JSON.parse(tsvOf(result, 'dataset_description.json')!) + assert.deepEqual(description.Authors, ['Ada Lovelace']) + assert.equal(description.SourceDatasets, undefined) + const sidecar = JSON.parse(tsvOf(result, 'task-fourchoice_acq-discrimination_beh.json')!) + assert.deepEqual(sidecar.latency_s, { LongName: 'Latency (s)', Description: 'Time to choose.', Units: 's' }) + assert.deepEqual(sidecar.correct, { LongName: 'Correct?', Description: 'Rewarded choice?', Levels: { Correct: 'the rewarded odor', Incorrect: 'any other' } }) + assert.deepEqual(sidecar.trial, { LongName: 'Trial' }) +}) + +test('the upload\'s name in sourcedata/ is clean: no spaces, no dangling dash', async () => { + const result = await convertToBids(upload('four-choice-filled-3-animals-ABC001-003 -2-.zip', zipSync({ 'a.xlsx': reporting('ABC001') })), CONFIG, DATASET) + assert.equal(result.files[0].path, 'sourcedata/four-choice-filled-3-animals-ABC001-003-2.zip') +}) + +test('PDFs in a zip are the protocol documents: kept in logs/, and named in the README', async () => { + const zip = zipSync({ + 'cohort/Lab_ABC001.xlsx': reporting('ABC001'), + 'cohort/Task Protocol.pdf': strToU8('%PDF-1.4'), + 'other/Filling Instructions.pdf': strToU8('%PDF-1.4 second'), + }) + const result = await convertToBids(upload('cohort.zip', zip), CONFIG, DATASET) + assert.deepEqual(result.files.filter((f) => f.path.startsWith('logs/')).map((f) => f.path), ['logs/Task-Protocol.pdf', 'logs/Filling-Instructions.pdf']) + assert.match(tsvOf(result, 'README.md')!, /- `logs\/`: the protocol documents/) + assert.doesNotMatch(tsvOf(await convertToBids(upload('a.xlsx', reporting('A1')), CONFIG, DATASET), 'README.md')!, /logs\//) +}) + +test('only workbooks and PDFs are read from a zip: anything else (a video) passes through unread', async () => { + // No decoder reads this video's compression, so the conversion fails if it ever opens it. + const zip = undecodable(zipSync({ 'cohort/session.mp4': [new Uint8Array(100000), { level: 0 }], 'cohort/Lab_ABC001.xlsx': reporting('ABC001') }), 'cohort/session.mp4') + const result = await convertToBids(upload('cohort.zip', zip), CONFIG, DATASET) + assert.deepEqual(result.problems, []) + assert.deepEqual(result.subjects.map((s) => s.id), ['ABC001']) + // The upload itself goes to sourcedata/ as the File, never copied into memory. + const source = result.files.find((f) => f.path.startsWith('sourcedata/'))! + assert.ok(source.content instanceof Blob && source.content.size === zip.length) +}) + +test('a workbook with an animal and a date but no trial filled in is an error, not an empty dataset', async () => { + const blank = xlsx({ + METADATA: [['Animal ID: (XXX001)', 'X1'], ['Sex (M/F)', 'M']], + DISC: [['Date:', '9/2/2026'], ['Trial', 'Latency (s)'], [1, null]], + REV: [['Date:', '9/3/2026'], ['Trial', 'Latency (s)'], [1, null]], + }) + const result = await convertToBids(upload('blank.xlsx', blank), CONFIG, DATASET) + assert.deepEqual(result.problems.filter((p) => p.level === 'error').map((p) => p.message), + ['No trials are filled in: every DISC, REV sheet in blank.xlsx is empty or missing.']) +}) + +test('without sessionDate, tables go straight under beh/', async () => { + const { sessionDate: _, ...noSessions } = CONFIG + const result = await convertToBids(upload('a.xlsx', reporting('A1')), noSessions, DATASET) + assert.ok(result.files.some((f) => f.path === 'sub-A1/beh/sub-A1_task-fourchoice_acq-discrimination_beh.tsv')) +}) + +test('a zip: every reporting workbook is a subject; other files only go to sourcedata', async () => { + const zip = zipSync({ + 'cohort/Lab_ABC001.xlsx': reporting('ABC001'), + 'cohort/Lab_ABC002.xlsx': reporting('ABC002', 'f'), + 'cohort/Weight log.xlsx': xlsx({ WEIGHT: [['Day', 'Weight (g)'], [0, 30]] }), + 'cohort/Protocol.pdf': strToU8('%PDF-1.4'), + '__MACOSX/cohort/._Lab_ABC001.xlsx': strToU8('junk'), + 'cohort/.DS_Store': strToU8('junk'), + 'other/Protocol.pdf': strToU8('%PDF-1.4 second'), + }) + const result = await convertToBids(upload('cohort.zip', zip), CONFIG, DATASET) + assert.deepEqual(result.problems, []) + assert.deepEqual(result.subjects.map((s) => [s.id, s.sex]), [['ABC001', 'M'], ['ABC002', 'f']]) + const paths = result.files.map((f) => f.path) + // The upload goes to sourcedata/ whole: OSB imports it from there, unpacking it as before. + assert.deepEqual(paths.filter((p) => p.startsWith('sourcedata/')), ['sourcedata/cohort.zip']) + assert.equal(paths.filter((p) => p.startsWith('sub-')).length, 4) +}) + +test('problems: empty or duplicate Animal ID, nothing usable, unreadable file; a missing sheet or header is left out quietly', async () => { + const messages = async (bytes: Uint8Array, name = 'in.zip') => + (await convertToBids(upload(name, bytes), CONFIG, DATASET)).problems.map((p) => `${p.level}: ${p.message}`) + + assert.deepEqual(await messages(reporting(null), 'a.xlsx'), ['error: a.xlsx: "Animal ID: (XXX001)" on the METADATA sheet is empty.']) + assert.deepEqual(await messages(zipSync({ 'a.xlsx': reporting('X1'), 'b.xlsx': reporting('X-1') })), + ['error: b.xlsx and a.xlsx both have Animal ID X1.']) + const noRev = xlsx({ METADATA: [['Animal ID: (XXX001)', 'X1'], ['Sex (M/F)', 'M']], DISC: [['Notes only']] }) + assert.deepEqual(await messages(noRev, 'n.xlsx'), ['error: No trials are filled in: every DISC, REV sheet in n.xlsx is empty or missing.']) + const discOnly = xlsx({ METADATA: [['Animal ID: (XXX001)', 'X1']], DISC: [['Date:', '9/2/2026'], ['Trial', 'Latency (s)'], [1, 12]] }) + assert.deepEqual(await messages(discOnly, 'd.xlsx'), []) + assert.deepEqual(await messages(zipSync({ 'notes.pdf': strToU8('%PDF') })), + ['error: No workbook with "Animal ID: (XXX001)" on a METADATA sheet was found in in.zip.']) + assert.deepEqual(await messages(strToU8('not a zip')), ['error: in.zip could not be opened. Is it a valid zip file?']) + const undated = xlsx({ METADATA: [['Animal ID: (XXX001)', 'X1'], ['Sex (M/F)', 'M']], DISC: [['Date:', 'last week'], ['Trial', 'Latency (s)'], [1, 2]], REV: [['Trial', 'Latency (s)'], [1, 2]] }) + assert.deepEqual(await messages(undated, 'u.xlsx'), [ + 'error: u.xlsx, DISC sheet: "Date:" should be the testing date.', + 'error: u.xlsx, REV sheet: "Date:" should be the testing date.', + ]) +}) + +test('a stage with no rows is left out with a warning; sex is kept as written', async () => { + const empty = xlsx({ + METADATA: [['Animal ID: (XXX001)', 'X1'], ['Sex (M/F)', 'male']], + DISC: [['Date:', '9/2/2026'], ['Trial', 'Latency (s)'], [1, 12]], + REV: [['Date:', '9/3/2026'], ['Trial', 'Latency (s)'], [1, null], [2, null]], + }) + const result = await convertToBids(upload('x.xlsx', empty), CONFIG, DATASET) + assert.deepEqual(result.problems, [ + { level: 'warning', message: 'x.xlsx, REV sheet: no rows filled in; left out.' }, + ]) + assert.equal(result.subjects[0].sex, 'male') + assert.ok(result.files.some((f) => f.path === 'sub-X1/ses-20260902/beh/sub-X1_ses-20260902_task-fourchoice_acq-discrimination_beh.tsv')) + assert.ok(!result.files.some((f) => f.path.endsWith('acq-reversal_beh.tsv'))) +}) + +test('filledBy: a row counts only when one of those columns is filled, so a template\'s prefill is left out', async () => { + const sheet = xlsx({ + METADATA: [['Animal ID: (XXX001)', 'ABC001'], ['Sex (M/F)', 'M']], + DISC: [['Date:', '9/2/2026'], ['Trial', 'Ramekin Order', 'Latency (s)', 'Notes'], [1, 'ABCD', 7, null], [2, 'BCDA', null, 'SKIP'], [3, 'CDAB', null, null], [4, 'DABC', null, null]], + REV: [['Date:', '9/3/2026'], ['Trial', 'Latency (s)'], [1, 2]], + }) + const config = { ...CONFIG, tables: [{ ...CONFIG.tables[0], filledBy: ['latency_s', 'notes'] }, CONFIG.tables[1]] } + const result = await convertToBids(upload('f.xlsx', sheet), config, DATASET) + assert.equal(tsvOf(result, 'sub-ABC001/ses-20260902/beh/sub-ABC001_ses-20260902_task-fourchoice_acq-discrimination_beh.tsv'), + 'trial\tramekin_order\tlatency_s\tnotes\n1\tABCD\t7\tn/a\n2\tBCDA\tn/a\tSKIP\n') + // Without filledBy, the prefilled orders make every row count. + assert.equal(tsvOf(await convertToBids(upload('f.xlsx', sheet), CONFIG, DATASET), 'sub-ABC001/ses-20260902/beh/sub-ABC001_ses-20260902_task-fourchoice_acq-discrimination_beh.tsv')!.split('\n').length, 6) +}) + +test('participants.tsv: one row per animal, species and sex, and the configured METADATA cells', async () => { + const participants: BidsConfig['participants'] = { + species: 'mus musculus', + fields: [ + { column: 'strain', sheet: 'METADATA', label: 'Strain', Description: 'Strain.' }, + { column: 'dob', sheet: 'METADATA', label: 'DOB (mm/dd/yyyy)', LongName: 'Date of birth', Description: 'Date of birth.', type: 'date' }, + ], + } + const animal = (id: string, sex: string, strain: string | null) => xlsx({ + METADATA: [['Animal ID: (XXX001)', id], ['Sex (M/F)', sex], ['Strain', strain], ['DOB (mm/dd/yyyy)', 46199]], + DISC: [['Date:', '9/2/2026'], ['Trial', 'Latency (s)'], [1, 3]], + REV: [['Date:', '9/3/2026'], ['Trial', 'Latency (s)'], [1, 2]], + }) + const result = await convertToBids(upload('c.zip', zipSync({ 'a.xlsx': animal('ABC001', 'M', 'C57BL/6'), 'b.xlsx': animal('ABC002', 'Female', null) })), + { ...CONFIG, participants }, DATASET) + assert.equal(tsvOf(result, 'participants.tsv'), + 'participant_id\tspecies\tsex\tstrain\tdob\n' + + 'sub-ABC001\tmus musculus\tM\tC57BL/6\t2026-06-26\n' + + 'sub-ABC002\tmus musculus\tFemale\tn/a\t2026-06-26\n') + const sidecar = JSON.parse(tsvOf(result, 'participants.json')!) + assert.deepEqual(sidecar.dob, { LongName: 'Date of birth', Description: 'Date of birth.' }) + assert.deepEqual(sidecar.sex, { Description: 'Sex of the animal, as written on the sheet.' }) + assert.match(sidecar.participant_id.Description, /^Animal ID from the METADATA sheet \("Animal ID: \(XXX001\)"\)/) + assert.ok(!(await convertToBids(upload('a.xlsx', animal('ABC001', 'M', 'x')), CONFIG, DATASET)).files.some((f) => f.path === 'participants.tsv')) +}) + +test('phenotype: a sideways sheet becomes one row per animal, a group of columns per record', async () => { + const phenotype: BidsConfig['phenotype'] = [{ + name: 'weight', sheet: 'WEIGHT', header: 'Experimental Day', description: 'Weights.', + fields: [ + { column: 'date', label: 'Date', Description: 'Date of the weighing.', type: 'date' }, + { column: 'time', label: 'Time', Description: 'Time weighed.', type: 'time' }, + { column: 'weight', label: 'Weight (g)', Description: 'Body weight.', Units: 'g' }, + ], + }] + const sheet = xlsx({ + METADATA: [['Animal ID: (XXX001)', 'ABC001'], ['Sex (M/F)', 'M']], + WEIGHT: [['Experimental Day', 'Day 0', 'Day 1'], ['Stage', 'Initial', 'Restriction'], ['Date', '8/28/2026', 46263], ['Time', 0.5, '11:10:00'], ['Weight (g)', 30, 'N/A']], + DISC: [['Date:', '9/2/2026'], ['Trial', 'Latency (s)'], [1, 3]], + REV: [['Date:', '9/3/2026'], ['Trial', 'Latency (s)'], [1, 2]], + }) + const result = await convertToBids(upload('w.xlsx', sheet), { ...CONFIG, phenotype }, DATASET) + assert.deepEqual(result.problems, []) + assert.equal(tsvOf(result, 'phenotype/weight.tsv'), + 'participant_id\tday_0_date\tday_0_time\tday_0_weight\tday_1_date\tday_1_time\tday_1_weight\n' + + 'sub-ABC001\t2026-08-28\t12:00:00\t30\t2026-08-29\t11:10:00\tn/a\n') + const sidecar = JSON.parse(tsvOf(result, 'phenotype/weight.json')!) + assert.deepEqual(sidecar.MeasurementToolMetadata, { Description: 'Weights.' }) + assert.deepEqual(sidecar.day_1_weight, { Description: 'Day 1: Body weight.', Units: 'g' }) + const noSheet = await convertToBids(upload('n.xlsx', reporting('ABC001')), { ...CONFIG, phenotype }, DATASET) + assert.deepEqual(noSheet.problems.map((p) => p.message), ['n.xlsx, WEIGHT sheet: no "Experimental Day" row; left out of phenotype/weight.tsv.']) +}) + +test('cell values are not checked: whatever the sheet holds goes into the table as it is, with no warning', async () => { + const result = await convertToBids(upload('v.xlsx', xlsx({ + METADATA: [['Animal ID: (XXX001)', 'Mouse_7'], ['Sex (M/F)', 'M']], + DISC: [['Date:', '9/2/2026'], ['Trial', 'Ramekin Order', 'Correct?', 'Latency (s)', 'Odor Sequences'], [1, 'ABCA', 'Yes', -3, 'Error: #VALUE!'], [1, 'ABCD', 'Correct', 'fast', '#NAME?']], + REV: [['Date:', '9/3/2026'], ['Trial', 'Latency (s)'], [1, 2]], + })), { ...CONFIG, columns: { ramekin_order: { Description: 'Ramekin order.' } } }, DATASET) + assert.deepEqual(result.problems, []) + assert.equal(tsvOf(result, 'sub-Mouse7/ses-20260902/beh/sub-Mouse7_ses-20260902_task-fourchoice_acq-discrimination_beh.tsv'), + 'trial\tramekin_order\tcorrect\tlatency_s\todor_sequences\n1\tABCA\tYes\t-3\tError: #VALUE!\n1\tABCD\tCorrect\tfast\t#NAME?\n') + // What protocols.json says about a column goes into its JSON description. + assert.deepEqual(JSON.parse(tsvOf(result, 'task-fourchoice_acq-discrimination_beh.json')!).ramekin_order, + { LongName: 'Ramekin Order', Description: 'Ramekin order.' }) +}) + +test('the real 4C template archive reads: its blank reporting sheet is found, with no animal ID', async () => { + const protocols = JSON.parse(readFileSync(new URL('../../src/data/protocols.json', import.meta.url), 'utf8')) + const fourChoice = protocols.find((p: { id: string }) => p.id === 'four-choice-reversal') + const zip = new Uint8Array(readFileSync(new URL('../../public/protocols_archives/4c.zip', import.meta.url))) + const result = await convertToBids(upload('4c.zip', zip), fourChoice.bids, DATASET) + assert.deepEqual(result.problems.map((p) => p.message), + ['MAABCD 4C Digging Reversal Reporting Sheets.xlsx: "Animal ID: (XXX001)" on the METADATA sheet is empty.']) + assert.deepEqual(result.files.filter((f) => f.path.startsWith('sourcedata/')).map((f) => f.path), ['sourcedata/4c.zip']) + const reporting = unzipSync(zip)['MAABCD 4C Digging Reversal Reporting Sheets.xlsx'] + assert.deepEqual([...readWorkbook(reporting).keys()], ['METADATA', 'WEIGHT', 'ACCLIM', 'SHAPE', 'DISC', 'RECALL', 'REV', 'SUMMARY']) +}) + +test('every bids block in protocols.json is well formed', async () => { + const protocols = JSON.parse(readFileSync(new URL('../../src/data/protocols.json', import.meta.url), 'utf8')) + for (const p of protocols.filter((x: { bids?: unknown }) => x.bids)) { + const b = p.bids as BidsConfig + assert.match(b.task, /^[A-Za-z0-9]+$/, `${p.id}: task`) + assert.ok(b.subjectId?.sheet && b.subjectId?.label, `${p.id}: subjectId`) + assert.ok(b.tables.length, `${p.id}: tables`) + for (const t of b.tables) assert.ok(t.sheet && /^[A-Za-z0-9]+$/.test(t.acq) && t.header, `${p.id}: table ${t.sheet}`) + for (const t of b.tables) if (t.filledBy) assert.ok(t.filledBy.length && t.filledBy.every((n) => /^[a-z0-9_]+$/.test(n)), `${p.id}: ${t.sheet} filledBy`) + if (b.sessionDate) assert.ok(b.sessionDate.label, `${p.id}: sessionDate.label`) + assert.equal(new Set(b.tables.map((t) => t.acq)).size, b.tables.length, `${p.id}: acq labels repeat`) + } +}) + +test('fileTree: folders first, then files, each level sorted', async () => { + const { fileTree } = await import('../../src/core/bids/fileTree') + const lines = fileTree([ + 'sourcedata/b.xlsx', 'dataset_description.json', 'sub-X1/beh/sub-X1_acq-rev_beh.tsv', + 'sourcedata/a.pdf', 'sub-X1/beh/sub-X1_acq-disc_beh.tsv', + ]).map((l) => `${' '.repeat(l.depth)}${l.name}`) + assert.deepEqual(lines, [ + 'sourcedata/', ' a.pdf', ' b.xlsx', + 'sub-X1/', ' beh/', ' sub-X1_acq-disc_beh.tsv', ' sub-X1_acq-rev_beh.tsv', + 'dataset_description.json', + ]) +}) + +test('a column in skipColumns is left out of the table and its description', async () => { + const sheet = xlsx({ + METADATA: [['Animal ID: (XXX001)', 'ABC001']], + DISC: [['Date:', '9/2/2026'], ['Trial', 'Quadrant Chosen', 'Odor Chosen'], [1, 'NW', 'A']], + REV: [['Date:', '9/3/2026'], ['Trial', 'Quadrant Chosen', 'Odor Chosen'], [1, 'SE', 'B']], + }) + const result = await convertToBids(upload('a.xlsx', sheet), { ...CONFIG, skipColumns: ['quadrant_chosen'] }, DATASET) + assert.equal(tsvOf(result, 'sub-ABC001/ses-20260902/beh/sub-ABC001_ses-20260902_task-fourchoice_acq-discrimination_beh.tsv'), + 'trial\todor_chosen\n1\tA\n') + const sidecar = JSON.parse(tsvOf(result, 'task-fourchoice_acq-discrimination_beh.json')!) + assert.equal(sidecar.quadrant_chosen, undefined) + assert.ok(sidecar.trial && sidecar.odor_chosen) +}) + +test('tableInfo: the cells above a table go, as they are, into a JSON beside it; empty ones are left out', async () => { + const sheet = (odors: string[]) => [ + ['Experimenter:', 'Aria', 'Start time:', 0.3763888888888889], + ['Date:', '2026-09-02', 'End time:', null], + ['Trial Type:', 'Discrimination', 'Rewarded:', 'Anise'], + ['Odors:', ...odors], + ['Trial', 'Odor Chosen'], + [1, 'A'], + ] + const bytes = xlsx({ + METADATA: [['Animal ID: (XXX001)', 'ABC001']], + DISC: sheet(['A: Anise', null, 'B: Cinnamon']), + REV: sheet(['A: Anise', 'mint']), + }) + const config: BidsConfig = { ...CONFIG, tableInfo: [ + { key: 'Experimenter', label: 'Experimenter:' }, + { key: 'StartTime', label: 'Start time:', type: 'time' }, + { key: 'EndTime', label: 'End time:', type: 'time' }, + { key: 'Rewarded', label: 'Rewarded:' }, + { key: 'Odors', label: 'Odors:', type: 'list' }, + { key: 'Room', label: 'Room:' }, + ] } + const result = await convertToBids(upload('a.xlsx', bytes), config, DATASET) + const info = (acq: string, date: string) => + JSON.parse(tsvOf(result, `sub-ABC001/ses-${date}/beh/sub-ABC001_ses-${date}_task-fourchoice_acq-${acq}_beh.json`)!) + assert.deepEqual(info('discrimination', '20260902'), { + Experimenter: 'Aria', StartTime: '09:02:00', Rewarded: 'Anise', Odors: { A: 'Anise', B: 'Cinnamon' }, + }) + // A cell not written `letter: odor` keeps the row as a list, so nothing is lost. + assert.deepEqual(info('reversal', '20260902').Odors, ['A: Anise', 'mint']) + assert.match(tsvOf(result, 'README.md')!, /Each table's own `\.json`: the cells above the table on its sheet \(Experimenter, Start time, End time, Rewarded, Odors, Room\)\./) +}) + +test('an Excel date that also holds a time stays on its own day; a time that also holds a date keeps its time of day', async () => { + const participants: BidsConfig['participants'] = { fields: [{ column: 'dob', sheet: 'METADATA', label: 'DOB', Description: 'Date of birth.', type: 'date' }] } + const phenotype: BidsConfig['phenotype'] = [{ name: 'weight', sheet: 'WEIGHT', header: 'Experimental Day', fields: [ + { column: 'time', label: 'Time', Description: 'Time weighed.', type: 'time' }, + ] }] + const sheet = xlsx({ + // 2026-09-03 18:00, 2026-06-26 23:00; 2026-09-01 09:00, and a hair before midnight. + METADATA: [['Animal ID: (XXX001)', 'ABC001'], ['DOB', 46199.96]], + WEIGHT: [['Experimental Day', 'Day 0', 'Day 1'], ['Time', 46266.375, 0.999996]], + DISC: [['Date:', 46268.75], ['Trial', 'Latency (s)'], [1, 3]], + }) + const result = await convertToBids(upload('t.xlsx', sheet), { ...CONFIG, participants, phenotype, tables: [CONFIG.tables[0]] }, DATASET) + assert.ok(result.files.some((f) => f.path.startsWith('sub-ABC001/ses-20260903/'))) + assert.match(tsvOf(result, 'participants.tsv')!, /\t2026-06-26\n$/) + assert.equal(tsvOf(result, 'phenotype/weight.tsv'), 'participant_id\tday_0_time\tday_1_time\nsub-ABC001\t09:00:00\t00:00:00\n') +}) + +test('phenotype: a blank header cell shifts nothing; workbooks with different records share one table', async () => { + const phenotype: BidsConfig['phenotype'] = [{ name: 'weight', sheet: 'WEIGHT', header: 'Experimental Day', fields: [ + { column: 'weight', label: 'Weight (g)', Description: 'Body weight.', Units: 'g' }, + ] }] + const animal = (id: string, weight: Row[]) => xlsx({ + METADATA: [['Animal ID: (XXX001)', id]], + WEIGHT: weight, + DISC: [['Date:', '9/2/2026'], ['Trial', 'Latency (s)'], [1, 3]], + }) + const zip = zipSync({ + 'a.xlsx': animal('ABC001', [['Experimental Day', null, 'Day 0', 'Day 1'], ['Weight (g)', null, 20, 21]]), + 'b.xlsx': animal('ABC002', [['Experimental Day', 'Day 0', 'Day 1', 'Day 2'], ['Weight (g)', 30, 31, 32]]), + }) + const result = await convertToBids(upload('w.zip', zip), { ...CONFIG, phenotype, tables: [CONFIG.tables[0]] }, DATASET) + assert.deepEqual(result.problems, []) + assert.equal(tsvOf(result, 'phenotype/weight.tsv'), + 'participant_id\tday_0_weight\tday_1_weight\tday_2_weight\nsub-ABC001\t20\t21\tn/a\nsub-ABC002\t30\t31\t32\n') + assert.deepEqual(Object.keys(JSON.parse(tsvOf(result, 'phenotype/weight.json')!)), ['day_0_weight', 'day_1_weight', 'day_2_weight']) +}) + +test('a stage\'s column descriptions cover every workbook\'s columns', async () => { + const animal = (id: string, header: string[]) => xlsx({ + METADATA: [['Animal ID: (XXX001)', id]], + DISC: [['Date:', '9/2/2026'], header, [1, 3, 'x']], + }) + const zip = zipSync({ 'a.xlsx': animal('ABC001', ['Trial', 'Latency (s)']), 'b.xlsx': animal('ABC002', ['Trial', 'Latency (s)', 'Error type']) }) + const result = await convertToBids(upload('c.zip', zip), { ...CONFIG, tables: [CONFIG.tables[0]] }, DATASET) + const described = JSON.parse(tsvOf(result, 'task-fourchoice_acq-discrimination_beh.json')!) + assert.deepEqual([described.latency_s, described.error_type], [{ LongName: 'Latency (s)', Units: 's' }, { LongName: 'Error type' }]) +}) + +test('Animal IDs that differ only in upper/lower case are one ID twice', async () => { + const result = await convertToBids(upload('c.zip', zipSync({ 'a.xlsx': reporting('abc001'), 'b.xlsx': reporting('ABC-001') })), CONFIG, DATASET) + assert.deepEqual(result.problems.map((p) => p.message), ['b.xlsx (Animal ID ABC001) and a.xlsx (abc001) have the same Animal ID apart from upper/lower case.']) +}) + +test('a workbook on the 1904 date system: its dates read as the dates Excel shows', async () => { + const sheet = (date1904: boolean) => { + // 2026-09-02 is 46267 in the 1900 system, 44805 in the 1904 one. + const files = unzipSync(xlsx({ METADATA: [['Animal ID: (XXX001)', 'ABC001']], DISC: [['Date:', date1904 ? 44805 : 46267], ['Trial', 'Latency (s)'], [1, 3]] })) + if (date1904) files['xl/workbook.xml'] = strToU8(strFromU8(files['xl/workbook.xml']).replace('', '')) + return zipSync(files) + } + assert.equal(readWorkbook(sheet(true)).date1904, true) + assert.equal(readWorkbook(sheet(false)).date1904, undefined) + for (const date1904 of [true, false]) { + const result = await convertToBids(upload('d.xlsx', sheet(date1904)), { ...CONFIG, tables: [CONFIG.tables[0]] }, DATASET) + assert.ok(result.files.some((f) => f.path.startsWith('sub-ABC001/ses-20260902/')), `date1904=${date1904}`) + } +}) diff --git a/applications/idp-arc/frontend/tests/unit/bidsMerge.test.ts b/applications/idp-arc/frontend/tests/unit/bidsMerge.test.ts new file mode 100644 index 0000000..4b02b1d --- /dev/null +++ b/applications/idp-arc/frontend/tests/unit/bidsMerge.test.ts @@ -0,0 +1,29 @@ +// Merging a re-upload's per-animal files with the draft's (core/bids/merge.ts). Run: yarn test:unit +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { isMergedFile, mergeWithDraft } from '../../src/core/bids/merge' + +test('only the per-animal files, their descriptions and the stage descriptions are merged', () => { + assert.deepEqual(['participants.tsv', 'participants.json', 'phenotype/weight.tsv', 'phenotype/weight.json', 'task-x_acq-y_beh.json'].map(isMergedFile), [true, true, true, true, true]) + assert.deepEqual(['dataset_description.json', 'sub-A/beh/sub-A_beh.tsv', 'sub-A/ses-1/beh/sub-A_ses-1_task-x_acq-y_beh.json', 'sourcedata/participants.tsv'].map(isMergedFile), [false, false, false, false]) +}) + +test('a stage description keeps the columns only earlier uploads had', () => { + const merged = JSON.parse(mergeWithDraft('task-x_acq-y_beh.json', + '{"TaskName":"x","error_type":{"LongName":"Error type"},"latency_s":{"LongName":"old"}}', + '{"TaskName":"x","latency_s":{"LongName":"Latency (s)","Units":"s"}}')) + assert.deepEqual(merged, { TaskName: 'x', error_type: { LongName: 'Error type' }, latency_s: { LongName: 'Latency (s)', Units: 's' } }) +}) + +test('rows merge by participant_id; columns are the union, missing cells n/a', () => { + const existing = 'participant_id\tday_0_weight\tday_7_weight\nsub-A\t30\t28\nsub-B\t31\t29\n' + const incoming = 'participant_id\tday_0_weight\nsub-B\t32\nsub-C\t33\n' + assert.equal(mergeWithDraft('phenotype/weight.tsv', existing, incoming), + 'participant_id\tday_0_weight\tday_7_weight\nsub-A\t30\t28\nsub-B\t32\tn/a\nsub-C\t33\tn/a\n') + assert.equal(mergeWithDraft('participants.tsv', '', incoming), incoming) +}) + +test('descriptions merge by key, the new one winning', () => { + const merged = JSON.parse(mergeWithDraft('participants.json', '{"a":{"Description":"old"},"b":{"Description":"kept"}}', '{"a":{"Description":"new"}}')) + assert.deepEqual(merged, { a: { Description: 'new' }, b: { Description: 'kept' } }) +}) diff --git a/applications/idp-arc/frontend/tests/unit/dandiInstances.test.ts b/applications/idp-arc/frontend/tests/unit/dandiInstances.test.ts new file mode 100644 index 0000000..96ad950 --- /dev/null +++ b/applications/idp-arc/frontend/tests/unit/dandiInstances.test.ts @@ -0,0 +1,42 @@ +// The DANDI instance in use (core/dandiInstances.ts). Run: yarn test:unit +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import { DANDI_INSTANCES, dandiInstance, isDandiInstanceName, maabcdDandisetFor } from '../../src/core/dandiInstances' + +test('EMBER-DANDI when no instance is configured', () => { + for (const unset of [undefined, '', ' ']) { + assert.deepEqual(dandiInstance(unset), { name: 'ember-dandi', api: 'https://api-dandi.emberarchive.org', web: 'https://dandi.emberarchive.org' }) + } +}) + +test('each sandbox gives its own API and web origins', () => { + assert.deepEqual(dandiInstance(' dandi-sandbox '), { name: 'dandi-sandbox', api: 'https://api.sandbox.dandiarchive.org', web: 'https://sandbox.dandiarchive.org' }) + assert.equal(dandiInstance('ember-dandi-sandbox').api, 'https://api-dandi.sandbox.emberarchive.org') + assert.deepEqual(Object.keys(DANDI_INSTANCES), ['ember-dandi', 'ember-dandi-sandbox', 'dandi-sandbox']) +}) + +test('an unknown instance name throws, naming the ones there are', () => { + assert.throws(() => dandiInstance('dandi-sandbx'), /"dandi-sandbx".*ember-dandi, ember-dandi-sandbox, dandi-sandbox/) + assert.throws(() => dandiInstance('dandi'), /not a DANDI instance/) + assert.throws(() => dandiInstance('toString'), /not a DANDI instance/) +}) + +test('a protocol\'s MAABCD dandiset is the one for the instance in use, or none', () => { + const protocol = { maabcdAggregateDandisets: { 'ember-dandi': '000607', 'dandi-sandbox': '219158' } } + assert.equal(maabcdDandisetFor(protocol, 'ember-dandi'), '000607') + assert.equal(maabcdDandisetFor(protocol, 'dandi-sandbox'), '219158') + assert.equal(maabcdDandisetFor({}, 'ember-dandi'), undefined) +}) + +test('every maabcdAggregateDandisets key in protocols.json is an instance, and its value six digits', () => { + const protocols = JSON.parse(readFileSync(new URL('../../src/data/protocols.json', import.meta.url), 'utf8')) + for (const p of protocols) { + assert.equal('maabcdAggregateDandisetId' in p, false, `${p.id}: the field is now maabcdAggregateDandisets, by instance`) + for (const [instance, id] of Object.entries(p.maabcdAggregateDandisets ?? {})) { + assert.ok(isDandiInstanceName(instance), `${p.id}: "${instance}" is not a DANDI instance`) + assert.match(id as string, /^\d{6}$/, `${p.id}: ${instance}`) + } + } +}) + diff --git a/applications/idp-arc/frontend/tests/unit/dandisetReadme.test.ts b/applications/idp-arc/frontend/tests/unit/dandisetReadme.test.ts new file mode 100644 index 0000000..e2504fc --- /dev/null +++ b/applications/idp-arc/frontend/tests/unit/dandisetReadme.test.ts @@ -0,0 +1,120 @@ +// The README packed into an upload (core/dandisetReadme.ts). Run: yarn test:unit +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { strFromU8, strToU8, unzipSync, zipSync } from 'fflate' +import { dandisetReadme, withReadme } from '../../src/core/dandisetReadme' + +const README = dandisetReadme({ + name: 'Cohort A, spring 2026', + dandisetId: '000777', + dandisetUrl: 'https://dandi.example.org/dandiset/000777', + protocol: { + name: 'Four-choice reversal digging task', + url: 'https://github.com/maracbaylis/four-choice-example', + description: 'Mice must identify the single rewarded option.', + }, + originalName: 'cohort.zip', + folder: 'sourcedata/upload-2026-11-05T10-15-00Z', +}) + +const unpack = async (file: File) => unzipSync(new Uint8Array(await file.arrayBuffer())) + +/** When the researcher last saved the sheet: 3 Nov 2026, 14:05. */ +const SAVED = new Date(2026, 10, 3, 14, 5).getTime() + +/** The DOS date and time a zip's central directory stores for `name`, as a timestamp. */ +function dosDate(zip: Uint8Array, name: string): number { + const view = new DataView(zip.buffer, zip.byteOffset, zip.byteLength) + for (let i = 0; i + 46 <= zip.length; i++) { + if (view.getUint32(i, true) !== 0x02014b50) continue + const nameLength = view.getUint16(i + 28, true) + if (new TextDecoder().decode(zip.subarray(i + 46, i + 46 + nameLength)) !== name) continue + const time = view.getUint16(i + 12, true), date = view.getUint16(i + 14, true) + return new Date(1980 + (date >> 9), ((date >> 5) & 15) - 1, date & 31, time >> 11, (time >> 5) & 63, (time & 31) * 2).getTime() + } + throw new Error(`${name} is not in the zip`) +} + +test('the README says what the dataset is, where it is in the dandiset, how to cite it, and nothing time-dependent', () => { + assert.equal(README, [ + '# Cohort A, spring 2026', + '', + 'Behavioral data from the Four-choice reversal digging task.', + '', + 'Mice must identify the single rewarded option.', + '', + '## Files', + '', + '- `cohort.zip`: the researcher\'s upload. Every file here except this README comes from it, unchanged.', + '', + '## Where it is', + '', + '- Dandiset 000777: https://dandi.example.org/dandiset/000777', + '- This upload: `sourcedata/upload-2026-11-05T10-15-00Z/` in that dandiset.', + '- The tables made from it: the dandiset\'s `sub-/` folders, described in its top-level `README.md`.', + '', + '## How to cite', + '', + 'Cite a published version of dandiset 000777 by its DOI, listed on the dandiset\'s page. Uploads go to its draft, which has no DOI.', + '', + '## Analysis code', + '', + '- https://github.com/maracbaylis/four-choice-example', + '', + ].join('\n')) +}) + +test('without a description or analysis code, those lines are left out', () => { + const readme = dandisetReadme({ name: 'X', dandisetId: '1', dandisetUrl: 'u', protocol: { name: 'P' }, originalName: 'a.xlsx', folder: 'f' }) + assert.doesNotMatch(readme, /Analysis code|\n\n\n/) +}) + +test('a single file is zipped together with the README, under its own name', async () => { + const packed = await withReadme(new File(['sheet bytes'], 'animal 01.xlsx'), README) + assert.equal(packed.name, 'animal 01.zip') + const entries = await unpack(packed) + assert.deepEqual(Object.keys(entries), ['README.md', 'animal 01.xlsx']) + assert.equal(strFromU8(entries['README.md']), README) + assert.equal(strFromU8(entries['animal 01.xlsx']), 'sheet bytes') +}) + +test('a zip keeps its name and every entry byte for byte, folders included; the README is listed first', async () => { + const upload = zipSync({ 'cohort/': new Uint8Array(), 'cohort/a.xlsx': strToU8('a'), 'cohort/protocol.pdf': strToU8('p') }) + const packed = await withReadme(new File([upload], 'cohort.zip'), README) + assert.equal(packed.name, 'cohort.zip') + const entries = await unpack(packed) + assert.deepEqual(Object.keys(entries), ['README.md', 'cohort/', 'cohort/a.xlsx', 'cohort/protocol.pdf']) + assert.equal(strFromU8(entries['cohort/a.xlsx']), 'a') + // Everything before the old table of contents is copied, not recompressed. + const cdOffset = new DataView(upload.buffer).getUint32(upload.length - 6, true) + assert.deepEqual(new Uint8Array(await packed.slice(0, cdOffset).arrayBuffer()), upload.slice(0, cdOffset)) +}) + +test('a README.md already in the zip is replaced by ours; the other files stay', async () => { + const upload = zipSync({ 'README.md': strToU8('the lab\'s own notes'), 'a.xlsx': strToU8('a') }) + const entries = await unpack(await withReadme(new File([upload], 'x.zip'), README)) + assert.deepEqual(Object.keys(entries), ['README.md', 'a.xlsx']) + assert.equal(strFromU8(entries['README.md']), README) +}) + +test('the same file and README always give the same bytes, so a retry gets the same checksum', async () => { + const bytes = async () => new Uint8Array(await (await withReadme(new File(['sheet'], 'a.xlsx', { lastModified: SAVED }), README)).arrayBuffer()) + assert.deepEqual(await bytes(), await bytes()) +}) + +test('every file in the zip is dated when the researcher last saved theirs; one before 1980 gets 1980, the earliest a zip can hold', async () => { + const dates = async (lastModified: number) => { + const zip = new Uint8Array(await (await withReadme(new File(['sheet'], 'a.xlsx', { lastModified }), README)).arrayBuffer()) + const found: Date[] = [] + unzipSync(zip, { filter: (f) => { found.push(new Date(dosDate(zip, f.name))); return false } }) + return found.map((d) => d.toDateString()) + } + assert.deepEqual(await dates(SAVED), [new Date(SAVED).toDateString(), new Date(SAVED).toDateString()]) + assert.deepEqual(await dates(0), [new Date(1980, 0, 1).toDateString(), new Date(1980, 0, 1).toDateString()]) +}) + +test('a .zip that is not a readable zip is carried inside the new one as it is', async () => { + const entries = await unpack(await withReadme(new File(['not a zip'], 'broken.zip'), README)) + assert.deepEqual(Object.keys(entries), ['README.md', 'broken.zip']) + assert.equal(strFromU8(entries['broken.zip']), 'not a zip') +}) diff --git a/applications/idp-arc/frontend/tests/unit/emberClients.test.ts b/applications/idp-arc/frontend/tests/unit/emberClients.test.ts index ae5b4e8..7a34b6a 100644 --- a/applications/idp-arc/frontend/tests/unit/emberClients.test.ts +++ b/applications/idp-arc/frontend/tests/unit/emberClients.test.ts @@ -113,8 +113,8 @@ test('the dandiset list reads as many pages as EMBER\'s count says, through the test('a search is passed to EMBER, encoded, on every page', async () => { const requests = recordFetch(() => ({ json: { count: 1, results: [{ identifier: '000001' }] } })) - await new EmberDandiDirectClient('/ember-proxy').listOwnDandisets('ember-token', 'idp-protocol:four-choice-reversal') - assert.match(requests[0].url, /&search=idp-protocol%3Afour-choice-reversal&/) + await new EmberDandiDirectClient('/ember-proxy').listOwnDandisets('ember-token', 'maabcd-protocol:four-choice-reversal') + assert.match(requests[0].url, /&search=maabcd-protocol%3Afour-choice-reversal&/) }) test('one page when the count fits in it, none more for an empty account', async () => { @@ -132,3 +132,23 @@ test('an empty page ends the list early', async () => { await new EmberDandiDirectClient('/ember-proxy').listOwnDandisets('ember-token') assert.equal(requests.length, 1) }) + +test('a file already at the path: kept when its content is the same or replace is off, replaced when it differs', async () => { + const at = (blob: string) => (url: string) => url.endsWith('/assets/') ? { status: 409 } + : url.includes('/assets/?path=') ? { json: { results: [{ path: 'README.md', asset_id: 'old-asset', blob }] } } + : { json: { asset_id: 'new-asset', path: 'README.md' } } + const ember = new EmberDandiDirectClient('/ember-proxy') + const finalize = (replace: boolean) => ember.finalizeUpload('t', { dandisetId: '000777', path: 'README.md', parts: [], blobId: 'blob-new', replace }) + + recordFetch(at('blob-new')) + assert.deepEqual(await finalize(true), { assetPath: 'README.md', assetId: 'old-asset' }) + recordFetch(at('blob-old')) + assert.deepEqual(await finalize(false), { assetPath: 'README.md', assetId: 'old-asset' }) + + const requests = recordFetch(at('blob-old')) + assert.deepEqual(await finalize(true), { assetPath: 'README.md', assetId: 'new-asset' }) + const put = requests.at(-1)! + assert.equal(put.method, 'PUT') + assert.equal(put.url, '/ember-proxy/api/dandisets/000777/versions/draft/assets/old-asset/') + assert.deepEqual(put.body, { metadata: { path: 'README.md', schemaKey: 'Asset', encodingFormat: 'text/markdown' }, blob_id: 'blob-new' }) +}) diff --git a/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts b/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts index b27cdf1..e272610 100644 --- a/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts +++ b/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts @@ -1,23 +1,33 @@ // The EMBER-DANDI upload (core/use-cases/emberObjectStore.ts) against in-memory ports. Run: yarn test:unit import { test } from 'node:test' import assert from 'node:assert/strict' -import { createEmberObjectStore, EMBER_SIGN_IN } from '../../src/core/use-cases/emberObjectStore' +import { BIDS_WRITES_AT_ONCE, createEmberObjectStore, EMBER_SIGN_IN } from '../../src/core/use-cases/emberObjectStore' import type { IDandiDirectApi } from '../../src/core/ports/IDandiDirectApi' import type { IEmberUploadApi } from '../../src/core/ports/IEmberUploadApi' import { UserFacingError } from '../../src/core/userMessages' +import { strFromU8, unzipSync } from 'fflate' +import { reporting } from './xlsxFixture' const ORIGIN = 'https://api-dandi.example.org' -const file = () => new File(['animal data'], 'animal 01.xlsx') +const WEB = 'https://dandi.example.org' +const WORKBOOK = reporting('ABC001') +const file = () => new File([WORKBOOK as BlobPart], 'animal 01.xlsx', { lastModified: new Date(2026, 10, 3).getTime() }) +const BIDS = { + config: { task: 'fourchoice', subjectId: { sheet: 'METADATA', label: 'Animal ID: (XXX001)' }, tables: [{ sheet: 'DISC', acq: 'discrimination', header: 'Trial' }] }, + protocol: { name: 'Four-choice' }, +} const finalizedPaths: string[] = [] -function fakes(opts: { dedupDirect?: boolean; dedupOsb?: boolean; shortParts?: boolean; failOsbOnce?: boolean; failDirectOnce?: boolean } = {}) { +function fakes(opts: { draftName?: string; accountName?: string | null; accountFails?: boolean; dedupDirect?: boolean; dedupOsb?: boolean; shortParts?: boolean; failOsbOnce?: boolean; failDirectOnce?: boolean; draft?: Record; draftUnreadable?: boolean; slowFinalize?: boolean; failFinalizeOf?: string } = {}) { const calls: string[] = [] + const writes = { now: 0, most: 0 } + const sent: Blob[] = [] let osbFails = opts.failOsbOnce ? 1 : 0 let directFails = opts.failDirectOnce ? 1 : 0 const direct: IDandiDirectApi = { async listOwnDandisets() { return [] }, async createDandiset() { throw new Error('created through the protocol use case') }, - async getDraftMetadata() { return {} }, + async getDraftMetadata() { return opts.draftName ? { name: opts.draftName } : {} }, async updateDraftMetadata() {}, async getVersionInfo() { return { version: 'draft', status: 'Valid', errors: [], filesBeingChecked: 0 } }, async publishDraft() {}, @@ -27,12 +37,21 @@ function fakes(opts: { dedupDirect?: boolean; dedupOsb?: boolean; shortParts?: b if (directFails > 0) { directFails -= 1; throw new Error('EMBER initialize failed') } return opts.dedupDirect ? { parts: [], blobId: 'blob-1' } : { uploadId: 'up-1', parts: [{ partNumber: 1, size: 11, url: 'https://s3/direct' }] } }, - async putPart(url) { calls.push(`put:${url}`); return `etag-${url.split('/').pop()}` }, + async putPart(url, body) { calls.push(`put:${url}`); sent.push(body); return `etag-${url.split('/').pop()}` }, async finalizeUpload(token, input) { + writes.most = Math.max(writes.most, ++writes.now) + if (opts.slowFinalize) await new Promise((resolve) => setTimeout(resolve, 5)) + writes.now-- + if (input.path === opts.failFinalizeOf) throw new Error(`EMBER register failed for ${input.path}`) finalizedPaths.push(input.path) calls.push(`direct-finalize:${input.dandisetId}:${input.uploadId ?? 'dedup'}:${input.parts.map((p) => p.etag).join(',')}`) return { assetId: 'asset-1', assetPath: input.path } }, + async readDraftFile(_t, _id, path) { + calls.push(`read:${path}`) + if (opts.draftUnreadable) throw new Error('EMBER download of participants.tsv failed (HTTP 403)') + return opts.draft?.[path] ?? null + }, } const osb: IEmberUploadApi = { async getUploadUrls(token, input) { @@ -52,9 +71,17 @@ function fakes(opts: { dedupDirect?: boolean; dedupOsb?: boolean; shortParts?: b async recordWorkspace(dandisetId: string, workspaceId: number, protocol: { id: string }) { calls.push(`record:${dandisetId}:${workspaceId}:${protocol.id}`) }, } const store = (emberToken: string | null = 'ember-token') => createEmberObjectStore( - { getToken: async () => 'osb-token' }, { getToken: () => emberToken }, direct, osb, dandisets, `${ORIGIN}/`, + { getToken: async () => 'osb-token' }, + { + getToken: () => emberToken, + getAccount: async () => { + if (opts.accountFails) throw new Error('Could not read EMBER-DANDI account (HTTP 500).') + return { username: 'ada', name: opts.accountName ?? null } + }, + }, + direct, osb, dandisets, `${ORIGIN}/`, WEB, ) - return { calls, store } + return { calls, store, sent, writes } } test('uploads to the picked dandiset directly; the MAABCD copy is a separate call, through OSB', async () => { @@ -62,17 +89,18 @@ test('uploads to the picked dandiset directly; the MAABCD copy is a separate cal const progress: number[] = [] const stored = await store().put({ file: file(), protocolId: 'four-choice-reversal', userSub: 'user-1', - dandisets: { user: '000123', maabcd: '000533' }, + bids: BIDS, dandisets: { user: '000123', maabcd: '000533' }, }, (sent, total) => progress.push(sent / total)) - assert.deepEqual(calls, ['direct-init:ember-token:000123', 'put:https://s3/direct', 'direct-finalize:000123:up-1:etag-direct']) + assert.deepEqual(calls.slice(0, 3), ['direct-init:ember-token:000123', 'put:https://s3/direct', 'direct-finalize:000123:up-1:etag-direct']) // Plain data, so it can be saved across a reload: the copy needs the etag, not the file. assert.deepEqual(JSON.parse(JSON.stringify(stored)), stored) + calls.length = 0 await store().shareWithMaabcd!(stored, '000533', file()) - assert.deepEqual(calls.slice(3), ['osb-urls:osb-token:000533:animal 01.xlsx:true', 'put:https://s3/osb', 'osb-validate:000533:etag-osb']) + assert.deepEqual(calls, ['osb-urls:osb-token:000533:animal 01.zip:true', 'put:https://s3/osb', 'osb-validate:000533:etag-osb']) // The run imports the researcher's own copy, from EMBER's public origin (not the browser's proxy). assert.equal(stored.url, `${ORIGIN}/api/assets/asset-1/download/`) - assert.match(stored.key, /^four-choice-reversal\/[0-9a-f-]{36}\/animal-01\.xlsx$/) + assert.match(stored.key, /^sourcedata\/upload-\d{4}-\d\d-\d\dT\d\d-\d\d-\d\dZ\/animal-01\.zip$/) assert.equal(stored.dandisetId, '000123') assert.equal(progress.at(-1), 1) assert.ok(progress.every((p, i) => i === 0 || p >= progress[i - 1]), 'progress never goes backwards') @@ -82,7 +110,7 @@ test('creates the dandiset for the protocol when none was picked, and skips OSB const { calls, store } = fakes() const stored = await store().put({ file: file(), protocolId: 'asst', userSub: 'user-1', - dandisets: { newName: 'ASST (IDP)', protocol: { id: 'asst', name: 'ASST' }, maabcd: '' }, + bids: BIDS, dandisets: { newName: 'ASST (IDP)', protocol: { id: 'asst', name: 'ASST' }, maabcd: '' }, }) assert.equal(calls[0], 'create:ASST (IDP):asst') @@ -96,7 +124,7 @@ test('creates the dandiset for the protocol when none was picked, and skips OSB test('deduplicated content moves no bytes and registers against the existing blob', async () => { const { calls, store } = fakes({ dedupDirect: true, dedupOsb: true }) - const stored = await store().put({ file: file(), protocolId: 'p', userSub: 'u', dandisets: { user: '000123', maabcd: '000533' } }) + const stored = await store().put({ file: file(), protocolId: 'p', userSub: 'u', bids: BIDS, dandisets: { user: '000123', maabcd: '000533' } }) await store().shareWithMaabcd!(stored, '000533') assert.ok(!calls.some((c) => c.startsWith('put:'))) @@ -106,7 +134,7 @@ test('deduplicated content moves no bytes and registers against the existing blo test('a part list that does not cover the file is refused before any of it is uploaded', async () => { const { calls, store } = fakes({ shortParts: true }) - const stored = await store().put({ file: file(), protocolId: 'p', userSub: 'u', dandisets: { user: '000123', maabcd: '000533' } }) + const stored = await store().put({ file: file(), protocolId: 'p', userSub: 'u', bids: BIDS, dandisets: { user: '000123', maabcd: '000533' } }) await assert.rejects(store().shareWithMaabcd!(stored, '000533', file()), /part URLs/) assert.ok(!calls.includes('put:https://s3/a')) }) @@ -114,7 +142,7 @@ test('a part list that does not cover the file is refused before any of it is up test('without an EMBER-DANDI sign-in nothing starts and the user is asked to sign in', async () => { const { calls, store } = fakes() await assert.rejects( - store(null).put({ file: file(), protocolId: 'p', userSub: 'u', dandisets: { user: '000123' } }), + store(null).put({ file: file(), protocolId: 'p', userSub: 'u', bids: BIDS, dandisets: { user: '000123' } }), (err: unknown) => err instanceof UserFacingError && err.message === EMBER_SIGN_IN, ) assert.deepEqual(calls, []) @@ -124,31 +152,32 @@ test('without an EMBER-DANDI sign-in nothing starts and the user is asked to sig test('a failed MAABCD copy rejects on its own; calling it again makes only that copy', async () => { const { calls, store } = fakes({ failOsbOnce: true }) - const stored = await store().put({ file: file(), protocolId: 'p', userSub: 'u', dandisets: { user: '000123', maabcd: '000533' } }) + const stored = await store().put({ file: file(), protocolId: 'p', userSub: 'u', bids: BIDS, dandisets: { user: '000123', maabcd: '000533' } }) await assert.rejects(store().shareWithMaabcd!(stored, '000533', file()), /503/) calls.length = 0 await store().shareWithMaabcd!(stored, '000533', file()) - assert.deepEqual(calls, ['osb-urls:osb-token:000533:animal 01.xlsx:true', 'put:https://s3/osb', 'osb-validate:000533:etag-osb']) + assert.deepEqual(calls, ['osb-urls:osb-token:000533:animal 01.zip:true', 'put:https://s3/osb', 'osb-validate:000533:etag-osb']) }) test('without the file, the MAABCD copy works when EMBER already holds the bytes, and fails when it would need the bytes', async () => { const dedup = fakes({ dedupOsb: true }) - const stored = await dedup.store().put({ file: file(), protocolId: 'p', userSub: 'u', dandisets: { user: '000123', maabcd: '000533' } }) + const stored = await dedup.store().put({ file: file(), protocolId: 'p', userSub: 'u', bids: BIDS, dandisets: { user: '000123', maabcd: '000533' } }) await dedup.store().shareWithMaabcd!(stored, '000533', null) assert.ok(dedup.calls.includes('osb-validate:000533:blob-1')) const parts = fakes() - const first = await parts.store().put({ file: file(), protocolId: 'p', userSub: 'u', dandisets: { user: '000123', maabcd: '000533' } }) + const first = await parts.store().put({ file: file(), protocolId: 'p', userSub: 'u', bids: BIDS, dandisets: { user: '000123', maabcd: '000533' } }) await assert.rejects(parts.store().shareWithMaabcd!(first, '000533', null), /needs the file/) }) test('a resumed upload registers the same path, so it finds the asset rather than add one', async () => { const { calls, store } = fakes() - const resume = { userDandisetId: '000123', etag: 'e', path: 'p/fixed-uuid/f.xlsx' } - await store().put({ file: file(), protocolId: 'p', userSub: 'u', dandisets: { user: '000123' }, resume }) + const resume = { userDandisetId: '000123', etag: 'e', path: 'sourcedata/upload-fixed/f.zip' } + finalizedPaths.length = 0 + await store().put({ file: file(), protocolId: 'p', userSub: 'u', bids: BIDS, dandisets: { user: '000123' }, resume }) assert.ok(calls.includes('direct-finalize:000123:up-1:etag-direct')) - assert.equal(finalizedPaths.at(-1), 'p/fixed-uuid/f.xlsx') + assert.equal(finalizedPaths[0], 'sourcedata/upload-fixed/f.zip') }) test('a retry after the own copy failed reuses the dandiset it created', async () => { @@ -156,7 +185,7 @@ test('a retry after the own copy failed reuses the dandiset it created', async ( const checkpoints: unknown[] = [] const input = { file: file(), protocolId: 'asst', userSub: 'u', - dandisets: { newName: 'ASST (IDP)', protocol: { id: 'asst', name: 'ASST' } }, + bids: BIDS, dandisets: { newName: 'ASST (IDP)', protocol: { id: 'asst', name: 'ASST' } }, onCheckpoint: (c: unknown) => checkpoints.push(c), } await assert.rejects(store().put(input), /initialize failed/) @@ -170,10 +199,196 @@ test('a retry after the own copy failed reuses the dandiset it created', async ( test('a retry with everything done makes no copy at all', async () => { const { calls, store } = fakes() - const resume = { userDandisetId: '000123', own: { assetId: 'asset-1', assetPath: 'p/x/f' } } - const stored = await store().put({ file: file(), protocolId: 'p', userSub: 'u', dandisets: { user: '000123', maabcd: '000533' }, resume }) + const checkpoints: Record[] = [] + const input = { file: file(), protocolId: 'p', userSub: 'u', bids: BIDS, dandisets: { user: '000123', maabcd: '000533' } } + await store().put({ ...input, onCheckpoint: (c) => checkpoints.push(c as Record) }) + calls.length = 0 + const stored = await store().put({ ...input, resume: checkpoints.at(-1) }) assert.deepEqual(calls, []) assert.equal(stored.url, `${ORIGIN}/api/assets/asset-1/download/`) }) + +test('what goes up is the file zipped with a README linking the dandiset; the MAABCD copy rebuilds the same bytes', async () => { + const { store, sent } = fakes() + const stored = await store().put({ + file: file(), protocolId: 'four-choice-reversal', userSub: 'user-1', + bids: BIDS, dandisets: { user: '000123', protocol: { id: 'four-choice-reversal', name: 'Four-choice reversal digging task' } }, + }) + const uploaded = unzipSync(new Uint8Array(await sent[0].arrayBuffer())) + assert.deepEqual(Object.keys(uploaded), ['README.md', 'animal 01.xlsx']) + assert.deepEqual(uploaded['animal 01.xlsx'], WORKBOOK) + assert.match(strFromU8(uploaded['README.md']), /^- Dandiset 000123: https:\/\/dandi\.example\.org\/dandiset\/000123$/m) + // The README names the folder the upload went into. + assert.ok(strFromU8(uploaded['README.md']).includes(`- This upload: \`${stored.key.slice(0, stored.key.lastIndexOf('/'))}/\` in that dandiset.`)) + assert.equal(stored.readme, strFromU8(uploaded['README.md'])) + assert.equal(stored.name, 'animal 01.zip') + assert.equal(stored.size, sent[0].size) + + // Without the etag (an older checkpoint), the copy hashes the file it is given: rebuilt, it matches. + await store().shareWithMaabcd!({ ...stored, etag: undefined }, '000533', file()) + assert.deepEqual(new Uint8Array(await sent.at(-1)!.arrayBuffer()), new Uint8Array(await sent[0].arrayBuffer())) +}) + +test('the upload goes to sourcedata/, the tables made from it beside it; a retry skips what is done', async () => { + const { reporting } = await import('./xlsxFixture') + const { calls, store } = fakes({ dedupDirect: true }) + finalizedPaths.length = 0 + const bids = { + config: { + task: 'fourchoice', + subjectId: { sheet: 'METADATA', label: 'Animal ID: (XXX001)' }, + sessionDate: { label: 'Date:' }, + tables: [{ sheet: 'DISC', acq: 'discrimination', header: 'Trial' }, { sheet: 'REV', acq: 'reversal', header: 'Trial' }], + }, + protocol: { name: 'Four-choice', description: 'Mice dig.' }, + } + const workbook = new File([reporting('ABC001') as BlobPart], 'Lab_ABC001.xlsx') + const checkpoints: Record[] = [] + const written_: string[] = [] + const stored = await store().put({ + file: workbook, protocolId: 'four-choice-reversal', userSub: 'user-1', + dandisets: { user: '000123', newName: 'My cohort' }, bids, + onCheckpoint: (c) => checkpoints.push(c as Record), + onBidsProgress: (written, total) => written_.push(`${written}/${total}`), + }) + + // OSB imports the upload (with its README) from sourcedata/, so the run is unchanged. + assert.match(stored.key, /^sourcedata\/upload-\d{4}-\d\d-\d\dT\d\d-\d\d-\d\dZ\/Lab_ABC001\.zip$/) + assert.deepEqual(finalizedPaths.slice(1), [ + 'sub-ABC001/ses-20260902/beh/sub-ABC001_ses-20260902_task-fourchoice_acq-discrimination_beh.tsv', + 'sub-ABC001/ses-20260903/beh/sub-ABC001_ses-20260903_task-fourchoice_acq-reversal_beh.tsv', + 'task-fourchoice_acq-discrimination_beh.json', + 'task-fourchoice_acq-reversal_beh.json', + 'dataset_description.json', + 'README.md', + ]) + assert.equal(calls.filter((c) => c.startsWith('direct-finalize')).length, 7) + // Each BIDS file written is reported, so the step shows it moving after the file itself is up. + assert.deepEqual(written_, ['0/6', '1/6', '2/6', '3/6', '4/6', '5/6', '6/6']) + + // A retry from the last checkpoint registers nothing again. + finalizedPaths.length = 0 + written_.length = 0 + await store().put({ file: workbook, protocolId: 'four-choice-reversal', userSub: 'user-1', dandisets: { user: '000123' }, bids, resume: checkpoints.at(-1), + onBidsProgress: (written, total) => written_.push(`${written}/${total}`) }) + assert.deepEqual(finalizedPaths, []) + assert.deepEqual(written_, ['6/6']) + + // A sheet the conversion can't use stops the upload, saying why, before any table goes up. + const blank = new File([reporting(null) as BlobPart], 'blank.xlsx') + await assert.rejects( + store().put({ file: blank, protocolId: 'four-choice-reversal', userSub: 'user-1', dandisets: { user: '000123' }, bids }), + (e: unknown) => e instanceof UserFacingError && /Animal ID: \(XXX001\)" on the METADATA sheet is empty/.test(e.message), + ) +}) + +test('the BIDS dataset\'s author is the EMBER-DANDI account\'s name; the OSB name only when the account has none', async () => { + const { reporting } = await import('./xlsxFixture') + const authorsFor = async (opts: Parameters[0]) => { + const { sent, store } = fakes(opts) + await store().put({ + file: new File([reporting('ABC001') as BlobPart], 'Lab_ABC001.xlsx'), protocolId: 'four-choice-reversal', userSub: 'user-1', + dandisets: { user: '000123', newName: 'Four-choice' }, + bids: { + config: { task: 'fourchoice', subjectId: { sheet: 'METADATA', label: 'Animal ID: (XXX001)' }, tables: [{ sheet: 'DISC', acq: 'discrimination', header: 'Trial' }] }, + protocol: { name: 'Four-choice' }, + authors: ['Osb Name'], + }, + }) + const texts = await Promise.all(sent.map((b) => b.text())) + return texts.map((t) => { try { return JSON.parse(t) } catch { return null } }).find((j) => j?.BIDSVersion).Authors + } + assert.deepEqual(await authorsFor({ accountName: ' Ada Lovelace ' }), ['Ada Lovelace']) + assert.deepEqual(await authorsFor({ accountName: null }), ['Osb Name']) + assert.deepEqual(await authorsFor({ accountName: ' ' }), ['Osb Name']) + assert.deepEqual(await authorsFor({ accountFails: true }), ['Osb Name']) +}) + +test('the BIDS dataset is named after the dandiset itself, not the protocol, when uploading into an existing one', async () => { + const { reporting } = await import('./xlsxFixture') + const { sent, store } = fakes({ draftName: 'Lab cohort 2026' }) + await store().put({ + file: new File([reporting('ABC001') as BlobPart], 'Lab_ABC001.xlsx'), protocolId: 'four-choice-reversal', userSub: 'user-1', + dandisets: { user: '000123', newName: 'Four-choice' }, + bids: { + config: { task: 'fourchoice', subjectId: { sheet: 'METADATA', label: 'Animal ID: (XXX001)' }, tables: [{ sheet: 'DISC', acq: 'discrimination', header: 'Trial' }] }, + protocol: { name: 'Four-choice' }, + }, + }) + const texts = await Promise.all(sent.map((b) => b.text())) + const description = texts.map((t) => { try { return JSON.parse(t) } catch { return null } }).find((j) => j?.BIDSVersion) + assert.equal(description.Name, 'Lab cohort 2026') +}) + +test('a re-upload merges participants.tsv with the draft\'s: earlier animals stay, the same animal takes the new row', async () => { + const { reporting } = await import('./xlsxFixture') + const upload = (opts: Parameters[0]) => { + const { calls, sent, store } = fakes(opts) + finalizedPaths.length = 0 + const put = store().put({ + file: new File([reporting('ABC001') as BlobPart], 'Lab_ABC001.xlsx'), protocolId: 'four-choice-reversal', userSub: 'user-1', + dandisets: { user: '000123' }, + bids: { + config: { task: 'fourchoice', subjectId: { sheet: 'METADATA', label: 'Animal ID: (XXX001)' }, sex: { sheet: 'METADATA', label: 'Sex (M/F)' }, tables: [{ sheet: 'DISC', acq: 'discrimination', header: 'Trial' }], participants: { species: 'mus musculus', fields: [] } }, + protocol: { name: 'Four-choice' }, + }, + }) + return { calls, put, contentOf: async (path: string) => sent[finalizedPaths.indexOf(path)].text() } + } + const { calls, put, contentOf } = upload({ draft: { + 'participants.tsv': 'participant_id\tspecies\tsex\nsub-ABC009\tmus musculus\tfemale\nsub-ABC001\tmus musculus\tfemale\n', + 'participants.json': '{ "extra": { "Description": "From an earlier upload." } }', + } }) + await put + assert.equal(await contentOf('participants.tsv'), 'participant_id\tspecies\tsex\nsub-ABC009\tmus musculus\tfemale\nsub-ABC001\tmus musculus\tM\n') + assert.deepEqual(JSON.parse(await contentOf('participants.json')).extra, { Description: 'From an earlier upload.' }) + // participants.tsv is read first for the Animal ID check; only the merged files are read back, the tables are replaced. + const reads = calls.filter((c) => c.startsWith('read:')) + assert.equal(reads[0], 'read:participants.tsv') + assert.deepEqual(reads.slice(1).sort(), ['read:participants.json', 'read:participants.tsv', 'read:task-fourchoice_acq-discrimination_beh.json']) + + // The draft's copy can't be read: stop, rather than overwrite the earlier animals. + const unreadable = upload({ draftUnreadable: true }) + await assert.rejects(unreadable.put, /download of participants\.tsv failed/) + assert.ok(!finalizedPaths.includes('participants.tsv')) + + // The same animal in other upper/lower case: stopped before anything is written. + const cased = upload({ draft: { 'participants.tsv': 'participant_id\tspecies\tsex\nsub-abc001\tmus musculus\tM\n' } }) + await assert.rejects(cased.put, /Animal ID ABC001 is already in this dandiset as abc001\. Write it abc001/) + assert.ok(!cased.calls.some((c) => c.startsWith('direct-init'))) +}) + +test('BIDS files are written a few at a time, never more than BIDS_WRITES_AT_ONCE', async () => { + const { store, writes } = fakes({ dedupDirect: true, slowFinalize: true }) + const two = { ...BIDS, config: { ...BIDS.config, tables: [...BIDS.config.tables, { sheet: 'REV', acq: 'reversal', header: 'Trial' }] } } + const written: string[] = [] + await store().put({ file: file(), protocolId: 'p', userSub: 'u', bids: two, dandisets: { user: '000123' }, + onBidsProgress: (n, total) => written.push(`${n}/${total}`) }) + assert.equal(writes.most, BIDS_WRITES_AT_ONCE) + // Progress still counts up one by one, whichever write finishes first. + assert.deepEqual(written, ['0/6', '1/6', '2/6', '3/6', '4/6', '5/6', '6/6']) +}) + +test('a failed BIDS write starts no new one; the running ones finish, then it fails; a retry writes only the rest', async () => { + // Six files, four at a time: the first fails while three others run; the last two never start. + const failing = 'sub-ABC001/ses-20260902/beh/sub-ABC001_ses-20260902_task-fourchoice_acq-discrimination_beh.tsv' + const two = { ...BIDS, config: { ...BIDS.config, sessionDate: { label: 'Date:' }, tables: [...BIDS.config.tables, { sheet: 'REV', acq: 'reversal', header: 'Trial' }] } } + const { store, writes } = fakes({ dedupDirect: true, slowFinalize: true, failFinalizeOf: failing }) + const checkpoints: Record[] = [] + const input = { file: file(), protocolId: 'p', userSub: 'u', bids: two, dandisets: { user: '000123' } } + finalizedPaths.length = 0 + await assert.rejects(store().put({ ...input, onCheckpoint: (c) => checkpoints.push(c as Record) }), /register failed/) + assert.equal(writes.now, 0, 'nothing still running once it fails') + assert.deepEqual(writes.most, BIDS_WRITES_AT_ONCE) + const done = checkpoints.at(-1)!.bidsDone as string[] + assert.equal(done.length, 3, 'the three running beside the failure finished') + assert.ok(!finalizedPaths.includes('dataset_description.json') && !finalizedPaths.includes('README.md'), 'no write started after the failure') + + const retry = fakes({ dedupDirect: true }) + finalizedPaths.length = 0 + await retry.store().put({ ...input, resume: checkpoints.at(-1) }) + // The upload itself is done; only the three BIDS files not yet written go up. + assert.deepEqual(finalizedPaths.sort(), [failing, 'README.md', 'dataset_description.json'].sort()) +}) diff --git a/applications/idp-arc/frontend/tests/unit/objectStore.test.ts b/applications/idp-arc/frontend/tests/unit/objectStore.test.ts index 599cf43..a3449f9 100644 --- a/applications/idp-arc/frontend/tests/unit/objectStore.test.ts +++ b/applications/idp-arc/frontend/tests/unit/objectStore.test.ts @@ -20,6 +20,6 @@ test('object key segments are path-safe: no traversal, no slashes, no spaces', ( test('without a bucket URL the upload fails with a message for the user, before anything is sent', async () => { const file = new File(['x'], 'animal_01.xlsx') - await assert.rejects(new PublicBucketObjectStore(undefined).put({ file, protocolId: 'p', userSub: 'u' }), + await assert.rejects(new PublicBucketObjectStore(undefined).put({ file, protocolId: 'p', userSub: 'u', bids: { config: { task: 't', subjectId: { sheet: 'S', label: 'L' }, tables: [] }, protocol: { name: 'P' } } }), (err: unknown) => err instanceof UserFacingError && err.message === UPLOADS_NOT_SET_UP && /VITE_UPLOAD_BUCKET_URL/.test(err.details ?? '')) }) diff --git a/applications/idp-arc/frontend/tests/unit/pathSafe.test.ts b/applications/idp-arc/frontend/tests/unit/pathSafe.test.ts new file mode 100644 index 0000000..b253ab3 --- /dev/null +++ b/applications/idp-arc/frontend/tests/unit/pathSafe.test.ts @@ -0,0 +1,17 @@ +// One DANDI asset path segment (core/pathSafe.ts). Run: yarn test:unit +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { pathSafe } from '../../src/core/pathSafe' + +test('runs of other characters become one dash, and none is left before the extension', () => { + assert.equal(pathSafe('four-choice-filled-3-animals-ABC001-003 -2-.zip'), 'four-choice-filled-3-animals-ABC001-003-2.zip') + assert.equal(pathSafe('Weight and Feeding log.xlsx'), 'Weight-and-Feeding-log.xlsx') + assert.equal(pathSafe('animal_01.xlsx'), 'animal_01.xlsx') + assert.equal(pathSafe('a@b/c.xlsx'), 'a-b-c.xlsx') +}) + +test('nothing usable gives "unknown"; dots and dashes at the ends are dropped', () => { + assert.equal(pathSafe('@@@'), 'unknown') + assert.equal(pathSafe('--.hidden--'), 'hidden') + assert.equal(pathSafe('four-choice-reversal'), 'four-choice-reversal') +}) diff --git a/applications/idp-arc/frontend/tests/unit/protocolDandisets.test.ts b/applications/idp-arc/frontend/tests/unit/protocolDandisets.test.ts index 921bf83..a24bd5e 100644 --- a/applications/idp-arc/frontend/tests/unit/protocolDandisets.test.ts +++ b/applications/idp-arc/frontend/tests/unit/protocolDandisets.test.ts @@ -20,7 +20,7 @@ test('the protocol and the workspace are relatedResource entries, alongside any assert.equal(readProtocolLink(linked), 'four-choice-reversal') assert.equal(readWorkspaceLink(linked, DEV), 42) const entries = linked.relatedResource as { identifier: string; schemaKey?: string }[] - assert.deepEqual(entries.map((r) => r.identifier), ['doi:10/x', 'idp-protocol:four-choice-reversal', `osb-workspace:${DEV}:42`]) + assert.deepEqual(entries.map((r) => r.identifier), ['doi:10/x', 'maabcd-protocol:four-choice-reversal', `osb-workspace:${DEV}:42`]) assert.ok(entries.slice(1).every((r) => r.schemaKey === 'Resource')) assert.equal(linked.name, 'Mine') }) @@ -66,6 +66,7 @@ function fakeEmber(metadata: Record, publishing: { return { version, status: s.status as VersionStatus, errors: s.errors ?? [], filesBeingChecked: s.filesBeingChecked ?? 0 } }, async publishDraft(_t, id) { calls.push(`publish:${id}`) }, + async readDraftFile() { return null }, async getLatestPublished() { const all = publishing.versions ?? [null] return all[Math.min(versionReads++, all.length - 1)] @@ -84,7 +85,7 @@ test('the protocol\'s dandisets come from one search for its link, with no metad const { uc, calls, drafts } = fakeEmber({ '000001': withProtocolLink({}, FOUR) }) assert.deepEqual(await uc.listForProtocol('four-choice-reversal'), [{ id: '000001', name: 'set 000001' }]) - assert.deepEqual(calls, ['list:idp-protocol:four-choice-reversal']) + assert.deepEqual(calls, ['list:maabcd-protocol:four-choice-reversal']) assert.deepEqual(drafts, []) }) diff --git a/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts b/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts index 2402017..1209e28 100644 --- a/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts +++ b/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts @@ -22,6 +22,7 @@ const FOUR_CHOICE = { repoZipUrl: 'https://codeload.github.com/maracbaylis/four-choice-example/zip/refs/heads/main', notebooksDir: 'notebooks', inputFormats: ['.xlsx', '.zip'], + bids: { task: 'fourchoice', subjectId: { sheet: 'METADATA', label: 'Animal ID: (XXX001)' }, tables: [{ sheet: 'DISC', acq: 'discrimination', header: 'Trial' }] }, } const auth = { getToken: async () => 'token', tokenParsed: { sub: 'user-1' } } const file = () => new File(['x'], 'animal_01.xlsx') @@ -274,7 +275,7 @@ test('a run that stops before any notebook (nothing listed) failed, and says so test('a protocol without a repository fails clearly', async () => { const f = fakes() - const last = (await run(f, { protocol: { id: 'open-field', name: 'Open field task' } })).pop()! + const last = (await run(f, { protocol: { id: 'open-field', name: 'Open field task', bids: FOUR_CHOICE.bids } })).pop()! assert.equal(last.phase, 'failed') assert.match(last.error ?? '', /isn't available yet/) }) @@ -334,11 +335,33 @@ test('an EMBER-DANDI upload gets the run\'s workspace recorded in its dandiset, const create = f.calls.findIndex((c) => c.startsWith('create:')) assert.equal(f.calls[create + 1], 'record:42') assert.deepEqual(seen.dandisets, { - user: '000123', newName: 'Four-choice reversal digging task (IDP)', maabcd: '000533', - protocol: { id: 'four-choice-reversal', name: 'Four-choice reversal digging task', url: 'https://github.com/maracbaylis/four-choice-example' }, + user: '000123', newName: 'Four-choice reversal digging task', maabcd: '000533', + protocol: { + id: 'four-choice-reversal', name: 'Four-choice reversal digging task', url: 'https://github.com/maracbaylis/four-choice-example', + description: FOUR_CHOICE.description, + }, }) }) +for (const [typed, expected] of [ + [' Cohort A, week 3 ', 'Cohort A, week 3'], + [' ', 'Four-choice reversal digging task'], + [undefined, 'Four-choice reversal digging task'], +] as const) { + test(`a new dandiset is named ${JSON.stringify(typed)} -> "${expected}"`, async () => { + const seen: { dandisets?: { newName?: string } } = {} + const store: IObjectStore = { + async put(input) { + seen.dandisets = input.dandisets + return { url: 'https://api-dandi.example.org/api/assets/a/download/', key: 'k', name: 'animal_01.xlsx', dandisetId: '000777' } + }, + } + await createRunProtocolUseCase(auth, fakes().api, store)( + { protocol: FOUR_CHOICE, file: file(), workspaceName: 'Four-choice', dandisetName: typed }, () => {}) + assert.equal(seen.dandisets?.newName, expected) + }) +} + test('with "Share with MAABCD" unticked, nothing goes to the protocol\'s MAABCD dandiset', async () => { const f = fakes() const seen: { dandisets?: { maabcd?: string } } = {} diff --git a/applications/idp-arc/frontend/tests/unit/xlsxFixture.ts b/applications/idp-arc/frontend/tests/unit/xlsxFixture.ts new file mode 100644 index 0000000..bc4d6cd --- /dev/null +++ b/applications/idp-arc/frontend/tests/unit/xlsxFixture.ts @@ -0,0 +1,66 @@ +// In-memory .xlsx workbooks for the unit tests (not a test file itself). +import { strToU8, zipSync } from 'fflate' + +export type Row = (string | number | null | { formula: string })[] + +/** A minimal .xlsx: strings go through the shared-string table, except `inline:` ones. */ +export function xlsx(sheets: Record): Uint8Array { + const shared: string[] = [] + const esc = (s: string) => s.replace(/&/g, '&').replace(/ String.fromCharCode(65 + i) + const files: Record = {} + const names = Object.keys(sheets) + names.forEach((name, n) => { + const rows = sheets[name].map((row, r) => `${row.map((v, c) => { + const ref = `${col(c)}${r + 1}` + if (v === null) return `` + if (typeof v === 'number') return `${v}` + if (typeof v === 'object') return `${esc(v.formula)}` + if (v.startsWith('inline:')) return `${esc(v.slice(7))}` + shared.push(v) + return `${shared.length - 1}` + }).join('')}`).join('') + files[`xl/worksheets/sheet${n + 1}.xml`] = strToU8(`${rows}`) + }) + files['xl/workbook.xml'] = strToU8(`${names.map((name, n) => + ``).join('')}`) + files['xl/_rels/workbook.xml.rels'] = strToU8(`${names.map((_, n) => + ``).join('')}`) + // The first shared string as rich-text runs, the way Excel writes formatted text. + files['xl/sharedStrings.xml'] = strToU8(`${shared.map((s, i) => i === 0 && s.length > 1 + ? `${esc(s.slice(0, 1))}${esc(s.slice(1))}` + : `${esc(s)}`).join('')}`) + return zipSync(files) +} + +/** A four-choice Reporting Sheet: METADATA, and DISC and REV with a date, a header row and two trials. */ +export function reporting(id: string | null, sex: string | null = 'M'): Uint8Array { + // One date written out, one as Excel stores dates (days since 1899-12-30): 2026-09-03. + const trials = (rewarded: string, date: string | number): Row[] => [ + ['SECTION 6 — Testing'], + ['Date:', date, 'Start time:', '09:02'], + ['Trial Type:', 'Discrimination', null, 'Rewarded:', rewarded], + ['Trial', 'Ramekin Order\n(NW, NE, SW, SE)', 'Correct?', 'Latency (s)', 'Notes'], + [1, 'ABCD', { formula: 'IF(B5="A","Correct","Incorrect")' }, 29, null], + [2, 'inline:BCDA', { formula: 'IF(B6="A","Correct","Incorrect")' }, 3.5, 'tab\there\r\nnext & '], + [3, null, null, null, null], // numbered in the template, never filled + ] + return xlsx({ + METADATA: [['SECTION 1 — Animal Info'], ['Animal ID: (XXX001)', id, 'Strain', 'C57BL/6'], ['Sex (M/F)', sex]], + DISC: trials('Anise', '2026-09-02'), + REV: trials('Cinnamon', 46268), + }) +} + +/** `zip` with `name`'s compression method set to one nothing can decompress. */ +export function undecodable(zip: Uint8Array, name: string): Uint8Array { + const out = zip.slice() + const view = new DataView(out.buffer) + const encoded = strToU8(name) + for (let i = 0; i < out.length - encoded.length; i++) { + if (!encoded.every((b, j) => out[i + j] === b)) continue + if (i >= 30 && view.getUint32(i - 30, true) === 0x04034b50) view.setUint16(i - 30 + 8, 99, true) + if (i >= 46 && view.getUint32(i - 46, true) === 0x02014b50) view.setUint16(i - 46 + 10, 99, true) + } + return out +} diff --git a/applications/idp-arc/frontend/tests/unit/zipStream.test.ts b/applications/idp-arc/frontend/tests/unit/zipStream.test.ts new file mode 100644 index 0000000..93b27e6 --- /dev/null +++ b/applications/idp-arc/frontend/tests/unit/zipStream.test.ts @@ -0,0 +1,84 @@ +// Zips read and written without loading them into memory (core/zipStream.ts). Run: yarn test:unit +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { strFromU8, strToU8, unzipSync, zipSync, Zip, ZipDeflate } from 'fflate' +import { readZipEntries, readZipIndex, withEntry, zipOf } from '../../src/core/zipStream' +import { undecodable } from './xlsxFixture' + +const DATE = new Date(2026, 8, 2, 10, 30, 4) +const blob = (bytes: Uint8Array) => new Blob([bytes as BlobPart]) +const bytesOf = async (b: Blob) => new Uint8Array(await b.arrayBuffer()) + +/** A zip written as a stream, the way macOS Finder writes them: each entry's sizes come after its data. */ +function streamedZip(files: Record): Uint8Array { + const chunks: Uint8Array[] = [] + const zip = new Zip((error, data) => { if (error) throw error; chunks.push(data) }) + for (const [name, bytes] of Object.entries(files)) { + const entry = new ZipDeflate(name, { level: 6 }) + zip.add(entry) + entry.push(bytes, true) + } + zip.end() + return new Uint8Array(chunks.flatMap((c) => [...c])) +} + +test('readZipEntries returns only the entries asked for, decompressed', async () => { + const zip = zipSync({ 'c/a.xlsx': strToU8('workbook'), 'c/p.pdf': strToU8('pdf'), 'c/v.mp4': new Uint8Array(5000) }) + const kept = await readZipEntries(blob(zip), (name) => !name.endsWith('.mp4')) + assert.deepEqual(kept.map((e) => [e.name, strFromU8(e.bytes)]), [['c/a.xlsx', 'workbook'], ['c/p.pdf', 'pdf']]) +}) + +test('an entry not asked for is never decompressed, so even one no decoder reads passes through', async () => { + const zip = undecodable(zipSync({ 'v.mp4': [new Uint8Array(5000), { level: 0 }], 'a.xlsx': strToU8('workbook') }), 'v.mp4') + assert.deepEqual((await readZipEntries(blob(zip), (n) => n === 'a.xlsx')).map((e) => e.name), ['a.xlsx']) + await assert.rejects(readZipEntries(blob(zip), () => true)) +}) + +test('a zip written as a stream (sizes after each entry, as macOS Finder writes) is read', async () => { + const zip = streamedZip({ 'v.mp4': new Uint8Array(70000).map((_, i) => i * 7), 'a.xlsx': strToU8('workbook') }) + assert.ok(new DataView(zip.buffer).getUint16(6, true) & 8, 'the fixture has data descriptors') + const kept = await readZipEntries(blob(zip), (n) => n === 'a.xlsx') + assert.equal(strFromU8(kept[0].bytes), 'workbook') + assert.deepEqual((await readZipIndex(blob(zip)))?.names, ['v.mp4', 'a.xlsx']) +}) + +test('readZipEntries throws on something that is not a zip', async () => { + await assert.rejects(readZipEntries(blob(strToU8('not a zip')), () => true)) +}) + +test('readZipIndex lists the names, and is null for anything that is not a readable zip', async () => { + const zip = zipSync({ 'a/': new Uint8Array(), 'a/b.txt': strToU8('b') }) + assert.deepEqual((await readZipIndex(blob(zip)))?.names, ['a/', 'a/b.txt']) + assert.equal(await readZipIndex(blob(strToU8('not a zip at all, but long enough to scan'))), null) + assert.equal(await readZipIndex(blob(zip.slice(0, zip.length - 3))), null) +}) + +test('withEntry adds a file to a zip, comment kept; the result reads with fflate', async () => { + const zip = zipSync({ 'a.txt': strToU8('a') }, { comment: 'the lab\'s comment' } as never) + const index = (await readZipIndex(blob(zip)))! + const out = await bytesOf(withEntry(blob(zip), index, { name: 'README.md', data: strToU8('hello'), date: DATE })) + const entries = unzipSync(out) + assert.deepEqual(Object.keys(entries), ['README.md', 'a.txt']) + assert.equal(strFromU8(entries['README.md']), 'hello') + assert.deepEqual((await readZipIndex(blob(out)))?.comment, index.comment) +}) + +test('past 65,535 entries the zip gets ZIP64 records, and still reads', async () => { + const files: Record = {} + for (let i = 0; i < 65535; i++) files[`f${i}`] = new Uint8Array(0) + const zip = zipSync(files, { level: 0 }) + const index = (await readZipIndex(blob(zip)))! + assert.equal(index.count, 65535) + const out = withEntry(blob(zip), index, { name: 'README.md', data: strToU8('hello'), date: DATE }) + const reread = (await readZipIndex(out))! + assert.equal(reread.count, 65536) + assert.equal(reread.names[0], 'README.md') + assert.equal(strFromU8(unzipSync(await bytesOf(out), { filter: (f) => f.name === 'README.md' })['README.md']), 'hello') +}) + +test('zipOf stores each file as it is, a Blob read only for its checksum', async () => { + const out = await zipOf([{ name: 'README.md', data: strToU8('hello'), date: DATE }, { name: 'ünïcode name.xlsx', data: blob(strToU8('sheet')), date: DATE }]) + const entries = unzipSync(await bytesOf(out)) + assert.deepEqual(Object.keys(entries), ['README.md', 'ünïcode name.xlsx']) + assert.equal(strFromU8(entries['ünïcode name.xlsx']), 'sheet') +}) diff --git a/applications/idp-arc/frontend/vite.config.ts b/applications/idp-arc/frontend/vite.config.ts index 29c3518..eb4d3f0 100644 --- a/applications/idp-arc/frontend/vite.config.ts +++ b/applications/idp-arc/frontend/vite.config.ts @@ -4,7 +4,7 @@ import path from 'path' import fs from 'node:fs' import http from 'node:http' import https from 'node:https' -import { EMBER_API_ORIGIN } from './src/infra/emberUrls' +import { dandiInstance } from './src/core/dandiInstances' // Must use loadEnv(), not process.env — Vite doesn't load .env into process.env for this // file, so process.env here silently falls back to the production domain. @@ -13,6 +13,12 @@ const OSB_DOMAIN = env.VITE_OSB_BASE_DOMAIN || 'v2dev.opensourcebrain.org' const OSB_SCHEME = env.VITE_OSB_PROTOCOL || 'https' const OSB_WEB_ORIGIN = `${OSB_SCHEME}://www.${OSB_DOMAIN}` +// Throws at start for a VITE_DANDI_INSTANCE that isn't one of the three. +const DANDI_INSTANCE = dandiInstance(env.VITE_DANDI_INSTANCE) +const DANDI_API_ORIGIN = DANDI_INSTANCE.api +/** Dev server on a sandbox only (no OAuth app for us there): signs every proxied DANDI call with this + * key instead of the user's token. Not VITE_-prefixed, so it never reaches the bundle. */ +const DANDI_SANDBOX_API_KEY = DANDI_INSTANCE.name.endsWith('-sandbox') ? env.DANDI_SANDBOX_API_KEY?.trim() ?? '' : '' /** * Optional HTTPS for the dev server: EMBER-DANDI's OAuth application only accepts https:// * redirect URIs, so its sign-in needs https://localhost:5173 (registered as @@ -33,6 +39,7 @@ const devHttps = loadDevHttpsCerts() // eslint-disable-next-line no-console console.log(`[vite] proxying OSB -> ${OSB_WEB_ORIGIN}`) +console.log(`[vite] proxying DANDI -> ${DANDI_API_ORIGIN}${DANDI_SANDBOX_API_KEY ? ' (signed with DANDI_SANDBOX_API_KEY, no OAuth)' : ''}`) // IPv4 lookups and reused connections for every proxied call. macOS resolves `*.local` names // (local minikube: `osb.local`) through multicast DNS first, and the IPv6 query only falls back @@ -41,8 +48,11 @@ console.log(`[vite] proxying OSB -> ${OSB_WEB_ORIGIN}`) const agentOptions = { keepAlive: true, family: 4 } const upstreamAgent = OSB_SCHEME === 'https' ? new https.Agent(agentOptions) : new http.Agent(agentOptions) -export default defineConfig({ +export default defineConfig(({ command }) => ({ plugins: [react()], + define: { + __DANDI_SANDBOX_API_KEY__: JSON.stringify(command === 'serve' && !!DANDI_SANDBOX_API_KEY), + }, build: { sourcemap: true, outDir: 'dist', @@ -65,9 +75,12 @@ export default defineConfig({ }, // EMBER's token reply has no CORS headers. Only what the app calls, as nginx (default.conf). '^/ember-proxy/(oauth/token/|api/)': { - target: EMBER_API_ORIGIN, + target: DANDI_API_ORIGIN, changeOrigin: true, rewrite: (path) => path.replace(/^\/ember-proxy/, ''), + ...(DANDI_SANDBOX_API_KEY ? { + configure: (proxy) => proxy.on('proxyReq', (req) => req.setHeader('Authorization', `token ${DANDI_SANDBOX_API_KEY}`)), + } : {}), }, }, }, @@ -76,4 +89,4 @@ export default defineConfig({ '@': path.resolve(__dirname, './src'), }, } -}) +})) diff --git a/applications/idp-arc/frontend/yarn.lock b/applications/idp-arc/frontend/yarn.lock index ecd6b8e..caf3f2d 100644 --- a/applications/idp-arc/frontend/yarn.lock +++ b/applications/idp-arc/frontend/yarn.lock @@ -1311,6 +1311,11 @@ fdir@^6.5.0: resolved "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz" integrity sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg== +fflate@^0.8.2: + version "0.8.2" + resolved "https://registry.yarnpkg.com/fflate/-/fflate-0.8.2.tgz#fc8631f5347812ad6028bbe4a2308b2792aa1dea" + integrity sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A== + file-entry-cache@^8.0.0: version "8.0.0" resolved "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz"