Lumen & Gesso / website · lumengesso.com / app / api / studio / smoke.test.cjs
| 1 | // Run from the project root: node app/api/studio/smoke.test.cjs |
| 2 | // No live vendor, Cloudflare, network, customer or email access. |
| 3 | const { createRequire } = require('node:module'); |
| 4 | const path = require('node:path'); |
| 5 | const root = path.resolve(__dirname, '../../..'); |
| 6 | const backend = createRequire(path.join(root, 'package.json')); |
| 7 | const esbuild = backend('esbuild'); |
| 8 | const { DatabaseSync } = require('node:sqlite'); |
| 9 | const { strict: assert } = require('node:assert'); |
| 10 | const Module = require('node:module'); |
| 11 | const sends = [], initialized = []; |
| 12 | const auth = { |
| 13 | authOrigin: () => 'https://lumengesso.com', |
| 14 | getCustomerUser: () => Promise.resolve(global.user), |
| 15 | provisionCustomer: async email => { initialized.push(email); }, |
| 16 | lumenAuth: () => ({ handler: async req => { sends.push(await req.json()); return new Response(null,{status:200}); } }), |
| 17 | }; |
| 18 | const db = new DatabaseSync(':memory:'); |
| 19 | db.exec('CREATE TABLE integrations(key TEXT PRIMARY KEY, value TEXT, updated_at TEXT NOT NULL);'); |
| 20 | global.env = { EMAIL: {send: async () => {}}, COMMERCE_DB: { prepare: sql => ({ |
| 21 | bind: (...params) => ({ |
| 22 | first: () => Promise.resolve(sql.includes('?1') ? db.prepare(sql).get(Object.fromEntries(params.map((v, i) => [String(i + 1), v]))) : db.prepare(sql).get(...params)) |
| 23 | }), |
| 24 | }) } }; |
| 25 | let calls = []; |
| 26 | const testRequest = (action='generate', model='gpt-image-2.6-sunburst', addImage=false, headers = {}) => { |
| 27 | const fd = new FormData(); |
| 28 | fd.set('action', action); |
| 29 | fd.set('model', model); |
| 30 | fd.set('prompt', 'A small abstract image'); |
| 31 | if (addImage) fd.set('image', new Blob([global.testPng], {type:'image/png'}), 'test.png'); |
| 32 | return new Request('https://lumengesso.com/api/studio', {method:'POST', body:fd, headers: {origin:'https://lumengesso.com',...headers}}); |
| 33 | }; |
| 34 | (async()=>{ |
| 35 | global.testPng = await backend('sharp')({ create: { width: 2, height: 3, channels: 3, background: '#556677' } }).png().toBuffer(); |
| 36 | const bundle = await esbuild.build({ stdin: {contents: "export * from './app/api/studio/route'; export * from './app/lib/studio-quota';", resolveDir:root, loader:'ts' }, absWorkingDir:root, write:false,bundle:true,platform:'node',format:'cjs',external:['server-only', '@opennextjs/cloudflare','@/app/lib/lumen-auth','sharp'] }); |
| 37 | const bundled=new Module(path.join(root, '.studio-test.cjs'), module); |
| 38 | const oldLoad=Module._load; |
| 39 | Module._load = function(specifier, parent, isMain){ |
| 40 | if (specifier === 'server-only') return {}; |
| 41 | if (specifier === '@opennextjs/cloudflare') return {getCloudflareContext:()=>({env:global.env})}; |
| 42 | if (specifier === '@/app/lib/lumen-auth') return auth; |
| 43 | if (specifier === 'sharp') return backend('sharp'); |
| 44 | return oldLoad.apply(this,arguments); |
| 45 | }; |
| 46 | bundled._compile(bundle.outputFiles[0].text, path.join(root, '.studio-test.cjs')); |
| 47 | const {GET, POST, reserveStudioCall, studioLimits} = bundled.exports; |
| 48 | const fixture = global.testPng.toString('base64'); |
| 49 | global.fetch = async (url, init) => { |
| 50 | calls.push([url, init]); |
| 51 | if (url.includes('/chat/')) return Response.json({choices:[{message:{content:'Try a warmer palette.'}}]}); |
| 52 | if (url.includes('google')) return Response.json({candidates:[{content:{parts:[{inlineData:{data:fixture}}]}}]}); |
| 53 | return Response.json({data:[{b64_json:fixture}]}); |
| 54 | }; |
| 55 | delete process.env.LUMEN_STUDIO_ENABLED; |
| 56 | delete process.env.LUMEN_STUDIO_AUTH_DAILY_SENDS; |
| 57 | delete process.env.LUMEN_STUDIO_AUTH_IP_DAILY_SENDS; |
| 58 | delete process.env.LUMEN_STUDIO_AUTH_TOTAL_SENDS; |
| 59 | delete process.env.CLOUDFLARE_DEPLOYMENT_ENV; |
| 60 | assert.equal(studioLimits({}), null); |
| 61 | assert.equal((await (await GET()).json()).ready, false); |
| 62 | assert.equal((await POST(testRequest())).status, 401); |
| 63 | global.user = {id:'anonymous-disabled'}; |
| 64 | assert.equal((await POST(testRequest())).status, 503); |
| 65 | assert.equal((await POST(testRequest('generate',undefined,false,{origin:'https://other.test'}))).status,403); |
| 66 | Object.assign(process.env,{ LUMEN_STUDIO_ENABLED:'true', LUMEN_STUDIO_DAILY_CALLS:'4', LUMEN_STUDIO_ACCOUNT_DAILY_CALLS:'2', LUMEN_STUDIO_TOTAL_CALLS:'5', LUMEN_STUDIO_MODELS:'gpt-image-2.6-sunburst,gemini-3-pro-image', LUMEN_STUDIO_FEEDBACK:'true', OPENAI_API_KEY:'never-a-real-key', GEMINI_API_KEY:'never-a-real-key'}); |
| 67 | assert.deepEqual((await(await GET()).json()).models.map(m=>m.available),[true,true]); |
| 68 | const saved=global.env; global.env={}; |
| 69 | assert.equal((await(await GET()).json()).ready,false); |
| 70 | assert.equal((await POST(testRequest())).status,503); |
| 71 | global.env=saved; |
| 72 | assert.equal((await POST(testRequest('revise'))).status,400); |
| 73 | assert.equal((await POST(testRequest('generate','arbitrary-model'))).status,400); |
| 74 | assert.equal((await POST(testRequest('generate',undefined,false,{'content-length':String(7*1024*1024)}))).status,413); |
| 75 | const fd = new FormData(); |
| 76 | fd.set('action','revise');fd.set('model','gpt-image-2.6-sunburst');fd.set('prompt','Edit'); |
| 77 | fd.set('image',new Blob(['https://somewhere.invalid/file.jpg'], {type:'image/jpeg'}),'bad.jpg'); |
| 78 | assert.equal((await POST(new Request('https://lumengesso.com/api/studio',{method:'POST',headers:{origin:'https://lumengesso.com'},body:fd}))).status,400); |
| 79 | assert.equal(calls.length,0); |
| 80 | global.user={id:'first-account'}; |
| 81 | let response=await POST(testRequest()); |
| 82 | assert.equal(response.status,200); |
| 83 | assert.equal(response.headers.get('content-type'),'image/png'); |
| 84 | assert.deepEqual(Buffer.from(await response.arrayBuffer()),global.testPng); |
| 85 | response=await POST(testRequest('revise','gpt-image-2.6-sunburst',true)); |
| 86 | assert.equal(response.status,200); |
| 87 | assert.equal(calls[1][0].endsWith('/edits'),true); |
| 88 | assert.equal(calls[1][1].body.get('image').type,'image/jpeg'); |
| 89 | assert.equal((await POST(testRequest())).status,429); |
| 90 | global.user={id:'second-account'}; |
| 91 | assert.equal((await POST(testRequest('generate','gemini-3-pro-image'))).status,200); |
| 92 | response=await POST(testRequest('feedback',undefined,true)); |
| 93 | assert.deepEqual(await response.json(),{feedback:'Try a warmer palette.'}); |
| 94 | assert.equal(calls.length,4); |
| 95 | global.user={id:'third-account'}; |
| 96 | assert.equal((await POST(testRequest())).status,429); |
| 97 | const updates=db.prepare("UPDATE integrations SET value=json_set(value,'$.day','2000-01-01')").run(); |
| 98 | assert.equal(updates.changes,1); |
| 99 | assert.equal((await POST(testRequest())).status,200); |
| 100 | assert.equal((await POST(testRequest())).status,429); |
| 101 | assert.equal(calls.length,5); |
| 102 | const quota=JSON.parse(db.prepare("SELECT value FROM integrations").get().value); |
| 103 | assert.deepEqual([quota.daily,quota.total,Object.keys(quota.users).length],[1,5,1]); |
| 104 | assert.equal(JSON.stringify(quota).includes('third-account'),false); |
| 105 | db.exec('DELETE FROM integrations'); |
| 106 | const capped = await Promise.all(Array.from({length:25},(_,i)=>reserveStudioCall(global.env.COMMERCE_DB,'burst-'+i,{daily:8,perAccount:2,total:10}))); |
| 107 | assert.equal(capped.filter(Boolean).length,8); |
| 108 | console.log('Studio API mocked end-to-end: auth, origins, fail closed, validation, both image providers, feedback, per-account/daily/lifetime limits and concurrent reservations pass.'); |
| 109 | })().catch(e=>{console.error(e);process.exitCode=1}); |