@molecule/api-web-content-molecule
Provider bond · web-content · API (Node) · v1.1.2 · Apache-2.0
molecule.dev hosted web content — fetch a page or extract readable content, billed to your molecule project, no vendor account
npm install @molecule/api-web-content-moleculenpm · Source on GitHub · Implements @molecule/api-web-content
How it works
@molecule/api-web-content-molecule is a provider bond on the API (Node) side: it implements the web-content core interface (@molecule/api-web-content) 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-secrets, @molecule/api-web-content
Secrets: MOLECULE_API_KEY
Reference
molecule.dev hosted web content — fetch a page or extract readable content, 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-web-content-molecule @molecule/api-web-content @molecule/api-secrets
API
Interfaces
MoleculeWebContentConfig
Options for createProvider(). Every field falls back to its env var.
interface MoleculeWebContentConfig {
/**
* A molecule project API key (`mk_…`) or the in-sandbox token (`mbk_…`),
* scope `broker` or `broker:web-content`. 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 `browser`-mode fetch renders a page. */
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
}
}
MoleculeWebContentProvider
Web content provider backed by molecule.dev's hosted service.
The hosted machine fetches HTTP(S) targets from PUBLIC addresses only — loopback, private-network and link-local targets are refused before any connection — so a user-supplied URL cannot reach your network from molecule's render machine.
class MoleculeWebContentProvider implements WebContentProvider {
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: MoleculeWebContentConfig = {}) {
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
}
/** Reads one page on the hosted service and returns its readable content. */
async fetch(
source: { url: string } & Partial<{ html: string; baseUrl: string }>,
options?: WebContentOptions,
): Promise<WebContentResult> {
const plan = this.plan(source, options)
if (plan.url === undefined) {
throw new MoleculeServiceError(
'Pass exactly one of "url" or "html".',
400,
'hostedServices.error.invalidInput',
)
}
return this.request('web-content/fetch', {
url: plan.url,
...(plan.options !== undefined ? { options: plan.options } : {}),
})
}
/** Extracts readable content from HTML the caller already has — no page is fetched. */
async extract(
source: { html: string; baseUrl?: string } & Partial<{ url: string }>,
options?: WebContentOptions,
): Promise<WebContentResult> {
const plan = this.plan(source, options)
if (plan.html === undefined) {
throw new MoleculeServiceError(
'Pass exactly one of "url" or "html".',
400,
'hostedServices.error.invalidInput',
)
}
return this.request('web-content/extract', {
html: plan.html,
...(plan.baseUrl !== undefined ? { baseUrl: plan.baseUrl } : {}),
...(plan.options !== undefined ? { options: plan.options } : {}),
})
}
/** Validates one read locally, so a bad call never leaves the process. */
private plan(
source: { url?: string; html?: string; baseUrl?: string },
options?: WebContentOptions,
): { url?: string; html?: string; baseUrl?: string; options?: Record<string, unknown> } {
if (typeof source !== 'object' || source === null) {
throw new MoleculeServiceError(
'Pass exactly one of "url" or "html".',
400,
'hostedServices.error.invalidInput',
)
}
const { url, html, baseUrl } = source
if ((typeof url === 'string') === (typeof html === 'string')) {
throw new MoleculeServiceError(
'Pass exactly one of "url" or "html".',
400,
'hostedServices.error.invalidInput',
)
}
if (url !== undefined) {
if (url.length === 0 || url.length > WEB_CONTENT_SERVICE_LIMITS.maxUrlChars) {
throw new MoleculeServiceError(
`"url" must be 1-${WEB_CONTENT_SERVICE_LIMITS.maxUrlChars} characters.`,
400,
'hostedServices.error.invalidInput',
)
}
try {
const parsed = new URL(url)
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') throw new Error('scheme')
} catch (_error) {
// Intentional: the parse failure becomes the field error below.
throw new MoleculeServiceError(
'"url" must be an absolute http(s) URL.',
400,
'hostedServices.error.invalidInput',
)
}
}
if (html !== undefined) {
if (html.length === 0) {
throw new MoleculeServiceError(
'"html" must be non-empty text.',
400,
'hostedServices.error.invalidInput',
)
}
if (html.length > WEB_CONTENT_SERVICE_LIMITS.maxHtmlChars) {
throw new MoleculeServiceError(
`"html" is ${html.length} characters; the limit is ${WEB_CONTENT_SERVICE_LIMITS.maxHtmlChars}.`,
413,
'hostedServices.error.inputTooLarge',
)
}
}
if (baseUrl !== undefined) {
try {
const parsed = new URL(baseUrl)
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') throw new Error('scheme')
} catch (_error) {
// Intentional: the parse failure becomes the field error below.
throw new MoleculeServiceError(
'"baseUrl" must be an absolute http(s) URL.',
400,
'hostedServices.error.invalidInput',
)
}
}
let out: Record<string, unknown> | undefined
if (options !== undefined) {
if (typeof options !== 'object' || options === null) {
throw new MoleculeServiceError(
'"options" must be an object.',
400,
'hostedServices.error.invalidInput',
)
}
const o = options as Record<string, unknown>
out = {}
if (o.mode !== undefined) {
if (o.mode !== 'raw' && o.mode !== 'browser') {
throw new MoleculeServiceError(
'"options.mode" must be "raw" or "browser".',
400,
'hostedServices.error.invalidInput',
)
}
out.mode = o.mode
}
if (o.format !== undefined) {
if (o.format !== 'markdown' && o.format !== 'text') {
throw new MoleculeServiceError(
'"options.format" must be "markdown" or "text".',
400,
'hostedServices.error.invalidInput',
)
}
out.format = o.format
}
if (o.includeLinks !== undefined) {
if (typeof o.includeLinks !== 'boolean') {
throw new MoleculeServiceError(
'"options.includeLinks" must be a boolean.',
400,
'hostedServices.error.invalidInput',
)
}
out.includeLinks = o.includeLinks
}
if (o.settleMs !== undefined) {
if (
!Number.isInteger(o.settleMs) ||
(o.settleMs as number) < 0 ||
(o.settleMs as number) > WEB_CONTENT_SERVICE_LIMITS.maxSettleMs
) {
throw new MoleculeServiceError(
`"options.settleMs" must be an integer from 0 to ${WEB_CONTENT_SERVICE_LIMITS.maxSettleMs}.`,
400,
'hostedServices.error.invalidInput',
)
}
out.settleMs = o.settleMs
}
}
return { url, html, baseUrl, options: out }
}
/** One POST to the hosted service. */
private async request(path: string, body: Record<string, unknown>): Promise<WebContentResult> {
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 WebContentResult
if (typeof result.content !== 'string') {
throw new MoleculeServiceError(
'molecule.dev returned no content.',
502,
'hostedServices.error.upstreamFailed',
)
}
return result
}
}
(The 2 longest member comments are shortened to their first sentence to fit; the full declaration is in node_modules/@molecule/api-web-content-molecule/dist/provider.d.ts.)
Functions
createProvider(config)
Create a hosted web content provider.
function createProvider(config?: MoleculeWebContentConfig): WebContentProvider
config— Options; each falls back to its env var.
Returns: A WebContentProvider backed by molecule.dev.
Constants
provider
The provider implementation (wire with setProvider).
const provider: WebContentProvider
DEFAULT_SERVICES_URL
Default hosted services base URL.
const DEFAULT_SERVICES_URL: 'https://api.molecule.dev/api/v1/services'
WEB_CONTENT_SERVICE_LIMITS
Per-request limits of the hosted service (mirrored for local refusal).
const WEB_CONTENT_SERVICE_LIMITS: {
readonly maxUrlChars: 2048
readonly maxHtmlChars: 2000000
readonly maxContentChars: 500000
readonly maxLinks: 200
readonly maxSettleMs: 5000
}
webContentMoleculeSecretDefinitions
Secret definitions required by the molecule.dev hosted web content bond.
const webContentMoleculeSecretDefinitions: SecretDefinition[]
Core Interface
Implements @molecule/api-web-content interface.
Bond Wiring
Setup function to register this provider with the core interface:
import { setProvider } from '@molecule/api-web-content'
import { provider } from '@molecule/api-web-content-molecule'
export function setupWebContentMolecule(): void {
setProvider(provider)
}
Injection Notes
Requirements
Peer dependencies:
@molecule/api-secrets^1.0.1@molecule/api-web-content>=1.0.0
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-web-content@molecule/api-secrets