docstudio/server API reference

Every public export of docstudio/server in DocStudio 0.2.0: functions, constants, types and interfaces with signatures.

Import from docstudio/server.

Storage and service functions return failure results instead of throwing.

Functions

assetResolverFor

Creates an asset resolver for a list of asset identifiers loaded from an asset store.

assetResolverFor(store: AssetStore, sources: readonly string[], maxAssets?: number): Promise<AssetResolver>

checkAsset

Validates an asset against the storage limits and its declared media type.

checkAsset(asset: AssetData, limits: StorageLimits): StorageResult<AssetData>

checkComponentName

Validates a reusable component name.

checkComponentName(name: string): StorageResult<string>

checkId

Validates a storage identifier.

checkId(id: string): StorageResult<string>

checkPublish

Validates a component publish request and computes its hash.

checkPublish(request: ComponentPublishRequest, limits: StorageLimits): StorageResult<{ readonly template: JsonValue; readonly hash: string; }>

checkTemplate

Validates that a value is a storable JSON template within the size limit.

checkTemplate(value: unknown, limits: StorageLimits): StorageResult<JsonValue>

checkVersion

Validates a component version text.

checkVersion(version: string): StorageResult<string>

collectImageSources

Lists the image references a resolved tree uses.

collectImageSources(rdt: unknown): readonly string[]

countPages

Counts the pages of a PDF.

countPages(bytes: Uint8Array<ArrayBufferLike>): number

createFileStorage

Creates a storage adapter that keeps templates, components and assets as files in a directory.

createFileStorage(options: FileStorageOptions): Promise<Storage>

Errors. Rejects when the directory cannot be prepared. Port methods return { ok: false, code, message }.

createHostHandler

Creates the HTTP request listener for the template, component, asset and PDF routes.

createHostHandler(options: HostOptions): HostHandler
import { createServer, type Server } from 'node:http';
import {
  createHostHandler,
  createMemoryStorage,
  createPdfService,
  launchPlaywright,
  type PdfService,
} from 'docstudio/server';

export interface RunningHost {
  readonly server: Server;
  readonly pdf: PdfService;
}

export function startHost(port: number, token: string): RunningHost {
  const storage = createMemoryStorage();
  const pdf = createPdfService({ launchBrowser: () => launchPlaywright() });
  const handler = createHostHandler({
    storage,
    pdf,
    authorize: (request) => request.headers['authorization'] === `Bearer ${token}`,
  });
  const server = createServer(handler);
  server.listen(port, '127.0.0.1');
  return { server, pdf };
}

createMemoryStorage

Creates an in-process storage adapter.

createMemoryStorage(options?: MemoryStorageOptions): Storage
import { createServer, type Server } from 'node:http';
import {
  createHostHandler,
  createMemoryStorage,
  createPdfService,
  launchPlaywright,
  type PdfService,
} from 'docstudio/server';

export interface RunningHost {
  readonly server: Server;
  readonly pdf: PdfService;
}

export function startHost(port: number, token: string): RunningHost {
  const storage = createMemoryStorage();
  const pdf = createPdfService({ launchBrowser: () => launchPlaywright() });
  const handler = createHostHandler({
    storage,
    pdf,
    authorize: (request) => request.headers['authorization'] === `Bearer ${token}`,
  });
  const server = createServer(handler);
  server.listen(port, '127.0.0.1');
  return { server, pdf };
}

createNodeNetwork

Creates the network adapter the PDF service uses for approved remote images.

createNodeNetwork(): NetworkAdapter

createPdfHandler

Creates an HTTP request listener that serves PDF render requests.

createPdfHandler(service: PdfService, options?: HandlerOptions): (request: HttpRequestLike, response: HttpResponseLike) => void

createPdfHttpServer

Creates an HTTP server around the PDF handler.

createPdfHttpServer(service: PdfService, options?: HandlerOptions): HttpServerLike

createPdfService

Creates the PDF service: a Chromium-backed renderer with a queue, limits and request isolation.

createPdfService(options: PdfServiceOptions): PdfService

Errors. render never throws. It returns { ok: false, status, diagnostics } with 400, 413, 429, 500, 503 or 504.

import { compile } from 'docstudio/core';
import { createPdfService, launchPlaywright } from 'docstudio/server';

