@energy8platform/game-engine 0.15.2 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +22 -12
  2. package/dist/assets.d.ts +2 -14
  3. package/dist/core.cjs.js +16 -201
  4. package/dist/core.cjs.js.map +1 -1
  5. package/dist/core.d.ts +4 -35
  6. package/dist/core.esm.js +12 -197
  7. package/dist/core.esm.js.map +1 -1
  8. package/dist/debug.cjs.js +5 -233
  9. package/dist/debug.cjs.js.map +1 -1
  10. package/dist/debug.d.ts +2 -140
  11. package/dist/debug.esm.js +2 -233
  12. package/dist/debug.esm.js.map +1 -1
  13. package/dist/index.cjs.js +21 -432
  14. package/dist/index.cjs.js.map +1 -1
  15. package/dist/index.d.ts +10 -195
  16. package/dist/index.esm.js +14 -429
  17. package/dist/index.esm.js.map +1 -1
  18. package/dist/lua.cjs.js +7 -1493
  19. package/dist/lua.cjs.js.map +1 -1
  20. package/dist/lua.d.ts +1 -403
  21. package/dist/lua.esm.js +1 -1483
  22. package/dist/lua.esm.js.map +1 -1
  23. package/dist/react.cjs.js.map +1 -1
  24. package/dist/react.d.ts +4 -35
  25. package/dist/react.esm.js.map +1 -1
  26. package/dist/vite.cjs.js +19 -175
  27. package/dist/vite.cjs.js.map +1 -1
  28. package/dist/vite.d.ts +8 -3
  29. package/dist/vite.esm.js +10 -173
  30. package/dist/vite.esm.js.map +1 -1
  31. package/package.json +6 -16
  32. package/src/core/GameApplication.ts +14 -18
  33. package/src/debug/index.ts +4 -2
  34. package/src/index.ts +3 -3
  35. package/src/loading/LoadingScene.ts +1 -1
  36. package/src/loading/index.ts +9 -2
  37. package/src/lua/index.ts +3 -31
  38. package/src/types.ts +16 -41
  39. package/src/vite/index.ts +13 -196
  40. package/bin/simulate.ts +0 -139
  41. package/scripts/install-simulate.mjs +0 -101
  42. package/src/debug/DevBridge.ts +0 -305
  43. package/src/loading/CSSPreloader.ts +0 -129
  44. package/src/loading/logo.ts +0 -95
  45. package/src/lua/ActionRouter.ts +0 -132
  46. package/src/lua/LuaEngine.ts +0 -412
  47. package/src/lua/LuaEngineAPI.ts +0 -314
  48. package/src/lua/NativeSimulationRunner.ts +0 -367
  49. package/src/lua/ParallelSimulationRunner.ts +0 -156
  50. package/src/lua/PersistentState.ts +0 -80
  51. package/src/lua/SessionManager.ts +0 -227
  52. package/src/lua/SimulationRunner.ts +0 -192
  53. package/src/lua/SimulationWorker.ts +0 -44
  54. package/src/lua/fengari.d.ts +0 -10
  55. package/src/lua/types.ts +0 -149
package/dist/lua.cjs.js CHANGED
@@ -1,1499 +1,13 @@
1
1
  'use strict';
2
2
 
3
- var fengari = require('fengari');
4
- var worker_threads = require('worker_threads');
5
- var os = require('os');
6
- var url = require('url');
7
- var path = require('path');
8
- var child_process = require('child_process');
9
- var promises = require('fs/promises');
10
- var fs = require('fs');
11
- var crypto = require('crypto');
3
+ var lua = require('@energy8platform/platform-core/lua');
12
4
 
