Skip to content
← Public packages

@kody/onetimefax

Head-start stub for sending faxes from Kody with the Onetime Fax developer API. Fork it and add your API key.

FollowFork

Files

prepare-fax.ts

239 lines · 7.0 KB · TypeScript
import {
	array,
	boolean,
	number,
	object,
	optional,
	parseSafe,
	string,
} from 'remix/data-schema'
import {
	inputError,
	onetimefaxRequest,
	type OnetimeFax,
	type OnetimeFaxFile,
} from './client.ts'
import { readFax, summarizeFax, type FaxStatusResult } from './fax-status.ts'

/** The Onetime Fax MCP announcement lists 25 MB per file. */
const MAX_FILE_BYTES = 25 * 1024 * 1024
const DEFAULT_WAIT_MS = 30_000
const MAX_WAIT_MS = 120_000
const POLL_INTERVAL_MS = 2_000

const fileInput = object(
	{
		filename: string(),
		contentType: optional(string()),
		base64: optional(string()),
		text: optional(string()),
		url: optional(string()),
	},
	{ unknownKeys: 'error' },
)

const prepareFaxInput = object(
	{
		recipientNumber: string(),
		files: array(fileInput),
		waitForQuoteMs: optional(number()),
		dryRun: optional(boolean()),
	},
	{ unknownKeys: 'error' },
)

type FileInput = {
	filename: string
	contentType?: string
	base64?: string
	text?: string
	url?: string
}

export type PrepareFaxResult = FaxStatusResult & {
	dryRun: false
	/** True when every file is processed and a quote is available. */
	readyToSend: boolean
	uploaded: OnetimeFaxFile[]
	next: string
}

export type PrepareFaxDryRun = {
	dryRun: true
	wouldCreateDraftFor: string
	files: Array<{ filename: string; source: 'base64' | 'text' | 'url' }>
	note: string
}

const E164 = /^\+[1-9]\d{6,14}$/

function normalizeRecipient(value: string) {
	const compact = value.replace(/[\s().-]/g, '')
	if (!E164.test(compact)) {
		throw new Error(
			'recipientNumber must be an E.164 number such as +14155551212 (plus sign, country code, number).',
		)
	}
	return compact
}

function fileSource(file: FileInput): 'base64' | 'text' | 'url' {
	const sources = (['base64', 'text', 'url'] as const).filter(
		(key) => typeof file[key] === 'string',
	)
	if (sources.length !== 1) {
		throw new Error(
			`File "${file.filename}" needs exactly one of base64, text, or url.`,
		)
	}
	const source = sources[0]
	if (source === 'url') {
		let parsed: URL
		try {
			parsed = new URL(file.url as string)
		} catch {
			throw new Error(`File "${file.filename}" url is not a valid URL.`)
		}
		if (parsed.protocol !== 'https:') {
			throw new Error(`File "${file.filename}" url must use https.`)
		}
	}
	return source
}

function base64ToBytes(value: string) {
	const clean = value.replace(/^data:[^,]*,/, '').replace(/\s+/g, '')
	const binary = atob(clean)
	const bytes = new Uint8Array(binary.length)
	for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)
	return bytes
}

async function fileToBlob(file: FileInput, source: 'base64' | 'text' | 'url') {
	if (source === 'text') {
		return new Blob([file.text as string], {
			type: file.contentType ?? 'text/plain',
		})
	}
	if (source === 'base64') {
		return new Blob([base64ToBytes(file.base64 as string)], {
			type: file.contentType ?? 'application/pdf',
		})
	}
	// Plain fetch with no credential: the document URL never sees the API key.
	const response = await fetch(file.url as string)
	if (!response.ok) {
		throw new Error(
			`Could not download "${file.filename}" (HTTP ${response.status}).`,
		)
	}
	const blob = await response.blob()
	return file.contentType ? new Blob([blob], { type: file.contentType }) : blob
}

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))