export async function run(): Promise<{ bytes: number; pages: number }> {
  const compiled = compile({
    template: {
      schemaVersion: '1.0.0',
      body: [{ id: 'hello', type: 'text', content: ['Hello PDF'] }],
    },
    data: {},
  });
  if (compiled.tree === undefined) throw new Error('did not compile');
  const service = createPdfService({
    launchBrowser: () => launchPlaywright(),
    limits: { concurrency: 1, jobTimeoutMs: 30000 },
  });
  try {
    const result = await service.render({ rdt: compiled.tree, options: { title: 'Hello' } });
    if (!result.ok) throw new Error(result.diagnostics.map((item) => item.message).join('; '));
    return { bytes: result.pdf.length, pages: result.pages };
  } finally {
    await service.close();
  }
}

failure

Builds a failed storage result with a code and message.

failure<T>(code: StorageErrorCode, message: string): StorageResult<T>

fetchRemoteImage

Fetches an https image after checking the address, port, credentials and size.

fetchRemoteImage(url: string, network: NetworkAdapter, maxBytes: number, timeoutMs: number): Promise<RemoteImage>

isPdf

Checks that bytes start with the PDF signature.

isPdf(bytes: Uint8Array<ArrayBufferLike>): boolean

isPrivateAddress

Tells whether an address is loopback, private, link-local or otherwise not public.

isPrivateAddress(address: string): boolean

launchPlaywright

Launches Chromium through Playwright and returns the browser handle the PDF service needs.

launchPlaywright(options?: LaunchOptions): Promise<BrowserLike>

Errors. Rejects when Playwright or Chromium is not installed or cannot start.

prepareAssets

Builds the asset resolver for a document, including remote images the network adapter may fetch.

prepareAssets(rdt: unknown, base: AssetResolver | undefined, network: NetworkAdapter, maxRemoteBytes: number): Promise<AssetResolver | undefined>

resolverForDocument

Builds an asset resolver for the assets a resolved tree references.

resolverForDocument(store: AssetStore, rdt: unknown): Promise<AssetResolver>

sizeOf

Computes the serialized size of a JSON value.

sizeOf(value: JsonValue): number

success

Builds a successful storage result.

success<T>(value: T): StorageResult<T>

Constants

ASSET_MIME_TYPES

The image media types the asset store accepts.

const ASSET_MIME_TYPES: readonly string[]

COMPONENT_NAME

The regular expression a component name must match in storage.

const COMPONENT_NAME: RegExp

DEFAULT_HOST_LIMITS

The default limits of the host handler.

const DEFAULT_HOST_LIMITS: HostLimits

DEFAULT_SERVICE_LIMITS

The default limits of the PDF service: concurrency, queue, timeouts and sizes.

const DEFAULT_SERVICE_LIMITS: ServiceLimits

DEFAULT_STORAGE_LIMITS

The default limits of the storage adapters.

const DEFAULT_STORAGE_LIMITS: StorageLimits

DOCUMENT_CSP

The content security policy the PDF service applies to every rendered document.

const DOCUMENT_CSP: "default-src 'none'; img-src data:; font-src data:; style-src 'unsafe-inline'; script-src 'none'; base-uri 'none'; form-action 'none'"

SERVER_DEPENDS_ON

Declares that server depends on core.

const SERVER_DEPENDS_ON: "ds:core"

SERVER_MODULE_ID

The identifier of the server module.

const SERVER_MODULE_ID: "ds:server"

STORAGE_ID

The regular expression a storage identifier must match.

const STORAGE_ID: RegExp

Types

HostHandler

export type HostHandler = (request: HostRequestLike, response: HttpResponseLike) => void;

RemoteImage

export type RemoteImage =
  | { readonly ok: true; readonly mime: string; readonly bytes: Uint8Array }
  | { readonly ok: false; readonly reason: string };

ServiceResult

export type ServiceResult =
  | { readonly ok: true; readonly pdf: Uint8Array; readonly pages: number }
  | {
      readonly ok: false;
      readonly status: number;
      readonly diagnostics: readonly Diagnostic[];
    };

StorageErrorCode

export type StorageErrorCode =
  | 'INVALID_ID'
  | 'INVALID_VALUE'
  | 'NOT_FOUND'
  | 'CONFLICT'
  | 'ALREADY_EXISTS'
  | 'TOO_LARGE'
  | 'LIMIT_EXCEEDED'
  | 'IO_ERROR';