13
- var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
14
- const { lua: lua$1, lauxlib: lauxlib$1 } = fengari;
15
- const { to_luastring: to_luastring$1, to_jsstring: to_jsstring$1 } = fengari;
16
- /** Cache for to_luastring() results — avoids re-encoding the same keys every iteration */
17
- const luaStringCache = new Map();
18
- function cachedToLuastring(s) {
19
- let cached = luaStringCache.get(s);
20
- if (!cached) {
21
- cached = to_luastring$1(s);
22
- luaStringCache.set(s, cached);
23
- }
24
- return cached;
25
- }
26
- /**
27
- * Seeded xoshiro128** PRNG for deterministic simulation/replay.
28
- * Period: 2^128 - 1
29
- */
30
- function createSeededRng(seed) {
31
- let s0 = (seed >>> 0) | 1;
32
- let s1 = (seed * 1103515245 + 12345) >>> 0;
33
- let s2 = (seed * 6364136223846793005 + 1442695040888963407) >>> 0;
34
- let s3 = (seed * 1442695040888963407 + 6364136223846793005) >>> 0;
35
- return () => {
36
- const result = (((s1 * 5) << 7) * 9) >>> 0;
37
- const t = s1 << 9;
38
- s2 ^= s0;
39
- s3 ^= s1;
40
- s1 ^= s2;
41
- s0 ^= s3;
42
- s2 ^= t;
43
- s3 = ((s3 << 11) | (s3 >>> 21)) >>> 0;
44
- return result / 4294967296;
45
- };
46
- }
47
- /**
48
- * Implements and registers all platform `engine.*` functions into a Lua state.
49
- */
50
- class LuaEngineAPI {
51
- rng;
52
- logger;
53
- gameDefinition;
54
- constructor(gameDefinition, rng, logger) {
55
- this.gameDefinition = gameDefinition;
56
- this.rng = rng ?? Math.random;
57
- this.logger = logger ?? ((level, msg) => {
58
- const fn = level === 'error' ? console.error
59
- : level === 'warn' ? console.warn
60
- : level === 'debug' ? console.debug
61
- : console.log;
62
- fn(`[Lua:${level}] ${msg}`);
63
- });
64
- }
65
- /** Register `engine` global table on the Lua state */
66
- register(L) {
67
- // Create the `engine` table
68
- lua$1.lua_newtable(L);
69
- this.registerFunction(L, 'random', (LS) => {
70
- const min = lauxlib$1.luaL_checkinteger(LS, 1);
71
- const max = lauxlib$1.luaL_checkinteger(LS, 2);
72
- const result = this.random(Number(min), Number(max));
73
- lua$1.lua_pushinteger(LS, result);
74
- return 1;
75
- });
76
- this.registerFunction(L, 'random_float', (LS) => {
77
- lua$1.lua_pushnumber(LS, this.randomFloat());
78
- return 1;
79
- });
80
- this.registerFunction(L, 'random_weighted', (LS) => {
81
- lauxlib$1.luaL_checktype(LS, 1, lua$1.LUA_TTABLE);
82
- const weights = [];
83
- const len = lua$1.lua_rawlen(LS, 1);
84
- for (let i = 1; i <= len; i++) {
85
- lua$1.lua_rawgeti(LS, 1, i);
86
- weights.push(lua$1.lua_tonumber(LS, -1));
87
- lua$1.lua_pop(LS, 1);
88
- }
89
- const result = this.randomWeighted(weights);
90
- lua$1.lua_pushinteger(LS, result);
91
- return 1;
92
- });
93
- this.registerFunction(L, 'shuffle', (LS) => {
94
- lauxlib$1.luaL_checktype(LS, 1, lua$1.LUA_TTABLE);
95
- const arr = [];
96
- const len = lua$1.lua_rawlen(LS, 1);
97
- for (let i = 1; i <= len; i++) {
98
- lua$1.lua_rawgeti(LS, 1, i);
99
- arr.push(luaToJS(LS, -1));
100
- lua$1.lua_pop(LS, 1);
101
- }
102
- const shuffled = this.shuffle(arr);
103
- pushJSArray(LS, shuffled);
104
- return 1;
105
- });
106
- this.registerFunction(L, 'log', (LS) => {
107
- const level = to_jsstring$1(lauxlib$1.luaL_checkstring(LS, 1));
108
- const msg = to_jsstring$1(lauxlib$1.luaL_checkstring(LS, 2));
109
- this.logger(level, msg);
110
- return 0;
111
- });
112
- this.registerFunction(L, 'get_config', (LS) => {
113
- const config = this.getConfig();
114
- pushJSObject(LS, config);
115
- return 1;
116
- });
117
- // Set the table as global `engine`
118
- lua$1.lua_setglobal(L, to_luastring$1('engine'));
119
- }
120
- // ─── engine.* implementations ─────────────────────────
121
- random(min, max) {
122
- return Math.floor(this.rng() * (max - min + 1)) + min;
123
- }
124
- randomFloat() {
125
- return this.rng();
126
- }
127
- randomWeighted(weights) {
128
- const totalWeight = weights.reduce((a, b) => a + b, 0);
129
- let roll = this.rng() * totalWeight;
130
- for (let i = 0; i < weights.length; i++) {
131
- roll -= weights[i];
132
- if (roll < 0)
133
- return i + 1; // 1-based index
134
- }
135
- return weights.length; // fallback to last
136
- }
137
- shuffle(arr) {
138
- const copy = [...arr];
139
- for (let i = copy.length - 1; i > 0; i--) {
140
- const j = Math.floor(this.rng() * (i + 1));
141
- [copy[i], copy[j]] = [copy[j], copy[i]];
142
- }
143
- return copy;
144
- }
145
- getConfig() {
146
- const def = this.gameDefinition;
147
- let betLevels = [];
148
- if (Array.isArray(def.bet_levels)) {
149
- betLevels = def.bet_levels;
150
- }
151
- else if (def.bet_levels && 'levels' in def.bet_levels && def.bet_levels.levels) {
152
- betLevels = def.bet_levels.levels;
153
- }
154
- return {
155
- id: def.id,
156
- type: def.type,
157
- bet_levels: betLevels,
158
- };
159
- }
160
- // ─── Helpers ──────────────────────────────────────────
161
- registerFunction(L, name, fn) {
162
- lua$1.lua_pushcfunction(L, fn);
163
- lua$1.lua_setfield(L, -2, to_luastring$1(name));
164
- }
165
- }
166
- // ─── Lua ↔ JS marshalling ───────────────────────────────
167
- /** Read a Lua value at the given stack index and return its JS equivalent */
168
- function luaToJS(L, idx) {
169
- const type = lua$1.lua_type(L, idx);
170
- switch (type) {
171
- case lua$1.LUA_TNIL:
172
- return null;
173
- case lua$1.LUA_TBOOLEAN:
174
- return lua$1.lua_toboolean(L, idx);
175
- case lua$1.LUA_TNUMBER:
176
- if (lua$1.lua_isinteger(L, idx)) {
177
- return Number(lua$1.lua_tointeger(L, idx));
178
- }
179
- return lua$1.lua_tonumber(L, idx);
180
- case lua$1.LUA_TSTRING:
181
- return to_jsstring$1(lua$1.lua_tostring(L, idx));
182
- case lua$1.LUA_TTABLE:
183
- return luaTableToJS(L, idx);
184
- default:
185
- return null;
186
- }
187
- }
188
- /** Convert a Lua table to a JS object or array */
189
- function luaTableToJS(L, idx) {
190
- // Normalize index to absolute
191
- if (idx < 0)
192
- idx = lua$1.lua_gettop(L) + idx + 1;
193
- // Check if it's an array (sequential integer keys starting at 1)
194
- const len = lua$1.lua_rawlen(L, idx);
195
- if (len > 0) {
196
- // Verify it's a pure array by checking key 1 exists
197
- lua$1.lua_rawgeti(L, idx, 1);
198
- const hasFirst = lua$1.lua_type(L, -1) !== lua$1.LUA_TNIL;
199
- lua$1.lua_pop(L, 1);
200
- if (hasFirst) {
201
- // Check if there are also string keys (mixed table)
202
- let hasStringKeys = false;
203
- lua$1.lua_pushnil(L);
204
- while (lua$1.lua_next(L, idx) !== 0) {
205
- lua$1.lua_pop(L, 1); // pop value
206
- if (lua$1.lua_type(L, -1) === lua$1.LUA_TSTRING) {
207
- hasStringKeys = true;
208
- lua$1.lua_pop(L, 1); // pop key
209
- break;
210
- }
211
- }
212
- if (!hasStringKeys) {
213
- // Pure array
214
- const arr = [];
215
- for (let i = 1; i <= len; i++) {
216
- lua$1.lua_rawgeti(L, idx, i);
217
- arr.push(luaToJS(L, -1));
218
- lua$1.lua_pop(L, 1);
219
- }
220
- return arr;
221
- }
222
- }
223
- }
224
- // Object (or mixed table)
225
- const obj = {};
226
- lua$1.lua_pushnil(L);
227
- while (lua$1.lua_next(L, idx) !== 0) {
228
- const keyType = lua$1.lua_type(L, -2);
229
- let key;
230
- if (keyType === lua$1.LUA_TSTRING) {
231
- key = to_jsstring$1(lua$1.lua_tostring(L, -2));
232
- }
233
- else if (keyType === lua$1.LUA_TNUMBER) {
234
- key = String(lua$1.lua_tonumber(L, -2));
235
- }
236
- else {
237
- lua$1.lua_pop(L, 1);
238
- continue;
239
- }
240
- obj[key] = luaToJS(L, -1);
241
- lua$1.lua_pop(L, 1);
242
- }
243
- return obj;
244
- }
245
- /** Push a JS value onto the Lua stack */
246
- function pushJSValue(L, value) {
247
- if (value === null || value === undefined) {
248
- lua$1.lua_pushnil(L);
249
- }
250
- else if (typeof value === 'boolean') {
251
- lua$1.lua_pushboolean(L, value ? 1 : 0);
252
- }
253
- else if (typeof value === 'number') {
254
- if (Number.isInteger(value)) {
255
- lua$1.lua_pushinteger(L, value);
256
- }
257
- else {
258
- lua$1.lua_pushnumber(L, value);
259
- }
260
- }
261
- else if (typeof value === 'string') {
262
- lua$1.lua_pushstring(L, cachedToLuastring(value));
263
- }
264
- else if (Array.isArray(value)) {
265
- pushJSArray(L, value);
266
- }
267
- else if (typeof value === 'object') {
268
- pushJSObject(L, value);
269
- }
270
- else {
271
- lua$1.lua_pushnil(L);
272
- }
273
- }
274
- /** Push a JS array as a Lua table (1-based) */
275
- function pushJSArray(L, arr) {
276
- lua$1.lua_createtable(L, arr.length, 0);
277
- for (let i = 0; i < arr.length; i++) {
278
- pushJSValue(L, arr[i]);
279
- lua$1.lua_rawseti(L, -2, i + 1);
280
- }
281
- }
282
- /** Push a JS object as a Lua table */
283
- function pushJSObject(L, obj) {
284
- const keys = Object.keys(obj);
285
- lua$1.lua_createtable(L, 0, keys.length);
286
- for (const key of keys) {
287
- pushJSValue(L, obj[key]);
288
- lua$1.lua_setfield(L, -2, cachedToLuastring(key));
289
- }
290
- }
291
5
 
