-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
242 lines (214 loc) · 8.07 KB
/
server.js
File metadata and controls
242 lines (214 loc) · 8.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
import { createServer } from 'http';
import { readFile } from 'fs/promises';
import { extname, join, resolve } from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
// import { solve, solveOverallEV, generateStrategyChart } from './blackjack-solver.js';
import { computeRound2, calculateEdges } from './live/tvbet-market-solver.js';
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const native = require('./native/index.node');
const { solve, solveOverallEv, generateStrategyChart } = native;
const solveOverallEV = solveOverallEv;
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const mimeTypes = {
'.html': 'text/html',
'.js': 'application/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.wav': 'audio/wav',
'.mp4': 'video/mp4',
'.woff': 'application/font-woff',
'.ttf': 'application/font-ttf',
'.eot': 'application/vnd.ms-fontobject',
'.otf': 'application/font-otf',
'.wasm': 'application/wasm'
};
// ── JSON body parser (no dependencies) ───────────────────────────────
const MAX_BODY_SIZE = 1024 * 1024; // 1MB
function readBody(req) {
return new Promise((res, reject) => {
const chunks = [];
let size = 0;
let rejected = false;
req.on('data', chunk => {
size += chunk.length;
if (size > MAX_BODY_SIZE) {
if (!rejected) {
rejected = true;
reject(new Error('Payload too large'));
}
return;
}
chunks.push(chunk);
});
req.on('end', () => {
if (rejected) return;
try {
res(JSON.parse(Buffer.concat(chunks).toString()));
} catch {
reject(new Error('Invalid JSON'));
}
});
req.on('error', err => {
if (!rejected) reject(err);
});
});
}
function jsonResponse(res, status, data) {
const body = JSON.stringify(data);
res.writeHead(status, {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type',
});
res.end(body);
}
// ── Strategy chart helpers (moved from solver-worker.js) ─────────────
const CARD_TYPES = ['2','3','4','5','6','7','8','9','0','1'];
const SECTIONS = ['hard', 'soft', 'pairs'];
function computeDiff(baseline, current) {
const diff = { hard: {}, soft: {}, pairs: {} };
for (const s of SECTIONS) {
for (const row of Object.keys(current[s])) {
diff[s][row] = {};
for (const dc of CARD_TYPES) {
const base = baseline[s][row] ? baseline[s][row][dc] : null;
diff[s][row][dc] = base !== current[s][row][dc];
}
}
}
return diff;
}
function hasDeadCards(deadCards) {
if (!deadCards) return false;
for (const k of Object.keys(deadCards)) {
if (deadCards[k] > 0) return true;
}
return false;
}
// ── Server-side result cache (capped at 100 entries, evicts oldest) ──
const EV_CACHE_MAX = 100;
const evCache = new Map();
function evCacheSet(key, value) {
if (evCache.size >= EV_CACHE_MAX) {
evCache.delete(evCache.keys().next().value);
}
evCache.set(key, value);
}
// ── API route handlers ───────────────────────────────────────────────
async function handleAPI(req, res) {
const url = req.url;
// CORS preflight
if (req.method === 'OPTIONS') {
res.writeHead(204, {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
});
res.end();
return true;
}
if (req.method !== 'POST') return false;
try {
if (url === '/api/solve') {
const { dealerCard, playerCards, options } = await readBody(req);
const result = solve(dealerCard, playerCards, options || {});
jsonResponse(res, 200, result);
return true;
}
if (url === '/api/overallEV') {
const options = await readBody(req);
const cacheKey = JSON.stringify(options);
if (evCache.has(cacheKey)) {
jsonResponse(res, 200, { ...evCache.get(cacheKey), elapsed: '0.0', cached: true });
return true;
}
const t0 = performance.now();
const result = await solveOverallEV(options);
const elapsed = ((performance.now() - t0) / 1000).toFixed(1);
const cached = { ...result, elapsed };
evCacheSet(cacheKey, cached);
jsonResponse(res, 200, cached);
return true;
}
if (url === '/api/strategyChart') {
const options = await readBody(req);
const t0 = performance.now();
const current = generateStrategyChart(options);
let baseline, diff;
if (hasDeadCards(options.deadCards)) {
baseline = generateStrategyChart({ ...options, deadCards: {} });
diff = computeDiff(baseline, current);
} else {
baseline = current;
diff = null;
}
const elapsed = ((performance.now() - t0) / 1000).toFixed(1);
jsonResponse(res, 200, { baseline, current, diff, elapsed });
return true;
}
if (url === '/api/tvbet/round2') {
const { pc1, pc2, dealerUp, bookieOdds } = await readBody(req);
const t0 = performance.now();
const trueProbs = computeRound2(pc1, pc2, dealerUp);
const edges = calculateEdges(trueProbs, bookieOdds || {});
const fairOdds = {};
for (const [market, prob] of Object.entries(trueProbs)) {
fairOdds[market] = prob > 0 ? +(1 / prob).toFixed(2) : null;
}
const elapsed = ((performance.now() - t0)).toFixed(0);
jsonResponse(res, 200, { trueProbs, fairOdds, edges, elapsed: elapsed + 'ms' });
return true;
}
} catch (err) {
const status = err.message === 'Invalid JSON' ? 400
: err.message === 'Payload too large' ? 413
: 500;
jsonResponse(res, status, { error: err.message });
return true;
}
return false;
}
// ── Server ───────────────────────────────────────────────────────────
const server = createServer(async (req, res) => {
// API routes first
if (req.url.startsWith('/api/')) {
const handled = await handleAPI(req, res);
if (handled) return;
}
// Static file serving
try {
let filePath = req.url === '/' ? '/blackjack-calculator.html' : req.url;
filePath = resolve(join(__dirname, filePath));
// Prevent path traversal
if (!filePath.startsWith(__dirname)) {
res.writeHead(403);
res.end('Forbidden');
return;
}
const ext = extname(filePath);
const contentType = mimeTypes[ext] || 'application/octet-stream';
const content = await readFile(filePath);
res.writeHead(200, { 'Content-Type': contentType });
res.end(content);
} catch (error) {
if (error.code === 'ENOENT') {
res.writeHead(404);
res.end('File not found');
} else {
res.writeHead(500);
res.end('Server error');
}
}
});
const PORT = 8000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
console.log(`Open your browser and go to: http://localhost:${PORT}/blackjack-calculator.html`);
});