@molecule/api-document-text-molecule
Provider bond · pdf · API (Node) · v1.1.0 · Apache-2.0
molecule.dev hosted document text — extract the text of a PDF document, billed to your molecule project, no vendor account
npm install @molecule/api-document-text-moleculenpm · Source on GitHub · Implements @molecule/api-document-text
How it works
@molecule/api-document-text-molecule is a provider bond on the API (Node) side: it implements the pdf core interface (@molecule/api-document-text) with a concrete vendor or library behind it.
Your code calls the core; you wire this provider once at startup. Swapping vendors later is one line in that wiring, not a rewrite.
Works with: @molecule/api-document-text, @molecule/api-secrets
Secrets: MOLECULE_API_KEY
Reference
molecule.dev hosted document text — extract the text of a PDF document, billed to your molecule project, no vendor account
Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit
src/index.tsJSDoc, not this file.
Type
provider
Installation
npm install @molecule/api-document-text-molecule @molecule/api-document-text @molecule/api-secrets
API
Interfaces
MoleculeDocumentTextConfig
Options for createProvider(). Every field falls back to its env var.
interface MoleculeDocumentTextConfig {
/**
* A molecule project API key (`mk_…`) or the in-sandbox token (`mbk_…`),
* scope `broker` or `broker:pdf`. Defaults to
* `process.env.MOLECULE_API_KEY`.
*/
apiKey?: string
/**
* The hosted services base URL. Defaults to
* `process.env.MOLECULE_SERVICES_URL`, then
* `https://api.molecule.dev/api/v1/services`.
*/
servicesUrl?: string
/** Per-call timeout in milliseconds. Defaults to `60_000` — a large document parses in seconds. */
timeoutMs?: number
}
Classes
MoleculeServiceError
Error thrown for a refused or failed hosted-service call.
class MoleculeServiceError extends Error {
/** HTTP status from molecule.dev. */
readonly status: number
/** Stable error key from molecule.dev. */
readonly errorKey: string | undefined
/**
* Create the error.
*
* @param message - Human-readable message.
* @param status - HTTP status.
* @param errorKey - Stable error key, when the service sent one.
* @param cause - The underlying error, if any.
*/
constructor(message: string, status: number, errorKey?: string, cause?: unknown) {
super(message, cause === undefined ? undefined : { cause })
this.name = 'MoleculeServiceError'
this.status = status
this.errorKey = errorKey
}
}
MoleculeDocumentTextProvider
Document text provider backed by molecule.dev's hosted service.
The bytes are parsed by pdf.js in the API process — nothing about the document leaves molecule's infrastructure except the extracted text in the response.
class MoleculeDocumentTextProvider implements DocumentTextProvider {
readonly name = 'molecule'
private readonly apiKey: string
private readonly servicesUrl: string
private readonly timeoutMs: number
/**
* Create the provider.
*
* @param config - Options; each falls back to its env var.
*/
constructor(config: MoleculeDocumentTextConfig = {}) {
this.apiKey = config.apiKey ?? process.env.MOLECULE_API_KEY ?? ''
this.servicesUrl = resolveServicesUrl(
config.servicesUrl ?? process.env.MOLECULE_SERVICES_URL ?? DEFAULT_SERVICES_URL,
)
this.timeoutMs = config.timeoutMs ?? 60_000
}
/**
* Extracts the text of one PDF document on the hosted service.
*
* @param input - The document bytes, plus a password for an encrypted document.
* @param options - Extract options (page bound, per-page texts).
* @returns The extracted text.
*/
async extract(
input: { data: Uint8Array; password?: string },
options?: DocumentTextOptions,
): Promise<DocumentTextResult> {
const body = this.plan(input, options)
return this.request('pdf/to-text', body)
}
/** Validates one extraction locally, so a bad call never leaves the process. */
private plan(
input: { data?: Uint8Array; password?: string },
options?: DocumentTextOptions,
): Record<string, unknown> {
if (typeof input !== 'object' || input === null || !(input.data instanceof Uint8Array)) {
throw new MoleculeServiceError(
'"data" must be non-empty PDF bytes (Uint8Array or Buffer).',
400,
'hostedServices.error.invalidInput',
)
}
if (input.data.length === 0) {
throw new MoleculeServiceError(
'"data" must be non-empty PDF bytes (Uint8Array or Buffer).',
400,
'hostedServices.error.invalidInput',
)
}
if (input.data.length > DOCUMENT_TEXT_SERVICE_LIMITS.maxPdfBytes) {
throw new MoleculeServiceError(
`The document is ${input.data.length} bytes; the limit is ${DOCUMENT_TEXT_SERVICE_LIMITS.maxPdfBytes}.`,
413,
'hostedServices.error.inputTooLarge',
)
}
const out: Record<string, unknown> = { pdf: Buffer.from(input.data).toString('base64') }
if (input.password !== undefined || options !== undefined) {
const opt: Record<string, unknown> = {}
if (input.password !== undefined) {
if (typeof input.password !== 'string' || input.password.length === 0) {
throw new MoleculeServiceError(
'"password" must be non-empty text when given.',
400,
'hostedServices.error.invalidInput',
)
}
if (input.password.length > DOCUMENT_TEXT_SERVICE_LIMITS.maxPasswordChars) {
throw new MoleculeServiceError(
`"password" is ${input.password.length} characters; the limit is ${DOCUMENT_TEXT_SERVICE_LIMITS.maxPasswordChars}.`,
400,
'hostedServices.error.invalidInput',
)
}
opt.password = input.password
}
if (options !== undefined) {
if (typeof options !== 'object' || options === null) {
throw new MoleculeServiceError(
'"options" must be an object.',
400,
'hostedServices.error.invalidInput',
)
}
if (options.maxPages !== undefined) {
if (
typeof options.maxPages !== 'number' ||
!Number.isInteger(options.maxPages) ||
options.maxPages < 1 ||
options.maxPages > DOCUMENT_TEXT_SERVICE_LIMITS.maxPages
) {
throw new MoleculeServiceError(
`"options.maxPages" must be an integer from 1 to ${DOCUMENT_TEXT_SERVICE_LIMITS.maxPages}.`,
400,
'hostedServices.error.invalidInput',
)
}
opt.maxPages = options.maxPages
}
if (options.includePages !== undefined) {
if (typeof options.includePages !== 'boolean') {
throw new MoleculeServiceError(
'"options.includePages" must be a boolean.',
400,
'hostedServices.error.invalidInput',
)
}
opt.includePages = options.includePages
}
}
if (Object.keys(opt).length > 0) out.options = opt
}
return out
}
/** One POST to the hosted service. */
private async request(path: string, body: Record<string, unknown>): Promise<DocumentTextResult> {
if (!this.apiKey) {
throw new MoleculeServiceError(
'MOLECULE_API_KEY is not set. Create a project API key on molecule.dev (or with `mlcl apikey create`) and put it in the API .env.',
401,
'hostedServices.error.tokenInvalid',
)
}
const response = await fetch(`${this.servicesUrl}/${path}`, {
method: 'POST',
headers: { authorization: `Bearer ${this.apiKey}`, 'content-type': 'application/json' },
body: JSON.stringify(body),
signal: AbortSignal.timeout(this.timeoutMs),
})
const text = await response.text()
let data: unknown
try {
data = text ? JSON.parse(text) : {}
} catch (error) {
throw new MoleculeServiceError(
`molecule.dev returned ${response.status} with a non-JSON body.`,
response.status,
undefined,
error,
)
}
if (!response.ok) {
const err = data as { error?: string; errorKey?: string }
const hint = HINTS[response.status]
throw new MoleculeServiceError(
`molecule.dev ${path} failed (${response.status}): ${err.error ?? 'error'}${hint ? ` ${hint}` : ''}`,
response.status,
err.errorKey,
)
}
const result = data as DocumentTextResult
if (typeof result.text !== 'string' || typeof result.pageCount !== 'number') {
throw new MoleculeServiceError(
'molecule.dev returned no extracted text.',
502,
'hostedServices.error.upstreamFailed',
)
}
return result
}
}
Functions
createProvider(config)
Create a hosted document text provider.
function createProvider(config?: MoleculeDocumentTextConfig): DocumentTextProvider
config— Options; each falls back to its env var.
Returns: A DocumentTextProvider backed by molecule.dev.
Constants
provider
The provider implementation (wire with setProvider).
const provider: DocumentTextProvider
DEFAULT_SERVICES_URL
Default hosted services base URL.
const DEFAULT_SERVICES_URL: 'https://api.molecule.dev/api/v1/services'
DOCUMENT_TEXT_SERVICE_LIMITS
Per-request limits of the hosted service (mirrored for local refusal).
const DOCUMENT_TEXT_SERVICE_LIMITS: {
readonly maxPdfBytes: number
readonly maxTextChars: 500000
readonly maxPages: 500
readonly maxPasswordChars: 256
}
documentTextMoleculeSecretDefinitions
Secret definitions required by the molecule.dev hosted document text bond.
const documentTextMoleculeSecretDefinitions: SecretDefinition[]
Core Interface
Implements @molecule/api-document-text interface.
Bond Wiring
Setup function to register this provider with the core interface:
import { setProvider } from '@molecule/api-document-text'
import { provider } from '@molecule/api-document-text-molecule'
export function setupDocumentTextMolecule(): void {
setProvider(provider)
}
Injection Notes
Requirements
Peer dependencies:
@molecule/api-document-text>=1.0.0@molecule/api-secrets^1.0.1
Environment Variables
MOLECULE_API_KEY(required) — molecule.dev project API key- Setup: Create one for your project with
mlcl apikey create --project <id> --name <name>(keys start with mk_). - Get it here: https://www.molecule.dev
- Example:
mk_...
- Setup: Create one for your project with
Runtime Dependencies
@molecule/api-document-text@molecule/api-secrets