All connectors

bioRxiv and medRxiv

Official

bioRxiv and medRxiv

Let agents search preprints, read abstracts and every version, find journal publications, and download available PDFs. No account is required; access is read-only.

Preprints have not completed peer review. Automated PDF downloads may be blocked; open the PDF link in your browser when needed.

Search uses Europe PMC and may lag a day; other data comes from the provider API. Respect each preprint's licence and Europe PMC's attribution terms. This connector is not affiliated with the providers.

Add the connector.

Setup instructions

Add bioRxiv and medRxiv

Select Add connection in Houston. No account, API key or settings are required.

Automated PDF downloads may be blocked, especially by medRxiv. Open the PDF link in your browser if a download fails.

Advanced

Search uses Europe PMC and may lag a day; date-range listings use the servers directly. Check which server holds a DOI when a preprint is missing.

Provider API · Search syntax.

Files

  • connector.luau
    -- bioRxiv and medRxiv API (https://api.biorxiv.org), Europe PMC search and the servers' PDF files, public and read-only. Arguments and results keep the providers' native field names.
    type Options = {[string]: any}
    type Server = {name: string, site: string, categories: {string}}
    
    local API = "https://api.biorxiv.org"
    local EUROPE_PMC = "https://www.ebi.ac.uk/europepmc/webservices/rest/search"
    -- Houston ends a call after 30 s and the sandbox has no clock, so each request gets a fixed share of 27 s as
    -- {total, body}. The bioRxiv API prepares a whole page before its headers (0.3 to 3.5 s, up to 8 s when busy) and
    -- then sends its 70 to 230 KB within 1.5 s; it serves about three requests at a time. A call reading one answer or
    -- file gives the body 19 s, enough for the slowest Europe PMC answers and PDFs. A date range gives its first page 15 s
    -- whatever the limit, then reads up to three more pages at once in the remaining 12 s.
    local MAX_BYTES = 4 * 1024 * 1024
    local CALL, FIRST = table.freeze({27000, 19000}), table.freeze({15000, 7000})
    local LATER = table.freeze({CALL[1] - FIRST[1], 3000})
    local MAX_PAGES = 1 + 3
    -- The API serves fixed pages: 30 preprints, or 100 published-article links.
    local DETAILS_PAGE, PUBS_PAGE = 30, 100
    local MAX_CURSOR = 2 ^ 31 - 1
    local MAX_QUERY, DEFAULT_SEARCH = 2000, 25
    -- Upper bounds of one Europe PMC record's average size in bytes, which cap limit within the byte budget. 250 highly
    -- cited core records with large author lists took 2.75 MB (11 KB each, up to 72 KB) and 17.7 s; lite records stay under
    -- 1.4 KB. Europe PMC serves at most 1,000 records a page.
    local RECORD_BYTES: {[string]: number} = table.freeze({core = 40 * 1024, lite = 4 * 1024})
    local MAX_SEARCH: {[string]: number} = table.freeze({core = math.min(1000, MAX_BYTES // RECORD_BYTES.core),
    	lite = math.min(1000, MAX_BYTES // RECORD_BYTES.lite)})
    local SORTS = table.freeze({"relevance", "FIRST_PDATE_D desc", "FIRST_PDATE_D asc", "CITED desc"})
    local RESULT_TYPES = table.freeze({"core", "lite"})
    
    local function names(list: string): {string}
    	return table.freeze(string.split(list, ", "))
    end
    
    local SERVERS: {[string]: Server} = table.freeze({
    	biorxiv = {name = "bioRxiv", site = "https://www.biorxiv.org", categories = names("animal behavior and cognition, "
    		.. "biochemistry, bioengineering, bioinformatics, biophysics, cancer biology, cell biology, developmental biology, "
    		.. "ecology, evolutionary biology, genetics, genomics, immunology, microbiology, molecular biology, neuroscience, "
    		.. "paleontology, pathology, pharmacology and toxicology, physiology, plant biology, "
    		.. "scientific communication and education, synthetic biology, systems biology, zoology")},
    	medrxiv = {name = "medRxiv", site = "https://www.medrxiv.org", categories = names("addiction medicine, "
    		.. "allergy and immunology, anesthesia, cardiovascular medicine, dentistry and oral medicine, dermatology, "
    		.. "emergency medicine, endocrinology, epidemiology, forensic medicine, gastroenterology, "
    		.. "genetic and genomic medicine, geriatric medicine, health economics, health informatics, health policy, "
    		.. "health systems and quality improvement, hematology, hiv aids, infectious diseases, "
    		.. "intensive care and critical care medicine, medical education, medical ethics, nephrology, neurology, nursing, "
    		.. "nutrition, obstetrics and gynecology, occupational and environmental health, oncology, ophthalmology, "
    		.. "orthopedics, otolaryngology, pain medicine, palliative medicine, pathology, pediatrics, "
    		.. "pharmacology and therapeutics, primary care research, psychiatry and clinical psychology, "
    		.. "public and global health, radiology and imaging, rehabilitation medicine and physical therapy, "
    		.. "respiratory medicine, rheumatology, sexual and reproductive health, sports medicine, surgery, toxicology, "
    		.. "transplantation, urology")},
    } :: {[string]: Server})
    
    local function finite(value: any): boolean
    	return type(value) == "number" and value == value and math.abs(value) < 2 ^ 53
    end
    
    local function integer(value: any, field: string, minimum: number, maximum: number): number
    	if not (finite(value) and value % 1 == 0 and value >= minimum and value <= maximum) then
    		error(field .. " must be an integer from " .. string.format("%d", minimum) .. " to " .. string.format("%d", maximum), 0)
    	end
    	return value
    end
    
    local function choice(value: any, field: string, values: {string}): string
    	if not (type(value) == "string" and table.find(values, value)) then error(field .. " must be one of " .. table.concat(values, ", "), 0) end
    	return value
    end
    
    local function options(value: any, operation: string): Options
    	if type(value) ~= "table" then error(operation .. " takes one options table", 0) end
    	return table.clone(value :: Options)
    end
    
    local function noneLeft(args: Options, operation: string)
    	local unknown = next(args)
    	if unknown ~= nil then error(operation .. " received an unknown option " .. string.sub(tostring(unknown), 1, 64), 0) end
    end
    
    local function take(args: Options, field: string): any
    	local value = args[field]
    	args[field] = nil
    	return value
    end
    
    -- Takes an option, or its default when it is absent; false is a value, so it is rejected later.
    local function optional(args: Options, field: string, default: any): any
    	local value = take(args, field)
    	return if value == nil then default else value
    end
    
    local function server(args: Options): (string, Server)
    	local key = take(args, "server")
    	assert(type(key) == "string" and SERVERS[key], "server must be biorxiv or medrxiv")
    	return key, SERVERS[key]
    end
    
    -- A preprint DOI is 10.1101/ or 10.64898/ followed by digits and dots, such as 10.1101/2025.03.20.644356.
    local function preprintDoi(value: any): string?
    	local prefix, suffix = string.match(if type(value) == "string" then value else "", "^10%.(%d+)/(%d[%d%.]*)$")
    	return if (prefix == "1101" or prefix == "64898") and #(suffix :: string) <= 40 and string.sub(suffix :: string, -1) ~= "."
    		then value else nil
    end
    
    local function doi(value: any): string
    	local id = preprintDoi(value)
    	if not id then
    		error("doi must be a bare bioRxiv or medRxiv DOI such as 10.1101/339747 or 10.64898/2026.10.15.759504, without a "
    			.. "version, doi: or https://doi.org/", 0)
    	end
    	return id
    end
    
    local DAYS = table.freeze({31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31})
    
    -- A real YYYY-MM-DD date; the API answers other dates with an error or nothing.
    local function date(value: any, field: string): string
    	local y, m, d = string.match(if type(value) == "string" then value else "", "^(%d%d%d%d)%-(%d%d)%-(%d%d)$")
    	local year, month, day = tonumber(y), tonumber(m), tonumber(d)
    	local leap = year and year % 4 == 0 and (year % 100 ~= 0 or year % 400 == 0)
    	local days = if month and month >= 1 and month <= 12 then DAYS[month] + (if month == 2 and leap then 1 else 0) else nil
    	if not (year and days and day and day >= 1 and day <= days) then error(field .. " must be a date such as 2025-03-21", 0) end
    	return value
    end
    
    local function range(args: Options): (string, string)
    	local from, to = take(args, "from"), take(args, "to")
    	assert(from ~= nil and to ~= nil, "from and to go together")
    	assert(date(from, "from") <= date(to, "to"), "from must not be after to")
    	return from, to
    end
    
    local function errorCode(err: any): any
    	return if type(err) == "table" then err.code else nil
    end
    
    local function fail(operation: string, status: number?, retryable: boolean, message: string): never
    	return houston.fail({operation = operation, layer = "upstream", upstream_status = status, retryable = retryable,
    		message = message})
    end
    
    local function seconds(ms: number): string
    	return string.format("%g", ms / 1000) .. " s"
    end
    
    -- houston.fail repairs a character split by the cut.
    local function tidy(message: string): string
    	return string.sub(string.match(string.gsub(message, "%s+", " "), "^ ?(.-) ?$") :: string, 1, 300)
    end
    
    -- Europe PMC reports errors as {errCode, errMsg}; other error bodies, such as HTML or Cloudflare pages, are never shown.
    local function failure(operation: string, provider: string, response: HttpResponse, time: {number}, hint: string?): never
    	local status = response.statusCode
    	local detail = ""
    	if status >= 300 and status < 400 then
    		response.body:close()
    		detail = "unexpected redirect"
    	else
    		-- An error body that stalls or breaks counts as empty.
    		local read, prefix = pcall(function() return await(response.body:readPrefix(4096), time[2]) end)
    		-- readPrefix closes the body; after a failed read, close it explicitly.
    		if not read then pcall(function() response.body:close() end) end
    		if not read and errorCode(prefix) == "cancelled" then error(prefix, 0) end
    		local ok, decoded = false, nil
    		if read and string.match(prefix, "^%s*{") then ok, decoded = pcall(json.decode, prefix) end
    		if ok and type(decoded) == "table" and type(decoded.errMsg) == "string" then detail = tidy(decoded.errMsg) end
    	end
    	local message = provider .. " HTTP " .. tostring(status) .. (if detail == "" then "" else ": " .. detail)
    	local retry = response.headers["retry-after"]
    	if (status == 429 or status == 503) and retry and retry[1] then
    		-- Retry-After is either delay seconds or an HTTP date.
    		local value = string.sub(retry[1], 1, 32)
    		message ..= "; retry after " .. value .. (if string.match(value, "^%d+$") then "s" else "")
    	end
    	-- Input is validated first, so 4xx answers other than 429 are final.
    	return fail(operation, status, status == 429 or status >= 500, message .. (if hint then hint else ""))
    end
    
    -- Sends a GET whose headers must arrive within time[1] - time[2].
    local function send(operation: string, provider: string, target: string, accept: string, time: {number}): HttpResponse
    	local sent, response = pcall(function()
    		return await(http.request({method = "GET", url = target, headers = {Accept = {accept}}, timeoutMs = time[1] - time[2]}))
    	end)
    	if not sent then
    		if errorCode(response) ~= "timeout" then error(response, 0) end
    		fail(operation, nil, true, provider .. " did not answer within " .. seconds(time[1] - time[2]) .. "; retry")
    	end
    	return response
    end
    
    -- Decodes a JSON object; the anchored check is cheap, so a large page that is not JSON is never decoded.
    local function decode(operation: string, provider: string, raw: string): any
    	local ok, value = false, nil
    	if string.match(raw, "^%s*{") then ok, value = pcall(json.decode, raw) end
    	if not ok or type(value) ~= "table" then fail(operation, 200, false, provider .. " returned an invalid JSON object") end
    	return value
    end
    
    -- Reads and decodes a JSON object of at most budget bytes; tooMuch says why a smaller answer cannot be had.
    local function fetch(operation: string, provider: string, target: string, time: {number}, budget: number, tooMuch: string,
    	hint: string?): (any, number)
    	local response = send(operation, provider, target, "application/json", time)
    	if response.statusCode ~= 200 then failure(operation, provider, response, time, hint) end
    	local read, raw = pcall(function() return await(response.body:readAll(budget), time[2]) end)
    	if not read then
    		local code = errorCode(raw)
    		if code == "limit_exceeded" then
    			fail(operation, 200, false, provider .. " returned more data than one call can hold; " .. tooMuch)
    		elseif code == "timeout" then
    			fail(operation, 200, true, provider .. " did not finish sending its answer within " .. seconds(time[2]) .. "; retry")
    		elseif code == "cancelled" then
    			error(raw, 0)
    		end
    		local detail = if type(raw) == "table" and type(raw.message) == "string" then raw.message else tostring(raw)
    		fail(operation, 200, true, provider .. " response failed: " .. string.sub(detail, 1, 300))
    	end
    	return decode(operation, provider, raw), #raw
    end
    
    -- Statuses the API reports, always with HTTP 200, for input it rejects.
    local REJECTIONS = table.freeze({"must be", "not recognized", "not recognizable", "not found"})
    
    -- Reads an API answer: {status = "ok", collection} on success, or a status text such as "no posts found". Returns the
    -- collection and message, or nil when the status is one of empty's answers for no rows.
    local function apiAnswer(operation: string, body: any, empty: (string) -> boolean): (any, any)
    	local message = if type(body.messages) == "table" then body.messages[1] else nil
    	local status = if type(message) == "table" then message.status else nil
    	if type(status) ~= "string" or type(body.collection) ~= "table" then
    		fail(operation, 200, false, "bioRxiv API returned an unexpected answer")
    	end
    	if status == "ok" then return body.collection, message end
    	if empty(status) then return nil, message end
    	local lower = string.lower(status)
    	local rejected = false
    	for _, phrase in REJECTIONS do rejected = rejected or string.find(lower, phrase, 1, true) ~= nil end
    	return fail(operation, 200, not rejected, "bioRxiv API: " .. tidy(status))
    end
    
    local function apiPage(operation: string, target: string, time: {number}, empty: (string) -> boolean, tooMuch: string): (any, any, number)
    	local body, bytes = fetch(operation, "bioRxiv API", target, time, MAX_BYTES, tooMuch)
    	local rows, message = apiAnswer(operation, body, empty)
    	return rows, message, bytes
    end
    
    local function pdfUrl(site: string, id: string, version: string): string
    	return site .. "/content/" .. id .. "v" .. version .. ".full.pdf"
    end
    
    -- Copies a decoded list into a JSON array, so an empty one still encodes as [].
    local function array(list: any): any
    	local out = json.decode("[]")
    	for _, item in list do table.insert(out, item) end
    	return out
    end
    
    -- Adds each version's PDF address, which the API does not return.
    local function withPdf(rows: any, site: string): any
    	for _, row in rows do
    		if type(row) == "table" and preprintDoi(row.doi) and type(row.version) == "string" and string.match(row.version, "^%d+$") then
    			row.pdf_url = pdfUrl(site, row.doi, row.version)
    		end
    	end
    	return rows
    end
    
    local function noPosts(status: string): boolean
    	return status == "no posts found"
    end
    
    -- Reads up to pages later pages at once, from offset start, and returns their answers in order until the first that
    -- fails. They share the time and the bytes left: each request's own timeout bounds its headers, and the bodies get one
    -- deadline together.
    local function laterPages(operation: string, target: (number) -> string, start: number, size: number, pages: number,
    	budget: number): {any}
    	local requests: {{any}} = {}
    	for page = 1, pages do
    		requests[page] = {pcall(function()
    			return http.request({method = "GET", url = target(start + (page - 1) * size),
    				headers = {Accept = {"application/json"}}, timeoutMs = LATER[1] - LATER[2]})
    		end)}
    	end
    	-- Every operation is observed, so no failure goes unhandled; only the leading run of 200 answers is read.
    	local responses: {HttpResponse} = {}
    	for page = 1, pages do
    		local ok, response = requests[page][1], requests[page][2]
    		if ok then ok, response = pcall(await, response) end
    		if ok and response.statusCode == 200 and #responses == page - 1 then
    			table.insert(responses, response)
    		elseif ok then
    			response.body:close()
    		elseif errorCode(response) == "cancelled" then
    			error(response, 0)
    		end
    	end
    	local reads: {any} = {}
    	-- Reads start only while every earlier page started; the bodies after a failure are closed unread.
    	for page, response in responses do
    		local started, read = false, nil
    		if #reads == page - 1 then
    			started, read = pcall(function() return response.body:readAll(budget // #responses) end)
    		end
    		if started then table.insert(reads, read) else pcall(function() response.body:close() end) end
    	end
    	if #reads > 0 then
    		local ok, err = pcall(awaitAll, reads, LATER[2])
    		if not ok and errorCode(err) == "cancelled" then error(err, 0) end
    	end
    	local answers: {any} = {}
    	for page = 1, #reads do
    		-- A zero wait returns a settled read and cancels one still running.
    		local ok, raw = pcall(await, reads[page], 0)
    		local valid, body = false, nil
    		if ok then valid, body = pcall(decode, operation, "bioRxiv API", raw) end
    		if valid and #answers == page - 1 then table.insert(answers, body) end
    	end
    	return answers
    end
    
    -- Reads a date range from cursor within limit rows, the byte budget and the call time. The first page gets the same
    -- time whatever the limit, so asking for more rows never fails a call that one page would complete; the rest are read
    -- at once in the time left, and a failure among them returns the rows so far with next_cursor.
    local function collect(operation: string, args: Options, path: string, query: string, size: number, site: string?): Options
    	local cursor = integer(optional(args, "cursor", 0), "cursor", 0, MAX_CURSOR)
    	local limit = integer(optional(args, "limit", size), "limit", 1, size * MAX_PAGES)
    	noneLeft(args, operation)
    	local function target(offset: number): string
    		return API .. path .. "/" .. string.format("%d", offset) .. query
    	end
    	local rows = json.decode("[]")
    	local result: Options = {collection = rows}
    	local found, message, used = apiPage(operation, target(cursor), FIRST, noPosts,
    		"the API's page of " .. tostring(size) .. " is too large for one call")
    	-- No posts: the range is empty, or cursor is at or past its end, and the API reports no total.
    	if found == nil then return result end
    	local total = tonumber(message.total) or math.huge
    	if not finite(total) then fail(operation, 200, false, "bioRxiv API returned a page without its total") end
    	result.total = total
    	local fresh = tonumber(message.count_new_papers)
    	if finite(fresh) then result.count_new_papers = fresh end
    	-- Adds a page's rows up to limit and tells whether the range goes on.
    	local function add(page: any): boolean
    		for _, row in page do
    			if #rows >= limit then break end
    			table.insert(rows, row)
    		end
    		return #page > 0
    	end
    	local going = add(found)
    	local start = cursor + #rows
    	if going and #rows < limit and start < total then
    		local pages = math.min(MAX_PAGES - 1, math.ceil(math.min(limit - #rows, total - start) / size))
    		for _, body in laterPages(operation, target, start, size, pages, MAX_BYTES - used) do
    			local valid, later, reported = pcall(apiAnswer, operation, body, noPosts)
    			if not valid or (later and not finite(tonumber(reported.total))) then break end
    			going = later ~= nil and add(later)
    			if not going then break end
    		end
    	end
    	if site then withPdf(rows, site) end
    	if going and cursor + #rows < total then result.next_cursor = cursor + #rows end
    	return result
    end
    
    local function category(args: Options, entry: Server): string
    	local value = take(args, "category")
    	if value == nil then return "" end
    	local name = if type(value) == "string" then string.gsub(string.lower(value), "_", " ") else ""
    	if not table.find(entry.categories, name) then
    		error("category must be one of the " .. entry.name .. " categories: " .. table.concat(entry.categories, ", "), 0)
    	end
    	return "?category=" .. string.gsub(name, " ", "_")
    end
    
    -- A ROR ID's last 9 characters: 0, six lowercase letters or digits, and a two-digit checksum.
    local function funder(value: any): string
    	local id = if type(value) == "string" then string.match(value, "^https://ror%.org/(.*)$") or value else ""
    	assert(string.match(id, "^0[%l%d][%l%d][%l%d][%l%d][%l%d][%l%d]%d%d$"),
    		"funder must be a ROR ID such as 00k4n6c32 or https://ror.org/00k4n6c32")
    	return id
    end
    
    local function listPreprints(input: any): Options
    	local args = options(input, "listPreprints")
    	local key, entry = server(args)
    	local from, to = range(args)
    	local query = "/json" .. category(args, entry)
    	local ror = take(args, "funder")
    	local path = if ror == nil then "/details/" .. key .. "/" .. from .. "/" .. to
    		else "/funder/" .. key .. "/" .. from .. "/" .. to .. "/" .. funder(ror)
    	return collect("listPreprints", args, path, query, DETAILS_PAGE, entry.site)
    end
    
    local function getPreprint(input: any): Options
    	local args = options(input, "getPreprint")
    	local key, entry = server(args)
    	local id = doi(take(args, "doi"))
    	noneLeft(args, "getPreprint")
    	local rows = apiPage("getPreprint", API .. "/details/" .. key .. "/" .. id .. "/na/json", CALL, noPosts,
    		"this preprint's versions are too large for one call")
    	if rows == nil then
    		fail("getPreprint", 200, false, entry.name .. " has no preprint with DOI " .. id
    			.. "; check the server, since bioRxiv and medRxiv DOIs share the 10.1101 prefix")
    	end
    	return {collection = withPdf(array(rows), entry.site)}
    end
    
    -- A DOI with one slash, such as 10.1371/journal.pone.0256482 or 10.1016/S0140-6736(20)30183-5, as a path whose suffix
    -- is URL-encoded. The API reads the DOI from two path segments, so it cannot look up a suffix containing a slash.
    local function anyDoi(value: any): string
    	local prefix, suffix = string.match(if type(value) == "string" and #value <= 200 then value else "", "^(10%.%d%d%d%d+)/([%w%-%._;:()<>%[%]+]+)$")
    	if not prefix or string.match(suffix :: string, "^%.+$") then
    		error("doi must be a bare DOI with one slash, such as 10.1101/339747 or 10.1016/S0140-6736(20)30183-5; the API cannot "
    			.. "look up DOIs with several slashes", 0)
    	end
    	return prefix .. "/" .. url.encode(suffix :: string)
    end
    
    -- "no articles found for published version of ..." (a preprint not yet published) and "Preprint for DOI ... not found"
    -- (an article without a preprint) are both answers without a link.
    local function unlinked(status: string): boolean
    	return string.find(status, "^no articles found") ~= nil or string.find(status, "^Preprint for DOI .* not found$") ~= nil
    end
    
    local function getPublication(input: any): Options
    	local args = options(input, "getPublication")
    	local key = server(args)
    	local id = anyDoi(take(args, "doi"))
    	noneLeft(args, "getPublication")
    	local rows = apiPage("getPublication", API .. "/pubs/" .. key .. "/" .. id .. "/na/json", CALL, unlinked,
    		"this link is too large for one call")
    	return {collection = if rows then array(rows) else json.decode("[]")}
    end
    
    local function listPublications(input: any): Options
    	local args = options(input, "listPublications")
    	local key = server(args)
    	local from, to = range(args)
    	return collect("listPublications", args, "/pubs/" .. key .. "/" .. from .. "/" .. to, "", PUBS_PAGE, nil)
    end
    
    -- Checks that a query's parentheses and quotes are balanced, so it cannot escape the preprint filter around it.
    local function balanced(query: string): boolean
    	local depth, quoted, escaped = 0, false, false
    	for index = 1, #query do
    		local char = string.sub(query, index, index)
    		if escaped then
    			escaped = false
    		elseif char == "\\" then
    			escaped = true
    		elseif char == '"' then
    			quoted = not quoted
    		elseif not quoted and char == "(" then
    			depth += 1
    		elseif not quoted and char == ")" then
    			depth -= 1
    			if depth < 0 then return false end
    		end
    	end
    	return depth == 0 and not quoted and not escaped
    end
    
    local function searchPreprints(input: any): Options
    	local args = options(input, "searchPreprints")
    	local query = take(args, "query")
    	if not (type(query) == "string" and string.find(query, "%S") and #query <= MAX_QUERY) then
    		error("query must be a Europe PMC query of at most " .. tostring(MAX_QUERY) .. " bytes, not only spaces", 0)
    	end
    	assert(balanced(query), "query must balance its parentheses and double quotes")
    	local full = "(" .. query .. ") AND SRC:PPR AND "
    	if args.server == nil then
    		full ..= '(PUBLISHER:"bioRxiv" OR PUBLISHER:"medRxiv")'
    	else
    		local _, entry = server(args)
    		full ..= 'PUBLISHER:"' .. entry.name .. '"'
    	end
    	if args.from ~= nil or args.to ~= nil then
    		local from, to = range(args)
    		full ..= " AND FIRST_PDATE:[" .. from .. " TO " .. to .. "]"
    	end
    	local sort = take(args, "sort")
    	if sort ~= nil then choice(sort, "sort", SORTS) end
    	local resultType = choice(optional(args, "resultType", "core"), "resultType", RESULT_TYPES)
    	local limit = integer(optional(args, "limit", DEFAULT_SEARCH), "limit", 1, MAX_SEARCH[resultType])
    	local cursorMark = take(args, "cursorMark")
    	assert(cursorMark == nil or (type(cursorMark) == "string" and #cursorMark <= 256 and string.match(cursorMark, "^[%w+/=*]+$")),
    		"cursorMark must be the nextCursorMark of an earlier searchPreprints result")
    	noneLeft(args, "searchPreprints")
    	local target = EUROPE_PMC .. "?query=" .. url.encode(full) .. "&resultType=" .. resultType .. "&pageSize=" .. tostring(limit)
    		.. "&format=json&cursorMark=" .. url.encode(cursorMark or "*")
    		.. (if sort and sort ~= "relevance" then "&sort=" .. url.encode(sort) else "")
    	-- Europe PMC answers an unusable cursorMark with a 503 "temporarily unavailable".
    	local body = fetch("searchPreprints", "Europe PMC", target, CALL, MAX_BYTES,
    		"call again with a lower limit or resultType lite",
    		if cursorMark then "; if this persists, the cursorMark may not belong to this query: search again without it" else nil)
    	local list = if type(body.resultList) == "table" then body.resultList.result else nil
    	if not finite(body.hitCount) or type(list) ~= "table" then
    		fail("searchPreprints", 200, false, "Europe PMC returned an unexpected answer")
    	end
    	local results = array(list)
    	local result: Options = {hitCount = body.hitCount, results = results}
    	-- Europe PMC returns a cursor after every full page, the last one included.
    	if #results == limit and type(body.nextCursorMark) == "string" and body.nextCursorMark ~= cursorMark then
    		result.nextCursorMark = body.nextCursorMark
    	end
    	return result
    end
    
    local function downloadPdf(input: any): Options
    	local args = options(input, "downloadPdf")
    	local _, entry = server(args)
    	local id = doi(take(args, "doi"))
    	local version = take(args, "version")
    	version = string.format("%d", integer(if type(version) == "string" and string.match(version, "^%d+$")
    		then tonumber(version) else version, "version", 1, 999))
    	local path = take(args, "session_path")
    	assert(type(path) == "string" and path ~= "", "session_path must name a session file, such as preprint.pdf")
    	noneLeft(args, "downloadPdf")
    	local target = pdfUrl(entry.site, id, version)
    	local browser = "; open " .. target .. " in a browser instead"
    	-- Checking the session path first refuses an invalid one before any request, without creating or changing a file;
    	-- the file is opened only for a PDF, so a refused download leaves an existing one unchanged.
    	await(fs.exists(path))
    	local response = send("downloadPdf", entry.name, target, "application/pdf", CALL)
    	local status = response.statusCode
    	if status ~= 200 then
    		-- Cloudflare in front of both sites blocks some automated clients outright.
    		local reason = if status == 403 then "blocked the automated download"
    			elseif status == 404 then "has no PDF of version " .. version .. " of " .. id .. "; getPreprint lists the versions"
    			elseif status >= 300 and status < 400 then "answered with an unexpected redirect"
    			else nil
    		if reason == nil then failure("downloadPdf", entry.name, response, CALL, browser) end
    		response.body:close()
    		fail("downloadPdf", status, false, entry.name .. " HTTP " .. tostring(status) .. ": " .. reason
    			.. (if status == 404 then "" else browser))
    	end
    	local kind = response.headers["content-type"]
    	if not (kind and kind[1] and string.find(string.lower(kind[1]), "pdf", 1, true)) then
    		response.body:close()
    		fail("downloadPdf", 200, false, entry.name .. " returned a web page instead of the PDF" .. browser)
    	end
    	local opened, output = pcall(function() return fs.open(path, "w") end)
    	if not opened then
    		response.body:close()
    		error(output, 0)
    	end
    	output:write(response.body)
    	local written, err = pcall(function() await(output:close(), CALL[2]) end)
    	if not written then
    		local code = errorCode(err)
    		if code == "timeout" then
    			fail("downloadPdf", 200, true, entry.name .. " did not finish sending the PDF within " .. seconds(CALL[2]) .. "; retry")
    		elseif code == "cancelled" then
    			error(err, 0)
    		end
    		local detail = if type(err) == "table" and type(err.message) == "string" then err.message else tostring(err)
    		fail("downloadPdf", 200, true, entry.name .. " download failed: " .. string.sub(detail, 1, 300))
    	end
    	return {session_path = path, url = await(fs.signedGetUrl(path)), size = await(fs.stat(path)).size, pdf_url = target}
    end
    
    local function help(): string
    	local categories: {string} = {}
    	for _, key in {"biorxiv", "medrxiv"} do
    		table.insert(categories, "- " .. key .. ": " .. table.concat(SERVERS[key].categories, ", ") .. ".")
    	end
    	local details = tostring(DETAILS_PAGE * MAX_PAGES)
    	local pubs = tostring(PUBS_PAGE * MAX_PAGES)
    	return [[bioRxiv and medRxiv: search and read preprints in biology (bioRxiv) and health sciences (medRxiv) through the servers' public API (https://api.biorxiv.org), with keyword search powered by Europe PMC (https://europepmc.org, EMBL-EBI), and download their PDFs. No account or credentials. Read-only. Calls return completed values; do not wrap them in await(). Every function takes one options table; unknown options are rejected. Results keep the providers' field names and values. Preprints are not peer reviewed; each carries its own license (the license field, such as cc_by or cc_no). Credit bioRxiv or medRxiv, and Europe PMC for search results.
    
    server is "biorxiv" or "medrxiv"; both servers share the 10.1101 DOI prefix, and recent preprints use 10.64898. doi is a bare preprint DOI such as 10.1101/339747 or 10.64898/2026.10.15.759504, without a version suffix, doi: or https://doi.org/. Dates are real YYYY-MM-DD dates, with from not after to.
    
    ## searchPreprints({query, server?, from?, to?, sort?, resultType?, limit?, cursorMark?})
    
    Europe PMC search, restricted to bioRxiv and medRxiv preprints (both unless server is given); the API itself has no search. Europe PMC is current to about a day ago. Returns `{hitCount, results, nextCursorMark?}`. Each result has id (a Europe PMC PPR ID), doi, title, authorString, pubYear, firstPublicationDate, bookOrReportDetails.publisher ("bioRxiv" or "medRxiv"; lowercased it is the server for the other functions) and, with resultType "core" (the default), abstractText, authorList, license, citedByCount and more; "lite" leaves out abstracts and author details.
    - query: Europe PMC syntax, at most ]] .. tostring(MAX_QUERY) .. [[ bytes with balanced parentheses and quotes, for example `crispr AND "base editing"`, `TITLE:"single-cell" AND AUTH:"Smith J"`, `ABSTRACT:zebrafish` or `DOI:"10.1101/2021.10.22.465130"`. AND, OR and NOT must be capitalized.
    - from and to together filter firstPublicationDate, when Europe PMC first listed the preprint.
    - sort: ]] .. table.concat(SORTS, ", ") .. [[ (relevance by default; CITED desc puts the most cited first).
    - limit: results to return, 1 to ]] .. tostring(MAX_SEARCH.core) .. [[ with resultType core and 1 to ]] .. tostring(MAX_SEARCH.lite) .. [[ with lite, which fit one call (default ]] .. tostring(DEFAULT_SEARCH) .. [[). For the next page, call again with the same options and cursorMark = nextCursorMark. nextCursorMark is present after every full page while results may remain: when the last results exactly fill limit, continuing returns no results and no nextCursorMark.
    Europe PMC lists one record per preprint and names no version, so results have no pdf_url: read the versions, their abstracts and pdf_url with getPreprint.
    
    ## listPreprints({server, from, to, category?, funder?, limit?, cursor?})
    
    Preprint versions posted from from to to, inclusive. A revised version of an older preprint appears on the date it was posted. Returns `{collection, total?, count_new_papers?, next_cursor?}`: total counts the versions in the range, count_new_papers its first versions. When the API finds no posts from cursor on (an empty range, or a cursor at or past its end) it reports no total, so collection is empty and total absent. Each version has doi, title, authors ("Last, F.; ..."), author_corresponding, author_corresponding_institution, date, version (a string), type, license, category, abstract, jatsxml (the JATS XML address on the server's website), published (the journal DOI, or "NA") and server, plus pdf_url, the address of its PDF, added by Houston. date may lack zero padding, as in 2026-8-17.
    - category: one of the server's categories below (underscores accepted for spaces); the API would silently ignore any other.
    - funder: a ROR ID such as 00k4n6c32 (European Commission) or https://ror.org/00k4n6c32, to list only preprints declaring that funder; versions then also carry funder, an array of {name, id, id-type, award}. Funder data starts on 2025-04-10.
    - limit: versions to return, 1 to ]] .. details .. [[ (default ]] .. tostring(DETAILS_PAGE) .. [[). The API serves pages of ]] .. tostring(DETAILS_PAGE) .. [[: a call reads the first, then up to ]] .. tostring(MAX_PAGES - 1) .. [[ more at once. cursor: versions to skip (default 0). For the next page, call again with the same options and cursor = next_cursor. next_cursor is present while cursor plus the versions returned is below total; a call can return fewer than limit versions when a later page is slow, too large or fails, and next_cursor then continues after them. A month of bioRxiv holds about 7,000 versions, so narrow with category or a short range, or use searchPreprints.
    
    ## getPreprint({server, doi})
    
    Every version of one preprint, oldest first: `{collection}` with the fields of listPreprints. A DOI unknown to that server fails as not found; check the server.
    
    ## getPublication({server, doi})
    
    The journal article a preprint became: `{collection}` with at most one link {preprint_doi, published_doi, published_journal, preprint_platform, preprint_title, preprint_authors, preprint_category, preprint_date, published_date, preprint_abstract, preprint_author_corresponding, preprint_author_corresponding_institution} (no pdf_url, since a link names no version), or an empty collection when there is none. The API answers alike when the preprint is not published yet, when no preprint matches an article DOI, and when a preprint DOI belongs to the other server (both share 10.1101), so check the server with getPreprint before reading an empty collection as unpublished. doi is the preprint's DOI or the article's own DOI (such as 10.1016/S0140-6736(20)30183-5), which finds the preprint of an article; the API cannot look up DOIs with several slashes, such as 10.1093/nar/gkaf118.
    
    ## listPublications({server, from, to, limit?, cursor?})
    
    Preprints whose journal article was recorded from from to to: `{collection, total?, next_cursor?}` of the links getPublication returns. limit: 1 to ]] .. pubs .. [[ (default ]] .. tostring(PUBS_PAGE) .. [[), in pages of ]] .. tostring(PUBS_PAGE) .. [[; cursor and next_cursor work as in listPreprints.
    
    ## downloadPdf({server, doi, version, session_path})
    
    Saves the PDF of one version (an integer, or listPreprints' version string) to the session file session_path and returns `{session_path, url, size, pdf_url}`: url is a signed link to the saved file, pdf_url the PDF's address on the server's website. The website is behind Cloudflare, which limits and blocks automated downloads: HTTP 429 fails as retryable with the wait it asks (often one or two minutes), and HTTP 403, which medRxiv answers to automated PDF downloads, fails as not retryable. Either way, give people pdf_url to open in a browser. A refused download, or one that breaks while the PDF streams, leaves session_path unchanged.
    
    ## Errors and limits
    
    Invalid input fails before any request. Provider errors come back as upstream errors with the HTTP status and message; HTTP 429 and 5xx are retryable. The API answers HTTP 200 even to errors and reports them as a status, which comes back as the message. Each call reads at most ]] .. tostring(MAX_BYTES // 1048576) .. [[ MiB of JSON and has ]] .. seconds(CALL[1]) .. [[: a call reading one answer or file gives its headers ]] .. seconds(CALL[1] - CALL[2]) .. [[ and its body ]] .. seconds(CALL[2]) .. [[. A date range gives its first page ]] .. seconds(FIRST[1]) .. [[ whatever the limit (]] .. seconds(FIRST[1] - FIRST[2]) .. [[ for headers), so a larger limit never fails a call that one page would complete, and reads the later pages at once in the remaining ]] .. seconds(LATER[1]) .. [[. A call that runs out of time before it has any result fails as retryable; the API's page sizes are fixed, so a lower limit does not help then.
    
    Categories:
    ]] .. table.concat(categories, "\n") .. [[
    
    
    ## Example
    
    Here rxiv is the configured bioRxiv and medRxiv connection.
    
    ```lua
    local found = rxiv.searchPreprints({query = 'TITLE:"base editing"', server = "biorxiv", sort = "FIRST_PDATE_D desc", limit = 10})
    print(found.hitCount)
    if #found.results == 0 then return end
    local hit = found.results[1]
    local versions = rxiv.getPreprint({server = string.lower(hit.bookOrReportDetails.publisher), doi = hit.doi}).collection
    local latest = versions[#versions]
    print(latest.title, latest.version, latest.date, latest.published, latest.pdf_url)
    print(latest.abstract)
    
    local page = rxiv.listPreprints({server = "medrxiv", from = "2025-03-01", to = "2025-03-07", category = "epidemiology", limit = 90})
    for _, preprint in page.collection do print(preprint.doi, preprint.version, preprint.title) end
    -- More: rxiv.listPreprints({server = "medrxiv", from = "2025-03-01", to = "2025-03-07", category = "epidemiology",
    --	limit = 90, cursor = page.next_cursor}) while page.next_cursor.
    
    local ok, saved = pcall(rxiv.downloadPdf, {server = "biorxiv", doi = latest.doi, version = latest.version, session_path = "preprint.pdf"})
    print(if ok then saved.url else "Open " .. latest.pdf_url)
    ```]]
    end
    
    return {searchPreprints = searchPreprints, listPreprints = listPreprints, getPreprint = getPreprint,
    	getPublication = getPublication, listPublications = listPublications, downloadPdf = downloadPdf, help = help}
    
  • houston.json
    {
      "schema_version": 2,
      "name": "bioRxiv and medRxiv",
      "files": [
        "connector.luau"
      ],
      "icon": "icon.svg",
      "proxy": [
        {
          "match": {
            "protocol": "http",
            "host": [
              "api.biorxiv.org"
            ],
            "method": [
              "GET"
            ],
            "path": [
              "/details/biorxiv/*",
              "/details/medrxiv/*",
              "/funder/biorxiv/*",
              "/funder/medrxiv/*",
              "/pubs/biorxiv/*",
              "/pubs/medrxiv/*"
            ]
          },
          "action": {
            "headers": {
              "remove": [
                "Authorization",
                "Cookie"
              ]
            }
          }
        },
        {
          "match": {
            "protocol": "http",
            "host": [
              "www.ebi.ac.uk"
            ],
            "method": [
              "GET"
            ],
            "path": [
              "/europepmc/webservices/rest/search"
            ]
          },
          "action": {
            "headers": {
              "remove": [
                "Authorization",
                "Cookie"
              ]
            }
          }
        },
        {
          "match": {
            "protocol": "http",
            "host": [
              "www.biorxiv.org",
              "www.medrxiv.org"
            ],
            "method": [
              "GET"
            ],
            "path": [
              "/content/10.1101/{file}",
              "/content/10.64898/{file}"
            ]
          },
          "action": {
            "headers": {
              "remove": [
                "Authorization",
                "Cookie"
              ]
            }
          }
        }
      ]
    }
    
  • icon.svgicon.svg
  • README.md
    ---
    description: Search and read bioRxiv and medRxiv preprints, with every version, abstracts, categories, journal publications and PDFs.
    ---
    
    # bioRxiv and medRxiv
    
    Let agents search preprints, read abstracts and every version, find journal
    publications, and download available PDFs. No account is required; access is read-only.
    
    > Preprints have not completed peer review. Automated PDF downloads may be blocked;
    > open the PDF link in your browser when needed.
    
    Search uses [Europe PMC](https://europepmc.org) and may lag a day; other data comes
    from the [provider API](https://api.biorxiv.org). Respect each preprint's licence
    and [Europe PMC's attribution terms](https://europepmc.org/Copyright).
    This connector is not affiliated with the providers.
    
    [Add the connector](SETUP.md).
    
  • SETUP.md
    # Add bioRxiv and medRxiv
    
    Select **Add connection** in Houston. No account, API key or settings are required.
    
    > Automated PDF downloads may be blocked, especially by medRxiv. Open the PDF
    > link in your browser if a download fails.
    
    ## Advanced
    
    Search uses Europe PMC and may lag a day; date-range listings use the servers
    directly. Check which server holds a DOI when a preprint is missing.
    
    [Provider API](https://api.biorxiv.org) · [Search syntax](https://europepmc.org/searchsyntax).
    
  • tests
    • authentication.luau
      return {
      	contract = function(m)
      		m.authentication({
      			{
      				auth = {},
      				config = {},
      				endpoint = { "GET", "https://api.biorxiv.org/details/biorxiv/10.1101/339747/na/json" },
      				expected = "",
      				header = "Authorization",
      				method = "",
      				publisher = {},
      			},
      		})
      	end,
      }
      
    • downloads.luau
      -- PDFs stream from the server's website to a session file; Cloudflare's refusals fail clearly with the PDF's address.
      return {
      	scenario = {publisher = {}, config = {}, auth_method = "", auth_config = {}},
      	configure = function()
      		requests, responses = {}, {}
      		fs = fixture.files()
      		http = {request = function(req)
      			table.insert(requests, req)
      			assert(req.method == "GET" and req.headers.Authorization == nil and req.headers.Cookie == nil)
      			assert(#responses > 0, "unexpected request: " .. req.url)
      			local queued = table.remove(responses, 1)
      			if queued.requestError then error(queued.requestError, 0) end
      			return fixture.operation({statusCode = queued.status or 200, headers = queued.headers or {["content-type"] = {"application/pdf"}},
      				body = queued.reader or fixture.reader(queued.body or "")})
      		end}
      	end,
      	run = function(rxiv)
      		-- A PDF larger than readAll's default limit flows through native Reader and File streaming.
      		local size = 8 * 1024 * 1024 + 17
      		responses = {{body = "%PDF-1.4" .. string.rep("p", size - 8)}}
      		local saved = rxiv.downloadPdf({server = "biorxiv", doi = "10.1101/339747", version = "4", session_path = "papers/339747.pdf"})
      		assert(requests[1].url == "https://www.biorxiv.org/content/10.1101/339747v4.full.pdf", requests[1].url)
      		assert(requests[1].headers.Accept[1] == "application/pdf" and requests[1].timeoutMs == 8000)
      		assert(saved.session_path == "papers/339747.pdf" and saved.size == size and type(saved.url) == "string")
      		assert(saved.pdf_url == "https://www.biorxiv.org/content/10.1101/339747v4.full.pdf")
      		local file = fs.open("papers/339747.pdf", "r")
      		local first = await(file:read(8))
      		await(file:close())
      		assert(first.data == "%PDF-1.4", "downloaded bytes changed")
      
      		local function refused(response, opts, expected, absent)
      			responses = {response}
      			local before = #requests
      			local ok, err = pcall(rxiv.downloadPdf, opts)
      			for _, text in expected do
      				assert(not ok and string.find(tostring(err), text, 1, true), "missing " .. text .. " in " .. tostring(err))
      			end
      			if absent then assert(not string.find(tostring(err), absent, 1, true), "unexpected " .. absent .. " in " .. tostring(err)) end
      			assert(#requests == before + 1 and #responses == 0)
      		end
      		local BIO = {server = "biorxiv", doi = "10.64898/2026.10.15.759504", version = 1, session_path = "bio.pdf"}
      		local MED = {server = "medrxiv", doi = "10.1101/2020.09.09.20191205", version = 2, session_path = "med.pdf"}
      		local BIO_URL = "https://www.biorxiv.org/content/10.64898/2026.10.15.759504v1.full.pdf"
      		local MED_URL = "https://www.medrxiv.org/content/10.1101/2020.09.09.20191205v2.full.pdf"
      		-- A refused download leaves an existing file unchanged.
      		local existing = fs.open("bio.pdf", "w")
      		existing:write("kept")
      		await(existing:close())
      		local function kept()
      			local file = fs.open("bio.pdf", "r")
      			local chunk = await(file:read(16))
      			await(file:close())
      			assert(chunk.data == "kept", "a refused download changed the session file")
      		end
      		-- Cloudflare's rate limit asks for a long wait, which Houston leaves to the caller.
      		refused({status = 429, body = "error code: 1015", headers = {["retry-after"] = {"43"}, ["content-type"] = {"text/plain"}}}, BIO,
      			{"bioRxiv HTTP 429; retry after 43s; open " .. BIO_URL .. " in a browser instead", '"retryable":true', '"upstream_status":429'}, "1015")
      		kept()
      		refused({status = 403, body = "<html><title>Attention Required! | Cloudflare</title>Sorry, you have been blocked</html>",
      			headers = {["content-type"] = {"text/html"}}}, MED,
      			{"medRxiv HTTP 403: blocked the automated download; open " .. MED_URL .. " in a browser instead", '"retryable":false'}, "Cloudflare")
      		refused({status = 404, body = "<html>Not found</html>"}, BIO,
      			{"bioRxiv HTTP 404: has no PDF of version 1 of 10.64898/2026.10.15.759504; getPreprint lists the versions", '"retryable":false'}, "browser")
      		refused({status = 302, headers = {location = {"https://connect.biorxiv.org/login"}}}, MED,
      			{"medRxiv HTTP 302: answered with an unexpected redirect; open " .. MED_URL, '"retryable":false'}, "login")
      		refused({status = 503, body = ""}, BIO, {"bioRxiv HTTP 503; open " .. BIO_URL, '"retryable":true'})
      		-- A challenge page sent with 200 is not a PDF.
      		refused({body = "<html>Just a moment...</html>", headers = {["content-type"] = {"text/html; charset=UTF-8"}}}, MED,
      			{"medRxiv returned a web page instead of the PDF; open " .. MED_URL, '"retryable":false'}, "moment")
      		refused({body = "x", headers = {}}, BIO, {"bioRxiv returned a web page instead of the PDF"})
      		refused({requestError = {code = "timeout", message = "request deadline"}}, BIO, {"bioRxiv did not answer within 8 s; retry", '"retryable":true'})
      		kept()
      		-- A stream that breaks surfaces at the file's close instead of returning a download.
      		refused({reader = gzip.decode(fixture.reader("not a gzip stream"))}, BIO, {"bioRxiv download failed", '"retryable":true'})
      		-- An invalid session path fails before any request.
      		local before = #requests
      		assert(not pcall(rxiv.downloadPdf, {server = "biorxiv", doi = "10.1101/339747", version = 1, session_path = "../escape.pdf"}))
      		assert(#requests == before, "an invalid session path reached bioRxiv")
      	end,
      }
      
    • errors.luau
      -- Invalid input never reaches a provider, and provider errors, slow answers and bad bodies map to clear failures.
      return {
      	scenario = {publisher = {}, config = {}, auth_method = "", auth_config = {}},
      	configure = function()
      		calls = 0
      		status = 200
      		payload = "{}"
      		responseHeaders = {}
      		http = {request = function(req)
      			calls += 1
      			-- A table stands for a failure while waiting for headers, such as a timeout or a refused origin.
      			if requestError then error(requestError, 0) end
      			-- A body whose read fails stands in for a dropped connection or a cancelled invocation.
      			local body = if readError
      				then {readAll = function() error(readError, 0) end, readPrefix = function() error(readError, 0) end, close = function() end}
      				else fixture.reader(payload)
      			return fixture.operation({statusCode = status, headers = responseHeaders, body = body})
      		end}
      	end,
      	run = function(rxiv)
      		local function rejected(fn, expected)
      			local before = calls
      			local ok, err = pcall(fn)
      			assert(not ok and string.find(tostring(err), expected, 1, true), "wrong validation error: " .. tostring(err))
      			assert(calls == before, "invalid input reached a provider")
      		end
      		local function call(name, opts) return function() rxiv[name](opts) end end
      		local RANGE = {server = "biorxiv", from = "2025-03-01", to = "2025-03-07"}
      		local function with(base, extra)
      			local out = table.clone(base)
      			for key, value in extra do out[key] = value end
      			return out
      		end
      
      		for _, name in {"searchPreprints", "listPreprints", "getPreprint", "getPublication", "listPublications", "downloadPdf"} do
      			rejected(call(name, nil), name .. " takes one options table")
      			rejected(call(name, "x"), name .. " takes one options table")
      		end
      		for _, value in {"bioRxiv", "arxiv", "", 1} do
      			rejected(call("listPreprints", with(RANGE, {server = value})), "server must be biorxiv or medrxiv")
      			rejected(call("getPreprint", {server = value, doi = "10.1101/339747"}), "server must be biorxiv or medrxiv")
      			rejected(call("searchPreprints", {query = "x", server = value}), "server must be biorxiv or medrxiv")
      		end
      		rejected(call("getPreprint", {doi = "10.1101/339747"}), "server must be biorxiv or medrxiv")
      
      		-- Dates: real calendar days in order.
      		for _, value in {"2025-3-1", "2025/03/01", "2025-02-29", "2024-02-30", "2025-13-01", "2025-00-10", "2025-04-31", "1900-02-29", 20250301} do
      			rejected(call("listPreprints", with(RANGE, {from = value})), "from must be a date such as 2025-03-21")
      		end
      		rejected(call("listPublications", with(RANGE, {to = "2025-03-07x"})), "to must be a date")
      		rejected(call("listPreprints", with(RANGE, {from = "2025-03-08"})), "from must not be after to")
      		rejected(call("listPreprints", {server = "biorxiv", from = "2025-03-01"}), "from and to go together")
      		rejected(call("searchPreprints", {query = "x", to = "2025-03-01"}), "from and to go together")
      		rejected(call("searchPreprints", {query = "x", from = "2025-03-02", to = "2025-03-01"}), "from must not be after to")
      
      		-- Paging bounds come from the API's page sizes.
      		for _, value in {0, 121, 1.5, "30", false} do
      			rejected(call("listPreprints", with(RANGE, {limit = value})), "limit must be an integer from 1 to 120")
      		end
      		rejected(call("listPublications", with(RANGE, {limit = 401})), "limit must be an integer from 1 to 400")
      		for _, value in {-1, 2 ^ 31, 0.5, "30"} do
      			rejected(call("listPreprints", with(RANGE, {cursor = value})), "cursor must be an integer from 0 to 2147483647")
      		end
      		-- The API would silently ignore an unknown category and list every one.
      		for _, value in {"neurology", "cell-biology", "all", 5} do
      			rejected(call("listPreprints", with(RANGE, {category = value})), "category must be one of the bioRxiv categories: animal behavior")
      		end
      		rejected(call("listPreprints", with(RANGE, {server = "medrxiv", category = "neuroscience"})), "category must be one of the medRxiv categories")
      		rejected(call("listPublications", with(RANGE, {category = "neuroscience"})), "listPublications received an unknown option category")
      		for _, value in {"00k4n6c3", "00K4N6C32", "10k4n6c32", "00k4n6c3x", "https://ror.org/", "ror.org/00k4n6c32", 1} do
      			rejected(call("listPreprints", with(RANGE, {funder = value})), "funder must be a ROR ID such as 00k4n6c32")
      		end
      		rejected(call("listPreprints", with(RANGE, {interval = "30d"})), "listPreprints received an unknown option interval")
      
      		for _, value in {"339747", "10.1101/339747v2", "doi:10.1101/339747", "https://doi.org/10.1101/339747", "10.1371/journal.pone.1",
      			"10.1101/", "10.1101/2025.03.", "10.1101/../x", "10.1101/1/2", "10.1101/" .. string.rep("1", 41), 10.1101} do
      			rejected(call("getPreprint", {server = "biorxiv", doi = value}), "doi must be a bare bioRxiv or medRxiv DOI")
      			rejected(call("downloadPdf", {server = "biorxiv", doi = value, version = 1, session_path = "a.pdf"}), "doi must be a bare")
      		end
      		rejected(call("getPreprint", {server = "biorxiv", doi = "10.1101/1", version = 1}), "getPreprint received an unknown option version")
      		for _, value in {"10.1093/nar/gkaf118", "10.1/x", "10.1101/a b", "10.1101/x?y", "10.1101/x%2F", "10.1101/..", "10.1101/x#y", "10.1101/x\\y", "10.1101/x\"y", "https://doi.org/10.1101/1"} do
      			rejected(call("getPublication", {server = "biorxiv", doi = value}), "doi must be a bare DOI with one slash")
      		end
      
      		rejected(call("searchPreprints", {}), "query must be a Europe PMC query of at most 2000 bytes")
      		rejected(call("searchPreprints", {query = " \n"}), "not only spaces")
      		rejected(call("searchPreprints", {query = string.rep("a", 2001)}), "at most 2000 bytes")
      		-- Unbalanced parentheses or quotes could escape the preprint filter.
      		for _, value in {"x) OR (y", "(x", 'x"', "x)", '"x\\"', "x\\"} do
      			rejected(call("searchPreprints", {query = value}), "query must balance its parentheses and double quotes")
      		end
      		-- Europe PMC answers an unknown sort with a misleading 503.
      		for _, value in {"date", "P_PDATE_D desc", "CITED asc", 1} do
      			rejected(call("searchPreprints", {query = "x", sort = value}), "sort must be one of relevance, FIRST_PDATE_D desc")
      		end
      		rejected(call("searchPreprints", {query = "x", resultType = "idlist"}), "resultType must be one of core, lite")
      		-- limit fits the byte budget: about 40 KiB per core record and 4 KiB per lite one.
      		for _, value in {0, 103, 2.5} do
      			rejected(call("searchPreprints", {query = "x", limit = value}), "limit must be an integer from 1 to 102")
      		end
      		rejected(call("searchPreprints", {query = "x", limit = 1001, resultType = "lite"}), "limit must be an integer from 1 to 1000")
      		for _, value in {"", "a b", "a&b", string.rep("A", 257), 1} do
      			rejected(call("searchPreprints", {query = "x", cursorMark = value}), "cursorMark must be the nextCursorMark")
      		end
      		rejected(call("searchPreprints", {query = "x", synonym = true}), "searchPreprints received an unknown option synonym")
      
      		local PDF = {server = "biorxiv", doi = "10.1101/339747", version = 4, session_path = "a.pdf"}
      		for _, value in {0, 1000, 1.5, "v4", "", false} do
      			rejected(call("downloadPdf", with(PDF, {version = value})), "version must be an integer from 1 to 999")
      		end
      		rejected(call("downloadPdf", {server = "biorxiv", doi = "10.1101/339747", session_path = "a.pdf"}), "version must be an integer")
      		rejected(call("downloadPdf", with(PDF, {session_path = ""})), "session_path must name a session file")
      		rejected(call("downloadPdf", with(PDF, {format = "xml"})), "downloadPdf received an unknown option format")
      
      		local function upstream(code, body, headers, fn, expected, absent)
      			status, payload, responseHeaders = code, body, headers
      			local before = calls
      			local ok, err = pcall(fn)
      			for _, text in expected do
      				assert(not ok and string.find(tostring(err), text, 1, true), "missing " .. text .. " in " .. tostring(err))
      			end
      			if absent then assert(not string.find(tostring(err), absent, 1, true), "unexpected " .. absent .. " in " .. tostring(err)) end
      			assert(calls == before + 1, "a failed request was repeated")
      		end
      		local list = call("listPreprints", RANGE)
      		local get = call("getPreprint", {server = "medrxiv", doi = "10.1101/2020.09.09.20191205"})
      		local links = call("getPublication", {server = "biorxiv", doi = "10.1101/339747"})
      		local search = call("searchPreprints", {query = "x"})
      		local resume = call("searchPreprints", {query = "x", cursorMark = "AoIIQ=="})
      
      		-- The API answers HTTP 200 with a status for errors: rejections of input are final, anything else a fault.
      		upstream(200, '{"messages":[{"status":"no posts found"}], "collection":[]}', {}, get,
      			{"medRxiv has no preprint with DOI 10.1101/2020.09.09.20191205; check the server", '"retryable":false', '"upstream_status":200'})
      		upstream(200, '{"messages":[{"status":"Both dates must be in yyyy-mm-dd format"}], "collection":[]}', {}, list,
      			{"bioRxiv API: Both dates must be in yyyy-mm-dd format", '"retryable":false'})
      		upstream(200, '{"messages":[{"status":"DOI not recognizable"}], "collection":[]}', {}, links, {"bioRxiv API: DOI not recognizable", '"retryable":false'})
      		upstream(200, '{"messages":[{"status":"Server not recognized"}], "collection":[]}', {}, get, {"Server not recognized", '"retryable":false'})
      		upstream(200, '{"messages":[{"status":"funder value not found"}], "collection":[]}', {}, call("listPreprints", with(RANGE, {funder = "00k4n6c32"})),
      			{"bioRxiv API: funder value not found", '"retryable":false'})
      		upstream(200, '{"messages":[{"status":"database   unavailable"}], "collection":[]}', {}, list, {"bioRxiv API: database unavailable", '"retryable":true'})
      		upstream(200, '{"messages":[{"status":"ok","total":"many"}], "collection":[]}', {}, list, {"bioRxiv API returned a page without its total"})
      		upstream(200, '{"messages":[], "collection":[]}', {}, get, {"bioRxiv API returned an unexpected answer", '"retryable":false'})
      		upstream(200, '{"messages":[{"status":"ok"}]}', {}, links, {"bioRxiv API returned an unexpected answer"})
      		upstream(200, "<html>Maintenance</html>", {}, list, {"bioRxiv API returned an invalid JSON object", '"retryable":false'}, "Maintenance")
      		upstream(200, "[]", {}, get, {"bioRxiv API returned an invalid JSON object"})
      		upstream(404, "<!DOCTYPE HTML><title>404 Not Found</title>", {}, get, {"bioRxiv API HTTP 404", '"retryable":false', '"upstream_status":404'}, "DOCTYPE")
      		upstream(503, "", {["retry-after"] = {"120"}}, list, {"bioRxiv API HTTP 503; retry after 120s", '"retryable":true'})
      		upstream(301, "", {location = {"https://example.com/"}}, links, {"bioRxiv API HTTP 301: unexpected redirect", '"retryable":false'}, "example")
      		upstream(200, '{"x":"' .. string.rep("z", 4 * 1024 * 1024) .. '"}', {}, list,
      			{"bioRxiv API returned more data than one call can hold; the API's page of 30 is too large for one call", '"retryable":false'}, "limit_exceeded")
      
      		upstream(503, '{"errCode":503,"errMsg":"Search service is temporarily unavailable. Please retry later."}', {}, search,
      			{"Europe PMC HTTP 503: Search service is temporarily unavailable. Please retry later.", '"retryable":true'}, "cursorMark")
      		upstream(503, '{"errCode":503,"errMsg":"Search service is temporarily unavailable."}', {}, resume,
      			{"Europe PMC HTTP 503: Search service is temporarily unavailable.; if this persists, the cursorMark may not belong to this query"})
      		upstream(429, "", {["retry-after"] = {"Thu, 29 Oct 2026 20:00:00 GMT"}}, search,
      			{"Europe PMC HTTP 429; retry after Thu, 29 Oct 2026 20:00:00 GMT", '"retryable":true'}, "GMTs")
      		upstream(400, '{"errCode":400,"errMsg":"' .. string.rep("y", 1000) .. '"}', {}, search,
      			{"Europe PMC HTTP 400: " .. string.rep("y", 300), '"retryable":false'}, string.rep("y", 301))
      		upstream(200, '{"hitCount":"3","resultList":{"result":[]}}', {}, search, {"Europe PMC returned an unexpected answer", '"retryable":false'})
      		upstream(200, '{"hitCount":3}', {}, search, {"Europe PMC returned an unexpected answer"})
      		upstream(200, '{"hitCount":1,"resultList":{"result":[{"abstractText":"' .. string.rep("w", 4 * 1024 * 1024) .. '"}]}}', {}, search,
      			{"Europe PMC returned more data than one call can hold; call again with a lower limit or resultType lite", '"retryable":false'})
      
      		requestError = {code = "timeout", message = "request deadline"}
      		upstream(200, "", {}, search, {"Europe PMC did not answer within 8 s; retry", '"retryable":true'})
      		upstream(200, "", {}, call("listPreprints", with(RANGE, {limit = 90})), {"bioRxiv API did not answer within 8 s; retry", '"retryable":true'})
      		-- Other request failures pass through unchanged, message included, and never become an upstream failure.
      		requestError = {code = "access_denied", message = "origin not allowed"}
      		upstream(200, "", {}, get, {"origin not allowed"}, "retryable")
      		requestError = nil
      		readError = {code = "timeout", message = "await timed out"}
      		upstream(200, "", {}, get, {"bioRxiv API did not finish sending its answer within 19 s; retry", '"retryable":true'})
      		upstream(200, "", {}, call("listPreprints", with(RANGE, {limit = 31})), {"did not finish sending its answer within 7 s"})
      		readError = {code = "io_error", message = "connection reset by peer"}
      		upstream(200, "", {}, search, {"Europe PMC response failed: connection reset by peer", '"retryable":true'}, "more data")
      		-- An error body that stalls or breaks still gives the structured failure.
      		upstream(502, "", {}, list, {"bioRxiv API HTTP 502", '"retryable":true', '"upstream_status":502'}, "reset")
      		readError = {code = "timeout", message = "await timed out"}
      		upstream(400, "", {}, search, {"Europe PMC HTTP 400", '"retryable":false', '"upstream_status":400'}, "timed out")
      		readError = {code = "cancelled", message = "invocation cancelled"}
      		for _, fn in {list, search, call("listPreprints", with(RANGE, {limit = 60}))} do
      			local before = calls
      			local ok, err = pcall(fn)
      			-- A stand-in error loses its native identity across the export boundary; it must still not become an upstream failure.
      			assert(not ok and not string.find(tostring(err), "retryable", 1, true), "cancellation became an upstream error: " .. tostring(err))
      			assert(calls == before + 1)
      		end
      		readError = nil
      	end,
      }
      
    • manifest.luau
      return {
      	contract = function(m)
      		local resolveBioRxiv = function()
      			local r, err = m.resolve(nil, nil, nil, "")
      			assert(not err, tostring(err))
      			return r
      		end
      		-- TestBioRxivPublicReadRoutes
      		do
      			local r = resolveBioRxiv()
      			local api = "https://api.biorxiv.org"
      			local search = "https://www.ebi.ac.uk/europepmc/webservices/rest/search"
      			m.routes(r, "", true, {
      				"GET " .. api .. "/details/biorxiv/2025-03-01/2025-03-07/30/json?category=cell_biology",
      				"GET " .. api .. "/details/medrxiv/10.1101/2020.09.09.20191205/na/json",
      				"GET " .. api .. "/funder/biorxiv/2025-04-10/2025-07-10/00k4n6c32/0/json",
      				"GET " .. api .. "/pubs/medrxiv/10.1371/journal.pone.0256482/na/json",
      				"GET " .. api .. "/pubs/medrxiv/10.1016/S2468-2667%2820%2930133-X/na/json",
      				"GET " .. api .. "/pubs/biorxiv/2025-04-01/2025-04-30/100",
      				"GET "
      					.. search
      					.. "?query=%28x%29%20AND%20SRC%3APPR&resultType=core&pageSize=25&format=json&cursorMark=%2A",
      				"GET https://www.biorxiv.org/content/10.1101/339747v4.full.pdf",
      				"GET https://www.medrxiv.org/content/10.64898/2026.09.01.26361059v2.full.pdf",
      			})
      			m.routes(r, "", false, {
      				"POST " .. api .. "/details/biorxiv/2025-03-01/2025-03-07/0/json",
      				"GET " .. api .. "/details/arxiv/2025-03-01/2025-03-07",
      				"GET " .. api .. "/sum/m",
      				"GET " .. api .. "/usage/m/biorxiv",
      				"GET " .. api .. "/pub/2025-03-01/2025-03-07",
      				"GET " .. api .. "/publisher/10.15252/2025-03-01/2025-03-07",
      				"GET " .. api .. "/details/biorxiv/%2e%2e/sum/m",
      				"GET https://api.biorxiv.org.example.com/details/biorxiv/1/na/json",
      				"GET http://api.biorxiv.org:8080/details/biorxiv/1/na/json",
      				"GET https://connect.biorxiv.org/details/biorxiv/1/na/json",
      				"POST " .. search,
      				"GET " .. search .. "POST",
      				"GET https://www.ebi.ac.uk/europepmc/webservices/rest/PPR1/fullTextXML",
      				"GET https://www.ebi.ac.uk/chembl/api/data/molecule.json",
      				"POST https://www.biorxiv.org/content/10.1101/339747v4.full.pdf",
      				"GET https://www.biorxiv.org/content/early/2019/05/10/339747.source.xml",
      				"GET https://www.biorxiv.org/content/10.1101/339747/v4/full.pdf",
      				"GET https://www.biorxiv.org/content/10.1000/339747.full.pdf",
      				"GET https://www.biorxiv.org/user/login",
      				"GET https://biorxiv.org/content/10.1101/339747v4.full.pdf",
      				"GET https://connect.biorxiv.org/content/10.1101/339747v4.full.pdf",
      			})
      		end
      		-- TestBioRxivRejectsMethodOverridesAndDropsCredentials
      		do
      			local r = resolveBioRxiv()
      			local dropped = { "Authorization", "Cookie" }
      			for _, target in
      				{
      					"https://api.biorxiv.org/details/biorxiv/10.1101/339747/na/json",
      					"https://www.ebi.ac.uk/europepmc/webservices/rest/search",
      					"https://www.medrxiv.org/content/10.1101/2020.09.09.20191205v2.full.pdf",
      				}
      			do
      				local recipe, err = m.recipe(r, "GET", target, nil)
      				assert(not err, tostring(err))
      				m.rejectPreparedOverrides(recipe, r.Context, "GET " .. target)
      				local caller = { Accept = { "application/json" } }
      				for _, name in dropped do
      					caller[name] = { "caller-value" }
      				end
      				local headers, err = m.prepare(recipe, r.Context, caller)
      				if (err ~= nil) or (m.header(headers, "Accept") ~= "application/json") then
      					m.fail("prepare %s: %s %s", target, headers, err)
      				end
      				for _, name in dropped do
      					if m.header(headers, name) ~= "" then
      						m.fail("%s reached %s", name, target)
      					end
      				end
      			end
      		end
      	end,
      }
      
    • reads.luau
      -- Each export sends exact requests to the bioRxiv API or Europe PMC, pages within its limits and returns the providers' data.
      return {
      	scenario = {publisher = {}, config = {}, auth_method = "", auth_config = {}},
      	configure = function()
      		requests, responses = {}, {}
      		http = {request = function(req)
      			table.insert(requests, req)
      			assert(req.method == "GET" and req.body == nil, "every request is a GET")
      			assert(req.headers.Authorization == nil and req.headers.Cookie == nil, "the public APIs take no credentials")
      			assert(#responses > 0, "unexpected request: " .. req.url)
      			local queued = table.remove(responses, 1)
      			if queued.requestError then error(queued.requestError, 0) end
      			local body = if queued.readError
      				then {readAll = function() error(queued.readError, 0) end, readPrefix = function() error(queued.readError, 0) end, close = function() end}
      				else fixture.reader(queued.body)
      			return fixture.operation({statusCode = queued.status or 200, headers = queued.headers or {}, body = body})
      		end}
      		function respond(body, extra)
      			local queued = extra or {}
      			queued.body = body
      			table.insert(responses, queued)
      		end
      		-- A details page of n versions numbered from first, as the API sends it with a trailing blank line.
      		function details(total, first, n, extra)
      			local rows = {}
      			for i = first, first + n - 1 do
      				table.insert(rows, {doi = "10.1101/2025.03.20." .. tostring(600000 + i), version = "1", title = "Preprint " .. tostring(i),
      					date = "2025-3-2", server = "bioRxiv", published = "NA", category = "neuroscience"})
      			end
      			local message = {status = "ok", category = "all", interval = "2025-03-01:2025-03-07", cursor = if first == 0 then 0 else tostring(first),
      				count = n, count_new_papers = "250", total = tostring(total)}
      			for key, value in extra or {} do message[key] = value end
      			return '{"messages":[' .. json.encode(message) .. '], "collection":' .. (if n == 0 then "[]" else json.encode(rows)) .. "}\n\n\n"
      		end
      	end,
      	run = function(rxiv)
      		local API = "https://api.biorxiv.org"
      		local EPMC = "https://www.ebi.ac.uk/europepmc/webservices/rest/search?query="
      		local function req(i) return requests[i] end
      
      		local names = {}
      		for name, fn in rxiv do
      			assert(type(fn) == "function")
      			table.insert(names, name)
      		end
      		table.sort(names)
      		assert(table.concat(names, ",") == "downloadPdf,getPreprint,getPublication,listPreprints,listPublications,searchPreprints",
      			table.concat(names, ","))
      		assert(#requests == 0, "initialization made a request")
      
      		-- Search: a query wrapped in the preprint filter for both servers, Europe PMC's defaults and an empty array.
      		respond('{"version":"6.9","hitCount":0,"request":{},"resultList":{"result":[]}}')
      		local found = rxiv.searchPreprints({query = "zzqx OR (a AND b)"})
      		assert(req(1).url == EPMC .. "%28zzqx%20OR%20%28a%20AND%20b%29%29%20AND%20SRC%3APPR%20AND%20%28PUBLISHER%3A%22bioRxiv%22%20OR%20PUBLISHER%3A%22medRxiv%22%29"
      			.. "&resultType=core&pageSize=25&format=json&cursorMark=%2A", req(1).url)
      		assert(req(1).headers.Accept[1] == "application/json" and req(1).timeoutMs == 8000, "one-request calls give headers 8 s")
      		assert(found.hitCount == 0 and json.encode(found.results) == "[]" and found.nextCursorMark == nil)
      
      		-- Every option; a full page returns Europe PMC's cursor, and the caller's table is left unchanged.
      		local opts = {query = 'TITLE:"base editing"', server = "medrxiv", from = "2024-02-29", to = "2024-12-31",
      			sort = "FIRST_PDATE_D desc", resultType = "lite", limit = 2, cursorMark = "AoIIQIKqFyg1MjgxNzYwNA=="}
      		respond('{"hitCount":5,"nextCursorMark":"AoIIQE8BmCg0OTg4NTYzMA==","resultList":{"result":[{"id":"PPR1","doi":"10.1101/2020.09.09.20191205",'
      			.. '"bookOrReportDetails":{"publisher":"medRxiv"}},{"id":"PPR2","doi":"10.64898/2026.09.01.26361059"}]}}')
      		found = rxiv.searchPreprints(opts)
      		assert(req(2).url == EPMC .. "%28TITLE%3A%22base%20editing%22%29%20AND%20SRC%3APPR%20AND%20PUBLISHER%3A%22medRxiv%22"
      			.. "%20AND%20FIRST_PDATE%3A%5B2024-02-29%20TO%202024-12-31%5D&resultType=lite&pageSize=2&format=json"
      			.. "&cursorMark=AoIIQIKqFyg1MjgxNzYwNA%3D%3D&sort=FIRST_PDATE_D%20desc", req(2).url)
      		assert(found.hitCount == 5 and #found.results == 2 and found.results[1].bookOrReportDetails.publisher == "medRxiv")
      		assert(found.nextCursorMark == "AoIIQE8BmCg0OTg4NTYzMA==")
      		assert(opts.server == "medrxiv" and opts.limit == 2, "caller options were modified")
      		-- A short page is the last one; relevance is Europe PMC's default order, so it sends no sort.
      		respond('{"hitCount":3,"nextCursorMark":"AoIIQE8BmCg0OTg4NTYzMA==","resultList":{"result":[{"id":"PPR3"}]}}')
      		found = rxiv.searchPreprints({query = "x", server = "biorxiv", sort = "relevance", limit = 2})
      		assert(req(3).url == EPMC .. "%28x%29%20AND%20SRC%3APPR%20AND%20PUBLISHER%3A%22bioRxiv%22&resultType=core&pageSize=2&format=json&cursorMark=%2A",
      			req(3).url)
      		assert(#found.results == 1 and found.nextCursorMark == nil)
      		respond('{"hitCount":0,"resultList":{"result":[]}}')
      		rxiv.searchPreprints({query = "x", resultType = "lite", limit = 1000})
      		assert(string.find(req(#requests).url, "&resultType=lite&pageSize=1000&", 1, true), req(#requests).url)
      		respond('{"hitCount":0,"resultList":{"result":[]}}')
      		rxiv.searchPreprints({query = "x", limit = 102})
      		assert(string.find(req(#requests).url, "&resultType=core&pageSize=102&", 1, true), req(#requests).url)
      		-- A cursor equal to the one sent ends the search; quotes and escapes may hold parentheses.
      		respond('{"hitCount":3,"nextCursorMark":"AoIIQ==","resultList":{"result":[{"id":"PPR4"}]}}')
      		found = rxiv.searchPreprints({query = '"a (b" AND c\\)', limit = 1, cursorMark = "AoIIQ==", sort = "CITED desc"})
      		assert(found.nextCursorMark == nil and string.find(req(#requests).url, "&sort=CITED%20desc", 1, true))
      
      		-- A single DOI: every version, each with its PDF address.
      		respond('{"messages":[{"status":"ok","category":"all"}], "collection":[{"doi":"10.1101\\/339747","version":"1","server":"bioRxiv",'
      			.. '"date":"2018-06-05","published":"10.1038\\/s41592-019-0476-5"},{"doi":"10.1101\\/339747","version":"4","date":"2019-05-10"}]}')
      		local preprint = rxiv.getPreprint({server = "biorxiv", doi = "10.1101/339747"})
      		assert(req(#requests).url == API .. "/details/biorxiv/10.1101/339747/na/json" and req(#requests).timeoutMs == 8000, req(#requests).url)
      		assert(#preprint.collection == 2 and preprint.collection[1].published == "10.1038/s41592-019-0476-5")
      		assert(preprint.collection[1].pdf_url == "https://www.biorxiv.org/content/10.1101/339747v1.full.pdf")
      		assert(preprint.collection[2].pdf_url == "https://www.biorxiv.org/content/10.1101/339747v4.full.pdf")
      		respond('{"messages":[{"status":"ok"}], "collection":[{"doi":"10.64898\\/2026.09.01.26361059","version":"2"},{"doi":"bad","version":"1"}]}')
      		preprint = rxiv.getPreprint({server = "medrxiv", doi = "10.64898/2026.09.01.26361059"})
      		assert(req(#requests).url == API .. "/details/medrxiv/10.64898/2026.09.01.26361059/na/json")
      		assert(preprint.collection[1].pdf_url == "https://www.medrxiv.org/content/10.64898/2026.09.01.26361059v2.full.pdf")
      		assert(preprint.collection[2].pdf_url == nil, "a malformed row gets no PDF address")
      
      		-- Journal links by preprint or article DOI; an unpublished preprint and an article without a preprint have none.
      		respond('{"messages":[{"status":"ok"}], "collection":[{"preprint_doi":"10.1101\\/2021.04.29.21256344",'
      			.. '"published_doi":"10.1371\\/journal.pone.0256482","published_journal":"PLOS ONE"}]}')
      		local link = rxiv.getPublication({server = "medrxiv", doi = "10.1371/journal.pone.0256482"})
      		assert(req(#requests).url == API .. "/pubs/medrxiv/10.1371/journal.pone.0256482/na/json", req(#requests).url)
      		assert(link.collection[1].published_journal == "PLOS ONE")
      		-- A suffix with punctuation, as in Lancet DOIs, is URL-encoded; the API decodes it.
      		respond('{"messages":[{"status":"ok"}], "collection":[{"preprint_doi":"10.1101\\/2020.04.01.20049908","published_doi":"10.1016\\/S2468-2667(20)30133-X"}]}')
      		link = rxiv.getPublication({server = "medrxiv", doi = "10.1016/S2468-2667(20)30133-X"})
      		assert(req(#requests).url == API .. "/pubs/medrxiv/10.1016/S2468-2667%2820%2930133-X/na/json", req(#requests).url)
      		assert(link.collection[1].preprint_doi == "10.1101/2020.04.01.20049908")
      		respond('{"messages":[{"status":"ok"}], "collection":[]}')
      		rxiv.getPublication({server = "biorxiv", doi = "10.1002/(SICI)1097-0258(19980815)17:15<1661::AID-SIM968>3.0.CO;2-2"})
      		assert(req(#requests).url == API .. "/pubs/biorxiv/10.1002/%28SICI%291097-0258%2819980815%2917%3A15%3C1661%3A%3AAID-SIM968%3E3.0.CO%3B2-2/na/json",
      			req(#requests).url)
      		respond('{"messages":[{"status":"no articles found for published version of 10.1101\\/339747"}], "collection":[]}')
      		assert(json.encode(rxiv.getPublication({server = "biorxiv", doi = "10.1101/339747"}).collection) == "[]")
      		respond('{"messages":[{"status":"Preprint for DOI 10.1038\\/s41586-020-2012-7 not found"}], "collection":[]}')
      		assert(json.encode(rxiv.getPublication({server = "biorxiv", doi = "10.1038/s41586-020-2012-7"}).collection) == "[]")
      
      		-- A range of one page: the whole call time, the API's string totals as numbers and the PDF addresses.
      		local before = #requests
      		respond(details(2, 0, 2))
      		local page = rxiv.listPreprints({server = "biorxiv", from = "2025-03-01", to = "2025-03-07"})
      		assert(req(before + 1).url == API .. "/details/biorxiv/2025-03-01/2025-03-07/0/json", req(before + 1).url)
      		assert(req(before + 1).timeoutMs == 8000)
      		assert(page.total == 2 and page.count_new_papers == 250 and #page.collection == 2 and page.next_cursor == nil)
      		assert(page.collection[2].pdf_url == "https://www.biorxiv.org/content/10.1101/2025.03.20.600001v1.full.pdf")
      		assert(page.collection[1].date == "2025-3-2", "dates stay as the API sends them")
      
      		-- Several pages: the first gets 15 s (8 s for headers) whatever the limit, later ones share 12 s (9 s for headers), the last page is cut at limit and next_cursor follows it.
      		before = #requests
      		respond(details(1267, 30, 30))
      		respond(details(1267, 60, 30))
      		page = rxiv.listPreprints({server = "medrxiv", from = "2025-03-01", to = "2025-03-07", category = "Cardiovascular_Medicine",
      			cursor = 30, limit = 40})
      		assert(#requests == before + 2)
      		assert(req(before + 1).url == API .. "/details/medrxiv/2025-03-01/2025-03-07/30/json?category=cardiovascular_medicine", req(before + 1).url)
      		assert(req(before + 2).url == API .. "/details/medrxiv/2025-03-01/2025-03-07/60/json?category=cardiovascular_medicine", req(before + 2).url)
      		assert(req(before + 1).timeoutMs == 8000 and req(before + 2).timeoutMs == 9000)
      		assert(#page.collection == 40 and page.collection[40].title == "Preprint 69" and page.total == 1267 and page.next_cursor == 70)
      		assert(page.collection[1].pdf_url == "https://www.medrxiv.org/content/10.1101/2025.03.20.600030v1.full.pdf")
      
      		-- The total sizes the later pages, so no needless request is sent.
      		before = #requests
      		respond(details(95, 0, 30))
      		respond(details(95, 30, 30))
      		respond(details(95, 60, 30))
      		page = rxiv.listPreprints({server = "biorxiv", from = "2025-03-01", to = "2025-03-07", limit = 90})
      		assert(#requests == before + 3 and #page.collection == 90 and page.next_cursor == 90)
      		before = #requests
      		respond(details(95, 90, 5))
      		page = rxiv.listPreprints({server = "biorxiv", from = "2025-03-01", to = "2025-03-07", limit = 90, cursor = 90})
      		assert(#requests == before + 1 and #page.collection == 5 and page.next_cursor == nil)
      		-- An exactly full last page stops at the total.
      		before = #requests
      		respond(details(60, 0, 30))
      		respond(details(60, 30, 30))
      		page = rxiv.listPreprints({server = "biorxiv", from = "2025-03-01", to = "2025-03-07", limit = 90})
      		assert(#requests == before + 2 and #page.collection == 60 and page.next_cursor == nil)
      
      		-- No posts: an empty range, or a cursor at its end, is an empty array.
      		respond('{"messages":[{"status":"no posts found"}], "collection":[]}')
      		page = rxiv.listPreprints({server = "biorxiv", from = "2030-01-01", to = "2030-01-01"})
      		assert(json.encode(page.collection) == "[]" and page.total == nil and page.next_cursor == nil, "an unknown total is absent")
      		before = #requests
      		respond(details(1267, 30, 30))
      		respond('{"messages":[{"status":"no posts found"}], "collection":[]}')
      		page = rxiv.listPreprints({server = "biorxiv", from = "2025-03-01", to = "2025-03-07", limit = 60, cursor = 30})
      		assert(#requests == before + 2 and #page.collection == 30 and page.next_cursor == nil, "a page without posts ends the range")
      
      		-- Any failure of a later page returns the versions so far and where to continue.
      		local failures = {
      			{status = 500, body = "<html>error</html>"},
      			{status = 429, body = "", headers = {["retry-after"] = {"30"}}},
      			{requestError = {code = "timeout", message = "request deadline"}},
      			{readError = {code = "timeout", message = "await timed out"}},
      			{readError = {code = "io_error", message = "connection reset"}},
      			{body = "<html>maintenance</html>"},
      			{body = '{"messages":[{"status":"Both dates must be in yyyy-mm-dd format"}], "collection":[]}'},
      			{body = '{"messages":[{"status":"ok","total":"many"}], "collection":[{"doi":"10.1101/1"}]}'},
      			-- The first page used part of the budget, so this one overflows what remains.
      			{body = '{"x":"' .. string.rep("z", 4 * 1024 * 1024 - 1000) .. '"}'},
      		}
      		for _, failure in failures do
      			before = #requests
      			respond(details(1267, 0, 30))
      			table.insert(responses, failure)
      			page = rxiv.listPreprints({server = "biorxiv", from = "2025-03-01", to = "2025-03-07", limit = 60})
      			assert(#requests == before + 2 and #page.collection == 30 and page.next_cursor == 30 and page.total == 1267, "a later failure lost the collected versions")
      		end
      
      		-- Four pages at most: three later ones go out at once, and the first failure among them ends the rows there.
      		before = #requests
      		respond(details(1267, 0, 30))
      		respond(details(1267, 30, 30))
      		respond(details(1267, 60, 30))
      		respond(details(1267, 90, 30))
      		page = rxiv.listPreprints({server = "biorxiv", from = "2025-03-01", to = "2025-03-07", limit = 120})
      		assert(#requests == before + 4 and #page.collection == 120 and page.next_cursor == 120 and page.collection[120].title == "Preprint 119")
      		assert(req(before + 4).url == API .. "/details/biorxiv/2025-03-01/2025-03-07/90/json" and req(before + 4).timeoutMs == 9000)
      		for failed = 2, 4 do
      			before = #requests
      			for index = 1, 4 do
      				if index == failed then
      					table.insert(responses, {status = 502, body = ""})
      				else
      					respond(details(1267, (index - 1) * 30, 30))
      				end
      			end
      			page = rxiv.listPreprints({server = "biorxiv", from = "2025-03-01", to = "2025-03-07", limit = 120})
      			local kept = (failed - 1) * 30
      			assert(#requests == before + 4 and #page.collection == kept and page.next_cursor == kept, "rows after a failed page were kept")
      		end
      
      		-- A funder narrows the range; its versions keep their funder arrays.
      		before = #requests
      		respond(details(1, 0, 1, {funder = "European Commission : https://ror.org/00k4n6c32"}))
      		page = rxiv.listPreprints({server = "biorxiv", from = "2025-04-10", to = "2025-07-10", funder = "https://ror.org/00k4n6c32",
      			category = "cell biology"})
      		assert(req(before + 1).url == API .. "/funder/biorxiv/2025-04-10/2025-07-10/00k4n6c32/0/json?category=cell_biology", req(before + 1).url)
      		assert(#page.collection == 1)
      
      		-- Published-article links page by 100, without a category or PDF addresses.
      		before = #requests
      		local links = {}
      		for i = 1, 100 do links[i] = {preprint_doi = "10.1101/" .. tostring(i), published_doi = "10.1/x" .. tostring(i)} end
      		respond('{"messages":[{"status":"ok","interval":"2025-04-01:2025-04-30","cursor":0,"count":100,"total":"250"}], "collection":'
      			.. json.encode(links) .. "}")
      		respond('{"messages":[{"status":"ok","cursor":"100","count":100,"total":"250"}], "collection":' .. json.encode(links) .. "}")
      		page = rxiv.listPublications({server = "biorxiv", from = "2025-04-01", to = "2025-04-30", limit = 150})
      		assert(req(before + 1).url == API .. "/pubs/biorxiv/2025-04-01/2025-04-30/0", req(before + 1).url)
      		assert(req(before + 2).url == API .. "/pubs/biorxiv/2025-04-01/2025-04-30/100", req(before + 2).url)
      		assert(#page.collection == 150 and page.total == 250 and page.next_cursor == 150 and page.collection[1].pdf_url == nil)
      		assert(page.count_new_papers == nil)
      		respond('{"messages":[{"status":"ok","cursor":0,"count":0,"total":"0"}], "collection":[]}')
      		page = rxiv.listPublications({server = "medrxiv", from = "2025-04-01", to = "2025-04-01"})
      		assert(json.encode(page.collection) == "[]" and page.next_cursor == nil)
      		assert(#responses == 0, "a queued response was not requested")
      	end,
      }