292
- /**
293
- * Replicates the platform's action dispatch and transition evaluation.
294
- * Routes play requests to the correct action, evaluates transition conditions
295
- * against current variables to determine next actions and session operations.
296
- */
297
- class ActionRouter {
298
- actions;
299
- constructor(gameDefinition) {
300
- this.actions = gameDefinition.actions;
301
- }
302
- /** Look up action by name and validate prerequisites */
303
- resolveAction(actionName, hasSession) {
304
- const action = this.actions[actionName];
305
- if (!action) {
306
- throw new Error(`Unknown action: "${actionName}". Available: ${Object.keys(this.actions).join(', ')}`);
307
- }
308
- if (action.requires_session && !hasSession) {
309
- throw new Error(`Action "${actionName}" requires an active session`);
310
- }
311
- return action;
312
- }
313
- /** Evaluate transitions in order, return the first matching rule */
314
- evaluateTransitions(action, variables) {
315
- for (const rule of action.transitions) {
316
- if (evaluateCondition(rule.condition, variables)) {
317
- return { rule, nextActions: rule.next_actions };
318
- }
319
- }
320
- throw new Error(`No matching transition for action with stage "${action.stage}". ` +
321
- `Variables: ${JSON.stringify(variables)}`);
322
- }
323
- }
324
- // ─── Condition Evaluator ────────────────────────────────
325
- /**
326
- * Evaluates a transition condition expression against variables.
327
- *
328
- * Supports:
329
- * - "always" → true
330
- * - Simple comparisons: "var > 0", "var == 1", "var >= 10", "var != 0", "var < 5", "var <= 3"
331
- * - Logical connectives: "expr && expr", "expr || expr"
332
- *
333
- * This covers all patterns used by the platform's govaluate conditions.
334
- */
335
- function evaluateCondition(condition, variables) {
336
- const trimmed = condition.trim();
337
- if (trimmed === 'always')
338
- return true;
339
- // Handle || (OR) — lowest precedence
340
- if (trimmed.includes('||')) {
341
- const parts = splitOnOperator(trimmed, '||');
342
- return parts.some(part => evaluateCondition(part, variables));
343
- }
344
- // Handle && (AND)
345
- if (trimmed.includes('&&')) {
346
- const parts = splitOnOperator(trimmed, '&&');
347
- return parts.every(part => evaluateCondition(part, variables));
348
- }
349
- // Single comparison: "variable op value"
350
- return evaluateComparison(trimmed, variables);
351
- }
352
- function splitOnOperator(expr, operator) {
353
- const parts = [];
354
- let depth = 0;
355
- let current = '';
356
- for (let i = 0; i < expr.length; i++) {
357
- if (expr[i] === '(')
358
- depth++;
359
- else if (expr[i] === ')')
360
- depth--;
361
- if (depth === 0 && expr.substring(i, i + operator.length) === operator) {
362
- parts.push(current);
363
- current = '';
364
- i += operator.length - 1;
365
- }
366
- else {
367
- current += expr[i];
368
- }
369
- }
370
- parts.push(current);
371
- return parts;
372
- }
373
- function evaluateComparison(expr, variables) {
374
- // Match: variable_name operator value
375
- const match = expr.trim().match(/^\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*(>=|<=|!=|==|>|<)\s*(-?\d+(?:\.\d+)?)\s*$/);
376
- if (!match) {
377
- throw new Error(`Cannot parse condition: "${expr}"`);
378
- }
379
- const [, varName, op, valueStr] = match;
380
- const left = variables[varName] ?? 0;
381
- const right = parseFloat(valueStr);
382
- switch (op) {
383
- case '>': return left > right;
384
- case '>=': return left >= right;
385
- case '<': return left < right;
386
- case '<=': return left <= right;
387
- case '==': return left === right;
388
- case '!=': return left !== right;
389
- default: return false;
390
- }
391
- }
392
6
 
