import {readFile,stat} from 'node:fs/promises'; import {syncStarterKitRewards} from './starter-kit-rewards.mjs'; const defaultConfig='/home/dunerealms/.config/kit-delivery.json'; // Existing kit inventory, existing delivery table, existing central scheduler. // This is another verified source for that delivery table, not a paid sale. export async function openStarterKitDelivery(db,settings,{readConfig=async path=>({mode:(await stat(path)).mode,config:JSON.parse(await readFile(path,'utf8'))}),createPool=async options=>{const {Pool}=await import('pg');return new Pool(options);},logger=console}={}){ let pool=null; try{ const {mode,config}=await readConfig(settings.KIT_DELIVERY_CONFIG||defaultConfig),target=config.postgres; if(mode&0o007||!target||target.host!=='127.0.0.1'||target.port!==15432||typeof target.database!=='string'||!/^[_a-z][_a-z0-9]{2,63}$/i.test(target.database)||typeof target.user!=='string'||!target.user||typeof target.password!=='string'||!target.password)throw Error('Private inventory delivery configuration required'); pool=await createPool({...target,max:1,connectionTimeoutMillis:5000,idleTimeoutMillis:30000,statement_timeout:5000});pool.on?.('error',()=>logger.warn?.('Kit inventory delivery is unavailable; quest receipts remain queued')); }catch{logger.warn?.('Kit reward delivery configuration is unavailable; quest receipts remain queued');} return Object.freeze({configured:pool!==null,async drain(){const result=await syncStarterKitRewards(db,pool||{async query(){throw Error('Kit inventory delivery is unavailable');}});return {...result,failed:result.retained?1:0};},async close(){await pool?.end();}}); }