StorageResult

export type StorageResult<T> =
  | { readonly ok: true; readonly value: T }
  | { readonly ok: false; readonly code: StorageErrorCode; readonly message: string };

Interfaces

AssetData

export interface AssetData {
  readonly mime: string;
  readonly bytes: Uint8Array;
}

AssetStore

export interface AssetStore {
  list(): Promise<StorageResult<readonly AssetSummary[]>>;
  get(id: string): Promise<StorageResult<AssetData>>;
  put(id: string, asset: AssetData): Promise<StorageResult<AssetSummary>>;
  delete(id: string): Promise<StorageResult<null>>;
}

AssetSummary

export interface AssetSummary {
  readonly id: string;
  readonly mime: string;
  readonly size: number;
}

BrowserLike

export interface BrowserLike {
  newContext(options: ContextOptionsLike): Promise<ContextLike>;
  close(): Promise<void>;
  isConnected(): boolean;
}

ComponentPublishRequest

export interface ComponentPublishRequest {
  readonly name: string;
  readonly version: string;
  readonly template: JsonValue;
  readonly notes: string;
  readonly publishedAt: string;
}

ComponentStorage

export interface ComponentStorage {
  list(): Promise<StorageResult<readonly ComponentSummary[]>>;
  get(name: string, version: string): Promise<StorageResult<StoredComponent>>;
  publish(request: ComponentPublishRequest): Promise<StorageResult<StoredComponent>>;
}

ComponentSummary

export interface ComponentSummary {
  readonly name: string;
  readonly versions: readonly ComponentVersion[];
}

ComponentVersion

export interface ComponentVersion {
  readonly version: string;
  readonly hash: string;
  readonly notes: string;
  readonly publishedAt: string;
}

ContextLike

export interface ContextLike {
  route(url: string, handler: (route: RouteLike) => unknown): Promise<unknown>;
  newPage(): Promise<PageLike>;
  close(): Promise<void>;
}

ContextOptionsLike

export interface ContextOptionsLike {
  acceptDownloads: boolean;
  serviceWorkers: 'block';
  viewport: { width: number; height: number };
}

FileOperations

export interface FileOperations {
  readonly writeFile: (path: string, data: string | Uint8Array) => Promise<void>;
  readonly rename: (from: string, to: string) => Promise<void>;
  readonly rm: (path: string) => Promise<void>;
}

FileStorageOptions

export interface FileStorageOptions {
  readonly directory: string;
  readonly limits?: Partial<StorageLimits>;
  readonly now?: () => string;
  readonly operations?: Partial<FileOperations>;
}

HandlerOptions

export interface HandlerOptions {
  readonly maxBodyBytes?: number;
  readonly authorize?: (
    headers: Readonly<Record<string, string | string[] | undefined>>,
  ) => boolean;
}

HostLimits

export interface HostLimits {
  readonly maxJsonBytes: number;
  readonly maxAssetBytes: number;
  readonly maxComponentDepth: number;
  readonly maxComponents: number;
}

HostOptions

export interface HostOptions {
  readonly storage: Storage;
  readonly pdf: PdfService;
  readonly authorize?: (request: HostRequestLike) => boolean | Promise<boolean>;
  readonly ready?: () => boolean | Promise<boolean>;
  readonly limits?: Partial<HostLimits>;
}

HostRequestLike

export interface HostRequestLike extends HttpRequestLike {
  readonly url?: string | undefined;
}

HttpRequestLike

export interface HttpRequestLike {
  readonly method?: string | undefined;
  readonly headers: Readonly<Record<string, string | string[] | undefined>>;
  readonly socket: { destroy(): void };
  on(event: 'data', listener: (chunk: Uint8Array) => void): unknown;
  on(event: 'end' | 'error', listener: () => void): unknown;
}

HttpResponseLike

export interface HttpResponseLike {
  readonly headersSent: boolean;
  setHeader(name: string, value: string): unknown;
  writeHead(status: number, headers?: Record<string, string>): unknown;
  end(body?: string | Uint8Array): unknown;
  once(event: 'finish', listener: () => void): unknown;
}

HttpServerLike

