import { AudibleApiError, NotConnectedError } from '../src/errors.ts'
import { resolveLocale } from '../src/locales.ts'
import { allowedBody, allowedQuery, buildQuery, isAllowedCall, WISHLIST_REMOVE, type QueryValue, type WishlistBody } from '../src/policy.ts'
import type { AudibleCall } from '../src/request.ts'
import { loadAccount, saveAccount, type FakeAccount } from './state.ts'
export { AudibleApiError }
const page = (rows: unknown[], size: number, index: number) => rows.slice(index * size, (index + 1) * size)
const num = (value: QueryValue, fallback: number) => (value == null || value === '' ? fallback : Number(value))
function notFound(method: string, pathWithQuery: string): never {
throw new AudibleApiError(404, `Audible API ${method} ${pathWithQuery} → HTTP 404 (body: empty)`)
}
function serve(account: FakeAccount, method: string, path: string, query: Record<string, QueryValue>, body: WishlistBody | undefined, pathWithQuery: string) {
if (method === 'GET' && path === '/1.0/library') {
const size = num(query.num_results, 50)
const title = typeof query.title === 'string' ? query.title.toLowerCase() : ''
const rows = title ? account.library.filter((i) => String(i.title ?? '').toLowerCase().includes(title)) : account.library
return { items: page(rows, size, num(query.page, 1) - 1), total_results: rows.length }
}
if (method === 'GET' && path.startsWith('/1.0/library/')) {
const item = account.library.find((i) => i.asin === path.slice('/1.0/library/'.length))
return item ? { item } : notFound(method, pathWithQuery)
}
if (method === 'GET' && path === '/1.0/wishlist') {
const size = num(query.num_results, 20)
return { products: page(account.wishlist, size, num(query.page, 0)), total_results: account.wishlist.length }
}
if (method === 'POST' && body) {
const { asin } = body
if (!account.wishlist.some((p) => p.asin === asin)) account.wishlist.unshift({ asin })
return null
}
if (method === 'DELETE' && path === WISHLIST_REMOVE) {
// Assumed like the add: Audible's answer for an ASIN not on the Wishlist is unobserved.
const asins = new Set(query.asins as string[])
account.wishlist = account.wishlist.filter((p) => !asins.has(p.asin))
return null
}
return notFound(method, pathWithQuery)
}
export default async function audibleRequest<T = unknown>(call: AudibleCall): Promise<T> {
const rawMethod: unknown = call.method ?? 'GET'
const path: unknown = call.path
if (typeof rawMethod !== 'string' || typeof path !== 'string') {
throw new Error('The Audible credential package takes a string method and path.')
}
const method = rawMethod.toUpperCase()
if (!isAllowedCall(method, path)) {
throw new Error(`The Audible credential package does not allow ${method} ${path}.`)
}
const body = allowedBody(method, path, call.body)
const query = allowedQuery(method, path, call.query) ?? {}
const pathWithQuery = `${path}${buildQuery(query)}`
const account = await loadAccount()
if (!account) throw new NotConnectedError()
const result = serve(account, method, path, query, body, pathWithQuery)
if (method !== 'GET') await saveAccount(account)
return result as T
}
export async function connectedLocale(): Promise<string | null> {
const account = await loadAccount()
return account ? resolveLocale(account.locale).countryCode : null
}