← 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.
Files
import assert from 'node:assert/strict'
import { afterEach, test } from 'node:test'
import getAccount from '../src/account.ts'
import faxStatus from '../src/fax-status.ts'
import prepareFax from '../src/prepare-fax.ts'
import removeFile from '../src/remove-file.ts'
import sendFax from '../src/send-fax.ts'
type Call = { url: string; method: string; headers: Record<string, string>; body: unknown }
const realFetch = globalThis.fetch
let calls: Call[] = []
function mockFetch(handler: (call: Call) => { status?: number; json?: unknown }) {
calls = []
globalThis.fetch = (async (url: string, init: RequestInit = {}) => {
const call: Call = {
url: String(url),
method: init.method ?? 'GET',
headers: (init.headers ?? {}) as Record<string, string>,
body: init.body,
}
calls.push(call)
const { status = 200, json } = handler(call)
return new Response(status === 204 ? null : JSON.stringify(json ?? {}), {
status,
headers: { 'content-type': 'application/json' },
})
}) as typeof fetch
}
afterEach(() => {
globalThis.fetch = realFetch
})
const readyFax = {
id: 'cmr4abc',
recipientNumber: '+14155551212',
status: 'draft',
files: [{ id: 'cmr5def', filename: 'hello.txt', status: 'ready', pageCount: 1 }],
pageCount: 1,
quote: { priceCents: 500, creditBalanceCents: 1000, shortfallCents: 0 },
creditsConsumedCents: null,
}
test('account sends the bearer placeholder, headers-only, to app.onetimefax.com', async () => {
mockFetch(() => ({ json: { account: { creditBalanceCents: 2500 } } }))
const result = await getAccount({})
assert.equal(result.account.creditBalanceCents, 2500)
assert.equal(calls[0].url, 'https://app.onetimefax.com/api/v1/account')
assert.equal(calls[0].headers.Authorization, 'Bearer {{secret:onetimefax-api-token}}')
assert.equal(calls[0].headers['x-kody-secret-resolution'], 'headers-only')
})
test('exports reject unknown keys', async () => {
await assert.rejects(() => getAccount({ extra: 1 }), /input rejected/)
await assert.rejects(() => faxStatus({ faxId: 'a', id: 'b' }), /input rejected/)
await assert.rejects(() => sendFax({ faxId: 'a', confirmed: true }), /input rejected/)
await assert.rejects(
() => prepareFax({ recipientNumber: '+14155551212', files: [], to: 'x' }),
/input rejected/,
)
})
test('fax-status rejects ids that are not path safe', async () => {
await assert.rejects(() => faxStatus({ faxId: '../account' }), /faxId must be/)
})
test('fax-status summarizes the documented GET response', async () => {
mockFetch(() => ({ json: { fax: readyFax } }))
const status = await faxStatus({ faxId: 'cmr4abc' })
assert.equal(calls[0].url, 'https://app.onetimefax.com/api/v1/faxes/cmr4abc')
assert.equal(status.filesReady, true)
assert.equal(status.quote?.priceCents, 500)
})
test('prepare-fax dryRun makes no network calls', async () => {
mockFetch(() => ({ json: {} }))
const result = await prepareFax({
recipientNumber: '+1 (415) 555-1212',
files: [{ filename: 'a.txt', text: 'hi' }],
dryRun: true,
})
assert.equal(result.dryRun, true)
assert.equal(calls.length, 0)
if (result.dryRun) assert.equal(result.wouldCreateDraftFor, '+14155551212')
})
test('prepare-fax validates recipient and file sources', async () => {
await assert.rejects(
() => prepareFax({ recipientNumber: '555-1212', files: [{ filename: 'a', text: 'x' }] }),
/E\.164/,
)
await assert.rejects(
() =>
prepareFax({
recipientNumber: '+14155551212',
files: [{ filename: 'a', text: 'x', base64: 'eA==' }],
}),
/exactly one/,
)
await assert.rejects(
() =>
prepareFax({
recipientNumber: '+14155551212',
files: [{ filename: 'a', url: 'http://example.com/a.pdf' }],
}),
/https/,
)
})
test('prepare-fax creates a draft, uploads multipart, and returns the quote', async () => {
mockFetch((call) => {
if (call.method === 'POST' && call.url.endsWith('/api/v1/faxes')) {
return { json: { fax: { id: 'cmr4abc', status: 'draft' } } }
}
if (call.method === 'POST' && call.url.endsWith('/files')) {
return { json: { file: { id: 'cmr5def', filename: 'hello.txt', status: 'uploaded' } } }
}
return { json: { fax: readyFax } }
})
const result = await prepareFax({
recipientNumber: '+14155551212',
files: [{ filename: 'hello.txt', text: 'Hello' }],
})
assert.equal(result.dryRun, false)
if (!result.dryRun) {
assert.equal(result.readyToSend, true)
assert.equal(result.faxId, 'cmr4abc')
}
assert.deepEqual(JSON.parse(String(calls[0].body)), { recipientNumber: '+14155551212' })
assert.ok(calls[1].body instanceof FormData)
assert.ok((calls[1].body as FormData).get('file') instanceof Blob)
assert.equal(calls[1].headers['Content-Type'], undefined)
})
test('send-fax without confirm only previews', async () => {
mockFetch(() => ({ json: { fax: readyFax } }))
const result = await sendFax({ faxId: 'cmr4abc' })
assert.equal(result.sent, false)
assert.equal(calls.length, 1)
assert.equal(calls[0].method, 'GET')
})
test('send-fax dryRun wins over confirm', async () => {
mockFetch(() => ({ json: { fax: readyFax } }))
const result = await sendFax({ faxId: 'cmr4abc', confirm: true, dryRun: true })
assert.equal(result.sent, false)
assert.ok(calls.every((call) => call.method === 'GET'))
})
test('send-fax refuses above maxPriceCents and on shortfall', async () => {
mockFetch(() => ({ json: { fax: readyFax } }))
await assert.rejects(
() => sendFax({ faxId: 'cmr4abc', confirm: true, maxPriceCents: 100 }),
/above maxPriceCents/,
)
mockFetch(() => ({
json: { fax: { ...readyFax, quote: { priceCents: 500, creditBalanceCents: 0, shortfallCents: 500 } } },
}))
await assert.rejects(() => sendFax({ faxId: 'cmr4abc', confirm: true }), /Add credits/)
assert.ok(calls.every((call) => call.method === 'GET'))
})
test('send-fax with confirm posts send and reports the charge', async () => {
mockFetch((call) =>
call.method === 'POST'
? {
json: {
fax: { id: 'cmr4abc', status: 'queued' },
creditsConsumedCents: 500,
creditBalanceCents: 500,
replayed: false,
},
}
: { json: { fax: readyFax } },
)
const result = await sendFax({ faxId: 'cmr4abc', confirm: true, maxPriceCents: 500 })
assert.equal(result.sent, true)
if (result.sent) {
assert.equal(result.status, 'queued')
assert.equal(result.creditsConsumedCents, 500)
}
assert.equal(calls[1].url, 'https://app.onetimefax.com/api/v1/faxes/cmr4abc/send')
})
test('API errors surface status and body', async () => {
mockFetch(() => ({ status: 402, json: { error: 'insufficient_credits', shortfallCents: 200 } }))
await assert.rejects(() => faxStatus({ faxId: 'cmr4abc' }), /HTTP 402.*shortfallCents/)
})
test('remove-file sends DELETE and handles 204', async () => {
mockFetch(() => ({ status: 204 }))
const result = await removeFile({ faxId: 'cmr4abc', fileId: 'cmr5def' })
assert.equal(result.removed, true)
assert.equal(calls[0].method, 'DELETE')
assert.equal(calls[0].url, 'https://app.onetimefax.com/api/v1/faxes/cmr4abc/files/cmr5def')
})