// Test-only: resolves `kody:*` imports to in-process mocks so package source // can run under `node --test`. Register mocks on globalThis.__kodyMocks // (keyed by the full specifier) BEFORE dynamically importing the module under // test. Not reachable from any package export, so it is never bundled. import { registerHooks } from 'node:module' import { pathToFileURL } from 'node:url' globalThis.__kodyMocks ??= {} const PREFIX = 'kody-mock:' registerHooks({ resolve(specifier, context, nextResolve) { if (specifier.startsWith('kody:')) { return { url: PREFIX + specifier, shortCircuit: true } } try { return nextResolve(specifier, context) } catch (error) { // Optional: resolve npm deps (e.g. remix) from a shared install. const extra = process.env.KODY_TEST_NODE_MODULES if (extra && !specifier.startsWith('.') && !specifier.startsWith('node:')) { return nextResolve(specifier, { ...context, parentURL: pathToFileURL(extra + '/_resolve-base.js').href, }) } throw error } }, load(url, context, nextLoad) { if (url.startsWith(PREFIX)) { const spec = url.slice(PREFIX.length) const ref = `globalThis.__kodyMocks[${JSON.stringify(spec)}]` const get = `function __m() { const m = ${ref}; if (!m) throw new Error(${JSON.stringify('No kody mock registered for ' + spec)}); return m }` // Lazy delegation: tests may (re)register mocks after import. const names = spec === 'kody:runtime' ? ['packageStorage', 'packageContext', 'packages', 'createAuthenticatedFetch'] : Object.keys(globalThis.__kodyMocks[spec] ?? {}).filter( (k) => k !== 'default' && /^[A-Za-z_$][\w$]*$/.test(k), ) const source = [ get, 'export default function (...args) { return __m().default(...args) }', spec === 'kody:runtime' ? 'export const kody = new Proxy({}, { get: (_t, key) => __m().kody[key] })' : '', ...names.map( (n) => `export function ${n}(...args) { return __m()[${JSON.stringify(n)}](...args) }`, ), ].join('\n') return { format: 'module', source, shortCircuit: true } } return nextLoad(url, context) }, })