export interface HttpServerLike {
  listen(port: number, host: string, listener?: () => void): unknown;
  close(listener?: () => void): unknown;
  address(): string | { readonly port: number } | null;
}

JobLog

export interface JobLog {
  readonly id: number;
  readonly status: number;
  readonly ms: number;
  readonly bytes: number;
  readonly pages: number;
}

LaunchOptions

export interface LaunchOptions {
  readonly args?: readonly string[];
}

MemoryStorageOptions

export interface MemoryStorageOptions {
  readonly limits?: Partial<StorageLimits>;
  readonly now?: () => string;
}

NetworkAdapter

export interface NetworkAdapter {
  lookup(hostname: string): Promise<readonly string[]>;
  get(request: {
    readonly address: string;
    readonly hostname: string;
    readonly port: number;
    readonly path: string;
    readonly timeoutMs: number;
    readonly maxBytes: number;
  }): Promise<RemoteResponse>;
}

PageLike

export interface PageLike {
  goto(url: string, options: { waitUntil: 'load'; timeout: number }): Promise<unknown>;
  evaluate(expression: string): Promise<unknown>;
  pdf(options: PdfOptionsLike): Promise<Uint8Array>;
  on(event: 'crash', handler: () => void): unknown;
  close(): Promise<void>;
}

PdfFeatures

export interface PdfFeatures {
  readonly tagged: boolean;
}

PdfOptionsLike

export interface PdfOptionsLike {
  preferCSSPageSize: boolean;
  printBackground: boolean;
  displayHeaderFooter: boolean;
  tagged: boolean;
  headerTemplate: string;
  footerTemplate: string;
}

PdfService

export interface PdfService {
  render(request: unknown, assets?: AssetResolver): Promise<ServiceResult>;
  stats(): ServiceStats;
  close(): Promise<void>;
}

PdfServiceOptions

export interface PdfServiceOptions {
  readonly launchBrowser: () => Promise<BrowserLike>;
  readonly assets?: AssetResolver;
  readonly fonts?: FontRegistry;
  readonly limits?: Partial<ServiceLimits>;
  readonly features?: Partial<PdfFeatures>;
  readonly network?: NetworkAdapter;
  readonly log?: (entry: JobLog) => void;
}

RemoteResponse

export interface RemoteResponse {
  readonly status: number;
  readonly contentType: string;
  readonly body: Uint8Array;
}

RequestLike

export interface RequestLike {
  url(): string;
}

RouteLike

export interface RouteLike {
  request(): RequestLike;
  fulfill(options: {
    status: number;
    contentType: string;
    headers: Record<string, string>;
    body: string;
  }): Promise<void>;
  abort(): Promise<void>;
}

ServiceLimits

export interface ServiceLimits {
  readonly concurrency: number;
  readonly queueSize: number;
  readonly jobTimeoutMs: number;
  readonly maxRequestChars: number;
  readonly maxPdfBytes: number;
  readonly recycleAfterJobs: number;
  readonly maxRemoteImageBytes: number;
}

ServiceStats

export interface ServiceStats {
  readonly running: number;
  readonly queued: number;
  readonly launches: number;
  readonly completed: number;
}

Storage

export interface Storage {
  readonly templates: TemplateStore;
  readonly components: ComponentStorage;
  readonly assets: AssetStore;
}

StorageLimits

export interface StorageLimits {
  readonly maxTemplateBytes: number;
  readonly maxAssetBytes: number;
  readonly maxNotesChars: number;
  readonly maxItems: number;
}

StoredComponent

export interface StoredComponent extends ComponentVersion {
  readonly name: string;
  readonly template: JsonValue;
}

StoredTemplate

export interface StoredTemplate extends TemplateSummary {
  readonly template: JsonValue;
}

TemplateStore

export interface TemplateStore {
  list(): Promise<StorageResult<readonly TemplateSummary[]>>;
  get(id: string): Promise<StorageResult<StoredTemplate>>;
  save(
    id: string,
    template: JsonValue,
    expectedRevision: number,
  ): Promise<StorageResult<StoredTemplate>>;
  delete(id: string): Promise<StorageResult<null>>;
}

TemplateSummary

export interface TemplateSummary {
  readonly id: string;
  readonly revision: number;
  readonly updatedAt: string;
}