// Offline transport/browser fixtures around the unmodified production routes. // No collector or article extractor is reimplemented here. No network fetch. const fs = require('node:fs') const path = require('node:path') const vm = require('node:vm') const { createRequire } = require('node:module') const express = require('express') const cheerio = require('cheerio') function startFixture () { const stats = { sectionRequests: 0, browserSessions: 0, articleRequests: 0 } const urls = ['complete', 'partial', 'absent'].map(k => `https://www.bloomberg.com/news/articles/bench-${k}`) const section = urls.map((url,i) => `
Synthetic benchmark headline ${i}${i ? '' : ''}
`).join('') const allowedSections = new Set(['/markets/stocks','/markets/currencies','/markets/rates-bonds','/markets/commodities','/technology','/economics','/politics']) const body = url => `

Synthetic complete editorial body.

Synthetic final paragraph.

${url.endsWith('partial') ? '
' : ''}
` const browser = {async newPage () {return page()}, async close () {}} function page () { let current = ''; let state = 'email'; let markup = ''; const values = new Map() function document () { const html = state === 'article' ? markup : state === 'authenticated' ? 'Fixture account control' : state === 'password' ? '
' : '
' const $ = cheerio.load(html) const wrap = n => ({ hidden: $(n).is('[hidden]'), disabled: $(n).is('[disabled]'), getAttribute: k => $(n).attr(k) ?? null, getClientRects: () => $(n).parents().addBack().is('[hidden], [aria-hidden="true"]') ? [] : [{}], get form () { const p=$(n).closest('form')[0];return p ? wrap(p) : null }, querySelectorAll: s => $(n).find(s).toArray().map(wrap), set value (v) {values.set(n,v)}, dispatchEvent () {}, click () {state = state === 'email' ? 'password' : 'authenticated';if(state==='authenticated')current='https://www.bloomberg.com/markets'} }) return {querySelectorAll:s=>$(s).toArray().map(wrap),querySelector:s=>{const n=$(s)[0];return n?wrap(n):null}} } return { async setViewport () {}, async evaluateOnNewDocument () {}, async close () {}, url () {return current}, async content () {return markup}, async goto (url) { current=url if(url==='https://www.bloomberg.com/account/signin'){stats.browserSessions++;state='email';return {status:()=>200}} if(!urls.includes(url))throw new Error('offline_navigation_rejected') stats.articleRequests++;state='article';markup=body(url) return {status:()=>url.endsWith('absent')?403:200} }, async evaluate (fn,...args) {return vm.runInNewContext(`(${fn.toString()})(...args)`, {document:document(),args,Event:class {}})}, async waitForSelector (selector) {if(!document().querySelector(selector))throw new Error('offline_element_missing')}, async waitForFunction (fn,_options,...args) {if(!await this.evaluate(fn,...args))throw new Error('offline_state_missing')}, async type (_selector,text) {if(text!=='offline-fixture')throw new Error('offline_credentials_rejected')} } } const index=path.resolve(__dirname,'../index.js');const localRequire=createRequire(index) let server const ready=new Promise((resolve,reject)=>{ const factory=()=>{const app=express();const listen=app.listen.bind(app);app.listen=()=>{server=listen(0,'127.0.0.1',()=>resolve(server));server.once('error',()=>reject(new Error('fixture_service_unavailable')));return server};return app};factory.json=express.json vm.runInNewContext(fs.readFileSync(index,'utf8'),{ require(name){if(name==='express')return factory;if(name==='puppeteer-extra')return {use(){},async launch(){return browser}};if(name==='puppeteer-extra-plugin-stealth')return ()=>({});return localRequire(name)}, process:{env:{PORT:'0',BYPARR_URL:'http://offline-byparr.invalid'}},AbortController, setTimeout(fn,ms){if([2000,800,500,3000].includes(ms)){queueMicrotask(fn);return undefined};return setTimeout(fn,ms)},clearTimeout, console:{log(){},error(){}}, async fetch(destination,options){ if(destination!=='http://offline-byparr.invalid/v1')throw new Error('offline_network_rejected') const req=JSON.parse(options.body);const u=new URL(req.url) if(req.cmd!=='request.get'||u.origin!=='https://www.bloomberg.com'||!allowedSections.has(u.pathname))throw new Error('offline_request_rejected') stats.sectionRequests++ return {ok:true,async json(){return {solution:{url:req.url,response:section}}}} } }) }) return {ready,stats,close:()=>new Promise(resolve=>server?server.close(resolve):resolve())} } module.exports={startFixture} if(require.main===module){ const fixture=startFixture() fixture.ready.then(server=>process.stdout.write(JSON.stringify({port:server.address().port})+'\n')).catch(()=>{console.error('fixture_service_unavailable');process.exitCode=1}) }