import assert from 'node:assert/strict'
import { readdirSync, readFileSync } from 'node:fs'
import { execFileSync } from 'node:child_process'
import { registerHooks } from 'node:module'
import { test } from 'node:test'
const manifest = JSON.parse(process.env.AUTH_TEST_BASE ? execFileSync('git',['show',`${process.env.AUTH_TEST_BASE}:package.json`],{encoding:'utf8'}) : readFileSync(new URL('../../package.json', import.meta.url), 'utf8'))
const capabilityOf: Record<string, string> = { 'secret-list.ts': 'secretList' }
if(process.env.AUTH_TEST_BASE) capabilityOf['secret-set.ts']='secretSet'
const srcUrl = new URL('../', import.meta.url).href
const imports = new Map<string, Set<string>>()
registerHooks({
resolve(specifier, context, next) {
const parent = context.parentURL ?? ''
if (specifier === 'kody:runtime') return { url: `mock:kody-runtime?${capabilityOf[parent.slice(srcUrl.length)] ?? ''}`, shortCircuit: true }
const resolved = process.env.AUTH_TEST_BASE && specifier.startsWith('./') && parent.startsWith(srcUrl)
? {url:new URL(specifier,parent).href,shortCircuit:true} : next(specifier, context)
imports.set(parent, (imports.get(parent) ?? new Set()).add(resolved.url))
return resolved
},
load(url, context, next) {
if (process.env.AUTH_TEST_BASE && url.startsWith(srcUrl) && !url.includes('/__tests__/')) return {format:'module-typescript',shortCircuit:true,source:execFileSync('git',['show',`${process.env.AUTH_TEST_BASE}:src/${url.split('/').at(-1)}`],{encoding:'utf8'})}
if (!url.startsWith('mock:kody-runtime')) return next(url, context)
const kody = url.endsWith('?') ? '' : 'export const kody={};'
return { format: 'module', shortCircuit: true, source: `export const packageStorage=()=>({}); export const packageContext={}; export const credential=async()=>({}); ${kody}` }
},
})
test('each export subpath offers exactly these names', async () => {
const offered: Record<string, string[]> = {}
for (const [subpath, file] of Object.entries(manifest.exports as Record<string, string>)) {
offered[subpath] = Object.keys(await import(new URL(`../../${file}`, import.meta.url).href)).sort()
}
assert.deepEqual(offered, {
'.': ['default'],
'./status': ['default'],
'./request': ['AudibleApiError', 'connectedLocale', 'default'],
'./license': ['ArchiveDisabledError', 'default'],
'./credits': ['default'],
})
})
test('kody.credentials declares only the audible-login need', () => {
assert.deepEqual(Object.keys(manifest.kody.credentials), ['audible-login'])
assert.deepEqual(manifest.kody.credentials['audible-login'], {kind:'login',provider:'audible',description:'Use the owner-provisioned Audible login for Library, Wishlist, credits and device removal.'})
assert.equal('secretMounts' in manifest.kody, false)
})
test('each capability module makes exactly its one Kody call', () => {
for (const [file, capability] of Object.entries(capabilityOf)) {
const source = readFileSync(new URL(file, srcUrl), 'utf8')
assert.deepEqual([...source.matchAll(/\bkody\b(?!:)(\.\w+\s*\()?/g)].map(([, call]) => call?.replace(/\s/g, '')), [undefined, `.${capability}(`], file)
}
})
function assertModuleImports(file: string, source: string): void {
assert.doesNotMatch(source, /\bimport\s*\(/, file)
if (!(file in capabilityOf)) assert.doesNotMatch(source, /\bkody\s*\.\s*\w+\s*\(/, file)
}
test('all modules use static imports and only capability modules call Kody', () => {
for (const file of productionModules('src')) {
assertModuleImports(file, readFileSync(new URL(file, srcUrl), 'utf8'))
}
})
function productionModules(dir: string): string[] {
const names = readdirSync(new URL(`../../${dir}/`, import.meta.url), { recursive: true, encoding: 'utf8' })
return names.filter((name) => /\.(ts|mjs)$/.test(name) && !name.split('/').includes('__tests__'))
}
async function capabilitiesReachedFrom(file: string): Promise<string[]> {
const entry = new URL(`../../${file}`, import.meta.url).href
await import(entry)
const seen = new Set<string>()
const visit = (url: string) => {
if (seen.has(url)) return
seen.add(url)
for (const next of imports.get(url) ?? []) visit(next)
}
visit(entry)
return Object.entries(capabilityOf).filter(([module]) => seen.has(srcUrl + module)).map(([, capability]) => capability).sort()
}
test('the app lists exactly the Kody capabilities its code calls', async () => {
assert.deepEqual(manifest.kody.app.capabilities, await capabilitiesReachedFrom(manifest.kody.app.entry))
})
test('the README tells importing apps every Kody capability the exports call', async () => {
const reached: Record<string, string[]> = {}
for (const [subpath, file] of Object.entries(manifest.exports as Record<string, string>)) reached[subpath] = await capabilitiesReachedFrom(file)
assert.deepEqual(reached, {
'.': [],
'./status': ['secretList'],
'./request': ['secretList'],
'./license': [],
'./credits': ['secretList'],
})
const readme = readFileSync(new URL('../../README.md', import.meta.url), 'utf8')
const listed = [...new Set(Object.values(reached).flat())].sort().map((name) => `"${name}"`)
assert.ok(readme.includes(`"capabilities": [${listed.join(', ')}]`))
})
test('no export or hosted app reaches login/registration or a secret save',async()=>{
for(const file of [...Object.values(manifest.exports),manifest.kody.app.entry]){
await capabilitiesReachedFrom(String(file))
const seen=new Set<string>()
const visit=(url:string)=>{if(seen.has(url))return;seen.add(url);for(const next of imports.get(url)??[])visit(next)}
visit(new URL(`../../${file}`,import.meta.url).href)
for(const path of ['login.ts','register.ts','secret-set.ts','complete-auth.ts','start-auth.ts'])assert.equal(seen.has(srcUrl+path),false,`${file} reaches ${path}`)
}
})