import { TestStore } from '../../src/__tests__/helpers/sqlite.ts' import assert from 'node:assert/strict' import { registerHooks } from 'node:module' import { test } from 'node:test' const g = globalThis as any g.contractStore = new TestStore() g.contractContext = { packageId: 'local:audible' } registerHooks({ resolve: (specifier, context, next) => (specifier === 'kody:runtime' ? { url: 'mock:runtime', shortCircuit: true } : next(specifier, context)), load: (url, context, next) => url === 'mock:runtime' ? { format: 'module', shortCircuit: true, source: ` const s = globalThis.contractStore export const packageStorage = () => ({ sql:async(q,p)=>s.sql(q,p), get: async k => s.get(k) ?? null, set: async (k, v) => { s.set(k, structuredClone(v)) }, delete: async k => s.delete(k) }) export const kody = { secretList:async()=>({secrets:[{name:'audible-login',scope:'user',description:JSON.stringify({registration:'00000000-0000-4000-8000-000000000001',deviceName:'Contract',registeredAt:'2026-10-01T00:00:00Z'}),updated_at:'1'}]}) }; export const credential=async()=>{if(!globalThis.loginMapped)throw new Error('missing');return{name:'audible-login',scope:'user',kind:'login',hosts:['api.audible.ca','api.amazon.ca'],fetch:globalThis.fetch}}; export const packageContext = globalThis.contractContext` } : next(url, context), }) const real = { request: await import('../../src/request.ts'), status: (await import('../../src/status.ts')).default, credits: (await import('../../src/credits.ts')).default, license: (await import('../../src/license.ts')).default, } const fake = { request: await import('../request.ts'), status: (await import('../status.ts')).default, credits: (await import('../credits.ts')).default, license: (await import('../license.ts')).default, } const seed = (await import('../seed.ts')).default type Api = typeof real const library = [{ asin: 'B000000001', title: 'The First Gate', percent_complete: 42 }, { asin: 'B000000002', title: 'Second' }] const wishlist = [{ asin: 'B000000009', title: 'Wanted' }] const accountInformation = { customer_information: { credits_fulfillment_data: { credits_to_be_received: 1 }, subscription: { subscription_details: [{ next_bill_date: '2026-11-15T00:00:00Z', next_bill_amount: { amount: '14.95', currency: 'CAD' } }] } } } const sent: string[] = [] const audible: Record = { 'GET https://api.audible.ca/1.0/library?num_results=50&page=1': [200, { items: library, total_results: 2 }], 'GET https://api.audible.ca/1.0/library/B000000001': [200, { item: library[0] }], 'GET https://api.audible.ca/1.0/library/B00000000X': [404, null], 'GET https://api.audible.ca/1.0/wishlist?num_results=20&page=0': [200, { products: wishlist, total_results: 1 }], 'POST https://api.audible.ca/1.0/wishlist': [201, null], 'GET https://api.audible.ca/1.0/collections/__WISHLIST': [200, { collection_id: '__WISHLIST', state_token: 'synthetic-state' }], 'DELETE https://api.audible.ca/1.0/collections/__WISHLIST/items?state_token=synthetic-state&asins=B000000009': [204, null], 'DELETE https://api.audible.ca/1.0/collections/__WISHLIST/items?state_token=synthetic-state&asins=B000000009&asins=B00000000X': [204, null], 'GET https://api.audible.ca/1.0/library?num_results=1&page=2': [200, { items: [library[1]], total_results: 2 }], 'GET https://api.audible.ca/1.0/wishlist?num_results=1&page=1': [200, { products: [], total_results: 1 }], 'GET https://api.audible.ca/1.0/account/information?response_groups=customer_benefits%2Cplan_summary%2Csubscription_details&source=Credit': [200, accountInformation], } g.fetch = async (url: string, init: RequestInit = {}) => { const key = `${init.method ?? 'GET'} ${url}` sent.push(key) const [status, body] = audible[key] ?? [599, { unexpected: key }] return new Response(body == null ? null : JSON.stringify(body), { status }) } async function connect(side: 'real' | 'fake') { unmapLogin() if (side === 'fake') await seed({ locale: 'ca', library, wishlist, accountInformation }) else g.loginMapped = true } function unmapLogin() { g.contractStore.clear() g.loginMapped = false } const outcome = async (run: () => Promise) => { try { return { ok: await run() } } catch (e: any) { return { error: { name: e.name, message: e.message, ...(e.status ? { status: e.status } : {}) } } } } const cases: Array<{ name: string; connected: boolean; run: (api: Api) => Promise; expect: unknown }> = [ { name: 'request before Connect', connected: false, run: api => api.request.default({ path: '/1.0/library' }), expect: { error: { name: 'NotConnectedError', message: 'Audible is not connected. Open Audible setup and provision audible-login.' } } }, { name: 'credits before Connect', connected: false, run: api => api.credits(), expect: { error: { name: 'NotConnectedError', message: 'Audible is not connected. Open Audible setup and provision audible-login.' } } }, { name: 'connectedLocale before Connect', connected: false, run: api => api.request.connectedLocale(), expect: { ok: null } }, { name: 'a call outside the policy', connected: true, run: api => api.request.default({ path: '/1.0/account/information' }), expect: { error: { name: 'Error', message: 'The Audible credential package does not allow GET /1.0/account/information.' } } }, { name: 'a Wishlist add with extra keys', connected: true, run: api => api.request.default({ method: 'POST', path: '/1.0/wishlist', body: { asin: 'B000000009', x: 1 } }), expect: { error: { name: 'Error', message: 'The Audible credential package does not allow that body for POST /1.0/wishlist.' } } }, { name: 'a query key outside the policy', connected: true, run: api => api.request.default({ path: '/1.0/library', query: { 'Bad-Key': 1 } }), expect: { error: { name: 'Error', message: 'Query key "Bad-Key" is not allowed.' } } }, { name: 'Library page', connected: true, run: api => api.request.default({ path: '/1.0/library', query: { num_results: 50, page: 1 } }), expect: { ok: { items: library, total_results: 2 } } }, { name: 'Library item', connected: true, run: api => api.request.default({ path: '/1.0/library/B000000001' }), expect: { ok: { item: library[0] } } }, { name: 'Library item not owned', connected: true, run: api => api.request.default({ path: '/1.0/library/B00000000X' }), expect: { error: { name: 'AudibleApiError', message: 'Audible API GET /1.0/library/B00000000X → HTTP 404 (body: empty)', status: 404 } } }, { name: 'Wishlist page', connected: true, run: api => api.request.default({ path: '/1.0/wishlist', query: { num_results: 20, page: 0 } }), expect: { ok: { products: wishlist, total_results: 1 } } }, { name: 'Wishlist add', connected: true, run: api => api.request.default({ method: 'POST', path: '/1.0/wishlist', body: { asin: 'B000000009' } }), expect: { ok: null } }, { name: 'Library second page is one-based', connected: true, run: api => api.request.default({ path: '/1.0/library', query: { num_results: 1, page: 2 } }), expect: { ok: { items: [{ asin: 'B000000002', title: 'Second' }], total_results: 2 } } }, { name: 'Wishlist second page is zero-based', connected: true, run: api => api.request.default({ path: '/1.0/wishlist', query: { num_results: 1, page: 1 } }), expect: { ok: { products: [], total_results: 1 } } }, { name: 'Wishlist remove', connected: true, run: api => api.request.default({ method: 'DELETE', path: '/1.0/collections/__WISHLIST/items', query: { asins: 'B000000009' } }), expect: { ok: null } }, { name: 'Wishlist remove of a listed and an unlisted item', connected: true, run: api => api.request.default({ method: 'DELETE', path: '/1.0/collections/__WISHLIST/items', query: { asins: ['B000000009', 'B00000000X'] } }), expect: { ok: null } }, { name: 'Wishlist remove on the old route', connected: true, run: api => api.request.default({ method: 'DELETE', path: '/1.0/wishlist/B000000009' }), expect: { error: { name: 'Error', message: 'The Audible credential package does not allow DELETE /1.0/wishlist/B000000009.' } } }, { name: 'Wishlist remove with a caller state_token', connected: true, run: api => api.request.default({ method: 'DELETE', path: '/1.0/collections/__WISHLIST/items', query: { asins: 'B000000009', state_token: 'x' } }), expect: { error: { name: 'Error', message: 'The Audible credential package does not allow that query for DELETE /1.0/collections/__WISHLIST/items.' } } }, { name: 'non-string method', connected: true, run: api => api.request.default({ method: 7 as any, path: '/1.0/library' }), expect: { error: { name: 'Error', message: 'The Audible credential package takes a string method and path.' } } }, { name: 'non-string path', connected: true, run: api => api.request.default({ path: 7 as any }), expect: { error: { name: 'Error', message: 'The Audible credential package takes a string method and path.' } } }, { name: 'connectedLocale', connected: true, run: api => api.request.connectedLocale(), expect: { ok: 'ca' } }, { name: 'credits', connected: true, run: api => api.credits(), expect: { ok: { nextCharge: { date: '2026-11-15', credits: 1, cents: 1495, currency: 'CAD' } } } }, { name: 'license while archive is off', connected: true, run: api => api.license({ asin: 'B000000001', body: {} }), expect: { error: { name: 'ArchiveDisabledError', message: 'NAS archive is off, so Books cannot be saved to the NAS. To turn it on, ask your agent to follow “Turning NAS archive on” in the README of the package that holds your Audible credentials.' } } }, ] for (const c of cases) { test(`fake matches real: ${c.name}`, async () => { const answers = [] for (const [side, api] of [['real', real], ['fake', fake]] as const) { if (c.connected) await connect(side) else unmapLogin() const before = sent.length answers.push(await outcome(() => c.run(api))) if (side === 'fake') assert.equal(sent.length, before, 'fake sends no fetch') } assert.deepEqual(answers[1], answers[0], 'fake answers like the real export') assert.deepEqual(answers[0], c.expect) }) } test('status has the same keys, types, and connection facts on both sides', async () => { const shape = (s: Record) => Object.fromEntries(Object.entries(s).map(([k, v]) => [k, v === null ? 'null' : Array.isArray(v) ? 'array' : typeof v])) for (const connected of [false, true]) { const answers: any[] = [] for (const [side, api] of [['real', real], ['fake', fake]] as const) { if (connected) await connect(side) else unmapLogin() const before = sent.length if(connected&&side==='real'){await api.request.default({path:'/1.0/library',query:{num_results:50,page:1}})} answers.push(await api.status()) if (side === 'fake') assert.equal(sent.length, before, 'fake status sends no fetch') } assert.deepEqual(shape(answers[1]), shape(answers[0])) const facts = ({ ok, connected, ready, locale, archiveEnabled, archiveReady }: any) => ({ ok, connected, ready, locale, archiveEnabled, archiveReady }) assert.deepEqual(facts(answers[1]), facts(answers[0])) assert.deepEqual(facts(answers[0]), connected ? { ok: true, connected: true, ready: true, locale: 'ca', archiveEnabled: false, archiveReady: false } : { ok: true, connected: false, ready: false, locale: null, archiveEnabled: false, archiveReady: false }) } }) test('the real side reached Audible only through the canned URLs', () => { assert.ok(sent.length >= 6, `real side sent ${sent.length} requests`) assert.deepEqual(sent.filter(k => !(k in audible)), []) }) test('the fake exports every subpath the real package exports, plus ./seed', async () => { const { readFileSync } = await import('node:fs') const realExports = Object.keys(JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8')).exports).filter(k => k !== '.') const fakeExports = Object.keys(JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).exports) assert.deepEqual(fakeExports.filter(k => k !== './seed').sort(), realExports.sort()) }) test('seed refuses a hosted context before writing or deleting storage', async () => { await connect('fake') const before = structuredClone([...g.contractStore]) g.contractContext.packageId = 'pkg-hosted' try { await assert.rejects(seed({ library: [] }), /seeds only local runs/) await assert.rejects(seed({ connected: false }), /seeds only local runs/) assert.deepEqual([...g.contractStore], before) } finally { g.contractContext.packageId = 'local:audible' } }) test('seed disconnects and rejects malformed rows', async () => { await connect('fake') await assert.rejects(seed({ library: [null] }), /library must be an array/) await seed({ connected: false }) assert.equal((await fake.status()).connected, false) }) test('fake Wishlist writes persist across calls without fetch', async () => { await connect('fake') const before = sent.length await fake.request.default({ method: 'POST', path: '/1.0/wishlist', body: { asin: 'B000000008' } }) await fake.request.default({ method: 'POST', path: '/1.0/wishlist', body: { asin: 'B000000008' } }) assert.deepEqual(await fake.request.default({ path: '/1.0/wishlist' }), { products: [{ asin: 'B000000008' }, { asin: 'B000000009', title: 'Wanted' }], total_results: 2, }) await fake.request.default({ method: 'DELETE', path: '/1.0/collections/__WISHLIST/items', query: { asins: ['B000000008'] } }) assert.deepEqual(await fake.request.default({ path: '/1.0/wishlist' }), { products: [{ asin: 'B000000009', title: 'Wanted' }], total_results: 1, }) assert.equal(sent.length, before) })