393
- const MAX_SESSION_SPINS = 200;
394
- /**
395
- * Manages session lifecycle matching the platform server behavior:
396
- * - createSession: initial spin counted (spinsPlayed=1, totalWin=spinWin)
397
- * - updateSession: accumulates win, decrements spins, checks max win cap on session level
398
- * - completeSession: returns cumulative totalWin, cleans up session vars
399
- * - Safety cap: 200 spins max per session
400
- */
401
- class SessionManager {
402
- session = null;
403
- get isActive() {
404
- return this.session !== null && !this.session.completed;
405
- }
406
- get current() {
407
- if (!this.session)
408
- return null;
409
- return this.toSessionData();
410
- }
411
- get sessionTotalWin() {
412
- return this.session?.totalWin ?? 0;
413
- }
414
- /** Get the fixed bet amount from the session (server uses session bet, not request bet) */
415
- get sessionBet() {
416
- return this.session?.bet;
417
- }
418
- /** Get spinsVarName to restore free_spins_remaining into variables */
419
- get spinsVarName() {
420
- return this.session?.spinsVarName;
421
- }
422
- get spinsRemaining() {
423
- return this.session?.spinsRemaining ?? 0;
424
- }
425
- /**
426
- * Create a new session from a transition rule.
427
- * Server behavior: initial spin is already counted (spinsPlayed=1, totalWin includes spinWin).
428
- */
429
- createSession(rule, variables, bet, spinWin, maxWinCap) {
430
- let spinsRemaining = -1;
431
- let spinsVarName;
432
- if (rule.session_config?.total_spins_var) {
433
- spinsVarName = rule.session_config.total_spins_var;
434
- spinsRemaining = variables[spinsVarName] ?? -1;
435
- }
436
- const persistentVarNames = rule.session_config?.persistent_vars ?? [];
437
- const persistentVars = {};
438
- for (const varName of persistentVarNames) {
439
- persistentVars[varName] = variables[varName] ?? 0;
440
- }
441
- this.session = {
442
- spinsRemaining,
443
- spinsPlayed: 1, // initial spin counts
444
- totalWin: spinWin, // initial spin win included
445
- completed: false,
446
- maxWinReached: false,
447
- bet,
448
- maxWinCap,
449
- spinsVarName,
450
- persistentVarNames,
451
- persistentVars,
452
- persistentData: {},
453
- };
454
- return this.toSessionData();
455
- }
456
- /**
457
- * Update session after a bonus spin.
458
- * Server behavior: accumulate win, decrement spins, check retrigger, check max win cap,
459
- * safety cap at 200 spins.
460
- */
461
- updateSession(rule, variables, spinWin) {
462
- if (!this.session)
463
- throw new Error('No active session');
464
- // Accumulate win and count spin
465
- this.session.totalWin += spinWin;
466
- this.session.spinsPlayed++;
467
- // Decrement spins (only for non-unlimited sessions)
468
- if (this.session.spinsRemaining > 0) {
469
- this.session.spinsRemaining--;
470
- }
471
- // Handle retrigger (add_spins_var)
472
- if (rule.add_spins_var) {
473
- const extraSpins = variables[rule.add_spins_var] ?? 0;
474
- if (extraSpins > 0 && this.session.spinsRemaining >= 0) {
475
- this.session.spinsRemaining += extraSpins;
476
- }
477
- }
478
- // Safety cap: server limits sessions to 200 spins
479
- if (this.session.spinsPlayed >= MAX_SESSION_SPINS) {
480
- this.session.spinsRemaining = 0;
481
- }
482
- // Update session persistent vars from current variables
483
- for (const varName of this.session.persistentVarNames) {
484
- if (varName in variables) {
485
- this.session.persistentVars[varName] = variables[varName];
486
- }
487
- }
488
- // Check max win cap (on session level, not per spin)
489
- if (this.session.maxWinCap !== undefined && this.session.totalWin >= this.session.maxWinCap) {
490
- this.session.totalWin = this.session.maxWinCap;
491
- this.session.spinsRemaining = 0;
492
- this.session.maxWinReached = true;
493
- }
494
- // Auto-complete if spins exhausted or explicit complete
495
- if (this.session.spinsRemaining === 0 || rule.complete_session) {
496
- this.session.completed = true;
497
- }
498
- return this.toSessionData();
499
- }
500
- /**
501
- * Complete the session explicitly.
502
- * Returns cumulative totalWin and list of session-scoped var names to clean up.
503
- */
504
- completeSession() {
505
- if (!this.session)
506
- throw new Error('No active session to complete');
507
- this.session.completed = true;
508
- const totalWin = this.session.totalWin;
509
- const session = this.toSessionData();
510
- const sessionVarNames = [...this.session.persistentVarNames];
511
- this.session = null;
512
- return { totalWin, session, sessionVarNames };
513
- }
514
- /** Mark max win reached — stops the session */
515
- markMaxWinReached() {
516
- if (this.session) {
517
- this.session.maxWinReached = true;
518
- this.session.completed = true;
519
- }
520
- }
521
- /** Store _persist_* data extracted from Lua result */
522
- storePersistData(data) {
523
- if (!this.session)
524
- return;
525
- for (const key of Object.keys(data)) {
526
- if (key.startsWith('_persist_')) {
527
- const cleanKey = key.slice('_persist_'.length);
528
- this.session.persistentData[cleanKey] = data[key];
529
- }
530
- }
531
- }
532
- /** Get persistent params to inject into next execute() call */
533
- getPersistentParams() {
534
- if (!this.session)
535
- return {};
536
- const params = {};
537
- // Session persistent vars (float64) → state.variables
538
- for (const [key, value] of Object.entries(this.session.persistentVars)) {
539
- params[key] = value;
540
- }
541
- // _persist_ complex data → _ps_* in state.params
542
- for (const [key, value] of Object.entries(this.session.persistentData)) {
543
- params[`_ps_${key}`] = value;
544
- }
545
- return params;
546
- }
547
- /** Reset all session state */
548
- reset() {
549
- this.session = null;
550
- }
551
- toSessionData() {
552
- if (!this.session)
553
- throw new Error('No session');
554
- return {
555
- spinsRemaining: this.session.spinsRemaining,
556
- spinsPlayed: this.session.spinsPlayed,
557
- totalWin: Math.round(this.session.totalWin * 100) / 100,
558
- completed: this.session.completed,
559
- maxWinReached: this.session.maxWinReached,
560
- betAmount: this.session.bet,
561
- };
562
- }
563
- }
564
-
565
- /**
566
- * Manages cross-spin persistent state — variables that survive between base game spins.
567
- * Separate from session-scoped persistence (handled by SessionManager).
568
- *
569
- * Handles two mechanisms:
570
- * 1. Numeric vars declared in `persistent_state.vars` — stored in state.variables
571
- * 2. Complex data with `_persist_game_*` prefix — stored separately, injected as `_ps_*`
572
- */
573
- class PersistentState {
574
- config;
575
- vars = {};
576
- gameData = {};
577
- constructor(config) {
578
- this.config = config;
579
- }
580
- /** Load persistent vars into variables map before execute() */
581
- loadIntoVariables(variables) {
582
- if (!this.config)
583
- return;
584
- for (const varName of this.config.vars) {
585
- if (varName in this.vars) {
586
- variables[varName] = this.vars[varName];
587
- }
588
- }
589
- }
590
- /** Save persistent vars from variables map after execute() */
591
- saveFromVariables(variables) {
592
- if (!this.config)
593
- return;
594
- for (const varName of this.config.vars) {
595
- if (varName in variables) {
596
- this.vars[varName] = variables[varName];
597
- }
598
- }
599
- }
600
- /** Extract _persist_game_* keys from Lua return data, store them */
601
- storeGameData(data) {
602
- for (const key of Object.keys(data)) {
603
- if (key.startsWith('_persist_game_')) {
604
- const cleanKey = key.slice('_persist_game_'.length);
605
- this.gameData[cleanKey] = data[key];
606
- delete data[key]; // remove from client data
607
- }
608
- }
609
- }
610
- /** Get _ps_* params for next execute() call */
611
- getGameDataParams() {
612
- const params = {};
613
- for (const [key, value] of Object.entries(this.gameData)) {
614
- params[`_ps_${key}`] = value;
615
- }
616
- return params;
617
- }
618
- /** Get exposed vars for client data.persistent_state */
619
- getExposedVars() {
620
- if (!this.config?.exposed_vars?.length)
621
- return undefined;
622
- const exposed = {};
623
- for (const varName of this.config.exposed_vars) {
624
- if (varName in this.vars) {
625
- exposed[varName] = this.vars[varName];
626
- }
627
- }
628
- return exposed;
629
- }
630
- /** Reset all state */
631
- reset() {
632
- this.vars = {};
633
- this.gameData = {};
634
- }
635
- }
636
-
637
- const { lua, lauxlib, lualib } = fengari;
638
- const { to_luastring, to_jsstring } = fengari;
639
- /** Default engine variables matching the server's NewGameState() */
640
- const DEFAULT_VARIABLES = {
641
- multiplier: 1,
642
- total_multiplier: 1,
643
- global_multiplier: 1,
644
- last_win_amount: 0,
645
- free_spins_awarded: 0,
646
- };
647
- /**
648
- * Runs Lua game scripts locally, replicating the platform's server-side execution.
649
- *
650
- * Implements the full lifecycle matching `casino_platform/internal/usecase/game_usecase.go`:
651
- * action routing → state assembly → Lua execute() → result extraction →
652
- * transition evaluation → session management.
653
- */
654
- class LuaEngine {
655
- L;
656
- api;
657
- actionRouter;
658
- sessionManager;
659
- persistentState;
660
- gameDefinition;
661
- variables = {};
662
- simulationMode;
663
- /** Reusable state objects to avoid per-iteration allocation */
664
- _stateVars = {};
665
- _stateParams = {};
666
- constructor(config) {
667
- this.gameDefinition = config.gameDefinition;
668
- this.simulationMode = config.simulationMode ?? false;
669
- const rng = config.seed !== undefined
670
- ? createSeededRng(config.seed)
671
- : undefined;
672
- this.api = new LuaEngineAPI(config.gameDefinition, rng, config.logger);
673
- this.actionRouter = new ActionRouter(config.gameDefinition);
674
- this.sessionManager = new SessionManager();
675
- this.persistentState = new PersistentState(config.gameDefinition.persistent_state);
676
- this.L = lauxlib.luaL_newstate();
677
- lualib.luaL_openlibs(this.L);
678
- // Polyfill Lua 5.1/5.2 functions removed in 5.3
679
- lauxlib.luaL_dostring(this.L, to_luastring(`
680
- math.pow = function(a, b) return a ^ b end
681
- math.atan2 = math.atan2 or function(y, x) return math.atan(y, x) end
682
- math.log10 = math.log10 or function(x) return math.log(x, 10) end
683
- math.cosh = math.cosh or function(x) return (math.exp(x) + math.exp(-x)) / 2 end
684
- math.sinh = math.sinh or function(x) return (math.exp(x) - math.exp(-x)) / 2 end
685
- math.tanh = math.tanh or function(x) return math.sinh(x) / math.cosh(x) end
686
- math.frexp = math.frexp or function(x)
687
- if x == 0 then return 0, 0 end
688
- local e = math.floor(math.log(math.abs(x), 2)) + 1
689
- return x / (2 ^ e), e
690
- end
691
- math.ldexp = math.ldexp or function(m, e) return m * (2 ^ e) end
692
- unpack = unpack or table.unpack
693
- loadstring = loadstring or load
694
- table.getn = table.getn or function(t) return #t end
695
- `));
696
- this.api.register(this.L);
697
- this.loadScript(config.script);
698
- }
699
- get session() {
700
- return this.sessionManager.current;
701
- }
702
- get persistentVars() {
703
- return { ...this.variables };
704
- }
705
- /**
706
- * Execute a play action — replicates server's Play() function.
707
- */
708
- execute(params) {
709
- const { action: actionName, params: clientParams } = params;
710
- // 1. Resolve action
711
- const action = this.actionRouter.resolveAction(actionName, this.sessionManager.isActive);
712
- // 2. Determine bet — server uses session bet for session actions
713
- let bet = params.bet;
714
- if (this.sessionManager.isActive && this.sessionManager.sessionBet !== undefined) {
715
- bet = this.sessionManager.sessionBet;
716
- }
717
- // 3. Build state.variables (matching server's NewGameState + restore)
718
- // Reuse pooled object to avoid per-iteration allocation
719
- const stateVars = this._stateVars;
720
- // Clear previous keys
721
- for (const key in stateVars)
722
- delete stateVars[key];
723
- // Apply defaults, then engine vars, then bet
724
- Object.assign(stateVars, DEFAULT_VARIABLES, this.variables);
725
- stateVars.bet = bet;
726
- // Load cross-spin persistent state
727
- this.persistentState.loadIntoVariables(stateVars);
728
- // Load session persistent vars + restore spinsRemaining
729
- if (this.sessionManager.isActive) {
730
- const sessionParams = this.sessionManager.getPersistentParams();
731
- for (const [k, v] of Object.entries(sessionParams)) {
732
- if (typeof v === 'number') {
733
- stateVars[k] = v;
734
- }
735
- }
736
- // Restore spinsRemaining into the variable the script reads
737
- if (this.sessionManager.spinsVarName) {
738
- stateVars[this.sessionManager.spinsVarName] = this.sessionManager.spinsRemaining;
739
- }
740
- // Also set free_spins_remaining for convenience
741
- stateVars.free_spins_remaining = this.sessionManager.spinsRemaining;
742
- }
743
- // 4. Build state.params (reuse pooled object)
744
- const stateParams = this._stateParams;
745
- for (const key in stateParams)
746
- delete stateParams[key];
747
- if (clientParams)
748
- Object.assign(stateParams, clientParams);
749
- stateParams._action = actionName;
750
- // Inject session _ps_* persistent data
751
- if (this.sessionManager.isActive) {
752
- const sessionParams = this.sessionManager.getPersistentParams();
753
- for (const [k, v] of Object.entries(sessionParams)) {
754
- if (typeof v !== 'number') {
755
- stateParams[k] = v;
756
- }
757
- }
758
- }
759
- // Inject cross-spin _ps_* game data
760
- const gameDataParams = this.persistentState.getGameDataParams();
761
- Object.assign(stateParams, gameDataParams);
762
- // Handle buy bonus
763
- if (action.buy_bonus_mode && this.gameDefinition.buy_bonus) {
764
- const mode = this.gameDefinition.buy_bonus.modes[action.buy_bonus_mode];
765
- if (mode) {
766
- stateParams.buy_bonus = true;
767
- stateParams.buy_bonus_mode = action.buy_bonus_mode;
768
- if (mode.scatter_distribution) {
769
- stateParams.forced_scatter_count = this.pickFromDistribution(mode.scatter_distribution);
770
- }
771
- }
772
- }
773
- // Handle ante bet
774
- if (clientParams?.ante_bet && this.gameDefinition.ante_bet) {
775
- stateParams.ante_bet = true;
776
- }
777
- // 5. Execute Lua (server: executor.Execute(stage, state))
778
- const luaResult = this.callLuaExecute(action.stage, actionName, stateParams, stateVars);
779
- // 6. Process result (server: ApplyLuaResult)
780
- const totalWinMultiplier = typeof luaResult.total_win === 'number' ? luaResult.total_win : 0;
781
- const resultVariables = (luaResult.variables ?? {});
782
- const spinWin = Math.round(totalWinMultiplier * bet * 100) / 100;
783
- // Merge ONLY Lua return variables into engine state (not the whole stateVars).
784
- // On the server, state.Variables is a temporary object rebuilt each call.
785
- // Only the Lua result's `variables` table persists between calls.
786
- Object.assign(this.variables, resultVariables);
787
- // Also update stateVars for transition evaluation below
788
- Object.assign(stateVars, resultVariables);
789
- // Build client data (everything except special keys)
790
- const data = {};
791
- for (const [key, value] of Object.entries(luaResult)) {
792
- if (key !== 'total_win' && key !== 'variables') {
793
- data[key] = value;
794
- }
795
- }
796
- // 7. Handle _persist_* and _persist_game_* keys
797
- this.sessionManager.storePersistData(data);
798
- this.persistentState.storeGameData(data);
799
- // Save cross-spin persistent state (from stateVars which has Lua result merged)
800
- this.persistentState.saveFromVariables(stateVars);
801
- // Add exposed persistent vars to client data
802
- const exposedVars = this.persistentState.getExposedVars();
803
- if (exposedVars) {
804
- data.persistent_state = exposedVars;
805
- }
806
- // Remove _persist_* keys from client data
807
- for (const key of Object.keys(data)) {
808
- if (key.startsWith('_persist_')) {
809
- delete data[key];
810
- }
811
- }
812
- // 8. Evaluate transitions (server uses state.Variables which is stateVars)
813
- const { rule, nextActions } = this.actionRouter.evaluateTransitions(action, stateVars);
814
- // 9. Determine credit behavior (server: creditNow logic)
815
- let creditDeferred = action.credit === 'defer' || rule.credit_override === 'defer';
816
- // 10. Session lifecycle (server: create/update/complete session)
817
- let session = this.sessionManager.current;
818
- let resultTotalWin = spinWin;
819
- let sessionCompleted = false;
820
- // Calculate max win cap for session
821
- const maxWinCap = this.calculateMaxWinCap(bet);
822
- if (rule.creates_session && !this.sessionManager.isActive) {
823
- // CREATE SESSION — initial spin counted (server: createSession includes spinWin)
824
- session = this.sessionManager.createSession(rule, stateVars, bet, spinWin, maxWinCap);
825
- creditDeferred = true;
826
- resultTotalWin = spinWin;
827
- // Clear the trigger variable — it was consumed to set spinsRemaining
828
- if (rule.session_config?.total_spins_var) {
829
- delete this.variables[rule.session_config.total_spins_var];
830
- }
831
- }
832
- else if (this.sessionManager.isActive) {
833
- // UPDATE SESSION — accumulate win, check completion
834
- session = this.sessionManager.updateSession(rule, stateVars, spinWin);
835
- if (session?.completed) {
836
- // SESSION COMPLETED — server returns session.TotalWin as result.TotalWin
837
- const completed = this.sessionManager.completeSession();
838
- session = completed.session;
839
- resultTotalWin = completed.totalWin;
840
- sessionCompleted = true;
841
- creditDeferred = false;
842
- // Clean up session-scoped variables
843
- for (const varName of completed.sessionVarNames) {
844
- delete this.variables[varName];
845
- }
846
- }
847
- else {
848
- // Mid-session: totalWin = spinWin, credit deferred
849
- resultTotalWin = spinWin;
850
- creditDeferred = true;
851
- }
852
- }
853
- // No session: resultTotalWin = spinWin (already set)
854
- // Apply max win cap for non-session spins
855
- if (!this.sessionManager.isActive && !sessionCompleted && maxWinCap !== undefined && resultTotalWin > maxWinCap) {
856
- resultTotalWin = maxWinCap;
857
- this.variables.max_win_reached = 1;
858
- data.max_win_reached = true;
859
- }
860
- return {
861
- totalWin: Math.round(resultTotalWin * 100) / 100,
862
- data,
863
- nextActions,
864
- session,
865
- // In simulation mode, return reference directly (caller only reads, never mutates)
866
- variables: this.simulationMode ? this.variables : { ...this.variables },
867
- creditDeferred,
868
- };
869
- }
870
- reset() {
871
- this.variables = {};
872
- this.sessionManager.reset();
873
- this.persistentState.reset();
874
- }
875
- destroy() {
876
- if (this.L) {
877
- lua.lua_close(this.L);
878
- this.L = null;
879
- }
880
- }
881
- // ─── Private ──────────────────────────────────────────
882
- loadScript(source) {
883
- const status = lauxlib.luaL_dostring(this.L, to_luastring(source));
884
- if (status !== lua.LUA_OK) {
885
- const err = to_jsstring(lua.lua_tostring(this.L, -1));
886
- lua.lua_pop(this.L, 1);
887
- throw new Error(`Failed to load Lua script: ${err}`);
888
- }
889
- lua.lua_getglobal(this.L, cachedToLuastring('execute'));
890
- if (lua.lua_type(this.L, -1) !== lua.LUA_TFUNCTION) {
891
- lua.lua_pop(this.L, 1);
892
- throw new Error('Lua script must define a global `execute(state)` function');
893
- }
894
- lua.lua_pop(this.L, 1);
895
- }
896
- callLuaExecute(stage, action, params, variables) {
897
- lua.lua_getglobal(this.L, cachedToLuastring('execute'));
898
- // Build state table: {stage, action, params, variables}
899
- lua.lua_createtable(this.L, 0, 4);
900
- // state.stage
901
- lua.lua_pushstring(this.L, cachedToLuastring(stage));
902
- lua.lua_setfield(this.L, -2, cachedToLuastring('stage'));
903
- // state.action (server sets this at top level)
904
- lua.lua_pushstring(this.L, cachedToLuastring(action));
905
- lua.lua_setfield(this.L, -2, cachedToLuastring('action'));
906
- // state.params
907
- pushJSValue(this.L, params);
908
- lua.lua_setfield(this.L, -2, cachedToLuastring('params'));
909
- // state.variables
910
- pushJSValue(this.L, variables);
911
- lua.lua_setfield(this.L, -2, cachedToLuastring('variables'));
912
- const status = lua.lua_pcall(this.L, 1, 1, 0);
913
- if (status !== lua.LUA_OK) {
914
- const err = to_jsstring(lua.lua_tostring(this.L, -1));
915
- lua.lua_pop(this.L, 1);
916
- throw new Error(`Lua execute() failed: ${err}`);
917
- }
918
- if (this.simulationMode) {
919
- // Fast path: extract only total_win, variables, _persist_* keys
920
- const result = {};
921
- lua.lua_getfield(this.L, -1, cachedToLuastring('total_win'));
922
- result.total_win = lua.lua_type(this.L, -1) === lua.LUA_TNUMBER
923
- ? lua.lua_tonumber(this.L, -1) : 0;
924
- lua.lua_pop(this.L, 1);
925
- lua.lua_getfield(this.L, -1, cachedToLuastring('variables'));
926
- if (lua.lua_type(this.L, -1) === lua.LUA_TTABLE) {
927
- result.variables = luaToJS(this.L, -1);
928
- }
929
- lua.lua_pop(this.L, 1);
930
- // Scan for _persist_* keys (different stages may or may not have them)
931
- lua.lua_pushnil(this.L);
932
- while (lua.lua_next(this.L, -2) !== 0) {
933
- if (lua.lua_type(this.L, -2) === lua.LUA_TSTRING) {
934
- const key = to_jsstring(lua.lua_tostring(this.L, -2));
935
- if (key.startsWith('_persist_')) {
936
- result[key] = luaToJS(this.L, -1);
937
- }
938
- }
939
- lua.lua_pop(this.L, 1);
940
- }
941
- lua.lua_pop(this.L, 1);
942
- return result;
943
- }
944
- // Full path
945
- const result = luaToJS(this.L, -1);
946
- lua.lua_pop(this.L, 1);
947
- if (!result || typeof result !== 'object' || Array.isArray(result)) {
948
- throw new Error('Lua execute() must return a table');
949
- }
950
- return result;
951
- }
952
- calculateMaxWinCap(bet) {
953
- const mw = this.gameDefinition.max_win;
954
- if (!mw)
955
- return undefined;
956
- const caps = [];
957
- if (mw.multiplier !== undefined)
958
- caps.push(bet * mw.multiplier);
959
- if (mw.fixed !== undefined)
960
- caps.push(mw.fixed);
961
- return caps.length > 0 ? Math.min(...caps) : undefined;
962
- }
963
- pickFromDistribution(distribution) {
964
- const entries = Object.entries(distribution);
965
- const totalWeight = entries.reduce((sum, [, w]) => sum + w, 0);
966
- let roll = this.api.randomFloat() * totalWeight;
967
- for (const [value, weight] of entries) {
968
- roll -= weight;
969
- if (roll < 0)
970
- return parseInt(value, 10);
971
- }
972
- return parseInt(entries[entries.length - 1][0], 10);
973
- }
974
- }
975
-
976
- /**
977
- * Runs N iterations of a Lua game script and collects RTP statistics.
978
- * Supports regular spins, buy bonus, and ante bet simulation.
979
- *
980
- * @example
981
- * ```ts
982
- * const runner = new SimulationRunner({
983
- * script: luaSource,
984
- * gameDefinition,
985
- * iterations: 1_000_000,
986
- * bet: 1.0,
987
- * seed: 42,
988
- * onProgress: (done, total) => console.log(`${done}/${total}`),
989
- * });
990
- *
991
- * const result = runner.run();
992
- * console.log(`RTP: ${result.totalRtp.toFixed(2)}%`);
993
- * ```
994
- */
995
- class SimulationRunner {
996
- config;
997
- constructor(config) {
998
- this.config = config;
999
- }
1000
- run() {
1001
- const { script, gameDefinition, iterations, bet, seed, action: startAction = 'spin', params, progressInterval = 100_000, onProgress, } = this.config;
1002
- const engine = new LuaEngine({
1003
- script,
1004
- gameDefinition,
1005
- seed,
1006
- logger: () => { },
1007
- simulationMode: true,
1008
- });
1009
- const spinCost = this.calculateSpinCost(startAction, bet, gameDefinition, params);
1010
- let totalWagered = 0;
1011
- let totalWon = 0;
1012
- let baseGameWin = 0;
1013
- let bonusWin = 0;
1014
- let hits = 0;
1015
- let maxWinMultiplier = 0;
1016
- let maxWinHits = 0;
1017
- let bonusTriggered = 0;
1018
- let bonusSpinsPlayed = 0;
1019
- const startTime = Date.now();
1020
- try {
1021
- for (let i = 0; i < iterations; i++) {
1022
- totalWagered += spinCost;
1023
- let roundWin = 0;
1024
- let roundBonusWin = 0;
1025
- // Execute the starting action
1026
- let result = engine.execute({
1027
- action: startAction,
1028
- bet,
1029
- params,
1030
- });
1031
- const baseWin = result.totalWin;
1032
- // If a session was created, play through it using nextActions from the engine
1033
- if (result.session && !result.session.completed) {
1034
- bonusTriggered++;
1035
- let safetyLimit = 10_000;
1036
- while (result.session && !result.session.completed && safetyLimit-- > 0) {
1037
- const nextAction = result.nextActions[0];
1038
- result = engine.execute({ action: nextAction, bet });
1039
- bonusSpinsPlayed++;
1040
- }
1041
- // Session completion returns cumulative totalWin (includes trigger spin).
1042
- // Use it as the full round win — don't add baseWin separately.
1043
- roundWin = result.totalWin;
1044
- roundBonusWin = roundWin - baseWin;
1045
- }
1046
- else {
1047
- // No session — just base game win
1048
- roundWin = baseWin;
1049
- }
1050
- baseGameWin += baseWin;
1051
- bonusWin += roundBonusWin;
1052
- totalWon += roundWin;
1053
- if (roundWin > 0)
1054
- hits++;
1055
- const roundMultiplier = roundWin / bet;
1056
- if (roundMultiplier > maxWinMultiplier) {
1057
- maxWinMultiplier = roundMultiplier;
1058
- }
1059
- if (result.variables?.max_win_reached === 1) {
1060
- maxWinHits++;
1061
- }
1062
- // Progress reporting
1063
- if (onProgress && (i + 1) % progressInterval === 0) {
1064
- onProgress(i + 1, iterations);
1065
- }
1066
- }
1067
- }
1068
- finally {
1069
- engine.destroy();
1070
- }
1071
- const durationMs = Date.now() - startTime;
1072
- return {
1073
- gameId: gameDefinition.id,
1074
- action: startAction,
1075
- iterations,
1076
- durationMs,
1077
- totalRtp: totalWagered > 0 ? (totalWon / totalWagered) * 100 : 0,
1078
- baseGameRtp: totalWagered > 0 ? (baseGameWin / totalWagered) * 100 : 0,
1079
- bonusRtp: totalWagered > 0 ? (bonusWin / totalWagered) * 100 : 0,
1080
- hitFrequency: iterations > 0 ? (hits / iterations) * 100 : 0,
1081
- maxWin: Math.round(maxWinMultiplier * 100) / 100,
1082
- maxWinHits,
1083
- bonusTriggered,
1084
- bonusSpinsPlayed,
1085
- _raw: { totalWagered, totalWon, baseGameWin, bonusWin, hits },
1086
- };
1087
- }
1088
- /** Calculate the real cost of one spin (accounting for buy bonus / ante bet) */
1089
- calculateSpinCost(action, bet, gameDefinition, params) {
1090
- // Check if this is a buy bonus action
1091
- const actionDef = gameDefinition.actions[action];
1092
- if (actionDef?.buy_bonus_mode && gameDefinition.buy_bonus) {
1093
- const mode = gameDefinition.buy_bonus.modes[actionDef.buy_bonus_mode];
1094
- if (mode) {
1095
- return bet * mode.cost_multiplier;
1096
- }
1097
- }
1098
- // Check ante bet
1099
- if (params?.ante_bet && gameDefinition.ante_bet) {
1100
- return bet * gameDefinition.ante_bet.cost_multiplier;
1101
- }
1102
- return bet;
1103
- }
1104
- }
1105
- /** Format a SimulationResult for console output */
1106
- function formatSimulationResult(result) {
1107
- const lines = [
1108
- '',
1109
- '--- Simulation Results ---',
1110
- `Game: ${result.gameId}`,
1111
- `Action: ${result.action}`,
1112
- `Iterations: ${result.iterations.toLocaleString()}`,
1113
- `Duration: ${(result.durationMs / 1000).toFixed(1)}s`,
1114
- `Total RTP: ${result.totalRtp.toFixed(2)}%`,
1115
- `Base Game RTP: ${result.baseGameRtp.toFixed(2)}%`,
1116
- `Bonus RTP: ${result.bonusRtp.toFixed(2)}%`,
1117
- `Hit Frequency: ${result.hitFrequency.toFixed(2)}%`,
1118
- `Max Win: ${result.maxWin.toFixed(2)}x`,
1119
- `Max Win Hits: ${result.maxWinHits} (rounds capped by max_win)`,
1120
- ];
1121
- if (result.bonusTriggered > 0) {
1122
- const frequency = Math.round(result.iterations / result.bonusTriggered);
1123
- lines.push(`Bonus Triggered: ${result.bonusTriggered.toLocaleString()} (1 in ${frequency} spins)`);
1124
- lines.push(`Bonus Spins Played: ${result.bonusSpinsPlayed.toLocaleString()}`);
1125
- }
1126
- return lines.join('\n');
1127
- }
1128
-
1129
- /// <reference types="node" />
1130
- const SEED_STRIDE = 1 << 20; // 2^20 — gap between worker seeds to avoid overlap
1131
- /**
1132
- * Runs simulation across multiple worker threads for parallel speedup.
1133
- * Each worker gets an independent LuaEngine with a partitioned seed range.
1134
- *
1135
- * Results are statistically equivalent to single-threaded mode but not
1136
- * bit-identical (different RNG sequence ordering).
1137
- *
1138
- * @example
1139
- * ```ts
1140
- * const runner = new ParallelSimulationRunner({
1141
- * script: luaSource,
1142
- * gameDefinition,
1143
- * iterations: 1_000_000,
1144
- * bet: 1.0,
1145
- * workerCount: 8,
1146
- * onProgress: (done, total) => console.log(`${done}/${total}`),
1147
- * });
1148
- * const result = await runner.run();
1149
- * ```
1150
- */
1151
- class ParallelSimulationRunner {
1152
- config;
1153
- workerCount;
1154
- constructor(config) {
1155
- this.config = config;
1156
- const maxWorkers = os.cpus().length;
1157
- this.workerCount = Math.max(1, Math.min(config.workerCount ?? maxWorkers, maxWorkers, config.iterations));
1158
- }
1159
- async run() {
1160
- const { iterations, seed, onProgress, workerCount: _, ...restConfig } = this.config;
1161
- const workerCount = this.workerCount;
1162
- // Split iterations evenly, remainder goes to last worker
1163
- const baseChunk = Math.floor(iterations / workerCount);
1164
- const remainder = iterations - baseChunk * workerCount;
1165
- const workerPath = path.join(path.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('lua.cjs.js', document.baseURI).href)))), 'SimulationWorker.ts');
1166
- const progressPerWorker = new Array(workerCount).fill(0);
1167
- const totalIterations = iterations;
1168
- const promises = Array.from({ length: workerCount }, (_, i) => {
1169
- const workerIterations = baseChunk + (i < remainder ? 1 : 0);
1170
- const workerSeed = seed !== undefined ? seed + i * SEED_STRIDE : undefined;
1171
- const workerConfig = {
1172
- config: {
1173
- ...restConfig,
1174
- iterations: workerIterations,
1175
- seed: workerSeed,
1176
- progressInterval: this.config.progressInterval,
1177
- },
1178
- };
1179
- return new Promise((resolve, reject) => {
1180
- const worker = new worker_threads.Worker(workerPath, {
1181
- workerData: workerConfig,
1182
- // tsx registers itself via --require/--import; pass through to workers
1183
- execArgv: process.execArgv,
1184
- });
1185
- worker.on('message', (msg) => {
1186
- if (msg.type === 'progress' && onProgress) {
1187
- progressPerWorker[i] = msg.progress.completed;
1188
- const totalCompleted = progressPerWorker.reduce((a, b) => a + b, 0);
1189
- onProgress(totalCompleted, totalIterations);
1190
- }
1191
- else if (msg.type === 'result') {
1192
- resolve(msg.result);
1193
- }
1194
- else if (msg.type === 'error') {
1195
- reject(new Error(`Worker ${i} failed: ${msg.error}`));
1196
- }
1197
- });
1198
- worker.on('error', (err) => reject(new Error(`Worker ${i} error: ${err.message}`)));
1199
- worker.on('exit', (code) => {
1200
- if (code !== 0)
1201
- reject(new Error(`Worker ${i} exited with code ${code}`));
1202
- });
1203
- });
1204
- });
1205
- const results = await Promise.all(promises);
1206
- return aggregateResults(results);
1207
- }
1208
- }
1209
- function aggregateResults(results) {
1210
- const raw = {
1211
- totalWagered: 0,
1212
- totalWon: 0,
1213
- baseGameWin: 0,
1214
- bonusWin: 0,
1215
- hits: 0,
1216
- };
1217
- let iterations = 0;
1218
- let maxWin = 0;
1219
- let maxWinHits = 0;
1220
- let bonusTriggered = 0;
1221
- let bonusSpinsPlayed = 0;
1222
- let maxDurationMs = 0;
1223
- for (const r of results) {
1224
- const rr = r._raw;
1225
- raw.totalWagered += rr.totalWagered;
1226
- raw.totalWon += rr.totalWon;
1227
- raw.baseGameWin += rr.baseGameWin;
1228
- raw.bonusWin += rr.bonusWin;
1229
- raw.hits += rr.hits;
1230
- iterations += r.iterations;
1231
- if (r.maxWin > maxWin)
1232
- maxWin = r.maxWin;
1233
- maxWinHits += r.maxWinHits;
1234
- bonusTriggered += r.bonusTriggered;
1235
- bonusSpinsPlayed += r.bonusSpinsPlayed;
1236
- if (r.durationMs > maxDurationMs)
1237
- maxDurationMs = r.durationMs;
1238
- }
1239
- return {
1240
- gameId: results[0].gameId,
1241
- action: results[0].action,
1242
- iterations,
1243
- durationMs: maxDurationMs,
1244
- totalRtp: raw.totalWagered > 0 ? (raw.totalWon / raw.totalWagered) * 100 : 0,
1245
- baseGameRtp: raw.totalWagered > 0 ? (raw.baseGameWin / raw.totalWagered) * 100 : 0,
1246
- bonusRtp: raw.totalWagered > 0 ? (raw.bonusWin / raw.totalWagered) * 100 : 0,
1247
- hitFrequency: iterations > 0 ? (raw.hits / iterations) * 100 : 0,
1248
- maxWin,
1249
- maxWinHits,
1250
- bonusTriggered,
1251
- bonusSpinsPlayed,
1252
- _raw: raw,
1253
- };
1254
- }
1255
-
1256
- // ─── Runner ─────────────────────────────────────────────
1257
- class NativeSimulationRunner {
1258
- config;
1259
- constructor(config) {
1260
- this.config = config;
1261
- }
1262
- async run() {
1263
- const { binaryPath, script, gameDefinition, iterations, bet, action, params } = this.config;
1264
- const id = crypto.randomBytes(8).toString('hex');
1265
- const tmpDir = os.tmpdir();
1266
- const luaPath = path.join(tmpDir, `sim-${id}.lua`);
1267
- const configPath = path.join(tmpDir, `sim-${id}.json`);
1268
- try {
1269
- // Write temp files
1270
- await Promise.all([
1271
- promises.writeFile(luaPath, script, 'utf-8'),
1272
- promises.writeFile(configPath, JSON.stringify({ ...gameDefinition, script_path: luaPath }), 'utf-8'),
1273
- ]);
1274
- // Build CLI args
1275
- const args = [
1276
- '-config', configPath,
1277
- '-iterations', String(iterations),
1278
- '-bet', String(bet),
1279
- '-format', 'json',
1280
- ];
1281
- if (action) {
1282
- args.push('-action', action);
1283
- }
1284
- if (params && Object.keys(params).length > 0) {
1285
- args.push('-params', JSON.stringify(params));
1286
- }
1287
- // Execute binary
1288
- const output = await this.exec(binaryPath, args);
1289
- // Parse JSON output
1290
- const json = JSON.parse(output);
1291
- return mapGoResult(json);
1292
- }
1293
- finally {
1294
- // Cleanup temp files
1295
- await Promise.allSettled([promises.unlink(luaPath), promises.unlink(configPath)]);
1296
- }
1297
- }
1298
- exec(binary, args) {
1299
- return new Promise((resolve, reject) => {
1300
- const child = child_process.spawn(binary, args, { stdio: ['ignore', 'pipe', 'pipe'] });
1301
- let stdout = '';
1302
- let stderr = '';
1303
- child.stdout.on('data', (chunk) => {
1304
- stdout += chunk.toString();
1305
- });
1306
- child.stderr.on('data', (chunk) => {
1307
- stderr += chunk.toString();
1308
- });
1309
- child.on('error', (err) => {
1310
- reject(new Error(`Failed to execute simulation binary: ${err.message}`));
1311
- });
1312
- child.on('close', (code) => {
1313
- if (code !== 0) {
1314
- reject(new Error(`Simulation binary exited with code ${code}: ${stderr.trim()}`));
1315
- }
1316
- else {
1317
- resolve(stdout);
1318
- }
1319
- });
1320
- });
1321
- }
1322
- }
1323
- // ─── Result mapping ─────────────────────────────────────
1324
- function mapGoResult(json) {
1325
- const baseStage = json.per_stage_stats?.base_game;
1326
- const baseGameRtp = baseStage?.rtp ?? 0;
1327
- const baseGameWin = baseStage?.total_win ?? 0;
1328
- const perStage = json.per_stage_stats
1329
- ? Object.fromEntries(Object.entries(json.per_stage_stats).map(([key, s]) => [
1330
- key,
1331
- {
1332
- totalWin: s.total_win,
1333
- spinCount: s.spin_count,
1334
- hitCount: s.hit_count,
1335
- maxWin: s.max_win,
1336
- rtp: s.rtp,
1337
- perSpinRtp: s.per_spin_rtp,
1338
- hitFrequency: s.hit_frequency,
1339
- avgWin: s.avg_win,
1340
- },
1341
- ]))
1342
- : undefined;
1343
- return {
1344
- gameId: json.game_id,
1345
- action: 'spin',
1346
- iterations: json.iterations,
1347
- durationMs: Math.round(json.duration_sec * 1000),
1348
- totalRtp: json.total_rtp,
1349
- baseGameRtp,
1350
- bonusRtp: json.total_rtp - baseGameRtp,
1351
- hitFrequency: json.hit_frequency,
1352
- maxWin: json.max_win,
1353
- maxWinHits: json.max_win_hits,
1354
- bonusTriggered: json.bonus_triggered,
1355
- bonusSpinsPlayed: json.bonus_spins_total,
1356
- speed: json.speed,
1357
- workersUsed: json.workers_used,
1358
- perStage,
1359
- winDistribution: json.win_distribution,
1360
- _raw: {
1361
- totalWagered: json.total_bet,
1362
- totalWon: json.total_win,
1363
- baseGameWin,
1364
- bonusWin: json.total_win - baseGameWin,
1365
- hits: json.iterations > 0 ? Math.round((json.hit_frequency * json.iterations) / 100) : 0,
1366
- },
1367
- };
1368
- }
1369
- // ─── Binary discovery ───────────────────────────────────
1370
- /**
1371
- * Search for a native simulation binary in standard locations.
1372
- * Returns the absolute path if found, null otherwise.
1373
- */
1374
- function findNativeBinary(baseDir) {
1375
- // 1. Explicit env var
1376
- const envPath = process.env.SIMULATE_BINARY;
1377
- if (envPath && isExecutable(envPath)) {
1378
- return envPath;
1379
- }
1380
- const platform = process.platform; // darwin, linux, win32
1381
- const nodeArch = process.arch; // arm64, x64
1382
- const goArch = nodeArch === 'x64' ? 'amd64' : nodeArch;
1383
- const goPlatform = platform === 'win32' ? 'windows' : platform;
1384
- const ext = platform === 'win32' ? '.exe' : '';
1385
- const names = [
1386
- `simulate-${goPlatform}-${goArch}${ext}`,
1387
- `simulation-${goPlatform}-${goArch}${ext}`,
1388
- `simulate${ext}`,
1389
- `simulation${ext}`,
1390
- ];
1391
- // Search directories: user's project first, then this package's bin/
1392
- const searchDirs = [];
1393
- if (baseDir)
1394
- searchDirs.push(baseDir);
1395
- // This package's root (where postinstall downloads the binary)
1396
- try {
1397
- const pkgRoot = path.join(path.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('lua.cjs.js', document.baseURI).href)))), '..');
1398
- if (!searchDirs.includes(pkgRoot))
1399
- searchDirs.push(pkgRoot);
1400
- }
1401
- catch {
1402
- // fallback for CJS
1403
- if (typeof __dirname !== 'undefined') {
1404
- const pkgRoot = path.join(__dirname, '..');
1405
- if (!searchDirs.includes(pkgRoot))
1406
- searchDirs.push(pkgRoot);
1407
- }
1408
- }
1409
- for (const dir of searchDirs) {
1410
- for (const name of names) {
1411
- const candidate = path.join(dir, 'bin', name);
1412
- if (isExecutable(candidate))
1413
- return candidate;
1414
- }
1415
- }
1416
- // Check $PATH
1417
- for (const bin of ['simulate', 'simulation']) {
1418
- try {
1419
- const cmd = platform === 'win32' ? `where ${bin}` : `which ${bin}`;
1420
- const result = child_process.execSync(cmd, { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'ignore'] }).trim();
1421
- if (result)
1422
- return result.split('\n')[0];
1423
- }
1424
- catch {
1425
- // not found
1426
- }
1427
- }
1428
- return null;
1429
- }
1430
- function isExecutable(path) {
1431
- try {
1432
- fs.accessSync(path, fs.constants.X_OK);
1433
- return true;
1434
- }
1435
- catch {
1436
- return false;
1437
- }
1438
- }
1439
- // ─── Extended formatting ────────────────────────────────
1440
- /** Format a NativeSimulationResult with per-stage and distribution data */
1441
- function formatNativeResult(result) {
1442
- const lines = [
1443
- '',
1444
- '--- Simulation Results ---',
1445
- `Game: ${result.gameId}`,
1446
- `Iterations: ${result.iterations.toLocaleString()}`,
1447
- `Duration: ${(result.durationMs / 1000).toFixed(1)}s`,
1448
- ];
1449
- if (result.speed) {
1450
- lines.push(`Speed: ${Math.round(result.speed).toLocaleString()} iterations/sec`);
1451
- }
1452
- if (result.workersUsed) {
1453
- lines.push(`Workers: ${result.workersUsed}`);
1454
- }
1455
- lines.push('', '--- Total ---', `Total RTP: ${result.totalRtp.toFixed(2)}%`, `Base Game RTP: ${result.baseGameRtp.toFixed(2)}%`, `Bonus RTP: ${result.bonusRtp.toFixed(2)}%`, `Hit Frequency: ${result.hitFrequency.toFixed(2)}%`, `Max Win: ${result.maxWin.toFixed(2)}x`, `Max Win Cap Hits: ${result.maxWinHits}`);
1456
- if (result.bonusTriggered > 0) {
1457
- const frequency = Math.round(result.iterations / result.bonusTriggered);
1458
- lines.push('', '--- Bonus Stats ---', `Bonus Triggered: ${result.bonusTriggered.toLocaleString()} (1 in ${frequency} spins)`, `Bonus Spins Total: ${result.bonusSpinsPlayed.toLocaleString()}`);
1459
- }
1460
- // Per-stage breakdown
1461
- if (result.perStage && Object.keys(result.perStage).length > 0) {
1462
- lines.push('', '--- Per-Stage Breakdown ---');
1463
- const header = 'Stage | Spins | RTP (contrib) | Per-Spin RTP | Hit Freq | Avg Win | Max Win';
1464
- lines.push(header);
1465
- lines.push('-'.repeat(header.length));
1466
- for (const [stage, stats] of Object.entries(result.perStage)) {
1467
- lines.push(`${stage.padEnd(20)} | ${String(stats.spinCount).padStart(10)} | ` +
1468
- `${stats.rtp.toFixed(2).padStart(12)}% | ` +
1469
- `${stats.perSpinRtp.toFixed(2).padStart(11)}% | ` +
1470
- `${stats.hitFrequency.toFixed(2).padStart(8)}% | ` +
1471
- `${stats.avgWin.toFixed(3).padStart(8)}x | ` +
1472
- `${stats.maxWin.toFixed(2).padStart(8)}x`);
1473
- }
1474
- }
1475
- // Win distribution
1476
- if (result.winDistribution && result.winDistribution.length > 0) {
1477
- lines.push('', '--- Win Distribution ---');
1478
- for (const bucket of result.winDistribution) {
1479
- const bar = '█'.repeat(Math.round(bucket.pct / 2));
1480
- lines.push(`${bucket.label.padEnd(10)} ${String(bucket.count).padStart(10)} (${bucket.pct.toFixed(2).padStart(6)}%) ${bar}`);
1481
- }
1482
- }
1483
- return lines.join('\n');
1484
- }
1485
-
1486
- exports.ActionRouter = ActionRouter;
1487
- exports.LuaEngine = LuaEngine;
1488
- exports.LuaEngineAPI = LuaEngineAPI;
1489
- exports.NativeSimulationRunner = NativeSimulationRunner;
1490
- exports.ParallelSimulationRunner = ParallelSimulationRunner;
1491
- exports.PersistentState = PersistentState;
1492
- exports.SessionManager = SessionManager;
1493
- exports.SimulationRunner = SimulationRunner;
1494
- exports.createSeededRng = createSeededRng;
1495
- exports.evaluateCondition = evaluateCondition;
1496
- exports.findNativeBinary = findNativeBinary;
1497
- exports.formatNativeResult = formatNativeResult;
1498
- exports.formatSimulationResult = formatSimulationResult;
7
+ Object.keys(lua).forEach(function (k) {
8
+ if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
9
+ enumerable: true,
10
+ get: function () { return lua[k]; }
11
+ });
12
+ });
1499
13
  //# sourceMappingURL=lua.cjs.js.map