TypeScript SDK
Call Papyrus from Node, Bun and browsers with a typed client
@axelered/papyrus is the TypeScript client of Papyrus, with one method per operation and typed, validated responses. It requires Node 22.12 or later, or Bun. Deno, edge runtimes and browsers work but are not tested. SDK X.Y is made for server X.Y.
npm install @axelered/papyrusimport { openAsBlob } from 'node:fs'
import { Papyrus } from '@axelered/papyrus'
const client = new Papyrus({ baseUrl: 'http://127.0.0.1:8000', apiKey: 'dev' })
const doc = await client.markdown(await openAsBlob('pricing.html'), {
filename: 'pricing.html',
chunking: { maxTokens: 64 },
})
console.log(doc.source.title)
for (const chunk of doc.chunks ?? []) {
console.log(chunk.index, chunk.kind, chunk.headings, chunk.tokens)
}Service levels
0 text [ 'Service levels' ] 16
1 text [ 'Service levels', 'Response times' ] 4
2 table [ 'Service levels', 'Response times' ] 51
3 text [ 'Service levels', 'Escalation' ] 28Configure the client
| Option | Default |
|---|---|
baseUrl | The PAPYRUS_BASE_URL variable; required |
apiKey | The PAPYRUS_API_KEY variable; without it requests carry no Authorization header |
timeout | 310000 milliseconds for each attempt, including upload and response; every operation also accepts its own timeout |
maxRetries | 2; 0 turns retries off |
fetch | The global fetch; replace it for proxies, private certificate authorities and longer timeouts |
The server reads a comma-separated list of keys from its own PAPYRUS_API_KEY. The client takes a single key and rejects a value with a comma.
Keep timeout above the server's limits.deadline, 300 seconds by default. The server answers only when it is done, so with a shorter timeout you get a client timeout instead of deadline_exceeded.
Wait longer than 300 seconds on Node
Node's fetch stops waiting after 300 seconds whatever timeout is, and the call rejects with TimedOut. When the server has a longer limits.deadline, install undici@7, which works with Node 22 and later, and pass a fetch that uses its agent:
import { Papyrus } from '@axelered/papyrus'
import { Agent } from 'undici'
const extra: object = { dispatcher: new Agent({ headersTimeout: 0, bodyTimeout: 0 }) }
const client = new Papyrus({
timeout: 900_000,
fetch: (url, init) => fetch(url, { ...init, ...extra }),
})Call the global fetch. The one exported by undici sends uploads as the text [object FormData].
Choose how you send the document
markdown, render, thumbnail and inspect take the document as their first argument:
| Value | What the client sends |
|---|---|
string, URL | A URI, as is. Strings are never local paths: without :// the call rejects with a TypeError |
Blob, File | An upload |
ArrayBuffer, Uint8Array, Buffer | An upload |
await client.markdown('s3://prod/docs/report.pdf')
await client.markdown(await openAsBlob('sample.pdf'), { filename: 'sample.pdf' })
await client.markdown(Bun.file('sample.pdf'))Set filename on uploads that have no name of their own, because the extension refines format detection. File and Bun.file keep their names. Streams are rejected with a TypeError, so read them into a Blob first with await new Response(stream).blob().
screenshot takes the URL of a page.
Set options
Options are fields of the second argument, named as in the API. Papyrus applies its defaults to the ones you leave out and returns the resolved values in options:
import { writeFile } from 'node:fs/promises'
import { bytes } from '@axelered/papyrus'
const page = await client.render(await openAsBlob('sample.pdf'), { page: 1, width: 800, format: 'webp' })
console.log(page.source.pageCount, page.result.width, page.result.height)
console.log(page.options)
await writeFile('page.webp', bytes(page.result))1 800 1133
{ page: 1, width: 800, format: 'webp' }The same argument takes timeout and signal. When you abort, the call rejects with the signal's reason.
Read scans and images
By default, readMode is auto: the server reads scans, images and presentations from their page images when your operator has configured a vision model, and everything else from its text. Set readMode: 'ocr' to read every page from its image, or 'text' to never use the model. OCR covers how auto decides, the formats, the backends and the limits.
const doc = await client.markdown(await openAsBlob('scan.pdf'), {
filename: 'scan.pdf',
readMode: 'ocr',
chunking: {},
})
console.log(doc.options.readMode, doc.source.pageCount)
for (const chunk of doc.chunks ?? []) console.log(chunk.page, chunk.headings)options.readMode is the mode the server used, text or ocr: formats without pages, and spreadsheets, are read as text. Raise the client timeout together with limits.deadline for long documents.
Read the result
| Function | Returns |
|---|---|
text(result) | Markdown as a string; throws TypeError on an image |
bytes(result) | The artifact as a Uint8Array |
Responses are plain objects that you can cache as JSON, clone, and pass from React Server Components to Client Components. Fields the server omits are undefined.
With destination, Papyrus writes the result to remote storage and the response has no content or chunks. result.uri is set, and both functions throw TypeError.
const stored = await client.markdown('s3://prod/docs/report.pdf', { destination: 's3://prod/md/report.md' })
console.log(stored.result.uri)Call Papyrus from a browser
Add the origin of the page to cors.allow_origins in the server configuration.
The API key is visible to whoever opens the page. Call Papyrus from your own backend unless every user of the page may have the key.
Handle errors
| Error | Meaning |
|---|---|
APIError | The server answered with an error; branch on code, listed in error codes. code is undefined when the answer comes from a proxy |
ConnectionFailed | The server is unreachable or the connection was lost |
TimedOut | A ConnectionFailed caused by a timeout |
InvalidResponse | The answer is not a response this SDK version knows, for example an enum value added by a newer server |
import { APIError } from '@axelered/papyrus'
try {
await client.render(await openAsBlob('sample.pdf'), { page: 5 })
} catch (error) {
if (!(error instanceof APIError)) throw error
console.log(error.status, error.code, error.detail)
}422 page_out_of_range page 5 is out of range, the document has 1The four errors derive from PapyrusError. Use error.requestId to find the request in the server logs; error.errors lists the invalid fields of a validation_error. If a file is deleted or changed after openAsBlob, the call rejects with the runtime's own error.
The client retries only requests the server did not process: queue_full, refused connections, unknown hosts, and 502 or 503 answers from a proxy. Before each retry it waits for Retry-After or an exponential backoff, at most 30 seconds. Timeouts, lost connections and every other error, ocr_rate_limited included, reject at once.
Browsers do not tell connection failures apart and do not expose Retry-After. There the client retries only error answers, with the backoff.
Check the server
health() rejects unless the server is up. ready() returns false when the server is at capacity and rejects when it is unreachable. Both use public routes, so neither verifies the API key.