/**
 * Prepare a fax without spending credits: create a draft for the recipient,
 * upload the documents, and wait for Onetime Fax to count pages and quote a
 * price. Use this first, show the person the recipient, files, page count,
 * and price, then call `./send-fax` with the returned `faxId` and `confirm: true`.
 *
 * Wraps `POST /api/v1/faxes`, `POST /api/v1/faxes/{id}/files` (multipart
 * `file` field), and `GET /api/v1/faxes/{id}` (https://www.onetimefax.com/developers/).
 *
 * @param input.recipientNumber - E.164 fax number, e.g. `+14155551212`
 * @param input.files - One or more `{ filename, contentType?, base64 | text | url }`. `url` must be public HTTPS and is downloaded without your API key. Max 25 MB each.
 * @param input.waitForQuoteMs - How long to poll for the quote (default 30000, max 120000). 0 returns right after upload.
 * @param input.dryRun - Validate input and describe the plan without calling Onetime Fax
 * @returns Draft summary with `faxId`, `quote` (`priceCents`, `creditBalanceCents`, `shortfallCents`), `readyToSend`, and `uploaded` files
 *
 * @example
 * import prepareFax from 'kody:@kody/onetimefax/prepare-fax'
 *
 * const draft = await prepareFax({
 *   recipientNumber: '+14155551212',
 *   files: [{ filename: 'hello.txt', contentType: 'text/plain', text: 'Hello from Kody' }],
 * })
 */
export default async function prepareFax(
	raw: unknown,
): Promise<PrepareFaxResult | PrepareFaxDryRun> {
	const parsed = parseSafe(prepareFaxInput, raw)
	if (!parsed.success) {
		throw inputError(
			'prepare-fax',
			'recipientNumber, files[{ filename, contentType, base64 | text | url }], waitForQuoteMs, dryRun',
			parsed.issues,
		)
	}
	const input = parsed.value
	const recipientNumber = normalizeRecipient(input.recipientNumber)
	const files: FileInput[] = input.files
	if (files.length === 0) {
		throw new Error('files must include at least one document.')
	}
	const sources = files.map((file: FileInput) => fileSource(file))
	const waitForQuoteMs = Math.min(
		Math.max(input.waitForQuoteMs ?? DEFAULT_WAIT_MS, 0),
		MAX_WAIT_MS,
	)

	if (input.dryRun === true) {
		return {
			dryRun: true,
			wouldCreateDraftFor: recipientNumber,
			files: files.map((file: FileInput, index: number) => ({
				filename: file.filename,
				source: sources[index],
			})),
			note: 'Dry run. No draft was created and no credits were spent.',
		}
	}

	const created = await onetimefaxRequest<{ fax: OnetimeFax }>(
		'POST',
		'/api/v1/faxes',
		{ json: { recipientNumber } },
	)
	const faxId = created.data.fax.id

	const uploaded: OnetimeFaxFile[] = []
	for (const [index, file] of files.entries()) {
		const blob = await fileToBlob(file, sources[index])
		if (blob.size > MAX_FILE_BYTES) {
			throw new Error(
				`File "${file.filename}" is ${blob.size} bytes. Onetime Fax accepts up to 25 MB per file. Draft ${faxId} was created; remove or replace files before sending.`,
			)
		}
		const form = new FormData()
		form.append('file', blob, file.filename)
		const result = await onetimefaxRequest<{ file: OnetimeFaxFile }>(
			'POST',
			`/api/v1/faxes/${encodeURIComponent(faxId)}/files`,
			{ formData: form },
		)
		uploaded.push(result.data.file)
	}

	const deadline = Date.now() + waitForQuoteMs
	let summary = summarizeFax(await readFax(faxId))
	while (
		!(summary.filesReady && summary.quote) &&
		Date.now() + POLL_INTERVAL_MS <= deadline
	) {
		await sleep(POLL_INTERVAL_MS)
		summary = summarizeFax(await readFax(faxId))
	}

	const readyToSend = Boolean(summary.filesReady && summary.quote)
	return {
		...summary,
		dryRun: false,
		readyToSend,
		uploaded,
		next: readyToSend
			? `Show the recipient, files, page count, and price. Then call ./send-fax with { faxId: "${faxId}", confirm: true }.`
			: `Files are still processing. Call ./fax-status with { faxId: "${faxId}" } until quote is set, then ./send-fax.`,
	}
}