import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import path from 'node:path'

const LIB_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'lib')

/**
 * Load an extension lib and hand back the globals it declares.
 *
 * The files under lib/ are CLASSIC scripts, not ES modules: manifest.json
 * lists them in `background.scripts` and options.html pulls them in with a
 * plain <script> tag, so they declare bare functions into a shared scope and
 * export nothing. Rather than bolt a `module.exports` shim onto production
 * code that would never run in the browser, evaluate the real file the same
 * way the browser does — as a script body — and pick the declarations back out.
 *
 * This means the specs exercise the exact bytes that get packaged into the
 * XPI. Only usable for libs that touch no browser APIs at load time
 * (url.js, platforms.js); cookies.js and api.js reference `browser.*` and
 * would need stubbing, which is why they aren't loaded this way.
 *
 * @param {string} filename e.g. 'url.js'
 * @param {string[]} names  declarations to return, e.g. ['normalizeApiUrl']
 */
export function loadLib(filename, names) {
  const source = readFileSync(path.join(LIB_DIR, filename), 'utf8')
  const factory = new Function(`${source}\nreturn { ${names.join(', ')} }`)
  return factory()
}
