From 44a6892f037ba0128ad8ec026b393e4678b7709b Mon Sep 17 00:00:00 2001 From: ceifa Date: Sat, 18 Jan 2025 13:36:21 -0300 Subject: [PATCH 01/83] change apis to accept an option object directly --- src/factory.ts | 17 ++++++++++------- src/luawasm.ts | 20 +++++++++++++++----- src/types.ts | 2 -- 3 files changed, 25 insertions(+), 14 deletions(-) diff --git a/src/factory.ts b/src/factory.ts index 63449f5..0ef86d7 100755 --- a/src/factory.ts +++ b/src/factory.ts @@ -2,7 +2,7 @@ import version from 'package-version' import LuaEngine from './engine' import LuaWasm from './luawasm' -import { CreateEngineOptions, EnvironmentVariables } from './types' +import { CreateEngineOptions } from './types' /** * Represents a factory for creating and configuring Lua engines. @@ -12,21 +12,24 @@ export default class LuaFactory { /** * Constructs a new LuaFactory instance. - * @param [customWasmUri] - Custom URI for the Lua WebAssembly module. - * @param [environmentVariables] - Environment variables for the Lua engine. + * @param opts.wasmFile - Custom URI for the Lua WebAssembly module. + * @param opts.env - Environment variables for the Lua engine. + * @param opts.stdin - Standard input for the Lua engine. + * @param opts.stdout - Standard output for the Lua engine. + * @param opts.stderr - Standard error for the Lua engine. */ - public constructor(customWasmUri?: string, environmentVariables?: EnvironmentVariables) { - if (customWasmUri === undefined) { + public constructor(opts: Parameters[0] = {}) { + if (opts.wasmFile === undefined) { const isBrowser = (typeof window === 'object' && typeof window.document !== 'undefined') || (typeof self === 'object' && self?.constructor?.name === 'DedicatedWorkerGlobalScope') if (isBrowser) { - customWasmUri = `https://unpkg.com/wasmoon@${version}/dist/glue.wasm` + opts.wasmFile = `https://unpkg.com/wasmoon@${version}/dist/glue.wasm` } } - this.luaWasmPromise = LuaWasm.initialize(customWasmUri, environmentVariables) + this.luaWasmPromise = LuaWasm.initialize(opts) } /** diff --git a/src/luawasm.ts b/src/luawasm.ts index 98ed2cd..04b5b34 100755 --- a/src/luawasm.ts +++ b/src/luawasm.ts @@ -1,5 +1,7 @@ import initWasmModule from '../build/glue.js' -import { EnvironmentVariables, LUA_REGISTRYINDEX, LuaReturn, LuaState, LuaType } from './types' +import { LUA_REGISTRYINDEX, LuaReturn, LuaState, LuaType } from './types' + +type EnvironmentVariables = Record interface LuaEmscriptenModule extends EmscriptenModule { ccall: typeof ccall @@ -21,15 +23,23 @@ interface ReferenceMetadata { } export default class LuaWasm { - public static async initialize(customWasmFileLocation?: string, environmentVariables?: EnvironmentVariables): Promise { + public static async initialize(opts: { + wasmFile?: string + env?: EnvironmentVariables + stdin?: () => number | null + stdout?: () => number | null + stderr?: () => number | null + }): Promise { const module: LuaEmscriptenModule = await initWasmModule({ locateFile: (path: string, scriptDirectory: string) => { - return customWasmFileLocation || scriptDirectory + path + return opts.wasmFile || scriptDirectory + path }, preRun: (initializedModule: LuaEmscriptenModule) => { - if (typeof environmentVariables === 'object') { - Object.entries(environmentVariables).forEach(([k, v]) => (initializedModule.ENV[k] = v)) + if (typeof opts?.env === 'object') { + Object.entries(opts.env).forEach(([k, v]) => (initializedModule.ENV[k] = v)) } + + initializedModule.FS.init(opts?.stdin ?? null, opts?.stdout ?? null, opts?.stderr ?? null) }, }) return new LuaWasm(module) diff --git a/src/types.ts b/src/types.ts index 64e89a8..1e12c75 100755 --- a/src/types.ts +++ b/src/types.ts @@ -1,7 +1,5 @@ export type LuaState = number -export type EnvironmentVariables = Record - export interface CreateEngineOptions { /** Injects all the lua standard libraries (math, coroutine, debug) */ openStandardLibs?: boolean From fce233a7e719ea24ae567474adfa0dd28628c548 Mon Sep 17 00:00:00 2001 From: ceifa Date: Sat, 18 Jan 2025 13:36:28 -0300 Subject: [PATCH 02/83] convert bin to esm --- bin/wasmoon | 171 +++++++++++++++++++++----------------------- test/engine.test.js | 10 +-- tsconfig.json | 3 +- 3 files changed, 88 insertions(+), 96 deletions(-) diff --git a/bin/wasmoon b/bin/wasmoon index 9100384..92cd027 100755 --- a/bin/wasmoon +++ b/bin/wasmoon @@ -1,114 +1,107 @@ #!/usr/bin/env node -const { LuaFactory, LuaReturn, LuaType, LUA_MULTRET, decorate } = require('../dist') -const fs = require('fs') -const path = require('path') -const readline = require('readline') - -async function* walk(dir) { - const dirents = await fs.promises.readdir(dir, { withFileTypes: true }) - for (const dirent of dirents) { - const res = path.resolve(dir, dirent.name) - if (dirent.isDirectory()) { - yield* walk(res) - } else { - yield res - } +import { LuaFactory, LuaReturn, LuaType, LUA_MULTRET, decorate } from '../dist/index.js' +import pkg from '../package.json' with { type: 'json' } +import fs from 'node:fs' +import path from 'node:path' +import readline from 'node:readline' + +const factory = new LuaFactory() +const luamodule = await factory.getLuaModule() +const lua = await factory.createEngine() + +let snippets = process.argv.splice(2) + +const consumeOption = (option, single) => { + let i = -1 + const values = [] + while ((i = snippets.indexOf(option)) >= 0) { + values.push(snippets.splice(i, single ? 1 : 2).reverse()[0]) } + return values } -async function main() { - const factory = new LuaFactory() - const luamodule = await factory.getLuaModule() - const lua = await factory.createEngine() - - let snippets = process.argv.splice(2) +const warnings = consumeOption('-W', true).length > 0 +if (warnings) { + luamodule.lua_warning(lua.global.address, '@on', 0) +} - const consumeOption = (option, single) => { - let i = -1 - const values = [] - while ((i = snippets.indexOf(option)) >= 0) { - values.push(snippets.splice(i, single ? 1 : 2).reverse()[0]) - } - return values - } +const executes = consumeOption('-e') +for (const execute of executes) { + await lua.doString(execute) +} - const includes = consumeOption('-l') - const forceInteractive = consumeOption('-i', true).length > 0 - const runFile = process.stdin.isTTY && consumeOption(snippets[0], true)[0] - const args = snippets +const includes = consumeOption('-l') +const forceInteractive = consumeOption('-i', true).length > 0 +const runFile = process.stdin.isTTY && consumeOption(snippets[0], true)[0] +const args = snippets - for (const include of includes) { - const relativeInclude = path.resolve(process.cwd(), include) - const stat = await fs.promises.lstat(relativeInclude) - if (stat.isFile()) { - await factory.mountFile(relativeInclude, await fs.promises.readFile(relativeInclude)) - } else { - for await (const file of walk(relativeInclude)) { - await factory.mountFile(file, await fs.promises.readFile(file)) - } +for (const include of includes) { + const relativeInclude = path.resolve(process.cwd(), include) + const stat = await fs.promises.lstat(relativeInclude) + if (stat.isFile()) { + await factory.mountFile(relativeInclude, await fs.promises.readFile(relativeInclude)) + } else { + for (const file of await fs.promises.readdir(relativeInclude, { recursive: true })) { + await factory.mountFile(file, await fs.promises.readFile(file)) } } +} - lua.global.set('arg', decorate(args, { disableProxy: true })) +lua.global.set('arg', decorate(args, { disableProxy: true })) - const interactive = process.stdin.isTTY && (forceInteractive || !runFile) +const interactive = process.stdin.isTTY && (forceInteractive || !runFile) - if (runFile) { - const relativeRunFile = path.resolve(process.cwd(), runFile) - await factory.mountFile(relativeRunFile, await fs.promises.readFile(relativeRunFile)) +if (runFile) { + const relativeRunFile = path.resolve(process.cwd(), runFile) + await factory.mountFile(relativeRunFile, await fs.promises.readFile(relativeRunFile)) - await lua.doFile(relativeRunFile) - console.log(lua.global.indexToString(-1)) - } + await lua.doFile(relativeRunFile) + console.log(lua.global.indexToString(-1)) +} - if (!interactive && runFile) { - return - } +if (!interactive && runFile) { + process.exit(0) +} - if (interactive) { - // Call directly from module to bypass the result verification - const loadcode = (code) => !lua.global.setTop(0) && luamodule.luaL_loadstring(lua.global.address, code) === LuaReturn.Ok +if (interactive) { + // Call directly from module to bypass the result verification + const loadcode = (code) => !lua.global.setTop(0) && luamodule.luaL_loadstring(lua.global.address, code) === LuaReturn.Ok - const version = require('../package.json').version - console.log('Welcome to Wasmoon v' + version) + const version = pkg.version + const luaversion = lua.global.get('_VERSION') + console.log(`Welcome to Wasmoon ${version} (${luaversion})`) - const rl = readline.createInterface({ - input: process.stdin, - output: process.stdout, - terminal: true, - removeHistoryDuplicates: true, - }) + const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + terminal: true, + removeHistoryDuplicates: true, + }) - rl.prompt() + rl.prompt() - for await (const line of rl) { - const loaded = loadcode(line) || loadcode(`return ${line}`) - if (!loaded) { - console.log(lua.global.getValue(-1, LuaType.String)) - rl.prompt() - continue - } + for await (const line of rl) { + const loaded = loadcode(line) || loadcode(`return ${line}`) + if (!loaded) { + console.log(lua.global.getValue(-1, LuaType.String)) + rl.prompt() + continue + } - const result = luamodule.lua_pcallk(lua.global.address, 0, LUA_MULTRET, 0, 0, null) - if (result === LuaReturn.Ok) { - const returnValues = Array.from({ length: lua.global.getTop() }).map((_, i) => lua.global.indexToString(i + 1)) + const result = luamodule.lua_pcallk(lua.global.address, 0, LUA_MULTRET, 0, 0, null) + if (result === LuaReturn.Ok) { + const returnValues = Array.from({ length: lua.global.getTop() }).map((_, i) => lua.global.indexToString(i + 1)) - if (returnValues.length) { - console.log(...returnValues) - } - } else { - console.log(lua.global.getValue(-1, LuaType.String)) + if (returnValues.length) { + console.log(...returnValues) } - - rl.prompt() + } else { + console.log(lua.global.getValue(-1, LuaType.String)) } - } else { - await lua.doString(fs.readFileSync(0, 'utf-8')) - console.log(lua.global.indexToString(-1)) + + rl.prompt() } +} else { + await lua.doString(fs.readFileSync(0, 'utf-8')) + console.log(lua.global.indexToString(-1)) } - -main().catch((err) => { - console.error(err) - process.exit(1) -}) diff --git a/test/engine.test.js b/test/engine.test.js index 23e6361..3a1ab1f 100644 --- a/test/engine.test.js +++ b/test/engine.test.js @@ -806,13 +806,13 @@ describe('Engine', () => { it('lots of doString calls should succeed', async () => { const engine = await getEngine() - const length = 10000; + const length = 10000 for (let i = 0; i < length; i++) { - const a = Math.floor(Math.random() * 100); - const b = Math.floor(Math.random() * 100); - const result = await engine.doString(`return ${a} + ${b};`); - expect(result).to.equal(a + b); + const a = Math.floor(Math.random() * 100) + const b = Math.floor(Math.random() * 100) + const result = await engine.doString(`return ${a} + ${b};`) + expect(result).to.equal(a + b) } }) }) diff --git a/tsconfig.json b/tsconfig.json index f911e66..14dbd93 100755 --- a/tsconfig.json +++ b/tsconfig.json @@ -16,8 +16,7 @@ "noUnusedLocals": true, "importHelpers": true, "strict": true, - "resolveJsonModule": true, - + "resolveJsonModule": true }, "include": ["src/**/*", "test/**/*", "bench/**/*", "eslint.config.js"], "exclude": ["node_modules"] From 867ae7068c9516b9c1354a374f82fe7b80780854 Mon Sep 17 00:00:00 2001 From: ceifa Date: Sat, 18 Jan 2025 17:03:52 -0300 Subject: [PATCH 03/83] wip: new improved cli --- bin/wasmoon | 263 ++++++++++++++++++++++++++++++++++++++--------- build.sh | 4 +- eslint.config.js | 2 +- src/global.ts | 2 +- src/luawasm.ts | 3 +- 5 files changed, 224 insertions(+), 50 deletions(-) diff --git a/bin/wasmoon b/bin/wasmoon index 92cd027..d262f60 100755 --- a/bin/wasmoon +++ b/bin/wasmoon @@ -1,98 +1,266 @@ #!/usr/bin/env node -import { LuaFactory, LuaReturn, LuaType, LUA_MULTRET, decorate } from '../dist/index.js' +import { LuaFactory, LuaReturn, LuaType, LUA_MULTRET, LuaRawResult, decorate, decorateFunction } from '../dist/index.js' import pkg from '../package.json' with { type: 'json' } import fs from 'node:fs' import path from 'node:path' import readline from 'node:readline' -const factory = new LuaFactory() -const luamodule = await factory.getLuaModule() -const lua = await factory.createEngine() +function printUsage() { + console.log( + ` +usage: wasmoon [options] [script [args]] +Available options are: + -e stat execute string 'stat' + -i enter interactive mode after executing 'script' + -l mod require library 'mod' into global 'mod' + -l g=mod require library 'mod' into global 'g' + -v show version information + -E ignore environment variables + -W turn warnings on + -- stop handling options + - stop handling options and execute stdin +`.trim(), + ) + process.exit(1) +} + +function parseArgs(args) { + const executeSnippets = [] + const includeModules = [] + let forceInteractive = false + let warnings = false + let ignoreEnv = false + let showVersion = false + let scriptFile = null + + const outArgs = [] + + let i = 0 + for (; i < args.length; i++) { + const arg = args[i] + + if (arg === '--') { + i++ + break + } + + if (arg.startsWith('-') && arg.length > 1) { + switch (arg) { + case '-v': + showVersion = true + break + + case '-W': + warnings = true + break + + case '-E': + ignoreEnv = true + break + + case '-i': + forceInteractive = true + break + + case '-e': + i++ + if (i >= args.length) { + console.error('Missing argument after -e') + printUsage() + } + executeSnippets.push(args[i]) + break + + case '-l': + i++ + if (i >= args.length) { + console.error('Missing argument after -l') + printUsage() + } + includeModules.push(args[i]) + break -let snippets = process.argv.splice(2) + case '-': + scriptFile = '-' + i++ + break -const consumeOption = (option, single) => { - let i = -1 - const values = [] - while ((i = snippets.indexOf(option)) >= 0) { - values.push(snippets.splice(i, single ? 1 : 2).reverse()[0]) + default: + console.log(`unrecognized option: '${arg}'`) + printUsage() + break + } + } else { + scriptFile = arg + i++ + break + } } - return values + + outArgs.push(...args.slice(i)) + + return { + executeSnippets, + includeModules, + forceInteractive, + warnings, + showVersion, + scriptFile, + scriptArgs: outArgs, + ignoreEnv, + } +} + +const { executeSnippets, includeModules, ignoreEnv, forceInteractive, warnings, showVersion, scriptFile, scriptArgs } = parseArgs( + process.argv.slice(2), +) + +const factory = new LuaFactory({ env: ignoreEnv ? undefined : process.env }) +const luamodule = await factory.getLuaModule() +const lua = await factory.createEngine() + +if (showVersion) { + console.log(`wasmoon ${pkg.version} (${lua.global.get('_VERSION')})`) + process.exit(0) } -const warnings = consumeOption('-W', true).length > 0 if (warnings) { luamodule.lua_warning(lua.global.address, '@on', 0) } -const executes = consumeOption('-e') -for (const execute of executes) { - await lua.doString(execute) +for (const snippet of executeSnippets) { + await lua.doString(snippet) } -const includes = consumeOption('-l') -const forceInteractive = consumeOption('-i', true).length > 0 -const runFile = process.stdin.isTTY && consumeOption(snippets[0], true)[0] -const args = snippets +function currentDir() { + const pointer = luamodule.module._malloc(128); + const baseidx = pointer >> 2; -for (const include of includes) { - const relativeInclude = path.resolve(process.cwd(), include) - const stat = await fs.promises.lstat(relativeInclude) - if (stat.isFile()) { - await factory.mountFile(relativeInclude, await fs.promises.readFile(relativeInclude)) - } else { - for (const file of await fs.promises.readdir(relativeInclude, { recursive: true })) { - await factory.mountFile(file, await fs.promises.readFile(file)) + try { + if (!luamodule.lua_getstack(lua.global.address, 1, pointer)) { + return null; + } + + if (!luamodule.lua_getinfo(lua.global.address, 'S', pointer)) { + return null; } + + // https://www.lua.org/manual/5.4/manual.html#lua_Debug + const sourcePtr = luamodule.module.HEAPU32[baseidx + 4]; + let source = luamodule.module.UTF8ToString(sourcePtr); + + if (!source || source === '=[C]' || source.startsWith('return ')) { + return '.' + } else { + if (source.startsWith('@')) { + source = source.substring(1) + } + + return source + } + } finally { + luamodule.module._free(pointer); } } -lua.global.set('arg', decorate(args, { disableProxy: true })) +lua.global.getTable('package', (packageIdx) => { + luamodule.lua_getfield(lua.global.address, packageIdx, 'searchers') -const interactive = process.stdin.isTTY && (forceInteractive || !runFile) + lua.global.pushValue(decorateFunction((thread, moduleName) => { + if (moduleName.endsWith('.lua')) { + const calledDirectory = currentDir() + const luafile = path.resolve(calledDirectory, moduleName) -if (runFile) { - const relativeRunFile = path.resolve(process.cwd(), runFile) - await factory.mountFile(relativeRunFile, await fs.promises.readFile(relativeRunFile)) + try { + const content = fs.readFileSync(luafile) + factory.mountFileSync(luamodule, luafile, content) + } catch { + // ignore + } - await lua.doFile(relativeRunFile) - console.log(lua.global.indexToString(-1)) + const load = luamodule.luaL_loadfilex(lua.global.address, luafile, null) + if (load === LuaReturn.Ok) { + thread.pushValue(luafile) + return new LuaRawResult(2) + } + } + }, { receiveThread: true })) + + const len = luamodule.lua_rawlen(lua.global.address, -1) + luamodule.lua_rawseti(lua.global.address, -2, len + BigInt(1)) + + lua.global.pop() +}) + +lua.global.set('loadfile', (filename) => { + // TODO +}) + +for (const include of includeModules) { + // TODO } -if (!interactive && runFile) { - process.exit(0) +lua.global.set('arg', decorate(scriptArgs, { disableProxy: true })) + +const isTTY = process.stdin.isTTY + +if (scriptFile) { + if (scriptFile === '-') { + const input = fs.readFileSync(0, 'utf-8') + await lua.doString(input) + console.log(lua.global.indexToString(-1)) + } else { + const absolutePath = path.resolve(process.cwd(), scriptFile) + const content = await fs.promises.readFile(absolutePath) + await factory.mountFile(absolutePath, content) + await lua.doFile(absolutePath) + console.log(lua.global.indexToString(-1)) + } } -if (interactive) { - // Call directly from module to bypass the result verification - const loadcode = (code) => !lua.global.setTop(0) && luamodule.luaL_loadstring(lua.global.address, code) === LuaReturn.Ok +const shouldInteractive = isTTY && (forceInteractive || (!scriptFile && !executeSnippets.length)) + +if (shouldInteractive) { + // Bypass result verification for interactive mode + const loadcode = (code) => { + lua.global.setTop(0) + return luamodule.luaL_loadstring(lua.global.address, code) === LuaReturn.Ok + } const version = pkg.version const luaversion = lua.global.get('_VERSION') console.log(`Welcome to Wasmoon ${version} (${luaversion})`) + console.log('Type Lua code and press Enter to execute. Ctrl+C to exit.\n') const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: true, removeHistoryDuplicates: true, + prompt: '> ', }) rl.prompt() for await (const line of rl) { - const loaded = loadcode(line) || loadcode(`return ${line}`) + // try to load (compile) it first as an expression (return ) and second as a statement + const loaded = loadcode(`return ${line}`) || loadcode(line) if (!loaded) { - console.log(lua.global.getValue(-1, LuaType.String)) + // Failed to parse + const err = lua.global.getValue(-1, LuaType.String) + console.log(err) rl.prompt() continue } const result = luamodule.lua_pcallk(lua.global.address, 0, LUA_MULTRET, 0, 0, null) if (result === LuaReturn.Ok) { - const returnValues = Array.from({ length: lua.global.getTop() }).map((_, i) => lua.global.indexToString(i + 1)) - - if (returnValues.length) { + const count = lua.global.getTop() + if (count > 0) { + const returnValues = [] + for (let i = 1; i <= count; i++) { + returnValues.push(lua.global.indexToString(i)) + } console.log(...returnValues) } } else { @@ -101,7 +269,10 @@ if (interactive) { rl.prompt() } -} else { - await lua.doString(fs.readFileSync(0, 'utf-8')) +} else if (!scriptFile) { + // If we're not interactive, and we did NOT run a file, + // read from stdin until EOF. (Non-TTY or no -i, no file). + const input = fs.readFileSync(0, 'utf-8') + await lua.doString(input) console.log(lua.global.indexToString(-1)) } diff --git a/build.sh b/build.sh index 9d54f96..774b0c3 100755 --- a/build.sh +++ b/build.sh @@ -24,7 +24,9 @@ emcc \ 'setValue', \ 'lengthBytesUTF8', \ 'stringToUTF8', \ - 'stringToNewUTF8' + 'stringToNewUTF8', \ + 'UTF8ToString', \ + 'HEAPU32' ]" \ -s INCOMING_MODULE_JS_API="[ 'locateFile', \ diff --git a/eslint.config.js b/eslint.config.js index 1610949..23e7807 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -22,7 +22,7 @@ export default [ }, }, { - files: ['**/*.js', '**/*.mjs', '**/*.ts'], + files: ['**/*.js', '**/*.mjs', '**/*.ts', './bin/*'], ignores: ['**/test/*', '**/bench/*'], plugins: { 'simple-import-sort': simpleImportSort, diff --git a/src/global.ts b/src/global.ts index e006d5e..0fbef7a 100755 --- a/src/global.ts +++ b/src/global.ts @@ -177,7 +177,7 @@ export default class Global extends Thread { } finally { // +1 for the table if (this.getTop() !== startStackTop + 1) { - console.warn(`getTable: expected stack size ${startStackTop} got ${this.getTop()}`) + console.warn(`getTable: expected stack size ${startStackTop + 1} got ${this.getTop()}`) } this.setTop(startStackTop) } diff --git a/src/luawasm.ts b/src/luawasm.ts index 04b5b34..032ba9e 100755 --- a/src/luawasm.ts +++ b/src/luawasm.ts @@ -13,6 +13,7 @@ interface LuaEmscriptenModule extends EmscriptenModule { stringToNewUTF8: typeof allocateUTF8 lengthBytesUTF8: typeof lengthBytesUTF8 stringToUTF8: typeof stringToUTF8 + UTF8ToString: typeof UTF8ToString ENV: EnvironmentVariables _realloc: (pointer: number, size: number) => number } @@ -121,7 +122,7 @@ export default class LuaWasm { public lua_tointegerx: (L: LuaState, idx: number, isnum: number | null) => bigint public lua_toboolean: (L: LuaState, idx: number) => number public lua_tolstring: (L: LuaState, idx: number, len: number | null) => string - public lua_rawlen: (L: LuaState, idx: number) => number + public lua_rawlen: (L: LuaState, idx: number) => bigint public lua_tocfunction: (L: LuaState, idx: number) => number public lua_touserdata: (L: LuaState, idx: number) => number public lua_tothread: (L: LuaState, idx: number) => LuaState From eae545ba4b91ea07f1c2663bec3d9a2793c95ac0 Mon Sep 17 00:00:00 2001 From: ceifa Date: Tue, 18 Feb 2025 09:15:22 -0300 Subject: [PATCH 04/83] implement option to use raw node fs --- bin/wasmoon | 78 +------ build.sh | 1 + package-lock.json | 401 +++++++++++++++++++----------------- package.json | 26 +-- rolldown.config.ts | 2 +- src/factory.ts | 1 + src/luawasm.ts | 20 +- test/initialization.test.js | 2 +- test/luatests.js | 17 +- test/utils.js | 2 +- tsconfig.json | 5 +- 11 files changed, 260 insertions(+), 295 deletions(-) diff --git a/bin/wasmoon b/bin/wasmoon index d262f60..2abc218 100755 --- a/bin/wasmoon +++ b/bin/wasmoon @@ -115,7 +115,7 @@ const { executeSnippets, includeModules, ignoreEnv, forceInteractive, warnings, process.argv.slice(2), ) -const factory = new LuaFactory({ env: ignoreEnv ? undefined : process.env }) +const factory = new LuaFactory({ env: ignoreEnv ? undefined : process.env, fs: 'node' }) const luamodule = await factory.getLuaModule() const lua = await factory.createEngine() @@ -128,76 +128,18 @@ if (warnings) { luamodule.lua_warning(lua.global.address, '@on', 0) } -for (const snippet of executeSnippets) { - await lua.doString(snippet) -} - -function currentDir() { - const pointer = luamodule.module._malloc(128); - const baseidx = pointer >> 2; - - try { - if (!luamodule.lua_getstack(lua.global.address, 1, pointer)) { - return null; - } - - if (!luamodule.lua_getinfo(lua.global.address, 'S', pointer)) { - return null; - } - - // https://www.lua.org/manual/5.4/manual.html#lua_Debug - const sourcePtr = luamodule.module.HEAPU32[baseidx + 4]; - let source = luamodule.module.UTF8ToString(sourcePtr); - - if (!source || source === '=[C]' || source.startsWith('return ')) { - return '.' - } else { - if (source.startsWith('@')) { - source = source.substring(1) - } - - return source - } - } finally { - luamodule.module._free(pointer); +for (const module of includeModules) { + let [global, mod] = module.split('=') + if (!mod) { + mod = global } -} - -lua.global.getTable('package', (packageIdx) => { - luamodule.lua_getfield(lua.global.address, packageIdx, 'searchers') - lua.global.pushValue(decorateFunction((thread, moduleName) => { - if (moduleName.endsWith('.lua')) { - const calledDirectory = currentDir() - const luafile = path.resolve(calledDirectory, moduleName) - - try { - const content = fs.readFileSync(luafile) - factory.mountFileSync(luamodule, luafile, content) - } catch { - // ignore - } - - const load = luamodule.luaL_loadfilex(lua.global.address, luafile, null) - if (load === LuaReturn.Ok) { - thread.pushValue(luafile) - return new LuaRawResult(2) - } - } - }, { receiveThread: true })) - - const len = luamodule.lua_rawlen(lua.global.address, -1) - luamodule.lua_rawseti(lua.global.address, -2, len + BigInt(1)) - - lua.global.pop() -}) - -lua.global.set('loadfile', (filename) => { - // TODO -}) + const require = lua.global.get('require') + lua.global.set(global, require(mod)) +} -for (const include of includeModules) { - // TODO +for (const snippet of executeSnippets) { + await lua.doString(snippet) } lua.global.set('arg', decorate(scriptArgs, { disableProxy: true })) diff --git a/build.sh b/build.sh index 774b0c3..252517e 100755 --- a/build.sh +++ b/build.sh @@ -13,6 +13,7 @@ else fi emcc \ + -lnodefs.js \ -s WASM=1 $extension -o ./build/glue.js \ -s EXPORTED_RUNTIME_METHODS="[ 'ccall', \ diff --git a/package-lock.json b/package-lock.json index a9b3163..4e37b2b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,29 +9,29 @@ "version": "1.16.0", "license": "MIT", "dependencies": { - "@types/emscripten": "1.39.10" + "@types/emscripten": "1.40.0" }, "bin": { "wasmoon": "bin/wasmoon" }, "devDependencies": { - "@eslint/js": "9.17.0", - "@types/node": "22.10.2", - "@typescript-eslint/parser": "8.18.2", - "chai": "5.1.2", + "@eslint/js": "9.20.0", + "@types/node": "22.13.4", + "@typescript-eslint/parser": "8.24.1", + "chai": "5.2.0", "chai-as-promised": "8.0.1", - "eslint": "9.17.0", - "eslint-config-prettier": "9.1.0", - "eslint-plugin-prettier": "5.2.1", + "eslint": "9.20.1", + "eslint-config-prettier": "10.0.1", + "eslint-plugin-prettier": "5.2.3", "eslint-plugin-simple-import-sort": "12.1.1", "fengari": "0.1.4", - "mocha": "11.0.1", - "prettier": "3.4.2", - "rolldown": "1.0.0-beta.1-commit.7c52c94", + "mocha": "11.1.0", + "prettier": "3.5.1", + "rolldown": "1.0.0-beta.3", "rollup-plugin-copy": "3.5.0", "tslib": "2.8.1", - "typescript": "5.7.2", - "typescript-eslint": "8.18.2" + "typescript": "5.7.3", + "typescript-eslint": "8.24.1" } }, "node_modules/@emnapi/core": { @@ -137,9 +137,9 @@ } }, "node_modules/@eslint/core": { - "version": "0.9.1", - "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.9.1.tgz", - "integrity": "sha512-GuUdqkyyzQI5RMIWkHhvTWLCyLo1jNK3vzkSyaExH5kHPDHcuL2VOpHjmMY+y3+NC69qAKToBqldTBgYeLSr9Q==", + "version": "0.10.0", + "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.10.0.tgz", + "integrity": "sha512-gFHJ+xBOo4G3WRlR1e/3G8A6/KZAH6zcE/hkLRCZTi/B9avAG365QhFA8uOGzTMqgTghpn7/fSnscW++dpMSAw==", "dev": true, "license": "Apache-2.0", "dependencies": { @@ -198,9 +198,9 @@ } }, "node_modules/@eslint/js": { - "version": "9.17.0", - "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.17.0.tgz", - "integrity": "sha512-Sxc4hqcs1kTu0iID3kcZDW3JHq2a77HO9P8CP6YEA/FpH3Ll8UXE2r/86Rz9YJLKme39S9vU5OWNjC6Xl0Cr3w==", + "version": "9.20.0", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.20.0.tgz", + "integrity": "sha512-iZA07H9io9Wn836aVTytRaNqh00Sad+EamwOVJT12GTLw1VGMFV/4JaME+JjLtr9fiGaoWgYnS54wrfWsSs4oQ==", "dev": true, "license": "MIT", "engines": { @@ -218,12 +218,13 @@ } }, "node_modules/@eslint/plugin-kit": { - "version": "0.2.4", - "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.2.4.tgz", - "integrity": "sha512-zSkKow6H5Kdm0ZUQUB2kV5JIXqoG0+uH5YADhaEHswm664N9Db8dXSi0nMJpacpMf+MyyglF1vnZohpEg5yUtg==", + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.2.5.tgz", + "integrity": "sha512-lB05FkqEdUg2AA0xEbUz0SnkXT1LcCTa438W4IWTUh4hdOnVbQyOJ81OrDXsJk/LSiJHubgGEFoR5EHq1NsH1A==", "dev": true, "license": "Apache-2.0", "dependencies": { + "@eslint/core": "^0.10.0", "levn": "^0.4.1" }, "engines": { @@ -366,9 +367,9 @@ } }, "node_modules/@oxc-project/types": { - "version": "0.45.0", - "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.45.0.tgz", - "integrity": "sha512-s1xCyuYV024s4Jh9l3a9/gSyIG5qr6P0gdwz03UMx6UqaXRkhD2INeRSNxGM/XXKfYVbAqUBy3q/QEMkTNio9Q==", + "version": "0.46.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.46.0.tgz", + "integrity": "sha512-BHU261xrLasw04d2cToR36F6VV0T7t62rtQUprvBRL4Uru9P23moMkDmZUMSZSQj0fIUTA3oTOTwQ7cc4Av/iw==", "dev": true, "license": "MIT", "funding": { @@ -400,9 +401,9 @@ } }, "node_modules/@rolldown/binding-darwin-arm64": { - "version": "1.0.0-beta.1-commit.7c52c94", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.0.0-beta.1-commit.7c52c94.tgz", - "integrity": "sha512-02iMa/cL+kLkS6xC98MBZSkpInFtAK0gKxjQhmdvplF+WMr/i4VUDrwEIP+N0ydOiUw3rfXcz+Vykh2Srw2ioQ==", + "version": "1.0.0-beta.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.0.0-beta.3.tgz", + "integrity": "sha512-qB1ofY+09nDYYaEi5kVsjqy4cKsVPI9E5bkV46CRrQsTF/BBM29wpvaj8qTRQ41qwInFA5kmqnVVr35yfH7ddw==", "cpu": [ "arm64" ], @@ -414,9 +415,9 @@ ] }, "node_modules/@rolldown/binding-darwin-x64": { - "version": "1.0.0-beta.1-commit.7c52c94", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.0.0-beta.1-commit.7c52c94.tgz", - "integrity": "sha512-14jCHf59q/SeqMvhq5cah3qwC6/G7Z/64Z77jgwofFLyGbdYmFFv4ct92vXG3Wno88MwAbuilKIaOiu0HhpBmQ==", + "version": "1.0.0-beta.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.0.0-beta.3.tgz", + "integrity": "sha512-Fk+rqyeszMaZK12wItqFDXdUadg+TVQqOPh0fdaCefVebd29N+9fpFrARyo8gReyt/lcnEN4nWgdn7l99R70QA==", "cpu": [ "x64" ], @@ -428,9 +429,9 @@ ] }, "node_modules/@rolldown/binding-freebsd-x64": { - "version": "1.0.0-beta.1-commit.7c52c94", - "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.0.0-beta.1-commit.7c52c94.tgz", - "integrity": "sha512-iICCEIauX0xGByel25JkMG8jTN3zF70XHaon6ylbkCsqpZzXTn9qx/KTUKEv0aeoxeAU6JU7Sxk9aK6KHPHkHQ==", + "version": "1.0.0-beta.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.0.0-beta.3.tgz", + "integrity": "sha512-B7QzJKu53MB/hvwO276AsyxN+p9lfgCkIO94TQB6t3auq3pDCC6u6gdRI1Ydwn6/gpMLiUNCW4mnpxCE5fE5tg==", "cpu": [ "x64" ], @@ -442,9 +443,9 @@ ] }, "node_modules/@rolldown/binding-linux-arm-gnueabihf": { - "version": "1.0.0-beta.1-commit.7c52c94", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.0.0-beta.1-commit.7c52c94.tgz", - "integrity": "sha512-xS/2DVlMhi9BcJ15uAvIFdMuGS4bKpOsHkwoVIYxkGNKcLD8J4kDK0Uaa9Wkb191pygqmZZYe+y+m5dp8WyEQQ==", + "version": "1.0.0-beta.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.0.0-beta.3.tgz", + "integrity": "sha512-NB5JrXP5dAigDTbvVc6VWiOY3Rr/0u1pi/9LYoBtMYiST7hYOrBPO9lvDF9w/23yKCr1+8PF4wFGR/YxKTNN5Q==", "cpu": [ "arm" ], @@ -456,9 +457,9 @@ ] }, "node_modules/@rolldown/binding-linux-arm64-gnu": { - "version": "1.0.0-beta.1-commit.7c52c94", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.0.0-beta.1-commit.7c52c94.tgz", - "integrity": "sha512-4Wtczg6ZjIqYZ+r5s6KxqUJ1XTcMHk9b0PunedmRsx1Po9lXLhLtD7xMSLrPHT2s6upj/ast5Nc1CocBlGH2kQ==", + "version": "1.0.0-beta.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.0.0-beta.3.tgz", + "integrity": "sha512-bYyZLXzJ2boZ7CdUuCSAaTcWkVKcBUOL+B86zv+tRyrtk4BIpHF+L+vOg5uPD/PHwrIglxAno5MN4NnpkUj5fQ==", "cpu": [ "arm64" ], @@ -470,9 +471,9 @@ ] }, "node_modules/@rolldown/binding-linux-arm64-musl": { - "version": "1.0.0-beta.1-commit.7c52c94", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.0.0-beta.1-commit.7c52c94.tgz", - "integrity": "sha512-WMSnRcek6BRXnOiZisTjmKD93BrugSLkJngbZZvXYoPTXLb19pPntnN7hV9J/V7UkgjdXAdwJwtzUfHfqUzWrg==", + "version": "1.0.0-beta.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.0.0-beta.3.tgz", + "integrity": "sha512-t/jaaFrCSvwX2075jRfa2bwAcsuTtY1/sIT4XqsDg2MVxWQtaUyBx5Mi0pqZKTjdOPnL+f/zoUC9dxT2lUpNmw==", "cpu": [ "arm64" ], @@ -484,9 +485,9 @@ ] }, "node_modules/@rolldown/binding-linux-x64-gnu": { - "version": "1.0.0-beta.1-commit.7c52c94", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.0.0-beta.1-commit.7c52c94.tgz", - "integrity": "sha512-M5kXmTgi8aP9GKzMcLtbpQ5xPic2xzuilazT0Q8oCbU3rcQg39OTs2A/1pNGqqVzertVWmMw473jDs+39MF4KQ==", + "version": "1.0.0-beta.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.0.0-beta.3.tgz", + "integrity": "sha512-EeDNLPU0Xw8ByRWxNLO30AF0fKYkdb/6rH5G073NFBDkj7ggYR/CvsNBjtDeCJ7+I6JG4xUjete2+VeV+GQjiA==", "cpu": [ "x64" ], @@ -498,9 +499,9 @@ ] }, "node_modules/@rolldown/binding-linux-x64-musl": { - "version": "1.0.0-beta.1-commit.7c52c94", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.0.0-beta.1-commit.7c52c94.tgz", - "integrity": "sha512-4i2hLAjupLmxTRqk6YZORs7CKCdXmzymNTy64rfoSmiL5iN4Ike9erB++pUpmmqG8UmOvrZXzbMWwvVd9GIPPw==", + "version": "1.0.0-beta.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.0.0-beta.3.tgz", + "integrity": "sha512-iTcAj8FKac3nyQhvFuqKt6Xqu9YNDbe1ew6US2OSN4g3zwfujgylaRCitEG+Uzd7AZfSVVLAfqrxKMa36Sj9Mg==", "cpu": [ "x64" ], @@ -512,9 +513,9 @@ ] }, "node_modules/@rolldown/binding-wasm32-wasi": { - "version": "1.0.0-beta.1-commit.7c52c94", - "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.0.0-beta.1-commit.7c52c94.tgz", - "integrity": "sha512-EekMm2D41TDmpqdhVXeXM0dU4SHFe2tZBY9ondJhA2lOHW0No5Y/i2D5dXauaGDBYljZldhUL/oRINc0/1uF8A==", + "version": "1.0.0-beta.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.0.0-beta.3.tgz", + "integrity": "sha512-sYgbsbyspvVZ2zplqsTxjf2N3e8UQGQnSsN5u4bMX461gY5vAsjUiA4nf1/ztDBMHWT79lF2QNx4csjnjSxMlA==", "cpu": [ "wasm32" ], @@ -529,9 +530,9 @@ } }, "node_modules/@rolldown/binding-win32-arm64-msvc": { - "version": "1.0.0-beta.1-commit.7c52c94", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.0.0-beta.1-commit.7c52c94.tgz", - "integrity": "sha512-rubF+iwgtmeZfyvR+1y3qYsRWqi0qtDqI6vrDjbyXC7i4NU6/Lpcd5aS60eMJc7chQ9E64SNxddi6V7H38er/g==", + "version": "1.0.0-beta.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.0.0-beta.3.tgz", + "integrity": "sha512-qszMtrWybBLTFaew2WgEBRMlz1B/V8XxU87uezXlKcLW36aoRWR8LspZvqqoBkvJzbQtfOgm1HdTIk/v3Rn7QQ==", "cpu": [ "arm64" ], @@ -543,9 +544,9 @@ ] }, "node_modules/@rolldown/binding-win32-ia32-msvc": { - "version": "1.0.0-beta.1-commit.7c52c94", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-1.0.0-beta.1-commit.7c52c94.tgz", - "integrity": "sha512-qo4Vd1i+tsHQ1AYMgy1vTYcDwcb9Pnzjve1ni97PUdzMc2EtR8BvamX0QxEdlYRZGNiv7PXFVUlTzIpPLimL8w==", + "version": "1.0.0-beta.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-1.0.0-beta.3.tgz", + "integrity": "sha512-J+mzAO68VK91coLVuUln/XN0ummIEOODyupZ2BmXY8suBHPVAyLLAP54rlucBPQmzU8fI6DXM2bl2whZ+KEXpQ==", "cpu": [ "ia32" ], @@ -557,9 +558,9 @@ ] }, "node_modules/@rolldown/binding-win32-x64-msvc": { - "version": "1.0.0-beta.1-commit.7c52c94", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.0.0-beta.1-commit.7c52c94.tgz", - "integrity": "sha512-vdhlPFeNk1UNF4t52Lg1Y1FEvjFbYqtbpxz2w8M+HozdJLSRaVJdXPI/tMMFhdC/YlMFRNrZN5W+PwHUhbFxSQ==", + "version": "1.0.0-beta.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.0.0-beta.3.tgz", + "integrity": "sha512-r06rAi+1eStgavGnw+2y4F7gpb0w9ocnKk0Ir7LmegLAkMZ/v4Fjo9jZUrLTLtmI36108v1uvUPrIAFzFOWE7g==", "cpu": [ "x64" ], @@ -582,9 +583,9 @@ } }, "node_modules/@types/emscripten": { - "version": "1.39.10", - "resolved": "https://registry.npmjs.org/@types/emscripten/-/emscripten-1.39.10.tgz", - "integrity": "sha512-TB/6hBkYQJxsZHSqyeuO1Jt0AB/bW6G7rHt9g7lML7SOF6lbgcHvw/Lr+69iqN0qxgXLhWKScAon73JNnptuDw==", + "version": "1.40.0", + "resolved": "https://registry.npmjs.org/@types/emscripten/-/emscripten-1.40.0.tgz", + "integrity": "sha512-MD2JJ25S4tnjnhjWyalMS6K6p0h+zQV6+Ylm+aGbiS8tSn/aHLSGNzBgduj6FB4zH0ax2GRMGYi/8G1uOxhXWA==", "license": "MIT" }, "node_modules/@types/estree": { @@ -630,9 +631,9 @@ "license": "MIT" }, "node_modules/@types/node": { - "version": "22.10.2", - "resolved": "https://registry.npmjs.org/@types/node/-/node-22.10.2.tgz", - "integrity": "sha512-Xxr6BBRCAOQixvonOye19wnzyDiUtTeqldOOmj3CkeblonbccA12PFwlufvRdrpjXxqnmUaeiU5EOA+7s5diUQ==", + "version": "22.13.4", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.13.4.tgz", + "integrity": "sha512-ywP2X0DYtX3y08eFVx5fNIw7/uIv8hYUKgXoK8oayJlLnKcRfEYCxWMVE1XagUdVtCJlZT1AU4LXEABW+L1Peg==", "dev": true, "license": "MIT", "dependencies": { @@ -640,21 +641,21 @@ } }, "node_modules/@typescript-eslint/eslint-plugin": { - "version": "8.18.2", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.18.2.tgz", - "integrity": "sha512-adig4SzPLjeQ0Tm+jvsozSGiCliI2ajeURDGHjZ2llnA+A67HihCQ+a3amtPhUakd1GlwHxSRvzOZktbEvhPPg==", + "version": "8.24.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.24.1.tgz", + "integrity": "sha512-ll1StnKtBigWIGqvYDVuDmXJHVH4zLVot1yQ4fJtLpL7qacwkxJc1T0bptqw+miBQ/QfUbhl1TcQ4accW5KUyA==", "dev": true, "license": "MIT", "dependencies": { "@eslint-community/regexpp": "^4.10.0", - "@typescript-eslint/scope-manager": "8.18.2", - "@typescript-eslint/type-utils": "8.18.2", - "@typescript-eslint/utils": "8.18.2", - "@typescript-eslint/visitor-keys": "8.18.2", + "@typescript-eslint/scope-manager": "8.24.1", + "@typescript-eslint/type-utils": "8.24.1", + "@typescript-eslint/utils": "8.24.1", + "@typescript-eslint/visitor-keys": "8.24.1", "graphemer": "^1.4.0", "ignore": "^5.3.1", "natural-compare": "^1.4.0", - "ts-api-utils": "^1.3.0" + "ts-api-utils": "^2.0.1" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -670,16 +671,16 @@ } }, "node_modules/@typescript-eslint/parser": { - "version": "8.18.2", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.18.2.tgz", - "integrity": "sha512-y7tcq4StgxQD4mDr9+Jb26dZ+HTZ/SkfqpXSiqeUXZHxOUyjWDKsmwKhJ0/tApR08DgOhrFAoAhyB80/p3ViuA==", + "version": "8.24.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.24.1.tgz", + "integrity": "sha512-Tqoa05bu+t5s8CTZFaGpCH2ub3QeT9YDkXbPd3uQ4SfsLoh1/vv2GEYAioPoxCWJJNsenXlC88tRjwoHNts1oQ==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/scope-manager": "8.18.2", - "@typescript-eslint/types": "8.18.2", - "@typescript-eslint/typescript-estree": "8.18.2", - "@typescript-eslint/visitor-keys": "8.18.2", + "@typescript-eslint/scope-manager": "8.24.1", + "@typescript-eslint/types": "8.24.1", + "@typescript-eslint/typescript-estree": "8.24.1", + "@typescript-eslint/visitor-keys": "8.24.1", "debug": "^4.3.4" }, "engines": { @@ -695,14 +696,14 @@ } }, "node_modules/@typescript-eslint/scope-manager": { - "version": "8.18.2", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.18.2.tgz", - "integrity": "sha512-YJFSfbd0CJjy14r/EvWapYgV4R5CHzptssoag2M7y3Ra7XNta6GPAJPPP5KGB9j14viYXyrzRO5GkX7CRfo8/g==", + "version": "8.24.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.24.1.tgz", + "integrity": "sha512-OdQr6BNBzwRjNEXMQyaGyZzgg7wzjYKfX2ZBV3E04hUCBDv3GQCHiz9RpqdUIiVrMgJGkXm3tcEh4vFSHreS2Q==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/types": "8.18.2", - "@typescript-eslint/visitor-keys": "8.18.2" + "@typescript-eslint/types": "8.24.1", + "@typescript-eslint/visitor-keys": "8.24.1" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -713,16 +714,16 @@ } }, "node_modules/@typescript-eslint/type-utils": { - "version": "8.18.2", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.18.2.tgz", - "integrity": "sha512-AB/Wr1Lz31bzHfGm/jgbFR0VB0SML/hd2P1yxzKDM48YmP7vbyJNHRExUE/wZsQj2wUCvbWH8poNHFuxLqCTnA==", + "version": "8.24.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.24.1.tgz", + "integrity": "sha512-/Do9fmNgCsQ+K4rCz0STI7lYB4phTtEXqqCAs3gZW0pnK7lWNkvWd5iW545GSmApm4AzmQXmSqXPO565B4WVrw==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/typescript-estree": "8.18.2", - "@typescript-eslint/utils": "8.18.2", + "@typescript-eslint/typescript-estree": "8.24.1", + "@typescript-eslint/utils": "8.24.1", "debug": "^4.3.4", - "ts-api-utils": "^1.3.0" + "ts-api-utils": "^2.0.1" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -737,9 +738,9 @@ } }, "node_modules/@typescript-eslint/types": { - "version": "8.18.2", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.18.2.tgz", - "integrity": "sha512-Z/zblEPp8cIvmEn6+tPDIHUbRu/0z5lqZ+NvolL5SvXWT5rQy7+Nch83M0++XzO0XrWRFWECgOAyE8bsJTl1GQ==", + "version": "8.24.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.24.1.tgz", + "integrity": "sha512-9kqJ+2DkUXiuhoiYIUvIYjGcwle8pcPpdlfkemGvTObzgmYfJ5d0Qm6jwb4NBXP9W1I5tss0VIAnWFumz3mC5A==", "dev": true, "license": "MIT", "engines": { @@ -751,20 +752,20 @@ } }, "node_modules/@typescript-eslint/typescript-estree": { - "version": "8.18.2", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.18.2.tgz", - "integrity": "sha512-WXAVt595HjpmlfH4crSdM/1bcsqh+1weFRWIa9XMTx/XHZ9TCKMcr725tLYqWOgzKdeDrqVHxFotrvWcEsk2Tg==", + "version": "8.24.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.24.1.tgz", + "integrity": "sha512-UPyy4MJ/0RE648DSKQe9g0VDSehPINiejjA6ElqnFaFIhI6ZEiZAkUI0D5MCk0bQcTf/LVqZStvQ6K4lPn/BRg==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/types": "8.18.2", - "@typescript-eslint/visitor-keys": "8.18.2", + "@typescript-eslint/types": "8.24.1", + "@typescript-eslint/visitor-keys": "8.24.1", "debug": "^4.3.4", "fast-glob": "^3.3.2", "is-glob": "^4.0.3", "minimatch": "^9.0.4", "semver": "^7.6.0", - "ts-api-utils": "^1.3.0" + "ts-api-utils": "^2.0.1" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -778,16 +779,16 @@ } }, "node_modules/@typescript-eslint/utils": { - "version": "8.18.2", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.18.2.tgz", - "integrity": "sha512-Cr4A0H7DtVIPkauj4sTSXVl+VBWewE9/o40KcF3TV9aqDEOWoXF3/+oRXNby3DYzZeCATvbdksYsGZzplwnK/Q==", + "version": "8.24.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.24.1.tgz", + "integrity": "sha512-OOcg3PMMQx9EXspId5iktsI3eMaXVwlhC8BvNnX6B5w9a4dVgpkQZuU8Hy67TolKcl+iFWq0XX+jbDGN4xWxjQ==", "dev": true, "license": "MIT", "dependencies": { "@eslint-community/eslint-utils": "^4.4.0", - "@typescript-eslint/scope-manager": "8.18.2", - "@typescript-eslint/types": "8.18.2", - "@typescript-eslint/typescript-estree": "8.18.2" + "@typescript-eslint/scope-manager": "8.24.1", + "@typescript-eslint/types": "8.24.1", + "@typescript-eslint/typescript-estree": "8.24.1" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -802,13 +803,13 @@ } }, "node_modules/@typescript-eslint/visitor-keys": { - "version": "8.18.2", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.18.2.tgz", - "integrity": "sha512-zORcwn4C3trOWiCqFQP1x6G3xTRyZ1LYydnj51cRnJ6hxBlr/cKPckk+PKPUw/fXmvfKTcw7bwY3w9izgx5jZw==", + "version": "8.24.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.24.1.tgz", + "integrity": "sha512-EwVHlp5l+2vp8CoqJm9KikPZgi3gbdZAtabKT9KPShGeOcJhsv4Zdo3oc8T8I0uKEmYoU4ItyxbptjF08enaxg==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/types": "8.18.2", + "@typescript-eslint/types": "8.24.1", "eslint-visitor-keys": "^4.2.0" }, "engines": { @@ -833,9 +834,9 @@ } }, "node_modules/@valibot/to-json-schema": { - "version": "1.0.0-beta.3", - "resolved": "https://registry.npmjs.org/@valibot/to-json-schema/-/to-json-schema-1.0.0-beta.3.tgz", - "integrity": "sha512-20XQh1u5sOLwS3NOB7oHCo3clQ9h4GlavXgLKMux2PYpHowb7P97cND0dg8T3+fE1WoKVACcLppvzAPpSx0F+Q==", + "version": "1.0.0-beta.4", + "resolved": "https://registry.npmjs.org/@valibot/to-json-schema/-/to-json-schema-1.0.0-beta.4.tgz", + "integrity": "sha512-wXBdCyoqec+NLCl5ihitXzZXD4JAjPK3+HfskSXzfhiNFvKje0A/v1LygqKidUgIbaJtREmq/poJGbaS/0MKuQ==", "dev": true, "license": "MIT", "peerDependencies": { @@ -1049,9 +1050,9 @@ } }, "node_modules/chai": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/chai/-/chai-5.1.2.tgz", - "integrity": "sha512-aGtmf24DW6MLHHG5gCx4zaI3uBq3KRtxeVs0DjFH6Z0rDNbsvTxFASFvdj79pxjxZ8/5u3PIiN3IwEIQkiiuPw==", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-5.2.0.tgz", + "integrity": "sha512-mCuXncKXk5iCLhfhwTc0izo0gtEmpz5CtG2y8GiOINBlMVS6v8TMRc5TaLWKS6692m9+dVVfzgeVxR5UxWHTYw==", "dev": true, "license": "MIT", "dependencies": { @@ -1144,15 +1145,18 @@ } }, "node_modules/cliui": { - "version": "7.0.4", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-7.0.4.tgz", - "integrity": "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", + "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", "dev": true, "license": "ISC", "dependencies": { "string-width": "^4.2.0", - "strip-ansi": "^6.0.0", + "strip-ansi": "^6.0.1", "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=12" } }, "node_modules/cliui/node_modules/ansi-regex": { @@ -1376,19 +1380,19 @@ } }, "node_modules/eslint": { - "version": "9.17.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.17.0.tgz", - "integrity": "sha512-evtlNcpJg+cZLcnVKwsai8fExnqjGPicK7gnUtlNuzu+Fv9bI0aLpND5T44VLQtoMEnI57LoXO9XAkIXwohKrA==", + "version": "9.20.1", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.20.1.tgz", + "integrity": "sha512-m1mM33o6dBUjxl2qb6wv6nGNwCAsns1eKtaQ4l/NPHeTvhiUPbtdfMyktxN4B3fgHIgsYh1VT3V9txblpQHq+g==", "dev": true, "license": "MIT", "dependencies": { "@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/regexpp": "^4.12.1", "@eslint/config-array": "^0.19.0", - "@eslint/core": "^0.9.0", + "@eslint/core": "^0.11.0", "@eslint/eslintrc": "^3.2.0", - "@eslint/js": "9.17.0", - "@eslint/plugin-kit": "^0.2.3", + "@eslint/js": "9.20.0", + "@eslint/plugin-kit": "^0.2.5", "@humanfs/node": "^0.16.6", "@humanwhocodes/module-importer": "^1.0.1", "@humanwhocodes/retry": "^0.4.1", @@ -1436,22 +1440,22 @@ } }, "node_modules/eslint-config-prettier": { - "version": "9.1.0", - "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-9.1.0.tgz", - "integrity": "sha512-NSWl5BFQWEPi1j4TjVNItzYV7dZXZ+wP6I6ZhrBGpChQhZRUaElihE9uRRkcbRnNb76UMKDF3r+WTmNcGPKsqw==", + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-10.0.1.tgz", + "integrity": "sha512-lZBts941cyJyeaooiKxAtzoPHTN+GbQTJFAIdQbRhA4/8whaAraEh47Whw/ZFfrjNSnlAxqfm9i0XVAEkULjCw==", "dev": true, "license": "MIT", "bin": { - "eslint-config-prettier": "bin/cli.js" + "eslint-config-prettier": "build/bin/cli.js" }, "peerDependencies": { "eslint": ">=7.0.0" } }, "node_modules/eslint-plugin-prettier": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/eslint-plugin-prettier/-/eslint-plugin-prettier-5.2.1.tgz", - "integrity": "sha512-gH3iR3g4JfF+yYPaJYkN7jEl9QbweL/YfkoRlNnuIEHEz1vHVlCmWOS+eGGiRuzHQXdJFCOTxRgvju9b8VUmrw==", + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/eslint-plugin-prettier/-/eslint-plugin-prettier-5.2.3.tgz", + "integrity": "sha512-qJ+y0FfCp/mQYQ/vWQ3s7eUlFEL4PyKfAJxsnYTJ4YT73nsJBWqmEpFryxV9OeUiqmsTsYJ5Y+KDNaeP31wrRw==", "dev": true, "license": "MIT", "dependencies": { @@ -1519,6 +1523,19 @@ "url": "https://opencollective.com/eslint" } }, + "node_modules/eslint/node_modules/@eslint/core": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.11.0.tgz", + "integrity": "sha512-DWUB2pksgNEb6Bz2fggIy1wh6fGgZP4Xyy/Mt0QZPiloKKXerbqq9D3SBQTlCRYOrcRPu4vuz+CGjwdfqxnoWA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@types/json-schema": "^7.0.15" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, "node_modules/eslint/node_modules/brace-expansion": { "version": "1.1.11", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", @@ -2352,9 +2369,9 @@ } }, "node_modules/mocha": { - "version": "11.0.1", - "resolved": "https://registry.npmjs.org/mocha/-/mocha-11.0.1.tgz", - "integrity": "sha512-+3GkODfsDG71KSCQhc4IekSW+ItCK/kiez1Z28ksWvYhKXV/syxMlerR/sC7whDp7IyreZ4YxceMLdTs5hQE8A==", + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/mocha/-/mocha-11.1.0.tgz", + "integrity": "sha512-8uJR5RTC2NgpY3GrYcgpZrsEd9zKbPDpob1RezyR2upGHRQtHWofmzTMzTMSV6dru3tj5Ukt0+Vnq1qhFEEwAg==", "dev": true, "license": "MIT", "dependencies": { @@ -2375,8 +2392,8 @@ "strip-json-comments": "^3.1.1", "supports-color": "^8.1.1", "workerpool": "^6.5.1", - "yargs": "^16.2.0", - "yargs-parser": "^20.2.9", + "yargs": "^17.7.2", + "yargs-parser": "^21.1.1", "yargs-unparser": "^2.0.0" }, "bin": { @@ -2608,9 +2625,9 @@ } }, "node_modules/prettier": { - "version": "3.4.2", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.4.2.tgz", - "integrity": "sha512-e9MewbtFo+Fevyuxn/4rrcDAaq0IYxPGLvObpQjiZBMAzB9IGmzlnG9RZy3FFas+eBMu2vA0CszMeduow5dIuQ==", + "version": "3.5.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.5.1.tgz", + "integrity": "sha512-hPpFQvHwL3Qv5AdRvBFMhnKo4tYxp0ReXiPn2bxkiohEX6mBeBwEpBSQTkD458RaaDKQMYSp4hX4UtfUTA5wDw==", "dev": true, "license": "MIT", "bin": { @@ -2745,32 +2762,32 @@ } }, "node_modules/rolldown": { - "version": "1.0.0-beta.1-commit.7c52c94", - "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.0.0-beta.1-commit.7c52c94.tgz", - "integrity": "sha512-WSkfhxZ/LMc6FkXhdMoOlyY7YsvxEC1ioqTIwceT7edoA1cIqkGY4pcaNtk1Ve/0hhTGFFPksbGlWW0avVwGQg==", + "version": "1.0.0-beta.3", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.0.0-beta.3.tgz", + "integrity": "sha512-DBpF1K8tSwU/0dQ7zL9BYcje0/GjO5lgfdEW0rHHFfGjGDh8TBVNlokfEXtdt/IoJOiTdtySfsrgarLJkZmZTQ==", "dev": true, "license": "MIT", "dependencies": { - "@oxc-project/types": "0.45.0", - "@valibot/to-json-schema": "1.0.0-beta.3", - "valibot": "1.0.0-beta.9" + "@oxc-project/types": "0.46.0", + "@valibot/to-json-schema": "1.0.0-beta.4", + "valibot": "1.0.0-beta.12" }, "bin": { "rolldown": "bin/cli.js" }, "optionalDependencies": { - "@rolldown/binding-darwin-arm64": "1.0.0-beta.1-commit.7c52c94", - "@rolldown/binding-darwin-x64": "1.0.0-beta.1-commit.7c52c94", - "@rolldown/binding-freebsd-x64": "1.0.0-beta.1-commit.7c52c94", - "@rolldown/binding-linux-arm-gnueabihf": "1.0.0-beta.1-commit.7c52c94", - "@rolldown/binding-linux-arm64-gnu": "1.0.0-beta.1-commit.7c52c94", - "@rolldown/binding-linux-arm64-musl": "1.0.0-beta.1-commit.7c52c94", - "@rolldown/binding-linux-x64-gnu": "1.0.0-beta.1-commit.7c52c94", - "@rolldown/binding-linux-x64-musl": "1.0.0-beta.1-commit.7c52c94", - "@rolldown/binding-wasm32-wasi": "1.0.0-beta.1-commit.7c52c94", - "@rolldown/binding-win32-arm64-msvc": "1.0.0-beta.1-commit.7c52c94", - "@rolldown/binding-win32-ia32-msvc": "1.0.0-beta.1-commit.7c52c94", - "@rolldown/binding-win32-x64-msvc": "1.0.0-beta.1-commit.7c52c94" + "@rolldown/binding-darwin-arm64": "1.0.0-beta.3", + "@rolldown/binding-darwin-x64": "1.0.0-beta.3", + "@rolldown/binding-freebsd-x64": "1.0.0-beta.3", + "@rolldown/binding-linux-arm-gnueabihf": "1.0.0-beta.3", + "@rolldown/binding-linux-arm64-gnu": "1.0.0-beta.3", + "@rolldown/binding-linux-arm64-musl": "1.0.0-beta.3", + "@rolldown/binding-linux-x64-gnu": "1.0.0-beta.3", + "@rolldown/binding-linux-x64-musl": "1.0.0-beta.3", + "@rolldown/binding-wasm32-wasi": "1.0.0-beta.3", + "@rolldown/binding-win32-arm64-msvc": "1.0.0-beta.3", + "@rolldown/binding-win32-ia32-msvc": "1.0.0-beta.3", + "@rolldown/binding-win32-x64-msvc": "1.0.0-beta.3" }, "peerDependencies": { "@babel/runtime": ">=7" @@ -2844,9 +2861,9 @@ "license": "MIT" }, "node_modules/semver": { - "version": "7.6.3", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz", - "integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==", + "version": "7.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.1.tgz", + "integrity": "sha512-hlq8tAfn0m/61p4BVRcPzIGr6LKiMwo4VM6dGi6pt4qcRkmNzTcWq6eCEjEh+qXjkMDvPlOFFSGwQjoEa6gyMA==", "dev": true, "license": "ISC", "bin": { @@ -3093,16 +3110,16 @@ } }, "node_modules/ts-api-utils": { - "version": "1.4.3", - "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-1.4.3.tgz", - "integrity": "sha512-i3eMG77UTMD0hZhgRS562pv83RC6ukSAC2GMNWc+9dieh/+jDM5u5YG+NHX6VNDRHQcHwmsTHctP9LhbC3WxVw==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.0.1.tgz", + "integrity": "sha512-dnlgjFSVetynI8nzgJ+qF62efpglpWRk8isUEWZGWlJYySCTD6aKvbUDu+zbPeDakk3bg5H4XpitHukgfL1m9w==", "dev": true, "license": "MIT", "engines": { - "node": ">=16" + "node": ">=18.12" }, "peerDependencies": { - "typescript": ">=4.2.0" + "typescript": ">=4.8.4" } }, "node_modules/tslib": { @@ -3126,9 +3143,9 @@ } }, "node_modules/typescript": { - "version": "5.7.2", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.7.2.tgz", - "integrity": "sha512-i5t66RHxDvVN40HfDd1PsEThGNnlMCMT3jMUuoh9/0TaqWevNontacunWyN02LA9/fIbEWlcHZcgTKb9QoaLfg==", + "version": "5.7.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.7.3.tgz", + "integrity": "sha512-84MVSjMEHP+FQRPy3pX9sTVV/INIex71s9TL2Gm5FG/WG1SqXeKyZ0k7/blY/4FdOzI12CBy1vGc4og/eus0fw==", "dev": true, "license": "Apache-2.0", "bin": { @@ -3140,15 +3157,15 @@ } }, "node_modules/typescript-eslint": { - "version": "8.18.2", - "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.18.2.tgz", - "integrity": "sha512-KuXezG6jHkvC3MvizeXgupZzaG5wjhU3yE8E7e6viOvAvD9xAWYp8/vy0WULTGe9DYDWcQu7aW03YIV3mSitrQ==", + "version": "8.24.1", + "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.24.1.tgz", + "integrity": "sha512-cw3rEdzDqBs70TIcb0Gdzbt6h11BSs2pS0yaq7hDWDBtCCSei1pPSUXE9qUdQ/Wm9NgFg8mKtMt1b8fTHIl1jA==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/eslint-plugin": "8.18.2", - "@typescript-eslint/parser": "8.18.2", - "@typescript-eslint/utils": "8.18.2" + "@typescript-eslint/eslint-plugin": "8.24.1", + "@typescript-eslint/parser": "8.24.1", + "@typescript-eslint/utils": "8.24.1" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -3190,9 +3207,9 @@ } }, "node_modules/valibot": { - "version": "1.0.0-beta.9", - "resolved": "https://registry.npmjs.org/valibot/-/valibot-1.0.0-beta.9.tgz", - "integrity": "sha512-yEX8gMAZ2R1yI2uwOO4NCtVnJQx36zn3vD0omzzj9FhcoblvPukENIiRZXKZwCnqSeV80bMm8wNiGhQ0S8fiww==", + "version": "1.0.0-beta.12", + "resolved": "https://registry.npmjs.org/valibot/-/valibot-1.0.0-beta.12.tgz", + "integrity": "sha512-j3WIxJ0pmUFMfdfUECn3YnZPYOiG0yHYcFEa/+RVgo0I+MXE3ToLt7gNRLtY5pwGfgNmsmhenGZfU5suu9ijUA==", "dev": true, "license": "MIT", "peerDependencies": { @@ -3350,32 +3367,32 @@ } }, "node_modules/yargs": { - "version": "16.2.0", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-16.2.0.tgz", - "integrity": "sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==", + "version": "17.7.2", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", + "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", "dev": true, "license": "MIT", "dependencies": { - "cliui": "^7.0.2", + "cliui": "^8.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", - "string-width": "^4.2.0", + "string-width": "^4.2.3", "y18n": "^5.0.5", - "yargs-parser": "^20.2.2" + "yargs-parser": "^21.1.1" }, "engines": { - "node": ">=10" + "node": ">=12" } }, "node_modules/yargs-parser": { - "version": "20.2.9", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.9.tgz", - "integrity": "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==", + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", "dev": true, "license": "ISC", "engines": { - "node": ">=10" + "node": ">=12" } }, "node_modules/yargs-unparser": { diff --git a/package.json b/package.json index 6ce6e81..0aa3e59 100755 --- a/package.json +++ b/package.json @@ -41,25 +41,25 @@ "webassembly" ], "devDependencies": { - "@eslint/js": "9.17.0", - "@types/node": "22.10.2", - "@typescript-eslint/parser": "8.18.2", - "chai": "5.1.2", + "@eslint/js": "9.20.0", + "@types/node": "22.13.4", + "@typescript-eslint/parser": "8.24.1", + "chai": "5.2.0", "chai-as-promised": "8.0.1", - "eslint": "9.17.0", - "eslint-config-prettier": "9.1.0", - "eslint-plugin-prettier": "5.2.1", + "eslint": "9.20.1", + "eslint-config-prettier": "10.0.1", + "eslint-plugin-prettier": "5.2.3", "eslint-plugin-simple-import-sort": "12.1.1", "fengari": "0.1.4", - "mocha": "11.0.1", - "prettier": "3.4.2", - "rolldown": "1.0.0-beta.1-commit.7c52c94", + "mocha": "11.1.0", + "prettier": "3.5.1", + "rolldown": "1.0.0-beta.3", "rollup-plugin-copy": "3.5.0", "tslib": "2.8.1", - "typescript": "5.7.2", - "typescript-eslint": "8.18.2" + "typescript": "5.7.3", + "typescript-eslint": "8.24.1" }, "dependencies": { - "@types/emscripten": "1.39.10" + "@types/emscripten": "1.40.0" } } diff --git a/rolldown.config.ts b/rolldown.config.ts index 2dfbc28..a8db3a5 100644 --- a/rolldown.config.ts +++ b/rolldown.config.ts @@ -12,7 +12,7 @@ export default defineConfig({ sourcemap: true, minify: production, }, - external: ['module'], + external: ['module', 'node:fs'], define: { // Webpack workaround: https://github.com/webpack/webpack/issues/16878 'import.meta': 'Object(import.meta)', diff --git a/src/factory.ts b/src/factory.ts index 0ef86d7..b3a45ad 100755 --- a/src/factory.ts +++ b/src/factory.ts @@ -15,6 +15,7 @@ export default class LuaFactory { * @param opts.wasmFile - Custom URI for the Lua WebAssembly module. * @param opts.env - Environment variables for the Lua engine. * @param opts.stdin - Standard input for the Lua engine. + * @param opts.fs - File system that should be used for the Lua engine. * @param opts.stdout - Standard output for the Lua engine. * @param opts.stderr - Standard error for the Lua engine. */ diff --git a/src/luawasm.ts b/src/luawasm.ts index 032ba9e..75f10fa 100755 --- a/src/luawasm.ts +++ b/src/luawasm.ts @@ -27,17 +27,33 @@ export default class LuaWasm { public static async initialize(opts: { wasmFile?: string env?: EnvironmentVariables + fs?: 'node' | 'memory' stdin?: () => number | null stdout?: () => number | null stderr?: () => number | null }): Promise { + const fs = opts.fs === 'node' && typeof process !== 'undefined' ? await import('node:fs') : null + const module: LuaEmscriptenModule = await initWasmModule({ locateFile: (path: string, scriptDirectory: string) => { return opts.wasmFile || scriptDirectory + path }, - preRun: (initializedModule: LuaEmscriptenModule) => { + preRun: (initializedModule: any) => { if (typeof opts?.env === 'object') { - Object.entries(opts.env).forEach(([k, v]) => (initializedModule.ENV[k] = v)) + Object.assign(initializedModule.ENV, opts.env) + } + + if (fs) { + const rootdirs = fs + .readdirSync('/') + .filter((dir) => !['dev', 'lib', 'proc'].includes(dir)) + .map((dir) => `/${dir}`) + + for (const dir of rootdirs) { + initializedModule.FS.mkdirTree(dir) + initializedModule.FS.mount(initializedModule.FS.filesystems.NODEFS, { root: dir }, dir) + } + initializedModule.FS.chdir(process.cwd()) } initializedModule.FS.init(opts?.stdin ?? null, opts?.stdout ?? null, opts?.stderr ?? null) diff --git a/test/initialization.test.js b/test/initialization.test.js index 72d1684..c0a4026 100644 --- a/test/initialization.test.js +++ b/test/initialization.test.js @@ -19,7 +19,7 @@ describe('Initialization', () => { const env = { ENV_TEST: 'test', } - const engine = await new LuaFactory(undefined, env).createEngine() + const engine = await new LuaFactory({ env }).createEngine() const value = await engine.doString('return os.getenv("ENV_TEST")') diff --git a/test/luatests.js b/test/luatests.js index 3b08dd2..681266e 100644 --- a/test/luatests.js +++ b/test/luatests.js @@ -1,25 +1,12 @@ import { LuaFactory } from '../dist/index.js' import { fileURLToPath } from 'node:url' -import { readFile, readdir } from 'node:fs/promises' -import { resolve } from 'node:path' - -async function* walk(dir) { - const dirents = await readdir(dir, { withFileTypes: true }) - for (const dirent of dirents) { - const res = resolve(dir, dirent.name) - if (dirent.isDirectory()) { - yield* walk(res) - } else { - yield res - } - } -} +import { readFile, glob } from 'node:fs/promises' const factory = new LuaFactory() const testsPath = import.meta.resolve('../lua/testes') const filePath = fileURLToPath(typeof testsPath === 'string' ? testsPath : await Promise.resolve(testsPath)) -for await (const file of walk(filePath)) { +for await (const file of glob(`${filePath}/**/*.lua`)) { const relativeFile = file.replace(`${filePath}/`, '') await factory.mountFile(relativeFile, await readFile(file)) } diff --git a/test/utils.js b/test/utils.js index 0bd5368..3106620 100644 --- a/test/utils.js +++ b/test/utils.js @@ -1,7 +1,7 @@ import { LuaFactory } from '../dist/index.js' export const getFactory = (env) => { - return new LuaFactory(undefined, env) + return new LuaFactory({ env }) } export const getEngine = (config = {}) => { diff --git a/tsconfig.json b/tsconfig.json index 14dbd93..625eae6 100755 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,11 +1,12 @@ { "compilerOptions": { "incremental": false, - "moduleResolution": "node", + "module": "ES2022", + "moduleResolution": "Bundler", "inlineSources": false, "removeComments": false, "sourceMap": false, - "target": "ES2018", + "target": "ES2022", "skipLibCheck": true, "lib": ["ESNEXT", "DOM"], "forceConsistentCasingInFileNames": true, From 2e0ab5f9de25ce260c5566ccfd70f8f1eac5ff71 Mon Sep 17 00:00:00 2001 From: ceifa Date: Tue, 18 Feb 2025 09:18:59 -0300 Subject: [PATCH 05/83] drop support for node 18 and 20 --- .github/workflows/test.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 50e5cc3..119e830 100755 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -10,13 +10,13 @@ jobs: strategy: matrix: - node-version: [18, 20, 22] + node-version: [22] steps: - uses: actions/checkout@v4 with: submodules: recursive - - uses: mymindstorm/setup-emsdk@v12 + - uses: mymindstorm/setup-emsdk@v14 - name: Use Node.js ${{ matrix.node-version }} uses: actions/setup-node@v4 with: From 580e25abf5bfa4cbe452c22d9a729c06f7aa52ec Mon Sep 17 00:00:00 2001 From: ceifa Date: Tue, 18 Feb 2025 10:35:26 -0300 Subject: [PATCH 06/83] unify build command --- build-wasm.js | 41 +++++++++++++++++++++++++++++++++ package.json | 6 ++--- rolldown.config.ts | 3 --- build.sh => utils/build-wasm.sh | 6 ++--- 4 files changed, 46 insertions(+), 10 deletions(-) create mode 100644 build-wasm.js rename build.sh => utils/build-wasm.sh (97%) mode change 100755 => 100644 diff --git a/build-wasm.js b/build-wasm.js new file mode 100644 index 0000000..eab40f8 --- /dev/null +++ b/build-wasm.js @@ -0,0 +1,41 @@ +import { execSync } from 'node:child_process' +import { resolve } from 'node:path' + +const isUnix = process.platform !== 'win32' +const rootdir = import.meta.dirname; +const args = process.argv.slice(2) + +const execute = (command) => { + console.log(`Running: ${command}`) + try { + execSync(command, { stdio: 'inherit' }) + } catch (error) { + console.error(`Error running command: ${command}`) + process.exit(1) + } +} + +execute('git submodule update --init --recursive') + +if (isUnix) { + let emccInstalled = false + try { + const version = execSync('emcc --version', { encoding: 'utf-8' }) + console.log('Emscripten is installed:', version) + + emccInstalled = true + } catch (error) { + console.error('Emscripten is not installed or not in your PATH. Will try to build using Docker.') + } + + if (emccInstalled) { + const command = `${resolve(rootdir, 'utils/build-wasm.sh')} ${args.join(' ')}` + execute(command) + } +} + + +const dockerVolume = `${rootdir}:/wasmoon` +const command = `docker run --rm -v "${dockerVolume}" emscripten/emsdk /wasmoon/utils/build-wasm.sh ${args.join(' ')}` + +execute(command) diff --git a/package.json b/package.json index 0aa3e59..d9a0bd9 100755 --- a/package.json +++ b/package.json @@ -5,10 +5,8 @@ "main": "./dist/index.js", "type": "module", "scripts": { - "build:wasm:dev": "./build.sh dev", - "build:wasm": "./build.sh", - "build:wasm:docker:dev": "docker run --rm -v $(pwd):/wasmoon emscripten/emsdk /wasmoon/build.sh dev", - "build:wasm:docker": "docker run --rm -v $(pwd):/wasmoon emscripten/emsdk /wasmoon/build.sh", + "build:wasm:dev": "node build-wasm dev", + "build:wasm": "node build-wasm", "start": "rolldown -w -c", "test": "mocha --parallel --require ./test/boot.js test/*.test.js", "luatests": "node --experimental-import-meta-resolve test/luatests.js", diff --git a/rolldown.config.ts b/rolldown.config.ts index a8db3a5..4ecd699 100644 --- a/rolldown.config.ts +++ b/rolldown.config.ts @@ -2,15 +2,12 @@ import { defineConfig } from 'rolldown' import copy from 'rollup-plugin-copy' import pkg from './package.json' with { type: 'json' } -const production = !process.env.ROLLUP_WATCH - export default defineConfig({ input: './src/index.ts', output: { file: 'dist/index.js', format: 'esm', sourcemap: true, - minify: production, }, external: ['module', 'node:fs'], define: { diff --git a/build.sh b/utils/build-wasm.sh old mode 100755 new mode 100644 similarity index 97% rename from build.sh rename to utils/build-wasm.sh index 252517e..3b6d9f5 --- a/build.sh +++ b/utils/build-wasm.sh @@ -1,8 +1,8 @@ #!/bin/bash -e cd $(dirname $0) -mkdir -p build +mkdir -p ../build -LUA_SRC=$(ls ./lua/*.c | grep -v "luac.c" | grep -v "lua.c" | tr "\n" " ") +LUA_SRC=$(ls ../lua/*.c | grep -v "luac.c" | grep -v "lua.c" | tr "\n" " ") extension="" if [ "$1" == "dev" ]; @@ -14,7 +14,7 @@ fi emcc \ -lnodefs.js \ - -s WASM=1 $extension -o ./build/glue.js \ + -s WASM=1 $extension -o ../build/glue.js \ -s EXPORTED_RUNTIME_METHODS="[ 'ccall', \ 'addFunction', \ From 32fdd5c859e513ea834ad60ba26aaf6afd43837c Mon Sep 17 00:00:00 2001 From: ceifa Date: Mon, 24 Feb 2025 21:05:59 -0300 Subject: [PATCH 07/83] specify cjs --- utils/{create-bindings.js => create-bindings.cjs} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename utils/{create-bindings.js => create-bindings.cjs} (100%) mode change 100755 => 100644 diff --git a/utils/create-bindings.js b/utils/create-bindings.cjs old mode 100755 new mode 100644 similarity index 100% rename from utils/create-bindings.js rename to utils/create-bindings.cjs From 9fdcef43e0df4f0366b60bb8eeda127441b76561 Mon Sep 17 00:00:00 2001 From: ceifa Date: Mon, 24 Feb 2025 21:06:14 -0300 Subject: [PATCH 08/83] add node fs support for windows --- rolldown.config.ts | 2 +- src/luawasm.ts | 42 ++++++++++++++++++++++++++++++++++-------- 2 files changed, 35 insertions(+), 9 deletions(-) diff --git a/rolldown.config.ts b/rolldown.config.ts index 4ecd699..5186a59 100644 --- a/rolldown.config.ts +++ b/rolldown.config.ts @@ -9,7 +9,7 @@ export default defineConfig({ format: 'esm', sourcemap: true, }, - external: ['module', 'node:fs'], + external: ['module', 'node:fs', 'node:child_process'], define: { // Webpack workaround: https://github.com/webpack/webpack/issues/16878 'import.meta': 'Object(import.meta)', diff --git a/src/luawasm.ts b/src/luawasm.ts index 75f10fa..84d4cdd 100755 --- a/src/luawasm.ts +++ b/src/luawasm.ts @@ -33,6 +33,7 @@ export default class LuaWasm { stderr?: () => number | null }): Promise { const fs = opts.fs === 'node' && typeof process !== 'undefined' ? await import('node:fs') : null + const child_process = opts.fs === 'node' && typeof process !== 'undefined' ? await import('node:child_process') : null const module: LuaEmscriptenModule = await initWasmModule({ locateFile: (path: string, scriptDirectory: string) => { @@ -43,17 +44,42 @@ export default class LuaWasm { Object.assign(initializedModule.ENV, opts.env) } - if (fs) { - const rootdirs = fs - .readdirSync('/') - .filter((dir) => !['dev', 'lib', 'proc'].includes(dir)) - .map((dir) => `/${dir}`) + if (fs && child_process) { + let rootdirs: string[] + if (process.platform === 'win32') { + const stdout = child_process.execSync('wmic logicaldisk get name', { encoding: 'utf8' }) + const drives = stdout + .split('\n') + .map((line) => line.trim()) + .filter((line) => line && line !== 'Name') + .map((line) => line + '\\') + + rootdirs = [] + for (const drive of drives) { + rootdirs.push( + ...fs + .readdirSync(drive) + .filter((dir) => !['dev', 'lib', 'proc'].includes(dir)) + .map((dir) => `${drive}${dir}`.replace(/\\|\\\\/g, '/')), + ) + } + } else { + rootdirs = fs + .readdirSync('/') + .filter((dir) => !['dev', 'lib', 'proc'].includes(dir)) + .map((dir) => `/${dir}`) + } for (const dir of rootdirs) { - initializedModule.FS.mkdirTree(dir) - initializedModule.FS.mount(initializedModule.FS.filesystems.NODEFS, { root: dir }, dir) + try { + initializedModule.FS.mkdirTree(dir) + initializedModule.FS.mount(initializedModule.FS.filesystems.NODEFS, { root: dir }, dir) + } catch { + // silently fail to mount (generally due to EPERM) + } } - initializedModule.FS.chdir(process.cwd()) + + initializedModule.FS.chdir(process.cwd().replace(/\\|\\\\/g, '/')) } initializedModule.FS.init(opts?.stdin ?? null, opts?.stdout ?? null, opts?.stderr ?? null) From dbda8f06179373c51cd3b45c43f26e77e29998d7 Mon Sep 17 00:00:00 2001 From: ceifa Date: Mon, 24 Feb 2025 21:06:24 -0300 Subject: [PATCH 09/83] more close to real api --- bin/wasmoon | 22 ++++++++-------------- 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/bin/wasmoon b/bin/wasmoon index 2abc218..1025970 100755 --- a/bin/wasmoon +++ b/bin/wasmoon @@ -1,8 +1,7 @@ #!/usr/bin/env node -import { LuaFactory, LuaReturn, LuaType, LUA_MULTRET, LuaRawResult, decorate, decorateFunction } from '../dist/index.js' +import { LuaFactory, LuaReturn, LuaType, LUA_MULTRET, decorate } from '../dist/index.js' import pkg from '../package.json' with { type: 'json' } import fs from 'node:fs' -import path from 'node:path' import readline from 'node:readline' function printUsage() { @@ -146,18 +145,13 @@ lua.global.set('arg', decorate(scriptArgs, { disableProxy: true })) const isTTY = process.stdin.isTTY -if (scriptFile) { - if (scriptFile === '-') { - const input = fs.readFileSync(0, 'utf-8') - await lua.doString(input) - console.log(lua.global.indexToString(-1)) - } else { - const absolutePath = path.resolve(process.cwd(), scriptFile) - const content = await fs.promises.readFile(absolutePath) - await factory.mountFile(absolutePath, content) - await lua.doFile(absolutePath) - console.log(lua.global.indexToString(-1)) - } +if (scriptFile === '-' || (!scriptFile && !isTTY)) { + const input = fs.readFileSync(0, 'utf-8') + await lua.doString(input) + console.log(lua.global.indexToString(-1)) +} else if (scriptFile) { + await lua.doFile(scriptFile) + console.log(lua.global.indexToString(-1)) } const shouldInteractive = isTTY && (forceInteractive || (!scriptFile && !executeSnippets.length)) From d9a63f9937e6552ea9554ad0bc17654e6dea2b49 Mon Sep 17 00:00:00 2001 From: ceifa Date: Mon, 24 Feb 2025 21:07:12 -0300 Subject: [PATCH 10/83] remove finalization registry check --- src/type-extensions/function.ts | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/src/type-extensions/function.ts b/src/type-extensions/function.ts index 753ee90..1972dc3 100644 --- a/src/type-extensions/function.ts +++ b/src/type-extensions/function.ts @@ -23,14 +23,11 @@ export interface FunctionTypeExtensionOptions { } class FunctionTypeExtension extends TypeExtension { - private readonly functionRegistry = - typeof FinalizationRegistry !== 'undefined' - ? new FinalizationRegistry((func: number) => { - if (!this.thread.isClosed()) { - this.thread.lua.luaL_unref(this.thread.address, LUA_REGISTRYINDEX, func) - } - }) - : undefined + private readonly functionRegistry = new FinalizationRegistry((func: number) => { + if (!this.thread.isClosed()) { + this.thread.lua.luaL_unref(this.thread.address, LUA_REGISTRYINDEX, func) + } + }) private gcPointer: number private functionWrapper: number From 1e04deb680e018e488f3bfe1ea0bfbb875116591 Mon Sep 17 00:00:00 2001 From: ceifa Date: Mon, 24 Feb 2025 22:52:46 -0300 Subject: [PATCH 11/83] stdin finally working (at least on linux) --- bin/wasmoon | 91 ++++++++++++++++++++++++++++++++------------- utils/build-wasm.sh | 0 2 files changed, 65 insertions(+), 26 deletions(-) mode change 100644 => 100755 utils/build-wasm.sh diff --git a/bin/wasmoon b/bin/wasmoon index 1025970..3dd5324 100755 --- a/bin/wasmoon +++ b/bin/wasmoon @@ -18,7 +18,7 @@ Available options are: -W turn warnings on -- stop handling options - stop handling options and execute stdin -`.trim(), +`.trim() ) process.exit(1) } @@ -48,19 +48,15 @@ function parseArgs(args) { case '-v': showVersion = true break - case '-W': warnings = true break - case '-E': ignoreEnv = true break - case '-i': forceInteractive = true break - case '-e': i++ if (i >= args.length) { @@ -69,7 +65,6 @@ function parseArgs(args) { } executeSnippets.push(args[i]) break - case '-l': i++ if (i >= args.length) { @@ -78,12 +73,10 @@ function parseArgs(args) { } includeModules.push(args[i]) break - case '-': scriptFile = '-' i++ break - default: console.log(`unrecognized option: '${arg}'`) printUsage() @@ -110,11 +103,70 @@ function parseArgs(args) { } } -const { executeSnippets, includeModules, ignoreEnv, forceInteractive, warnings, showVersion, scriptFile, scriptArgs } = parseArgs( - process.argv.slice(2), -) +const { + executeSnippets, + includeModules, + ignoreEnv, + forceInteractive, + warnings, + showVersion, + scriptFile, + scriptArgs, +} = parseArgs(process.argv.slice(2)) + +// When running interactively, process.stdin is used by readline. +// To allow Lua’s io.read to work (even in interactive mode), we open +// a separate file descriptor to the terminal (e.g. '/dev/tty' on Unix). +let inputFD = 0 +if (process.stdin.isTTY) { + try { + inputFD = fs.openSync('/dev/tty', 'r') + } catch (e) { + // If opening /dev/tty fails (or on non-Unix systems), fallback to fd 0. + inputFD = 0 + } +} + +const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + terminal: true, + removeHistoryDuplicates: true, + prompt: '> ' +}) + +let isresuming = false +const factory = new LuaFactory({ + env: ignoreEnv ? undefined : process.env, + fs: 'node', + stdin: () => { + if (isresuming) { + isresuming = false + return null + } else { + rl.pause() + } + + const buffer = Buffer.alloc(1) + const bytesRead = fs.readSync(inputFD, buffer, 0, buffer.length) + if (bytesRead > 0) { + const content = buffer.toString('utf8') + process.stdout.write(content) + + const charcode = content.charCodeAt(0) + if (charcode === 13) { + rl.resume() + isresuming = true + return null + } + + return charcode + } else { + return null + } + } +}) -const factory = new LuaFactory({ env: ignoreEnv ? undefined : process.env, fs: 'node' }) const luamodule = await factory.getLuaModule() const lua = await factory.createEngine() @@ -132,7 +184,6 @@ for (const module of includeModules) { if (!mod) { mod = global } - const require = lua.global.get('require') lua.global.set(global, require(mod)) } @@ -145,17 +196,14 @@ lua.global.set('arg', decorate(scriptArgs, { disableProxy: true })) const isTTY = process.stdin.isTTY -if (scriptFile === '-' || (!scriptFile && !isTTY)) { +if (scriptFile === '-') { const input = fs.readFileSync(0, 'utf-8') await lua.doString(input) - console.log(lua.global.indexToString(-1)) } else if (scriptFile) { await lua.doFile(scriptFile) - console.log(lua.global.indexToString(-1)) } const shouldInteractive = isTTY && (forceInteractive || (!scriptFile && !executeSnippets.length)) - if (shouldInteractive) { // Bypass result verification for interactive mode const loadcode = (code) => { @@ -168,14 +216,6 @@ if (shouldInteractive) { console.log(`Welcome to Wasmoon ${version} (${luaversion})`) console.log('Type Lua code and press Enter to execute. Ctrl+C to exit.\n') - const rl = readline.createInterface({ - input: process.stdin, - output: process.stdout, - terminal: true, - removeHistoryDuplicates: true, - prompt: '> ', - }) - rl.prompt() for await (const line of rl) { @@ -210,5 +250,4 @@ if (shouldInteractive) { // read from stdin until EOF. (Non-TTY or no -i, no file). const input = fs.readFileSync(0, 'utf-8') await lua.doString(input) - console.log(lua.global.indexToString(-1)) } diff --git a/utils/build-wasm.sh b/utils/build-wasm.sh old mode 100644 new mode 100755 From 048878a833c6bac5256258729ec754d1fa630b7a Mon Sep 17 00:00:00 2001 From: ceifa Date: Tue, 25 Feb 2025 08:00:39 -0300 Subject: [PATCH 12/83] add jsr publish --- .github/workflows/publish.yml | 101 ++++++++++++++++++++++++++++++---- 1 file changed, 90 insertions(+), 11 deletions(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 4aa8198..770a619 100755 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -3,26 +3,105 @@ name: CI on: push: branches: [main] + pull_request: + branches: [main] jobs: - publish: + build: runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 + - name: Checkout repository + uses: actions/checkout@v4 with: submodules: recursive - - uses: mymindstorm/setup-emsdk@v14 + + - name: Setup EMSDK + uses: mymindstorm/setup-emsdk@v14 + - name: Use Node.js 22.x uses: actions/setup-node@v4 with: node-version: 22.x - - run: npm ci - - run: npm run lint:nofix - - run: npm run build:wasm - - run: npm run build - - run: npm test - - run: npm run luatests - - uses: JS-DevTools/npm-publish@v3 + + - name: Install dependencies + run: npm ci + + - name: Run lint (no fix) + run: npm run lint:nofix + + - name: Build WASM + run: npm run build:wasm + + - name: Build project + run: npm run build + + - name: Run tests + run: npm test + + - name: Run Lua tests + run: npm run luatests + + - name: Upload build artifact + uses: actions/upload-artifact@v3 + with: + name: build-artifact + path: | + package.json + package-lock.json + dist/ + wasm/ + + publish_npm: + runs-on: ubuntu-latest + needs: build + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Download build artifact + uses: actions/download-artifact@v3 + with: + name: build-artifact + path: build-artifact + + - name: Restore build artifact + run: cp -r build-artifact/* . + + - name: Publish to npm + uses: JS-DevTools/npm-publish@v3 with: token: ${{ secrets.NPM_TOKEN }} + + publish_jsr: + runs-on: ubuntu-latest + needs: build + permissions: + contents: read + id-token: write + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Download build artifact + uses: actions/download-artifact@v3 + with: + name: build-artifact + path: build-artifact + + - name: Restore build artifact + run: cp -r build-artifact/* . + + - name: Generate jsr.json from package.json + run: | + node -e "const pkg = require('./package.json'); \ + const jsr = { \ + name: pkg.name, \ + version: pkg.version, \ + description: pkg.description, \ + repository: pkg.repository, \ + license: pkg.license \ + }; \ + require('fs').writeFileSync('jsr.json', JSON.stringify(jsr, null, 2));" + + - name: Publish to JSR + run: npx jsr publish From 07096b3fd8d7130c17d1ef3379c49d98c2e430d4 Mon Sep 17 00:00:00 2001 From: ceifa Date: Tue, 25 Feb 2025 08:04:23 -0300 Subject: [PATCH 13/83] update artifact package --- .github/workflows/publish.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 770a619..eaf7ed8 100755 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -42,14 +42,14 @@ jobs: run: npm run luatests - name: Upload build artifact - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: build-artifact path: | package.json package-lock.json dist/ - wasm/ + bin/ publish_npm: runs-on: ubuntu-latest @@ -59,7 +59,7 @@ jobs: uses: actions/checkout@v4 - name: Download build artifact - uses: actions/download-artifact@v3 + uses: actions/download-artifact@v4 with: name: build-artifact path: build-artifact @@ -83,7 +83,7 @@ jobs: uses: actions/checkout@v4 - name: Download build artifact - uses: actions/download-artifact@v3 + uses: actions/download-artifact@v4 with: name: build-artifact path: build-artifact From 26839478857b3a8c90f7dba1a0707bd6052feac5 Mon Sep 17 00:00:00 2001 From: ceifa Date: Tue, 25 Feb 2025 08:13:41 -0300 Subject: [PATCH 14/83] lint --- bin/wasmoon | 19 ++++++------------- package.json | 4 ++-- src/luawasm.ts | 2 +- build-wasm.js => utils/build-wasm.js | 5 +++-- 4 files changed, 12 insertions(+), 18 deletions(-) rename build-wasm.js => utils/build-wasm.js (93%) diff --git a/bin/wasmoon b/bin/wasmoon index 3dd5324..4c8cfbf 100755 --- a/bin/wasmoon +++ b/bin/wasmoon @@ -18,7 +18,7 @@ Available options are: -W turn warnings on -- stop handling options - stop handling options and execute stdin -`.trim() +`.trim(), ) process.exit(1) } @@ -103,16 +103,9 @@ function parseArgs(args) { } } -const { - executeSnippets, - includeModules, - ignoreEnv, - forceInteractive, - warnings, - showVersion, - scriptFile, - scriptArgs, -} = parseArgs(process.argv.slice(2)) +const { executeSnippets, includeModules, ignoreEnv, forceInteractive, warnings, showVersion, scriptFile, scriptArgs } = parseArgs( + process.argv.slice(2), +) // When running interactively, process.stdin is used by readline. // To allow Lua’s io.read to work (even in interactive mode), we open @@ -132,7 +125,7 @@ const rl = readline.createInterface({ output: process.stdout, terminal: true, removeHistoryDuplicates: true, - prompt: '> ' + prompt: '> ', }) let isresuming = false @@ -164,7 +157,7 @@ const factory = new LuaFactory({ } else { return null } - } + }, }) const luamodule = await factory.getLuaModule() diff --git a/package.json b/package.json index d9a0bd9..82f1c7a 100755 --- a/package.json +++ b/package.json @@ -5,8 +5,8 @@ "main": "./dist/index.js", "type": "module", "scripts": { - "build:wasm:dev": "node build-wasm dev", - "build:wasm": "node build-wasm", + "build:wasm:dev": "node utils/build-wasm dev", + "build:wasm": "node utils/build-wasm", "start": "rolldown -w -c", "test": "mocha --parallel --require ./test/boot.js test/*.test.js", "luatests": "node --experimental-import-meta-resolve test/luatests.js", diff --git a/src/luawasm.ts b/src/luawasm.ts index 84d4cdd..8902f64 100755 --- a/src/luawasm.ts +++ b/src/luawasm.ts @@ -52,7 +52,7 @@ export default class LuaWasm { .split('\n') .map((line) => line.trim()) .filter((line) => line && line !== 'Name') - .map((line) => line + '\\') + .map((line) => `${line}\\`) rootdirs = [] for (const drive of drives) { diff --git a/build-wasm.js b/utils/build-wasm.js similarity index 93% rename from build-wasm.js rename to utils/build-wasm.js index eab40f8..7a9b590 100644 --- a/build-wasm.js +++ b/utils/build-wasm.js @@ -2,7 +2,7 @@ import { execSync } from 'node:child_process' import { resolve } from 'node:path' const isUnix = process.platform !== 'win32' -const rootdir = import.meta.dirname; +const rootdir = resolve(import.meta.dirname, '..') const args = process.argv.slice(2) const execute = (command) => { @@ -31,10 +31,11 @@ if (isUnix) { if (emccInstalled) { const command = `${resolve(rootdir, 'utils/build-wasm.sh')} ${args.join(' ')}` execute(command) + + process.exit(0) } } - const dockerVolume = `${rootdir}:/wasmoon` const command = `docker run --rm -v "${dockerVolume}" emscripten/emsdk /wasmoon/utils/build-wasm.sh ${args.join(' ')}` From a315ababc7f0990d1c6ef9cbdc97f257738f62b1 Mon Sep 17 00:00:00 2001 From: ceifa Date: Tue, 25 Feb 2025 08:24:04 -0300 Subject: [PATCH 15/83] fix jsr.json structure --- .github/workflows/publish.yml | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index eaf7ed8..e4c5f21 100755 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -97,9 +97,7 @@ jobs: const jsr = { \ name: pkg.name, \ version: pkg.version, \ - description: pkg.description, \ - repository: pkg.repository, \ - license: pkg.license \ + exports: pkg.main \ }; \ require('fs').writeFileSync('jsr.json', JSON.stringify(jsr, null, 2));" From 68deb27b4e079e0843505b1399da3325be46fc65 Mon Sep 17 00:00:00 2001 From: ceifa Date: Tue, 25 Feb 2025 08:26:08 -0300 Subject: [PATCH 16/83] package name --- .github/workflows/publish.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index e4c5f21..534ae7f 100755 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -95,7 +95,7 @@ jobs: run: | node -e "const pkg = require('./package.json'); \ const jsr = { \ - name: pkg.name, \ + name: `@ceifa/${pkg.name}`, \ version: pkg.version, \ exports: pkg.main \ }; \ From 84ee22ce695e75d66bdfaa276476705ce58ca81e Mon Sep 17 00:00:00 2001 From: ceifa Date: Tue, 25 Feb 2025 08:28:03 -0300 Subject: [PATCH 17/83] concatenation --- .github/workflows/publish.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 534ae7f..4b12368 100755 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -95,7 +95,7 @@ jobs: run: | node -e "const pkg = require('./package.json'); \ const jsr = { \ - name: `@ceifa/${pkg.name}`, \ + name: '@ceifa/' + pkg.name, \ version: pkg.version, \ exports: pkg.main \ }; \ From 745fac60c45e04687039ac65b054f1e13aa60015 Mon Sep 17 00:00:00 2001 From: ceifa Date: Tue, 25 Feb 2025 08:37:30 -0300 Subject: [PATCH 18/83] force include --- .github/workflows/publish.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 4b12368..9825163 100755 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -97,7 +97,8 @@ jobs: const jsr = { \ name: '@ceifa/' + pkg.name, \ version: pkg.version, \ - exports: pkg.main \ + exports: pkg.main, \ + include: ['dist/**/*', 'bin/**/*'] \ }; \ require('fs').writeFileSync('jsr.json', JSON.stringify(jsr, null, 2));" From 3b4d4e125d5d8271ff33cc292b665e0c7a5ce7bc Mon Sep 17 00:00:00 2001 From: ceifa Date: Tue, 25 Feb 2025 08:56:23 -0300 Subject: [PATCH 19/83] force exclude dist --- .github/workflows/publish.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 9825163..0a8f53c 100755 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -98,7 +98,8 @@ jobs: name: '@ceifa/' + pkg.name, \ version: pkg.version, \ exports: pkg.main, \ - include: ['dist/**/*', 'bin/**/*'] \ + include: ['dist/**/*', 'bin/**/*'], \ + exclude: ['!dist/**/*'], \ }; \ require('fs').writeFileSync('jsr.json', JSON.stringify(jsr, null, 2));" From f8f95f5cb99f0597ab69ba1dd3c032c29c14b28d Mon Sep 17 00:00:00 2001 From: ceifa Date: Tue, 25 Feb 2025 08:59:07 -0300 Subject: [PATCH 20/83] try not checking out repo --- .github/workflows/publish.yml | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 0a8f53c..ac9ebe7 100755 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -79,9 +79,6 @@ jobs: contents: read id-token: write steps: - - name: Checkout repository - uses: actions/checkout@v4 - - name: Download build artifact uses: actions/download-artifact@v4 with: @@ -98,8 +95,7 @@ jobs: name: '@ceifa/' + pkg.name, \ version: pkg.version, \ exports: pkg.main, \ - include: ['dist/**/*', 'bin/**/*'], \ - exclude: ['!dist/**/*'], \ + include: ['dist/**/*', 'bin/**/*'] }; \ require('fs').writeFileSync('jsr.json', JSON.stringify(jsr, null, 2));" From 8acf55d30b66aab2d5bdcc5bfe7b5d2dde383d01 Mon Sep 17 00:00:00 2001 From: ceifa Date: Tue, 25 Feb 2025 09:01:10 -0300 Subject: [PATCH 21/83] license --- .github/workflows/publish.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index ac9ebe7..a7f4aa4 100755 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -50,6 +50,7 @@ jobs: package-lock.json dist/ bin/ + LICENSE publish_npm: runs-on: ubuntu-latest From b3778d6d89df5b5ab1a7bb24d75e24e1617727d5 Mon Sep 17 00:00:00 2001 From: ceifa Date: Tue, 25 Feb 2025 09:34:13 -0300 Subject: [PATCH 22/83] test older emscripten version --- .github/workflows/publish.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index a7f4aa4..84bf493 100755 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -17,6 +17,8 @@ jobs: - name: Setup EMSDK uses: mymindstorm/setup-emsdk@v14 + with: + version: 4.0.1 - name: Use Node.js 22.x uses: actions/setup-node@v4 @@ -94,7 +96,7 @@ jobs: node -e "const pkg = require('./package.json'); \ const jsr = { \ name: '@ceifa/' + pkg.name, \ - version: pkg.version, \ + version: 1.16.1, \ exports: pkg.main, \ include: ['dist/**/*', 'bin/**/*'] }; \ From 657a0799d91f33d8a5ae3e4a72cada6c64610a03 Mon Sep 17 00:00:00 2001 From: ceifa Date: Tue, 25 Feb 2025 09:34:44 -0300 Subject: [PATCH 23/83] fix string --- .github/workflows/publish.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 84bf493..2039fc8 100755 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -96,7 +96,7 @@ jobs: node -e "const pkg = require('./package.json'); \ const jsr = { \ name: '@ceifa/' + pkg.name, \ - version: 1.16.1, \ + version: '1.16.1', \ exports: pkg.main, \ include: ['dist/**/*', 'bin/**/*'] }; \ From 32af619d08ab3330e7e94430cd7056115ef0e8b6 Mon Sep 17 00:00:00 2001 From: ceifa Date: Tue, 25 Feb 2025 09:42:55 -0300 Subject: [PATCH 24/83] disable jsr publish --- .github/workflows/publish.yml | 61 +++++++++++++++++------------------ 1 file changed, 30 insertions(+), 31 deletions(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 2039fc8..3dbc317 100755 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -3,8 +3,6 @@ name: CI on: push: branches: [main] - pull_request: - branches: [main] jobs: build: @@ -75,32 +73,33 @@ jobs: with: token: ${{ secrets.NPM_TOKEN }} - publish_jsr: - runs-on: ubuntu-latest - needs: build - permissions: - contents: read - id-token: write - steps: - - name: Download build artifact - uses: actions/download-artifact@v4 - with: - name: build-artifact - path: build-artifact - - - name: Restore build artifact - run: cp -r build-artifact/* . - - - name: Generate jsr.json from package.json - run: | - node -e "const pkg = require('./package.json'); \ - const jsr = { \ - name: '@ceifa/' + pkg.name, \ - version: '1.16.1', \ - exports: pkg.main, \ - include: ['dist/**/*', 'bin/**/*'] - }; \ - require('fs').writeFileSync('jsr.json', JSON.stringify(jsr, null, 2));" - - - name: Publish to JSR - run: npx jsr publish + # Emscripten still doesn't support deno + # publish_jsr: + # runs-on: ubuntu-latest + # needs: build + # permissions: + # contents: read + # id-token: write + # steps: + # - name: Download build artifact + # uses: actions/download-artifact@v4 + # with: + # name: build-artifact + # path: build-artifact + + # - name: Restore build artifact + # run: cp -r build-artifact/* . + + # - name: Generate jsr.json from package.json + # run: | + # node -e "const pkg = require('./package.json'); \ + # const jsr = { \ + # name: '@ceifa/' + pkg.name, \ + # version: pkg.version, \ + # exports: pkg.main, \ + # include: ['dist/**/*', 'bin/**/*'] + # }; \ + # require('fs').writeFileSync('jsr.json', JSON.stringify(jsr, null, 2));" + + # - name: Publish to JSR + # run: npx jsr publish From a34ed7448fa0d85f3b1d3ce217b8d28b46a7a515 Mon Sep 17 00:00:00 2001 From: ceifa Date: Wed, 26 Feb 2025 18:22:44 -0300 Subject: [PATCH 25/83] better api for stdio --- bin/wasmoon | 49 +++++++++++++++++++++++++++------------------ src/luawasm.ts | 46 +++++++++++++++++++++++++++++++++++------- utils/build-wasm.sh | 5 ++++- 3 files changed, 72 insertions(+), 28 deletions(-) diff --git a/bin/wasmoon b/bin/wasmoon index 4c8cfbf..a71cbed 100755 --- a/bin/wasmoon +++ b/bin/wasmoon @@ -128,34 +128,43 @@ const rl = readline.createInterface({ prompt: '> ', }) -let isresuming = false const factory = new LuaFactory({ env: ignoreEnv ? undefined : process.env, fs: 'node', stdin: () => { - if (isresuming) { - isresuming = false - return null - } else { + try { rl.pause() - } - const buffer = Buffer.alloc(1) - const bytesRead = fs.readSync(inputFD, buffer, 0, buffer.length) - if (bytesRead > 0) { - const content = buffer.toString('utf8') - process.stdout.write(content) - - const charcode = content.charCodeAt(0) - if (charcode === 13) { - rl.resume() - isresuming = true - return null + let buffer = Buffer.alloc(0xff) + let content = '' + let current = 0 + + while (true) { + const bytesRead = fs.readSync(inputFD, buffer, current, buffer.length - current) + if (bytesRead > 0) { + const charcode = buffer[current++] + if (charcode === 127) { + current = Math.max(0, current - 2) + } else { + if (charcode === 13) { + break + } + } + + content = buffer.subarray(0, current).toString('utf8') + process.stdout.write('\x1b[2K') + process.stdout.write('\x1b[0G') + process.stdout.write(content) + } else { + break + } } - return charcode - } else { - return null + rl.resume() + return content + } catch (err) { + // the error will not be thrown to the top, its better to log it + console.error(err) } }, }) diff --git a/src/luawasm.ts b/src/luawasm.ts index 8902f64..789373d 100755 --- a/src/luawasm.ts +++ b/src/luawasm.ts @@ -13,6 +13,7 @@ interface LuaEmscriptenModule extends EmscriptenModule { stringToNewUTF8: typeof allocateUTF8 lengthBytesUTF8: typeof lengthBytesUTF8 stringToUTF8: typeof stringToUTF8 + intArrayFromString: typeof intArrayFromString UTF8ToString: typeof UTF8ToString ENV: EnvironmentVariables _realloc: (pointer: number, size: number) => number @@ -28,18 +29,20 @@ export default class LuaWasm { wasmFile?: string env?: EnvironmentVariables fs?: 'node' | 'memory' - stdin?: () => number | null - stdout?: () => number | null - stderr?: () => number | null + stdin?: () => string + stdout?: (content: string) => void + stderr?: (content: string) => void }): Promise { const fs = opts.fs === 'node' && typeof process !== 'undefined' ? await import('node:fs') : null const child_process = opts.fs === 'node' && typeof process !== 'undefined' ? await import('node:child_process') : null const module: LuaEmscriptenModule = await initWasmModule({ + print: opts.stdout, + printErr: opts.stderr, locateFile: (path: string, scriptDirectory: string) => { return opts.wasmFile || scriptDirectory + path }, - preRun: (initializedModule: any) => { + preRun: (initializedModule: LuaEmscriptenModule) => { if (typeof opts?.env === 'object') { Object.assign(initializedModule.ENV, opts.env) } @@ -72,8 +75,9 @@ export default class LuaWasm { for (const dir of rootdirs) { try { - initializedModule.FS.mkdirTree(dir) - initializedModule.FS.mount(initializedModule.FS.filesystems.NODEFS, { root: dir }, dir) + const moduleFS = initializedModule.FS as any // emscripten FS module is not correctly typed + moduleFS.mkdirTree(dir) + moduleFS.mount(moduleFS.filesystems.NODEFS, { root: dir }, dir) } catch { // silently fail to mount (generally due to EPERM) } @@ -82,7 +86,35 @@ export default class LuaWasm { initializedModule.FS.chdir(process.cwd().replace(/\\|\\\\/g, '/')) } - initializedModule.FS.init(opts?.stdin ?? null, opts?.stdout ?? null, opts?.stderr ?? null) + if (opts.stdin) { + let bufferedInput: number[] | undefined + initializedModule.FS.init( + () => { + if (!opts.stdin) { + throw new Error('stdin is not defined, it was probably mutated from original options') + } + + if (!bufferedInput) { + const stdin = opts.stdin() + if (typeof stdin === 'string') { + bufferedInput = initializedModule.intArrayFromString(stdin, true).concat([0]) + } else { + throw new Error('stdin must return a string') + } + } + + if (bufferedInput.length === 0) { + bufferedInput = undefined + return null + } + + const item = bufferedInput.shift() + return !item || item === 0 ? null : item + }, + null, + null, + ) + } }, }) return new LuaWasm(module) diff --git a/utils/build-wasm.sh b/utils/build-wasm.sh index 3b6d9f5..6b18ceb 100755 --- a/utils/build-wasm.sh +++ b/utils/build-wasm.sh @@ -26,12 +26,15 @@ emcc \ 'lengthBytesUTF8', \ 'stringToUTF8', \ 'stringToNewUTF8', \ + 'intArrayFromString', \ 'UTF8ToString', \ 'HEAPU32' ]" \ -s INCOMING_MODULE_JS_API="[ 'locateFile', \ - 'preRun' + 'preRun', \ + 'print', \ + 'printErr' \ ]" \ -s ENVIRONMENT="web,worker,node" \ -s MODULARIZE=1 \ From e63fcb622ff56d09fae84fcec98a304c3314dd24 Mon Sep 17 00:00:00 2001 From: ceifa Date: Wed, 26 Feb 2025 18:25:25 -0300 Subject: [PATCH 26/83] check for docker --- utils/build-wasm.js | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/utils/build-wasm.js b/utils/build-wasm.js index 7a9b590..ff97b26 100644 --- a/utils/build-wasm.js +++ b/utils/build-wasm.js @@ -36,6 +36,14 @@ if (isUnix) { } } +try { + execSync('docker --version', { encoding: 'utf-8' }) +} +catch (error) { + console.error('Docker is not installed or not in your PATH. Please install Docker to build the WASM file.') + process.exit(1) +} + const dockerVolume = `${rootdir}:/wasmoon` const command = `docker run --rm -v "${dockerVolume}" emscripten/emsdk /wasmoon/utils/build-wasm.sh ${args.join(' ')}` From ecc6388bc0ff9594cf09069ec29380035d59941b Mon Sep 17 00:00:00 2001 From: ceifa Date: Wed, 26 Feb 2025 20:38:14 -0300 Subject: [PATCH 27/83] changed library api to abstract wasm (but keep it exposed) and change api of lua creation --- bench/comparisons.js | 74 +++++-- bench/heapsort.lua | 2 + bench/steps.js | 62 +++--- bin/wasmoon | 41 ++-- package.json | 1 + src/engine.ts | 8 +- src/factory.ts | 97 --------- src/global.ts | 16 +- src/index.ts | 7 +- src/lua.ts | 46 +++++ src/{luawasm.ts => module.ts} | 47 +++-- src/thread.ts | 26 +-- src/type-extension.ts | 4 +- src/type-extensions/error.ts | 6 +- src/type-extensions/function.ts | 14 +- src/type-extensions/null.ts | 6 +- src/type-extensions/promise.ts | 10 +- src/type-extensions/proxy.ts | 8 +- src/type-extensions/userdata.ts | 8 +- test/debug.js | 10 +- test/engine.test.js | 352 ++++++++++++++++---------------- test/filesystem.test.js | 52 ++--- test/initialization.test.js | 25 ++- test/luatests.js | 21 +- test/promises.test.js | 118 +++++------ test/utils.js | 11 +- utils/build-wasm.sh | 1 + 27 files changed, 544 insertions(+), 529 deletions(-) delete mode 100755 src/factory.ts create mode 100755 src/lua.ts rename src/{luawasm.ts => module.ts} (95%) diff --git a/bench/comparisons.js b/bench/comparisons.js index 49c7b1b..1a72e9a 100644 --- a/bench/comparisons.js +++ b/bench/comparisons.js @@ -1,30 +1,62 @@ -const { readFileSync } = require('fs') -const path = require('path') +import { readFileSync } from 'fs' +import path from 'path' +import { performance } from 'perf_hooks' +import { Lua } from '../dist/index.js' +import fengari from 'fengari' -const fengari = require('fengari') -const wasmoon = require('../dist/index') +const heapsort = readFileSync(path.resolve(import.meta.dirname, 'heapsort.lua'), 'utf-8') -const heapsort = readFileSync(path.resolve(__dirname, 'heapsort.lua'), 'utf-8') +function calculateStats(times) { + const n = times.length + const avg = times.reduce((sum, t) => sum + t, 0) / n + const stdDev = Math.sqrt(times.reduce((sum, t) => sum + (t - avg) ** 2, 0) / n) + return { avg, stdDev } +} + +async function benchmark(name, iterations, warmup, fn) { + console.log(`\nBenchmarking ${name}...`) + + for (let i = 0; i < warmup; i++) { + await fn() + } -const startFengari = () => { - const state = fengari.lauxlib.luaL_newstate() - fengari.lualib.luaL_openlibs(state) + const times = [] + for (let i = 0; i < iterations; i++) { + const start = performance.now() + await fn() + const end = performance.now() + times.push(end - start) + } - console.time('Fengari') - fengari.lauxlib.luaL_loadstring(state, fengari.to_luastring(heapsort)) - fengari.lua.lua_callk(state, 0, 1, 0, null) - fengari.lua.lua_callk(state, 0, 0, 0, null) - console.timeEnd('Fengari') + const { avg, stdDev } = calculateStats(times) + console.log(`${name}: ${iterations} iterations | avg: ${avg.toFixed(3)} ms | std dev: ${stdDev.toFixed(3)} ms`) } -const startWasmoon = async () => { - const state = await new wasmoon.LuaFactory().createEngine() +async function benchmarkFengari(iterations, warmup) { + function runFengariIteration() { + const state = fengari.lauxlib.luaL_newstate() + fengari.lualib.luaL_openlibs(state) + fengari.lauxlib.luaL_loadstring(state, fengari.to_luastring(heapsort)) + fengari.lua.lua_callk(state, 0, 1, 0, null) + fengari.lua.lua_callk(state, 0, 0, 0, null) + } + await benchmark('Fengari', iterations, warmup, runFengariIteration) +} + +async function benchmarkWasmoon(iterations, warmup) { + const lua = await Lua.load() - console.time('Wasmoon') - state.global.lua.luaL_loadstring(state.global.address, heapsort) - state.global.lua.lua_callk(state.global.address, 0, 1, 0, null) - state.global.lua.lua_callk(state.global.address, 0, 0, 0, null) - console.timeEnd('Wasmoon') + async function runWasmoonIteration() { + const state = lua.createState() + state.global.lua.luaL_loadstring(state.global.address, heapsort) + state.global.lua.lua_callk(state.global.address, 0, 1, 0, null) + state.global.lua.lua_callk(state.global.address, 0, 0, 0, null) + } + await benchmark('Wasmoon', iterations, warmup, runWasmoonIteration) } -Promise.resolve().then(startFengari).then(startWasmoon).catch(console.error) +const iterations = 100 +const warmup = 10 + +await benchmarkFengari(iterations, warmup) +await benchmarkWasmoon(iterations, warmup) diff --git a/bench/heapsort.lua b/bench/heapsort.lua index 5e7ce00..026f651 100644 --- a/bench/heapsort.lua +++ b/bench/heapsort.lua @@ -57,4 +57,6 @@ return function() assert(a[i] <= a[i + 1]) end end + + return Num end diff --git a/bench/steps.js b/bench/steps.js index 9c670d5..9066fcd 100644 --- a/bench/steps.js +++ b/bench/steps.js @@ -1,44 +1,39 @@ -const { readFileSync } = require('fs') -const path = require('path') +import { readFileSync } from 'fs' +import path from 'path' +import { Lua } from '../dist/index.js' +import assert from 'node:assert' -const wasmoon = require('../dist/index') +const heapsort = readFileSync(path.resolve(import.meta.dirname, 'heapsort.lua'), 'utf-8') -const heapsort = readFileSync(path.resolve(__dirname, 'heapsort.lua'), 'utf-8') - -const createFactory = () => { +const createFactory = async () => { console.time('Create factory') - _ = new wasmoon.LuaFactory() + await Lua.load() console.timeEnd('Create factory') } -const loadWasm = async () => { - console.time('Load wasm') - await new wasmoon.LuaFactory().getLuaModule() - console.timeEnd('Load wasm') -} - -const createEngine = async () => { - const factory = new wasmoon.LuaFactory() +const createState = async () => { + const lua = await Lua.load() - console.time('Create engine') - await factory.createEngine() - console.timeEnd('Create engine') + console.time('Create state') + lua.createState() + console.timeEnd('Create state') } -const createEngineWithoutSuperpowers = async () => { - const factory = new wasmoon.LuaFactory() +const createStateWithoutSuperpowers = async () => { + const lua = await Lua.load() - console.time('Create engine without superpowers') - await factory.createEngine({ + console.time('Create state without superpowers') + lua.createState({ injectObjects: false, enableProxy: false, openStandardLibs: false, }) - console.timeEnd('Create engine without superpowers') + console.timeEnd('Create state without superpowers') } const runHeapsort = async () => { - const state = await new wasmoon.LuaFactory().createEngine() + const lua = await Lua.load() + const state = lua.createState() console.time('Run plain heapsort') state.global.lua.luaL_loadstring(state.global.address, heapsort) @@ -48,16 +43,18 @@ const runHeapsort = async () => { } const runInteropedHeapsort = async () => { - const state = await new wasmoon.LuaFactory().createEngine() + const lua = await Lua.load() + const state = lua.createState() console.time('Run interoped heapsort') const runHeapsort = await state.doString(heapsort) - runHeapsort() + assert(runHeapsort() === 10) console.timeEnd('Run interoped heapsort') } const insertComplexObjects = async () => { - const state = await new wasmoon.LuaFactory().createEngine() + const lua = await Lua.load() + const state = lua.createState() const obj1 = { hello: 'world', } @@ -77,7 +74,8 @@ const insertComplexObjects = async () => { } const insertComplexObjectsWithoutProxy = async () => { - const state = await new wasmoon.LuaFactory().createEngine({ + const lua = await Lua.load() + const state = lua.createState({ enableProxy: false, }) const obj1 = { @@ -99,7 +97,8 @@ const insertComplexObjectsWithoutProxy = async () => { } const getComplexObjects = async () => { - const state = await new wasmoon.LuaFactory().createEngine() + const lua = await Lua.load() + const state = lua.createState() await state.doString(` local obj1 = { hello = 'world', @@ -124,9 +123,8 @@ const getComplexObjects = async () => { Promise.resolve() .then(createFactory) - .then(loadWasm) - .then(createEngine) - .then(createEngineWithoutSuperpowers) + .then(createState) + .then(createStateWithoutSuperpowers) .then(runHeapsort) .then(runInteropedHeapsort) .then(insertComplexObjects) diff --git a/bin/wasmoon b/bin/wasmoon index a71cbed..db9cbb7 100755 --- a/bin/wasmoon +++ b/bin/wasmoon @@ -1,5 +1,5 @@ #!/usr/bin/env node -import { LuaFactory, LuaReturn, LuaType, LUA_MULTRET, decorate } from '../dist/index.js' +import { Lua, LuaReturn, LuaType, LUA_MULTRET, decorate } from '../dist/index.js' import pkg from '../package.json' with { type: 'json' } import fs from 'node:fs' import readline from 'node:readline' @@ -128,7 +128,7 @@ const rl = readline.createInterface({ prompt: '> ', }) -const factory = new LuaFactory({ +const lua = await Lua.load({ env: ignoreEnv ? undefined : process.env, fs: 'node', stdin: () => { @@ -169,16 +169,15 @@ const factory = new LuaFactory({ }, }) -const luamodule = await factory.getLuaModule() -const lua = await factory.createEngine() +const state = lua.createState() if (showVersion) { - console.log(`wasmoon ${pkg.version} (${lua.global.get('_VERSION')})`) + console.log(`wasmoon ${pkg.version} (${state.global.get('_VERSION')})`) process.exit(0) } if (warnings) { - luamodule.lua_warning(lua.global.address, '@on', 0) + lua.module.lua_warning(state.global.address, '@on', 0) } for (const module of includeModules) { @@ -186,35 +185,35 @@ for (const module of includeModules) { if (!mod) { mod = global } - const require = lua.global.get('require') - lua.global.set(global, require(mod)) + const require = state.global.get('require') + state.global.set(global, require(mod)) } for (const snippet of executeSnippets) { - await lua.doString(snippet) + await state.doString(snippet) } -lua.global.set('arg', decorate(scriptArgs, { disableProxy: true })) +state.global.set('arg', decorate(scriptArgs, { disableProxy: true })) const isTTY = process.stdin.isTTY if (scriptFile === '-') { const input = fs.readFileSync(0, 'utf-8') - await lua.doString(input) + await state.doString(input) } else if (scriptFile) { - await lua.doFile(scriptFile) + await state.doFile(scriptFile) } const shouldInteractive = isTTY && (forceInteractive || (!scriptFile && !executeSnippets.length)) if (shouldInteractive) { // Bypass result verification for interactive mode const loadcode = (code) => { - lua.global.setTop(0) - return luamodule.luaL_loadstring(lua.global.address, code) === LuaReturn.Ok + state.global.setTop(0) + return lua.module.luaL_loadstring(state.global.address, code) === LuaReturn.Ok } const version = pkg.version - const luaversion = lua.global.get('_VERSION') + const luaversion = state.global.get('_VERSION') console.log(`Welcome to Wasmoon ${version} (${luaversion})`) console.log('Type Lua code and press Enter to execute. Ctrl+C to exit.\n') @@ -225,24 +224,24 @@ if (shouldInteractive) { const loaded = loadcode(`return ${line}`) || loadcode(line) if (!loaded) { // Failed to parse - const err = lua.global.getValue(-1, LuaType.String) + const err = state.global.getValue(-1, LuaType.String) console.log(err) rl.prompt() continue } - const result = luamodule.lua_pcallk(lua.global.address, 0, LUA_MULTRET, 0, 0, null) + const result = lua.module.lua_pcallk(state.global.address, 0, LUA_MULTRET, 0, 0, null) if (result === LuaReturn.Ok) { - const count = lua.global.getTop() + const count = state.global.getTop() if (count > 0) { const returnValues = [] for (let i = 1; i <= count; i++) { - returnValues.push(lua.global.indexToString(i)) + returnValues.push(state.global.indexToString(i)) } console.log(...returnValues) } } else { - console.log(lua.global.getValue(-1, LuaType.String)) + console.log(state.global.getValue(-1, LuaType.String)) } rl.prompt() @@ -251,5 +250,5 @@ if (shouldInteractive) { // If we're not interactive, and we did NOT run a file, // read from stdin until EOF. (Non-TTY or no -i, no file). const input = fs.readFileSync(0, 'utf-8') - await lua.doString(input) + await state.doString(input) } diff --git a/package.json b/package.json index 82f1c7a..746bc87 100755 --- a/package.json +++ b/package.json @@ -3,6 +3,7 @@ "version": "1.16.0", "description": "A real lua VM with JS bindings made with webassembly", "main": "./dist/index.js", + "types": "./dist/index.d.ts", "type": "module", "scripts": { "build:wasm:dev": "node utils/build-wasm dev", diff --git a/src/engine.ts b/src/engine.ts index 59ab415..440e91d 100755 --- a/src/engine.ts +++ b/src/engine.ts @@ -1,6 +1,6 @@ import { CreateEngineOptions } from './types' import Global from './global' -import type LuaWasm from './luawasm' +import type LuaModule from './module' import Thread from './thread' import createErrorType from './type-extensions/error' import createFunctionType from './type-extensions/function' @@ -14,7 +14,7 @@ export default class LuaEngine { public global: Global public constructor( - private cmodule: LuaWasm, + private module: LuaModule, { openStandardLibs = true, injectObjects = false, @@ -23,7 +23,7 @@ export default class LuaEngine { functionTimeout = undefined as number | undefined, }: CreateEngineOptions = {}, ) { - this.global = new Global(this.cmodule, traceAllocations) + this.global = new Global(this.module, traceAllocations) // Generic handlers - These may be required to be registered for additional types. this.global.registerTypeExtension(0, createTableType(this.global)) @@ -52,7 +52,7 @@ export default class LuaEngine { this.global.registerTypeExtension(4, createUserdataType(this.global)) if (openStandardLibs) { - this.cmodule.luaL_openlibs(this.global.address) + this.module.luaL_openlibs(this.global.address) } } diff --git a/src/factory.ts b/src/factory.ts deleted file mode 100755 index b3a45ad..0000000 --- a/src/factory.ts +++ /dev/null @@ -1,97 +0,0 @@ -// A rollup plugin will resolve this to the current version on package.json -import version from 'package-version' -import LuaEngine from './engine' -import LuaWasm from './luawasm' -import { CreateEngineOptions } from './types' - -/** - * Represents a factory for creating and configuring Lua engines. - */ -export default class LuaFactory { - private luaWasmPromise: Promise - - /** - * Constructs a new LuaFactory instance. - * @param opts.wasmFile - Custom URI for the Lua WebAssembly module. - * @param opts.env - Environment variables for the Lua engine. - * @param opts.stdin - Standard input for the Lua engine. - * @param opts.fs - File system that should be used for the Lua engine. - * @param opts.stdout - Standard output for the Lua engine. - * @param opts.stderr - Standard error for the Lua engine. - */ - public constructor(opts: Parameters[0] = {}) { - if (opts.wasmFile === undefined) { - const isBrowser = - (typeof window === 'object' && typeof window.document !== 'undefined') || - (typeof self === 'object' && self?.constructor?.name === 'DedicatedWorkerGlobalScope') - - if (isBrowser) { - opts.wasmFile = `https://unpkg.com/wasmoon@${version}/dist/glue.wasm` - } - } - - this.luaWasmPromise = LuaWasm.initialize(opts) - } - - /** - * Mounts a file in the Lua environment asynchronously. - * @param path - Path to the file in the Lua environment. - * @param content - Content of the file to be mounted. - * @returns - A Promise that resolves once the file is mounted. - */ - public async mountFile(path: string, content: string | ArrayBufferView): Promise { - this.mountFileSync(await this.getLuaModule(), path, content) - } - - /** - * Mounts a file in the Lua environment synchronously. - * @param luaWasm - Lua WebAssembly module. - * @param path - Path to the file in the Lua environment. - * @param content - Content of the file to be mounted. - */ - public mountFileSync(luaWasm: LuaWasm, path: string, content: string | ArrayBufferView): void { - const fileSep = path.lastIndexOf('/') - const file = path.substring(fileSep + 1) - const body = path.substring(0, path.length - file.length - 1) - - if (body.length > 0) { - const parts = body.split('/').reverse() - let parent = '' - - while (parts.length) { - const part = parts.pop() - if (!part) { - continue - } - - const current = `${parent}/${part}` - try { - luaWasm.module.FS.mkdir(current) - } catch { - // ignore EEXIST - } - - parent = current - } - } - - luaWasm.module.FS.writeFile(path, content) - } - - /** - * Creates a Lua engine with the specified options. - * @param [options] - Configuration options for the Lua engine. - * @returns - A Promise that resolves to a new LuaEngine instance. - */ - public async createEngine(options: CreateEngineOptions = {}): Promise { - return new LuaEngine(await this.getLuaModule(), options) - } - - /** - * Gets the Lua WebAssembly module. - * @returns - A Promise that resolves to the Lua WebAssembly module. - */ - public async getLuaModule(): Promise { - return this.luaWasmPromise - } -} diff --git a/src/global.ts b/src/global.ts index 0fbef7a..fd28272 100755 --- a/src/global.ts +++ b/src/global.ts @@ -1,4 +1,4 @@ -import type LuaWasm from './luawasm' +import type LuaModule from './module' import Thread from './thread' import LuaTypeExtension from './type-extension' import { LuaLibraries, LuaType } from './types' @@ -17,18 +17,18 @@ export default class Global extends Thread { /** * Constructs a new Global instance. - * @param cmodule - The Lua WebAssembly module. + * @param cmodule - The Lua module. * @param shouldTraceAllocations - Whether to trace memory allocations. */ - public constructor(cmodule: LuaWasm, shouldTraceAllocations: boolean) { + public constructor(cmodule: LuaModule, shouldTraceAllocations: boolean) { if (shouldTraceAllocations) { const memoryStats: LuaMemoryStats = { memoryUsed: 0 } - const allocatorFunctionPointer = cmodule.module.addFunction( + const allocatorFunctionPointer = cmodule._emscripten.addFunction( (_userData: number, pointer: number, oldSize: number, newSize: number): number => { if (newSize === 0) { if (pointer) { memoryStats.memoryUsed -= oldSize - cmodule.module._free(pointer) + cmodule._emscripten._free(pointer) } return 0 } @@ -40,7 +40,7 @@ export default class Global extends Thread { return 0 } - const reallocated = cmodule.module._realloc(pointer, newSize) + const reallocated = cmodule._emscripten._realloc(pointer, newSize) if (reallocated) { memoryStats.memoryUsed = endMemory } @@ -51,7 +51,7 @@ export default class Global extends Thread { const address = cmodule.lua_newstate(allocatorFunctionPointer, null) if (!address) { - cmodule.module.removeFunction(allocatorFunctionPointer) + cmodule._emscripten.removeFunction(allocatorFunctionPointer) throw new Error('lua_newstate returned a null pointer') } super(cmodule, [], address) @@ -84,7 +84,7 @@ export default class Global extends Thread { this.lua.lua_close(this.address) if (this.allocatorFunctionPointer) { - this.lua.module.removeFunction(this.allocatorFunctionPointer) + this.lua._emscripten.removeFunction(this.allocatorFunctionPointer) } for (const wrapper of this.typeExtensions) { diff --git a/src/index.ts b/src/index.ts index 243c251..11cb4a6 100755 --- a/src/index.ts +++ b/src/index.ts @@ -1,5 +1,5 @@ export { default as LuaEngine } from './engine' -export { default as LuaFactory } from './factory' +export { default as Lua } from './lua' export { default as LuaGlobal } from './global' export { default as LuaMultiReturn } from './multireturn' export { default as LuaRawResult } from './raw-result' @@ -7,9 +7,12 @@ export { default as LuaThread } from './thread' // Export the underlying bindings to allow users to just // use the bindings rather than the wrappers. export { decorate, Decoration } from './decoration' -export { default as LuaWasm } from './luawasm' +export { default as LuaModule } from './module' export { default as LuaTypeExtension } from './type-extension' export { decorateFunction } from './type-extensions/function' export { decorateProxy } from './type-extensions/proxy' export { decorateUserdata } from './type-extensions/userdata' export * from './types' + +import Lua from './lua' +export default Lua diff --git a/src/lua.ts b/src/lua.ts new file mode 100755 index 0000000..ac799de --- /dev/null +++ b/src/lua.ts @@ -0,0 +1,46 @@ +import LuaModule from './module' +import LuaEngine from './engine' +import { CreateEngineOptions } from './types' + +/** + * Represents a factory for creating and configuring Lua engines. + */ +export default class Lua { + /** + * Constructs a new LuaFactory instance. + * @param opts.wasmFile - Custom URI for the Lua WebAssembly module. + * @param opts.env - Environment variables for the Lua engine. + * @param opts.stdin - Standard input for the Lua engine. + * @param opts.fs - File system that should be used for the Lua engine. + * @param opts.stdout - Standard output for the Lua engine. + * @param opts.stderr - Standard error for the Lua engine. + */ + public static async load(luaModuleOpts: Parameters[0] = {}): Promise { + return new Lua(await LuaModule.initialize(luaModuleOpts)) + } + + public constructor(public readonly module: LuaModule) {} + + public createState(stateOpts: CreateEngineOptions = {}): LuaEngine { + return new LuaEngine(this.module, stateOpts) + } + + /** + * Mounts a file in the Lua environment synchronously. + * @param path - Path to the file in the Lua environment. + * @param content - Content of the file to be mounted. + */ + public mountFile(path: string, content: string | ArrayBufferView): void { + const dirname = this.module._emscripten.PATH.dirname(path) + this.module._emscripten.FS.mkdirTree(dirname) + this.module._emscripten.FS.writeFile(path, content) + } + + public get filesystem(): typeof this.module._emscripten.FS { + return this.module._emscripten.FS + } + + public get path(): typeof this.module._emscripten.PATH { + return this.module._emscripten.PATH + } +} diff --git a/src/luawasm.ts b/src/module.ts similarity index 95% rename from src/luawasm.ts rename to src/module.ts index 789373d..1f0d8ad 100755 --- a/src/luawasm.ts +++ b/src/module.ts @@ -1,5 +1,7 @@ import initWasmModule from '../build/glue.js' -import { LUA_REGISTRYINDEX, LuaReturn, LuaState, LuaType } from './types' +import { LUA_REGISTRYINDEX, LuaReturn, LuaState, LuaType } from './types.js' +// A rolldown plugin will resolve this to the current version on package.json +import version from 'package-version' type EnvironmentVariables = Record @@ -9,7 +11,16 @@ interface LuaEmscriptenModule extends EmscriptenModule { removeFunction: typeof removeFunction setValue: typeof setValue getValue: typeof getValue - FS: typeof FS + FS: typeof FS & { + mkdirTree: (path: string) => void + filesystems: { + NODEFS: Emscripten.FileSystemType + MEMFS: Emscripten.FileSystemType + } + } + PATH: { + dirname: (typeof import('node:path'))['dirname'] + } stringToNewUTF8: typeof allocateUTF8 lengthBytesUTF8: typeof lengthBytesUTF8 stringToUTF8: typeof stringToUTF8 @@ -24,7 +35,7 @@ interface ReferenceMetadata { refCount: number } -export default class LuaWasm { +export default class LuaModule { public static async initialize(opts: { wasmFile?: string env?: EnvironmentVariables @@ -32,9 +43,17 @@ export default class LuaWasm { stdin?: () => string stdout?: (content: string) => void stderr?: (content: string) => void - }): Promise { - const fs = opts.fs === 'node' && typeof process !== 'undefined' ? await import('node:fs') : null - const child_process = opts.fs === 'node' && typeof process !== 'undefined' ? await import('node:child_process') : null + }): Promise { + const isBrowser = + (typeof window === 'object' && typeof window.document !== 'undefined') || + (typeof self === 'object' && self?.constructor?.name === 'DedicatedWorkerGlobalScope') + + if (opts.wasmFile === undefined && isBrowser) { + opts.wasmFile = `https://unpkg.com/wasmoon@${version}/dist/glue.wasm` + } + + const fs = !isBrowser && opts.fs === 'node' && typeof process !== 'undefined' ? await import('node:fs') : null + const child_process = !isBrowser && opts.fs === 'node' && typeof process !== 'undefined' ? await import('node:child_process') : null const module: LuaEmscriptenModule = await initWasmModule({ print: opts.stdout, @@ -75,7 +94,7 @@ export default class LuaWasm { for (const dir of rootdirs) { try { - const moduleFS = initializedModule.FS as any // emscripten FS module is not correctly typed + const moduleFS = initializedModule.FS moduleFS.mkdirTree(dir) moduleFS.mount(moduleFS.filesystems.NODEFS, { root: dir }, dir) } catch { @@ -117,10 +136,10 @@ export default class LuaWasm { } }, }) - return new LuaWasm(module) + return new LuaModule(module) } - public module: LuaEmscriptenModule + public _emscripten: LuaEmscriptenModule public luaL_checkversion_: (L: LuaState, ver: number, sz: number) => void public luaL_getmetafield: (L: LuaState, obj: number, e: string | null) => LuaType @@ -283,7 +302,7 @@ export default class LuaWasm { private lastRefIndex?: number public constructor(module: LuaEmscriptenModule) { - this.module = module + this._emscripten = module this.luaL_checkversion_ = this.cwrap('luaL_checkversion_', null, ['number', 'number', 'number']) this.luaL_getmetafield = this.cwrap('luaL_getmetafield', 'number', ['number', 'number', 'string']) @@ -521,7 +540,7 @@ export default class LuaWasm { const hasStringOrNumber = argTypes.some((argType) => argType === 'string|number') if (!hasStringOrNumber) { return (...args: any[]) => - this.module.ccall(name, returnType, argTypes as Emscripten.JSType[], args as Emscripten.TypeCompatibleWithC[]) + this._emscripten.ccall(name, returnType, argTypes as Emscripten.JSType[], args as Emscripten.TypeCompatibleWithC[]) } return (...args: any[]) => { @@ -533,7 +552,7 @@ export default class LuaWasm { } else { // because it will be freed later, this can only be used on functions that lua internally copies the string if (args[i]?.length > 1024) { - const bufferPointer = this.module.stringToNewUTF8(args[i] as string) + const bufferPointer = this._emscripten.stringToNewUTF8(args[i] as string) args[i] = bufferPointer pointersToBeFreed.push(bufferPointer) return 'number' @@ -546,10 +565,10 @@ export default class LuaWasm { }) try { - return this.module.ccall(name, returnType, resolvedArgTypes, args as Emscripten.TypeCompatibleWithC[]) + return this._emscripten.ccall(name, returnType, resolvedArgTypes, args as Emscripten.TypeCompatibleWithC[]) } finally { for (const pointer of pointersToBeFreed) { - this.module._free(pointer) + this._emscripten._free(pointer) } } } diff --git a/src/thread.ts b/src/thread.ts index f02ee49..bd9d832 100755 --- a/src/thread.ts +++ b/src/thread.ts @@ -1,5 +1,5 @@ import { Decoration } from './decoration' -import type LuaWasm from './luawasm' +import type LuaModule from './module' import MultiReturn from './multireturn' import { Pointer } from './pointer' import LuaTypeExtension from './type-extension' @@ -26,14 +26,14 @@ const INSTRUCTION_HOOK_COUNT = 1000 export default class Thread { public readonly address: LuaState - public readonly lua: LuaWasm + public readonly lua: LuaModule protected readonly typeExtensions: OrderedExtension[] private closed = false private hookFunctionPointer: number | undefined private timeout?: number private readonly parent?: Thread - public constructor(lua: LuaWasm, typeExtensions: OrderedExtension[], address: number, parent?: Thread) { + public constructor(lua: LuaModule, typeExtensions: OrderedExtension[], address: number, parent?: Thread) { this.lua = lua this.typeExtensions = typeExtensions this.address = address @@ -53,14 +53,14 @@ export default class Thread { } public loadString(luaCode: string, name?: string): void { - const size = this.lua.module.lengthBytesUTF8(luaCode) + const size = this.lua._emscripten.lengthBytesUTF8(luaCode) const pointerSize = size + 1 - const bufferPointer = this.lua.module._malloc(pointerSize) + const bufferPointer = this.lua._emscripten._malloc(pointerSize) try { - this.lua.module.stringToUTF8(luaCode, bufferPointer, pointerSize) + this.lua._emscripten.stringToUTF8(luaCode, bufferPointer, pointerSize) this.assertOk(this.lua.luaL_loadbufferx(this.address, bufferPointer, size, name ?? bufferPointer, null)) } finally { - this.lua.module._free(bufferPointer) + this.lua._emscripten._free(bufferPointer) } } @@ -69,16 +69,16 @@ export default class Thread { } public resume(argCount = 0): LuaResumeResult { - const dataPointer = this.lua.module._malloc(PointerSize) + const dataPointer = this.lua._emscripten._malloc(PointerSize) try { - this.lua.module.setValue(dataPointer, 0, 'i32') + this.lua._emscripten.setValue(dataPointer, 0, 'i32') const luaResult = this.lua.lua_resume(this.address, null, argCount, dataPointer) return { result: luaResult, - resultCount: this.lua.module.getValue(dataPointer, 'i32'), + resultCount: this.lua._emscripten.getValue(dataPointer, 'i32'), } } finally { - this.lua.module._free(dataPointer) + this.lua._emscripten._free(dataPointer) } } @@ -312,7 +312,7 @@ export default class Thread { } if (this.hookFunctionPointer) { - this.lua.module.removeFunction(this.hookFunctionPointer) + this.lua._emscripten.removeFunction(this.hookFunctionPointer) } this.closed = true @@ -322,7 +322,7 @@ export default class Thread { public setTimeout(timeout: number | undefined): void { if (timeout && timeout > 0) { if (!this.hookFunctionPointer) { - this.hookFunctionPointer = this.lua.module.addFunction((): void => { + this.hookFunctionPointer = this.lua._emscripten.addFunction((): void => { if (Date.now() > timeout) { this.pushValue(new LuaTimeoutError(`thread timeout exceeded`)) this.lua.lua_error(this.address) diff --git a/src/type-extension.ts b/src/type-extension.ts index 4543cd3..e4929cc 100644 --- a/src/type-extension.ts +++ b/src/type-extension.ts @@ -25,7 +25,7 @@ export default abstract class LuaTypeExtension { public constructor(thread: Global, injectObject: boolean) { super(thread, 'js_error') - this.gcPointer = thread.lua.module.addFunction((functionStateAddress: LuaState) => { + this.gcPointer = thread.lua._emscripten.addFunction((functionStateAddress: LuaState) => { // Throws a lua error which does a jump if it does not match. const userDataPointer = thread.lua.luaL_checkudata(functionStateAddress, 1, this.name) - const referencePointer = thread.lua.module.getValue(userDataPointer, '*') + const referencePointer = thread.lua._emscripten.getValue(userDataPointer, '*') thread.lua.unref(referencePointer) return LuaReturn.Ok @@ -72,7 +72,7 @@ class ErrorTypeExtension extends TypeExtension { } public close(): void { - this.thread.lua.module.removeFunction(this.gcPointer) + this.thread.lua._emscripten.removeFunction(this.gcPointer) } } diff --git a/src/type-extensions/function.ts b/src/type-extensions/function.ts index 1972dc3..28b5283 100644 --- a/src/type-extensions/function.ts +++ b/src/type-extensions/function.ts @@ -50,12 +50,12 @@ class FunctionTypeExtension extends TypeExtension { + this.gcPointer = thread.lua._emscripten.addFunction((calledL: LuaState) => { // Throws a lua error which does a jump if it does not match. thread.lua.luaL_checkudata(calledL, 1, this.name) const userDataPointer = thread.lua.luaL_checkudata(calledL, 1, this.name) - const referencePointer = thread.lua.module.getValue(userDataPointer, '*') + const referencePointer = thread.lua._emscripten.getValue(userDataPointer, '*') thread.lua.unref(referencePointer) return LuaReturn.Ok @@ -74,11 +74,11 @@ class FunctionTypeExtension extends TypeExtension { + this.functionWrapper = thread.lua._emscripten.addFunction((calledL: LuaState) => { const calledThread = thread.stateToThread(calledL) const refUserdata = thread.lua.luaL_checkudata(calledL, thread.lua.lua_upvalueindex(1), this.name) - const refPointer = thread.lua.module.getValue(refUserdata, '*') + const refPointer = thread.lua._emscripten.getValue(refUserdata, '*') const { target, options } = thread.lua.getRef(refPointer) as Decoration const argsQuantity = calledThread.getTop() @@ -127,8 +127,8 @@ class FunctionTypeExtension extends TypeExtension { public constructor(thread: Global) { super(thread, 'js_null') - this.gcPointer = thread.lua.module.addFunction((functionStateAddress: LuaState) => { + this.gcPointer = thread.lua._emscripten.addFunction((functionStateAddress: LuaState) => { // Throws a lua error which does a jump if it does not match. const userDataPointer = thread.lua.luaL_checkudata(functionStateAddress, 1, this.name) - const referencePointer = thread.lua.module.getValue(userDataPointer, '*') + const referencePointer = thread.lua._emscripten.getValue(userDataPointer, '*') thread.lua.unref(referencePointer) return LuaReturn.Ok @@ -69,7 +69,7 @@ class NullTypeExtension extends TypeExtension { } public close(): void { - this.thread.lua.module.removeFunction(this.gcPointer) + this.thread.lua._emscripten.removeFunction(this.gcPointer) } } diff --git a/src/type-extensions/promise.ts b/src/type-extensions/promise.ts index 0aa2c51..ea8da1b 100644 --- a/src/type-extensions/promise.ts +++ b/src/type-extensions/promise.ts @@ -14,10 +14,10 @@ class PromiseTypeExtension extends TypeExtension> { public constructor(thread: Global, injectObject: boolean) { super(thread, 'js_promise') - this.gcPointer = thread.lua.module.addFunction((functionStateAddress: LuaState) => { + this.gcPointer = thread.lua._emscripten.addFunction((functionStateAddress: LuaState) => { // Throws a lua error which does a jump if it does not match. const userDataPointer = thread.lua.luaL_checkudata(functionStateAddress, 1, this.name) - const referencePointer = thread.lua.module.getValue(userDataPointer, '*') + const referencePointer = thread.lua._emscripten.getValue(userDataPointer, '*') thread.lua.unref(referencePointer) return LuaReturn.Ok @@ -63,7 +63,7 @@ class PromiseTypeExtension extends TypeExtension> { promiseResult = { status: 'rejected', value: err } }) - const continuance = this.thread.lua.module.addFunction((continuanceState: LuaState) => { + const continuance = this.thread.lua._emscripten.addFunction((continuanceState: LuaState) => { // If this yield has been called from within a coroutine and so manually resumed // then there may not yet be any results. In that case yield again. if (!promiseResult) { @@ -75,7 +75,7 @@ class PromiseTypeExtension extends TypeExtension> { return thread.lua.lua_yieldk(functionThread.address, 0, 0, continuance) } - this.thread.lua.module.removeFunction(continuance) + this.thread.lua._emscripten.removeFunction(continuance) const continuanceThread = thread.stateToThread(continuanceState) @@ -128,7 +128,7 @@ class PromiseTypeExtension extends TypeExtension> { } public close(): void { - this.thread.lua.module.removeFunction(this.gcPointer) + this.thread.lua._emscripten.removeFunction(this.gcPointer) } public pushValue(thread: Thread, decoration: Decoration>): boolean { diff --git a/src/type-extensions/proxy.ts b/src/type-extensions/proxy.ts index 9be9b1d..9d4d76b 100644 --- a/src/type-extensions/proxy.ts +++ b/src/type-extensions/proxy.ts @@ -22,10 +22,10 @@ class ProxyTypeExtension extends TypeExtension { public constructor(thread: Global) { super(thread, 'js_proxy') - this.gcPointer = thread.lua.module.addFunction((functionStateAddress: LuaState) => { + this.gcPointer = thread.lua._emscripten.addFunction((functionStateAddress: LuaState) => { // Throws a lua error which does a jump if it does not match. const userDataPointer = thread.lua.luaL_checkudata(functionStateAddress, 1, this.name) - const referencePointer = thread.lua.module.getValue(userDataPointer, '*') + const referencePointer = thread.lua._emscripten.getValue(userDataPointer, '*') thread.lua.unref(referencePointer) return LuaReturn.Ok @@ -131,7 +131,7 @@ class ProxyTypeExtension extends TypeExtension { public getValue(thread: Thread, index: number): any { const refUserdata = thread.lua.lua_touserdata(thread.address, index) - const referencePointer = thread.lua.module.getValue(refUserdata, '*') + const referencePointer = thread.lua._emscripten.getValue(refUserdata, '*') return thread.lua.getRef(referencePointer) } @@ -169,7 +169,7 @@ class ProxyTypeExtension extends TypeExtension { } public close(): void { - this.thread.lua.module.removeFunction(this.gcPointer) + this.thread.lua._emscripten.removeFunction(this.gcPointer) } } diff --git a/src/type-extensions/userdata.ts b/src/type-extensions/userdata.ts index f09ae7e..89a3811 100644 --- a/src/type-extensions/userdata.ts +++ b/src/type-extensions/userdata.ts @@ -18,10 +18,10 @@ class UserdataTypeExtension extends TypeExtension { + this.gcPointer = thread.lua._emscripten.addFunction((functionStateAddress: LuaState) => { // Throws a lua error which does a jump if it does not match. const userDataPointer = thread.lua.luaL_checkudata(functionStateAddress, 1, this.name) - const referencePointer = thread.lua.module.getValue(userDataPointer, '*') + const referencePointer = thread.lua._emscripten.getValue(userDataPointer, '*') thread.lua.unref(referencePointer) return LuaReturn.Ok @@ -49,7 +49,7 @@ class UserdataTypeExtension extends TypeExtension { +describe('State', () => { let intervals = [] const setIntervalSafe = (callback, interval) => { intervals.push(setInterval(() => callback(), interval)) @@ -33,32 +33,32 @@ describe('Engine', () => { }) it('receive lua table on JS function should succeed', async () => { - const engine = await getEngine() - engine.global.set('stringify', (table) => { + const state = await getState() + state.global.set('stringify', (table) => { return JSON.stringify(table) }) - await engine.doString('value = stringify({ test = 1 })') + await state.doString('value = stringify({ test = 1 })') - expect(engine.global.get('value')).to.be.equal(JSON.stringify({ test: 1 })) + expect(state.global.get('value')).to.be.equal(JSON.stringify({ test: 1 })) }) it('get a global table inside a JS function called by lua should succeed', async () => { - const engine = await getEngine() - engine.global.set('t', { test: 1 }) - engine.global.set('test', () => { - return engine.global.get('t') + const state = await getState() + state.global.set('t', { test: 1 }) + state.global.set('test', () => { + return state.global.get('t') }) - const value = await engine.doString('return test(2)') + const value = await state.doString('return test(2)') expect(value).to.be.eql({ test: 1 }) }) it('receive JS object on lua should succeed', async () => { - const engine = await getEngine() + const state = await getState() - engine.global.set('test', () => { + state.global.set('test', () => { return { aaaa: 1, bbb: 'hey', @@ -67,27 +67,27 @@ describe('Engine', () => { }, } }) - const value = await engine.doString('return test().test()') + const value = await state.doString('return test().test()') expect(value).to.be.equal(22) }) it('receive JS object with circular references on lua should succeed', async () => { - const engine = await getEngine() + const state = await getState() const obj = { hello: 'world', } obj.self = obj - engine.global.set('obj', obj) + state.global.set('obj', obj) - const value = await engine.doString('return obj.self.self.self.hello') + const value = await state.doString('return obj.self.self.self.hello') expect(value).to.be.equal('world') }) it('receive Lua object with circular references on JS should succeed', async () => { - const engine = await getEngine() - const value = await engine.doString(` + const state = await getState() + const value = await state.doString(` local obj1 = { hello = 'world', } @@ -122,8 +122,8 @@ describe('Engine', () => { }) it('receive lua array with circular references on JS should succeed', async () => { - const engine = await getEngine() - const value = await engine.doString(` + const state = await getState() + const value = await state.doString(` obj = { "hello", "world" @@ -138,7 +138,7 @@ describe('Engine', () => { }) it('receive JS object with multiple circular references on lua should succeed', async () => { - const engine = await getEngine() + const state = await getState() const obj1 = { hello: 'world', } @@ -147,45 +147,45 @@ describe('Engine', () => { hello: 'everybody', } obj2.self = obj2 - engine.global.set('obj', { obj1, obj2 }) + state.global.set('obj', { obj1, obj2 }) - await engine.doString(` + await state.doString(` assert(obj.obj1.self.self.hello == "world") assert(obj.obj2.self.self.hello == "everybody") `) }) it('receive JS object with null prototype on lua should succeed', async () => { - const engine = await getEngine() + const state = await getState() const obj = Object.create(null) obj.hello = 'world' - engine.global.set('obj', obj) + state.global.set('obj', obj) - const value = await engine.doString(`return obj.hello`) + const value = await state.doString(`return obj.hello`) expect(value).to.be.equal('world') }) it('a lua error should throw on JS', async () => { - const engine = await getEngine() + const state = await getState() - await expect(engine.doString(`x -`)).to.eventually.be.rejected + await expect(state.doString(`x -`)).to.eventually.be.rejected }) it('call a lua function from JS should succeed', async () => { - const engine = await getEngine() + const state = await getState() - await engine.doString(`function sum(x, y) return x + y end`) - const sum = engine.global.get('sum') + await state.doString(`function sum(x, y) return x + y end`) + const sum = state.global.get('sum') expect(sum(10, 50)).to.be.equal(60) }) it('scheduled lua calls should succeed', async () => { - const engine = await getEngine() - engine.global.set('setInterval', setIntervalSafe) + const state = await getState() + state.global.set('setInterval', setIntervalSafe) - await engine.doString(` + await state.doString(` test = "" setInterval(function() test = test .. "i" @@ -193,33 +193,33 @@ describe('Engine', () => { `) await setTimeout(20) - const test = engine.global.get('test') + const test = state.global.get('test') expect(test).length.above(3) expect(test).length.below(21) expect(test).to.be.equal(''.padEnd(test.length, 'i')) }) it('scheduled lua calls should fail silently if invalid', async () => { - const engine = await getEngine() - engine.global.set('setInterval', setIntervalSafe) + const state = await getState() + state.global.set('setInterval', setIntervalSafe) const originalConsoleWarn = console.warn console.warn = mock.fn() - await engine.doString(` + await state.doString(` test = 0 setInterval(function() test = test + 1 end, 5) `) - engine.global.close() + state.global.close() await setTimeout(5 + 5) console.warn = originalConsoleWarn }) it('call lua function from JS passing an array argument should succeed', async () => { - const engine = await getEngine() + const state = await getState() - const sum = await engine.doString(` + const sum = await state.doString(` return function(arr) local sum = 0 for k, v in ipairs(arr) do @@ -233,24 +233,24 @@ describe('Engine', () => { }) it('call a global function with multiple returns should succeed', async () => { - const engine = await getEngine() + const state = await getState() - await engine.doString(` + await state.doString(` function f(x,y) return 1,x,y,"Hello World",{},function() end end `) - const returns = engine.global.call('f', 10, 25) + const returns = state.global.call('f', 10, 25) expect(returns).to.have.length(6) expect(returns.slice(0, -1)).to.eql([1, 10, 25, 'Hello World', {}]) expect(returns.at(-1)).to.be.a('function') }) it('get a lua thread should succeed', async () => { - const engine = await getEngine() + const state = await getState() - const thread = await engine.doString(` + const thread = await state.doString(` return coroutine.create(function() print("hey") end) @@ -261,15 +261,15 @@ describe('Engine', () => { }) it('a JS error should pause lua execution', async () => { - const engine = await getEngine() + const state = await getState() const check = mock.fn() - engine.global.set('check', check) - engine.global.set('throw', () => { + state.global.set('check', check) + state.global.set('throw', () => { throw new Error('expected error') }) await expect( - engine.doString(` + state.doString(` throw() check() `), @@ -278,14 +278,14 @@ describe('Engine', () => { }) it('catch a JS error with pcall should succeed', async () => { - const engine = await getEngine() + const state = await getState() const check = mock.fn() - engine.global.set('check', check) - engine.global.set('throw', () => { + state.global.set('check', check) + state.global.set('throw', () => { throw new Error('expected error') }) - await engine.doString(` + await state.doString(` local success, err = pcall(throw) assert(success == false) assert(tostring(err) == "Error: expected error") @@ -296,11 +296,11 @@ describe('Engine', () => { }) it('call a JS function in a different thread should succeed', async () => { - const engine = await getEngine() + const state = await getState() const sum = mock.fn((x, y) => x + y) - engine.global.set('sum', sum) + state.global.set('sum', sum) - await engine.doString(` + await state.doString(` coroutine.resume(coroutine.create(function() sum(10, 20) end)) @@ -311,8 +311,8 @@ describe('Engine', () => { }) it('get callable table as function should succeed', async () => { - const engine = await getEngine() - await engine.doString(` + const state = await getState() + await state.doString(` _G['sum'] = setmetatable({}, { __call = function(self, x, y) return x + y @@ -320,15 +320,15 @@ describe('Engine', () => { }) `) - engine.global.lua.lua_getglobal(engine.global.address, 'sum') - const sum = engine.global.getValue(-1, LuaType.Function) + state.global.lua.lua_getglobal(state.global.address, 'sum') + const sum = state.global.getValue(-1, LuaType.Function) expect(sum(10, 30)).to.be.equal(40) }) it('lua_resume with yield succeeds', async () => { - const engine = await getEngine() - const thread = engine.global.newThread() + const state = await getState() + const thread = state.global.newThread() thread.loadString(` local yieldRes = coroutine.yield(10) return yieldRes @@ -353,34 +353,34 @@ describe('Engine', () => { }) it('get memory with allocation tracing should succeeds', async () => { - const engine = await getEngine({ traceAllocations: true }) - expect(engine.global.getMemoryUsed()).to.be.greaterThan(0) + const state = await getState({ traceAllocations: true }) + expect(state.global.getMemoryUsed()).to.be.greaterThan(0) }) it('get memory should return correct', async () => { - const engine = await getEngine({ traceAllocations: true }) + const state = await getState({ traceAllocations: true }) - const totalMemory = await engine.doString(` + const totalMemory = await state.doString(` collectgarbage() local x = 10 local batata = { dawdwa = 1 } return collectgarbage('count') * 1024 `) - expect(engine.global.getMemoryUsed()).to.be.equal(totalMemory) + expect(state.global.getMemoryUsed()).to.be.equal(totalMemory) }) it('get memory without tracing should throw', async () => { - const engine = await getEngine({ traceAllocations: false }) + const state = await getState({ traceAllocations: false }) - expect(() => engine.global.getMemoryUsed()).to.throw() + expect(() => state.global.getMemoryUsed()).to.throw() }) it('limit memory use causes program loading failure succeeds', async () => { - const engine = await getEngine({ traceAllocations: true }) - engine.global.setMemoryMax(engine.global.getMemoryUsed()) + const state = await getState({ traceAllocations: true }) + state.global.setMemoryMax(state.global.getMemoryUsed()) expect(() => { - engine.global.loadString(` + state.global.loadString(` local a = 10 local b = 20 return a + b @@ -388,8 +388,8 @@ describe('Engine', () => { }).to.throw('not enough memory') // Remove the limit and retry - engine.global.setMemoryMax(undefined) - engine.global.loadString(` + state.global.setMemoryMax(undefined) + state.global.loadString(` local a = 10 local b = 20 return a + b @@ -397,35 +397,35 @@ describe('Engine', () => { }) it('limit memory use causes program runtime failure succeeds', async () => { - const engine = await getEngine({ traceAllocations: true }) - engine.global.loadString(` + const state = await getState({ traceAllocations: true }) + state.global.loadString(` local tab = {} for i = 1, 50, 1 do tab[i] = i end `) - engine.global.setMemoryMax(engine.global.getMemoryUsed()) + state.global.setMemoryMax(state.global.getMemoryUsed()) - await expect(engine.global.run()).to.eventually.be.rejectedWith('not enough memory') + await expect(state.global.run()).to.eventually.be.rejectedWith('not enough memory') }) it('table supported circular dependencies', async () => { - const engine = await getEngine() + const state = await getState() const a = { name: 'a' } const b = { name: 'b' } b.a = a a.b = b - engine.global.pushValue(a) - const res = engine.global.getValue(-1) + state.global.pushValue(a) + const res = state.global.getValue(-1) expect(res.b.a).to.be.eql(res) }) it('wrap a js object (with metatable)', async () => { - const engine = await getEngine() - engine.global.set('TestClass', { + const state = await getState() + state.global.set('TestClass', { create: (name) => { return decorate( { @@ -446,7 +446,7 @@ describe('Engine', () => { }, }) - const res = await engine.doString(` + const res = await state.doString(` local instance = TestClass.create("demo name") return instance.name `) @@ -454,11 +454,11 @@ describe('Engine', () => { }) it('wrap a js object using proxy', async () => { - const engine = await getEngine() - engine.global.set('TestClass', { + const state = await getState() + state.global.set('TestClass', { create: (name) => new TestClass(name), }) - const res = await engine.doString(` + const res = await state.doString(` local instance = TestClass.create("demo name 2") return instance:getName() `) @@ -466,11 +466,11 @@ describe('Engine', () => { }) it('wrap a js object using proxy and apply metatable in lua', async () => { - const engine = await getEngine() - engine.global.set('TestClass', { + const state = await getState() + state.global.set('TestClass', { create: (name) => new TestClass(name), }) - const res = await engine.doString(` + const res = await state.doString(` local instance = TestClass.create("demo name 2") -- Based in the simple lua classes tutotial @@ -495,10 +495,10 @@ describe('Engine', () => { }) it('classes should be a userdata when proxied', async () => { - const engine = await getEngine() - engine.global.set('obj', { TestClass }) + const state = await getState() + state.global.set('obj', { TestClass }) - const testClass = await engine.doString(` + const testClass = await state.doString(` return obj.TestClass `) @@ -506,27 +506,27 @@ describe('Engine', () => { }) it('timeout blocking lua program', async () => { - const engine = await getEngine() - engine.global.loadString(` + const state = await getState() + state.global.loadString(` local i = 0 while true do i = i + 1 end `) - await expect(engine.global.run(0, { timeout: 5 })).eventually.to.be.rejectedWith('thread timeout exceeded') + await expect(state.global.run(0, { timeout: 5 })).eventually.to.be.rejectedWith('thread timeout exceeded') }) it('overwrite lib function', async () => { - const engine = await getEngine() + const state = await getState() let output = '' - engine.global.getTable(LuaLibraries.Base, (index) => { - engine.global.setField(index, 'print', (val) => { + state.global.getTable(LuaLibraries.Base, (index) => { + state.global.setField(index, 'print', (val) => { // Not a proper print implementation. output += `${val}\n` }) }) - await engine.doString(` + await state.doString(` print("hello") print("world") `) @@ -535,28 +535,28 @@ describe('Engine', () => { }) it('inject a userdata with a metatable should succeed', async () => { - const engine = await getEngine() + const state = await getState() const obj = decorate( {}, { metatable: { __index: (_, k) => `Hello ${k}!` }, }, ) - engine.global.set('obj', obj) + state.global.set('obj', obj) - const res = await engine.doString('return obj.World') + const res = await state.doString('return obj.World') expect(res).to.be.equal('Hello World!') }) it('a userdata should be collected', async () => { - const engine = await getEngine() + const state = await getState() const obj = {} - engine.global.set('obj', obj) - const refIndex = engine.global.lua.getLastRefIndex() - const oldRef = engine.global.lua.getRef(refIndex) + state.global.set('obj', obj) + const refIndex = state.global.lua.getLastRefIndex() + const oldRef = state.global.lua.getRef(refIndex) - await engine.doString(` + await state.doString(` local weaktable = {} setmetatable(weaktable, { __mode = "v" }) table.insert(weaktable, obj) @@ -566,43 +566,43 @@ describe('Engine', () => { `) expect(oldRef).to.be.equal(obj) - const newRef = engine.global.lua.getRef(refIndex) + const newRef = state.global.lua.getRef(refIndex) expect(newRef).to.be.equal(undefined) }) it('environment variables should be set', async () => { - const factory = getFactory({ TEST: 'true' }) - const engine = await factory.createEngine() + const lua = await getLua({ TEST: 'true' }) + const state = lua.createState() - const testEnvVar = await engine.doString(`return os.getenv('TEST')`) + const testEnvVar = await state.doString(`return os.getenv('TEST')`) expect(testEnvVar).to.be.equal('true') }) it('static methods should be callable on classes', async () => { - const engine = await getEngine() - engine.global.set('TestClass', TestClass) + const state = await getState() + state.global.set('TestClass', TestClass) - const testHello = await engine.doString(`return TestClass.hello()`) + const testHello = await state.doString(`return TestClass.hello()`) expect(testHello).to.be.equal('world') }) it('should be possible to access function properties', async () => { - const engine = await getEngine() + const state = await getState() const testFunction = () => undefined testFunction.hello = 'world' - engine.global.set('TestFunction', decorateProxy(testFunction, { proxy: true })) + state.global.set('TestFunction', decorateProxy(testFunction, { proxy: true })) - const testHello = await engine.doString(`return TestFunction.hello`) + const testHello = await state.doString(`return TestFunction.hello`) expect(testHello).to.be.equal('world') }) it('throw error includes stack trace', async () => { - const engine = await getEngine() + const state = await getState() try { - await engine.doString(` + await state.doString(` local function a() error("function a threw error") end @@ -622,12 +622,12 @@ describe('Engine', () => { }) it('should get only the last result on run', async () => { - const engine = await getEngine() + const state = await getState() - const a = await engine.doString(`return 1`) - const b = await engine.doString(`return 3`) - const c = engine.doStringSync(`return 2`) - const d = engine.doStringSync(`return 5`) + const a = await state.doString(`return 1`) + const b = await state.doString(`return 3`) + const c = state.doStringSync(`return 2`) + const d = state.doStringSync(`return 5`) expect(a).to.be.equal(1) expect(b).to.be.equal(3) @@ -636,12 +636,12 @@ describe('Engine', () => { }) it('should get only the return values on call function', async () => { - const engine = await getEngine() - engine.global.set('hello', (name) => `Hello ${name}!`) + const state = await getState() + state.global.set('hello', (name) => `Hello ${name}!`) - const a = await engine.doString(`return 1`) - const b = engine.doStringSync(`return 5`) - const values = engine.global.call('hello', 'joao') + const a = await state.doString(`return 1`) + const b = state.doStringSync(`return 5`) + const values = state.global.call('hello', 'joao') expect(a).to.be.equal(1) expect(b).to.be.equal(5) @@ -650,69 +650,69 @@ describe('Engine', () => { }) it('create a large string variable should succeed', async () => { - const engine = await getEngine() + const state = await getState() const str = 'a'.repeat(1000000) - engine.global.set('str', str) + state.global.set('str', str) - const res = await engine.doString('return str') + const res = await state.doString('return str') expect(res).to.be.equal(str) }) it('execute a large string should succeed', async () => { - const engine = await getEngine() + const state = await getState() const str = 'a'.repeat(1000000) - const res = await engine.doString(`return [[${str}]]`) + const res = await state.doString(`return [[${str}]]`) expect(res).to.be.equal(str) }) it('negative integers should be pushed and retrieved as string', async () => { - const engine = await getEngine() - engine.global.set('value', -1) + const state = await getState() + state.global.set('value', -1) - const res = await engine.doString(`return tostring(value)`) + const res = await state.doString(`return tostring(value)`) expect(res).to.be.equal('-1') }) it('negative integers should be pushed and retrieved as number', async () => { - const engine = await getEngine() - engine.global.set('value', -1) + const state = await getState() + state.global.set('value', -1) - const res = await engine.doString(`return value`) + const res = await state.doString(`return value`) expect(res).to.be.equal(-1) }) it('number greater than 32 bit int should be pushed and retrieved as string', async () => { - const engine = await getEngine() + const state = await getState() const value = 1689031554550 - engine.global.set('value', value) + state.global.set('value', value) - const res = await engine.doString(`return tostring(value)`) + const res = await state.doString(`return tostring(value)`) expect(res).to.be.equal(`${String(value)}`) }) it('number greater than 32 bit int should be pushed and retrieved as number', async () => { - const engine = await getEngine() + const state = await getState() const value = 1689031554550 - engine.global.set('value', value) + state.global.set('value', value) - const res = await engine.doString(`return value`) + const res = await state.doString(`return value`) expect(res).to.be.equal(value) }) it('number greater than 32 bit int should be usable as a format argument', async () => { - const engine = await getEngine() + const state = await getState() const value = 1689031554550 - engine.global.set('value', value) + state.global.set('value', value) - const res = await engine.doString(`return ("%d"):format(value)`) + const res = await state.doString(`return ("%d"):format(value)`) expect(res).to.be.equal('1689031554550') }) @@ -721,10 +721,10 @@ describe('Engine', () => { // When yielding within a callback the error 'attempt to yield across a C-call boundary'. // This test just checks that throwing that error still allows the lua global to be // re-used and doesn't cause JS to abort or some nonsense. - const engine = await getEngine() + const state = await getState() const testEmitter = new EventEmitter() - engine.global.set('yield', () => new Promise((resolve) => testEmitter.once('resolve', resolve))) - const resPromise = engine.doString(` + state.global.set('yield', () => new Promise((resolve) => testEmitter.once('resolve', resolve))) + const resPromise = state.doString(` local res = yield():next(function () coroutine.yield() return 15 @@ -735,13 +735,13 @@ describe('Engine', () => { testEmitter.emit('resolve') await expect(resPromise).to.eventually.be.rejectedWith('Error: attempt to yield across a C-call boundary') - expect(await engine.doString(`return 42`)).to.equal(42) + expect(await state.doString(`return 42`)).to.equal(42) }) it('forced yield within JS callback from Lua doesnt cause vm to crash', async () => { - const engine = await getEngine({ functionTimeout: 10 }) - engine.global.set('promise', Promise.resolve()) - const thread = engine.global.newThread() + const state = await getState({ functionTimeout: 10 }) + state.global.set('promise', Promise.resolve()) + const thread = state.global.newThread() thread.loadString(` promise:next(function () while true do @@ -751,13 +751,13 @@ describe('Engine', () => { `) await expect(thread.run(0, { timeout: 5 })).to.eventually.be.rejectedWith('thread timeout exceeded') - expect(await engine.doString(`return 42`)).to.equal(42) + expect(await state.doString(`return 42`)).to.equal(42) }) it('function callback timeout still allows timeout of caller thread', async () => { - const engine = await getEngine() - engine.global.set('promise', Promise.resolve()) - const thread = engine.global.newThread() + const state = await getState() + state.global.set('promise', Promise.resolve()) + const thread = state.global.newThread() thread.loadString(` promise:next(function () -- nothing @@ -768,33 +768,33 @@ describe('Engine', () => { }) it('null injected and valid', async () => { - const engine = await getEngine() - engine.global.loadString(` + const state = await getState() + state.global.loadString(` local args = { ... } assert(args[1] == null, string.format("expected first argument to be null, got %s", tostring(args[1]))) return null, args[1], tostring(null) `) - engine.global.pushValue(null) - const res = await engine.global.run(1) + state.global.pushValue(null) + const res = await state.global.run(1) expect(res).to.deep.equal([null, null, 'null']) }) it('null injected as nil', async () => { - const engine = await getEngine({ injectObjects: false }) - engine.global.loadString(` + const state = await getState({ injectObjects: false }) + state.global.loadString(` local args = { ... } assert(type(args[1]) == "nil", string.format("expected first argument to be nil, got %s", type(args[1]))) return nil, args[1], tostring(nil) `) - engine.global.pushValue(null) - const res = await engine.global.run(1) + state.global.pushValue(null) + const res = await state.global.run(1) expect(res).to.deep.equal([null, null, 'nil']) }) it('Nested callback from JS to Lua', async () => { - const engine = await getEngine() - engine.global.set('call', (fn) => fn()) - const res = await engine.doString(` + const state = await getState() + state.global.set('call', (fn) => fn()) + const res = await state.doString(` return call(function () return call(function () return 10 @@ -805,13 +805,13 @@ describe('Engine', () => { }) it('lots of doString calls should succeed', async () => { - const engine = await getEngine() + const state = await getState() const length = 10000 for (let i = 0; i < length; i++) { const a = Math.floor(Math.random() * 100) const b = Math.floor(Math.random() * 100) - const result = await engine.doString(`return ${a} + ${b};`) + const result = await state.doString(`return ${a} + ${b};`) expect(result).to.equal(a + b) } }) diff --git a/test/filesystem.test.js b/test/filesystem.test.js index 849f933..d1c5f54 100644 --- a/test/filesystem.test.js +++ b/test/filesystem.test.js @@ -1,66 +1,66 @@ import { expect } from 'chai' -import { getEngine, getFactory } from './utils.js' +import { getState, getLua } from './utils.js' describe('Filesystem', () => { it('mount a file and require inside lua should succeed', async () => { - const factory = getFactory() - await factory.mountFile('test.lua', 'answerToLifeTheUniverseAndEverything = 42') - const engine = await factory.createEngine() + const lua = await getLua() + lua.mountFile('test.lua', 'answerToLifeTheUniverseAndEverything = 42') + const state = lua.createState() - await engine.doString('require("test")') + await state.doString('require("test")') - expect(engine.global.get('answerToLifeTheUniverseAndEverything')).to.be.equal(42) + expect(state.global.get('answerToLifeTheUniverseAndEverything')).to.be.equal(42) }) it('mount a file in a complex directory and require inside lua should succeed', async () => { - const factory = getFactory() - await factory.mountFile('yolo/sofancy/test.lua', 'return 42') - const engine = await factory.createEngine() + const lua = await getLua() + lua.mountFile('yolo/sofancy/test.lua', 'return 42') + const state = lua.createState() - const value = await engine.doString('return require("yolo/sofancy/test")') + const value = await state.doString('return require("yolo/sofancy/test")') expect(value).to.be.equal(42) }) it('mount a init file and require the module inside lua should succeed', async () => { - const factory = getFactory() - await factory.mountFile('hello/init.lua', 'return 42') - const engine = await factory.createEngine() + const lua = await getLua() + lua.mountFile('hello/init.lua', 'return 42') + const state = lua.createState() - const value = await engine.doString('return require("hello")') + const value = await state.doString('return require("hello")') expect(value).to.be.equal(42) }) it('require a file which is not mounted should throw', async () => { - const engine = await getEngine() + const state = await getState() - await expect(engine.doString('require("nothing")')).to.eventually.be.rejected + await expect(state.doString('require("nothing")')).to.eventually.be.rejected }) it('mount a file and run it should succeed', async () => { - const factory = getFactory() - const engine = await factory.createEngine() + const lua = await getLua() + const state = lua.createState() - await factory.mountFile('init.lua', `return 42`) - const value = await engine.doFile('init.lua') + lua.mountFile('init.lua', `return 42`) + const value = await state.doFile('init.lua') expect(value).to.be.equal(42) }) it('run a file which is not mounted should throw', async () => { - const engine = await getEngine() + const state = await getState() - await expect(engine.doFile('init.lua')).to.eventually.be.rejected + await expect(state.doFile('init.lua')).to.eventually.be.rejected }) it('mount a file with a large content should succeed', async () => { - const factory = getFactory() - const engine = await factory.createEngine() + const lua = await getLua() + const state = lua.createState() const content = 'a'.repeat(1000000) - await factory.mountFile('init.lua', `local a = "${content}" return a`) - const value = await engine.doFile('init.lua') + lua.mountFile('init.lua', `local a = "${content}" return a`) + const value = await state.doFile('init.lua') expect(value).to.be.equal(content) }) diff --git a/test/initialization.test.js b/test/initialization.test.js index c0a4026..90952b4 100644 --- a/test/initialization.test.js +++ b/test/initialization.test.js @@ -1,13 +1,23 @@ -import { LuaFactory } from '../dist/index.js' +import { Lua } from '../dist/index.js' import { expect } from 'chai' describe('Initialization', () => { - it('create engine should succeed', async () => { - await new LuaFactory().createEngine() + it('create state should succeed', async () => { + const lua = await Lua.load() + lua.createState() }) - it('create engine with options should succeed', async () => { - await new LuaFactory().createEngine({ + it('create multiple states should succeed', async () => { + const lua = await Lua.load() + const state1 = lua.createState() + const state2 = lua.createState() + + expect(state1.global.address).to.not.be.equal(state2.global.address) + }) + + it('create state with options should succeed', async () => { + const lua = await Lua.load() + lua.createState({ enableProxy: true, injectObjects: true, openStandardLibs: true, @@ -19,9 +29,10 @@ describe('Initialization', () => { const env = { ENV_TEST: 'test', } - const engine = await new LuaFactory({ env }).createEngine() + const lua = await Lua.load({ env }) + const state = lua.createState() - const value = await engine.doString('return os.getenv("ENV_TEST")') + const value = await state.doString('return os.getenv("ENV_TEST")') expect(value).to.be.equal(env.ENV_TEST) }) diff --git a/test/luatests.js b/test/luatests.js index 681266e..cfe2df7 100644 --- a/test/luatests.js +++ b/test/luatests.js @@ -1,24 +1,23 @@ -import { LuaFactory } from '../dist/index.js' +import { Lua } from '../dist/index.js' import { fileURLToPath } from 'node:url' import { readFile, glob } from 'node:fs/promises' -const factory = new LuaFactory() +const lua = await Lua.load() const testsPath = import.meta.resolve('../lua/testes') const filePath = fileURLToPath(typeof testsPath === 'string' ? testsPath : await Promise.resolve(testsPath)) for await (const file of glob(`${filePath}/**/*.lua`)) { const relativeFile = file.replace(`${filePath}/`, '') - await factory.mountFile(relativeFile, await readFile(file)) + lua.mountFile(relativeFile, await readFile(file)) } -const lua = await factory.createEngine() -const luamodule = await factory.getLuaModule() -luamodule.lua_warning(lua.global.address, '@on', 0) -lua.global.set('arg', ['lua', 'all.lua']) -lua.global.set('_port', true) -lua.global.getTable('os', (i) => { - lua.global.setField(i, 'setlocale', (locale) => { +const state = lua.createState() +lua.module.lua_warning(state.global.address, '@on', 0) +state.global.set('arg', ['lua', 'all.lua']) +state.global.set('_port', true) +state.global.getTable('os', (i) => { + state.global.setField(i, 'setlocale', (locale) => { return locale && locale !== 'C' ? false : 'C' }) }) -lua.doFileSync('all.lua') +state.doFileSync('all.lua') diff --git a/test/promises.test.js b/test/promises.test.js index d7b1d60..6227707 100644 --- a/test/promises.test.js +++ b/test/promises.test.js @@ -1,16 +1,16 @@ import { expect } from 'chai' -import { getEngine, tick } from './utils.js' +import { getState, tick } from './utils.js' import { mock } from 'node:test' describe('Promises', () => { it('use promise next should succeed', async () => { - const engine = await getEngine() + const state = await getState() const check = mock.fn() - engine.global.set('check', check) + state.global.set('check', check) const promise = new Promise((resolve) => setTimeout(() => resolve(60), 5)) - engine.global.set('promise', promise) + state.global.set('promise', promise) - const res = engine.doString(` + const res = state.doString(` promise:next(check) `) @@ -21,13 +21,13 @@ describe('Promises', () => { }) it('chain promises with next should succeed', async () => { - const engine = await getEngine() + const state = await getState() const check = mock.fn() - engine.global.set('check', check) + state.global.set('check', check) const promise = new Promise((resolve) => resolve(60)) - engine.global.set('promise', promise) + state.global.set('promise', promise) - const res = engine.doString(` + const res = state.doString(` promise:next(function(value) return value * 2 end):next(check):next(check) @@ -42,12 +42,12 @@ describe('Promises', () => { }) it('call an async function should succeed', async () => { - const engine = await getEngine() - engine.global.set('asyncFunction', async () => Promise.resolve(60)) + const state = await getState() + state.global.set('asyncFunction', async () => Promise.resolve(60)) const check = mock.fn() - engine.global.set('check', check) + state.global.set('check', check) - const res = engine.doString(` + const res = state.doString(` asyncFunction():next(check) `) @@ -57,10 +57,10 @@ describe('Promises', () => { }) it('return an async function should succeed', async () => { - const engine = await getEngine() - engine.global.set('asyncFunction', async () => Promise.resolve(60)) + const state = await getState() + state.global.set('asyncFunction', async () => Promise.resolve(60)) - const asyncFunction = await engine.doString(` + const asyncFunction = await state.doString(` return asyncFunction `) const value = await asyncFunction() @@ -69,10 +69,10 @@ describe('Promises', () => { }) it('return a chained promise should succeed', async () => { - const engine = await getEngine() - engine.global.set('asyncFunction', async () => Promise.resolve(60)) + const state = await getState() + state.global.set('asyncFunction', async () => Promise.resolve(60)) - const asyncFunction = await engine.doString(` + const asyncFunction = await state.doString(` return asyncFunction():next(function(x) return x * 2 end) `) const value = await asyncFunction @@ -81,13 +81,13 @@ describe('Promises', () => { }) it('await an promise inside coroutine should succeed', async () => { - const engine = await getEngine() + const state = await getState() const check = mock.fn() - engine.global.set('check', check) + state.global.set('check', check) const promise = new Promise((resolve) => setTimeout(() => resolve(60), 5)) - engine.global.set('promise', promise) + state.global.set('promise', promise) - const res = engine.doString(` + const res = state.doString(` local co = coroutine.create(function() local value = promise:await() check(value) @@ -108,13 +108,13 @@ describe('Promises', () => { }) it('awaited coroutines should ignore resume until it resolves the promise', async () => { - const engine = await getEngine() + const state = await getState() const check = mock.fn() - engine.global.set('check', check) + state.global.set('check', check) const promise = new Promise((resolve) => setTimeout(() => resolve(60), 5)) - engine.global.set('promise', promise) + state.global.set('promise', promise) - const res = engine.doString(` + const res = state.doString(` local co = coroutine.create(function() local value = promise:await() check(value) @@ -133,9 +133,9 @@ describe('Promises', () => { }) it('await a thread run with async calls should succeed', async () => { - const engine = await getEngine() - engine.global.set('sleep', (input) => new Promise((resolve) => setTimeout(resolve, input))) - const asyncThread = engine.global.newThread() + const state = await getState() + state.global.set('sleep', (input) => new Promise((resolve) => setTimeout(resolve, input))) + const asyncThread = state.global.newThread() asyncThread.loadString(` sleep(1):await() @@ -147,9 +147,9 @@ describe('Promises', () => { }) it('run thread with async calls and yields should succeed', async () => { - const engine = await getEngine() - engine.global.set('sleep', (input) => new Promise((resolve) => setTimeout(resolve, input))) - const asyncThread = engine.global.newThread() + const state = await getState() + state.global.set('sleep', (input) => new Promise((resolve) => setTimeout(resolve, input))) + const asyncThread = state.global.newThread() asyncThread.loadString(` coroutine.yield() @@ -165,9 +165,9 @@ describe('Promises', () => { }) it('reject a promise should succeed', async () => { - const engine = await getEngine() - engine.global.set('throw', () => new Promise((_, reject) => reject(new Error('expected test error')))) - const asyncThread = engine.global.newThread() + const state = await getState() + state.global.set('throw', () => new Promise((_, reject) => reject(new Error('expected test error')))) + const asyncThread = state.global.newThread() asyncThread.loadString(` throw():await() @@ -178,9 +178,9 @@ describe('Promises', () => { }) it('pcall a promise await should succeed', async () => { - const engine = await getEngine() - engine.global.set('throw', () => new Promise((_, reject) => reject(new Error('expected test error')))) - const asyncThread = engine.global.newThread() + const state = await getState() + state.global.set('throw', () => new Promise((_, reject) => reject(new Error('expected test error')))) + const asyncThread = state.global.newThread() asyncThread.loadString(` local succeed, err = pcall(function() throw():await() end) @@ -192,13 +192,13 @@ describe('Promises', () => { }) it('catch a promise rejection should succeed', async () => { - const engine = await getEngine() + const state = await getState() const fulfilled = mock.fn() const rejected = mock.fn() - engine.global.set('handlers', { fulfilled, rejected }) - engine.global.set('throw', new Promise((_, reject) => reject(new Error('expected test error')))) + state.global.set('handlers', { fulfilled, rejected }) + state.global.set('throw', new Promise((_, reject) => reject(new Error('expected test error')))) - const res = engine.doString(` + const res = state.doString(` throw:next(handlers.fulfilled, handlers.rejected):catch(function() end) `) @@ -209,10 +209,10 @@ describe('Promises', () => { }) it('run with async callback', async () => { - const engine = await getEngine() - const thread = engine.global.newThread() + const state = await getState() + const thread = state.global.newThread() - engine.global.set('asyncCallback', async (input) => { + state.global.set('asyncCallback', async (input) => { return Promise.resolve(input * 2) }) @@ -232,8 +232,8 @@ describe('Promises', () => { }) it('promise creation from js', async () => { - const engine = await getEngine() - const res = await engine.doString(` + const state = await getState() + const res = await state.doString(` local promise = Promise.create(function (resolve) resolve(10) end) @@ -248,8 +248,8 @@ describe('Promises', () => { }) it('reject promise creation from js', async () => { - const engine = await getEngine() - const res = await engine.doString(` + const state = await getState() + const res = await state.doString(` local rejection = Promise.create(function (resolve, reject) reject("expected rejection") end) @@ -261,9 +261,9 @@ describe('Promises', () => { }) it('resolve multiple promises with promise.all', async () => { - const engine = await getEngine() - engine.global.set('sleep', (input) => new Promise((resolve) => setTimeout(resolve, input))) - const resPromise = engine.doString(` + const state = await getState() + state.global.set('sleep', (input) => new Promise((resolve) => setTimeout(resolve, input))) + const resPromise = state.doString(` local promises = {} for i = 1, 10 do table.insert(promises, sleep(5):next(function () @@ -278,9 +278,9 @@ describe('Promises', () => { }) it('error in promise next catchable', async () => { - const engine = await getEngine() - engine.global.set('sleep', (input) => new Promise((resolve) => setTimeout(resolve, input))) - const resPromise = engine.doString(` + const state = await getState() + state.global.set('sleep', (input) => new Promise((resolve) => setTimeout(resolve, input))) + const resPromise = state.doString(` return sleep(1):next(function () error("sleep done") end):await() @@ -289,11 +289,11 @@ describe('Promises', () => { }) it('should not be possible to await in synchronous run', async () => { - const engine = await getEngine() - engine.global.set('sleep', (input) => new Promise((resolve) => setTimeout(resolve, input))) + const state = await getState() + state.global.set('sleep', (input) => new Promise((resolve) => setTimeout(resolve, input))) expect(() => { - engine.doStringSync(`sleep(5):await()`) + state.doStringSync(`sleep(5):await()`) }).to.throw('cannot await in the main thread') }) }) diff --git a/test/utils.js b/test/utils.js index 3106620..8a0e97d 100644 --- a/test/utils.js +++ b/test/utils.js @@ -1,11 +1,12 @@ -import { LuaFactory } from '../dist/index.js' +import { Lua } from '../dist/index.js' -export const getFactory = (env) => { - return new LuaFactory({ env }) +export const getLua = (env) => { + return Lua.load({ env }) } -export const getEngine = (config = {}) => { - return new LuaFactory().createEngine({ +export const getState = async (config = {}) => { + const lua = await Lua.load() + return lua.createState({ injectObjects: true, ...config, }) diff --git a/utils/build-wasm.sh b/utils/build-wasm.sh index 6b18ceb..4818b30 100755 --- a/utils/build-wasm.sh +++ b/utils/build-wasm.sh @@ -20,6 +20,7 @@ emcc \ 'addFunction', \ 'removeFunction', \ 'FS', \ + 'PATH', \ 'ENV', \ 'getValue', \ 'setValue', \ From 9dac5f9e00fd70669215831d7b3340cca71ec775 Mon Sep 17 00:00:00 2001 From: Gabriel Francisco Date: Fri, 13 Mar 2026 20:39:51 -0300 Subject: [PATCH 28/83] update packages, use oxc --- .prettierrc => .oxfmtrc.json | 4 +- .oxlintrc.json | 13 + bench/steps.js | 4 +- eslint.config.js | 140 -- lua | 2 +- package-lock.json | 2469 ++++++++++++------------------- package.json | 30 +- src/module.ts | 75 +- src/type-extensions/function.ts | 10 +- src/type-extensions/promise.ts | 1 + src/type-extensions/table.ts | 2 +- tsconfig.json | 2 +- utils/build-wasm.js | 3 +- utils/build-wasm.sh | 7 +- 14 files changed, 1067 insertions(+), 1695 deletions(-) rename .prettierrc => .oxfmtrc.json (61%) create mode 100644 .oxlintrc.json delete mode 100644 eslint.config.js diff --git a/.prettierrc b/.oxfmtrc.json similarity index 61% rename from .prettierrc rename to .oxfmtrc.json index f2060e4..600545a 100644 --- a/.prettierrc +++ b/.oxfmtrc.json @@ -5,5 +5,7 @@ "quoteProps": "consistent", "semi": false, "printWidth": 140, - "tabWidth": 4 + "tabWidth": 4, + "sortPackageJson": false, + "ignorePatterns": ["rolldown.config.*.js"] } diff --git a/.oxlintrc.json b/.oxlintrc.json new file mode 100644 index 0000000..ceebf07 --- /dev/null +++ b/.oxlintrc.json @@ -0,0 +1,13 @@ +{ + "plugins": ["import", "promise", "node"], + "rules": { + "no-shadow": "off", + "no-extend-native": "off", + "consistent-function-scoping": "off", + "promise/always-return": "off" + }, + "ignorePatterns": ["dist/**", "build/**", "rolldown.config.ts", "rolldown.config.*.js", "utils/**"], + "env": { + "builtin": true + } +} diff --git a/bench/steps.js b/bench/steps.js index 9066fcd..ec6c273 100644 --- a/bench/steps.js +++ b/bench/steps.js @@ -47,8 +47,8 @@ const runInteropedHeapsort = async () => { const state = lua.createState() console.time('Run interoped heapsort') - const runHeapsort = await state.doString(heapsort) - assert(runHeapsort() === 10) + const executeHeapsort = await state.doString(heapsort) + assert(executeHeapsort() === 10) console.timeEnd('Run interoped heapsort') } diff --git a/eslint.config.js b/eslint.config.js deleted file mode 100644 index 23e7807..0000000 --- a/eslint.config.js +++ /dev/null @@ -1,140 +0,0 @@ -import eslint from '@eslint/js' -import tsParser from '@typescript-eslint/parser' -import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended' -import simpleImportSort from 'eslint-plugin-simple-import-sort' -import tseslint from 'typescript-eslint' - -export default [ - { - ignores: ['**/dist/*', '**/build/*', '**/rolldown.config.ts', '**/utils/*', 'eslint.config.js'], - }, - eslint.configs.recommended, - ...tseslint.configs.recommended, - eslintPluginPrettierRecommended, - { - files: ['test/**/*.js', 'bench/**/*.js'], - rules: { - '@typescript-eslint/no-var-requires': 'off', - '@typescript-eslint/no-require-imports': 'off', - '@typescript-eslint/explicit-function-return-type': 'off', - '@typescript-eslint/no-unsafe-argument': 'off', - 'no-undef': 'off', - }, - }, - { - files: ['**/*.js', '**/*.mjs', '**/*.ts', './bin/*'], - ignores: ['**/test/*', '**/bench/*'], - plugins: { - 'simple-import-sort': simpleImportSort, - }, - languageOptions: { - parser: tsParser, - ecmaVersion: 'latest', - sourceType: 'script', - parserOptions: { - project: './tsconfig.json', - }, - }, - rules: { - 'no-console': 'off', - '@typescript-eslint/no-unsafe-call': 'off', - '@typescript-eslint/no-unsafe-member-access': 'off', - '@typescript-eslint/no-unsafe-assignment': 'off', - '@typescript-eslint/no-unsafe-return': 'off', - '@typescript-eslint/restrict-plus-operands': 'off', - '@typescript-eslint/restrict-template-expressions': 'off', - '@typescript-eslint/no-non-null-assertion': 'off', - '@typescript-eslint/camelcase': 'off', - '@typescript-eslint/member-naming': 'off', - - '@typescript-eslint/no-unused-vars': [ - 'error', - { - argsIgnorePattern: '^_', - }, - ], - - '@typescript-eslint/member-ordering': [ - 'error', - { - classes: [ - 'public-static-field', - 'protected-static-field', - 'private-static-field', - 'public-static-method', - 'protected-static-method', - 'private-static-method', - 'public-instance-field', - 'protected-instance-field', - 'private-instance-field', - 'public-constructor', - 'protected-constructor', - 'private-constructor', - 'public-instance-method', - 'protected-instance-method', - 'private-instance-method', - ], - }, - ], - - 'curly': ['error', 'all'], - 'eqeqeq': 'error', - 'max-classes-per-file': 'error', - 'no-alert': 'error', - 'no-caller': 'error', - 'no-eval': 'error', - 'no-extend-native': 'error', - 'no-extra-bind': 'error', - 'no-implicit-coercion': 'error', - 'no-labels': 'error', - 'no-new': 'error', - 'no-new-func': 'error', - 'no-new-wrappers': 'error', - 'no-octal-escape': 'error', - 'no-return-assign': 'error', - 'no-self-compare': 'error', - 'no-sequences': 'error', - 'no-throw-literal': 'error', - 'no-unmodified-loop-condition': 'error', - 'no-useless-call': 'error', - 'no-useless-concat': 'error', - 'no-void': 'error', - 'prefer-promise-reject-errors': 'error', - 'radix': ['error', 'always'], - 'no-shadow': 'off', - - 'no-duplicate-imports': 'error', - 'prefer-numeric-literals': 'error', - 'prefer-template': 'error', - 'symbol-description': 'error', - - '@typescript-eslint/array-type': [ - 'error', - { - default: 'array-simple', - }, - ], - - '@typescript-eslint/consistent-type-definitions': ['error', 'interface'], - - '@typescript-eslint/explicit-function-return-type': [ - 'error', - { - allowExpressions: true, - allowTypedFunctionExpressions: true, - allowHigherOrderFunctions: true, - }, - ], - - '@typescript-eslint/interface-name-prefix': 'off', - '@typescript-eslint/no-redundant-type-constituents': 'off', - '@typescript-eslint/no-explicit-any': 'off', - '@typescript-eslint/no-floating-promises': 'error', - '@typescript-eslint/no-parameter-properties': 'off', - '@typescript-eslint/no-require-imports': 'error', - '@typescript-eslint/no-useless-constructor': 'error', - '@typescript-eslint/prefer-for-of': 'error', - 'prettier/prettier': 'error', - }, - }, -] diff --git a/lua b/lua index be908a7..c6b4848 160000 --- a/lua +++ b/lua @@ -1 +1 @@ -Subproject commit be908a7d4d8130264ad67c5789169769f824c5d1 +Subproject commit c6b484823806e08e1756b1a6066a3ace6f080fae diff --git a/package-lock.json b/package-lock.json index 4e37b2b..f6f2eb7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,47 +9,41 @@ "version": "1.16.0", "license": "MIT", "dependencies": { - "@types/emscripten": "1.40.0" + "@types/emscripten": "1.41.5" }, "bin": { "wasmoon": "bin/wasmoon" }, "devDependencies": { - "@eslint/js": "9.20.0", - "@types/node": "22.13.4", - "@typescript-eslint/parser": "8.24.1", - "chai": "5.2.0", - "chai-as-promised": "8.0.1", - "eslint": "9.20.1", - "eslint-config-prettier": "10.0.1", - "eslint-plugin-prettier": "5.2.3", - "eslint-plugin-simple-import-sort": "12.1.1", - "fengari": "0.1.4", - "mocha": "11.1.0", - "prettier": "3.5.1", - "rolldown": "1.0.0-beta.3", + "@types/node": "25.5.0", + "chai": "6.2.2", + "chai-as-promised": "8.0.2", + "fengari": "0.1.5", + "mocha": "11.7.5", + "oxfmt": "0.40.0", + "oxlint": "1.55.0", + "rolldown": "1.0.0-rc.9", "rollup-plugin-copy": "3.5.0", "tslib": "2.8.1", - "typescript": "5.7.3", - "typescript-eslint": "8.24.1" + "typescript": "5.9.3" } }, "node_modules/@emnapi/core": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.3.1.tgz", - "integrity": "sha512-pVGjBIt1Y6gg3EJN8jTcfpP/+uuRksIo055oE/OBkDNcjZqVbfkWCksG1Jp4yZnj3iKWyWX8fdG/j6UDYPbFog==", + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.9.0.tgz", + "integrity": "sha512-0DQ98G9ZQZOxfUcQn1waV2yS8aWdZ6kJMbYCJB3oUBecjWYO1fqJ+a1DRfPF3O5JEkwqwP1A9QEN/9mYm2Yd0w==", "dev": true, "license": "MIT", "optional": true, "dependencies": { - "@emnapi/wasi-threads": "1.0.1", + "@emnapi/wasi-threads": "1.2.0", "tslib": "^2.4.0" } }, "node_modules/@emnapi/runtime": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.3.1.tgz", - "integrity": "sha512-kEBmG8KyqtxJZv+ygbEim+KCGtIq1fC22Ms3S4ziXmYKm8uyoLX0MHONVKwp+9opg390VaKRNt4a7A9NwmpNhw==", + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.9.0.tgz", + "integrity": "sha512-QN75eB0IH2ywSpRpNddCRfQIhmJYBCJ1x5Lb3IscKAL8bMnVAKnRg8dCoXbHzVLLH7P38N2Z3mtulB7W0J0FKw==", "dev": true, "license": "MIT", "optional": true, @@ -58,9 +52,9 @@ } }, "node_modules/@emnapi/wasi-threads": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.0.1.tgz", - "integrity": "sha512-iIBu7mwkq4UQGeMEM8bLwNK962nXdhodeScX4slfQnRhEMMzvYivHhutCIk8uojvmASXXPC2WNEjwxFWk72Oqw==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.0.tgz", + "integrity": "sha512-N10dEJNSsUx41Z6pZsXU8FjPjpBEplgH24sfkmITrBED1/U2Esum9F3lfLrMjKHHjmi557zQn7kR9R+XWXu5Rg==", "dev": true, "license": "MIT", "optional": true, @@ -68,312 +62,733 @@ "tslib": "^2.4.0" } }, - "node_modules/@eslint-community/eslint-utils": { - "version": "4.4.1", - "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.4.1.tgz", - "integrity": "sha512-s3O3waFUrMV8P/XaF/+ZTp1X9XBZW1a4B97ZnjQF2KYWaFD2A8KyFBsrsfSjEmjn3RGWAIuvlneuZm3CUK3jbA==", + "node_modules/@isaacs/cliui": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", + "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", "dev": true, - "license": "MIT", + "license": "ISC", "dependencies": { - "eslint-visitor-keys": "^3.4.3" + "string-width": "^5.1.2", + "string-width-cjs": "npm:string-width@^4.2.0", + "strip-ansi": "^7.0.1", + "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", + "wrap-ansi": "^8.1.0", + "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" }, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": ">=12" + } + }, + "node_modules/@napi-rs/wasm-runtime": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.1.tgz", + "integrity": "sha512-p64ah1M1ld8xjWv3qbvFwHiFVWrq1yFvV4f7w+mzaqiR4IlSgkqhcRdHwsGgomwzBH51sRY4NEowLxnaBjcW/A==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "^1.7.1", + "@emnapi/runtime": "^1.7.1", + "@tybys/wasm-util": "^0.10.1" }, "funding": { - "url": "https://opencollective.com/eslint" + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@nodelib/fs.scandir": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", + "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "2.0.5", + "run-parallel": "^1.1.9" }, - "peerDependencies": { - "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" + "engines": { + "node": ">= 8" } }, - "node_modules/@eslint-community/regexpp": { - "version": "4.12.1", - "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.1.tgz", - "integrity": "sha512-CCZCDJuduB9OUkFkY2IgppNZMi2lBQgD2qzwXkEia16cge2pijY/aXi96CJMquDMn3nJdlPV1A5KrJEXwfLNzQ==", + "node_modules/@nodelib/fs.stat": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", + "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", "dev": true, "license": "MIT", "engines": { - "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + "node": ">= 8" } }, - "node_modules/@eslint/config-array": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.19.1.tgz", - "integrity": "sha512-fo6Mtm5mWyKjA/Chy1BYTdn5mGJoDNjC7C64ug20ADsRDGrA85bN3uK3MaKbeRkRuuIEAR5N33Jr1pbm411/PA==", + "node_modules/@nodelib/fs.walk": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", + "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", "dev": true, - "license": "Apache-2.0", + "license": "MIT", "dependencies": { - "@eslint/object-schema": "^2.1.5", - "debug": "^4.3.1", - "minimatch": "^3.1.2" + "@nodelib/fs.scandir": "2.1.5", + "fastq": "^1.6.0" }, "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + "node": ">= 8" } }, - "node_modules/@eslint/config-array/node_modules/brace-expansion": { - "version": "1.1.11", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", - "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "node_modules/@oxc-project/types": { + "version": "0.115.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.115.0.tgz", + "integrity": "sha512-4n91DKnebUS4yjUHl2g3/b2T+IUdCfmoZGhmwsovZCDaJSs+QkVAM+0AqqTxHSsHfeiMuueT75cZaZcT/m0pSw==", "dev": true, "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" + "funding": { + "url": "https://github.com/sponsors/Boshen" } }, - "node_modules/@eslint/config-array/node_modules/minimatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", - "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "node_modules/@oxfmt/binding-android-arm-eabi": { + "version": "0.40.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm-eabi/-/binding-android-arm-eabi-0.40.0.tgz", + "integrity": "sha512-S6zd5r1w/HmqR8t0CTnGjFTBLDq2QKORPwriCHxo4xFNuhmOTABGjPaNvCJJVnrKBLsohOeiDX3YqQfJPF+FXw==", + "cpu": [ + "arm" + ], "dev": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^1.1.7" - }, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], "engines": { - "node": "*" + "node": "^20.19.0 || >=22.12.0" } }, - "node_modules/@eslint/core": { - "version": "0.10.0", - "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.10.0.tgz", - "integrity": "sha512-gFHJ+xBOo4G3WRlR1e/3G8A6/KZAH6zcE/hkLRCZTi/B9avAG365QhFA8uOGzTMqgTghpn7/fSnscW++dpMSAw==", + "node_modules/@oxfmt/binding-android-arm64": { + "version": "0.40.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm64/-/binding-android-arm64-0.40.0.tgz", + "integrity": "sha512-/mbS9UUP/5Vbl2D6osIdcYiP0oie63LKMoTyGj5hyMCK/SFkl3EhtyRAfdjPvuvHC0SXdW6ePaTKkBSq1SNcIw==", + "cpu": [ + "arm64" + ], "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@types/json-schema": "^7.0.15" - }, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + "node": "^20.19.0 || >=22.12.0" } }, - "node_modules/@eslint/eslintrc": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.2.0.tgz", - "integrity": "sha512-grOjVNN8P3hjJn/eIETF1wwd12DdnwFDoyceUJLYYdkpbwq3nLi+4fqrTAONx7XDALqlL220wC/RHSC/QTI/0w==", + "node_modules/@oxfmt/binding-darwin-arm64": { + "version": "0.40.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-arm64/-/binding-darwin-arm64-0.40.0.tgz", + "integrity": "sha512-wRt8fRdfLiEhnRMBonlIbKrJWixoEmn6KCjKE9PElnrSDSXETGZfPb8ee+nQNTobXkCVvVLytp2o0obAsxl78Q==", + "cpu": [ + "arm64" + ], "dev": true, "license": "MIT", - "dependencies": { - "ajv": "^6.12.4", - "debug": "^4.3.2", - "espree": "^10.0.1", - "globals": "^14.0.0", - "ignore": "^5.2.0", - "import-fresh": "^3.2.1", - "js-yaml": "^4.1.0", - "minimatch": "^3.1.2", - "strip-json-comments": "^3.1.1" - }, + "optional": true, + "os": [ + "darwin" + ], "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" + "node": "^20.19.0 || >=22.12.0" } }, - "node_modules/@eslint/eslintrc/node_modules/brace-expansion": { - "version": "1.1.11", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", - "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "node_modules/@oxfmt/binding-darwin-x64": { + "version": "0.40.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-x64/-/binding-darwin-x64-0.40.0.tgz", + "integrity": "sha512-fzowhqbOE/NRy+AE5ob0+Y4X243WbWzDb00W+pKwD7d9tOqsAFbtWUwIyqqCoCLxj791m2xXIEeLH/3uz7zCCg==", + "cpu": [ + "x64" + ], "dev": true, "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" } }, - "node_modules/@eslint/eslintrc/node_modules/minimatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", - "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "node_modules/@oxfmt/binding-freebsd-x64": { + "version": "0.40.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-freebsd-x64/-/binding-freebsd-x64-0.40.0.tgz", + "integrity": "sha512-agZ9ITaqdBjcerRRFEHB8s0OyVcQW8F9ZxsszjxzeSthQ4fcN2MuOtQFWec1ed8/lDa50jSLHVE2/xPmTgtCfQ==", + "cpu": [ + "x64" + ], "dev": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^1.1.7" - }, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], "engines": { - "node": "*" + "node": "^20.19.0 || >=22.12.0" } }, - "node_modules/@eslint/js": { - "version": "9.20.0", - "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.20.0.tgz", - "integrity": "sha512-iZA07H9io9Wn836aVTytRaNqh00Sad+EamwOVJT12GTLw1VGMFV/4JaME+JjLtr9fiGaoWgYnS54wrfWsSs4oQ==", + "node_modules/@oxfmt/binding-linux-arm-gnueabihf": { + "version": "0.40.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-0.40.0.tgz", + "integrity": "sha512-ZM2oQ47p28TP1DVIp7HL1QoMUgqlBFHey0ksHct7tMXoU5BqjNvPWw7888azzMt25lnyPODVuye1wvNbvVUFOA==", + "cpu": [ + "arm" + ], "dev": true, "license": "MIT", + "optional": true, + "os": [ + "linux" + ], "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + "node": "^20.19.0 || >=22.12.0" } }, - "node_modules/@eslint/object-schema": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-2.1.5.tgz", - "integrity": "sha512-o0bhxnL89h5Bae5T318nFoFzGy+YE5i/gGkoPAgkmTVdRKTiv3p8JHevPiPaMwoloKfEiiaHlawCqaZMqRm+XQ==", + "node_modules/@oxfmt/binding-linux-arm-musleabihf": { + "version": "0.40.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-0.40.0.tgz", + "integrity": "sha512-RBFPAxRAIsMisKM47Oe6Lwdv6agZYLz02CUhVCD1sOv5ajAcRMrnwCFBPWwGXpazToW2mjnZxFos8TuFjTU15A==", + "cpu": [ + "arm" + ], "dev": true, - "license": "Apache-2.0", + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + "node": "^20.19.0 || >=22.12.0" } }, - "node_modules/@eslint/plugin-kit": { - "version": "0.2.5", - "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.2.5.tgz", - "integrity": "sha512-lB05FkqEdUg2AA0xEbUz0SnkXT1LcCTa438W4IWTUh4hdOnVbQyOJ81OrDXsJk/LSiJHubgGEFoR5EHq1NsH1A==", + "node_modules/@oxfmt/binding-linux-arm64-gnu": { + "version": "0.40.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-0.40.0.tgz", + "integrity": "sha512-Nb2XbQ+wV3W2jSIihXdPj7k83eOxeSgYP3N/SRXvQ6ZYPIk6Q86qEh5Gl/7OitX3bQoQrESqm1yMLvZV8/J7dA==", + "cpu": [ + "arm64" + ], "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@eslint/core": "^0.10.0", - "levn": "^0.4.1" - }, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + "node": "^20.19.0 || >=22.12.0" } }, - "node_modules/@humanfs/core": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.1.tgz", - "integrity": "sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA==", + "node_modules/@oxfmt/binding-linux-arm64-musl": { + "version": "0.40.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-musl/-/binding-linux-arm64-musl-0.40.0.tgz", + "integrity": "sha512-tGmWhLD/0YMotCdfezlT6tC/MJG/wKpo4vnQ3Cq+4eBk/BwNv7EmkD0VkD5F/dYkT3b8FNU01X2e8vvJuWoM1w==", + "cpu": [ + "arm64" + ], "dev": true, - "license": "Apache-2.0", + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], "engines": { - "node": ">=18.18.0" + "node": "^20.19.0 || >=22.12.0" } }, - "node_modules/@humanfs/node": { - "version": "0.16.6", - "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.6.tgz", - "integrity": "sha512-YuI2ZHQL78Q5HbhDiBA1X4LmYdXCKCMQIfw0pw7piHJwyREFebJUvrQN4cMssyES6x+vfUbx1CIpaQUKYdQZOw==", + "node_modules/@oxfmt/binding-linux-ppc64-gnu": { + "version": "0.40.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-0.40.0.tgz", + "integrity": "sha512-rVbFyM3e7YhkVnp0IVYjaSHfrBWcTRWb60LEcdNAJcE2mbhTpbqKufx0FrhWfoxOrW/+7UJonAOShoFFLigDqQ==", + "cpu": [ + "ppc64" + ], "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@humanfs/core": "^0.19.1", - "@humanwhocodes/retry": "^0.3.0" - }, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], "engines": { - "node": ">=18.18.0" + "node": "^20.19.0 || >=22.12.0" } }, - "node_modules/@humanfs/node/node_modules/@humanwhocodes/retry": { - "version": "0.3.1", - "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.3.1.tgz", - "integrity": "sha512-JBxkERygn7Bv/GbN5Rv8Ul6LVknS+5Bp6RgDC/O8gEBU/yeH5Ui5C/OlWrTb6qct7LjjfT6Re2NxB0ln0yYybA==", + "node_modules/@oxfmt/binding-linux-riscv64-gnu": { + "version": "0.40.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-0.40.0.tgz", + "integrity": "sha512-3ZqBw14JtWeEoLiioJcXSJz8RQyPE+3jLARnYM1HdPzZG4vk+Ua8CUupt2+d+vSAvMyaQBTN2dZK+kbBS/j5mA==", + "cpu": [ + "riscv64" + ], "dev": true, - "license": "Apache-2.0", + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], "engines": { - "node": ">=18.18" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/nzakas" + "node": "^20.19.0 || >=22.12.0" } }, - "node_modules/@humanwhocodes/module-importer": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", - "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", + "node_modules/@oxfmt/binding-linux-riscv64-musl": { + "version": "0.40.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-0.40.0.tgz", + "integrity": "sha512-JJ4PPSdcbGBjPvb+O7xYm2FmAsKCyuEMYhqatBAHMp/6TA6rVlf9Z/sYPa4/3Bommb+8nndm15SPFRHEPU5qFA==", + "cpu": [ + "riscv64" + ], "dev": true, - "license": "Apache-2.0", + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], "engines": { - "node": ">=12.22" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/nzakas" + "node": "^20.19.0 || >=22.12.0" } }, - "node_modules/@humanwhocodes/retry": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.1.tgz", - "integrity": "sha512-c7hNEllBlenFTHBky65mhq8WD2kbN9Q6gk0bTk8lSBvc554jpXSkST1iePudpt7+A/AQvuHs9EMqjHDXMY1lrA==", + "node_modules/@oxfmt/binding-linux-s390x-gnu": { + "version": "0.40.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-0.40.0.tgz", + "integrity": "sha512-Kp0zNJoX9Ik77wUya2tpBY3W9f40VUoMQLWVaob5SgCrblH/t2xr/9B2bWHfs0WCefuGmqXcB+t0Lq77sbBmZw==", + "cpu": [ + "s390x" + ], "dev": true, - "license": "Apache-2.0", + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], "engines": { - "node": ">=18.18" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/nzakas" + "node": "^20.19.0 || >=22.12.0" } }, - "node_modules/@isaacs/cliui": { - "version": "8.0.2", - "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", - "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", + "node_modules/@oxfmt/binding-linux-x64-gnu": { + "version": "0.40.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-gnu/-/binding-linux-x64-gnu-0.40.0.tgz", + "integrity": "sha512-7YTCNzleWTaQTqNGUNQ66qVjpoV6DjbCOea+RnpMBly2bpzrI/uu7Rr+2zcgRfNxyjXaFTVQKaRKjqVdeUfeVA==", + "cpu": [ + "x64" + ], "dev": true, - "license": "ISC", - "dependencies": { - "string-width": "^5.1.2", - "string-width-cjs": "npm:string-width@^4.2.0", - "strip-ansi": "^7.0.1", - "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", - "wrap-ansi": "^8.1.0", - "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" - }, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], "engines": { - "node": ">=12" + "node": "^20.19.0 || >=22.12.0" } }, - "node_modules/@napi-rs/wasm-runtime": { - "version": "0.2.6", - "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-0.2.6.tgz", - "integrity": "sha512-z8YVS3XszxFTO73iwvFDNpQIzdMmSDTP/mB3E/ucR37V3Sx57hSExcXyMoNwaucWxnsWf4xfbZv0iZ30jr0M4Q==", + "node_modules/@oxfmt/binding-linux-x64-musl": { + "version": "0.40.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-musl/-/binding-linux-x64-musl-0.40.0.tgz", + "integrity": "sha512-hWnSzJ0oegeOwfOEeejYXfBqmnRGHusgtHfCPzmvJvHTwy1s3Neo59UKc1CmpE3zxvrCzJoVHos0rr97GHMNPw==", + "cpu": [ + "x64" + ], "dev": true, "license": "MIT", "optional": true, - "dependencies": { - "@emnapi/core": "^1.3.1", - "@emnapi/runtime": "^1.3.1", - "@tybys/wasm-util": "^0.9.0" + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" } }, - "node_modules/@nodelib/fs.scandir": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", - "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", + "node_modules/@oxfmt/binding-openharmony-arm64": { + "version": "0.40.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-openharmony-arm64/-/binding-openharmony-arm64-0.40.0.tgz", + "integrity": "sha512-28sJC1lR4qtBJGzSRRbPnSW3GxU2+4YyQFE6rCmsUYqZ5XYH8jg0/w+CvEzQ8TuAQz5zLkcA25nFQGwoU0PT3Q==", + "cpu": [ + "arm64" + ], "dev": true, "license": "MIT", - "dependencies": { - "@nodelib/fs.stat": "2.0.5", - "run-parallel": "^1.1.9" - }, + "optional": true, + "os": [ + "openharmony" + ], "engines": { - "node": ">= 8" + "node": "^20.19.0 || >=22.12.0" } }, - "node_modules/@nodelib/fs.stat": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", - "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", + "node_modules/@oxfmt/binding-win32-arm64-msvc": { + "version": "0.40.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-0.40.0.tgz", + "integrity": "sha512-cDkRnyT0dqwF5oIX1Cv59HKCeZQFbWWdUpXa3uvnHFT2iwYSSZspkhgjXjU6iDp5pFPaAEAe9FIbMoTgkTmKPg==", + "cpu": [ + "arm64" + ], "dev": true, "license": "MIT", + "optional": true, + "os": [ + "win32" + ], "engines": { - "node": ">= 8" + "node": "^20.19.0 || >=22.12.0" } }, - "node_modules/@nodelib/fs.walk": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", - "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", + "node_modules/@oxfmt/binding-win32-ia32-msvc": { + "version": "0.40.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-0.40.0.tgz", + "integrity": "sha512-7rPemBJjqm5Gkv6ZRCPvK8lE6AqQ/2z31DRdWazyx2ZvaSgL7QGofHXHNouRpPvNsT9yxRNQJgigsWkc+0qg4w==", + "cpu": [ + "ia32" + ], "dev": true, "license": "MIT", - "dependencies": { - "@nodelib/fs.scandir": "2.1.5", - "fastq": "^1.6.0" - }, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-win32-x64-msvc": { + "version": "0.40.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-x64-msvc/-/binding-win32-x64-msvc-0.40.0.tgz", + "integrity": "sha512-/Zmj0yTYSvmha6TG1QnoLqVT7ZMRDqXvFXXBQpIjteEwx9qvUYMBH2xbiOFhDeMUJkGwC3D6fdKsFtaqUvkwNA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-android-arm-eabi": { + "version": "1.55.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm-eabi/-/binding-android-arm-eabi-1.55.0.tgz", + "integrity": "sha512-NhvgAhncTSOhRahQSCnkK/4YIGPjTmhPurQQ2dwt2IvwCMTvZRW5vF2K10UBOxFve4GZDMw6LtXZdC2qeuYIVQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-android-arm64": { + "version": "1.55.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm64/-/binding-android-arm64-1.55.0.tgz", + "integrity": "sha512-P9iWRh+Ugqhg+D7rkc7boHX8o3H2h7YPcZHQIgvVBgnua5tk4LR2L+IBlreZs58/95cd2x3/004p5VsQM9z4SA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-darwin-arm64": { + "version": "1.55.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-arm64/-/binding-darwin-arm64-1.55.0.tgz", + "integrity": "sha512-esakkJIt7WFAhT30P/Qzn96ehFpzdZ1mNuzpOb8SCW7lI4oB8VsyQnkSHREM671jfpuBb/o2ppzBCx5l0jpgMA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-darwin-x64": { + "version": "1.55.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-x64/-/binding-darwin-x64-1.55.0.tgz", + "integrity": "sha512-xDMFRCCAEK9fOH6As2z8ELsC+VDGSFRHwIKVSilw+xhgLwTDFu37rtmRbmUlx8rRGS6cWKQPTc47AVxAZEVVPQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-freebsd-x64": { + "version": "1.55.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-freebsd-x64/-/binding-freebsd-x64-1.55.0.tgz", + "integrity": "sha512-mYZqnwUD7ALCRxGenyLd1uuG+rHCL+OTT6S8FcAbVm/ZT2AZMGjvibp3F6k1SKOb2aeqFATmwRykrE41Q0GWVw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-arm-gnueabihf": { + "version": "1.55.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.55.0.tgz", + "integrity": "sha512-LcX6RYcF9vL9ESGwJW3yyIZ/d/ouzdOKXxCdey1q0XJOW1asrHsIg5MmyKdEBR4plQx+shvYeQne7AzW5f3T1w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-arm-musleabihf": { + "version": "1.55.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-1.55.0.tgz", + "integrity": "sha512-C+8GS1rPtK+dI7mJFkqoRBkDuqbrNihnyYQsJPS9ez+8zF9JzfvU19lawqt4l/Y23o5uQswE/DORa8aiXUih3w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-arm64-gnu": { + "version": "1.55.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.55.0.tgz", + "integrity": "sha512-ErLE4XbmcCopA4/CIDiH6J1IAaDOMnf/KSx/aFObs4/OjAAM3sFKWGZ57pNOMxhhyBdcmcXwYymph9GwcpcqgQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-arm64-musl": { + "version": "1.55.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.55.0.tgz", + "integrity": "sha512-/kp65avi6zZfqEng56TTuhiy3P/3pgklKIdf38yvYeJ9/PgEeRA2A2AqKAKbZBNAqUzrzHhz9jF6j/PZvhJzTQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-ppc64-gnu": { + "version": "1.55.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.55.0.tgz", + "integrity": "sha512-A6pTdXwcEEwL/nmz0eUJ6WxmxcoIS+97GbH96gikAyre3s5deC7sts38ZVVowjS2QQFuSWkpA4ZmQC0jZSNvJQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-riscv64-gnu": { + "version": "1.55.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-1.55.0.tgz", + "integrity": "sha512-clj0lnIN+V52G9tdtZl0LbdTSurnZ1NZj92Je5X4lC7gP5jiCSW+Y/oiDiSauBAD4wrHt2S7nN3pA0zfKYK/6Q==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-riscv64-musl": { + "version": "1.55.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-1.55.0.tgz", + "integrity": "sha512-NNu08pllN5x/O94/sgR3DA8lbrGBnTHsINZZR0hcav1sj79ksTiKKm1mRzvZvacwQ0hUnGinFo+JO75ok2PxYg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-s390x-gnu": { + "version": "1.55.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.55.0.tgz", + "integrity": "sha512-BvfQz3PRlWZRoEZ17dZCqgQsMRdpzGZomJkVATwCIGhHVVeHJMQdmdXPSjcT1DCNUrOjXnVyj1RGDj5+/Je2+Q==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-x64-gnu": { + "version": "1.55.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.55.0.tgz", + "integrity": "sha512-ngSOoFCSBMKVQd24H8zkbcBNc7EHhjnF1sv3mC9NNXQ/4rRjI/4Dj9+9XoDZeFEkF1SX1COSBXF1b2Pr9rqdEw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-x64-musl": { + "version": "1.55.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-musl/-/binding-linux-x64-musl-1.55.0.tgz", + "integrity": "sha512-BDpP7W8GlaG7BR6QjGZAleYzxoyKc/D24spZIF2mB3XsfALQJJT/OBmP8YpeTb1rveFSBHzl8T7l0aqwkWNdGA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-openharmony-arm64": { + "version": "1.55.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-openharmony-arm64/-/binding-openharmony-arm64-1.55.0.tgz", + "integrity": "sha512-PS6GFvmde/pc3fCA2Srt51glr8Lcxhpf6WIBFfLphndjRrD34NEcses4TSxQrEcxYo6qVywGfylM0ZhSCF2gGA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-win32-arm64-msvc": { + "version": "1.55.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.55.0.tgz", + "integrity": "sha512-P6JcLJGs/q1UOvDLzN8otd9JsH4tsuuPDv+p7aHqHM3PrKmYdmUvkNj4K327PTd35AYcznOCN+l4ZOaq76QzSw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-win32-ia32-msvc": { + "version": "1.55.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-1.55.0.tgz", + "integrity": "sha512-gzkk4zE2zsE+WmRxFOiAZHpCpUNDFytEakqNXoNHW+PnYEOTPKDdW6nrzgSeTbGKVPXNAKQnRnMgrh7+n3Xueg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], "engines": { - "node": ">= 8" + "node": "^20.19.0 || >=22.12.0" } }, - "node_modules/@oxc-project/types": { - "version": "0.46.0", - "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.46.0.tgz", - "integrity": "sha512-BHU261xrLasw04d2cToR36F6VV0T7t62rtQUprvBRL4Uru9P23moMkDmZUMSZSQj0fIUTA3oTOTwQ7cc4Av/iw==", + "node_modules/@oxlint/binding-win32-x64-msvc": { + "version": "1.55.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.55.0.tgz", + "integrity": "sha512-ZFALNow2/og75gvYzNP7qe+rREQ5xunktwA+lgykoozHZ6hw9bqg4fn5j2UvG4gIn1FXqrZHkOAXuPf5+GOYTQ==", + "cpu": [ + "x64" + ], "dev": true, "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/Boshen" + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" } }, "node_modules/@pkgjs/parseargs": { @@ -387,23 +802,27 @@ "node": ">=14" } }, - "node_modules/@pkgr/core": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/@pkgr/core/-/core-0.1.1.tgz", - "integrity": "sha512-cq8o4cWH0ibXh9VGi5P20Tu9XF/0fFXl9EUinr9QfTM7a7p0oTA4iJRCQWppXR1Pg8dSM0UCItCkPwsk9qWWYA==", + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.0.0-rc.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.0.0-rc.9.tgz", + "integrity": "sha512-lcJL0bN5hpgJfSIz/8PIf02irmyL43P+j1pTCfbD1DbLkmGRuFIA4DD3B3ZOvGqG0XiVvRznbKtN0COQVaKUTg==", + "cpu": [ + "arm64" + ], "dev": true, "license": "MIT", + "optional": true, + "os": [ + "android" + ], "engines": { - "node": "^12.20.0 || ^14.18.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/unts" + "node": "^20.19.0 || >=22.12.0" } }, "node_modules/@rolldown/binding-darwin-arm64": { - "version": "1.0.0-beta.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.0.0-beta.3.tgz", - "integrity": "sha512-qB1ofY+09nDYYaEi5kVsjqy4cKsVPI9E5bkV46CRrQsTF/BBM29wpvaj8qTRQ41qwInFA5kmqnVVr35yfH7ddw==", + "version": "1.0.0-rc.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.0.0-rc.9.tgz", + "integrity": "sha512-J7Zk3kLYFsLtuH6U+F4pS2sYVzac0qkjcO5QxHS7OS7yZu2LRs+IXo+uvJ/mvpyUljDJ3LROZPoQfgBIpCMhdQ==", "cpu": [ "arm64" ], @@ -412,12 +831,15 @@ "optional": true, "os": [ "darwin" - ] + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } }, "node_modules/@rolldown/binding-darwin-x64": { - "version": "1.0.0-beta.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.0.0-beta.3.tgz", - "integrity": "sha512-Fk+rqyeszMaZK12wItqFDXdUadg+TVQqOPh0fdaCefVebd29N+9fpFrARyo8gReyt/lcnEN4nWgdn7l99R70QA==", + "version": "1.0.0-rc.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.0.0-rc.9.tgz", + "integrity": "sha512-iwtmmghy8nhfRGeNAIltcNXzD0QMNaaA5U/NyZc1Ia4bxrzFByNMDoppoC+hl7cDiUq5/1CnFthpT9n+UtfFyg==", "cpu": [ "x64" ], @@ -426,12 +848,15 @@ "optional": true, "os": [ "darwin" - ] + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } }, "node_modules/@rolldown/binding-freebsd-x64": { - "version": "1.0.0-beta.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.0.0-beta.3.tgz", - "integrity": "sha512-B7QzJKu53MB/hvwO276AsyxN+p9lfgCkIO94TQB6t3auq3pDCC6u6gdRI1Ydwn6/gpMLiUNCW4mnpxCE5fE5tg==", + "version": "1.0.0-rc.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.0.0-rc.9.tgz", + "integrity": "sha512-DLFYI78SCiZr5VvdEplsVC2Vx53lnA4/Ga5C65iyldMVaErr86aiqCoNBLl92PXPfDtUYjUh+xFFor40ueNs4Q==", "cpu": [ "x64" ], @@ -440,12 +865,15 @@ "optional": true, "os": [ "freebsd" - ] + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } }, "node_modules/@rolldown/binding-linux-arm-gnueabihf": { - "version": "1.0.0-beta.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.0.0-beta.3.tgz", - "integrity": "sha512-NB5JrXP5dAigDTbvVc6VWiOY3Rr/0u1pi/9LYoBtMYiST7hYOrBPO9lvDF9w/23yKCr1+8PF4wFGR/YxKTNN5Q==", + "version": "1.0.0-rc.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.0.0-rc.9.tgz", + "integrity": "sha512-CsjTmTwd0Hri6iTw/DRMK7kOZ7FwAkrO4h8YWKoX/kcj833e4coqo2wzIFywtch/8Eb5enQ/lwLM7w6JX1W5RQ==", "cpu": [ "arm" ], @@ -454,12 +882,15 @@ "optional": true, "os": [ "linux" - ] + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } }, "node_modules/@rolldown/binding-linux-arm64-gnu": { - "version": "1.0.0-beta.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.0.0-beta.3.tgz", - "integrity": "sha512-bYyZLXzJ2boZ7CdUuCSAaTcWkVKcBUOL+B86zv+tRyrtk4BIpHF+L+vOg5uPD/PHwrIglxAno5MN4NnpkUj5fQ==", + "version": "1.0.0-rc.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.0.0-rc.9.tgz", + "integrity": "sha512-2x9O2JbSPxpxMDhP9Z74mahAStibTlrBMW0520+epJH5sac7/LwZW5Bmg/E6CXuEF53JJFW509uP+lSedaUNxg==", "cpu": [ "arm64" ], @@ -468,12 +899,15 @@ "optional": true, "os": [ "linux" - ] + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } }, "node_modules/@rolldown/binding-linux-arm64-musl": { - "version": "1.0.0-beta.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.0.0-beta.3.tgz", - "integrity": "sha512-t/jaaFrCSvwX2075jRfa2bwAcsuTtY1/sIT4XqsDg2MVxWQtaUyBx5Mi0pqZKTjdOPnL+f/zoUC9dxT2lUpNmw==", + "version": "1.0.0-rc.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.0.0-rc.9.tgz", + "integrity": "sha512-JA1QRW31ogheAIRhIg9tjMfsYbglXXYGNPLdPEYrwFxdbkQCAzvpSCSHCDWNl4hTtrol8WeboCSEpjdZK8qrCg==", "cpu": [ "arm64" ], @@ -482,12 +916,49 @@ "optional": true, "os": [ "linux" - ] + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.0.0-rc.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.0.0-rc.9.tgz", + "integrity": "sha512-aOKU9dJheda8Kj8Y3w9gnt9QFOO+qKPAl8SWd7JPHP+Cu0EuDAE5wokQubLzIDQWg2myXq2XhTpOVS07qqvT+w==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.0.0-rc.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.0.0-rc.9.tgz", + "integrity": "sha512-OalO94fqj7IWRn3VdXWty75jC5dk4C197AWEuMhIpvVv2lw9fiPhud0+bW2ctCxb3YoBZor71QHbY+9/WToadA==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } }, "node_modules/@rolldown/binding-linux-x64-gnu": { - "version": "1.0.0-beta.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.0.0-beta.3.tgz", - "integrity": "sha512-EeDNLPU0Xw8ByRWxNLO30AF0fKYkdb/6rH5G073NFBDkj7ggYR/CvsNBjtDeCJ7+I6JG4xUjete2+VeV+GQjiA==", + "version": "1.0.0-rc.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.0.0-rc.9.tgz", + "integrity": "sha512-cVEl1vZtBsBZna3YMjGXNvnYYrOJ7RzuWvZU0ffvJUexWkukMaDuGhUXn0rjnV0ptzGVkvc+vW9Yqy6h8YX4pg==", "cpu": [ "x64" ], @@ -496,12 +967,15 @@ "optional": true, "os": [ "linux" - ] + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } }, "node_modules/@rolldown/binding-linux-x64-musl": { - "version": "1.0.0-beta.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.0.0-beta.3.tgz", - "integrity": "sha512-iTcAj8FKac3nyQhvFuqKt6Xqu9YNDbe1ew6US2OSN4g3zwfujgylaRCitEG+Uzd7AZfSVVLAfqrxKMa36Sj9Mg==", + "version": "1.0.0-rc.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.0.0-rc.9.tgz", + "integrity": "sha512-UzYnKCIIc4heAKgI4PZ3dfBGUZefGCJ1TPDuLHoCzgrMYPb5Rv6TLFuYtyM4rWyHM7hymNdsg5ik2C+UD9VDbA==", "cpu": [ "x64" ], @@ -510,12 +984,32 @@ "optional": true, "os": [ "linux" - ] + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.0.0-rc.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.0.0-rc.9.tgz", + "integrity": "sha512-+6zoiF+RRyf5cdlFQP7nm58mq7+/2PFaY2DNQeD4B87N36JzfF/l9mdBkkmTvSYcYPE8tMh/o3cRlsx1ldLfog==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } }, "node_modules/@rolldown/binding-wasm32-wasi": { - "version": "1.0.0-beta.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.0.0-beta.3.tgz", - "integrity": "sha512-sYgbsbyspvVZ2zplqsTxjf2N3e8UQGQnSsN5u4bMX461gY5vAsjUiA4nf1/ztDBMHWT79lF2QNx4csjnjSxMlA==", + "version": "1.0.0-rc.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.0.0-rc.9.tgz", + "integrity": "sha512-rgFN6sA/dyebil3YTlL2evvi/M+ivhfnyxec7AccTpRPccno/rPoNlqybEZQBkcbZu8Hy+eqNJCqfBR8P7Pg8g==", "cpu": [ "wasm32" ], @@ -523,16 +1017,16 @@ "license": "MIT", "optional": true, "dependencies": { - "@napi-rs/wasm-runtime": "^0.2.4" + "@napi-rs/wasm-runtime": "^1.1.1" }, "engines": { - "node": ">=14.21.3" + "node": ">=14.0.0" } }, "node_modules/@rolldown/binding-win32-arm64-msvc": { - "version": "1.0.0-beta.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.0.0-beta.3.tgz", - "integrity": "sha512-qszMtrWybBLTFaew2WgEBRMlz1B/V8XxU87uezXlKcLW36aoRWR8LspZvqqoBkvJzbQtfOgm1HdTIk/v3Rn7QQ==", + "version": "1.0.0-rc.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.0.0-rc.9.tgz", + "integrity": "sha512-lHVNUG/8nlF1IQk1C0Ci574qKYyty2goMiPlRqkC5R+3LkXDkL5Dhx8ytbxq35m+pkHVIvIxviD+TWLdfeuadA==", "cpu": [ "arm64" ], @@ -541,26 +1035,15 @@ "optional": true, "os": [ "win32" - ] - }, - "node_modules/@rolldown/binding-win32-ia32-msvc": { - "version": "1.0.0-beta.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-1.0.0-beta.3.tgz", - "integrity": "sha512-J+mzAO68VK91coLVuUln/XN0ummIEOODyupZ2BmXY8suBHPVAyLLAP54rlucBPQmzU8fI6DXM2bl2whZ+KEXpQ==", - "cpu": [ - "ia32" ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] + "engines": { + "node": "^20.19.0 || >=22.12.0" + } }, "node_modules/@rolldown/binding-win32-x64-msvc": { - "version": "1.0.0-beta.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.0.0-beta.3.tgz", - "integrity": "sha512-r06rAi+1eStgavGnw+2y4F7gpb0w9ocnKk0Ir7LmegLAkMZ/v4Fjo9jZUrLTLtmI36108v1uvUPrIAFzFOWE7g==", + "version": "1.0.0-rc.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.0.0-rc.9.tgz", + "integrity": "sha512-G0oA4+w1iY5AGi5HcDTxWsoxF509hrFIPB2rduV5aDqS9FtDg1CAfa7V34qImbjfhIcA8C+RekocJZA96EarwQ==", "cpu": [ "x64" ], @@ -569,12 +1052,22 @@ "optional": true, "os": [ "win32" - ] + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.0-rc.9", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.9.tgz", + "integrity": "sha512-w6oiRWgEBl04QkFZgmW+jnU1EC9b57Oihi2ot3HNWIQRqgHp5PnYDia5iZ5FF7rpa4EQdiqMDXjlqKGXBhsoXw==", + "dev": true, + "license": "MIT" }, "node_modules/@tybys/wasm-util": { - "version": "0.9.0", - "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.9.0.tgz", - "integrity": "sha512-6+7nlbMVX/PVDCwaIQ8nTOPveOcFLSt8GcXdx8hD0bt39uWxYT88uXzqTd4fTvqta7oeUJqudepapKNt2DYJFw==", + "version": "0.10.1", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.1.tgz", + "integrity": "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg==", "dev": true, "license": "MIT", "optional": true, @@ -583,16 +1076,9 @@ } }, "node_modules/@types/emscripten": { - "version": "1.40.0", - "resolved": "https://registry.npmjs.org/@types/emscripten/-/emscripten-1.40.0.tgz", - "integrity": "sha512-MD2JJ25S4tnjnhjWyalMS6K6p0h+zQV6+Ylm+aGbiS8tSn/aHLSGNzBgduj6FB4zH0ax2GRMGYi/8G1uOxhXWA==", - "license": "MIT" - }, - "node_modules/@types/estree": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.6.tgz", - "integrity": "sha512-AYnb1nQyY49te+VRAVgmzfcgjYS91mY5P0TKUDCLEM+gNnA+3T6rWITXRLYCpahpqSQbN5cE+gHpnPyXjHWxcw==", - "dev": true, + "version": "1.41.5", + "resolved": "https://registry.npmjs.org/@types/emscripten/-/emscripten-1.41.5.tgz", + "integrity": "sha512-cMQm7pxu6BxtHyqJ7mQZ2kXWV5SLmugybFdHCBbJ5eHzOo6VhBckEgAT3//rP5FwPHNPeEiq4SmQ5ucBwsOo4Q==", "license": "MIT" }, "node_modules/@types/fs-extra": { @@ -616,13 +1102,6 @@ "@types/node": "*" } }, - "node_modules/@types/json-schema": { - "version": "7.0.15", - "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", - "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", - "dev": true, - "license": "MIT" - }, "node_modules/@types/minimatch": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/@types/minimatch/-/minimatch-5.1.2.tgz", @@ -631,266 +1110,13 @@ "license": "MIT" }, "node_modules/@types/node": { - "version": "22.13.4", - "resolved": "https://registry.npmjs.org/@types/node/-/node-22.13.4.tgz", - "integrity": "sha512-ywP2X0DYtX3y08eFVx5fNIw7/uIv8hYUKgXoK8oayJlLnKcRfEYCxWMVE1XagUdVtCJlZT1AU4LXEABW+L1Peg==", - "dev": true, - "license": "MIT", - "dependencies": { - "undici-types": "~6.20.0" - } - }, - "node_modules/@typescript-eslint/eslint-plugin": { - "version": "8.24.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.24.1.tgz", - "integrity": "sha512-ll1StnKtBigWIGqvYDVuDmXJHVH4zLVot1yQ4fJtLpL7qacwkxJc1T0bptqw+miBQ/QfUbhl1TcQ4accW5KUyA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@eslint-community/regexpp": "^4.10.0", - "@typescript-eslint/scope-manager": "8.24.1", - "@typescript-eslint/type-utils": "8.24.1", - "@typescript-eslint/utils": "8.24.1", - "@typescript-eslint/visitor-keys": "8.24.1", - "graphemer": "^1.4.0", - "ignore": "^5.3.1", - "natural-compare": "^1.4.0", - "ts-api-utils": "^2.0.1" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "@typescript-eslint/parser": "^8.0.0 || ^8.0.0-alpha.0", - "eslint": "^8.57.0 || ^9.0.0", - "typescript": ">=4.8.4 <5.8.0" - } - }, - "node_modules/@typescript-eslint/parser": { - "version": "8.24.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.24.1.tgz", - "integrity": "sha512-Tqoa05bu+t5s8CTZFaGpCH2ub3QeT9YDkXbPd3uQ4SfsLoh1/vv2GEYAioPoxCWJJNsenXlC88tRjwoHNts1oQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/scope-manager": "8.24.1", - "@typescript-eslint/types": "8.24.1", - "@typescript-eslint/typescript-estree": "8.24.1", - "@typescript-eslint/visitor-keys": "8.24.1", - "debug": "^4.3.4" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "eslint": "^8.57.0 || ^9.0.0", - "typescript": ">=4.8.4 <5.8.0" - } - }, - "node_modules/@typescript-eslint/scope-manager": { - "version": "8.24.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.24.1.tgz", - "integrity": "sha512-OdQr6BNBzwRjNEXMQyaGyZzgg7wzjYKfX2ZBV3E04hUCBDv3GQCHiz9RpqdUIiVrMgJGkXm3tcEh4vFSHreS2Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/types": "8.24.1", - "@typescript-eslint/visitor-keys": "8.24.1" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "node_modules/@typescript-eslint/type-utils": { - "version": "8.24.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.24.1.tgz", - "integrity": "sha512-/Do9fmNgCsQ+K4rCz0STI7lYB4phTtEXqqCAs3gZW0pnK7lWNkvWd5iW545GSmApm4AzmQXmSqXPO565B4WVrw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/typescript-estree": "8.24.1", - "@typescript-eslint/utils": "8.24.1", - "debug": "^4.3.4", - "ts-api-utils": "^2.0.1" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "eslint": "^8.57.0 || ^9.0.0", - "typescript": ">=4.8.4 <5.8.0" - } - }, - "node_modules/@typescript-eslint/types": { - "version": "8.24.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.24.1.tgz", - "integrity": "sha512-9kqJ+2DkUXiuhoiYIUvIYjGcwle8pcPpdlfkemGvTObzgmYfJ5d0Qm6jwb4NBXP9W1I5tss0VIAnWFumz3mC5A==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "node_modules/@typescript-eslint/typescript-estree": { - "version": "8.24.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.24.1.tgz", - "integrity": "sha512-UPyy4MJ/0RE648DSKQe9g0VDSehPINiejjA6ElqnFaFIhI6ZEiZAkUI0D5MCk0bQcTf/LVqZStvQ6K4lPn/BRg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/types": "8.24.1", - "@typescript-eslint/visitor-keys": "8.24.1", - "debug": "^4.3.4", - "fast-glob": "^3.3.2", - "is-glob": "^4.0.3", - "minimatch": "^9.0.4", - "semver": "^7.6.0", - "ts-api-utils": "^2.0.1" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "typescript": ">=4.8.4 <5.8.0" - } - }, - "node_modules/@typescript-eslint/utils": { - "version": "8.24.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.24.1.tgz", - "integrity": "sha512-OOcg3PMMQx9EXspId5iktsI3eMaXVwlhC8BvNnX6B5w9a4dVgpkQZuU8Hy67TolKcl+iFWq0XX+jbDGN4xWxjQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@eslint-community/eslint-utils": "^4.4.0", - "@typescript-eslint/scope-manager": "8.24.1", - "@typescript-eslint/types": "8.24.1", - "@typescript-eslint/typescript-estree": "8.24.1" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "eslint": "^8.57.0 || ^9.0.0", - "typescript": ">=4.8.4 <5.8.0" - } - }, - "node_modules/@typescript-eslint/visitor-keys": { - "version": "8.24.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.24.1.tgz", - "integrity": "sha512-EwVHlp5l+2vp8CoqJm9KikPZgi3gbdZAtabKT9KPShGeOcJhsv4Zdo3oc8T8I0uKEmYoU4ItyxbptjF08enaxg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/types": "8.24.1", - "eslint-visitor-keys": "^4.2.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.0.tgz", - "integrity": "sha512-UyLnSehNt62FFhSwjZlHmeokpRK59rcz29j+F1/aDgbkbRTk7wIc9XzdoasMUbRNKDM0qQt/+BJ4BrpFeABemw==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/@valibot/to-json-schema": { - "version": "1.0.0-beta.4", - "resolved": "https://registry.npmjs.org/@valibot/to-json-schema/-/to-json-schema-1.0.0-beta.4.tgz", - "integrity": "sha512-wXBdCyoqec+NLCl5ihitXzZXD4JAjPK3+HfskSXzfhiNFvKje0A/v1LygqKidUgIbaJtREmq/poJGbaS/0MKuQ==", - "dev": true, - "license": "MIT", - "peerDependencies": { - "valibot": "^1.0.0 || ^1.0.0-beta.5 || ^1.0.0-rc" - } - }, - "node_modules/acorn": { - "version": "8.14.0", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.14.0.tgz", - "integrity": "sha512-cl669nCJTZBsL97OF4kUQm5g5hC2uihk0NxY3WENAC0TYdILVkAyHymAntgxGkl7K+t0cXIrH5siy5S4XkFycA==", - "dev": true, - "license": "MIT", - "bin": { - "acorn": "bin/acorn" - }, - "engines": { - "node": ">=0.4.0" - } - }, - "node_modules/acorn-jsx": { - "version": "5.3.2", - "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", - "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", - "dev": true, - "license": "MIT", - "peerDependencies": { - "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" - } - }, - "node_modules/ajv": { - "version": "6.12.6", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", - "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "version": "25.5.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-25.5.0.tgz", + "integrity": "sha512-jp2P3tQMSxWugkCUKLRPVUpGaL5MVFwF8RDuSRztfwgN1wmqJeMSbKlnEtQqU8UrhTmzEmZdu2I6v2dpp7XIxw==", "dev": true, "license": "MIT", "dependencies": { - "fast-deep-equal": "^3.1.1", - "fast-json-stable-stringify": "^2.0.0", - "json-schema-traverse": "^0.4.1", - "uri-js": "^4.2.2" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/epoberezkin" - } - }, - "node_modules/ansi-colors": { - "version": "4.1.3", - "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-4.1.3.tgz", - "integrity": "sha512-/6w/C21Pm1A7aZitlI5Ni/2J6FFQN8i1Cvz3kHABAAbw93v/NlvKdVOqz7CCWz/3iv/JplRSEEZ83XION15ovw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" + "undici-types": "~7.18.0" } }, "node_modules/ansi-regex": { @@ -922,33 +1148,6 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, - "node_modules/anymatch": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", - "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", - "dev": true, - "license": "ISC", - "dependencies": { - "normalize-path": "^3.0.0", - "picomatch": "^2.0.4" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/anymatch/node_modules/picomatch": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", - "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8.6" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, "node_modules/argparse": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", @@ -963,17 +1162,7 @@ "dev": true, "license": "MIT", "engines": { - "node": ">=8" - } - }, - "node_modules/assertion-error": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", - "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" + "node": ">=8" } }, "node_modules/balanced-match": { @@ -983,19 +1172,6 @@ "dev": true, "license": "MIT" }, - "node_modules/binary-extensions": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", - "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/brace-expansion": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", @@ -1026,16 +1202,6 @@ "dev": true, "license": "ISC" }, - "node_modules/callsites": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", - "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, "node_modules/camelcase": { "version": "6.3.0", "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz", @@ -1050,33 +1216,27 @@ } }, "node_modules/chai": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/chai/-/chai-5.2.0.tgz", - "integrity": "sha512-mCuXncKXk5iCLhfhwTc0izo0gtEmpz5CtG2y8GiOINBlMVS6v8TMRc5TaLWKS6692m9+dVVfzgeVxR5UxWHTYw==", + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz", + "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==", "dev": true, "license": "MIT", - "dependencies": { - "assertion-error": "^2.0.1", - "check-error": "^2.1.1", - "deep-eql": "^5.0.1", - "loupe": "^3.1.0", - "pathval": "^2.0.0" - }, + "peer": true, "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/chai-as-promised": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/chai-as-promised/-/chai-as-promised-8.0.1.tgz", - "integrity": "sha512-OIEJtOL8xxJSH8JJWbIoRjybbzR52iFuDHuF8eb+nTPD6tgXLjRqsgnUGqQfFODxYvq5QdirT0pN9dZ0+Gz6rA==", + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/chai-as-promised/-/chai-as-promised-8.0.2.tgz", + "integrity": "sha512-1GadL+sEJVLzDjcawPM4kjfnL+p/9vrxiEUonowKOAzvVg0PixJUdtuDzdkDeQhK3zfOE76GqGkZIQ7/Adcrqw==", "dev": true, "license": "MIT", "dependencies": { - "check-error": "^2.0.0" + "check-error": "^2.1.1" }, "peerDependencies": { - "chai": ">= 2.1.2 < 6" + "chai": ">= 2.1.2 < 7" } }, "node_modules/chalk": { @@ -1107,41 +1267,19 @@ } }, "node_modules/chokidar": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", - "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz", + "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==", "dev": true, "license": "MIT", "dependencies": { - "anymatch": "~3.1.2", - "braces": "~3.0.2", - "glob-parent": "~5.1.2", - "is-binary-path": "~2.1.0", - "is-glob": "~4.0.1", - "normalize-path": "~3.0.0", - "readdirp": "~3.6.0" + "readdirp": "^4.0.1" }, "engines": { - "node": ">= 8.10.0" + "node": ">= 14.16.0" }, "funding": { "url": "https://paulmillr.com/funding/" - }, - "optionalDependencies": { - "fsevents": "~2.3.2" - } - }, - "node_modules/chokidar/node_modules/glob-parent": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", - "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", - "dev": true, - "license": "ISC", - "dependencies": { - "is-glob": "^4.0.1" - }, - "engines": { - "node": ">= 6" } }, "node_modules/cliui": { @@ -1302,27 +1440,10 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/deep-eql": { - "version": "5.0.2", - "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz", - "integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/deep-is": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", - "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", - "dev": true, - "license": "MIT" - }, "node_modules/diff": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/diff/-/diff-5.2.0.tgz", - "integrity": "sha512-uIFDxqpRZGZ6ThOk84hEfqWoHx2devRFvpTZcTHur85vImfaxUbTW9Ryh4CpCuDnToOP1CEtXKIgytHBPVff5A==", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/diff/-/diff-7.0.0.tgz", + "integrity": "sha512-PJWHUb1RFevKCwaFA9RlG5tCd+FO5iRh9A8HEtkmBH2Li03iJriB6m6JIN4rGz3K3JLawI7/veA1xzRKP6ISBw==", "dev": true, "license": "BSD-3-Clause", "engines": { @@ -1379,291 +1500,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/eslint": { - "version": "9.20.1", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.20.1.tgz", - "integrity": "sha512-m1mM33o6dBUjxl2qb6wv6nGNwCAsns1eKtaQ4l/NPHeTvhiUPbtdfMyktxN4B3fgHIgsYh1VT3V9txblpQHq+g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@eslint-community/eslint-utils": "^4.2.0", - "@eslint-community/regexpp": "^4.12.1", - "@eslint/config-array": "^0.19.0", - "@eslint/core": "^0.11.0", - "@eslint/eslintrc": "^3.2.0", - "@eslint/js": "9.20.0", - "@eslint/plugin-kit": "^0.2.5", - "@humanfs/node": "^0.16.6", - "@humanwhocodes/module-importer": "^1.0.1", - "@humanwhocodes/retry": "^0.4.1", - "@types/estree": "^1.0.6", - "@types/json-schema": "^7.0.15", - "ajv": "^6.12.4", - "chalk": "^4.0.0", - "cross-spawn": "^7.0.6", - "debug": "^4.3.2", - "escape-string-regexp": "^4.0.0", - "eslint-scope": "^8.2.0", - "eslint-visitor-keys": "^4.2.0", - "espree": "^10.3.0", - "esquery": "^1.5.0", - "esutils": "^2.0.2", - "fast-deep-equal": "^3.1.3", - "file-entry-cache": "^8.0.0", - "find-up": "^5.0.0", - "glob-parent": "^6.0.2", - "ignore": "^5.2.0", - "imurmurhash": "^0.1.4", - "is-glob": "^4.0.0", - "json-stable-stringify-without-jsonify": "^1.0.1", - "lodash.merge": "^4.6.2", - "minimatch": "^3.1.2", - "natural-compare": "^1.4.0", - "optionator": "^0.9.3" - }, - "bin": { - "eslint": "bin/eslint.js" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "url": "https://eslint.org/donate" - }, - "peerDependencies": { - "jiti": "*" - }, - "peerDependenciesMeta": { - "jiti": { - "optional": true - } - } - }, - "node_modules/eslint-config-prettier": { - "version": "10.0.1", - "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-10.0.1.tgz", - "integrity": "sha512-lZBts941cyJyeaooiKxAtzoPHTN+GbQTJFAIdQbRhA4/8whaAraEh47Whw/ZFfrjNSnlAxqfm9i0XVAEkULjCw==", - "dev": true, - "license": "MIT", - "bin": { - "eslint-config-prettier": "build/bin/cli.js" - }, - "peerDependencies": { - "eslint": ">=7.0.0" - } - }, - "node_modules/eslint-plugin-prettier": { - "version": "5.2.3", - "resolved": "https://registry.npmjs.org/eslint-plugin-prettier/-/eslint-plugin-prettier-5.2.3.tgz", - "integrity": "sha512-qJ+y0FfCp/mQYQ/vWQ3s7eUlFEL4PyKfAJxsnYTJ4YT73nsJBWqmEpFryxV9OeUiqmsTsYJ5Y+KDNaeP31wrRw==", - "dev": true, - "license": "MIT", - "dependencies": { - "prettier-linter-helpers": "^1.0.0", - "synckit": "^0.9.1" - }, - "engines": { - "node": "^14.18.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint-plugin-prettier" - }, - "peerDependencies": { - "@types/eslint": ">=8.0.0", - "eslint": ">=8.0.0", - "eslint-config-prettier": "*", - "prettier": ">=3.0.0" - }, - "peerDependenciesMeta": { - "@types/eslint": { - "optional": true - }, - "eslint-config-prettier": { - "optional": true - } - } - }, - "node_modules/eslint-plugin-simple-import-sort": { - "version": "12.1.1", - "resolved": "https://registry.npmjs.org/eslint-plugin-simple-import-sort/-/eslint-plugin-simple-import-sort-12.1.1.tgz", - "integrity": "sha512-6nuzu4xwQtE3332Uz0to+TxDQYRLTKRESSc2hefVT48Zc8JthmN23Gx9lnYhu0FtkRSL1oxny3kJ2aveVhmOVA==", - "dev": true, - "license": "MIT", - "peerDependencies": { - "eslint": ">=5.0.0" - } - }, - "node_modules/eslint-scope": { - "version": "8.2.0", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.2.0.tgz", - "integrity": "sha512-PHlWUfG6lvPc3yvP5A4PNyBL1W8fkDUccmI21JUu/+GKZBoH/W5u6usENXUrWFRsyoW5ACUjFGgAFQp5gUlb/A==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "esrecurse": "^4.3.0", - "estraverse": "^5.2.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/eslint-visitor-keys": { - "version": "3.4.3", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", - "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/eslint/node_modules/@eslint/core": { - "version": "0.11.0", - "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.11.0.tgz", - "integrity": "sha512-DWUB2pksgNEb6Bz2fggIy1wh6fGgZP4Xyy/Mt0QZPiloKKXerbqq9D3SBQTlCRYOrcRPu4vuz+CGjwdfqxnoWA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@types/json-schema": "^7.0.15" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - } - }, - "node_modules/eslint/node_modules/brace-expansion": { - "version": "1.1.11", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", - "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "node_modules/eslint/node_modules/eslint-visitor-keys": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.0.tgz", - "integrity": "sha512-UyLnSehNt62FFhSwjZlHmeokpRK59rcz29j+F1/aDgbkbRTk7wIc9XzdoasMUbRNKDM0qQt/+BJ4BrpFeABemw==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/eslint/node_modules/minimatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", - "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", - "dev": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^1.1.7" - }, - "engines": { - "node": "*" - } - }, - "node_modules/espree": { - "version": "10.3.0", - "resolved": "https://registry.npmjs.org/espree/-/espree-10.3.0.tgz", - "integrity": "sha512-0QYC8b24HWY8zjRnDTL6RiHfDbAWn63qb4LMj1Z4b076A4une81+z03Kg7l7mn/48PUTqoLptSXez8oknU8Clg==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "acorn": "^8.14.0", - "acorn-jsx": "^5.3.2", - "eslint-visitor-keys": "^4.2.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/espree/node_modules/eslint-visitor-keys": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.0.tgz", - "integrity": "sha512-UyLnSehNt62FFhSwjZlHmeokpRK59rcz29j+F1/aDgbkbRTk7wIc9XzdoasMUbRNKDM0qQt/+BJ4BrpFeABemw==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/esquery": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.6.0.tgz", - "integrity": "sha512-ca9pw9fomFcKPvFLXhBKUK90ZvGibiGOvRJNbjljY7s7uq/5YO4BOzcYtJqExdx99rF6aAcnRxHmcUHcz6sQsg==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "estraverse": "^5.1.0" - }, - "engines": { - "node": ">=0.10" - } - }, - "node_modules/esrecurse": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", - "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "estraverse": "^5.2.0" - }, - "engines": { - "node": ">=4.0" - } - }, - "node_modules/estraverse": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", - "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=4.0" - } - }, - "node_modules/esutils": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", - "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/fast-deep-equal": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", - "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/fast-diff": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/fast-diff/-/fast-diff-1.3.0.tgz", - "integrity": "sha512-VxPP4NqbUjj6MaAOafWeUn2cXWLcCtljklUtZf0Ind4XQ+QPtmA0b18zZy0jIQx+ExRVCR/ZQpBmik5lXshNsw==", - "dev": true, - "license": "Apache-2.0" - }, "node_modules/fast-glob": { "version": "3.3.2", "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.2.tgz", @@ -1694,20 +1530,6 @@ "node": ">= 6" } }, - "node_modules/fast-json-stable-stringify": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", - "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", - "dev": true, - "license": "MIT" - }, - "node_modules/fast-levenshtein": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", - "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", - "dev": true, - "license": "MIT" - }, "node_modules/fastq": { "version": "1.18.0", "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.18.0.tgz", @@ -1719,28 +1541,15 @@ } }, "node_modules/fengari": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/fengari/-/fengari-0.1.4.tgz", - "integrity": "sha512-6ujqUuiIYmcgkGz8MGAdERU57EIluGGPSUgGPTsco657EHa+srq0S3/YUl/r9kx1+D+d4rGfYObd+m8K22gB1g==", - "dev": true, - "license": "MIT", - "dependencies": { - "readline-sync": "^1.4.9", - "sprintf-js": "^1.1.1", - "tmp": "^0.0.33" - } - }, - "node_modules/file-entry-cache": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", - "integrity": "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==", + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/fengari/-/fengari-0.1.5.tgz", + "integrity": "sha512-0DS4Nn4rV8qyFlQCpKK8brT61EUtswynrpfFTcgLErcilBIBskSMQ86fO2WVuybr14ywyKdRjv91FiRZwnEuvQ==", "dev": true, "license": "MIT", "dependencies": { - "flat-cache": "^4.0.0" - }, - "engines": { - "node": ">=16.0.0" + "readline-sync": "^1.4.10", + "sprintf-js": "^1.1.3", + "tmp": "^0.2.5" } }, "node_modules/fill-range": { @@ -1783,27 +1592,6 @@ "flat": "cli.js" } }, - "node_modules/flat-cache": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz", - "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==", - "dev": true, - "license": "MIT", - "dependencies": { - "flatted": "^3.2.9", - "keyv": "^4.5.4" - }, - "engines": { - "node": ">=16" - } - }, - "node_modules/flatted": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.3.2.tgz", - "integrity": "sha512-AiwGJM8YcNOaobumgtng+6NHuOqC3A7MixFeDafM3X9cIUM+xUXoS5Vfgf+OihAYe20fxqNM9yPBXJzRtZ/4eA==", - "dev": true, - "license": "ISC" - }, "node_modules/foreground-child": { "version": "3.3.0", "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.0.tgz", @@ -1843,21 +1631,6 @@ "dev": true, "license": "ISC" }, - "node_modules/fsevents": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", - "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^8.16.0 || ^10.6.0 || >=11.0.0" - } - }, "node_modules/get-caller-file": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", @@ -1879,40 +1652,14 @@ "jackspeak": "^3.1.2", "minimatch": "^9.0.4", "minipass": "^7.1.2", - "package-json-from-dist": "^1.0.0", - "path-scurry": "^1.11.1" - }, - "bin": { - "glob": "dist/esm/bin.mjs" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/glob-parent": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", - "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", - "dev": true, - "license": "ISC", - "dependencies": { - "is-glob": "^4.0.3" - }, - "engines": { - "node": ">=10.13.0" - } - }, - "node_modules/globals": { - "version": "14.0.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz", - "integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" + "package-json-from-dist": "^1.0.0", + "path-scurry": "^1.11.1" + }, + "bin": { + "glob": "dist/esm/bin.mjs" }, "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "url": "https://github.com/sponsors/isaacs" } }, "node_modules/globby": { @@ -1988,13 +1735,6 @@ "dev": true, "license": "ISC" }, - "node_modules/graphemer": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz", - "integrity": "sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==", - "dev": true, - "license": "MIT" - }, "node_modules/has-flag": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", @@ -2025,33 +1765,6 @@ "node": ">= 4" } }, - "node_modules/import-fresh": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz", - "integrity": "sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw==", - "dev": true, - "license": "MIT", - "dependencies": { - "parent-module": "^1.0.0", - "resolve-from": "^4.0.0" - }, - "engines": { - "node": ">=6" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/imurmurhash": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", - "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.8.19" - } - }, "node_modules/inflight": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", @@ -2071,19 +1784,6 @@ "dev": true, "license": "ISC" }, - "node_modules/is-binary-path": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", - "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", - "dev": true, - "license": "MIT", - "dependencies": { - "binary-extensions": "^2.0.0" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/is-extglob": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", @@ -2127,6 +1827,16 @@ "node": ">=0.12.0" } }, + "node_modules/is-path-inside": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.3.tgz", + "integrity": "sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/is-plain-obj": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-2.1.0.tgz", @@ -2196,27 +1906,6 @@ "js-yaml": "bin/js-yaml.js" } }, - "node_modules/json-buffer": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", - "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/json-schema-traverse": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", - "dev": true, - "license": "MIT" - }, - "node_modules/json-stable-stringify-without-jsonify": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", - "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", - "dev": true, - "license": "MIT" - }, "node_modules/jsonfile": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", @@ -2227,30 +1916,6 @@ "graceful-fs": "^4.1.6" } }, - "node_modules/keyv": { - "version": "4.5.4", - "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", - "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", - "dev": true, - "license": "MIT", - "dependencies": { - "json-buffer": "3.0.1" - } - }, - "node_modules/levn": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", - "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "prelude-ls": "^1.2.1", - "type-check": "~0.4.0" - }, - "engines": { - "node": ">= 0.8.0" - } - }, "node_modules/locate-path": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", @@ -2267,13 +1932,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/lodash.merge": { - "version": "4.6.2", - "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", - "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", - "dev": true, - "license": "MIT" - }, "node_modules/log-symbols": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-4.1.0.tgz", @@ -2291,13 +1949,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/loupe": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.1.2.tgz", - "integrity": "sha512-23I4pFZHmAemUnz8WZXbYRSKYj801VDaNv9ETuMh7IrMc7VuVVSo+Z9iLE3ni30+U48iDWfi30d3twAXBYmnCg==", - "dev": true, - "license": "MIT" - }, "node_modules/lru-cache": { "version": "10.4.3", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", @@ -2369,29 +2020,30 @@ } }, "node_modules/mocha": { - "version": "11.1.0", - "resolved": "https://registry.npmjs.org/mocha/-/mocha-11.1.0.tgz", - "integrity": "sha512-8uJR5RTC2NgpY3GrYcgpZrsEd9zKbPDpob1RezyR2upGHRQtHWofmzTMzTMSV6dru3tj5Ukt0+Vnq1qhFEEwAg==", + "version": "11.7.5", + "resolved": "https://registry.npmjs.org/mocha/-/mocha-11.7.5.tgz", + "integrity": "sha512-mTT6RgopEYABzXWFx+GcJ+ZQ32kp4fMf0xvpZIIfSq9Z8lC/++MtcCnQ9t5FP2veYEP95FIYSvW+U9fV4xrlig==", "dev": true, "license": "MIT", "dependencies": { - "ansi-colors": "^4.1.3", "browser-stdout": "^1.3.1", - "chokidar": "^3.5.3", + "chokidar": "^4.0.1", "debug": "^4.3.5", - "diff": "^5.2.0", + "diff": "^7.0.0", "escape-string-regexp": "^4.0.0", "find-up": "^5.0.0", "glob": "^10.4.5", "he": "^1.2.0", + "is-path-inside": "^3.0.3", "js-yaml": "^4.1.0", "log-symbols": "^4.1.0", - "minimatch": "^5.1.6", + "minimatch": "^9.0.5", "ms": "^2.1.3", + "picocolors": "^1.1.1", "serialize-javascript": "^6.0.2", "strip-json-comments": "^3.1.1", "supports-color": "^8.1.1", - "workerpool": "^6.5.1", + "workerpool": "^9.2.0", "yargs": "^17.7.2", "yargs-parser": "^21.1.1", "yargs-unparser": "^2.0.0" @@ -2404,19 +2056,6 @@ "node": "^18.18.0 || ^20.9.0 || >=21.1.0" } }, - "node_modules/mocha/node_modules/minimatch": { - "version": "5.1.6", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.6.tgz", - "integrity": "sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g==", - "dev": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^2.0.1" - }, - "engines": { - "node": ">=10" - } - }, "node_modules/mocha/node_modules/supports-color": { "version": "8.1.1", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", @@ -2440,23 +2079,6 @@ "dev": true, "license": "MIT" }, - "node_modules/natural-compare": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", - "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", - "dev": true, - "license": "MIT" - }, - "node_modules/normalize-path": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", - "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/once": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", @@ -2467,32 +2089,89 @@ "wrappy": "1" } }, - "node_modules/optionator": { - "version": "0.9.4", - "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", - "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", + "node_modules/oxfmt": { + "version": "0.40.0", + "resolved": "https://registry.npmjs.org/oxfmt/-/oxfmt-0.40.0.tgz", + "integrity": "sha512-g0C3I7xUj4b4DcagevM9kgH6+pUHytikxUcn3/VUkvzTNaaXBeyZqb7IBsHwojeXm4mTBEC/aBjBTMVUkZwWUQ==", "dev": true, "license": "MIT", "dependencies": { - "deep-is": "^0.1.3", - "fast-levenshtein": "^2.0.6", - "levn": "^0.4.1", - "prelude-ls": "^1.2.1", - "type-check": "^0.4.0", - "word-wrap": "^1.2.5" + "tinypool": "2.1.0" + }, + "bin": { + "oxfmt": "bin/oxfmt" }, "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/os-tmpdir": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", - "integrity": "sha512-D2FR03Vir7FIu45XBY20mTb+/ZSWB00sjU9jdQXt83gDrI4Ztz5Fs7/yy74g2N5SVQY4xY1qDr4rNddwYRVX0g==", + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/sponsors/Boshen" + }, + "optionalDependencies": { + "@oxfmt/binding-android-arm-eabi": "0.40.0", + "@oxfmt/binding-android-arm64": "0.40.0", + "@oxfmt/binding-darwin-arm64": "0.40.0", + "@oxfmt/binding-darwin-x64": "0.40.0", + "@oxfmt/binding-freebsd-x64": "0.40.0", + "@oxfmt/binding-linux-arm-gnueabihf": "0.40.0", + "@oxfmt/binding-linux-arm-musleabihf": "0.40.0", + "@oxfmt/binding-linux-arm64-gnu": "0.40.0", + "@oxfmt/binding-linux-arm64-musl": "0.40.0", + "@oxfmt/binding-linux-ppc64-gnu": "0.40.0", + "@oxfmt/binding-linux-riscv64-gnu": "0.40.0", + "@oxfmt/binding-linux-riscv64-musl": "0.40.0", + "@oxfmt/binding-linux-s390x-gnu": "0.40.0", + "@oxfmt/binding-linux-x64-gnu": "0.40.0", + "@oxfmt/binding-linux-x64-musl": "0.40.0", + "@oxfmt/binding-openharmony-arm64": "0.40.0", + "@oxfmt/binding-win32-arm64-msvc": "0.40.0", + "@oxfmt/binding-win32-ia32-msvc": "0.40.0", + "@oxfmt/binding-win32-x64-msvc": "0.40.0" + } + }, + "node_modules/oxlint": { + "version": "1.55.0", + "resolved": "https://registry.npmjs.org/oxlint/-/oxlint-1.55.0.tgz", + "integrity": "sha512-T+FjepiyWpaZMhekqRpH8Z3I4vNM610p6w+Vjfqgj5TZUxHXl7N8N5IPvmOU8U4XdTRxqtNNTh9Y4hLtr7yvFg==", "dev": true, "license": "MIT", + "bin": { + "oxlint": "bin/oxlint" + }, "engines": { - "node": ">=0.10.0" + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/sponsors/Boshen" + }, + "optionalDependencies": { + "@oxlint/binding-android-arm-eabi": "1.55.0", + "@oxlint/binding-android-arm64": "1.55.0", + "@oxlint/binding-darwin-arm64": "1.55.0", + "@oxlint/binding-darwin-x64": "1.55.0", + "@oxlint/binding-freebsd-x64": "1.55.0", + "@oxlint/binding-linux-arm-gnueabihf": "1.55.0", + "@oxlint/binding-linux-arm-musleabihf": "1.55.0", + "@oxlint/binding-linux-arm64-gnu": "1.55.0", + "@oxlint/binding-linux-arm64-musl": "1.55.0", + "@oxlint/binding-linux-ppc64-gnu": "1.55.0", + "@oxlint/binding-linux-riscv64-gnu": "1.55.0", + "@oxlint/binding-linux-riscv64-musl": "1.55.0", + "@oxlint/binding-linux-s390x-gnu": "1.55.0", + "@oxlint/binding-linux-x64-gnu": "1.55.0", + "@oxlint/binding-linux-x64-musl": "1.55.0", + "@oxlint/binding-openharmony-arm64": "1.55.0", + "@oxlint/binding-win32-arm64-msvc": "1.55.0", + "@oxlint/binding-win32-ia32-msvc": "1.55.0", + "@oxlint/binding-win32-x64-msvc": "1.55.0" + }, + "peerDependencies": { + "oxlint-tsgolint": ">=0.15.0" + }, + "peerDependenciesMeta": { + "oxlint-tsgolint": { + "optional": true + } } }, "node_modules/p-limit": { @@ -2534,19 +2213,6 @@ "dev": true, "license": "BlueOak-1.0.0" }, - "node_modules/parent-module": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", - "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", - "dev": true, - "license": "MIT", - "dependencies": { - "callsites": "^3.0.0" - }, - "engines": { - "node": ">=6" - } - }, "node_modules/path-exists": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", @@ -2604,64 +2270,12 @@ "node": ">=8" } }, - "node_modules/pathval": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/pathval/-/pathval-2.0.0.tgz", - "integrity": "sha512-vE7JKRyES09KiunauX7nd2Q9/L7lhok4smP9RZTDeD4MVs72Dp2qNFVz39Nz5a0FVEW0BJR6C0DYrq6unoziZA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 14.16" - } - }, - "node_modules/prelude-ls": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", - "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/prettier": { - "version": "3.5.1", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.5.1.tgz", - "integrity": "sha512-hPpFQvHwL3Qv5AdRvBFMhnKo4tYxp0ReXiPn2bxkiohEX6mBeBwEpBSQTkD458RaaDKQMYSp4hX4UtfUTA5wDw==", - "dev": true, - "license": "MIT", - "bin": { - "prettier": "bin/prettier.cjs" - }, - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/prettier/prettier?sponsor=1" - } - }, - "node_modules/prettier-linter-helpers": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/prettier-linter-helpers/-/prettier-linter-helpers-1.0.0.tgz", - "integrity": "sha512-GbK2cP9nraSSUF9N2XwUwqfzlAFlMNYYl+ShE/V+H8a9uNl/oUqB1w2EL54Jh0OlyRSd8RfWYJ3coVS4TROP2w==", - "dev": true, - "license": "MIT", - "dependencies": { - "fast-diff": "^1.1.2" - }, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/punycode": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", - "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } + "license": "ISC" }, "node_modules/queue-microtask": { "version": "1.2.3", @@ -2695,29 +2309,17 @@ } }, "node_modules/readdirp": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", - "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", - "dev": true, - "license": "MIT", - "dependencies": { - "picomatch": "^2.2.1" - }, - "engines": { - "node": ">=8.10.0" - } - }, - "node_modules/readdirp/node_modules/picomatch": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", - "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz", + "integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==", "dev": true, "license": "MIT", "engines": { - "node": ">=8.6" + "node": ">= 14.18.0" }, "funding": { - "url": "https://github.com/sponsors/jonschlinkert" + "type": "individual", + "url": "https://paulmillr.com/funding/" } }, "node_modules/readline-sync": { @@ -2740,16 +2342,6 @@ "node": ">=0.10.0" } }, - "node_modules/resolve-from": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", - "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=4" - } - }, "node_modules/reusify": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.0.4.tgz", @@ -2762,40 +2354,37 @@ } }, "node_modules/rolldown": { - "version": "1.0.0-beta.3", - "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.0.0-beta.3.tgz", - "integrity": "sha512-DBpF1K8tSwU/0dQ7zL9BYcje0/GjO5lgfdEW0rHHFfGjGDh8TBVNlokfEXtdt/IoJOiTdtySfsrgarLJkZmZTQ==", + "version": "1.0.0-rc.9", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.0.0-rc.9.tgz", + "integrity": "sha512-9EbgWge7ZH+yqb4d2EnELAntgPTWbfL8ajiTW+SyhJEC4qhBbkCKbqFV4Ge4zmu5ziQuVbWxb/XwLZ+RIO7E8Q==", "dev": true, "license": "MIT", "dependencies": { - "@oxc-project/types": "0.46.0", - "@valibot/to-json-schema": "1.0.0-beta.4", - "valibot": "1.0.0-beta.12" + "@oxc-project/types": "=0.115.0", + "@rolldown/pluginutils": "1.0.0-rc.9" }, "bin": { - "rolldown": "bin/cli.js" - }, - "optionalDependencies": { - "@rolldown/binding-darwin-arm64": "1.0.0-beta.3", - "@rolldown/binding-darwin-x64": "1.0.0-beta.3", - "@rolldown/binding-freebsd-x64": "1.0.0-beta.3", - "@rolldown/binding-linux-arm-gnueabihf": "1.0.0-beta.3", - "@rolldown/binding-linux-arm64-gnu": "1.0.0-beta.3", - "@rolldown/binding-linux-arm64-musl": "1.0.0-beta.3", - "@rolldown/binding-linux-x64-gnu": "1.0.0-beta.3", - "@rolldown/binding-linux-x64-musl": "1.0.0-beta.3", - "@rolldown/binding-wasm32-wasi": "1.0.0-beta.3", - "@rolldown/binding-win32-arm64-msvc": "1.0.0-beta.3", - "@rolldown/binding-win32-ia32-msvc": "1.0.0-beta.3", - "@rolldown/binding-win32-x64-msvc": "1.0.0-beta.3" + "rolldown": "bin/cli.mjs" }, - "peerDependencies": { - "@babel/runtime": ">=7" + "engines": { + "node": "^20.19.0 || >=22.12.0" }, - "peerDependenciesMeta": { - "@babel/runtime": { - "optional": true - } + "optionalDependencies": { + "@rolldown/binding-android-arm64": "1.0.0-rc.9", + "@rolldown/binding-darwin-arm64": "1.0.0-rc.9", + "@rolldown/binding-darwin-x64": "1.0.0-rc.9", + "@rolldown/binding-freebsd-x64": "1.0.0-rc.9", + "@rolldown/binding-linux-arm-gnueabihf": "1.0.0-rc.9", + "@rolldown/binding-linux-arm64-gnu": "1.0.0-rc.9", + "@rolldown/binding-linux-arm64-musl": "1.0.0-rc.9", + "@rolldown/binding-linux-ppc64-gnu": "1.0.0-rc.9", + "@rolldown/binding-linux-s390x-gnu": "1.0.0-rc.9", + "@rolldown/binding-linux-x64-gnu": "1.0.0-rc.9", + "@rolldown/binding-linux-x64-musl": "1.0.0-rc.9", + "@rolldown/binding-openharmony-arm64": "1.0.0-rc.9", + "@rolldown/binding-wasm32-wasi": "1.0.0-rc.9", + "@rolldown/binding-win32-arm64-msvc": "1.0.0-rc.9", + "@rolldown/binding-win32-x64-msvc": "1.0.0-rc.9" } }, "node_modules/rollup-plugin-copy": { @@ -2860,19 +2449,6 @@ ], "license": "MIT" }, - "node_modules/semver": { - "version": "7.7.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.1.tgz", - "integrity": "sha512-hlq8tAfn0m/61p4BVRcPzIGr6LKiMwo4VM6dGi6pt4qcRkmNzTcWq6eCEjEh+qXjkMDvPlOFFSGwQjoEa6gyMA==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, "node_modules/serialize-javascript": { "version": "6.0.2", "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.2.tgz", @@ -3066,34 +2642,24 @@ "node": ">=8" } }, - "node_modules/synckit": { - "version": "0.9.2", - "resolved": "https://registry.npmjs.org/synckit/-/synckit-0.9.2.tgz", - "integrity": "sha512-vrozgXDQwYO72vHjUb/HnFbQx1exDjoKzqx23aXEg2a9VIg2TSFZ8FmeZpTjUCFMYw7mpX4BE2SFu8wI7asYsw==", + "node_modules/tinypool": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-2.1.0.tgz", + "integrity": "sha512-Pugqs6M0m7Lv1I7FtxN4aoyToKg1C4tu+/381vH35y8oENM/Ai7f7C4StcoK4/+BSw9ebcS8jRiVrORFKCALLw==", "dev": true, "license": "MIT", - "dependencies": { - "@pkgr/core": "^0.1.0", - "tslib": "^2.6.2" - }, "engines": { - "node": "^14.18.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/unts" + "node": "^20.0.0 || >=22.0.0" } }, "node_modules/tmp": { - "version": "0.0.33", - "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz", - "integrity": "sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==", + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.5.tgz", + "integrity": "sha512-voyz6MApa1rQGUxT3E+BK7/ROe8itEx7vD8/HEvt4xwXucvQ5G5oeEiHkmHZJuBO21RpOf+YYm9MOivj709jow==", "dev": true, "license": "MIT", - "dependencies": { - "os-tmpdir": "~1.0.2" - }, "engines": { - "node": ">=0.6.0" + "node": ">=14.14" } }, "node_modules/to-regex-range": { @@ -3109,19 +2675,6 @@ "node": ">=8.0" } }, - "node_modules/ts-api-utils": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.0.1.tgz", - "integrity": "sha512-dnlgjFSVetynI8nzgJ+qF62efpglpWRk8isUEWZGWlJYySCTD6aKvbUDu+zbPeDakk3bg5H4XpitHukgfL1m9w==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18.12" - }, - "peerDependencies": { - "typescript": ">=4.8.4" - } - }, "node_modules/tslib": { "version": "2.8.1", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", @@ -3129,25 +2682,13 @@ "dev": true, "license": "0BSD" }, - "node_modules/type-check": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", - "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", - "dev": true, - "license": "MIT", - "dependencies": { - "prelude-ls": "^1.2.1" - }, - "engines": { - "node": ">= 0.8.0" - } - }, "node_modules/typescript": { - "version": "5.7.3", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.7.3.tgz", - "integrity": "sha512-84MVSjMEHP+FQRPy3pX9sTVV/INIex71s9TL2Gm5FG/WG1SqXeKyZ0k7/blY/4FdOzI12CBy1vGc4og/eus0fw==", + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", "dev": true, "license": "Apache-2.0", + "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -3156,33 +2697,10 @@ "node": ">=14.17" } }, - "node_modules/typescript-eslint": { - "version": "8.24.1", - "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.24.1.tgz", - "integrity": "sha512-cw3rEdzDqBs70TIcb0Gdzbt6h11BSs2pS0yaq7hDWDBtCCSei1pPSUXE9qUdQ/Wm9NgFg8mKtMt1b8fTHIl1jA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/eslint-plugin": "8.24.1", - "@typescript-eslint/parser": "8.24.1", - "@typescript-eslint/utils": "8.24.1" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "eslint": "^8.57.0 || ^9.0.0", - "typescript": ">=4.8.4 <5.8.0" - } - }, "node_modules/undici-types": { - "version": "6.20.0", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.20.0.tgz", - "integrity": "sha512-Ny6QZ2Nju20vw1SRHe3d9jVu6gJ+4e3+MMpqu7pqE5HT6WsTSlce++GQmK5UXS8mzV8DSYHrQH+Xrf2jVcuKNg==", + "version": "7.18.2", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz", + "integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==", "dev": true, "license": "MIT" }, @@ -3196,31 +2714,6 @@ "node": ">= 4.0.0" } }, - "node_modules/uri-js": { - "version": "4.4.1", - "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", - "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "punycode": "^2.1.0" - } - }, - "node_modules/valibot": { - "version": "1.0.0-beta.12", - "resolved": "https://registry.npmjs.org/valibot/-/valibot-1.0.0-beta.12.tgz", - "integrity": "sha512-j3WIxJ0pmUFMfdfUECn3YnZPYOiG0yHYcFEa/+RVgo0I+MXE3ToLt7gNRLtY5pwGfgNmsmhenGZfU5suu9ijUA==", - "dev": true, - "license": "MIT", - "peerDependencies": { - "typescript": ">=5" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", @@ -3237,20 +2730,10 @@ "node": ">= 8" } }, - "node_modules/word-wrap": { - "version": "1.2.5", - "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", - "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/workerpool": { - "version": "6.5.1", - "resolved": "https://registry.npmjs.org/workerpool/-/workerpool-6.5.1.tgz", - "integrity": "sha512-Fs4dNYcsdpYSAfVxhnl1L5zTksjvOJxtC5hzMNl+1t9B8hTJTdKDyZ5ju7ztgPy+ft9tBFXoOlDNiOT9WUXZlA==", + "version": "9.3.4", + "resolved": "https://registry.npmjs.org/workerpool/-/workerpool-9.3.4.tgz", + "integrity": "sha512-TmPRQYYSAnnDiEB0P/Ytip7bFGvqnSU6I2BcuSw7Hx+JSg/DsUi5ebYfc8GYaSdpuvOcEs6dXxPurOYpe9QFwg==", "dev": true, "license": "Apache-2.0" }, diff --git a/package.json b/package.json index 746bc87..3afca7c 100755 --- a/package.json +++ b/package.json @@ -13,8 +13,8 @@ "luatests": "node --experimental-import-meta-resolve test/luatests.js", "build": "rolldown -c && tsc -d --emitDeclarationOnly --rootDir src --declarationDir dist", "clean": "rm -rf dist build", - "lint": "prettier --write . && eslint . --fix --cache", - "lint:nofix": "eslint ." + "lint": "oxfmt --write . && oxlint --config .oxlintrc.json -D suspicious --import-plugin --node-plugin --promise-plugin --fix .", + "lint:nofix": "oxfmt --check . && oxlint --config .oxlintrc.json -D suspicious --import-plugin --node-plugin --promise-plugin ." }, "files": [ "bin/*", @@ -40,25 +40,19 @@ "webassembly" ], "devDependencies": { - "@eslint/js": "9.20.0", - "@types/node": "22.13.4", - "@typescript-eslint/parser": "8.24.1", - "chai": "5.2.0", - "chai-as-promised": "8.0.1", - "eslint": "9.20.1", - "eslint-config-prettier": "10.0.1", - "eslint-plugin-prettier": "5.2.3", - "eslint-plugin-simple-import-sort": "12.1.1", - "fengari": "0.1.4", - "mocha": "11.1.0", - "prettier": "3.5.1", - "rolldown": "1.0.0-beta.3", + "@types/node": "25.5.0", + "chai": "6.2.2", + "chai-as-promised": "8.0.2", + "fengari": "0.1.5", + "mocha": "11.7.5", + "oxfmt": "0.40.0", + "oxlint": "1.55.0", + "rolldown": "1.0.0-rc.9", "rollup-plugin-copy": "3.5.0", "tslib": "2.8.1", - "typescript": "5.7.3", - "typescript-eslint": "8.24.1" + "typescript": "5.9.3" }, "dependencies": { - "@types/emscripten": "1.40.0" + "@types/emscripten": "1.41.5" } } diff --git a/src/module.ts b/src/module.ts index 1f0d8ad..cdd3ae0 100755 --- a/src/module.ts +++ b/src/module.ts @@ -12,11 +12,11 @@ interface LuaEmscriptenModule extends EmscriptenModule { setValue: typeof setValue getValue: typeof getValue FS: typeof FS & { - mkdirTree: (path: string) => void filesystems: { NODEFS: Emscripten.FileSystemType MEMFS: Emscripten.FileSystemType } + mkdirTree: (path: string) => void } PATH: { dirname: (typeof import('node:path'))['dirname'] @@ -56,8 +56,6 @@ export default class LuaModule { const child_process = !isBrowser && opts.fs === 'node' && typeof process !== 'undefined' ? await import('node:child_process') : null const module: LuaEmscriptenModule = await initWasmModule({ - print: opts.stdout, - printErr: opts.stderr, locateFile: (path: string, scriptDirectory: string) => { return opts.wasmFile || scriptDirectory + path }, @@ -69,7 +67,9 @@ export default class LuaModule { if (fs && child_process) { let rootdirs: string[] if (process.platform === 'win32') { - const stdout = child_process.execSync('wmic logicaldisk get name', { encoding: 'utf8' }) + const stdout = child_process.execSync('wmic logicaldisk get name', { + encoding: 'utf8', + }) const drives = stdout .split('\n') .map((line) => line.trim()) @@ -105,33 +105,31 @@ export default class LuaModule { initializedModule.FS.chdir(process.cwd().replace(/\\|\\\\/g, '/')) } - if (opts.stdin) { + if (opts.stdin || opts.stdout || opts.stderr) { let bufferedInput: number[] | undefined initializedModule.FS.init( - () => { - if (!opts.stdin) { - throw new Error('stdin is not defined, it was probably mutated from original options') - } - - if (!bufferedInput) { - const stdin = opts.stdin() - if (typeof stdin === 'string') { - bufferedInput = initializedModule.intArrayFromString(stdin, true).concat([0]) - } else { - throw new Error('stdin must return a string') - } - } - - if (bufferedInput.length === 0) { - bufferedInput = undefined - return null - } - - const item = bufferedInput.shift() - return !item || item === 0 ? null : item - }, - null, - null, + opts.stdin + ? () => { + if (!bufferedInput) { + const input = opts.stdin?.() + if (typeof input === 'string') { + bufferedInput = initializedModule.intArrayFromString(input, true).concat([0]) + } else { + throw new Error('stdin must return a string') + } + } + + if (bufferedInput.length === 0) { + bufferedInput = undefined + return null + } + + const item = bufferedInput.shift() + return !item || item === 0 ? null : item + } + : null, + createOutputWriter(opts.stdout), + createOutputWriter(opts.stderr), ) } }, @@ -574,3 +572,22 @@ export default class LuaModule { } } } + +function createOutputWriter(writer?: (content: string) => void): ((charCode: number | null) => void) | null { + if (!writer) { + return null + } + + let buffer = '' + return (charCode: number | null): void => { + if (charCode === null || charCode === 10) { + writer(buffer) + buffer = '' + return + } + + if (charCode !== 13) { + buffer += String.fromCharCode(charCode) + } + } +} diff --git a/src/type-extensions/function.ts b/src/type-extensions/function.ts index 28b5283..9625653 100644 --- a/src/type-extensions/function.ts +++ b/src/type-extensions/function.ts @@ -79,28 +79,28 @@ class FunctionTypeExtension extends TypeExtension + const { target, options: decorationOptions } = thread.lua.getRef(refPointer) as Decoration const argsQuantity = calledThread.getTop() const args = [] - if (options.receiveThread) { + if (decorationOptions.receiveThread) { args.push(calledThread) } - if (options.receiveArgsQuantity) { + if (decorationOptions.receiveArgsQuantity) { args.push(argsQuantity) } else { for (let i = 1; i <= argsQuantity; i++) { const value = calledThread.getValue(i) - if (i !== 1 || !options?.self || value !== options.self) { + if (i !== 1 || !decorationOptions?.self || value !== decorationOptions.self) { args.push(value) } } } try { - const result = target.apply(options?.self, args) + const result = target.apply(decorationOptions?.self, args) if (result === undefined) { return 0 diff --git a/src/type-extensions/promise.ts b/src/type-extensions/promise.ts index ea8da1b..2130c6b 100644 --- a/src/type-extensions/promise.ts +++ b/src/type-extensions/promise.ts @@ -58,6 +58,7 @@ class PromiseTypeExtension extends TypeExtension> { const awaitPromise = self .then((res) => { promiseResult = { status: 'fulfilled', value: res } + return res }) .catch((err) => { promiseResult = { status: 'rejected', value: err } diff --git a/src/type-extensions/table.ts b/src/type-extensions/table.ts index 3d08304..6fb4335 100644 --- a/src/type-extensions/table.ts +++ b/src/type-extensions/table.ts @@ -28,7 +28,7 @@ class TableTypeExtension extends TypeExtension { if (!table) { const keys = this.readTableKeys(thread, index) - const isSequential = keys.length > 0 && keys.every((key, index) => key === String(index + 1)) + const isSequential = keys.length > 0 && keys.every((key, keyIndex) => key === String(keyIndex + 1)) table = isSequential ? [] : {} seenMap.set(pointer, table) diff --git a/tsconfig.json b/tsconfig.json index 625eae6..af4b756 100755 --- a/tsconfig.json +++ b/tsconfig.json @@ -19,6 +19,6 @@ "strict": true, "resolveJsonModule": true }, - "include": ["src/**/*", "test/**/*", "bench/**/*", "eslint.config.js"], + "include": ["src/**/*", "test/**/*", "bench/**/*"], "exclude": ["node_modules"] } diff --git a/utils/build-wasm.js b/utils/build-wasm.js index ff97b26..4913605 100644 --- a/utils/build-wasm.js +++ b/utils/build-wasm.js @@ -38,8 +38,7 @@ if (isUnix) { try { execSync('docker --version', { encoding: 'utf-8' }) -} -catch (error) { +} catch (error) { console.error('Docker is not installed or not in your PATH. Please install Docker to build the WASM file.') process.exit(1) } diff --git a/utils/build-wasm.sh b/utils/build-wasm.sh index 4818b30..74d02c2 100755 --- a/utils/build-wasm.sh +++ b/utils/build-wasm.sh @@ -31,6 +31,11 @@ emcc \ 'UTF8ToString', \ 'HEAPU32' ]" \ + -s DEFAULT_LIBRARY_FUNCS_TO_INCLUDE="[ + '\$FS_mkdirTree', \ + '\$PATH', \ + '\$PATH_FS' + ]" \ -s INCOMING_MODULE_JS_API="[ 'locateFile', \ 'preRun', \ @@ -44,8 +49,6 @@ emcc \ -s ALLOW_MEMORY_GROWTH=1 \ -s STRICT=1 \ -s EXPORT_ES6=1 \ - -s NODEJS_CATCH_EXIT=0 \ - -s NODEJS_CATCH_REJECTION=0 \ -s MALLOC=emmalloc \ -s STACK_SIZE=1MB \ -s WASM_BIGINT \ From 9fd1b195b3dfc3ac03a52b8b65076e5e92605d22 Mon Sep 17 00:00:00 2001 From: Gabriel Francisco Date: Fri, 13 Mar 2026 20:52:22 -0300 Subject: [PATCH 29/83] fix lua 5.5.1 implementation --- src/global.ts | 24 +++++++++++++++++++----- src/module.ts | 17 +++++++++++------ src/types.ts | 2 +- test/luatests.js | 21 +++++++++++++++++++++ utils/build-wasm.sh | 5 ++--- utils/create-bindings.sh | 2 +- 6 files changed, 55 insertions(+), 16 deletions(-) diff --git a/src/global.ts b/src/global.ts index fd28272..e5df71d 100755 --- a/src/global.ts +++ b/src/global.ts @@ -36,7 +36,11 @@ export default class Global extends Thread { const endMemoryDelta = pointer ? newSize - oldSize : newSize const endMemory = memoryStats.memoryUsed + endMemoryDelta - if (newSize > oldSize && memoryStats.memoryMax && endMemory > memoryStats.memoryMax) { + if ( + newSize > oldSize && + memoryStats.memoryMax && + endMemory > memoryStats.memoryMax + ) { return 0 } @@ -49,7 +53,11 @@ export default class Global extends Thread { 'iiiii', ) - const address = cmodule.lua_newstate(allocatorFunctionPointer, null) + const address = cmodule.lua_newstate( + allocatorFunctionPointer, + null, + ((Date.now() >>> 0) ^ Math.floor(Math.random() * 0x100000000)) >>> 0, + ) if (!address) { cmodule._emscripten.removeFunction(allocatorFunctionPointer) throw new Error('lua_newstate returned a null pointer') @@ -171,13 +179,17 @@ export default class Global extends Thread { const type = this.lua.lua_getglobal(this.address, name) try { if (type !== LuaType.Table) { - throw new TypeError(`Unexpected type in ${name}. Expected ${LuaType[LuaType.Table]}. Got ${LuaType[type]}.`) + throw new TypeError( + `Unexpected type in ${name}. Expected ${LuaType[LuaType.Table]}. Got ${LuaType[type]}.`, + ) } callback(startStackTop + 1) } finally { // +1 for the table if (this.getTop() !== startStackTop + 1) { - console.warn(`getTable: expected stack size ${startStackTop + 1} got ${this.getTop()}`) + console.warn( + `getTable: expected stack size ${startStackTop + 1} got ${this.getTop()}`, + ) } this.setTop(startStackTop) } @@ -209,7 +221,9 @@ export default class Global extends Thread { private getMemoryStatsRef(): LuaMemoryStats { if (!this.memoryStats) { - throw new Error('Memory allocations is not being traced, please build engine with { traceAllocations: true }') + throw new Error( + 'Memory allocations is not being traced, please build engine with { traceAllocations: true }', + ) } return this.memoryStats diff --git a/src/module.ts b/src/module.ts index cdd3ae0..a4bde12 100755 --- a/src/module.ts +++ b/src/module.ts @@ -180,6 +180,7 @@ export default class LuaModule { public luaL_getsubtable: (L: LuaState, idx: number, fname: string | null) => number public luaL_traceback: (L: LuaState, L1: LuaState, msg: string | null, level: number) => void public luaL_requiref: (L: LuaState, modname: string | null, openf: number, glb: number) => void + public luaL_openselectedlibs: (L: LuaState, load: number, preload: number) => void public luaL_buffinit: (L: LuaState, B: number | null) => void public luaL_prepbuffsize: (B: number | null, sz: number) => string public luaL_addlstring: (B: number | null, s: string | null, l: number) => void @@ -188,9 +189,10 @@ export default class LuaModule { public luaL_pushresult: (B: number | null) => void public luaL_pushresultsize: (B: number | null, sz: number) => void public luaL_buffinitsize: (L: LuaState, B: number | null, sz: number) => string - public lua_newstate: (f: number | null, ud: number | null) => LuaState + public lua_newstate: (f: number | null, ud: number | null, seed: number) => LuaState public lua_close: (L: LuaState) => void public lua_newthread: (L: LuaState) => LuaState + public lua_closethread: (L: LuaState, from: LuaState | null) => LuaReturn public lua_resetthread: (L: LuaState) => LuaReturn public lua_atpanic: (L: LuaState, panicf: number) => number public lua_version: (L: LuaState) => number @@ -281,7 +283,7 @@ export default class LuaModule { public lua_gethook: (L: LuaState) => number public lua_gethookmask: (L: LuaState) => number public lua_gethookcount: (L: LuaState) => number - public lua_setcstacklimit: (L: LuaState, limit: number) => number + public lua_setcstacklimit: (_L: LuaState, _limit: number) => number public luaopen_base: (L: LuaState) => number public luaopen_coroutine: (L: LuaState) => number public luaopen_table: (L: LuaState) => number @@ -337,6 +339,7 @@ export default class LuaModule { this.luaL_getsubtable = this.cwrap('luaL_getsubtable', 'number', ['number', 'number', 'string']) this.luaL_traceback = this.cwrap('luaL_traceback', null, ['number', 'number', 'string', 'number']) this.luaL_requiref = this.cwrap('luaL_requiref', null, ['number', 'string', 'number', 'number']) + this.luaL_openselectedlibs = this.cwrap('luaL_openselectedlibs', null, ['number', 'number', 'number']) this.luaL_buffinit = this.cwrap('luaL_buffinit', null, ['number', 'number']) this.luaL_prepbuffsize = this.cwrap('luaL_prepbuffsize', 'string', ['number', 'number']) this.luaL_addlstring = this.cwrap('luaL_addlstring', null, ['number', 'string', 'number']) @@ -345,10 +348,11 @@ export default class LuaModule { this.luaL_pushresult = this.cwrap('luaL_pushresult', null, ['number']) this.luaL_pushresultsize = this.cwrap('luaL_pushresultsize', null, ['number', 'number']) this.luaL_buffinitsize = this.cwrap('luaL_buffinitsize', 'string', ['number', 'number', 'number']) - this.lua_newstate = this.cwrap('lua_newstate', 'number', ['number', 'number']) + this.lua_newstate = this.cwrap('lua_newstate', 'number', ['number', 'number', 'number']) this.lua_close = this.cwrap('lua_close', null, ['number']) this.lua_newthread = this.cwrap('lua_newthread', 'number', ['number']) - this.lua_resetthread = this.cwrap('lua_resetthread', 'number', ['number']) + this.lua_closethread = this.cwrap('lua_closethread', 'number', ['number', 'number']) + this.lua_resetthread = (L) => this.lua_closethread(L, null) this.lua_atpanic = this.cwrap('lua_atpanic', 'number', ['number', 'number']) this.lua_version = this.cwrap('lua_version', 'number', ['number']) this.lua_absindex = this.cwrap('lua_absindex', 'number', ['number', 'number']) @@ -438,7 +442,8 @@ export default class LuaModule { this.lua_gethook = this.cwrap('lua_gethook', 'number', ['number']) this.lua_gethookmask = this.cwrap('lua_gethookmask', 'number', ['number']) this.lua_gethookcount = this.cwrap('lua_gethookcount', 'number', ['number']) - this.lua_setcstacklimit = this.cwrap('lua_setcstacklimit', 'number', ['number', 'number']) + // Deprecated in Lua 5.5; keep the JS API surface as a no-op compatibility shim. + this.lua_setcstacklimit = () => 0 this.luaopen_base = this.cwrap('luaopen_base', 'number', ['number']) this.luaopen_coroutine = this.cwrap('luaopen_coroutine', 'number', ['number']) this.luaopen_table = this.cwrap('luaopen_table', 'number', ['number']) @@ -449,7 +454,7 @@ export default class LuaModule { this.luaopen_math = this.cwrap('luaopen_math', 'number', ['number']) this.luaopen_debug = this.cwrap('luaopen_debug', 'number', ['number']) this.luaopen_package = this.cwrap('luaopen_package', 'number', ['number']) - this.luaL_openlibs = this.cwrap('luaL_openlibs', null, ['number']) + this.luaL_openlibs = (L) => this.luaL_openselectedlibs(L, -1, 0) } public lua_remove(luaState: LuaState, index: number): void { diff --git a/src/types.ts b/src/types.ts index 1e12c75..393c812 100755 --- a/src/types.ts +++ b/src/types.ts @@ -36,7 +36,7 @@ export const PointerSize = 4 export const LUA_MULTRET = -1 export const LUAI_MAXSTACK = 1000000 -export const LUA_REGISTRYINDEX = -LUAI_MAXSTACK - 1000 +export const LUA_REGISTRYINDEX = -(Math.trunc(0x7fffffff / 2) + 1000) export enum LuaType { None = -1, diff --git a/test/luatests.js b/test/luatests.js index cfe2df7..27460f6 100644 --- a/test/luatests.js +++ b/test/luatests.js @@ -6,6 +6,27 @@ const lua = await Lua.load() const testsPath = import.meta.resolve('../lua/testes') const filePath = fileURLToPath(typeof testsPath === 'string' ? testsPath : await Promise.resolve(testsPath)) +if (!lua.filesystem.analyzePath('/dev/full').exists) { + const deviceMode = lua.filesystem.lookupPath('/dev/null').node.mode + const fullDevice = lua.filesystem.makedev(64, 0) + lua.filesystem.registerDevice(fullDevice, { + open(stream) { + stream.seekable = false + }, + close() {}, + read() { + return 0 + }, + write() { + throw new lua.filesystem.ErrnoError(28) + }, + llseek() { + throw new lua.filesystem.ErrnoError(70) + }, + }) + lua.filesystem.mkdev('/dev/full', deviceMode, fullDevice) +} + for await (const file of glob(`${filePath}/**/*.lua`)) { const relativeFile = file.replace(`${filePath}/`, '') lua.mountFile(relativeFile, await readFile(file)) diff --git a/utils/build-wasm.sh b/utils/build-wasm.sh index 74d02c2..b044209 100755 --- a/utils/build-wasm.sh +++ b/utils/build-wasm.sh @@ -102,7 +102,7 @@ emcc \ '_lua_newstate', \ '_lua_close', \ '_lua_newthread', \ - '_lua_resetthread', \ + '_lua_closethread', \ '_lua_atpanic', \ '_lua_version', \ '_lua_absindex', \ @@ -192,7 +192,6 @@ emcc \ '_lua_gethook', \ '_lua_gethookmask', \ '_lua_gethookcount', \ - '_lua_setcstacklimit', \ '_luaopen_base', \ '_luaopen_coroutine', \ '_luaopen_table', \ @@ -203,6 +202,6 @@ emcc \ '_luaopen_math', \ '_luaopen_debug', \ '_luaopen_package', \ - '_luaL_openlibs' \ + '_luaL_openselectedlibs' \ ]" \ ${LUA_SRC} diff --git a/utils/create-bindings.sh b/utils/create-bindings.sh index b47efb3..036c15e 100755 --- a/utils/create-bindings.sh +++ b/utils/create-bindings.sh @@ -1,3 +1,3 @@ #!/bin/sh -e -find ../lua/ -name "*.h" | ./create-bindings.js +find ../lua/ -name "*.h" | ./create-bindings.cjs From d41aca81f399dcb82409d3941e5af24d570cbc44 Mon Sep 17 00:00:00 2001 From: Gabriel Francisco Date: Sat, 14 Mar 2026 11:57:25 -0300 Subject: [PATCH 30/83] add a test to ensure no regressions on 64bit numbers --- test/engine.test.js | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/test/engine.test.js b/test/engine.test.js index 8b1fdd1..05fbcfb 100644 --- a/test/engine.test.js +++ b/test/engine.test.js @@ -717,6 +717,25 @@ describe('State', () => { expect(res).to.be.equal('1689031554550') }) + it('64-bit integers pushed through the raw Lua API should keep integer semantics', async () => { + const state = await getState() + const value = 9223372036854775807n + + state.global.lua.lua_pushinteger(state.global.address, value) + state.global.lua.lua_setglobal(state.global.address, 'value') + + const asString = await state.doString(`return tostring(value)`) + const asFormatted = await state.doString(`return ("%d"):format(value)`) + + state.global.lua.lua_getglobal(state.global.address, 'value') + const roundTrip = state.global.lua.lua_tointegerx(state.global.address, -1, null) + state.global.pop() + + expect(asString).to.be.equal('9223372036854775807') + expect(asFormatted).to.be.equal('9223372036854775807') + expect(roundTrip).to.be.equal(value) + }) + it('yielding in a JS callback into Lua does not break lua state', async () => { // When yielding within a callback the error 'attempt to yield across a C-call boundary'. // This test just checks that throwing that error still allows the lua global to be From a23e34d83f5e157cab5244eea37d8fe021cd6195 Mon Sep 17 00:00:00 2001 From: Gabriel Francisco Date: Sat, 14 Mar 2026 13:59:52 -0300 Subject: [PATCH 31/83] optimize build size --- .github/workflows/test.yml | 6 +- bench/comparisons.js | 84 +++--- bench/index.js | 20 ++ bench/steps.js | 216 +++++++-------- bench/utils.js | 240 +++++++++++++++++ package-lock.json | 528 ------------------------------------- package.json | 2 +- rolldown.config.ts | 22 +- utils/build-wasm.sh | 2 +- 9 files changed, 423 insertions(+), 697 deletions(-) create mode 100644 bench/index.js create mode 100644 bench/utils.js diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 119e830..e18e2c3 100755 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -10,15 +10,15 @@ jobs: strategy: matrix: - node-version: [22] + node-version: [22, 24] steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 with: submodules: recursive - uses: mymindstorm/setup-emsdk@v14 - name: Use Node.js ${{ matrix.node-version }} - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 with: node-version: ${{ matrix.node-version }} - run: npm ci diff --git a/bench/comparisons.js b/bench/comparisons.js index 1a72e9a..5b6dd14 100644 --- a/bench/comparisons.js +++ b/bench/comparisons.js @@ -1,62 +1,52 @@ -import { readFileSync } from 'fs' -import path from 'path' -import { performance } from 'perf_hooks' import { Lua } from '../dist/index.js' import fengari from 'fengari' +import { isMainModule, parseBenchOptions, readBenchAsset, runBenchmarks } from './utils.js' -const heapsort = readFileSync(path.resolve(import.meta.dirname, 'heapsort.lua'), 'utf-8') +const heapsort = readBenchAsset('heapsort.lua') -function calculateStats(times) { - const n = times.length - const avg = times.reduce((sum, t) => sum + t, 0) / n - const stdDev = Math.sqrt(times.reduce((sum, t) => sum + (t - avg) ** 2, 0) / n) - return { avg, stdDev } -} - -async function benchmark(name, iterations, warmup, fn) { - console.log(`\nBenchmarking ${name}...`) - - for (let i = 0; i < warmup; i++) { - await fn() +function runFengariIteration() { + const state = fengari.lauxlib.luaL_newstate() + try { + fengari.lualib.luaL_openlibs(state) + assertStatus(fengari.lauxlib.luaL_loadstring(state, fengari.to_luastring(heapsort)), 'Fengari load') + assertStatus(fengari.lua.lua_pcallk(state, 0, 1, 0, 0, null), 'Fengari compile') + assertStatus(fengari.lua.lua_pcallk(state, 0, 1, 0, 0, null), 'Fengari execute') + } finally { + fengari.lua.lua_close(state) } +} - const times = [] - for (let i = 0; i < iterations; i++) { - const start = performance.now() - await fn() - const end = performance.now() - times.push(end - start) +function createWasmoonIteration(lua) { + return function runWasmoonIteration() { + const state = lua.createState() + try { + assertStatus(state.global.lua.luaL_loadstring(state.global.address, heapsort), 'Wasmoon load') + assertStatus(state.global.lua.lua_pcallk(state.global.address, 0, 1, 0, 0, null), 'Wasmoon compile') + assertStatus(state.global.lua.lua_pcallk(state.global.address, 0, 1, 0, 0, null), 'Wasmoon execute') + } finally { + state.global.close() + } } - - const { avg, stdDev } = calculateStats(times) - console.log(`${name}: ${iterations} iterations | avg: ${avg.toFixed(3)} ms | std dev: ${stdDev.toFixed(3)} ms`) } -async function benchmarkFengari(iterations, warmup) { - function runFengariIteration() { - const state = fengari.lauxlib.luaL_newstate() - fengari.lualib.luaL_openlibs(state) - fengari.lauxlib.luaL_loadstring(state, fengari.to_luastring(heapsort)) - fengari.lua.lua_callk(state, 0, 1, 0, null) - fengari.lua.lua_callk(state, 0, 0, 0, null) +function assertStatus(status, label) { + if (status !== 0) { + throw new Error(`${label} failed with status ${status}`) } - await benchmark('Fengari', iterations, warmup, runFengariIteration) } -async function benchmarkWasmoon(iterations, warmup) { +export async function runComparisonBench(options = {}) { const lua = await Lua.load() - - async function runWasmoonIteration() { - const state = lua.createState() - state.global.lua.luaL_loadstring(state.global.address, heapsort) - state.global.lua.lua_callk(state.global.address, 0, 1, 0, null) - state.global.lua.lua_callk(state.global.address, 0, 0, 0, null) - } - await benchmark('Wasmoon', iterations, warmup, runWasmoonIteration) + return runBenchmarks({ + title: 'Comparison benchmarks', + benches: [ + { name: 'Fengari heapsort', run: runFengariIteration }, + { name: 'Wasmoon heapsort', run: createWasmoonIteration(lua) }, + ], + options, + }) } -const iterations = 100 -const warmup = 10 - -await benchmarkFengari(iterations, warmup) -await benchmarkWasmoon(iterations, warmup) +if (isMainModule(import.meta.url)) { + await runComparisonBench(parseBenchOptions()) +} diff --git a/bench/index.js b/bench/index.js new file mode 100644 index 0000000..f2555a9 --- /dev/null +++ b/bench/index.js @@ -0,0 +1,20 @@ +import { runComparisonBench } from './comparisons.js' +import { runStepBench } from './steps.js' +import { parseBenchOptions, printArtifactSizes, printBenchUsage } from './utils.js' + +const options = parseBenchOptions() + +if (options.help) { + printBenchUsage() + process.exit(0) +} + +printArtifactSizes() + +if (options.suite === 'all' || options.suite === 'steps') { + await runStepBench(options) +} + +if (options.suite === 'all' || options.suite === 'comparisons') { + await runComparisonBench(options) +} diff --git a/bench/steps.js b/bench/steps.js index ec6c273..568a4f6 100644 --- a/bench/steps.js +++ b/bench/steps.js @@ -1,133 +1,133 @@ -import { readFileSync } from 'fs' -import path from 'path' import { Lua } from '../dist/index.js' -import assert from 'node:assert' +import assert from 'node:assert/strict' +import { isMainModule, parseBenchOptions, readBenchAsset, runBenchmarks } from './utils.js' -const heapsort = readFileSync(path.resolve(import.meta.dirname, 'heapsort.lua'), 'utf-8') - -const createFactory = async () => { - console.time('Create factory') - await Lua.load() - console.timeEnd('Create factory') -} - -const createState = async () => { - const lua = await Lua.load() - - console.time('Create state') - lua.createState() - console.timeEnd('Create state') -} - -const createStateWithoutSuperpowers = async () => { - const lua = await Lua.load() - - console.time('Create state without superpowers') - lua.createState({ - injectObjects: false, - enableProxy: false, - openStandardLibs: false, - }) - console.timeEnd('Create state without superpowers') -} - -const runHeapsort = async () => { - const lua = await Lua.load() - const state = lua.createState() - - console.time('Run plain heapsort') - state.global.lua.luaL_loadstring(state.global.address, heapsort) - state.global.lua.lua_pcallk(state.global.address, 0, 1, 0, 0, null) - state.global.lua.lua_pcallk(state.global.address, 0, 0, 0, 0, null) - console.timeEnd('Run plain heapsort') -} - -const runInteropedHeapsort = async () => { - const lua = await Lua.load() - const state = lua.createState() - - console.time('Run interoped heapsort') - const executeHeapsort = await state.doString(heapsort) - assert(executeHeapsort() === 10) - console.timeEnd('Run interoped heapsort') -} - -const insertComplexObjects = async () => { - const lua = await Lua.load() - const state = lua.createState() - const obj1 = { - hello: 'world', +const heapsort = readBenchAsset('heapsort.lua') +const luaObjectFixture = ` + local obj1 = { + hello = 'world', } obj1.self = obj1 - const obj2 = { - hello: 'everybody', - array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], - fn: () => { + local obj2 = { + 5, + hello = 'everybody', + array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, + fn = function() return 'hello' - }, + end, } obj2.self = obj2 + obj = { obj1, obj2 } +` - console.time('Insert complex objects') - state.global.set('obj', { obj1, obj2 }) - console.timeEnd('Insert complex objects') -} - -const insertComplexObjectsWithoutProxy = async () => { - const lua = await Lua.load() - const state = lua.createState({ - enableProxy: false, - }) +function createComplexObjects() { const obj1 = { hello: 'world', } obj1.self = obj1 + const obj2 = { hello: 'everybody', array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], - fn: () => { - return 'hello' - }, + fn: () => 'hello', } obj2.self = obj2 - console.time('Insert complex objects without proxy') - state.global.set('obj', { obj1, obj2 }) - console.timeEnd('Insert complex objects without proxy') + return { obj1, obj2 } } -const getComplexObjects = async () => { - const lua = await Lua.load() - const state = lua.createState() - await state.doString(` - local obj1 = { - hello = 'world', +function createStateBenchmark(lua, stateOptions = {}) { + return function runCreateState() { + const state = lua.createState(stateOptions) + state.global.close() + } +} + +function createRawHeapsortBenchmark(lua) { + return function runRawHeapsort() { + const state = lua.createState() + try { + assertStatus(state.global.lua.luaL_loadstring(state.global.address, heapsort), 'Load raw heapsort') + assertStatus(state.global.lua.lua_pcallk(state.global.address, 0, 1, 0, 0, null), 'Compile raw heapsort') + assertStatus(state.global.lua.lua_pcallk(state.global.address, 0, 1, 0, 0, null), 'Execute raw heapsort') + } finally { + state.global.close() + } + } +} + +function createInteropHeapsortBenchmark(lua) { + return async function runInteropHeapsort() { + const state = lua.createState() + try { + const executeHeapsort = await state.doString(heapsort) + assert.equal(executeHeapsort(), 10) + } finally { + state.global.close() + } + } +} + +function createInsertObjectsBenchmark(lua, stateOptions = {}) { + return function runInsertObjects() { + const state = lua.createState(stateOptions) + try { + state.global.set('obj', createComplexObjects()) + } finally { + state.global.close() } - obj1.self = obj1 - local obj2 = { - 5, - hello = 'everybody', - array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, - fn = function() - return 'hello' - end + } +} + +function createGetObjectsBenchmark(lua) { + return async function runGetObjects() { + const state = lua.createState() + try { + await state.doString(luaObjectFixture) + state.global.get('obj') + } finally { + state.global.close() } - obj2.self = obj2 - obj = { obj1, obj2 } - `) + } +} - console.time('Get complex objects') - state.global.get('obj') - console.timeEnd('Get complex objects') +function assertStatus(status, label) { + if (status !== 0) { + throw new Error(`${label} failed with status ${status}`) + } } -Promise.resolve() - .then(createFactory) - .then(createState) - .then(createStateWithoutSuperpowers) - .then(runHeapsort) - .then(runInteropedHeapsort) - .then(insertComplexObjects) - .then(insertComplexObjectsWithoutProxy) - .then(getComplexObjects) - .catch(console.error) +export async function runStepBench(options = {}) { + const lua = await Lua.load() + + return runBenchmarks({ + title: 'Operation benchmarks', + benches: [ + { name: 'Create factory', run: () => Lua.load() }, + { name: 'Create state', run: createStateBenchmark(lua) }, + { + name: 'Create state without superpowers', + run: createStateBenchmark(lua, { + enableProxy: false, + injectObjects: false, + openStandardLibs: false, + }), + }, + { name: 'Run raw heapsort', run: createRawHeapsortBenchmark(lua) }, + { name: 'Run interoped heapsort', run: createInteropHeapsortBenchmark(lua) }, + { name: 'Insert complex objects', run: createInsertObjectsBenchmark(lua) }, + { + name: 'Insert complex objects without proxy', + run: createInsertObjectsBenchmark(lua, { + enableProxy: false, + }), + }, + { name: 'Get complex objects', run: createGetObjectsBenchmark(lua) }, + ], + options, + }) +} + +if (isMainModule(import.meta.url)) { + await runStepBench(parseBenchOptions()) +} diff --git a/bench/utils.js b/bench/utils.js new file mode 100644 index 0000000..798334c --- /dev/null +++ b/bench/utils.js @@ -0,0 +1,240 @@ +import { readFileSync, statSync } from 'node:fs' +import path from 'node:path' +import { performance } from 'node:perf_hooks' +import { pathToFileURL } from 'node:url' + +const DEFAULT_OPTIONS = Object.freeze({ + filter: undefined, + help: false, + iterations: 50, + suite: 'all', + warmup: 5, +}) + +export function isMainModule(metaUrl) { + if (!process.argv[1]) { + return false + } + + return pathToFileURL(path.resolve(process.argv[1])).href === metaUrl +} + +export function readBenchAsset(fileName) { + return readFileSync(path.resolve(import.meta.dirname, fileName), 'utf-8') +} + +export function parseBenchOptions(argv = process.argv.slice(2), overrides = {}) { + const options = { ...DEFAULT_OPTIONS, ...overrides } + + for (let index = 0; index < argv.length; index++) { + const arg = argv[index] + + switch (arg) { + case '--iterations': + case '-i': + options.iterations = parseIntegerOption(argv[++index], arg, { min: 1 }) + break + case '--warmup': + case '-w': + options.warmup = parseIntegerOption(argv[++index], arg, { min: 0 }) + break + case '--filter': + case '-f': + options.filter = parseStringOption(argv[++index], arg) + break + case '--suite': + case '-s': + options.suite = parseSuiteOption(argv[++index], arg) + break + case '--help': + case '-h': + options.help = true + break + default: + throw new Error(`Unknown benchmark option: ${arg}`) + } + } + + return options +} + +export function printBenchUsage() { + console.log(`Usage: npm run bench -- [options] + +Options: + -i, --iterations Measured iterations per benchmark (default: ${DEFAULT_OPTIONS.iterations}) + -w, --warmup Warmup iterations per benchmark (default: ${DEFAULT_OPTIONS.warmup}) + -s, --suite Which suite to run: all, steps, comparisons + -f, --filter Only run benchmarks whose name includes the given text + -h, --help Show this help message`) +} + +export function printArtifactSizes() { + const artifacts = [ + { label: 'glue.js', path: path.resolve(import.meta.dirname, '../build/glue.js') }, + { label: 'glue.wasm', path: path.resolve(import.meta.dirname, '../build/glue.wasm') }, + ] + + console.log('Artifacts') + for (const artifact of artifacts) { + const size = readFileSize(artifact.path) + if (size === undefined) { + console.log(`${artifact.label}: missing (${artifact.path})`) + continue + } + + console.log(`${artifact.label}: ${formatBytes(size)} (${size} bytes)`) + } +} + +export async function runBenchmarks({ title, benches, options }) { + const activeBenches = filterBenches(benches, options.filter) + if (activeBenches.length === 0) { + throw new Error(`No benchmarks matched filter "${options.filter}"`) + } + + console.log(`\n${title}`) + console.log(`iterations=${options.iterations} warmup=${options.warmup}`) + + const results = [] + for (const bench of activeBenches) { + console.log(`running ${bench.name}...`) + results.push({ + name: bench.name, + stats: await benchmark(bench.run, options), + }) + } + + printResults(results) + return results +} + +async function benchmark(run, options) { + for (let iteration = 0; iteration < options.warmup; iteration++) { + await run() + } + + const samples = [] + for (let iteration = 0; iteration < options.iterations; iteration++) { + const start = performance.now() + await run() + samples.push(performance.now() - start) + } + + return calculateStats(samples) +} + +function calculateStats(samples) { + const sortedSamples = [...samples].sort((left, right) => left - right) + const total = samples.reduce((sum, sample) => sum + sample, 0) + const average = total / samples.length + const variance = samples.reduce((sum, sample) => sum + (sample - average) ** 2, 0) / samples.length + + return { + average, + max: sortedSamples.at(-1), + median: percentile(sortedSamples, 0.5), + min: sortedSamples[0], + stdDev: Math.sqrt(variance), + } +} + +function percentile(sortedSamples, fraction) { + const index = (sortedSamples.length - 1) * fraction + const lowerIndex = Math.floor(index) + const upperIndex = Math.ceil(index) + const lower = sortedSamples[lowerIndex] + const upper = sortedSamples[upperIndex] + + if (lowerIndex === upperIndex) { + return lower + } + + return lower + (upper - lower) * (index - lowerIndex) +} + +function printResults(results) { + const fastestAverage = Math.min(...results.map((result) => result.stats.average)) + const rows = results.map((result) => [ + result.name, + formatMilliseconds(result.stats.average), + formatMilliseconds(result.stats.median), + formatMilliseconds(result.stats.min), + formatMilliseconds(result.stats.max), + formatMilliseconds(result.stats.stdDev), + `${(result.stats.average / fastestAverage).toFixed(2)}x`, + ]) + + const headers = ['benchmark', 'avg', 'median', 'min', 'max', 'stddev', 'relative'] + const widths = headers.map((header, columnIndex) => + Math.max(header.length, ...rows.map((row) => row[columnIndex].length)), + ) + + console.log('') + console.log(formatRow(headers, widths)) + console.log(formatRow(widths.map((width) => '-'.repeat(width)), widths)) + for (const row of rows) { + console.log(formatRow(row, widths)) + } +} + +function formatRow(columns, widths) { + return columns.map((column, index) => column.padEnd(widths[index])).join(' ') +} + +function formatMilliseconds(value) { + return `${value.toFixed(3)} ms` +} + +function formatBytes(bytes) { + const units = ['B', 'KB', 'MB', 'GB'] + let size = bytes + let unitIndex = 0 + + while (size >= 1024 && unitIndex < units.length - 1) { + size /= 1024 + unitIndex++ + } + + return `${size.toFixed(unitIndex === 0 ? 0 : 2)} ${units[unitIndex]}` +} + +function filterBenches(benches, filter) { + if (!filter) { + return benches + } + + const normalizedFilter = filter.toLowerCase() + return benches.filter((bench) => bench.name.toLowerCase().includes(normalizedFilter)) +} + +function parseIntegerOption(rawValue, flagName, { min }) { + const value = Number.parseInt(parseStringOption(rawValue, flagName), 10) + if (!Number.isInteger(value) || value < min) { + throw new Error(`${flagName} must be an integer greater than or equal to ${min}`) + } + return value +} + +function parseSuiteOption(rawValue, flagName) { + const value = parseStringOption(rawValue, flagName) + if (!['all', 'comparisons', 'steps'].includes(value)) { + throw new Error(`${flagName} must be one of: all, comparisons, steps`) + } + return value +} + +function parseStringOption(rawValue, flagName) { + if (rawValue === undefined) { + throw new Error(`Missing value for ${flagName}`) + } + return rawValue +} + +function readFileSize(filePath) { + try { + return statSync(filePath).size + } catch { + return undefined + } +} diff --git a/package-lock.json b/package-lock.json index f6f2eb7..19406af 100644 --- a/package-lock.json +++ b/package-lock.json @@ -23,7 +23,6 @@ "oxfmt": "0.40.0", "oxlint": "1.55.0", "rolldown": "1.0.0-rc.9", - "rollup-plugin-copy": "3.5.0", "tslib": "2.8.1", "typescript": "5.9.3" } @@ -97,44 +96,6 @@ "url": "https://github.com/sponsors/Brooooooklyn" } }, - "node_modules/@nodelib/fs.scandir": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", - "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@nodelib/fs.stat": "2.0.5", - "run-parallel": "^1.1.9" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/@nodelib/fs.stat": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", - "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 8" - } - }, - "node_modules/@nodelib/fs.walk": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", - "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@nodelib/fs.scandir": "2.1.5", - "fastq": "^1.6.0" - }, - "engines": { - "node": ">= 8" - } - }, "node_modules/@oxc-project/types": { "version": "0.115.0", "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.115.0.tgz", @@ -1081,34 +1042,6 @@ "integrity": "sha512-cMQm7pxu6BxtHyqJ7mQZ2kXWV5SLmugybFdHCBbJ5eHzOo6VhBckEgAT3//rP5FwPHNPeEiq4SmQ5ucBwsOo4Q==", "license": "MIT" }, - "node_modules/@types/fs-extra": { - "version": "8.1.5", - "resolved": "https://registry.npmjs.org/@types/fs-extra/-/fs-extra-8.1.5.tgz", - "integrity": "sha512-0dzKcwO+S8s2kuF5Z9oUWatQJj5Uq/iqphEtE3GQJVRRYm/tD1LglU2UnXi2A8jLq5umkGouOXOR9y0n613ZwQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@types/glob": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/@types/glob/-/glob-7.2.0.tgz", - "integrity": "sha512-ZUxbzKl0IfJILTS6t7ip5fQQM/J3TJYubDm3nMbgubNNYS62eXeUpoLUC8/7fJNiFYHTrGPQn7hspDUzIHX3UA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/minimatch": "*", - "@types/node": "*" - } - }, - "node_modules/@types/minimatch": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/@types/minimatch/-/minimatch-5.1.2.tgz", - "integrity": "sha512-K0VQKziLUWkVKiRVrx4a40iPaxTUefQmjtkQofBkYRcoaaL/8rhwDWww9qWbrgicNOgnpIsMxyNIUM4+n6dUIA==", - "dev": true, - "license": "MIT" - }, "node_modules/@types/node": { "version": "25.5.0", "resolved": "https://registry.npmjs.org/@types/node/-/node-25.5.0.tgz", @@ -1155,16 +1088,6 @@ "dev": true, "license": "Python-2.0" }, - "node_modules/array-union": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/array-union/-/array-union-2.1.0.tgz", - "integrity": "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/balanced-match": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", @@ -1182,19 +1105,6 @@ "balanced-match": "^1.0.0" } }, - "node_modules/braces": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", - "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", - "dev": true, - "license": "MIT", - "dependencies": { - "fill-range": "^7.1.1" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/browser-stdout": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/browser-stdout/-/browser-stdout-1.3.1.tgz", @@ -1380,20 +1290,6 @@ "dev": true, "license": "MIT" }, - "node_modules/colorette": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/colorette/-/colorette-1.4.0.tgz", - "integrity": "sha512-Y2oEozpomLn7Q3HFP7dpww7AtMJplbM9lGZP6RDfHqmbeRjiwRg4n6VM6j4KLmRke85uWEI7JqF17f3pqdRA0g==", - "dev": true, - "license": "MIT" - }, - "node_modules/concat-map": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", - "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", - "dev": true, - "license": "MIT" - }, "node_modules/cross-spawn": { "version": "7.0.6", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", @@ -1450,19 +1346,6 @@ "node": ">=0.3.1" } }, - "node_modules/dir-glob": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-3.0.1.tgz", - "integrity": "sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==", - "dev": true, - "license": "MIT", - "dependencies": { - "path-type": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/eastasianwidth": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", @@ -1500,46 +1383,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/fast-glob": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.2.tgz", - "integrity": "sha512-oX2ruAFQwf/Orj8m737Y5adxDQO0LAB7/S5MnxCdTNDd4p6BsyIVsv9JQsATbTSq8KHRpLwIHbVlUNatxd+1Ow==", - "dev": true, - "license": "MIT", - "dependencies": { - "@nodelib/fs.stat": "^2.0.2", - "@nodelib/fs.walk": "^1.2.3", - "glob-parent": "^5.1.2", - "merge2": "^1.3.0", - "micromatch": "^4.0.4" - }, - "engines": { - "node": ">=8.6.0" - } - }, - "node_modules/fast-glob/node_modules/glob-parent": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", - "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", - "dev": true, - "license": "ISC", - "dependencies": { - "is-glob": "^4.0.1" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/fastq": { - "version": "1.18.0", - "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.18.0.tgz", - "integrity": "sha512-QKHXPW0hD8g4UET03SdOdunzSouc9N4AuHdsX8XNcTsuz+yYFILVNIX4l9yHABMhiEI9Db0JTTIpu0wB+Y1QQw==", - "dev": true, - "license": "ISC", - "dependencies": { - "reusify": "^1.0.4" - } - }, "node_modules/fengari": { "version": "0.1.5", "resolved": "https://registry.npmjs.org/fengari/-/fengari-0.1.5.tgz", @@ -1552,19 +1395,6 @@ "tmp": "^0.2.5" } }, - "node_modules/fill-range": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", - "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", - "dev": true, - "license": "MIT", - "dependencies": { - "to-regex-range": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/find-up": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", @@ -1609,28 +1439,6 @@ "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/fs-extra": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz", - "integrity": "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==", - "dev": true, - "license": "MIT", - "dependencies": { - "graceful-fs": "^4.2.0", - "jsonfile": "^4.0.0", - "universalify": "^0.1.0" - }, - "engines": { - "node": ">=6 <7 || >=8" - } - }, - "node_modules/fs.realpath": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", - "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", - "dev": true, - "license": "ISC" - }, "node_modules/get-caller-file": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", @@ -1662,79 +1470,6 @@ "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/globby": { - "version": "10.0.1", - "resolved": "https://registry.npmjs.org/globby/-/globby-10.0.1.tgz", - "integrity": "sha512-sSs4inE1FB2YQiymcmTv6NWENryABjUNPeWhOvmn4SjtKybglsyPZxFB3U1/+L1bYi0rNZDqCLlHyLYDl1Pq5A==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/glob": "^7.1.1", - "array-union": "^2.1.0", - "dir-glob": "^3.0.1", - "fast-glob": "^3.0.3", - "glob": "^7.1.3", - "ignore": "^5.1.1", - "merge2": "^1.2.3", - "slash": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/globby/node_modules/brace-expansion": { - "version": "1.1.11", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", - "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "node_modules/globby/node_modules/glob": { - "version": "7.2.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", - "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "deprecated": "Glob versions prior to v9 are no longer supported", - "dev": true, - "license": "ISC", - "dependencies": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.1.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - }, - "engines": { - "node": "*" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/globby/node_modules/minimatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", - "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", - "dev": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^1.1.7" - }, - "engines": { - "node": "*" - } - }, - "node_modules/graceful-fs": { - "version": "4.2.11", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", - "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", - "dev": true, - "license": "ISC" - }, "node_modules/has-flag": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", @@ -1755,45 +1490,6 @@ "he": "bin/he" } }, - "node_modules/ignore": { - "version": "5.3.2", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", - "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 4" - } - }, - "node_modules/inflight": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", - "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", - "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", - "dev": true, - "license": "ISC", - "dependencies": { - "once": "^1.3.0", - "wrappy": "1" - } - }, - "node_modules/inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "dev": true, - "license": "ISC" - }, - "node_modules/is-extglob": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", - "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/is-fullwidth-code-point": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", @@ -1804,29 +1500,6 @@ "node": ">=8" } }, - "node_modules/is-glob": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", - "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-extglob": "^2.1.1" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/is-number": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", - "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.12.0" - } - }, "node_modules/is-path-inside": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.3.tgz", @@ -1847,16 +1520,6 @@ "node": ">=8" } }, - "node_modules/is-plain-object": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-3.0.1.tgz", - "integrity": "sha512-Xnpx182SBMrr/aBik8y+GuR4U1L9FqMSojwDQwPMmxyC6bvEqly9UBCxhauBF5vNh2gwWJNX6oDV7O+OM4z34g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/is-unicode-supported": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz", @@ -1906,16 +1569,6 @@ "js-yaml": "bin/js-yaml.js" } }, - "node_modules/jsonfile": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", - "integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==", - "dev": true, - "license": "MIT", - "optionalDependencies": { - "graceful-fs": "^4.1.6" - } - }, "node_modules/locate-path": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", @@ -1956,43 +1609,6 @@ "dev": true, "license": "ISC" }, - "node_modules/merge2": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", - "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 8" - } - }, - "node_modules/micromatch": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", - "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", - "dev": true, - "license": "MIT", - "dependencies": { - "braces": "^3.0.3", - "picomatch": "^2.3.1" - }, - "engines": { - "node": ">=8.6" - } - }, - "node_modules/micromatch/node_modules/picomatch": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", - "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8.6" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, "node_modules/minimatch": { "version": "9.0.5", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz", @@ -2079,16 +1695,6 @@ "dev": true, "license": "MIT" }, - "node_modules/once": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", - "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", - "dev": true, - "license": "ISC", - "dependencies": { - "wrappy": "1" - } - }, "node_modules/oxfmt": { "version": "0.40.0", "resolved": "https://registry.npmjs.org/oxfmt/-/oxfmt-0.40.0.tgz", @@ -2223,16 +1829,6 @@ "node": ">=8" } }, - "node_modules/path-is-absolute": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", - "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/path-key": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", @@ -2260,16 +1856,6 @@ "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/path-type": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz", - "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", @@ -2277,27 +1863,6 @@ "dev": true, "license": "ISC" }, - "node_modules/queue-microtask": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", - "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, "node_modules/randombytes": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", @@ -2342,17 +1907,6 @@ "node": ">=0.10.0" } }, - "node_modules/reusify": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.0.4.tgz", - "integrity": "sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==", - "dev": true, - "license": "MIT", - "engines": { - "iojs": ">=1.0.0", - "node": ">=0.10.0" - } - }, "node_modules/rolldown": { "version": "1.0.0-rc.9", "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.0.0-rc.9.tgz", @@ -2387,47 +1941,6 @@ "@rolldown/binding-win32-x64-msvc": "1.0.0-rc.9" } }, - "node_modules/rollup-plugin-copy": { - "version": "3.5.0", - "resolved": "https://registry.npmjs.org/rollup-plugin-copy/-/rollup-plugin-copy-3.5.0.tgz", - "integrity": "sha512-wI8D5dvYovRMx/YYKtUNt3Yxaw4ORC9xo6Gt9t22kveWz1enG9QrhVlagzwrxSC455xD1dHMKhIJkbsQ7d48BA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/fs-extra": "^8.0.1", - "colorette": "^1.1.0", - "fs-extra": "^8.1.0", - "globby": "10.0.1", - "is-plain-object": "^3.0.0" - }, - "engines": { - "node": ">=8.3" - } - }, - "node_modules/run-parallel": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", - "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "dependencies": { - "queue-microtask": "^1.2.2" - } - }, "node_modules/safe-buffer": { "version": "5.2.1", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", @@ -2495,16 +2008,6 @@ "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/slash": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", - "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/sprintf-js": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.3.tgz", @@ -2662,19 +2165,6 @@ "node": ">=14.14" } }, - "node_modules/to-regex-range": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", - "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-number": "^7.0.0" - }, - "engines": { - "node": ">=8.0" - } - }, "node_modules/tslib": { "version": "2.8.1", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", @@ -2688,7 +2178,6 @@ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", "dev": true, "license": "Apache-2.0", - "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -2704,16 +2193,6 @@ "dev": true, "license": "MIT" }, - "node_modules/universalify": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz", - "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 4.0.0" - } - }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", @@ -2832,13 +2311,6 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, - "node_modules/wrappy": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", - "dev": true, - "license": "ISC" - }, "node_modules/y18n": { "version": "5.0.8", "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", diff --git a/package.json b/package.json index 3afca7c..a04eb57 100755 --- a/package.json +++ b/package.json @@ -9,6 +9,7 @@ "build:wasm:dev": "node utils/build-wasm dev", "build:wasm": "node utils/build-wasm", "start": "rolldown -w -c", + "bench": "npm run build && node bench/index.js", "test": "mocha --parallel --require ./test/boot.js test/*.test.js", "luatests": "node --experimental-import-meta-resolve test/luatests.js", "build": "rolldown -c && tsc -d --emitDeclarationOnly --rootDir src --declarationDir dist", @@ -48,7 +49,6 @@ "oxfmt": "0.40.0", "oxlint": "1.55.0", "rolldown": "1.0.0-rc.9", - "rollup-plugin-copy": "3.5.0", "tslib": "2.8.1", "typescript": "5.9.3" }, diff --git a/rolldown.config.ts b/rolldown.config.ts index 5186a59..4446d35 100644 --- a/rolldown.config.ts +++ b/rolldown.config.ts @@ -1,5 +1,6 @@ +import { copyFile } from 'node:fs/promises' import { defineConfig } from 'rolldown' -import copy from 'rollup-plugin-copy' +import { replacePlugin } from 'rolldown/plugins' import pkg from './package.json' with { type: 'json' } export default defineConfig({ @@ -9,12 +10,12 @@ export default defineConfig({ format: 'esm', sourcemap: true, }, - external: ['module', 'node:fs', 'node:child_process'], - define: { - // Webpack workaround: https://github.com/webpack/webpack/issues/16878 - 'import.meta': 'Object(import.meta)', - }, + external: ['node:module', 'node:fs', 'node:child_process'], plugins: [ + replacePlugin({ + // Webpack workaround: https://github.com/webpack/webpack/issues/16878 + 'import.meta': 'Object(import.meta)', + }), { name: 'package-version', resolveId(source) { @@ -28,8 +29,11 @@ export default defineConfig({ } }, }, - copy({ - targets: [{ src: 'build/glue.wasm', dest: 'dist' }], - }), + { + name: 'copy-glue-wasm', + async writeBundle() { + await copyFile('build/glue.wasm', 'dist/glue.wasm') + }, + }, ], }) diff --git a/utils/build-wasm.sh b/utils/build-wasm.sh index b044209..f64546f 100755 --- a/utils/build-wasm.sh +++ b/utils/build-wasm.sh @@ -9,7 +9,7 @@ if [ "$1" == "dev" ]; then extension="-O0 -g3 -s ASSERTIONS=1 -s SAFE_HEAP=1 -s STACK_OVERFLOW_CHECK=2" else - extension="-O3" + extension="-Oz -fno-inline-functions -s BINARYEN_EXTRA_PASSES=gufa-optimizing" fi emcc \ From c3268919b999975788aef89daec84f4982f71aee Mon Sep 17 00:00:00 2001 From: Gabriel Francisco Date: Sat, 14 Mar 2026 14:38:19 -0300 Subject: [PATCH 32/83] lint and readme benchmark --- .github/workflows/publish.yml | 16 ++++++++-------- README.md | 17 +++++++++-------- bench/utils.js | 11 +++++++---- src/global.ts | 18 ++++-------------- 4 files changed, 28 insertions(+), 34 deletions(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 3dbc317..b711daf 100755 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -9,19 +9,19 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout repository - uses: actions/checkout@v4 + uses: actions/checkout@v6 with: submodules: recursive - name: Setup EMSDK uses: mymindstorm/setup-emsdk@v14 with: - version: 4.0.1 + version: 5.0.2 - - name: Use Node.js 22.x - uses: actions/setup-node@v4 + - name: Use Node.js 24.x + uses: actions/setup-node@v6 with: - node-version: 22.x + node-version: 24.x - name: Install dependencies run: npm ci @@ -42,7 +42,7 @@ jobs: run: npm run luatests - name: Upload build artifact - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v7 with: name: build-artifact path: | @@ -57,10 +57,10 @@ jobs: needs: build steps: - name: Checkout repository - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Download build artifact - uses: actions/download-artifact@v4 + uses: actions/download-artifact@v8 with: name: build-artifact path: build-artifact diff --git a/README.md b/README.md index a0f63e9..9d42ebd 100644 --- a/README.md +++ b/README.md @@ -74,17 +74,18 @@ $: ./sum.lua 10 30 ## When to use wasmoon and fengari -Wasmoon compiles the [official Lua code](https://github.com/lua/lua) to webassembly and creates an abstraction layer to interop between Lua and JS, instead of [fengari](https://github.com/fengari-lua/fengari), that is an entire Lua VM rewritten in JS. +Wasmoon compiles the [official Lua code](https://github.com/lua/lua) to WebAssembly and creates an abstraction layer to interop between Lua and JS, instead of [fengari](https://github.com/fengari-lua/fengari), which is an entire Lua VM rewritten in JS. ### Performance -Because of wasm, wasmoon will run Lua code much faster than fengari, but if you are going to interop a lot between JS and Lua, this may be not be true anymore, you probably should test on you specific use case to take the prove. +Because of WebAssembly, wasmoon runs Lua code significantly faster than fengari. The table below shows results from a [heap sort benchmark](https://github.com/ceifa/wasmoon/blob/main/bench/heapsort.lua) sorting a list of 2,000 numbers (100 iterations, 5 warmup): -This is the results running a [heap sort code](https://github.com/ceifa/wasmoon/blob/main/bench/heapsort.lua) in a list of 2k numbers 10x(less is better): +| | avg | median | min | max | stddev | relative | +| ---------------- | ---------- | ---------- | ---------- | ---------- | --------- | -------- | +| **Wasmoon** | 13.41 ms | 13.07 ms | 12.20 ms | 16.23 ms | 1.12 ms | 1.00x | +| **Fengari** | 137.36 ms | 138.51 ms | 119.70 ms | 165.54 ms | 11.16 ms | 10.24x | -| wasmoon | fengari | -| -------- | --------- | -| 15.267ms | 389.923ms | +Wasmoon is **~10x faster** than fengari for pure Lua execution. If your use case involves heavy interop between JS and Lua, the difference may be smaller, benchmark your specific scenario. ### Size @@ -92,8 +93,8 @@ Fengari is smaller than wasmoon, which can improve the user experience if in web | | wasmoon | fengari | | ----------- | ------- | ------- | -| **plain** | 393kB | 214kB | -| **gzipped** | 130kB | 69kB | +| **plain** | 357kB | 211kB | +| **gzipped** | 123kB | 69kB | ## Fixing common errors on web environment diff --git a/bench/utils.js b/bench/utils.js index 798334c..4c6c757 100644 --- a/bench/utils.js +++ b/bench/utils.js @@ -166,13 +166,16 @@ function printResults(results) { ]) const headers = ['benchmark', 'avg', 'median', 'min', 'max', 'stddev', 'relative'] - const widths = headers.map((header, columnIndex) => - Math.max(header.length, ...rows.map((row) => row[columnIndex].length)), - ) + const widths = headers.map((header, columnIndex) => Math.max(header.length, ...rows.map((row) => row[columnIndex].length))) console.log('') console.log(formatRow(headers, widths)) - console.log(formatRow(widths.map((width) => '-'.repeat(width)), widths)) + console.log( + formatRow( + widths.map((width) => '-'.repeat(width)), + widths, + ), + ) for (const row of rows) { console.log(formatRow(row, widths)) } diff --git a/src/global.ts b/src/global.ts index e5df71d..428aed5 100755 --- a/src/global.ts +++ b/src/global.ts @@ -36,11 +36,7 @@ export default class Global extends Thread { const endMemoryDelta = pointer ? newSize - oldSize : newSize const endMemory = memoryStats.memoryUsed + endMemoryDelta - if ( - newSize > oldSize && - memoryStats.memoryMax && - endMemory > memoryStats.memoryMax - ) { + if (newSize > oldSize && memoryStats.memoryMax && endMemory > memoryStats.memoryMax) { return 0 } @@ -179,17 +175,13 @@ export default class Global extends Thread { const type = this.lua.lua_getglobal(this.address, name) try { if (type !== LuaType.Table) { - throw new TypeError( - `Unexpected type in ${name}. Expected ${LuaType[LuaType.Table]}. Got ${LuaType[type]}.`, - ) + throw new TypeError(`Unexpected type in ${name}. Expected ${LuaType[LuaType.Table]}. Got ${LuaType[type]}.`) } callback(startStackTop + 1) } finally { // +1 for the table if (this.getTop() !== startStackTop + 1) { - console.warn( - `getTable: expected stack size ${startStackTop + 1} got ${this.getTop()}`, - ) + console.warn(`getTable: expected stack size ${startStackTop + 1} got ${this.getTop()}`) } this.setTop(startStackTop) } @@ -221,9 +213,7 @@ export default class Global extends Thread { private getMemoryStatsRef(): LuaMemoryStats { if (!this.memoryStats) { - throw new Error( - 'Memory allocations is not being traced, please build engine with { traceAllocations: true }', - ) + throw new Error('Memory allocations is not being traced, please build engine with { traceAllocations: true }') } return this.memoryStats From 4d8c2d4c455f4f6cf24ce4a21d2e9c6aaa337522 Mon Sep 17 00:00:00 2001 From: Gabriel Francisco Date: Tue, 24 Mar 2026 21:35:22 -0300 Subject: [PATCH 33/83] nodefs --- .github/workflows/publish.yml | 2 +- .github/workflows/test.yml | 2 + package-lock.json | 532 ++++++++++++++++++---------------- package.json | 9 +- src/module.ts | 332 ++++++++++++++++----- test/browser.test.js | 200 +++++++++++++ test/node.test.js | 250 ++++++++++++++++ test/nodefs.test.js | 410 ++++++++++++++++++++++++++ 8 files changed, 1424 insertions(+), 313 deletions(-) create mode 100644 test/browser.test.js create mode 100644 test/node.test.js create mode 100644 test/nodefs.test.js diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index b711daf..510a043 100755 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -16,7 +16,7 @@ jobs: - name: Setup EMSDK uses: mymindstorm/setup-emsdk@v14 with: - version: 5.0.2 + version: 5.0.4 - name: Use Node.js 24.x uses: actions/setup-node@v6 diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index e18e2c3..54fedfb 100755 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -17,6 +17,8 @@ jobs: with: submodules: recursive - uses: mymindstorm/setup-emsdk@v14 + with: + version: 5.0.4 - name: Use Node.js ${{ matrix.node-version }} uses: actions/setup-node@v6 with: diff --git a/package-lock.json b/package-lock.json index 19406af..1c200d0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -20,17 +20,18 @@ "chai-as-promised": "8.0.2", "fengari": "0.1.5", "mocha": "11.7.5", - "oxfmt": "0.40.0", - "oxlint": "1.55.0", - "rolldown": "1.0.0-rc.9", + "oxfmt": "0.42.0", + "oxlint": "1.57.0", + "playwright": "1.58.2", + "rolldown": "1.0.0-rc.11", "tslib": "2.8.1", - "typescript": "5.9.3" + "typescript": "6.0.2" } }, "node_modules/@emnapi/core": { - "version": "1.9.0", - "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.9.0.tgz", - "integrity": "sha512-0DQ98G9ZQZOxfUcQn1waV2yS8aWdZ6kJMbYCJB3oUBecjWYO1fqJ+a1DRfPF3O5JEkwqwP1A9QEN/9mYm2Yd0w==", + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.9.1.tgz", + "integrity": "sha512-mukuNALVsoix/w1BJwFzwXBN/dHeejQtuVzcDsfOEsdpCumXb/E9j8w11h5S54tT1xhifGfbbSm/ICrObRb3KA==", "dev": true, "license": "MIT", "optional": true, @@ -40,9 +41,9 @@ } }, "node_modules/@emnapi/runtime": { - "version": "1.9.0", - "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.9.0.tgz", - "integrity": "sha512-QN75eB0IH2ywSpRpNddCRfQIhmJYBCJ1x5Lb3IscKAL8bMnVAKnRg8dCoXbHzVLLH7P38N2Z3mtulB7W0J0FKw==", + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.9.1.tgz", + "integrity": "sha512-VYi5+ZVLhpgK4hQ0TAjiQiZ6ol0oe4mBx7mVv7IflsiEp0OWoVsp/+f9Vc1hOhE0TtkORVrI1GvzyreqpgWtkA==", "dev": true, "license": "MIT", "optional": true, @@ -97,9 +98,9 @@ } }, "node_modules/@oxc-project/types": { - "version": "0.115.0", - "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.115.0.tgz", - "integrity": "sha512-4n91DKnebUS4yjUHl2g3/b2T+IUdCfmoZGhmwsovZCDaJSs+QkVAM+0AqqTxHSsHfeiMuueT75cZaZcT/m0pSw==", + "version": "0.122.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.122.0.tgz", + "integrity": "sha512-oLAl5kBpV4w69UtFZ9xqcmTi+GENWOcPF7FCrczTiBbmC0ibXxCwyvZGbO39rCVEuLGAZM84DH0pUIyyv/YJzA==", "dev": true, "license": "MIT", "funding": { @@ -107,9 +108,9 @@ } }, "node_modules/@oxfmt/binding-android-arm-eabi": { - "version": "0.40.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm-eabi/-/binding-android-arm-eabi-0.40.0.tgz", - "integrity": "sha512-S6zd5r1w/HmqR8t0CTnGjFTBLDq2QKORPwriCHxo4xFNuhmOTABGjPaNvCJJVnrKBLsohOeiDX3YqQfJPF+FXw==", + "version": "0.42.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm-eabi/-/binding-android-arm-eabi-0.42.0.tgz", + "integrity": "sha512-dsqPTYsozeokRjlrt/b4E7Pj0z3eS3Eg74TWQuuKbjY4VttBmA88rB7d50Xrd+TZ986qdXCNeZRPEzZHAe+jow==", "cpu": [ "arm" ], @@ -124,9 +125,9 @@ } }, "node_modules/@oxfmt/binding-android-arm64": { - "version": "0.40.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm64/-/binding-android-arm64-0.40.0.tgz", - "integrity": "sha512-/mbS9UUP/5Vbl2D6osIdcYiP0oie63LKMoTyGj5hyMCK/SFkl3EhtyRAfdjPvuvHC0SXdW6ePaTKkBSq1SNcIw==", + "version": "0.42.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm64/-/binding-android-arm64-0.42.0.tgz", + "integrity": "sha512-t+aAjHxcr5eOBphFHdg1ouQU9qmZZoRxnX7UOJSaTwSoKsb6TYezNKO0YbWytGXCECObRqNcUxPoPr0KaraAIg==", "cpu": [ "arm64" ], @@ -141,9 +142,9 @@ } }, "node_modules/@oxfmt/binding-darwin-arm64": { - "version": "0.40.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-arm64/-/binding-darwin-arm64-0.40.0.tgz", - "integrity": "sha512-wRt8fRdfLiEhnRMBonlIbKrJWixoEmn6KCjKE9PElnrSDSXETGZfPb8ee+nQNTobXkCVvVLytp2o0obAsxl78Q==", + "version": "0.42.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-arm64/-/binding-darwin-arm64-0.42.0.tgz", + "integrity": "sha512-ulpSEYMKg61C5bRMZinFHrKJYRoKGVbvMEXA5zM1puX3O9T6Q4XXDbft20yrDijpYWeuG59z3Nabt+npeTsM1A==", "cpu": [ "arm64" ], @@ -158,9 +159,9 @@ } }, "node_modules/@oxfmt/binding-darwin-x64": { - "version": "0.40.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-x64/-/binding-darwin-x64-0.40.0.tgz", - "integrity": "sha512-fzowhqbOE/NRy+AE5ob0+Y4X243WbWzDb00W+pKwD7d9tOqsAFbtWUwIyqqCoCLxj791m2xXIEeLH/3uz7zCCg==", + "version": "0.42.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-x64/-/binding-darwin-x64-0.42.0.tgz", + "integrity": "sha512-ttxLKhQYPdFiM8I/Ri37cvqChE4Xa562nNOsZFcv1CKTVLeEozXjKuYClNvxkXmNlcF55nzM80P+CQkdFBu+uQ==", "cpu": [ "x64" ], @@ -175,9 +176,9 @@ } }, "node_modules/@oxfmt/binding-freebsd-x64": { - "version": "0.40.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-freebsd-x64/-/binding-freebsd-x64-0.40.0.tgz", - "integrity": "sha512-agZ9ITaqdBjcerRRFEHB8s0OyVcQW8F9ZxsszjxzeSthQ4fcN2MuOtQFWec1ed8/lDa50jSLHVE2/xPmTgtCfQ==", + "version": "0.42.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-freebsd-x64/-/binding-freebsd-x64-0.42.0.tgz", + "integrity": "sha512-Og7QS3yI3tdIKYZ58SXik0rADxIk2jmd+/YvuHRyKULWpG4V2fR5V4hvKm624Mc0cQET35waPXiCQWvjQEjwYQ==", "cpu": [ "x64" ], @@ -192,9 +193,9 @@ } }, "node_modules/@oxfmt/binding-linux-arm-gnueabihf": { - "version": "0.40.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-0.40.0.tgz", - "integrity": "sha512-ZM2oQ47p28TP1DVIp7HL1QoMUgqlBFHey0ksHct7tMXoU5BqjNvPWw7888azzMt25lnyPODVuye1wvNbvVUFOA==", + "version": "0.42.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-0.42.0.tgz", + "integrity": "sha512-jwLOw/3CW4H6Vxcry4/buQHk7zm9Ne2YsidzTL1kpiMe4qqrRCwev3dkyWe2YkFmP+iZCQ7zku4KwjcLRoh8ew==", "cpu": [ "arm" ], @@ -209,9 +210,9 @@ } }, "node_modules/@oxfmt/binding-linux-arm-musleabihf": { - "version": "0.40.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-0.40.0.tgz", - "integrity": "sha512-RBFPAxRAIsMisKM47Oe6Lwdv6agZYLz02CUhVCD1sOv5ajAcRMrnwCFBPWwGXpazToW2mjnZxFos8TuFjTU15A==", + "version": "0.42.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-0.42.0.tgz", + "integrity": "sha512-XwXu2vkMtiq2h7tfvN+WA/9/5/1IoGAVCFPiiQUvcAuG3efR97KNcRGM8BetmbYouFotQ2bDal3yyjUx6IPsTg==", "cpu": [ "arm" ], @@ -226,9 +227,9 @@ } }, "node_modules/@oxfmt/binding-linux-arm64-gnu": { - "version": "0.40.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-0.40.0.tgz", - "integrity": "sha512-Nb2XbQ+wV3W2jSIihXdPj7k83eOxeSgYP3N/SRXvQ6ZYPIk6Q86qEh5Gl/7OitX3bQoQrESqm1yMLvZV8/J7dA==", + "version": "0.42.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-0.42.0.tgz", + "integrity": "sha512-ea7s/XUJoT7ENAtUQDudFe3nkSM3e3Qpz4nJFRdzO2wbgXEcjnchKLEsV3+t4ev3r8nWxIYr9NRjPWtnyIFJVA==", "cpu": [ "arm64" ], @@ -243,9 +244,9 @@ } }, "node_modules/@oxfmt/binding-linux-arm64-musl": { - "version": "0.40.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-musl/-/binding-linux-arm64-musl-0.40.0.tgz", - "integrity": "sha512-tGmWhLD/0YMotCdfezlT6tC/MJG/wKpo4vnQ3Cq+4eBk/BwNv7EmkD0VkD5F/dYkT3b8FNU01X2e8vvJuWoM1w==", + "version": "0.42.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-musl/-/binding-linux-arm64-musl-0.42.0.tgz", + "integrity": "sha512-+JA0YMlSdDqmacygGi2REp57c3fN+tzARD8nwsukx9pkCHK+6DkbAA9ojS4lNKsiBjIW8WWa0pBrBWhdZEqfuw==", "cpu": [ "arm64" ], @@ -260,9 +261,9 @@ } }, "node_modules/@oxfmt/binding-linux-ppc64-gnu": { - "version": "0.40.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-0.40.0.tgz", - "integrity": "sha512-rVbFyM3e7YhkVnp0IVYjaSHfrBWcTRWb60LEcdNAJcE2mbhTpbqKufx0FrhWfoxOrW/+7UJonAOShoFFLigDqQ==", + "version": "0.42.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-0.42.0.tgz", + "integrity": "sha512-VfnET0j4Y5mdfCzh5gBt0NK28lgn5DKx+8WgSMLYYeSooHhohdbzwAStLki9pNuGy51y4I7IoW8bqwAaCMiJQg==", "cpu": [ "ppc64" ], @@ -277,9 +278,9 @@ } }, "node_modules/@oxfmt/binding-linux-riscv64-gnu": { - "version": "0.40.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-0.40.0.tgz", - "integrity": "sha512-3ZqBw14JtWeEoLiioJcXSJz8RQyPE+3jLARnYM1HdPzZG4vk+Ua8CUupt2+d+vSAvMyaQBTN2dZK+kbBS/j5mA==", + "version": "0.42.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-0.42.0.tgz", + "integrity": "sha512-gVlCbmBkB0fxBWbhBj9rcxezPydsQHf4MFKeHoTSPicOQ+8oGeTQgQ8EeesSybWeiFPVRx3bgdt4IJnH6nOjAA==", "cpu": [ "riscv64" ], @@ -294,9 +295,9 @@ } }, "node_modules/@oxfmt/binding-linux-riscv64-musl": { - "version": "0.40.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-0.40.0.tgz", - "integrity": "sha512-JJ4PPSdcbGBjPvb+O7xYm2FmAsKCyuEMYhqatBAHMp/6TA6rVlf9Z/sYPa4/3Bommb+8nndm15SPFRHEPU5qFA==", + "version": "0.42.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-0.42.0.tgz", + "integrity": "sha512-zN5OfstL0avgt/IgvRu0zjQzVh/EPkcLzs33E9LMAzpqlLWiPWeMDZyMGFlSRGOdDjuNmlZBCgj0pFnK5u32TQ==", "cpu": [ "riscv64" ], @@ -311,9 +312,9 @@ } }, "node_modules/@oxfmt/binding-linux-s390x-gnu": { - "version": "0.40.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-0.40.0.tgz", - "integrity": "sha512-Kp0zNJoX9Ik77wUya2tpBY3W9f40VUoMQLWVaob5SgCrblH/t2xr/9B2bWHfs0WCefuGmqXcB+t0Lq77sbBmZw==", + "version": "0.42.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-0.42.0.tgz", + "integrity": "sha512-9X6+H2L0qMc2sCAgO9HS03bkGLMKvOFjmEdchaFlany3vNZOjnVui//D8k/xZAtQv2vaCs1reD5KAgPoIU4msA==", "cpu": [ "s390x" ], @@ -328,9 +329,9 @@ } }, "node_modules/@oxfmt/binding-linux-x64-gnu": { - "version": "0.40.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-gnu/-/binding-linux-x64-gnu-0.40.0.tgz", - "integrity": "sha512-7YTCNzleWTaQTqNGUNQ66qVjpoV6DjbCOea+RnpMBly2bpzrI/uu7Rr+2zcgRfNxyjXaFTVQKaRKjqVdeUfeVA==", + "version": "0.42.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-gnu/-/binding-linux-x64-gnu-0.42.0.tgz", + "integrity": "sha512-BajxJ6KQvMMdpXGPWhBGyjb2Jvx4uec0w+wi6TJZ6Tv7+MzPwe0pO8g5h1U0jyFgoaF7mDl6yKPW3ykWcbUJRw==", "cpu": [ "x64" ], @@ -345,9 +346,9 @@ } }, "node_modules/@oxfmt/binding-linux-x64-musl": { - "version": "0.40.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-musl/-/binding-linux-x64-musl-0.40.0.tgz", - "integrity": "sha512-hWnSzJ0oegeOwfOEeejYXfBqmnRGHusgtHfCPzmvJvHTwy1s3Neo59UKc1CmpE3zxvrCzJoVHos0rr97GHMNPw==", + "version": "0.42.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-musl/-/binding-linux-x64-musl-0.42.0.tgz", + "integrity": "sha512-0wV284I6vc5f0AqAhgAbHU2935B4bVpncPoe5n/WzVZY/KnHgqxC8iSFGeSyLWEgstFboIcWkOPck7tqbdHkzA==", "cpu": [ "x64" ], @@ -362,9 +363,9 @@ } }, "node_modules/@oxfmt/binding-openharmony-arm64": { - "version": "0.40.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-openharmony-arm64/-/binding-openharmony-arm64-0.40.0.tgz", - "integrity": "sha512-28sJC1lR4qtBJGzSRRbPnSW3GxU2+4YyQFE6rCmsUYqZ5XYH8jg0/w+CvEzQ8TuAQz5zLkcA25nFQGwoU0PT3Q==", + "version": "0.42.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-openharmony-arm64/-/binding-openharmony-arm64-0.42.0.tgz", + "integrity": "sha512-p4BG6HpGnhfgHk1rzZfyR6zcWkE7iLrWxyehHfXUy4Qa5j3e0roglFOdP/Nj5cJJ58MA3isQ5dlfkW2nNEpolw==", "cpu": [ "arm64" ], @@ -379,9 +380,9 @@ } }, "node_modules/@oxfmt/binding-win32-arm64-msvc": { - "version": "0.40.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-0.40.0.tgz", - "integrity": "sha512-cDkRnyT0dqwF5oIX1Cv59HKCeZQFbWWdUpXa3uvnHFT2iwYSSZspkhgjXjU6iDp5pFPaAEAe9FIbMoTgkTmKPg==", + "version": "0.42.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-0.42.0.tgz", + "integrity": "sha512-mn//WV60A+IetORDxYieYGAoQso4KnVRRjORDewMcod4irlRe0OSC7YPhhwaexYNPQz/GCFk+v9iUcZ2W22yxQ==", "cpu": [ "arm64" ], @@ -396,9 +397,9 @@ } }, "node_modules/@oxfmt/binding-win32-ia32-msvc": { - "version": "0.40.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-0.40.0.tgz", - "integrity": "sha512-7rPemBJjqm5Gkv6ZRCPvK8lE6AqQ/2z31DRdWazyx2ZvaSgL7QGofHXHNouRpPvNsT9yxRNQJgigsWkc+0qg4w==", + "version": "0.42.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-0.42.0.tgz", + "integrity": "sha512-3gWltUrvuz4LPJXWivoAxZ28Of2O4N7OGuM5/X3ubPXCEV8hmgECLZzjz7UYvSDUS3grfdccQwmjynm+51EFpw==", "cpu": [ "ia32" ], @@ -413,9 +414,9 @@ } }, "node_modules/@oxfmt/binding-win32-x64-msvc": { - "version": "0.40.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-x64-msvc/-/binding-win32-x64-msvc-0.40.0.tgz", - "integrity": "sha512-/Zmj0yTYSvmha6TG1QnoLqVT7ZMRDqXvFXXBQpIjteEwx9qvUYMBH2xbiOFhDeMUJkGwC3D6fdKsFtaqUvkwNA==", + "version": "0.42.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-x64-msvc/-/binding-win32-x64-msvc-0.42.0.tgz", + "integrity": "sha512-Wg4TMAfQRL9J9AZevJ/ZNy3uyyDztDYQtGr4P8UyyzIhLhFrdSmz1J/9JT+rv0fiCDLaFOBQnj3f3K3+a5PzDQ==", "cpu": [ "x64" ], @@ -430,9 +431,9 @@ } }, "node_modules/@oxlint/binding-android-arm-eabi": { - "version": "1.55.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm-eabi/-/binding-android-arm-eabi-1.55.0.tgz", - "integrity": "sha512-NhvgAhncTSOhRahQSCnkK/4YIGPjTmhPurQQ2dwt2IvwCMTvZRW5vF2K10UBOxFve4GZDMw6LtXZdC2qeuYIVQ==", + "version": "1.57.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm-eabi/-/binding-android-arm-eabi-1.57.0.tgz", + "integrity": "sha512-C7EiyfAJG4B70496eV543nKiq5cH0o/xIh/ufbjQz3SIvHhlDDsyn+mRFh+aW8KskTyUpyH2LGWL8p2oN6bl1A==", "cpu": [ "arm" ], @@ -447,9 +448,9 @@ } }, "node_modules/@oxlint/binding-android-arm64": { - "version": "1.55.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm64/-/binding-android-arm64-1.55.0.tgz", - "integrity": "sha512-P9iWRh+Ugqhg+D7rkc7boHX8o3H2h7YPcZHQIgvVBgnua5tk4LR2L+IBlreZs58/95cd2x3/004p5VsQM9z4SA==", + "version": "1.57.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm64/-/binding-android-arm64-1.57.0.tgz", + "integrity": "sha512-9i80AresjZ/FZf5xK8tKFbhQnijD4s1eOZw6/FHUwD59HEZbVLRc2C88ADYJfLZrF5XofWDiRX/Ja9KefCLy7w==", "cpu": [ "arm64" ], @@ -464,9 +465,9 @@ } }, "node_modules/@oxlint/binding-darwin-arm64": { - "version": "1.55.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-arm64/-/binding-darwin-arm64-1.55.0.tgz", - "integrity": "sha512-esakkJIt7WFAhT30P/Qzn96ehFpzdZ1mNuzpOb8SCW7lI4oB8VsyQnkSHREM671jfpuBb/o2ppzBCx5l0jpgMA==", + "version": "1.57.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-arm64/-/binding-darwin-arm64-1.57.0.tgz", + "integrity": "sha512-0eUfhRz5L2yKa9I8k3qpyl37XK3oBS5BvrgdVIx599WZK63P8sMbg+0s4IuxmIiZuBK68Ek+Z+gcKgeYf0otsg==", "cpu": [ "arm64" ], @@ -481,9 +482,9 @@ } }, "node_modules/@oxlint/binding-darwin-x64": { - "version": "1.55.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-x64/-/binding-darwin-x64-1.55.0.tgz", - "integrity": "sha512-xDMFRCCAEK9fOH6As2z8ELsC+VDGSFRHwIKVSilw+xhgLwTDFu37rtmRbmUlx8rRGS6cWKQPTc47AVxAZEVVPQ==", + "version": "1.57.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-x64/-/binding-darwin-x64-1.57.0.tgz", + "integrity": "sha512-UvrSuzBaYOue+QMAcuDITe0k/Vhj6KZGjfnI6x+NkxBTke/VoM7ZisaxgNY0LWuBkTnd1OmeQfEQdQ48fRjkQg==", "cpu": [ "x64" ], @@ -498,9 +499,9 @@ } }, "node_modules/@oxlint/binding-freebsd-x64": { - "version": "1.55.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-freebsd-x64/-/binding-freebsd-x64-1.55.0.tgz", - "integrity": "sha512-mYZqnwUD7ALCRxGenyLd1uuG+rHCL+OTT6S8FcAbVm/ZT2AZMGjvibp3F6k1SKOb2aeqFATmwRykrE41Q0GWVw==", + "version": "1.57.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-freebsd-x64/-/binding-freebsd-x64-1.57.0.tgz", + "integrity": "sha512-wtQq0dCoiw4bUwlsNVDJJ3pxJA218fOezpgtLKrbQqUtQJcM9yP8z+I9fu14aHg0uyAxIY+99toL6uBa2r7nxA==", "cpu": [ "x64" ], @@ -515,9 +516,9 @@ } }, "node_modules/@oxlint/binding-linux-arm-gnueabihf": { - "version": "1.55.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.55.0.tgz", - "integrity": "sha512-LcX6RYcF9vL9ESGwJW3yyIZ/d/ouzdOKXxCdey1q0XJOW1asrHsIg5MmyKdEBR4plQx+shvYeQne7AzW5f3T1w==", + "version": "1.57.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.57.0.tgz", + "integrity": "sha512-qxFWl2BBBFcT4djKa+OtMdnLgoHEJXpqjyGwz8OhW35ImoCwR5qtAGqApNYce5260FQqoAHW8S8eZTjiX67Tsg==", "cpu": [ "arm" ], @@ -532,9 +533,9 @@ } }, "node_modules/@oxlint/binding-linux-arm-musleabihf": { - "version": "1.55.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-1.55.0.tgz", - "integrity": "sha512-C+8GS1rPtK+dI7mJFkqoRBkDuqbrNihnyYQsJPS9ez+8zF9JzfvU19lawqt4l/Y23o5uQswE/DORa8aiXUih3w==", + "version": "1.57.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-1.57.0.tgz", + "integrity": "sha512-SQoIsBU7J0bDW15/f0/RvxHfY3Y0+eB/caKBQtNFbuerTiA6JCYx9P1MrrFTwY2dTm/lMgTSgskvCEYk2AtG/Q==", "cpu": [ "arm" ], @@ -549,9 +550,9 @@ } }, "node_modules/@oxlint/binding-linux-arm64-gnu": { - "version": "1.55.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.55.0.tgz", - "integrity": "sha512-ErLE4XbmcCopA4/CIDiH6J1IAaDOMnf/KSx/aFObs4/OjAAM3sFKWGZ57pNOMxhhyBdcmcXwYymph9GwcpcqgQ==", + "version": "1.57.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.57.0.tgz", + "integrity": "sha512-jqxYd1W6WMeozsCmqe9Rzbu3SRrGTyGDAipRlRggetyYbUksJqJKvUNTQtZR/KFoJPb+grnSm5SHhdWrywv3RQ==", "cpu": [ "arm64" ], @@ -566,9 +567,9 @@ } }, "node_modules/@oxlint/binding-linux-arm64-musl": { - "version": "1.55.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.55.0.tgz", - "integrity": "sha512-/kp65avi6zZfqEng56TTuhiy3P/3pgklKIdf38yvYeJ9/PgEeRA2A2AqKAKbZBNAqUzrzHhz9jF6j/PZvhJzTQ==", + "version": "1.57.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.57.0.tgz", + "integrity": "sha512-i66WyEPVEvq9bxRUCJ/MP5EBfnTDN3nhwEdFZFTO5MmLLvzngfWEG3NSdXQzTT3vk5B9i6C2XSIYBh+aG6uqyg==", "cpu": [ "arm64" ], @@ -583,9 +584,9 @@ } }, "node_modules/@oxlint/binding-linux-ppc64-gnu": { - "version": "1.55.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.55.0.tgz", - "integrity": "sha512-A6pTdXwcEEwL/nmz0eUJ6WxmxcoIS+97GbH96gikAyre3s5deC7sts38ZVVowjS2QQFuSWkpA4ZmQC0jZSNvJQ==", + "version": "1.57.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.57.0.tgz", + "integrity": "sha512-oMZDCwz4NobclZU3pH+V1/upVlJZiZvne4jQP+zhJwt+lmio4XXr4qG47CehvrW1Lx2YZiIHuxM2D4YpkG3KVA==", "cpu": [ "ppc64" ], @@ -600,9 +601,9 @@ } }, "node_modules/@oxlint/binding-linux-riscv64-gnu": { - "version": "1.55.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-1.55.0.tgz", - "integrity": "sha512-clj0lnIN+V52G9tdtZl0LbdTSurnZ1NZj92Je5X4lC7gP5jiCSW+Y/oiDiSauBAD4wrHt2S7nN3pA0zfKYK/6Q==", + "version": "1.57.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-1.57.0.tgz", + "integrity": "sha512-uoBnjJ3MMEBbfnWC1jSFr7/nSCkcQYa72NYoNtLl1imshDnWSolYCjzb8LVCwYCCfLJXD+0gBLD7fyC14c0+0g==", "cpu": [ "riscv64" ], @@ -617,9 +618,9 @@ } }, "node_modules/@oxlint/binding-linux-riscv64-musl": { - "version": "1.55.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-1.55.0.tgz", - "integrity": "sha512-NNu08pllN5x/O94/sgR3DA8lbrGBnTHsINZZR0hcav1sj79ksTiKKm1mRzvZvacwQ0hUnGinFo+JO75ok2PxYg==", + "version": "1.57.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-1.57.0.tgz", + "integrity": "sha512-BdrwD7haPZ8a9KrZhKJRSj6jwCor+Z8tHFZ3PT89Y3Jq5v3LfMfEePeAmD0LOTWpiTmzSzdmyw9ijneapiVHKQ==", "cpu": [ "riscv64" ], @@ -634,9 +635,9 @@ } }, "node_modules/@oxlint/binding-linux-s390x-gnu": { - "version": "1.55.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.55.0.tgz", - "integrity": "sha512-BvfQz3PRlWZRoEZ17dZCqgQsMRdpzGZomJkVATwCIGhHVVeHJMQdmdXPSjcT1DCNUrOjXnVyj1RGDj5+/Je2+Q==", + "version": "1.57.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.57.0.tgz", + "integrity": "sha512-BNs+7ZNsRstVg2tpNxAXfMX/Iv5oZh204dVyb8Z37+/gCh+yZqNTlg6YwCLIMPSk5wLWIGOaQjT0GUOahKYImw==", "cpu": [ "s390x" ], @@ -651,9 +652,9 @@ } }, "node_modules/@oxlint/binding-linux-x64-gnu": { - "version": "1.55.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.55.0.tgz", - "integrity": "sha512-ngSOoFCSBMKVQd24H8zkbcBNc7EHhjnF1sv3mC9NNXQ/4rRjI/4Dj9+9XoDZeFEkF1SX1COSBXF1b2Pr9rqdEw==", + "version": "1.57.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.57.0.tgz", + "integrity": "sha512-AghS18w+XcENcAX0+BQGLiqjpqpaxKJa4cWWP0OWNLacs27vHBxu7TYkv9LUSGe5w8lOJHeMxcYfZNOAPqw2bg==", "cpu": [ "x64" ], @@ -668,9 +669,9 @@ } }, "node_modules/@oxlint/binding-linux-x64-musl": { - "version": "1.55.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-musl/-/binding-linux-x64-musl-1.55.0.tgz", - "integrity": "sha512-BDpP7W8GlaG7BR6QjGZAleYzxoyKc/D24spZIF2mB3XsfALQJJT/OBmP8YpeTb1rveFSBHzl8T7l0aqwkWNdGA==", + "version": "1.57.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-musl/-/binding-linux-x64-musl-1.57.0.tgz", + "integrity": "sha512-E/FV3GB8phu/Rpkhz5T96hAiJlGzn91qX5yj5gU754P5cmVGXY1Jw/VSjDSlZBCY3VHjsVLdzgdkJaomEmcNOg==", "cpu": [ "x64" ], @@ -685,9 +686,9 @@ } }, "node_modules/@oxlint/binding-openharmony-arm64": { - "version": "1.55.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-openharmony-arm64/-/binding-openharmony-arm64-1.55.0.tgz", - "integrity": "sha512-PS6GFvmde/pc3fCA2Srt51glr8Lcxhpf6WIBFfLphndjRrD34NEcses4TSxQrEcxYo6qVywGfylM0ZhSCF2gGA==", + "version": "1.57.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-openharmony-arm64/-/binding-openharmony-arm64-1.57.0.tgz", + "integrity": "sha512-xvZ2yZt0nUVfU14iuGv3V25jpr9pov5N0Wr28RXnHFxHCRxNDMtYPHV61gGLhN9IlXM96gI4pyYpLSJC5ClLCQ==", "cpu": [ "arm64" ], @@ -702,9 +703,9 @@ } }, "node_modules/@oxlint/binding-win32-arm64-msvc": { - "version": "1.55.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.55.0.tgz", - "integrity": "sha512-P6JcLJGs/q1UOvDLzN8otd9JsH4tsuuPDv+p7aHqHM3PrKmYdmUvkNj4K327PTd35AYcznOCN+l4ZOaq76QzSw==", + "version": "1.57.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.57.0.tgz", + "integrity": "sha512-Z4D8Pd0AyHBKeazhdIXeUUy5sIS3Mo0veOlzlDECg6PhRRKgEsBJCCV1n+keUZtQ04OP+i7+itS3kOykUyNhDg==", "cpu": [ "arm64" ], @@ -719,9 +720,9 @@ } }, "node_modules/@oxlint/binding-win32-ia32-msvc": { - "version": "1.55.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-1.55.0.tgz", - "integrity": "sha512-gzkk4zE2zsE+WmRxFOiAZHpCpUNDFytEakqNXoNHW+PnYEOTPKDdW6nrzgSeTbGKVPXNAKQnRnMgrh7+n3Xueg==", + "version": "1.57.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-1.57.0.tgz", + "integrity": "sha512-StOZ9nFMVKvevicbQfql6Pouu9pgbeQnu60Fvhz2S6yfMaii+wnueLnqQ5I1JPgNF0Syew4voBlAaHD13wH6tw==", "cpu": [ "ia32" ], @@ -736,9 +737,9 @@ } }, "node_modules/@oxlint/binding-win32-x64-msvc": { - "version": "1.55.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.55.0.tgz", - "integrity": "sha512-ZFALNow2/og75gvYzNP7qe+rREQ5xunktwA+lgykoozHZ6hw9bqg4fn5j2UvG4gIn1FXqrZHkOAXuPf5+GOYTQ==", + "version": "1.57.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.57.0.tgz", + "integrity": "sha512-6PuxhYgth8TuW0+ABPOIkGdBYw+qYGxgIdXPHSVpiCDm+hqTTWCmC739St1Xni0DJBt8HnSHTG67i1y6gr8qrA==", "cpu": [ "x64" ], @@ -764,9 +765,9 @@ } }, "node_modules/@rolldown/binding-android-arm64": { - "version": "1.0.0-rc.9", - "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.0.0-rc.9.tgz", - "integrity": "sha512-lcJL0bN5hpgJfSIz/8PIf02irmyL43P+j1pTCfbD1DbLkmGRuFIA4DD3B3ZOvGqG0XiVvRznbKtN0COQVaKUTg==", + "version": "1.0.0-rc.11", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.0.0-rc.11.tgz", + "integrity": "sha512-SJ+/g+xNnOh6NqYxD0V3uVN4W3VfnrGsC9/hoglicgTNfABFG9JjISvkkU0dNY84MNHLWyOgxP9v9Y9pX4S7+A==", "cpu": [ "arm64" ], @@ -781,9 +782,9 @@ } }, "node_modules/@rolldown/binding-darwin-arm64": { - "version": "1.0.0-rc.9", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.0.0-rc.9.tgz", - "integrity": "sha512-J7Zk3kLYFsLtuH6U+F4pS2sYVzac0qkjcO5QxHS7OS7yZu2LRs+IXo+uvJ/mvpyUljDJ3LROZPoQfgBIpCMhdQ==", + "version": "1.0.0-rc.11", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.0.0-rc.11.tgz", + "integrity": "sha512-7WQgR8SfOPwmDZGFkThUvsmd/nwAWv91oCO4I5LS7RKrssPZmOt7jONN0cW17ydGC1n/+puol1IpoieKqQidmg==", "cpu": [ "arm64" ], @@ -798,9 +799,9 @@ } }, "node_modules/@rolldown/binding-darwin-x64": { - "version": "1.0.0-rc.9", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.0.0-rc.9.tgz", - "integrity": "sha512-iwtmmghy8nhfRGeNAIltcNXzD0QMNaaA5U/NyZc1Ia4bxrzFByNMDoppoC+hl7cDiUq5/1CnFthpT9n+UtfFyg==", + "version": "1.0.0-rc.11", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.0.0-rc.11.tgz", + "integrity": "sha512-39Ks6UvIHq4rEogIfQBoBRusj0Q0nPVWIvqmwBLaT6aqQGIakHdESBVOPRRLacy4WwUPIx4ZKzfZ9PMW+IeyUQ==", "cpu": [ "x64" ], @@ -815,9 +816,9 @@ } }, "node_modules/@rolldown/binding-freebsd-x64": { - "version": "1.0.0-rc.9", - "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.0.0-rc.9.tgz", - "integrity": "sha512-DLFYI78SCiZr5VvdEplsVC2Vx53lnA4/Ga5C65iyldMVaErr86aiqCoNBLl92PXPfDtUYjUh+xFFor40ueNs4Q==", + "version": "1.0.0-rc.11", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.0.0-rc.11.tgz", + "integrity": "sha512-jfsm0ZHfhiqrvWjJAmzsqiIFPz5e7mAoCOPBNTcNgkiid/LaFKiq92+0ojH+nmJmKYkre4t71BWXUZDNp7vsag==", "cpu": [ "x64" ], @@ -832,9 +833,9 @@ } }, "node_modules/@rolldown/binding-linux-arm-gnueabihf": { - "version": "1.0.0-rc.9", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.0.0-rc.9.tgz", - "integrity": "sha512-CsjTmTwd0Hri6iTw/DRMK7kOZ7FwAkrO4h8YWKoX/kcj833e4coqo2wzIFywtch/8Eb5enQ/lwLM7w6JX1W5RQ==", + "version": "1.0.0-rc.11", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.0.0-rc.11.tgz", + "integrity": "sha512-zjQaUtSyq1nVe3nxmlSCuR96T1LPlpvmJ0SZy0WJFEsV4kFbXcq2u68L4E6O0XeFj4aex9bEauqjW8UQBeAvfQ==", "cpu": [ "arm" ], @@ -849,9 +850,9 @@ } }, "node_modules/@rolldown/binding-linux-arm64-gnu": { - "version": "1.0.0-rc.9", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.0.0-rc.9.tgz", - "integrity": "sha512-2x9O2JbSPxpxMDhP9Z74mahAStibTlrBMW0520+epJH5sac7/LwZW5Bmg/E6CXuEF53JJFW509uP+lSedaUNxg==", + "version": "1.0.0-rc.11", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.0.0-rc.11.tgz", + "integrity": "sha512-WMW1yE6IOnehTcFE9eipFkm3XN63zypWlrJQ2iF7NrQ9b2LDRjumFoOGJE8RJJTJCTBAdmLMnJ8uVitACUUo1Q==", "cpu": [ "arm64" ], @@ -866,9 +867,9 @@ } }, "node_modules/@rolldown/binding-linux-arm64-musl": { - "version": "1.0.0-rc.9", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.0.0-rc.9.tgz", - "integrity": "sha512-JA1QRW31ogheAIRhIg9tjMfsYbglXXYGNPLdPEYrwFxdbkQCAzvpSCSHCDWNl4hTtrol8WeboCSEpjdZK8qrCg==", + "version": "1.0.0-rc.11", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.0.0-rc.11.tgz", + "integrity": "sha512-jfndI9tsfm4APzjNt6QdBkYwre5lRPUgHeDHoI7ydKUuJvz3lZeCfMsI56BZj+7BYqiKsJm7cfd/6KYV7ubrBg==", "cpu": [ "arm64" ], @@ -883,9 +884,9 @@ } }, "node_modules/@rolldown/binding-linux-ppc64-gnu": { - "version": "1.0.0-rc.9", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.0.0-rc.9.tgz", - "integrity": "sha512-aOKU9dJheda8Kj8Y3w9gnt9QFOO+qKPAl8SWd7JPHP+Cu0EuDAE5wokQubLzIDQWg2myXq2XhTpOVS07qqvT+w==", + "version": "1.0.0-rc.11", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.0.0-rc.11.tgz", + "integrity": "sha512-ZlFgw46NOAGMgcdvdYwAGu2Q+SLFA9LzbJLW+iyMOJyhj5wk6P3KEE9Gct4xWwSzFoPI7JCdYmYMzVtlgQ+zfw==", "cpu": [ "ppc64" ], @@ -900,9 +901,9 @@ } }, "node_modules/@rolldown/binding-linux-s390x-gnu": { - "version": "1.0.0-rc.9", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.0.0-rc.9.tgz", - "integrity": "sha512-OalO94fqj7IWRn3VdXWty75jC5dk4C197AWEuMhIpvVv2lw9fiPhud0+bW2ctCxb3YoBZor71QHbY+9/WToadA==", + "version": "1.0.0-rc.11", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.0.0-rc.11.tgz", + "integrity": "sha512-hIOYmuT6ofM4K04XAZd3OzMySEO4K0/nc9+jmNcxNAxRi6c5UWpqfw3KMFV4MVFWL+jQsSh+bGw2VqmaPMTLyw==", "cpu": [ "s390x" ], @@ -917,9 +918,9 @@ } }, "node_modules/@rolldown/binding-linux-x64-gnu": { - "version": "1.0.0-rc.9", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.0.0-rc.9.tgz", - "integrity": "sha512-cVEl1vZtBsBZna3YMjGXNvnYYrOJ7RzuWvZU0ffvJUexWkukMaDuGhUXn0rjnV0ptzGVkvc+vW9Yqy6h8YX4pg==", + "version": "1.0.0-rc.11", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.0.0-rc.11.tgz", + "integrity": "sha512-qXBQQO9OvkjjQPLdUVr7Nr2t3QTZI7s4KZtfw7HzBgjbmAPSFwSv4rmET9lLSgq3rH/ndA3ngv3Qb8l2njoPNA==", "cpu": [ "x64" ], @@ -934,9 +935,9 @@ } }, "node_modules/@rolldown/binding-linux-x64-musl": { - "version": "1.0.0-rc.9", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.0.0-rc.9.tgz", - "integrity": "sha512-UzYnKCIIc4heAKgI4PZ3dfBGUZefGCJ1TPDuLHoCzgrMYPb5Rv6TLFuYtyM4rWyHM7hymNdsg5ik2C+UD9VDbA==", + "version": "1.0.0-rc.11", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.0.0-rc.11.tgz", + "integrity": "sha512-/tpFfoSTzUkH9LPY+cYbqZBDyyX62w5fICq9qzsHLL8uTI6BHip3Q9Uzft0wylk/i8OOwKik8OxW+QAhDmzwmg==", "cpu": [ "x64" ], @@ -951,9 +952,9 @@ } }, "node_modules/@rolldown/binding-openharmony-arm64": { - "version": "1.0.0-rc.9", - "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.0.0-rc.9.tgz", - "integrity": "sha512-+6zoiF+RRyf5cdlFQP7nm58mq7+/2PFaY2DNQeD4B87N36JzfF/l9mdBkkmTvSYcYPE8tMh/o3cRlsx1ldLfog==", + "version": "1.0.0-rc.11", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.0.0-rc.11.tgz", + "integrity": "sha512-mcp3Rio2w72IvdZG0oQ4bM2c2oumtwHfUfKncUM6zGgz0KgPz4YmDPQfnXEiY5t3+KD/i8HG2rOB/LxdmieK2g==", "cpu": [ "arm64" ], @@ -968,9 +969,9 @@ } }, "node_modules/@rolldown/binding-wasm32-wasi": { - "version": "1.0.0-rc.9", - "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.0.0-rc.9.tgz", - "integrity": "sha512-rgFN6sA/dyebil3YTlL2evvi/M+ivhfnyxec7AccTpRPccno/rPoNlqybEZQBkcbZu8Hy+eqNJCqfBR8P7Pg8g==", + "version": "1.0.0-rc.11", + "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.0.0-rc.11.tgz", + "integrity": "sha512-LXk5Hii1Ph9asuGRjBuz8TUxdc1lWzB7nyfdoRgI0WGPZKmCxvlKk8KfYysqtr4MfGElu/f/pEQRh8fcEgkrWw==", "cpu": [ "wasm32" ], @@ -985,9 +986,9 @@ } }, "node_modules/@rolldown/binding-win32-arm64-msvc": { - "version": "1.0.0-rc.9", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.0.0-rc.9.tgz", - "integrity": "sha512-lHVNUG/8nlF1IQk1C0Ci574qKYyty2goMiPlRqkC5R+3LkXDkL5Dhx8ytbxq35m+pkHVIvIxviD+TWLdfeuadA==", + "version": "1.0.0-rc.11", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.0.0-rc.11.tgz", + "integrity": "sha512-dDwf5otnx0XgRY1yqxOC4ITizcdzS/8cQ3goOWv3jFAo4F+xQYni+hnMuO6+LssHHdJW7+OCVL3CoU4ycnh35Q==", "cpu": [ "arm64" ], @@ -1002,9 +1003,9 @@ } }, "node_modules/@rolldown/binding-win32-x64-msvc": { - "version": "1.0.0-rc.9", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.0.0-rc.9.tgz", - "integrity": "sha512-G0oA4+w1iY5AGi5HcDTxWsoxF509hrFIPB2rduV5aDqS9FtDg1CAfa7V34qImbjfhIcA8C+RekocJZA96EarwQ==", + "version": "1.0.0-rc.11", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.0.0-rc.11.tgz", + "integrity": "sha512-LN4/skhSggybX71ews7dAj6r2geaMJfm3kMbK2KhFMg9B10AZXnKoLCVVgzhMHL0S+aKtr4p8QbAW8k+w95bAA==", "cpu": [ "x64" ], @@ -1019,9 +1020,9 @@ } }, "node_modules/@rolldown/pluginutils": { - "version": "1.0.0-rc.9", - "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.9.tgz", - "integrity": "sha512-w6oiRWgEBl04QkFZgmW+jnU1EC9b57Oihi2ot3HNWIQRqgHp5PnYDia5iZ5FF7rpa4EQdiqMDXjlqKGXBhsoXw==", + "version": "1.0.0-rc.11", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.11.tgz", + "integrity": "sha512-xQO9vbwBecJRv9EUcQ/y0dzSTJgA7Q6UVN7xp6B81+tBGSLVAK03yJ9NkJaUA7JFD91kbjxRSC/mDnmvXzbHoQ==", "dev": true, "license": "MIT" }, @@ -1439,6 +1440,21 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, "node_modules/get-caller-file": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", @@ -1696,9 +1712,9 @@ "license": "MIT" }, "node_modules/oxfmt": { - "version": "0.40.0", - "resolved": "https://registry.npmjs.org/oxfmt/-/oxfmt-0.40.0.tgz", - "integrity": "sha512-g0C3I7xUj4b4DcagevM9kgH6+pUHytikxUcn3/VUkvzTNaaXBeyZqb7IBsHwojeXm4mTBEC/aBjBTMVUkZwWUQ==", + "version": "0.42.0", + "resolved": "https://registry.npmjs.org/oxfmt/-/oxfmt-0.42.0.tgz", + "integrity": "sha512-QhejGErLSMReNuZ6vxgFHDyGoPbjTRNi6uGHjy0cvIjOQFqD6xmr/T+3L41ixR3NIgzcNiJ6ylQKpvShTgDfqg==", "dev": true, "license": "MIT", "dependencies": { @@ -1714,31 +1730,31 @@ "url": "https://github.com/sponsors/Boshen" }, "optionalDependencies": { - "@oxfmt/binding-android-arm-eabi": "0.40.0", - "@oxfmt/binding-android-arm64": "0.40.0", - "@oxfmt/binding-darwin-arm64": "0.40.0", - "@oxfmt/binding-darwin-x64": "0.40.0", - "@oxfmt/binding-freebsd-x64": "0.40.0", - "@oxfmt/binding-linux-arm-gnueabihf": "0.40.0", - "@oxfmt/binding-linux-arm-musleabihf": "0.40.0", - "@oxfmt/binding-linux-arm64-gnu": "0.40.0", - "@oxfmt/binding-linux-arm64-musl": "0.40.0", - "@oxfmt/binding-linux-ppc64-gnu": "0.40.0", - "@oxfmt/binding-linux-riscv64-gnu": "0.40.0", - "@oxfmt/binding-linux-riscv64-musl": "0.40.0", - "@oxfmt/binding-linux-s390x-gnu": "0.40.0", - "@oxfmt/binding-linux-x64-gnu": "0.40.0", - "@oxfmt/binding-linux-x64-musl": "0.40.0", - "@oxfmt/binding-openharmony-arm64": "0.40.0", - "@oxfmt/binding-win32-arm64-msvc": "0.40.0", - "@oxfmt/binding-win32-ia32-msvc": "0.40.0", - "@oxfmt/binding-win32-x64-msvc": "0.40.0" + "@oxfmt/binding-android-arm-eabi": "0.42.0", + "@oxfmt/binding-android-arm64": "0.42.0", + "@oxfmt/binding-darwin-arm64": "0.42.0", + "@oxfmt/binding-darwin-x64": "0.42.0", + "@oxfmt/binding-freebsd-x64": "0.42.0", + "@oxfmt/binding-linux-arm-gnueabihf": "0.42.0", + "@oxfmt/binding-linux-arm-musleabihf": "0.42.0", + "@oxfmt/binding-linux-arm64-gnu": "0.42.0", + "@oxfmt/binding-linux-arm64-musl": "0.42.0", + "@oxfmt/binding-linux-ppc64-gnu": "0.42.0", + "@oxfmt/binding-linux-riscv64-gnu": "0.42.0", + "@oxfmt/binding-linux-riscv64-musl": "0.42.0", + "@oxfmt/binding-linux-s390x-gnu": "0.42.0", + "@oxfmt/binding-linux-x64-gnu": "0.42.0", + "@oxfmt/binding-linux-x64-musl": "0.42.0", + "@oxfmt/binding-openharmony-arm64": "0.42.0", + "@oxfmt/binding-win32-arm64-msvc": "0.42.0", + "@oxfmt/binding-win32-ia32-msvc": "0.42.0", + "@oxfmt/binding-win32-x64-msvc": "0.42.0" } }, "node_modules/oxlint": { - "version": "1.55.0", - "resolved": "https://registry.npmjs.org/oxlint/-/oxlint-1.55.0.tgz", - "integrity": "sha512-T+FjepiyWpaZMhekqRpH8Z3I4vNM610p6w+Vjfqgj5TZUxHXl7N8N5IPvmOU8U4XdTRxqtNNTh9Y4hLtr7yvFg==", + "version": "1.57.0", + "resolved": "https://registry.npmjs.org/oxlint/-/oxlint-1.57.0.tgz", + "integrity": "sha512-DGFsuBX5MFZX9yiDdtKjTrYPq45CZ8Fft6qCltJITYZxfwYjVdGf/6wycGYTACloauwIPxUnYhBVeZbHvleGhw==", "dev": true, "license": "MIT", "bin": { @@ -1751,25 +1767,25 @@ "url": "https://github.com/sponsors/Boshen" }, "optionalDependencies": { - "@oxlint/binding-android-arm-eabi": "1.55.0", - "@oxlint/binding-android-arm64": "1.55.0", - "@oxlint/binding-darwin-arm64": "1.55.0", - "@oxlint/binding-darwin-x64": "1.55.0", - "@oxlint/binding-freebsd-x64": "1.55.0", - "@oxlint/binding-linux-arm-gnueabihf": "1.55.0", - "@oxlint/binding-linux-arm-musleabihf": "1.55.0", - "@oxlint/binding-linux-arm64-gnu": "1.55.0", - "@oxlint/binding-linux-arm64-musl": "1.55.0", - "@oxlint/binding-linux-ppc64-gnu": "1.55.0", - "@oxlint/binding-linux-riscv64-gnu": "1.55.0", - "@oxlint/binding-linux-riscv64-musl": "1.55.0", - "@oxlint/binding-linux-s390x-gnu": "1.55.0", - "@oxlint/binding-linux-x64-gnu": "1.55.0", - "@oxlint/binding-linux-x64-musl": "1.55.0", - "@oxlint/binding-openharmony-arm64": "1.55.0", - "@oxlint/binding-win32-arm64-msvc": "1.55.0", - "@oxlint/binding-win32-ia32-msvc": "1.55.0", - "@oxlint/binding-win32-x64-msvc": "1.55.0" + "@oxlint/binding-android-arm-eabi": "1.57.0", + "@oxlint/binding-android-arm64": "1.57.0", + "@oxlint/binding-darwin-arm64": "1.57.0", + "@oxlint/binding-darwin-x64": "1.57.0", + "@oxlint/binding-freebsd-x64": "1.57.0", + "@oxlint/binding-linux-arm-gnueabihf": "1.57.0", + "@oxlint/binding-linux-arm-musleabihf": "1.57.0", + "@oxlint/binding-linux-arm64-gnu": "1.57.0", + "@oxlint/binding-linux-arm64-musl": "1.57.0", + "@oxlint/binding-linux-ppc64-gnu": "1.57.0", + "@oxlint/binding-linux-riscv64-gnu": "1.57.0", + "@oxlint/binding-linux-riscv64-musl": "1.57.0", + "@oxlint/binding-linux-s390x-gnu": "1.57.0", + "@oxlint/binding-linux-x64-gnu": "1.57.0", + "@oxlint/binding-linux-x64-musl": "1.57.0", + "@oxlint/binding-openharmony-arm64": "1.57.0", + "@oxlint/binding-win32-arm64-msvc": "1.57.0", + "@oxlint/binding-win32-ia32-msvc": "1.57.0", + "@oxlint/binding-win32-x64-msvc": "1.57.0" }, "peerDependencies": { "oxlint-tsgolint": ">=0.15.0" @@ -1863,6 +1879,38 @@ "dev": true, "license": "ISC" }, + "node_modules/playwright": { + "version": "1.58.2", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.58.2.tgz", + "integrity": "sha512-vA30H8Nvkq/cPBnNw4Q8TWz1EJyqgpuinBcHET0YVJVFldr8JDNiU9LaWAE1KqSkRYazuaBhTpB5ZzShOezQ6A==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.58.2" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "fsevents": "2.3.2" + } + }, + "node_modules/playwright-core": { + "version": "1.58.2", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.58.2.tgz", + "integrity": "sha512-yZkEtftgwS8CsfYo7nm0KE8jsvm6i/PTgVtB8DL726wNf6H2IMsDuxCpJj59KDaxCtSnrWan2AeDqM7JBaultg==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/randombytes": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", @@ -1908,14 +1956,14 @@ } }, "node_modules/rolldown": { - "version": "1.0.0-rc.9", - "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.0.0-rc.9.tgz", - "integrity": "sha512-9EbgWge7ZH+yqb4d2EnELAntgPTWbfL8ajiTW+SyhJEC4qhBbkCKbqFV4Ge4zmu5ziQuVbWxb/XwLZ+RIO7E8Q==", + "version": "1.0.0-rc.11", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.0.0-rc.11.tgz", + "integrity": "sha512-NRjoKMusSjfRbSYiH3VSumlkgFe7kYAa3pzVOsVYVFY3zb5d7nS+a3KGQ7hJKXuYWbzJKPVQ9Wxq2UvyK+ENpw==", "dev": true, "license": "MIT", "dependencies": { - "@oxc-project/types": "=0.115.0", - "@rolldown/pluginutils": "1.0.0-rc.9" + "@oxc-project/types": "=0.122.0", + "@rolldown/pluginutils": "1.0.0-rc.11" }, "bin": { "rolldown": "bin/cli.mjs" @@ -1924,21 +1972,21 @@ "node": "^20.19.0 || >=22.12.0" }, "optionalDependencies": { - "@rolldown/binding-android-arm64": "1.0.0-rc.9", - "@rolldown/binding-darwin-arm64": "1.0.0-rc.9", - "@rolldown/binding-darwin-x64": "1.0.0-rc.9", - "@rolldown/binding-freebsd-x64": "1.0.0-rc.9", - "@rolldown/binding-linux-arm-gnueabihf": "1.0.0-rc.9", - "@rolldown/binding-linux-arm64-gnu": "1.0.0-rc.9", - "@rolldown/binding-linux-arm64-musl": "1.0.0-rc.9", - "@rolldown/binding-linux-ppc64-gnu": "1.0.0-rc.9", - "@rolldown/binding-linux-s390x-gnu": "1.0.0-rc.9", - "@rolldown/binding-linux-x64-gnu": "1.0.0-rc.9", - "@rolldown/binding-linux-x64-musl": "1.0.0-rc.9", - "@rolldown/binding-openharmony-arm64": "1.0.0-rc.9", - "@rolldown/binding-wasm32-wasi": "1.0.0-rc.9", - "@rolldown/binding-win32-arm64-msvc": "1.0.0-rc.9", - "@rolldown/binding-win32-x64-msvc": "1.0.0-rc.9" + "@rolldown/binding-android-arm64": "1.0.0-rc.11", + "@rolldown/binding-darwin-arm64": "1.0.0-rc.11", + "@rolldown/binding-darwin-x64": "1.0.0-rc.11", + "@rolldown/binding-freebsd-x64": "1.0.0-rc.11", + "@rolldown/binding-linux-arm-gnueabihf": "1.0.0-rc.11", + "@rolldown/binding-linux-arm64-gnu": "1.0.0-rc.11", + "@rolldown/binding-linux-arm64-musl": "1.0.0-rc.11", + "@rolldown/binding-linux-ppc64-gnu": "1.0.0-rc.11", + "@rolldown/binding-linux-s390x-gnu": "1.0.0-rc.11", + "@rolldown/binding-linux-x64-gnu": "1.0.0-rc.11", + "@rolldown/binding-linux-x64-musl": "1.0.0-rc.11", + "@rolldown/binding-openharmony-arm64": "1.0.0-rc.11", + "@rolldown/binding-wasm32-wasi": "1.0.0-rc.11", + "@rolldown/binding-win32-arm64-msvc": "1.0.0-rc.11", + "@rolldown/binding-win32-x64-msvc": "1.0.0-rc.11" } }, "node_modules/safe-buffer": { @@ -2173,9 +2221,9 @@ "license": "0BSD" }, "node_modules/typescript": { - "version": "5.9.3", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", - "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.2.tgz", + "integrity": "sha512-bGdAIrZ0wiGDo5l8c++HWtbaNCWTS4UTv7RaTH/ThVIgjkveJt83m74bBHMJkuCbslY8ixgLBVZJIOiQlQTjfQ==", "dev": true, "license": "Apache-2.0", "bin": { diff --git a/package.json b/package.json index a04eb57..6b951a3 100755 --- a/package.json +++ b/package.json @@ -46,11 +46,12 @@ "chai-as-promised": "8.0.2", "fengari": "0.1.5", "mocha": "11.7.5", - "oxfmt": "0.40.0", - "oxlint": "1.55.0", - "rolldown": "1.0.0-rc.9", + "oxfmt": "0.42.0", + "oxlint": "1.57.0", + "rolldown": "1.0.0-rc.11", "tslib": "2.8.1", - "typescript": "5.9.3" + "typescript": "6.0.2", + "playwright": "1.58.2" }, "dependencies": { "@types/emscripten": "1.41.5" diff --git a/src/module.ts b/src/module.ts index a4bde12..d9590a0 100755 --- a/src/module.ts +++ b/src/module.ts @@ -40,6 +40,7 @@ export default class LuaModule { wasmFile?: string env?: EnvironmentVariables fs?: 'node' | 'memory' + fsMountPaths?: string[] stdin?: () => string stdout?: (content: string) => void stderr?: (content: string) => void @@ -52,8 +53,8 @@ export default class LuaModule { opts.wasmFile = `https://unpkg.com/wasmoon@${version}/dist/glue.wasm` } - const fs = !isBrowser && opts.fs === 'node' && typeof process !== 'undefined' ? await import('node:fs') : null - const child_process = !isBrowser && opts.fs === 'node' && typeof process !== 'undefined' ? await import('node:child_process') : null + const useNodeFS = !isBrowser && opts.fs === 'node' && typeof process !== 'undefined' + const fs = useNodeFS ? await import('node:fs') : null const module: LuaEmscriptenModule = await initWasmModule({ locateFile: (path: string, scriptDirectory: string) => { @@ -64,32 +65,44 @@ export default class LuaModule { Object.assign(initializedModule.ENV, opts.env) } - if (fs && child_process) { + if (fs) { let rootdirs: string[] - if (process.platform === 'win32') { - const stdout = child_process.execSync('wmic logicaldisk get name', { - encoding: 'utf8', - }) - const drives = stdout - .split('\n') - .map((line) => line.trim()) - .filter((line) => line && line !== 'Name') - .map((line) => `${line}\\`) + if (opts.fsMountPaths) { + rootdirs = opts.fsMountPaths + } else if (process.platform === 'win32') { + const drives: string[] = [] + for (let i = 65; i <= 90; i++) { + const drive = `${String.fromCharCode(i)}:\\` + try { + fs.accessSync(drive) + drives.push(drive) + } catch { + // drive does not exist + } + } rootdirs = [] for (const drive of drives) { - rootdirs.push( - ...fs - .readdirSync(drive) - .filter((dir) => !['dev', 'lib', 'proc'].includes(dir)) - .map((dir) => `${drive}${dir}`.replace(/\\|\\\\/g, '/')), - ) + try { + rootdirs.push( + ...fs + .readdirSync(drive) + .filter(dir => !['dev', 'lib', 'proc'].includes(dir)) + .map(dir => `${drive}${dir}`.replace(/\\/g, '/')), + ) + } catch { + // drive not readable + } } } else { - rootdirs = fs - .readdirSync('/') - .filter((dir) => !['dev', 'lib', 'proc'].includes(dir)) - .map((dir) => `/${dir}`) + try { + rootdirs = fs + .readdirSync('/') + .filter(dir => !['dev', 'lib', 'proc'].includes(dir)) + .map(dir => `/${dir}`) + } catch { + rootdirs = [] + } } for (const dir of rootdirs) { @@ -97,12 +110,20 @@ export default class LuaModule { const moduleFS = initializedModule.FS moduleFS.mkdirTree(dir) moduleFS.mount(moduleFS.filesystems.NODEFS, { root: dir }, dir) - } catch { - // silently fail to mount (generally due to EPERM) + } catch (err: any) { + const isPermError = + err?.code === 'EACCES' || err?.code === 'EPERM' || err?.errno === 2 + if (!isPermError) { + console.warn(`Failed to mount ${dir}:`, err) + } } } - initializedModule.FS.chdir(process.cwd().replace(/\\|\\\\/g, '/')) + try { + initializedModule.FS.chdir(process.cwd().replace(/\\/g, '/')) + } catch { + // CWD may not be within mounted paths + } } if (opts.stdin || opts.stdout || opts.stderr) { @@ -113,7 +134,9 @@ export default class LuaModule { if (!bufferedInput) { const input = opts.stdin?.() if (typeof input === 'string') { - bufferedInput = initializedModule.intArrayFromString(input, true).concat([0]) + bufferedInput = initializedModule + .intArrayFromString(input, true) + .concat([0]) } else { throw new Error('stdin must return a string') } @@ -146,7 +169,12 @@ export default class LuaModule { public luaL_argerror: (L: LuaState, arg: number, extramsg: string | null) => number public luaL_typeerror: (L: LuaState, arg: number, tname: string | null) => number public luaL_checklstring: (L: LuaState, arg: number, l: number | null) => string - public luaL_optlstring: (L: LuaState, arg: number, def: string | null, l: number | null) => string + public luaL_optlstring: ( + L: LuaState, + arg: number, + def: string | null, + l: number | null, + ) => string public luaL_checknumber: (L: LuaState, arg: number) => number public luaL_optnumber: (L: LuaState, arg: number, def: number) => number public luaL_checkinteger: (L: LuaState, arg: number) => number @@ -174,7 +202,12 @@ export default class LuaModule { public luaL_loadstring: (L: LuaState, s: string | null) => LuaReturn public luaL_newstate: () => LuaState public luaL_len: (L: LuaState, idx: number) => number - public luaL_addgsub: (b: number | null, s: string | null, p: string | null, r: string | null) => void + public luaL_addgsub: ( + b: number | null, + s: string | null, + p: string | null, + r: string | null, + ) => void public luaL_gsub: (L: LuaState, s: string | null, p: string | null, r: string | null) => string public luaL_setfuncs: (L: LuaState, l: number | null, nup: number) => void public luaL_getsubtable: (L: LuaState, idx: number, fname: string | null) => number @@ -252,12 +285,41 @@ export default class LuaModule { public lua_rawsetp: (L: LuaState, idx: number, p: number | null) => void public lua_setmetatable: (L: LuaState, objindex: number) => number public lua_setiuservalue: (L: LuaState, idx: number, n: number) => number - public lua_callk: (L: LuaState, nargs: number, nresults: number, ctx: number, k: number | null) => void - public lua_pcallk: (L: LuaState, nargs: number, nresults: number, errfunc: number, ctx: number, k: number | null) => number - public lua_load: (L: LuaState, reader: number | null, dt: number | null, chunkname: string | null, mode: string | null) => LuaReturn - public lua_dump: (L: LuaState, writer: number | null, data: number | null, strip: number) => number + public lua_callk: ( + L: LuaState, + nargs: number, + nresults: number, + ctx: number, + k: number | null, + ) => void + public lua_pcallk: ( + L: LuaState, + nargs: number, + nresults: number, + errfunc: number, + ctx: number, + k: number | null, + ) => number + public lua_load: ( + L: LuaState, + reader: number | null, + dt: number | null, + chunkname: string | null, + mode: string | null, + ) => LuaReturn + public lua_dump: ( + L: LuaState, + writer: number | null, + data: number | null, + strip: number, + ) => number public lua_yieldk: (L: LuaState, nresults: number, ctx: number, k: number | null) => number - public lua_resume: (L: LuaState, from: LuaState | null, narg: number, nres: number | null) => LuaReturn + public lua_resume: ( + L: LuaState, + from: LuaState | null, + narg: number, + nres: number | null, + ) => LuaReturn public lua_status: (L: LuaState) => LuaReturn public lua_isyieldable: (L: LuaState) => number public lua_setwarnf: (L: LuaState, f: number | null, ud: number | null) => void @@ -278,7 +340,13 @@ export default class LuaModule { public lua_getupvalue: (L: LuaState, funcindex: number, n: number) => string public lua_setupvalue: (L: LuaState, funcindex: number, n: number) => string public lua_upvalueid: (L: LuaState, fidx: number, n: number) => number - public lua_upvaluejoin: (L: LuaState, fidx1: number, n1: number, fidx2: number, n2: number) => void + public lua_upvaluejoin: ( + L: LuaState, + fidx1: number, + n1: number, + fidx2: number, + n2: number, + ) => void public lua_sethook: (L: LuaState, func: number | null, mask: number, count: number) => void public lua_gethook: (L: LuaState) => number public lua_gethookmask: (L: LuaState) => number @@ -304,42 +372,100 @@ export default class LuaModule { public constructor(module: LuaEmscriptenModule) { this._emscripten = module - this.luaL_checkversion_ = this.cwrap('luaL_checkversion_', null, ['number', 'number', 'number']) - this.luaL_getmetafield = this.cwrap('luaL_getmetafield', 'number', ['number', 'number', 'string']) + this.luaL_checkversion_ = this.cwrap('luaL_checkversion_', null, [ + 'number', + 'number', + 'number', + ]) + this.luaL_getmetafield = this.cwrap('luaL_getmetafield', 'number', [ + 'number', + 'number', + 'string', + ]) this.luaL_callmeta = this.cwrap('luaL_callmeta', 'number', ['number', 'number', 'string']) this.luaL_tolstring = this.cwrap('luaL_tolstring', 'string', ['number', 'number', 'number']) this.luaL_argerror = this.cwrap('luaL_argerror', 'number', ['number', 'number', 'string']) this.luaL_typeerror = this.cwrap('luaL_typeerror', 'number', ['number', 'number', 'string']) - this.luaL_checklstring = this.cwrap('luaL_checklstring', 'string', ['number', 'number', 'number']) - this.luaL_optlstring = this.cwrap('luaL_optlstring', 'string', ['number', 'number', 'string', 'number']) + this.luaL_checklstring = this.cwrap('luaL_checklstring', 'string', [ + 'number', + 'number', + 'number', + ]) + this.luaL_optlstring = this.cwrap('luaL_optlstring', 'string', [ + 'number', + 'number', + 'string', + 'number', + ]) this.luaL_checknumber = this.cwrap('luaL_checknumber', 'number', ['number', 'number']) this.luaL_optnumber = this.cwrap('luaL_optnumber', 'number', ['number', 'number', 'number']) this.luaL_checkinteger = this.cwrap('luaL_checkinteger', 'number', ['number', 'number']) - this.luaL_optinteger = this.cwrap('luaL_optinteger', 'number', ['number', 'number', 'number']) + this.luaL_optinteger = this.cwrap('luaL_optinteger', 'number', [ + 'number', + 'number', + 'number', + ]) this.luaL_checkstack = this.cwrap('luaL_checkstack', null, ['number', 'number', 'string']) this.luaL_checktype = this.cwrap('luaL_checktype', null, ['number', 'number', 'number']) this.luaL_checkany = this.cwrap('luaL_checkany', null, ['number', 'number']) this.luaL_newmetatable = this.cwrap('luaL_newmetatable', 'number', ['number', 'string']) this.luaL_setmetatable = this.cwrap('luaL_setmetatable', null, ['number', 'string']) this.luaL_testudata = this.cwrap('luaL_testudata', 'number', ['number', 'number', 'string']) - this.luaL_checkudata = this.cwrap('luaL_checkudata', 'number', ['number', 'number', 'string']) + this.luaL_checkudata = this.cwrap('luaL_checkudata', 'number', [ + 'number', + 'number', + 'string', + ]) this.luaL_where = this.cwrap('luaL_where', null, ['number', 'number']) - this.luaL_fileresult = this.cwrap('luaL_fileresult', 'number', ['number', 'number', 'string']) + this.luaL_fileresult = this.cwrap('luaL_fileresult', 'number', [ + 'number', + 'number', + 'string', + ]) this.luaL_execresult = this.cwrap('luaL_execresult', 'number', ['number', 'number']) this.luaL_ref = this.cwrap('luaL_ref', 'number', ['number', 'number']) this.luaL_unref = this.cwrap('luaL_unref', null, ['number', 'number', 'number']) this.luaL_loadfilex = this.cwrap('luaL_loadfilex', 'number', ['number', 'string', 'string']) - this.luaL_loadbufferx = this.cwrap('luaL_loadbufferx', 'number', ['number', 'string|number', 'number', 'string|number', 'string']) + this.luaL_loadbufferx = this.cwrap('luaL_loadbufferx', 'number', [ + 'number', + 'string|number', + 'number', + 'string|number', + 'string', + ]) this.luaL_loadstring = this.cwrap('luaL_loadstring', 'number', ['number', 'string']) this.luaL_newstate = this.cwrap('luaL_newstate', 'number', []) this.luaL_len = this.cwrap('luaL_len', 'number', ['number', 'number']) - this.luaL_addgsub = this.cwrap('luaL_addgsub', null, ['number', 'string', 'string', 'string']) + this.luaL_addgsub = this.cwrap('luaL_addgsub', null, [ + 'number', + 'string', + 'string', + 'string', + ]) this.luaL_gsub = this.cwrap('luaL_gsub', 'string', ['number', 'string', 'string', 'string']) this.luaL_setfuncs = this.cwrap('luaL_setfuncs', null, ['number', 'number', 'number']) - this.luaL_getsubtable = this.cwrap('luaL_getsubtable', 'number', ['number', 'number', 'string']) - this.luaL_traceback = this.cwrap('luaL_traceback', null, ['number', 'number', 'string', 'number']) - this.luaL_requiref = this.cwrap('luaL_requiref', null, ['number', 'string', 'number', 'number']) - this.luaL_openselectedlibs = this.cwrap('luaL_openselectedlibs', null, ['number', 'number', 'number']) + this.luaL_getsubtable = this.cwrap('luaL_getsubtable', 'number', [ + 'number', + 'number', + 'string', + ]) + this.luaL_traceback = this.cwrap('luaL_traceback', null, [ + 'number', + 'number', + 'string', + 'number', + ]) + this.luaL_requiref = this.cwrap('luaL_requiref', null, [ + 'number', + 'string', + 'number', + 'number', + ]) + this.luaL_openselectedlibs = this.cwrap('luaL_openselectedlibs', null, [ + 'number', + 'number', + 'number', + ]) this.luaL_buffinit = this.cwrap('luaL_buffinit', null, ['number', 'number']) this.luaL_prepbuffsize = this.cwrap('luaL_prepbuffsize', 'string', ['number', 'number']) this.luaL_addlstring = this.cwrap('luaL_addlstring', null, ['number', 'string', 'number']) @@ -347,12 +473,16 @@ export default class LuaModule { this.luaL_addvalue = this.cwrap('luaL_addvalue', null, ['number']) this.luaL_pushresult = this.cwrap('luaL_pushresult', null, ['number']) this.luaL_pushresultsize = this.cwrap('luaL_pushresultsize', null, ['number', 'number']) - this.luaL_buffinitsize = this.cwrap('luaL_buffinitsize', 'string', ['number', 'number', 'number']) + this.luaL_buffinitsize = this.cwrap('luaL_buffinitsize', 'string', [ + 'number', + 'number', + 'number', + ]) this.lua_newstate = this.cwrap('lua_newstate', 'number', ['number', 'number', 'number']) this.lua_close = this.cwrap('lua_close', null, ['number']) this.lua_newthread = this.cwrap('lua_newthread', 'number', ['number']) this.lua_closethread = this.cwrap('lua_closethread', 'number', ['number', 'number']) - this.lua_resetthread = (L) => this.lua_closethread(L, null) + this.lua_resetthread = L => this.lua_closethread(L, null) this.lua_atpanic = this.cwrap('lua_atpanic', 'number', ['number', 'number']) this.lua_version = this.cwrap('lua_version', 'number', ['number']) this.lua_absindex = this.cwrap('lua_absindex', 'number', ['number', 'number']) @@ -381,11 +511,20 @@ export default class LuaModule { this.lua_topointer = this.cwrap('lua_topointer', 'number', ['number', 'number']) this.lua_arith = this.cwrap('lua_arith', null, ['number', 'number']) this.lua_rawequal = this.cwrap('lua_rawequal', 'number', ['number', 'number', 'number']) - this.lua_compare = this.cwrap('lua_compare', 'number', ['number', 'number', 'number', 'number']) + this.lua_compare = this.cwrap('lua_compare', 'number', [ + 'number', + 'number', + 'number', + 'number', + ]) this.lua_pushnil = this.cwrap('lua_pushnil', null, ['number']) this.lua_pushnumber = this.cwrap('lua_pushnumber', null, ['number', 'number']) this.lua_pushinteger = this.cwrap('lua_pushinteger', null, ['number', 'number']) - this.lua_pushlstring = this.cwrap('lua_pushlstring', 'string', ['number', 'string|number', 'number']) + this.lua_pushlstring = this.cwrap('lua_pushlstring', 'string', [ + 'number', + 'string|number', + 'number', + ]) this.lua_pushstring = this.cwrap('lua_pushstring', 'string', ['number', 'string|number']) this.lua_pushcclosure = this.cwrap('lua_pushcclosure', null, ['number', 'number', 'number']) this.lua_pushboolean = this.cwrap('lua_pushboolean', null, ['number', 'number']) @@ -399,9 +538,17 @@ export default class LuaModule { this.lua_rawgeti = this.cwrap('lua_rawgeti', 'number', ['number', 'number', 'number']) this.lua_rawgetp = this.cwrap('lua_rawgetp', 'number', ['number', 'number', 'number']) this.lua_createtable = this.cwrap('lua_createtable', null, ['number', 'number', 'number']) - this.lua_newuserdatauv = this.cwrap('lua_newuserdatauv', 'number', ['number', 'number', 'number']) + this.lua_newuserdatauv = this.cwrap('lua_newuserdatauv', 'number', [ + 'number', + 'number', + 'number', + ]) this.lua_getmetatable = this.cwrap('lua_getmetatable', 'number', ['number', 'number']) - this.lua_getiuservalue = this.cwrap('lua_getiuservalue', 'number', ['number', 'number', 'number']) + this.lua_getiuservalue = this.cwrap('lua_getiuservalue', 'number', [ + 'number', + 'number', + 'number', + ]) this.lua_setglobal = this.cwrap('lua_setglobal', null, ['number', 'string']) this.lua_settable = this.cwrap('lua_settable', null, ['number', 'number']) this.lua_setfield = this.cwrap('lua_setfield', null, ['number', 'number', 'string']) @@ -410,13 +557,46 @@ export default class LuaModule { this.lua_rawseti = this.cwrap('lua_rawseti', null, ['number', 'number', 'number']) this.lua_rawsetp = this.cwrap('lua_rawsetp', null, ['number', 'number', 'number']) this.lua_setmetatable = this.cwrap('lua_setmetatable', 'number', ['number', 'number']) - this.lua_setiuservalue = this.cwrap('lua_setiuservalue', 'number', ['number', 'number', 'number']) - this.lua_callk = this.cwrap('lua_callk', null, ['number', 'number', 'number', 'number', 'number']) - this.lua_pcallk = this.cwrap('lua_pcallk', 'number', ['number', 'number', 'number', 'number', 'number', 'number']) - this.lua_load = this.cwrap('lua_load', 'number', ['number', 'number', 'number', 'string', 'string']) + this.lua_setiuservalue = this.cwrap('lua_setiuservalue', 'number', [ + 'number', + 'number', + 'number', + ]) + this.lua_callk = this.cwrap('lua_callk', null, [ + 'number', + 'number', + 'number', + 'number', + 'number', + ]) + this.lua_pcallk = this.cwrap('lua_pcallk', 'number', [ + 'number', + 'number', + 'number', + 'number', + 'number', + 'number', + ]) + this.lua_load = this.cwrap('lua_load', 'number', [ + 'number', + 'number', + 'number', + 'string', + 'string', + ]) this.lua_dump = this.cwrap('lua_dump', 'number', ['number', 'number', 'number', 'number']) - this.lua_yieldk = this.cwrap('lua_yieldk', 'number', ['number', 'number', 'number', 'number']) - this.lua_resume = this.cwrap('lua_resume', 'number', ['number', 'number', 'number', 'number']) + this.lua_yieldk = this.cwrap('lua_yieldk', 'number', [ + 'number', + 'number', + 'number', + 'number', + ]) + this.lua_resume = this.cwrap('lua_resume', 'number', [ + 'number', + 'number', + 'number', + 'number', + ]) this.lua_status = this.cwrap('lua_status', 'number', ['number']) this.lua_isyieldable = this.cwrap('lua_isyieldable', 'number', ['number']) this.lua_setwarnf = this.cwrap('lua_setwarnf', null, ['number', 'number', 'number']) @@ -437,7 +617,13 @@ export default class LuaModule { this.lua_getupvalue = this.cwrap('lua_getupvalue', 'string', ['number', 'number', 'number']) this.lua_setupvalue = this.cwrap('lua_setupvalue', 'string', ['number', 'number', 'number']) this.lua_upvalueid = this.cwrap('lua_upvalueid', 'number', ['number', 'number', 'number']) - this.lua_upvaluejoin = this.cwrap('lua_upvaluejoin', null, ['number', 'number', 'number', 'number', 'number']) + this.lua_upvaluejoin = this.cwrap('lua_upvaluejoin', null, [ + 'number', + 'number', + 'number', + 'number', + 'number', + ]) this.lua_sethook = this.cwrap('lua_sethook', null, ['number', 'number', 'number', 'number']) this.lua_gethook = this.cwrap('lua_gethook', 'number', ['number']) this.lua_gethookmask = this.cwrap('lua_gethookmask', 'number', ['number']) @@ -454,7 +640,7 @@ export default class LuaModule { this.luaopen_math = this.cwrap('luaopen_math', 'number', ['number']) this.luaopen_debug = this.cwrap('luaopen_debug', 'number', ['number']) this.luaopen_package = this.cwrap('luaopen_package', 'number', ['number']) - this.luaL_openlibs = (L) => this.luaL_openselectedlibs(L, -1, 0) + this.luaL_openlibs = L => this.luaL_openselectedlibs(L, -1, 0) } public lua_remove(luaState: LuaState, index: number): void { @@ -540,10 +726,15 @@ export default class LuaModule { argTypes: Array, ): (...args: any[]) => any { // optimization for common case - const hasStringOrNumber = argTypes.some((argType) => argType === 'string|number') + const hasStringOrNumber = argTypes.some(argType => argType === 'string|number') if (!hasStringOrNumber) { return (...args: any[]) => - this._emscripten.ccall(name, returnType, argTypes as Emscripten.JSType[], args as Emscripten.TypeCompatibleWithC[]) + this._emscripten.ccall( + name, + returnType, + argTypes as Emscripten.JSType[], + args as Emscripten.TypeCompatibleWithC[], + ) } return (...args: any[]) => { @@ -555,7 +746,9 @@ export default class LuaModule { } else { // because it will be freed later, this can only be used on functions that lua internally copies the string if (args[i]?.length > 1024) { - const bufferPointer = this._emscripten.stringToNewUTF8(args[i] as string) + const bufferPointer = this._emscripten.stringToNewUTF8( + args[i] as string, + ) args[i] = bufferPointer pointersToBeFreed.push(bufferPointer) return 'number' @@ -568,7 +761,12 @@ export default class LuaModule { }) try { - return this._emscripten.ccall(name, returnType, resolvedArgTypes, args as Emscripten.TypeCompatibleWithC[]) + return this._emscripten.ccall( + name, + returnType, + resolvedArgTypes, + args as Emscripten.TypeCompatibleWithC[], + ) } finally { for (const pointer of pointersToBeFreed) { this._emscripten._free(pointer) @@ -578,7 +776,9 @@ export default class LuaModule { } } -function createOutputWriter(writer?: (content: string) => void): ((charCode: number | null) => void) | null { +function createOutputWriter( + writer?: (content: string) => void, +): ((charCode: number | null) => void) | null { if (!writer) { return null } diff --git a/test/browser.test.js b/test/browser.test.js new file mode 100644 index 0000000..6a8d826 --- /dev/null +++ b/test/browser.test.js @@ -0,0 +1,200 @@ +import { createServer } from 'node:http' +import { readFile } from 'node:fs/promises' +import { join } from 'node:path' +import { expect } from 'chai' +import { chromium } from 'playwright' + +const DIST_DIR = new URL('../dist', import.meta.url).pathname + +function startServer() { + const mimeTypes = { + '.html': 'text/html', + '.js': 'application/javascript', + '.wasm': 'application/wasm', + '.map': 'application/json', + } + + const testPage = ` + + +` + + const server = createServer(async (req, res) => { + const url = new URL(req.url, `http://localhost`) + + if (url.pathname === '/' || url.pathname === '/index.html') { + res.writeHead(200, { 'Content-Type': 'text/html' }) + res.end(testPage) + return + } + + const filePath = join(DIST_DIR, url.pathname) + + try { + const data = await readFile(filePath) + const ext = url.pathname.substring(url.pathname.lastIndexOf('.')) + res.writeHead(200, { 'Content-Type': mimeTypes[ext] || 'application/octet-stream' }) + res.end(data) + } catch { + res.writeHead(404) + res.end('Not found') + } + }) + + return new Promise((resolve) => { + server.listen(0, '127.0.0.1', () => { + const { port } = server.address() + resolve({ server, port }) + }) + }) +} + +describe('Browser environment', () => { + let server, port, browser, context + + before(async function () { + this.timeout(30_000) + ; ({ server, port } = await startServer()) + browser = await chromium.launch() + context = await browser.newContext() + }) + + after(async () => { + await context?.close() + await browser?.close() + server?.close() + }) + + async function runInBrowser(code) { + const page = await context.newPage() + const errors = [] + page.on('pageerror', (err) => errors.push(err)) + + try { + await page.goto(`http://127.0.0.1:${port}/`) + await page.waitForFunction(() => window.__ready === true, null, { timeout: 15_000 }) + + const result = await page.evaluate(async (code) => { + return await window.__runTest(code) + }, code) + + if (errors.length > 0) { + throw errors[0] + } + return result + } finally { + await page.close() + } + } + + it('load Lua engine in browser should succeed', async function () { + this.timeout(30_000) + const result = await runInBrowser(` + const lua = await Lua.load({ wasmFile }) + const state = lua.createState() + return state !== undefined + `) + expect(result).to.be.true + }) + + it('execute Lua code in browser should succeed', async function () { + this.timeout(30_000) + const result = await runInBrowser(` + const lua = await Lua.load({ wasmFile }) + const state = lua.createState() + return await state.doString('return 2 + 2') + `) + expect(result).to.be.equal(4) + }) + + it('pass JS values to Lua and back in browser should succeed', async function () { + this.timeout(30_000) + const result = await runInBrowser(` + const lua = await Lua.load({ wasmFile }) + const state = lua.createState({ injectObjects: true }) + state.global.set('name', 'wasmoon') + return await state.doString('return "hello " .. name') + `) + expect(result).to.be.equal('hello wasmoon') + }) + + it('call JS function from Lua in browser should succeed', async function () { + this.timeout(30_000) + const result = await runInBrowser(` + const lua = await Lua.load({ wasmFile }) + const state = lua.createState({ injectObjects: true }) + state.global.set('add', (a, b) => a + b) + return await state.doString('return add(10, 20)') + `) + expect(result).to.be.equal(30) + }) + + it('mount and require a file in browser should succeed', async function () { + this.timeout(30_000) + const result = await runInBrowser(` + const lua = await Lua.load({ wasmFile }) + lua.mountFile('mymodule.lua', 'return 42') + const state = lua.createState() + return await state.doString('return require("mymodule")') + `) + expect(result).to.be.equal(42) + }) + + it('handle Lua tables as JS objects in browser should succeed', async function () { + this.timeout(30_000) + const result = await runInBrowser(` + const lua = await Lua.load({ wasmFile }) + const state = lua.createState({ injectObjects: true }) + const value = await state.doString('return { x = 10, y = 20 }') + return { x: value.x, y: value.y } + `) + expect(result).to.be.eql({ x: 10, y: 20 }) + }) + + it('handle errors in browser should succeed', async function () { + this.timeout(30_000) + const result = await runInBrowser(` + const lua = await Lua.load({ wasmFile }) + const state = lua.createState() + try { + await state.doString('error("test error")') + return false + } catch (e) { + return e.message.includes('test error') + } + `) + expect(result).to.be.true + }) + + it('use coroutines in browser should succeed', async function () { + this.timeout(30_000) + const result = await runInBrowser(` + const lua = await Lua.load({ wasmFile }) + const state = lua.createState() + return await state.doString(\` + local co = coroutine.create(function() + coroutine.yield(1) + coroutine.yield(2) + return 3 + end) + local results = {} + while true do + local ok, value = coroutine.resume(co) + if not ok then break end + results[#results + 1] = value + if coroutine.status(co) == "dead" then break end + end + return results[1] + results[2] + results[3] + \`) + `) + expect(result).to.be.equal(6) + }) +}) diff --git a/test/node.test.js b/test/node.test.js new file mode 100644 index 0000000..51d8dcb --- /dev/null +++ b/test/node.test.js @@ -0,0 +1,250 @@ +import { readFileSync, writeFileSync, mkdirSync, rmSync } from 'node:fs' +import { join } from 'node:path' +import { tmpdir } from 'node:os' +import { expect } from 'chai' +import { Lua } from '../dist/index.js' + +describe('Node environment', () => { + it('load Lua engine in node should succeed', async () => { + const lua = await Lua.load() + const state = lua.createState() + const result = await state.doString('return 1 + 1') + expect(result).to.be.equal(2) + }) + + it('access environment variables should succeed', async () => { + const env = { MY_TEST_VAR: 'hello_from_node' } + const lua = await Lua.load({ env }) + const state = lua.createState() + const result = await state.doString('return os.getenv("MY_TEST_VAR")') + expect(result).to.be.equal('hello_from_node') + }) + + it('custom stdout should succeed', async () => { + const output = [] + const lua = await Lua.load({ + stdout: (content) => output.push(content), + }) + const state = lua.createState() + await state.doString('print("hello from node")') + expect(output.join('')).to.include('hello from node') + }) + + it('custom stderr should succeed', async () => { + const errors = [] + const lua = await Lua.load({ + stderr: (content) => errors.push(content), + }) + const state = lua.createState() + await state.doString('io.stderr:write("error output\\n")') + expect(errors.join('')).to.include('error output') + }) + + it('mount file and require in node should succeed', async () => { + const lua = await Lua.load() + lua.mountFile('nodetest.lua', 'return { value = 99 }') + const state = lua.createState({ injectObjects: true }) + const result = await state.doString('local m = require("nodetest"); return m.value') + expect(result).to.be.equal(99) + }) + + it('mount file with binary content should succeed', async () => { + const lua = await Lua.load() + const content = new Uint8Array([114, 101, 116, 117, 114, 110, 32, 52, 50]) // "return 42" + lua.mountFile('binary.lua', content) + const state = lua.createState() + const result = await state.doString('return dofile("binary.lua")') + expect(result).to.be.equal(42) + }) + + it('mount file in nested directories should succeed', async () => { + const lua = await Lua.load() + lua.mountFile('a/b/c/deep.lua', 'return "deep"') + const state = lua.createState() + const result = await state.doString('return require("a/b/c/deep")') + expect(result).to.be.equal('deep') + }) + + it('create multiple independent states should succeed', async () => { + const lua = await Lua.load() + const state1 = lua.createState() + const state2 = lua.createState() + + await state1.doString('x = 10') + await state2.doString('x = 20') + + const val1 = await state1.doString('return x') + const val2 = await state2.doString('return x') + + expect(val1).to.be.equal(10) + expect(val2).to.be.equal(20) + }) + + it('pass complex JS objects to Lua should succeed', async () => { + const state = (await Lua.load()).createState({ injectObjects: true }) + state.global.set('data', { + name: 'test', + nested: { value: 42 }, + items: [1, 2, 3], + }) + const result = await state.doString('return data.nested.value') + expect(result).to.be.equal(42) + }) + + it('call JS async functions from Lua should succeed', async () => { + const state = (await Lua.load()).createState({ injectObjects: true }) + state.global.set('fetchData', async () => { + return 'async result' + }) + const result = await state.doString('return fetchData():await()') + expect(result).to.be.equal('async result') + }) + + it('use NODEFS to read host files should succeed', async () => { + const tempDir = join(tmpdir(), `wasmoon-test-${Date.now()}`) + mkdirSync(tempDir, { recursive: true }) + const testFile = join(tempDir, 'test.txt') + writeFileSync(testFile, 'hello from host') + + try { + const lua = await Lua.load({ fs: 'node' }) + const state = lua.createState() + const result = await state.doString(` + local f = io.open("${testFile.replace(/\\/g, '/')}", "r") + local content = f:read("*a") + f:close() + return content + `) + expect(result).to.be.equal('hello from host') + } finally { + rmSync(tempDir, { recursive: true, force: true }) + } + }) + + it('use NODEFS to write and read back files should succeed', async () => { + const tempDir = join(tmpdir(), `wasmoon-test-${Date.now()}`) + mkdirSync(tempDir, { recursive: true }) + const testFile = join(tempDir, 'output.txt') + + try { + const lua = await Lua.load({ fs: 'node' }) + const state = lua.createState() + await state.doString(` + local f = io.open("${testFile.replace(/\\/g, '/')}", "w") + f:write("written from lua") + f:close() + `) + const content = readFileSync(testFile, 'utf8') + expect(content).to.be.equal('written from lua') + } finally { + rmSync(tempDir, { recursive: true, force: true }) + } + }) + + it('NODEFS cwd should match process.cwd', async () => { + const lua = await Lua.load({ fs: 'node' }) + const state = lua.createState() + // Write a temp file in the CWD and verify it can be read + const markerFile = join(process.cwd(), `.wasmoon-cwd-test-${Date.now()}.tmp`) + writeFileSync(markerFile, 'cwd-marker') + try { + const result = await state.doString(` + local f = io.open("${markerFile.replace(/\\/g, '/')}", "r") + if not f then return nil end + local content = f:read("*a") + f:close() + return content + `) + expect(result).to.be.equal('cwd-marker') + } finally { + rmSync(markerFile, { force: true }) + } + }) + + it('NODEFS with fsMountPaths should only mount specified paths', async () => { + const tempDir = join(tmpdir(), `wasmoon-mount-test-${Date.now()}`) + mkdirSync(tempDir, { recursive: true }) + const testFile = join(tempDir, 'specific.txt') + writeFileSync(testFile, 'mounted content') + + try { + const lua = await Lua.load({ fs: 'node', fsMountPaths: [tmpdir()] }) + const state = lua.createState() + const result = await state.doString(` + local f = io.open("${testFile.replace(/\\/g, '/')}", "r") + if not f then return nil end + local content = f:read("*a") + f:close() + return content + `) + expect(result).to.be.equal('mounted content') + } finally { + rmSync(tempDir, { recursive: true, force: true }) + } + }) + + it('NODEFS opening nonexistent file should return nil', async () => { + const lua = await Lua.load({ fs: 'node' }) + const state = lua.createState() + const result = await state.doString(` + local f, err = io.open("/tmp/wasmoon_nonexistent_file_${Date.now()}.txt", "r") + return f == nil and type(err) == "string" + `) + expect(result).to.be.true + }) + + it('mountFile and NODEFS should coexist', async () => { + const tempDir = join(tmpdir(), `wasmoon-coexist-${Date.now()}`) + mkdirSync(tempDir, { recursive: true }) + const hostFile = join(tempDir, 'host.txt') + writeFileSync(hostFile, 'from host') + + try { + const lua = await Lua.load({ fs: 'node' }) + lua.mountFile('virtual.lua', 'return "from virtual"') + const state = lua.createState() + + const hostContent = await state.doString(` + local f = io.open("${hostFile.replace(/\\/g, '/')}", "r") + local content = f:read("*a") + f:close() + return content + `) + const virtualContent = await state.doString('return dofile("virtual.lua")') + + expect(hostContent).to.be.equal('from host') + expect(virtualContent).to.be.equal('from virtual') + } finally { + rmSync(tempDir, { recursive: true, force: true }) + rmSync('virtual.lua', { force: true }) + } + }) + + it('standard libraries are available should succeed', async () => { + const state = (await Lua.load()).createState() + const result = await state.doString(` + local checks = {} + checks[1] = type(string.format) == "function" + checks[2] = type(table.insert) == "function" + checks[3] = type(math.floor) == "function" + checks[4] = type(os.time) == "function" + checks[5] = type(coroutine.create) == "function" + for _, v in ipairs(checks) do + if not v then return false end + end + return true + `) + expect(result).to.be.true + }) + + it('error handling with pcall should succeed', async () => { + const state = (await Lua.load()).createState() + const result = await state.doString(` + local ok, err = pcall(function() + error("node test error") + end) + return not ok and string.find(err, "node test error") ~= nil + `) + expect(result).to.be.true + }) +}) diff --git a/test/nodefs.test.js b/test/nodefs.test.js new file mode 100644 index 0000000..166530f --- /dev/null +++ b/test/nodefs.test.js @@ -0,0 +1,410 @@ +import { readFileSync, writeFileSync, mkdirSync, rmSync, existsSync, symlinkSync, readdirSync } from 'node:fs' +import { join } from 'node:path' +import { tmpdir } from 'node:os' +import { expect } from 'chai' +import { Lua } from '../dist/index.js' + +const createTempDir = () => { + const dir = join(tmpdir(), `wasmoon-nodefs-${Date.now()}-${Math.random().toString(36).slice(2)}`) + mkdirSync(dir, { recursive: true }) + return dir +} + +describe('Node FS', () => { + let tempDir + + beforeEach(() => { + tempDir = createTempDir() + }) + + afterEach(() => { + rmSync(tempDir, { recursive: true, force: true }) + }) + + it('read a host file should succeed', async () => { + writeFileSync(join(tempDir, 'hello.txt'), 'hello world') + + const lua = await Lua.load({ fs: 'node' }) + const state = lua.createState() + const result = await state.doString(` + local f = io.open("${join(tempDir, 'hello.txt').replace(/\\/g, '/')}", "r") + local content = f:read("*a") + f:close() + return content + `) + + expect(result).to.be.equal('hello world') + }) + + it('write a file to host should succeed', async () => { + const filePath = join(tempDir, 'output.txt') + + const lua = await Lua.load({ fs: 'node' }) + const state = lua.createState() + await state.doString(` + local f = io.open("${filePath.replace(/\\/g, '/')}", "w") + f:write("written from lua") + f:close() + `) + + expect(readFileSync(filePath, 'utf8')).to.be.equal('written from lua') + }) + + it('append to a host file should succeed', async () => { + const filePath = join(tempDir, 'append.txt') + writeFileSync(filePath, 'first line\n') + + const lua = await Lua.load({ fs: 'node' }) + const state = lua.createState() + await state.doString(` + local f = io.open("${filePath.replace(/\\/g, '/')}", "a") + f:write("second line\\n") + f:close() + `) + + expect(readFileSync(filePath, 'utf8')).to.be.equal('first line\nsecond line\n') + }) + + it('read file line by line should succeed', async () => { + writeFileSync(join(tempDir, 'lines.txt'), 'alpha\nbeta\ngamma\n') + + const lua = await Lua.load({ fs: 'node' }) + const state = lua.createState() + const result = await state.doString(` + local lines = {} + for line in io.lines("${join(tempDir, 'lines.txt').replace(/\\/g, '/')}") do + lines[#lines + 1] = line + end + return table.concat(lines, ",") + `) + + expect(result).to.be.equal('alpha,beta,gamma') + }) + + it('read binary file should succeed', async () => { + const buf = Buffer.from([0x00, 0x01, 0x02, 0xff, 0xfe]) + writeFileSync(join(tempDir, 'binary.dat'), buf) + + const lua = await Lua.load({ fs: 'node' }) + const state = lua.createState() + const result = await state.doString(` + local f = io.open("${join(tempDir, 'binary.dat').replace(/\\/g, '/')}", "rb") + local data = f:read("*a") + f:close() + return #data + `) + + expect(result).to.be.equal(5) + }) + + it('write and read back binary data should succeed', async () => { + const filePath = join(tempDir, 'binout.dat') + + const lua = await Lua.load({ fs: 'node' }) + const state = lua.createState() + await state.doString(` + local f = io.open("${filePath.replace(/\\/g, '/')}", "wb") + f:write(string.char(72, 101, 108, 108, 111)) + f:close() + `) + + expect(readFileSync(filePath, 'utf8')).to.be.equal('Hello') + }) + + it('check if file exists using io.open should succeed', async () => { + writeFileSync(join(tempDir, 'exists.txt'), 'yes') + + const lua = await Lua.load({ fs: 'node' }) + const state = lua.createState() + const result = await state.doString(` + local f = io.open("${join(tempDir, 'exists.txt').replace(/\\/g, '/')}", "r") + local exists = f ~= nil + if f then f:close() end + + local f2 = io.open("${join(tempDir, 'nope.txt').replace(/\\/g, '/')}", "r") + local not_exists = f2 == nil + if f2 then f2:close() end + + return exists and not_exists + `) + + expect(result).to.be.true + }) + + it('read file size should succeed', async () => { + writeFileSync(join(tempDir, 'sized.txt'), 'abcdefghij') + + const lua = await Lua.load({ fs: 'node' }) + const state = lua.createState() + const result = await state.doString(` + local f = io.open("${join(tempDir, 'sized.txt').replace(/\\/g, '/')}", "r") + local size = f:seek("end") + f:close() + return size + `) + + expect(result).to.be.equal(10) + }) + + it('seek within a file should succeed', async () => { + writeFileSync(join(tempDir, 'seek.txt'), 'abcdefghij') + + const lua = await Lua.load({ fs: 'node' }) + const state = lua.createState() + const result = await state.doString(` + local f = io.open("${join(tempDir, 'seek.txt').replace(/\\/g, '/')}", "r") + f:seek("set", 3) + local chunk = f:read(4) + f:close() + return chunk + `) + + expect(result).to.be.equal('defg') + }) + + it('doFile from host filesystem should succeed', async () => { + writeFileSync(join(tempDir, 'script.lua'), 'return 7 * 6') + + const lua = await Lua.load({ fs: 'node' }) + const state = lua.createState() + const result = await state.doFile(join(tempDir, 'script.lua').replace(/\\/g, '/')) + + expect(result).to.be.equal(42) + }) + + it('require a host lua file should succeed', async () => { + const luaDir = join(tempDir, 'lualibs') + mkdirSync(luaDir, { recursive: true }) + writeFileSync(join(luaDir, 'mymod.lua'), 'local M = {}; M.value = 99; return M') + + const lua = await Lua.load({ fs: 'node' }) + const state = lua.createState({ injectObjects: true }) + const result = await state.doString(` + package.path = "${luaDir.replace(/\\/g, '/')}/?.lua;" .. package.path + local m = require("mymod") + return m.value + `) + + expect(result).to.be.equal(99) + }) + + it('read from nested directories should succeed', async () => { + const nested = join(tempDir, 'a', 'b', 'c') + mkdirSync(nested, { recursive: true }) + writeFileSync(join(nested, 'deep.txt'), 'deep content') + + const lua = await Lua.load({ fs: 'node' }) + const state = lua.createState() + const result = await state.doString(` + local f = io.open("${join(nested, 'deep.txt').replace(/\\/g, '/')}", "r") + local content = f:read("*a") + f:close() + return content + `) + + expect(result).to.be.equal('deep content') + }) + + it('create directory from lua with os.execute should succeed', async () => { + const newDir = join(tempDir, 'newdir') + + const lua = await Lua.load({ fs: 'node' }) + const state = lua.createState() + await state.doString(` + os.execute("mkdir -p '${newDir.replace(/\\/g, '/')}'") + `) + + expect(existsSync(newDir)).to.be.true + }) + + it('remove a host file from lua with os.remove should succeed', async () => { + const filePath = join(tempDir, 'removeme.txt') + writeFileSync(filePath, 'to be deleted') + + const lua = await Lua.load({ fs: 'node' }) + const state = lua.createState() + const result = await state.doString(` + return os.remove("${filePath.replace(/\\/g, '/')}") + `) + + expect(result).to.be.true + expect(existsSync(filePath)).to.be.false + }) + + it('rename a host file from lua with os.rename should succeed', async () => { + const oldPath = join(tempDir, 'old.txt') + const newPath = join(tempDir, 'new.txt') + writeFileSync(oldPath, 'rename me') + + const lua = await Lua.load({ fs: 'node' }) + const state = lua.createState() + const result = await state.doString(` + return os.rename("${oldPath.replace(/\\/g, '/')}", "${newPath.replace(/\\/g, '/')}") + `) + + expect(result).to.be.true + expect(existsSync(oldPath)).to.be.false + expect(readFileSync(newPath, 'utf8')).to.be.equal('rename me') + }) + + it('doFile from cwd-relative path should succeed', async () => { + // NODEFS sets cwd to process.cwd(), so relative doFile should work + const lua = await Lua.load({ fs: 'node' }) + lua.mountFile('cwd_test.lua', 'return "from cwd"') + try { + const state = lua.createState() + const result = await state.doFile('cwd_test.lua') + + expect(result).to.be.equal('from cwd') + } finally { + rmSync('cwd_test.lua', { force: true }) + } + }) + + it('write large file should succeed', async () => { + const filePath = join(tempDir, 'large.txt') + const lineCount = 10000 + + const lua = await Lua.load({ fs: 'node' }) + const state = lua.createState() + await state.doString(` + local f = io.open("${filePath.replace(/\\/g, '/')}", "w") + for i = 1, ${lineCount} do + f:write("line " .. i .. "\\n") + end + f:close() + `) + + const content = readFileSync(filePath, 'utf8') + const lines = content.trimEnd().split('\n') + expect(lines.length).to.be.equal(lineCount) + expect(lines[0]).to.be.equal('line 1') + expect(lines[lineCount - 1]).to.be.equal(`line ${lineCount}`) + }) + + it('overwrite existing file should succeed', async () => { + const filePath = join(tempDir, 'overwrite.txt') + writeFileSync(filePath, 'original content') + + const lua = await Lua.load({ fs: 'node' }) + const state = lua.createState() + await state.doString(` + local f = io.open("${filePath.replace(/\\/g, '/')}", "w") + f:write("new content") + f:close() + `) + + expect(readFileSync(filePath, 'utf8')).to.be.equal('new content') + }) + + it('read UTF-8 content should succeed', async () => { + const content = 'héllo wörld 日本語 🌍' + writeFileSync(join(tempDir, 'utf8.txt'), content) + + const lua = await Lua.load({ fs: 'node' }) + const state = lua.createState() + const result = await state.doString(` + local f = io.open("${join(tempDir, 'utf8.txt').replace(/\\/g, '/')}", "r") + local data = f:read("*a") + f:close() + return data + `) + + expect(result).to.be.equal(content) + }) + + it('write UTF-8 content should succeed', async () => { + const filePath = join(tempDir, 'utf8out.txt') + + const lua = await Lua.load({ fs: 'node' }) + const state = lua.createState() + await state.doString(` + local f = io.open("${filePath.replace(/\\/g, '/')}", "w") + f:write("café ñ 中文") + f:close() + `) + + expect(readFileSync(filePath, 'utf8')).to.be.equal('café ñ 中文') + }) + + it('read empty file should succeed', async () => { + writeFileSync(join(tempDir, 'empty.txt'), '') + + const lua = await Lua.load({ fs: 'node' }) + const state = lua.createState() + const result = await state.doString(` + local f = io.open("${join(tempDir, 'empty.txt').replace(/\\/g, '/')}", "r") + local data = f:read("*a") + f:close() + return #data + `) + + expect(result).to.be.equal(0) + }) + + it('open non-existent file for reading should return nil', async () => { + const lua = await Lua.load({ fs: 'node' }) + const state = lua.createState() + const result = await state.doString(` + local f, err = io.open("${join(tempDir, 'nonexistent.txt').replace(/\\/g, '/')}", "r") + return f == nil + `) + + expect(result).to.be.true + }) + + it('io.tmpfile should succeed', async () => { + const lua = await Lua.load({ fs: 'node' }) + const state = lua.createState() + const result = await state.doString(` + local f = io.tmpfile() + f:write("temp data") + f:seek("set") + local data = f:read("*a") + f:close() + return data + `) + + expect(result).to.be.equal('temp data') + }) + + it('multiple states sharing the same NODEFS should succeed', async () => { + const filePath = join(tempDir, 'shared.txt') + + const lua = await Lua.load({ fs: 'node' }) + const state1 = lua.createState() + const state2 = lua.createState() + + await state1.doString(` + local f = io.open("${filePath.replace(/\\/g, '/')}", "w") + f:write("from state1") + f:close() + `) + + const result = await state2.doString(` + local f = io.open("${filePath.replace(/\\/g, '/')}", "r") + local data = f:read("*a") + f:close() + return data + `) + + expect(result).to.be.equal('from state1') + }) + + it('read number from file should succeed', async () => { + writeFileSync(join(tempDir, 'numbers.txt'), '42\n3.14\n100') + + const lua = await Lua.load({ fs: 'node' }) + const state = lua.createState() + const result = await state.doString(` + local f = io.open("${join(tempDir, 'numbers.txt').replace(/\\/g, '/')}", "r") + local n1 = f:read("*n") + local n2 = f:read("*n") + local n3 = f:read("*n") + f:close() + return n1 + n2 + n3 + `) + + expect(result).to.be.closeTo(145.14, 0.001) + }) +}) From dbcb003641754e1b98079da334787cd563949dd4 Mon Sep 17 00:00:00 2001 From: Gabriel Francisco Date: Tue, 24 Mar 2026 21:53:21 -0300 Subject: [PATCH 34/83] nodefs: load the current drive by default --- README.md | 8 ++-- src/module.ts | 91 +++++++++++++++++++++++++------------------- src/thread.ts | 2 +- test/browser.test.js | 2 +- tsconfig.json | 3 +- 5 files changed, 60 insertions(+), 46 deletions(-) diff --git a/README.md b/README.md index 9d42ebd..f8f2543 100644 --- a/README.md +++ b/README.md @@ -80,10 +80,10 @@ Wasmoon compiles the [official Lua code](https://github.com/lua/lua) to WebAssem Because of WebAssembly, wasmoon runs Lua code significantly faster than fengari. The table below shows results from a [heap sort benchmark](https://github.com/ceifa/wasmoon/blob/main/bench/heapsort.lua) sorting a list of 2,000 numbers (100 iterations, 5 warmup): -| | avg | median | min | max | stddev | relative | -| ---------------- | ---------- | ---------- | ---------- | ---------- | --------- | -------- | -| **Wasmoon** | 13.41 ms | 13.07 ms | 12.20 ms | 16.23 ms | 1.12 ms | 1.00x | -| **Fengari** | 137.36 ms | 138.51 ms | 119.70 ms | 165.54 ms | 11.16 ms | 10.24x | +| | avg | median | min | max | stddev | relative | +| ----------- | --------- | --------- | --------- | --------- | -------- | -------- | +| **Wasmoon** | 13.41 ms | 13.07 ms | 12.20 ms | 16.23 ms | 1.12 ms | 1.00x | +| **Fengari** | 137.36 ms | 138.51 ms | 119.70 ms | 165.54 ms | 11.16 ms | 10.24x | Wasmoon is **~10x faster** than fengari for pure Lua execution. If your use case involves heavy interop between JS and Lua, the difference may be smaller, benchmark your specific scenario. diff --git a/src/module.ts b/src/module.ts index d9590a0..2a1fd7e 100755 --- a/src/module.ts +++ b/src/module.ts @@ -21,7 +21,7 @@ interface LuaEmscriptenModule extends EmscriptenModule { PATH: { dirname: (typeof import('node:path'))['dirname'] } - stringToNewUTF8: typeof allocateUTF8 + stringToNewUTF8: typeof stringToNewUTF8 lengthBytesUTF8: typeof lengthBytesUTF8 stringToUTF8: typeof stringToUTF8 intArrayFromString: typeof intArrayFromString @@ -66,61 +66,74 @@ export default class LuaModule { } if (fs) { - let rootdirs: string[] - if (opts.fsMountPaths) { - rootdirs = opts.fsMountPaths - } else if (process.platform === 'win32') { - const drives: string[] = [] - for (let i = 65; i <= 90; i++) { - const drive = `${String.fromCharCode(i)}:\\` - try { - fs.accessSync(drive) - drives.push(drive) - } catch { - // drive does not exist - } - } + const cwd = process.cwd().replace(/\\/g, '/') + // Default to mounting the drive containing the CWD + const cwdDrive = process.platform === 'win32' ? cwd.slice(0, 3) : '/' + const mountPaths = opts.fsMountPaths ?? [cwdDrive] + + // Deduplicate and remove paths that are children of other mount paths + const normalized = [...new Set(mountPaths.map(p => p.replace(/\\/g, '/')))] + const filtered = normalized.filter( + path => + !normalized.some( + other => other !== path && path.startsWith(other + '/'), + ), + ) - rootdirs = [] - for (const drive of drives) { + // Expand drive roots into their subdirectories, since + // Emscripten's VFS already owns "/" and cannot be mounted over. + // Skip virtual/system filesystems that cause issues with NODEFS. + const skipDirs = [ + 'dev', + 'proc', + 'sys', + 'run', + 'snap', + 'System Volume Information', + '$Recycle.Bin', + 'Recovery', + ] + const expanded: string[] = [] + for (const dir of filtered) { + const isDriveRoot = dir === '/' || /^[A-Za-z]:\/$/.test(dir) + if (isDriveRoot) { try { - rootdirs.push( - ...fs - .readdirSync(drive) - .filter(dir => !['dev', 'lib', 'proc'].includes(dir)) - .map(dir => `${drive}${dir}`.replace(/\\/g, '/')), - ) + const children = fs + .readdirSync(dir) + .filter((child: string) => !skipDirs.includes(child)) + .map((child: string) => + dir === '/' + ? `/${child}` + : `${dir}${child}`.replace(/\\/g, '/'), + ) + expanded.push(...children) } catch { // drive not readable } - } - } else { - try { - rootdirs = fs - .readdirSync('/') - .filter(dir => !['dev', 'lib', 'proc'].includes(dir)) - .map(dir => `/${dir}`) - } catch { - rootdirs = [] + } else { + expanded.push(dir) } } - for (const dir of rootdirs) { + for (const dir of expanded) { try { const moduleFS = initializedModule.FS moduleFS.mkdirTree(dir) moduleFS.mount(moduleFS.filesystems.NODEFS, { root: dir }, dir) } catch (err: any) { - const isPermError = - err?.code === 'EACCES' || err?.code === 'EPERM' || err?.errno === 2 - if (!isPermError) { + // Ignore permission/not-found errors from both Node.js + // (string .code) and Emscripten ErrnoError (numeric .errno) + const isIgnorableError = + ['EACCES', 'EPERM', 'ENOENT'].includes(err?.code) || + err?.name === 'ErrnoError' + if (!isIgnorableError) { console.warn(`Failed to mount ${dir}:`, err) } } } try { - initializedModule.FS.chdir(process.cwd().replace(/\\/g, '/')) + initializedModule.FS.chdir(cwd) } catch { // CWD may not be within mounted paths } @@ -142,12 +155,12 @@ export default class LuaModule { } } - if (bufferedInput.length === 0) { + if (bufferedInput!.length === 0) { bufferedInput = undefined return null } - const item = bufferedInput.shift() + const item = bufferedInput!.shift() return !item || item === 0 ? null : item } : null, diff --git a/src/thread.ts b/src/thread.ts index bd9d832..b158efe 100755 --- a/src/thread.ts +++ b/src/thread.ts @@ -330,7 +330,7 @@ export default class Thread { }, 'vii') } - this.lua.lua_sethook(this.address, this.hookFunctionPointer, LuaEventMasks.Count, INSTRUCTION_HOOK_COUNT) + this.lua.lua_sethook(this.address, this.hookFunctionPointer!, LuaEventMasks.Count, INSTRUCTION_HOOK_COUNT) this.timeout = timeout } else if (this.hookFunctionPointer) { this.hookFunctionPointer = undefined diff --git a/test/browser.test.js b/test/browser.test.js index 6a8d826..da0f295 100644 --- a/test/browser.test.js +++ b/test/browser.test.js @@ -62,7 +62,7 @@ describe('Browser environment', () => { before(async function () { this.timeout(30_000) - ; ({ server, port } = await startServer()) + ;({ server, port } = await startServer()) browser = await chromium.launch() context = await browser.newContext() }) diff --git a/tsconfig.json b/tsconfig.json index af4b756..54b02dd 100755 --- a/tsconfig.json +++ b/tsconfig.json @@ -6,8 +6,9 @@ "inlineSources": false, "removeComments": false, "sourceMap": false, - "target": "ES2022", + "target": "ES2024", "skipLibCheck": true, + "types": ["emscripten", "node"], "lib": ["ESNEXT", "DOM"], "forceConsistentCasingInFileNames": true, "noImplicitReturns": true, From 0980891d448577b12b211cad997d41671764f344 Mon Sep 17 00:00:00 2001 From: Gabriel Francisco Date: Tue, 24 Mar 2026 21:59:38 -0300 Subject: [PATCH 35/83] lint --- .oxlintrc.json | 10 +- src/module.ts | 289 +++++++------------------------------------ test/browser.test.js | 4 +- test/nodefs.test.js | 2 +- 4 files changed, 58 insertions(+), 247 deletions(-) diff --git a/.oxlintrc.json b/.oxlintrc.json index ceebf07..1769aea 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -9,5 +9,13 @@ "ignorePatterns": ["dist/**", "build/**", "rolldown.config.ts", "rolldown.config.*.js", "utils/**"], "env": { "builtin": true - } + }, + "overrides": [ + { + "files": ["test/**"], + "rules": { + "no-unused-expressions": "off" + } + } + ] } diff --git a/src/module.ts b/src/module.ts index 2a1fd7e..4a01496 100755 --- a/src/module.ts +++ b/src/module.ts @@ -72,27 +72,15 @@ export default class LuaModule { const mountPaths = opts.fsMountPaths ?? [cwdDrive] // Deduplicate and remove paths that are children of other mount paths - const normalized = [...new Set(mountPaths.map(p => p.replace(/\\/g, '/')))] + const normalized = [...new Set(mountPaths.map((p) => p.replace(/\\/g, '/')))] const filtered = normalized.filter( - path => - !normalized.some( - other => other !== path && path.startsWith(other + '/'), - ), + (path) => !normalized.some((other) => other !== path && path.startsWith(other + '/')), ) // Expand drive roots into their subdirectories, since // Emscripten's VFS already owns "/" and cannot be mounted over. // Skip virtual/system filesystems that cause issues with NODEFS. - const skipDirs = [ - 'dev', - 'proc', - 'sys', - 'run', - 'snap', - 'System Volume Information', - '$Recycle.Bin', - 'Recovery', - ] + const skipDirs = ['dev', 'proc', 'sys', 'run', 'snap', 'System Volume Information', '$Recycle.Bin', 'Recovery'] const expanded: string[] = [] for (const dir of filtered) { const isDriveRoot = dir === '/' || /^[A-Za-z]:\/$/.test(dir) @@ -101,11 +89,7 @@ export default class LuaModule { const children = fs .readdirSync(dir) .filter((child: string) => !skipDirs.includes(child)) - .map((child: string) => - dir === '/' - ? `/${child}` - : `${dir}${child}`.replace(/\\/g, '/'), - ) + .map((child: string) => (dir === '/' ? `/${child}` : `${dir}${child}`.replace(/\\/g, '/'))) expanded.push(...children) } catch { // drive not readable @@ -123,9 +107,7 @@ export default class LuaModule { } catch (err: any) { // Ignore permission/not-found errors from both Node.js // (string .code) and Emscripten ErrnoError (numeric .errno) - const isIgnorableError = - ['EACCES', 'EPERM', 'ENOENT'].includes(err?.code) || - err?.name === 'ErrnoError' + const isIgnorableError = ['EACCES', 'EPERM', 'ENOENT'].includes(err?.code) || err?.name === 'ErrnoError' if (!isIgnorableError) { console.warn(`Failed to mount ${dir}:`, err) } @@ -147,9 +129,7 @@ export default class LuaModule { if (!bufferedInput) { const input = opts.stdin?.() if (typeof input === 'string') { - bufferedInput = initializedModule - .intArrayFromString(input, true) - .concat([0]) + bufferedInput = initializedModule.intArrayFromString(input, true).concat([0]) } else { throw new Error('stdin must return a string') } @@ -182,12 +162,7 @@ export default class LuaModule { public luaL_argerror: (L: LuaState, arg: number, extramsg: string | null) => number public luaL_typeerror: (L: LuaState, arg: number, tname: string | null) => number public luaL_checklstring: (L: LuaState, arg: number, l: number | null) => string - public luaL_optlstring: ( - L: LuaState, - arg: number, - def: string | null, - l: number | null, - ) => string + public luaL_optlstring: (L: LuaState, arg: number, def: string | null, l: number | null) => string public luaL_checknumber: (L: LuaState, arg: number) => number public luaL_optnumber: (L: LuaState, arg: number, def: number) => number public luaL_checkinteger: (L: LuaState, arg: number) => number @@ -215,12 +190,7 @@ export default class LuaModule { public luaL_loadstring: (L: LuaState, s: string | null) => LuaReturn public luaL_newstate: () => LuaState public luaL_len: (L: LuaState, idx: number) => number - public luaL_addgsub: ( - b: number | null, - s: string | null, - p: string | null, - r: string | null, - ) => void + public luaL_addgsub: (b: number | null, s: string | null, p: string | null, r: string | null) => void public luaL_gsub: (L: LuaState, s: string | null, p: string | null, r: string | null) => string public luaL_setfuncs: (L: LuaState, l: number | null, nup: number) => void public luaL_getsubtable: (L: LuaState, idx: number, fname: string | null) => number @@ -298,41 +268,12 @@ export default class LuaModule { public lua_rawsetp: (L: LuaState, idx: number, p: number | null) => void public lua_setmetatable: (L: LuaState, objindex: number) => number public lua_setiuservalue: (L: LuaState, idx: number, n: number) => number - public lua_callk: ( - L: LuaState, - nargs: number, - nresults: number, - ctx: number, - k: number | null, - ) => void - public lua_pcallk: ( - L: LuaState, - nargs: number, - nresults: number, - errfunc: number, - ctx: number, - k: number | null, - ) => number - public lua_load: ( - L: LuaState, - reader: number | null, - dt: number | null, - chunkname: string | null, - mode: string | null, - ) => LuaReturn - public lua_dump: ( - L: LuaState, - writer: number | null, - data: number | null, - strip: number, - ) => number + public lua_callk: (L: LuaState, nargs: number, nresults: number, ctx: number, k: number | null) => void + public lua_pcallk: (L: LuaState, nargs: number, nresults: number, errfunc: number, ctx: number, k: number | null) => number + public lua_load: (L: LuaState, reader: number | null, dt: number | null, chunkname: string | null, mode: string | null) => LuaReturn + public lua_dump: (L: LuaState, writer: number | null, data: number | null, strip: number) => number public lua_yieldk: (L: LuaState, nresults: number, ctx: number, k: number | null) => number - public lua_resume: ( - L: LuaState, - from: LuaState | null, - narg: number, - nres: number | null, - ) => LuaReturn + public lua_resume: (L: LuaState, from: LuaState | null, narg: number, nres: number | null) => LuaReturn public lua_status: (L: LuaState) => LuaReturn public lua_isyieldable: (L: LuaState) => number public lua_setwarnf: (L: LuaState, f: number | null, ud: number | null) => void @@ -353,13 +294,7 @@ export default class LuaModule { public lua_getupvalue: (L: LuaState, funcindex: number, n: number) => string public lua_setupvalue: (L: LuaState, funcindex: number, n: number) => string public lua_upvalueid: (L: LuaState, fidx: number, n: number) => number - public lua_upvaluejoin: ( - L: LuaState, - fidx1: number, - n1: number, - fidx2: number, - n2: number, - ) => void + public lua_upvaluejoin: (L: LuaState, fidx1: number, n1: number, fidx2: number, n2: number) => void public lua_sethook: (L: LuaState, func: number | null, mask: number, count: number) => void public lua_gethook: (L: LuaState) => number public lua_gethookmask: (L: LuaState) => number @@ -385,100 +320,42 @@ export default class LuaModule { public constructor(module: LuaEmscriptenModule) { this._emscripten = module - this.luaL_checkversion_ = this.cwrap('luaL_checkversion_', null, [ - 'number', - 'number', - 'number', - ]) - this.luaL_getmetafield = this.cwrap('luaL_getmetafield', 'number', [ - 'number', - 'number', - 'string', - ]) + this.luaL_checkversion_ = this.cwrap('luaL_checkversion_', null, ['number', 'number', 'number']) + this.luaL_getmetafield = this.cwrap('luaL_getmetafield', 'number', ['number', 'number', 'string']) this.luaL_callmeta = this.cwrap('luaL_callmeta', 'number', ['number', 'number', 'string']) this.luaL_tolstring = this.cwrap('luaL_tolstring', 'string', ['number', 'number', 'number']) this.luaL_argerror = this.cwrap('luaL_argerror', 'number', ['number', 'number', 'string']) this.luaL_typeerror = this.cwrap('luaL_typeerror', 'number', ['number', 'number', 'string']) - this.luaL_checklstring = this.cwrap('luaL_checklstring', 'string', [ - 'number', - 'number', - 'number', - ]) - this.luaL_optlstring = this.cwrap('luaL_optlstring', 'string', [ - 'number', - 'number', - 'string', - 'number', - ]) + this.luaL_checklstring = this.cwrap('luaL_checklstring', 'string', ['number', 'number', 'number']) + this.luaL_optlstring = this.cwrap('luaL_optlstring', 'string', ['number', 'number', 'string', 'number']) this.luaL_checknumber = this.cwrap('luaL_checknumber', 'number', ['number', 'number']) this.luaL_optnumber = this.cwrap('luaL_optnumber', 'number', ['number', 'number', 'number']) this.luaL_checkinteger = this.cwrap('luaL_checkinteger', 'number', ['number', 'number']) - this.luaL_optinteger = this.cwrap('luaL_optinteger', 'number', [ - 'number', - 'number', - 'number', - ]) + this.luaL_optinteger = this.cwrap('luaL_optinteger', 'number', ['number', 'number', 'number']) this.luaL_checkstack = this.cwrap('luaL_checkstack', null, ['number', 'number', 'string']) this.luaL_checktype = this.cwrap('luaL_checktype', null, ['number', 'number', 'number']) this.luaL_checkany = this.cwrap('luaL_checkany', null, ['number', 'number']) this.luaL_newmetatable = this.cwrap('luaL_newmetatable', 'number', ['number', 'string']) this.luaL_setmetatable = this.cwrap('luaL_setmetatable', null, ['number', 'string']) this.luaL_testudata = this.cwrap('luaL_testudata', 'number', ['number', 'number', 'string']) - this.luaL_checkudata = this.cwrap('luaL_checkudata', 'number', [ - 'number', - 'number', - 'string', - ]) + this.luaL_checkudata = this.cwrap('luaL_checkudata', 'number', ['number', 'number', 'string']) this.luaL_where = this.cwrap('luaL_where', null, ['number', 'number']) - this.luaL_fileresult = this.cwrap('luaL_fileresult', 'number', [ - 'number', - 'number', - 'string', - ]) + this.luaL_fileresult = this.cwrap('luaL_fileresult', 'number', ['number', 'number', 'string']) this.luaL_execresult = this.cwrap('luaL_execresult', 'number', ['number', 'number']) this.luaL_ref = this.cwrap('luaL_ref', 'number', ['number', 'number']) this.luaL_unref = this.cwrap('luaL_unref', null, ['number', 'number', 'number']) this.luaL_loadfilex = this.cwrap('luaL_loadfilex', 'number', ['number', 'string', 'string']) - this.luaL_loadbufferx = this.cwrap('luaL_loadbufferx', 'number', [ - 'number', - 'string|number', - 'number', - 'string|number', - 'string', - ]) + this.luaL_loadbufferx = this.cwrap('luaL_loadbufferx', 'number', ['number', 'string|number', 'number', 'string|number', 'string']) this.luaL_loadstring = this.cwrap('luaL_loadstring', 'number', ['number', 'string']) this.luaL_newstate = this.cwrap('luaL_newstate', 'number', []) this.luaL_len = this.cwrap('luaL_len', 'number', ['number', 'number']) - this.luaL_addgsub = this.cwrap('luaL_addgsub', null, [ - 'number', - 'string', - 'string', - 'string', - ]) + this.luaL_addgsub = this.cwrap('luaL_addgsub', null, ['number', 'string', 'string', 'string']) this.luaL_gsub = this.cwrap('luaL_gsub', 'string', ['number', 'string', 'string', 'string']) this.luaL_setfuncs = this.cwrap('luaL_setfuncs', null, ['number', 'number', 'number']) - this.luaL_getsubtable = this.cwrap('luaL_getsubtable', 'number', [ - 'number', - 'number', - 'string', - ]) - this.luaL_traceback = this.cwrap('luaL_traceback', null, [ - 'number', - 'number', - 'string', - 'number', - ]) - this.luaL_requiref = this.cwrap('luaL_requiref', null, [ - 'number', - 'string', - 'number', - 'number', - ]) - this.luaL_openselectedlibs = this.cwrap('luaL_openselectedlibs', null, [ - 'number', - 'number', - 'number', - ]) + this.luaL_getsubtable = this.cwrap('luaL_getsubtable', 'number', ['number', 'number', 'string']) + this.luaL_traceback = this.cwrap('luaL_traceback', null, ['number', 'number', 'string', 'number']) + this.luaL_requiref = this.cwrap('luaL_requiref', null, ['number', 'string', 'number', 'number']) + this.luaL_openselectedlibs = this.cwrap('luaL_openselectedlibs', null, ['number', 'number', 'number']) this.luaL_buffinit = this.cwrap('luaL_buffinit', null, ['number', 'number']) this.luaL_prepbuffsize = this.cwrap('luaL_prepbuffsize', 'string', ['number', 'number']) this.luaL_addlstring = this.cwrap('luaL_addlstring', null, ['number', 'string', 'number']) @@ -486,16 +363,12 @@ export default class LuaModule { this.luaL_addvalue = this.cwrap('luaL_addvalue', null, ['number']) this.luaL_pushresult = this.cwrap('luaL_pushresult', null, ['number']) this.luaL_pushresultsize = this.cwrap('luaL_pushresultsize', null, ['number', 'number']) - this.luaL_buffinitsize = this.cwrap('luaL_buffinitsize', 'string', [ - 'number', - 'number', - 'number', - ]) + this.luaL_buffinitsize = this.cwrap('luaL_buffinitsize', 'string', ['number', 'number', 'number']) this.lua_newstate = this.cwrap('lua_newstate', 'number', ['number', 'number', 'number']) this.lua_close = this.cwrap('lua_close', null, ['number']) this.lua_newthread = this.cwrap('lua_newthread', 'number', ['number']) this.lua_closethread = this.cwrap('lua_closethread', 'number', ['number', 'number']) - this.lua_resetthread = L => this.lua_closethread(L, null) + this.lua_resetthread = (L) => this.lua_closethread(L, null) this.lua_atpanic = this.cwrap('lua_atpanic', 'number', ['number', 'number']) this.lua_version = this.cwrap('lua_version', 'number', ['number']) this.lua_absindex = this.cwrap('lua_absindex', 'number', ['number', 'number']) @@ -524,20 +397,11 @@ export default class LuaModule { this.lua_topointer = this.cwrap('lua_topointer', 'number', ['number', 'number']) this.lua_arith = this.cwrap('lua_arith', null, ['number', 'number']) this.lua_rawequal = this.cwrap('lua_rawequal', 'number', ['number', 'number', 'number']) - this.lua_compare = this.cwrap('lua_compare', 'number', [ - 'number', - 'number', - 'number', - 'number', - ]) + this.lua_compare = this.cwrap('lua_compare', 'number', ['number', 'number', 'number', 'number']) this.lua_pushnil = this.cwrap('lua_pushnil', null, ['number']) this.lua_pushnumber = this.cwrap('lua_pushnumber', null, ['number', 'number']) this.lua_pushinteger = this.cwrap('lua_pushinteger', null, ['number', 'number']) - this.lua_pushlstring = this.cwrap('lua_pushlstring', 'string', [ - 'number', - 'string|number', - 'number', - ]) + this.lua_pushlstring = this.cwrap('lua_pushlstring', 'string', ['number', 'string|number', 'number']) this.lua_pushstring = this.cwrap('lua_pushstring', 'string', ['number', 'string|number']) this.lua_pushcclosure = this.cwrap('lua_pushcclosure', null, ['number', 'number', 'number']) this.lua_pushboolean = this.cwrap('lua_pushboolean', null, ['number', 'number']) @@ -551,17 +415,9 @@ export default class LuaModule { this.lua_rawgeti = this.cwrap('lua_rawgeti', 'number', ['number', 'number', 'number']) this.lua_rawgetp = this.cwrap('lua_rawgetp', 'number', ['number', 'number', 'number']) this.lua_createtable = this.cwrap('lua_createtable', null, ['number', 'number', 'number']) - this.lua_newuserdatauv = this.cwrap('lua_newuserdatauv', 'number', [ - 'number', - 'number', - 'number', - ]) + this.lua_newuserdatauv = this.cwrap('lua_newuserdatauv', 'number', ['number', 'number', 'number']) this.lua_getmetatable = this.cwrap('lua_getmetatable', 'number', ['number', 'number']) - this.lua_getiuservalue = this.cwrap('lua_getiuservalue', 'number', [ - 'number', - 'number', - 'number', - ]) + this.lua_getiuservalue = this.cwrap('lua_getiuservalue', 'number', ['number', 'number', 'number']) this.lua_setglobal = this.cwrap('lua_setglobal', null, ['number', 'string']) this.lua_settable = this.cwrap('lua_settable', null, ['number', 'number']) this.lua_setfield = this.cwrap('lua_setfield', null, ['number', 'number', 'string']) @@ -570,46 +426,13 @@ export default class LuaModule { this.lua_rawseti = this.cwrap('lua_rawseti', null, ['number', 'number', 'number']) this.lua_rawsetp = this.cwrap('lua_rawsetp', null, ['number', 'number', 'number']) this.lua_setmetatable = this.cwrap('lua_setmetatable', 'number', ['number', 'number']) - this.lua_setiuservalue = this.cwrap('lua_setiuservalue', 'number', [ - 'number', - 'number', - 'number', - ]) - this.lua_callk = this.cwrap('lua_callk', null, [ - 'number', - 'number', - 'number', - 'number', - 'number', - ]) - this.lua_pcallk = this.cwrap('lua_pcallk', 'number', [ - 'number', - 'number', - 'number', - 'number', - 'number', - 'number', - ]) - this.lua_load = this.cwrap('lua_load', 'number', [ - 'number', - 'number', - 'number', - 'string', - 'string', - ]) + this.lua_setiuservalue = this.cwrap('lua_setiuservalue', 'number', ['number', 'number', 'number']) + this.lua_callk = this.cwrap('lua_callk', null, ['number', 'number', 'number', 'number', 'number']) + this.lua_pcallk = this.cwrap('lua_pcallk', 'number', ['number', 'number', 'number', 'number', 'number', 'number']) + this.lua_load = this.cwrap('lua_load', 'number', ['number', 'number', 'number', 'string', 'string']) this.lua_dump = this.cwrap('lua_dump', 'number', ['number', 'number', 'number', 'number']) - this.lua_yieldk = this.cwrap('lua_yieldk', 'number', [ - 'number', - 'number', - 'number', - 'number', - ]) - this.lua_resume = this.cwrap('lua_resume', 'number', [ - 'number', - 'number', - 'number', - 'number', - ]) + this.lua_yieldk = this.cwrap('lua_yieldk', 'number', ['number', 'number', 'number', 'number']) + this.lua_resume = this.cwrap('lua_resume', 'number', ['number', 'number', 'number', 'number']) this.lua_status = this.cwrap('lua_status', 'number', ['number']) this.lua_isyieldable = this.cwrap('lua_isyieldable', 'number', ['number']) this.lua_setwarnf = this.cwrap('lua_setwarnf', null, ['number', 'number', 'number']) @@ -630,13 +453,7 @@ export default class LuaModule { this.lua_getupvalue = this.cwrap('lua_getupvalue', 'string', ['number', 'number', 'number']) this.lua_setupvalue = this.cwrap('lua_setupvalue', 'string', ['number', 'number', 'number']) this.lua_upvalueid = this.cwrap('lua_upvalueid', 'number', ['number', 'number', 'number']) - this.lua_upvaluejoin = this.cwrap('lua_upvaluejoin', null, [ - 'number', - 'number', - 'number', - 'number', - 'number', - ]) + this.lua_upvaluejoin = this.cwrap('lua_upvaluejoin', null, ['number', 'number', 'number', 'number', 'number']) this.lua_sethook = this.cwrap('lua_sethook', null, ['number', 'number', 'number', 'number']) this.lua_gethook = this.cwrap('lua_gethook', 'number', ['number']) this.lua_gethookmask = this.cwrap('lua_gethookmask', 'number', ['number']) @@ -653,7 +470,7 @@ export default class LuaModule { this.luaopen_math = this.cwrap('luaopen_math', 'number', ['number']) this.luaopen_debug = this.cwrap('luaopen_debug', 'number', ['number']) this.luaopen_package = this.cwrap('luaopen_package', 'number', ['number']) - this.luaL_openlibs = L => this.luaL_openselectedlibs(L, -1, 0) + this.luaL_openlibs = (L) => this.luaL_openselectedlibs(L, -1, 0) } public lua_remove(luaState: LuaState, index: number): void { @@ -739,15 +556,10 @@ export default class LuaModule { argTypes: Array, ): (...args: any[]) => any { // optimization for common case - const hasStringOrNumber = argTypes.some(argType => argType === 'string|number') + const hasStringOrNumber = argTypes.some((argType) => argType === 'string|number') if (!hasStringOrNumber) { return (...args: any[]) => - this._emscripten.ccall( - name, - returnType, - argTypes as Emscripten.JSType[], - args as Emscripten.TypeCompatibleWithC[], - ) + this._emscripten.ccall(name, returnType, argTypes as Emscripten.JSType[], args as Emscripten.TypeCompatibleWithC[]) } return (...args: any[]) => { @@ -759,9 +571,7 @@ export default class LuaModule { } else { // because it will be freed later, this can only be used on functions that lua internally copies the string if (args[i]?.length > 1024) { - const bufferPointer = this._emscripten.stringToNewUTF8( - args[i] as string, - ) + const bufferPointer = this._emscripten.stringToNewUTF8(args[i] as string) args[i] = bufferPointer pointersToBeFreed.push(bufferPointer) return 'number' @@ -774,12 +584,7 @@ export default class LuaModule { }) try { - return this._emscripten.ccall( - name, - returnType, - resolvedArgTypes, - args as Emscripten.TypeCompatibleWithC[], - ) + return this._emscripten.ccall(name, returnType, resolvedArgTypes, args as Emscripten.TypeCompatibleWithC[]) } finally { for (const pointer of pointersToBeFreed) { this._emscripten._free(pointer) @@ -789,9 +594,7 @@ export default class LuaModule { } } -function createOutputWriter( - writer?: (content: string) => void, -): ((charCode: number | null) => void) | null { +function createOutputWriter(writer?: (content: string) => void): ((charCode: number | null) => void) | null { if (!writer) { return null } diff --git a/test/browser.test.js b/test/browser.test.js index da0f295..1328803 100644 --- a/test/browser.test.js +++ b/test/browser.test.js @@ -82,8 +82,8 @@ describe('Browser environment', () => { await page.goto(`http://127.0.0.1:${port}/`) await page.waitForFunction(() => window.__ready === true, null, { timeout: 15_000 }) - const result = await page.evaluate(async (code) => { - return await window.__runTest(code) + const result = await page.evaluate(async (c) => { + return await window.__runTest(c) }, code) if (errors.length > 0) { diff --git a/test/nodefs.test.js b/test/nodefs.test.js index 166530f..27f5d9d 100644 --- a/test/nodefs.test.js +++ b/test/nodefs.test.js @@ -1,4 +1,4 @@ -import { readFileSync, writeFileSync, mkdirSync, rmSync, existsSync, symlinkSync, readdirSync } from 'node:fs' +import { readFileSync, writeFileSync, mkdirSync, rmSync, existsSync } from 'node:fs' import { join } from 'node:path' import { tmpdir } from 'node:os' import { expect } from 'chai' From c66b3e32e48234b04686a794ff56054b82803ce2 Mon Sep 17 00:00:00 2001 From: Gabriel Francisco Date: Tue, 24 Mar 2026 22:02:15 -0300 Subject: [PATCH 36/83] ci: install Playwright browsers before running tests The browser tests require Playwright's Chromium binary which isn't available in the CI runner by default. Co-Authored-By: Claude Opus 4.6 (1M context) --- .github/workflows/test.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 54fedfb..06a732e 100755 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -27,5 +27,6 @@ jobs: - run: npm run lint:nofix - run: npm run build:wasm - run: npm run build + - run: npx playwright install --with-deps chromium - run: npm test - run: npm run luatests From 335320efc0dd18a9876978cb399bab7519430a32 Mon Sep 17 00:00:00 2001 From: Gabriel Francisco Date: Sat, 25 Apr 2026 13:14:11 -0300 Subject: [PATCH 37/83] fix: keep new threads off of stack --- src/engine.ts | 12 ++++++------ test/engine.test.js | 16 ++++++++++++++++ 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/src/engine.ts b/src/engine.ts index 440e91d..bed0adf 100755 --- a/src/engine.ts +++ b/src/engine.ts @@ -1,4 +1,4 @@ -import { CreateEngineOptions } from './types' +import { CreateEngineOptions, LUA_REGISTRYINDEX } from './types' import Global from './global' import type LuaModule from './module' import Thread from './thread' @@ -62,7 +62,7 @@ export default class LuaEngine { * @returns A Promise that resolves to the result returned by the Lua script execution. */ public doString(script: string): Promise { - return this.callByteCode((thread) => thread.loadString(script)) + return this.callByteCode(thread => thread.loadString(script)) } /** @@ -71,7 +71,7 @@ export default class LuaEngine { * @returns - A Promise that resolves to the result returned by the Lua script execution. */ public doFile(filename: string): Promise { - return this.callByteCode((thread) => thread.loadFile(filename)) + return this.callByteCode(thread => thread.loadFile(filename)) } /** @@ -99,7 +99,8 @@ export default class LuaEngine { // WARNING: It will not wait for open handles and can potentially cause bugs if JS code tries to reference Lua after executed private async callByteCode(loader: (thread: Thread) => void): Promise { const thread = this.global.newThread() - const threadIndex = this.global.getTop() + // Move the thread off the global stack and into the registry as a GC anchor so it doesn't pile threads up into the stack + const ref = this.module.luaL_ref(this.global.address, LUA_REGISTRYINDEX) try { loader(thread) const result = await thread.run(0) @@ -111,8 +112,7 @@ export default class LuaEngine { } return undefined } finally { - // Pop the read on success or failure - this.global.remove(threadIndex) + this.module.luaL_unref(this.global.address, LUA_REGISTRYINDEX, ref) } } } diff --git a/test/engine.test.js b/test/engine.test.js index 05fbcfb..1bd7789 100644 --- a/test/engine.test.js +++ b/test/engine.test.js @@ -834,4 +834,20 @@ describe('State', () => { expect(result).to.equal(a + b) } }) + + it('many concurrent doString calls should succeed', async function () { + this.timeout(15000) + const state = await getState() + const length = 55 + + const promises = [] + for (let i = 0; i < length; i++) { + promises.push(state.doString(`return ${i}`)) + } + const results = await Promise.all(promises) + + for (let i = 0; i < length; i++) { + expect(results[i]).to.equal(i) + } + }) }) From 5c5dee5bb498372a0d8d1e43600607fe570cd647 Mon Sep 17 00:00:00 2001 From: Gabriel Francisco Date: Sat, 25 Apr 2026 14:30:09 -0300 Subject: [PATCH 38/83] cleanup --- package-lock.json | 539 +++++++++++++++----------------- package.json | 14 +- src/engine.ts | 4 +- src/thread.ts | 3 +- src/type-extensions/error.ts | 2 +- src/type-extensions/function.ts | 2 - test/browser.test.js | 10 +- test/engine.test.js | 26 +- 8 files changed, 293 insertions(+), 307 deletions(-) diff --git a/package-lock.json b/package-lock.json index 1c200d0..6c89b92 100644 --- a/package-lock.json +++ b/package-lock.json @@ -15,46 +15,23 @@ "wasmoon": "bin/wasmoon" }, "devDependencies": { - "@types/node": "25.5.0", + "@types/node": "*", "chai": "6.2.2", "chai-as-promised": "8.0.2", "fengari": "0.1.5", "mocha": "11.7.5", - "oxfmt": "0.42.0", - "oxlint": "1.57.0", - "playwright": "1.58.2", - "rolldown": "1.0.0-rc.11", + "oxfmt": "0.46.0", + "oxlint": "1.61.0", + "playwright": "1.59.1", + "rolldown": "1.0.0-rc.17", "tslib": "2.8.1", - "typescript": "6.0.2" - } - }, - "node_modules/@emnapi/core": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.9.1.tgz", - "integrity": "sha512-mukuNALVsoix/w1BJwFzwXBN/dHeejQtuVzcDsfOEsdpCumXb/E9j8w11h5S54tT1xhifGfbbSm/ICrObRb3KA==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@emnapi/wasi-threads": "1.2.0", - "tslib": "^2.4.0" - } - }, - "node_modules/@emnapi/runtime": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.9.1.tgz", - "integrity": "sha512-VYi5+ZVLhpgK4hQ0TAjiQiZ6ol0oe4mBx7mVv7IflsiEp0OWoVsp/+f9Vc1hOhE0TtkORVrI1GvzyreqpgWtkA==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "tslib": "^2.4.0" + "typescript": "6.0.3" } }, "node_modules/@emnapi/wasi-threads": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.0.tgz", - "integrity": "sha512-N10dEJNSsUx41Z6pZsXU8FjPjpBEplgH24sfkmITrBED1/U2Esum9F3lfLrMjKHHjmi557zQn7kR9R+XWXu5Rg==", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.1.tgz", + "integrity": "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==", "dev": true, "license": "MIT", "optional": true, @@ -81,26 +58,28 @@ } }, "node_modules/@napi-rs/wasm-runtime": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.1.tgz", - "integrity": "sha512-p64ah1M1ld8xjWv3qbvFwHiFVWrq1yFvV4f7w+mzaqiR4IlSgkqhcRdHwsGgomwzBH51sRY4NEowLxnaBjcW/A==", + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.4.tgz", + "integrity": "sha512-3NQNNgA1YSlJb/kMH1ildASP9HW7/7kYnRI2szWJaofaS1hWmbGI4H+d3+22aGzXXN9IJ+n+GiFVcGipJP18ow==", "dev": true, "license": "MIT", "optional": true, "dependencies": { - "@emnapi/core": "^1.7.1", - "@emnapi/runtime": "^1.7.1", "@tybys/wasm-util": "^0.10.1" }, "funding": { "type": "github", "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1", + "@emnapi/runtime": "^1.7.1" } }, "node_modules/@oxc-project/types": { - "version": "0.122.0", - "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.122.0.tgz", - "integrity": "sha512-oLAl5kBpV4w69UtFZ9xqcmTi+GENWOcPF7FCrczTiBbmC0ibXxCwyvZGbO39rCVEuLGAZM84DH0pUIyyv/YJzA==", + "version": "0.127.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.127.0.tgz", + "integrity": "sha512-aIYXQBo4lCbO4z0R3FHeucQHpF46l2LbMdxRvqvuRuW2OxdnSkcng5B8+K12spgLDj93rtN3+J2Vac/TIO+ciQ==", "dev": true, "license": "MIT", "funding": { @@ -108,9 +87,9 @@ } }, "node_modules/@oxfmt/binding-android-arm-eabi": { - "version": "0.42.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm-eabi/-/binding-android-arm-eabi-0.42.0.tgz", - "integrity": "sha512-dsqPTYsozeokRjlrt/b4E7Pj0z3eS3Eg74TWQuuKbjY4VttBmA88rB7d50Xrd+TZ986qdXCNeZRPEzZHAe+jow==", + "version": "0.46.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm-eabi/-/binding-android-arm-eabi-0.46.0.tgz", + "integrity": "sha512-b1doV4WRcJU+BESSlCvCjV+5CEr/T6h0frArAdV26Nir+gGNFNaylvDiiMPfF1pxeV0txZEs38ojzJaxBYg+ng==", "cpu": [ "arm" ], @@ -125,9 +104,9 @@ } }, "node_modules/@oxfmt/binding-android-arm64": { - "version": "0.42.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm64/-/binding-android-arm64-0.42.0.tgz", - "integrity": "sha512-t+aAjHxcr5eOBphFHdg1ouQU9qmZZoRxnX7UOJSaTwSoKsb6TYezNKO0YbWytGXCECObRqNcUxPoPr0KaraAIg==", + "version": "0.46.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm64/-/binding-android-arm64-0.46.0.tgz", + "integrity": "sha512-v6+HhjsoV3GO0u2u9jLSAZrvWfTraDxKofUIQ7/ktS7tzS+epVsxdHmeM+XxuNcAY/nWxxU1Sg4JcGTNRXraBA==", "cpu": [ "arm64" ], @@ -142,9 +121,9 @@ } }, "node_modules/@oxfmt/binding-darwin-arm64": { - "version": "0.42.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-arm64/-/binding-darwin-arm64-0.42.0.tgz", - "integrity": "sha512-ulpSEYMKg61C5bRMZinFHrKJYRoKGVbvMEXA5zM1puX3O9T6Q4XXDbft20yrDijpYWeuG59z3Nabt+npeTsM1A==", + "version": "0.46.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-arm64/-/binding-darwin-arm64-0.46.0.tgz", + "integrity": "sha512-3eeooJGrqGIlI5MyryDZsAcKXSmKIgAD4yYtfRrRJzXZ0UTFZtiSveIur56YPrGMYZwT4XyVhHsMqrNwr1XeFA==", "cpu": [ "arm64" ], @@ -159,9 +138,9 @@ } }, "node_modules/@oxfmt/binding-darwin-x64": { - "version": "0.42.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-x64/-/binding-darwin-x64-0.42.0.tgz", - "integrity": "sha512-ttxLKhQYPdFiM8I/Ri37cvqChE4Xa562nNOsZFcv1CKTVLeEozXjKuYClNvxkXmNlcF55nzM80P+CQkdFBu+uQ==", + "version": "0.46.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-x64/-/binding-darwin-x64-0.46.0.tgz", + "integrity": "sha512-QG8BDM0CXWbu84k2SKmCqfEddPQPFiBicwtYnLqHRWZZl57HbtOLRMac/KTq2NO4AEc4ICCBpFxJIV9zcqYfkQ==", "cpu": [ "x64" ], @@ -176,9 +155,9 @@ } }, "node_modules/@oxfmt/binding-freebsd-x64": { - "version": "0.42.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-freebsd-x64/-/binding-freebsd-x64-0.42.0.tgz", - "integrity": "sha512-Og7QS3yI3tdIKYZ58SXik0rADxIk2jmd+/YvuHRyKULWpG4V2fR5V4hvKm624Mc0cQET35waPXiCQWvjQEjwYQ==", + "version": "0.46.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-freebsd-x64/-/binding-freebsd-x64-0.46.0.tgz", + "integrity": "sha512-9DdCqS/n2ncu/Chazvt3cpgAjAmIGQDz7hFKSrNItMApyV/Ja9mz3hD4JakIE3nS8PW9smEbPWnb389QLBY4nw==", "cpu": [ "x64" ], @@ -193,9 +172,9 @@ } }, "node_modules/@oxfmt/binding-linux-arm-gnueabihf": { - "version": "0.42.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-0.42.0.tgz", - "integrity": "sha512-jwLOw/3CW4H6Vxcry4/buQHk7zm9Ne2YsidzTL1kpiMe4qqrRCwev3dkyWe2YkFmP+iZCQ7zku4KwjcLRoh8ew==", + "version": "0.46.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-0.46.0.tgz", + "integrity": "sha512-Dgs7VeE2jT0LHMhw6tPEt0xQYe54kBqHEovmWsv4FVQlegCOvlIJNx0S8n4vj8WUtpT+Z6BD2HhKJPLglLxvZg==", "cpu": [ "arm" ], @@ -210,9 +189,9 @@ } }, "node_modules/@oxfmt/binding-linux-arm-musleabihf": { - "version": "0.42.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-0.42.0.tgz", - "integrity": "sha512-XwXu2vkMtiq2h7tfvN+WA/9/5/1IoGAVCFPiiQUvcAuG3efR97KNcRGM8BetmbYouFotQ2bDal3yyjUx6IPsTg==", + "version": "0.46.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-0.46.0.tgz", + "integrity": "sha512-Zxn3adhTH13JKnU4xXJj8FeEfF680XjXh3gSShKl57HCMBRde2tUJTgogV/1MSHA80PJEVrDa7r66TLVq3Ia7Q==", "cpu": [ "arm" ], @@ -227,9 +206,9 @@ } }, "node_modules/@oxfmt/binding-linux-arm64-gnu": { - "version": "0.42.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-0.42.0.tgz", - "integrity": "sha512-ea7s/XUJoT7ENAtUQDudFe3nkSM3e3Qpz4nJFRdzO2wbgXEcjnchKLEsV3+t4ev3r8nWxIYr9NRjPWtnyIFJVA==", + "version": "0.46.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-0.46.0.tgz", + "integrity": "sha512-+TWipjrgVM8D7aIdDD0tlr3teLTTvQTn7QTE5BpT10H1Fj82gfdn9X6nn2sDgx/MepuSCfSnzFNJq2paLL0OiA==", "cpu": [ "arm64" ], @@ -244,9 +223,9 @@ } }, "node_modules/@oxfmt/binding-linux-arm64-musl": { - "version": "0.42.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-musl/-/binding-linux-arm64-musl-0.42.0.tgz", - "integrity": "sha512-+JA0YMlSdDqmacygGi2REp57c3fN+tzARD8nwsukx9pkCHK+6DkbAA9ojS4lNKsiBjIW8WWa0pBrBWhdZEqfuw==", + "version": "0.46.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-musl/-/binding-linux-arm64-musl-0.46.0.tgz", + "integrity": "sha512-aAUPBWJ1lGwwnxZUEDLJ94+Iy6MuwJwPxUgO4sCA5mEEyDk7b+cDQ+JpX1VR150Zoyd+D49gsrUzpUK5h587Eg==", "cpu": [ "arm64" ], @@ -261,9 +240,9 @@ } }, "node_modules/@oxfmt/binding-linux-ppc64-gnu": { - "version": "0.42.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-0.42.0.tgz", - "integrity": "sha512-VfnET0j4Y5mdfCzh5gBt0NK28lgn5DKx+8WgSMLYYeSooHhohdbzwAStLki9pNuGy51y4I7IoW8bqwAaCMiJQg==", + "version": "0.46.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-0.46.0.tgz", + "integrity": "sha512-ufBCJukyFX/UDrokP/r6BGDoTInnsDs7bxyzKAgMiZlt2Qu8GPJSJ6Zm6whIiJzKk0naxA8ilwmbO1LMw6Htxw==", "cpu": [ "ppc64" ], @@ -278,9 +257,9 @@ } }, "node_modules/@oxfmt/binding-linux-riscv64-gnu": { - "version": "0.42.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-0.42.0.tgz", - "integrity": "sha512-gVlCbmBkB0fxBWbhBj9rcxezPydsQHf4MFKeHoTSPicOQ+8oGeTQgQ8EeesSybWeiFPVRx3bgdt4IJnH6nOjAA==", + "version": "0.46.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-0.46.0.tgz", + "integrity": "sha512-eqtlC2YmPqjun76R1gVfGLuKWx7NuEnLEAudZ7n6ipSKbCZTqIKSs1b5Y8K/JHZsRpLkeSmAAjig5HOIg8fQzQ==", "cpu": [ "riscv64" ], @@ -295,9 +274,9 @@ } }, "node_modules/@oxfmt/binding-linux-riscv64-musl": { - "version": "0.42.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-0.42.0.tgz", - "integrity": "sha512-zN5OfstL0avgt/IgvRu0zjQzVh/EPkcLzs33E9LMAzpqlLWiPWeMDZyMGFlSRGOdDjuNmlZBCgj0pFnK5u32TQ==", + "version": "0.46.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-0.46.0.tgz", + "integrity": "sha512-yccVOO2nMXkQLGgy0He3EQEwKD7NF0zEk+/OWmroznkqXyJdN6bfK0LtNnr6/14Bh3FjpYq7bP33l/VloCnxpA==", "cpu": [ "riscv64" ], @@ -312,9 +291,9 @@ } }, "node_modules/@oxfmt/binding-linux-s390x-gnu": { - "version": "0.42.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-0.42.0.tgz", - "integrity": "sha512-9X6+H2L0qMc2sCAgO9HS03bkGLMKvOFjmEdchaFlany3vNZOjnVui//D8k/xZAtQv2vaCs1reD5KAgPoIU4msA==", + "version": "0.46.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-0.46.0.tgz", + "integrity": "sha512-aAf7fG23OQCey6VRPj9IeCraoYtpgtx0ZyJ1CXkPyT1wjzBE7c3xtuxHe/AdHaJfVVb/SXpSk8Gl1LzyQupSqw==", "cpu": [ "s390x" ], @@ -329,9 +308,9 @@ } }, "node_modules/@oxfmt/binding-linux-x64-gnu": { - "version": "0.42.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-gnu/-/binding-linux-x64-gnu-0.42.0.tgz", - "integrity": "sha512-BajxJ6KQvMMdpXGPWhBGyjb2Jvx4uec0w+wi6TJZ6Tv7+MzPwe0pO8g5h1U0jyFgoaF7mDl6yKPW3ykWcbUJRw==", + "version": "0.46.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-gnu/-/binding-linux-x64-gnu-0.46.0.tgz", + "integrity": "sha512-q0JPsTMyJNjYrBvYFDz4WbVsafNZaPCZv4RnFypRotLqpKROtBZcEaXQW4eb9YmvLU3NckVemLJnzkSZSdmOxw==", "cpu": [ "x64" ], @@ -346,9 +325,9 @@ } }, "node_modules/@oxfmt/binding-linux-x64-musl": { - "version": "0.42.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-musl/-/binding-linux-x64-musl-0.42.0.tgz", - "integrity": "sha512-0wV284I6vc5f0AqAhgAbHU2935B4bVpncPoe5n/WzVZY/KnHgqxC8iSFGeSyLWEgstFboIcWkOPck7tqbdHkzA==", + "version": "0.46.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-musl/-/binding-linux-x64-musl-0.46.0.tgz", + "integrity": "sha512-7LsLY9Cw57GPkhSR+duI3mt9baRczK/DtHYSldQ4BEU92da9igBQNl4z7Vq5U9NNPsh1FmpKvv1q9WDtiUQR1A==", "cpu": [ "x64" ], @@ -363,9 +342,9 @@ } }, "node_modules/@oxfmt/binding-openharmony-arm64": { - "version": "0.42.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-openharmony-arm64/-/binding-openharmony-arm64-0.42.0.tgz", - "integrity": "sha512-p4BG6HpGnhfgHk1rzZfyR6zcWkE7iLrWxyehHfXUy4Qa5j3e0roglFOdP/Nj5cJJ58MA3isQ5dlfkW2nNEpolw==", + "version": "0.46.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-openharmony-arm64/-/binding-openharmony-arm64-0.46.0.tgz", + "integrity": "sha512-lHiBOz8Duaku7JtRNLlps3j++eOaICPZSd8FCVmTDM4DFOPT71Bjn7g6iar1z7StXlKRweUKxWUs4sA+zWGDXg==", "cpu": [ "arm64" ], @@ -380,9 +359,9 @@ } }, "node_modules/@oxfmt/binding-win32-arm64-msvc": { - "version": "0.42.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-0.42.0.tgz", - "integrity": "sha512-mn//WV60A+IetORDxYieYGAoQso4KnVRRjORDewMcod4irlRe0OSC7YPhhwaexYNPQz/GCFk+v9iUcZ2W22yxQ==", + "version": "0.46.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-0.46.0.tgz", + "integrity": "sha512-/5ktYUliP89RhgC37DBH1x20U5zPSZMy3cMEcO0j3793rbHP9MWsknBwQB6eozRzWmYrh0IFM/p20EbPvDlYlg==", "cpu": [ "arm64" ], @@ -397,9 +376,9 @@ } }, "node_modules/@oxfmt/binding-win32-ia32-msvc": { - "version": "0.42.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-0.42.0.tgz", - "integrity": "sha512-3gWltUrvuz4LPJXWivoAxZ28Of2O4N7OGuM5/X3ubPXCEV8hmgECLZzjz7UYvSDUS3grfdccQwmjynm+51EFpw==", + "version": "0.46.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-0.46.0.tgz", + "integrity": "sha512-3WTnoiuIr8XvV0DIY7SN+1uJSwKf4sPpcbHfobcRT9JutGcLaef/miyBB87jxd3aqH+mS0+G5lsgHuXLUwjjpQ==", "cpu": [ "ia32" ], @@ -414,9 +393,9 @@ } }, "node_modules/@oxfmt/binding-win32-x64-msvc": { - "version": "0.42.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-x64-msvc/-/binding-win32-x64-msvc-0.42.0.tgz", - "integrity": "sha512-Wg4TMAfQRL9J9AZevJ/ZNy3uyyDztDYQtGr4P8UyyzIhLhFrdSmz1J/9JT+rv0fiCDLaFOBQnj3f3K3+a5PzDQ==", + "version": "0.46.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-x64-msvc/-/binding-win32-x64-msvc-0.46.0.tgz", + "integrity": "sha512-IXxiQpkYnOwNfP23vzwSfhdpxJzyiPTY7eTn6dn3DsriKddESzM8i6kfq9R7CD/PUJwCvQT22NgtygBeug3KoA==", "cpu": [ "x64" ], @@ -431,9 +410,9 @@ } }, "node_modules/@oxlint/binding-android-arm-eabi": { - "version": "1.57.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm-eabi/-/binding-android-arm-eabi-1.57.0.tgz", - "integrity": "sha512-C7EiyfAJG4B70496eV543nKiq5cH0o/xIh/ufbjQz3SIvHhlDDsyn+mRFh+aW8KskTyUpyH2LGWL8p2oN6bl1A==", + "version": "1.61.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm-eabi/-/binding-android-arm-eabi-1.61.0.tgz", + "integrity": "sha512-6eZBPgiigK5txqoVgRqxbaxiom4lM8AP8CyKPPvpzKnQ3iFRFOIDc+0AapF+qsUSwjOzr5SGk4SxQDpQhkSJMQ==", "cpu": [ "arm" ], @@ -448,9 +427,9 @@ } }, "node_modules/@oxlint/binding-android-arm64": { - "version": "1.57.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm64/-/binding-android-arm64-1.57.0.tgz", - "integrity": "sha512-9i80AresjZ/FZf5xK8tKFbhQnijD4s1eOZw6/FHUwD59HEZbVLRc2C88ADYJfLZrF5XofWDiRX/Ja9KefCLy7w==", + "version": "1.61.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm64/-/binding-android-arm64-1.61.0.tgz", + "integrity": "sha512-CkwLR69MUnyv5wjzebvbbtTSUwqLxM35CXE79bHqDIK+NtKmPEUpStTcLQRZMCo4MP0qRT6TXIQVpK0ZVScnMA==", "cpu": [ "arm64" ], @@ -465,9 +444,9 @@ } }, "node_modules/@oxlint/binding-darwin-arm64": { - "version": "1.57.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-arm64/-/binding-darwin-arm64-1.57.0.tgz", - "integrity": "sha512-0eUfhRz5L2yKa9I8k3qpyl37XK3oBS5BvrgdVIx599WZK63P8sMbg+0s4IuxmIiZuBK68Ek+Z+gcKgeYf0otsg==", + "version": "1.61.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-arm64/-/binding-darwin-arm64-1.61.0.tgz", + "integrity": "sha512-8JbefTkbmvqkqWjmQrHke+MdpgT2UghhD/ktM4FOQSpGeCgbMToJEKdl9zwhr/YWTl92i4QI1KiTwVExpcUN8A==", "cpu": [ "arm64" ], @@ -482,9 +461,9 @@ } }, "node_modules/@oxlint/binding-darwin-x64": { - "version": "1.57.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-x64/-/binding-darwin-x64-1.57.0.tgz", - "integrity": "sha512-UvrSuzBaYOue+QMAcuDITe0k/Vhj6KZGjfnI6x+NkxBTke/VoM7ZisaxgNY0LWuBkTnd1OmeQfEQdQ48fRjkQg==", + "version": "1.61.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-x64/-/binding-darwin-x64-1.61.0.tgz", + "integrity": "sha512-uWpoxDT47hTnDLcdEh5jVbso8rlTTu5o0zuqa9J8E0JAKmIWn7kGFEIB03Pycn2hd2vKxybPGLhjURy/9We5FQ==", "cpu": [ "x64" ], @@ -499,9 +478,9 @@ } }, "node_modules/@oxlint/binding-freebsd-x64": { - "version": "1.57.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-freebsd-x64/-/binding-freebsd-x64-1.57.0.tgz", - "integrity": "sha512-wtQq0dCoiw4bUwlsNVDJJ3pxJA218fOezpgtLKrbQqUtQJcM9yP8z+I9fu14aHg0uyAxIY+99toL6uBa2r7nxA==", + "version": "1.61.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-freebsd-x64/-/binding-freebsd-x64-1.61.0.tgz", + "integrity": "sha512-K/o4hEyW7flfMel0iBVznmMBt7VIMHGdjADocHKpK1DUF9erpWnJ+BSSWd2W0c8K3mPtpph+CuHzRU6CI3l9jQ==", "cpu": [ "x64" ], @@ -516,9 +495,9 @@ } }, "node_modules/@oxlint/binding-linux-arm-gnueabihf": { - "version": "1.57.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.57.0.tgz", - "integrity": "sha512-qxFWl2BBBFcT4djKa+OtMdnLgoHEJXpqjyGwz8OhW35ImoCwR5qtAGqApNYce5260FQqoAHW8S8eZTjiX67Tsg==", + "version": "1.61.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.61.0.tgz", + "integrity": "sha512-P6040ZkcyweJ0Po9yEFqJCdvZnf3VNCGs1SIHgXDf8AAQNC6ID/heXQs9iSgo2FH7gKaKq32VWc59XZwL34C5Q==", "cpu": [ "arm" ], @@ -533,9 +512,9 @@ } }, "node_modules/@oxlint/binding-linux-arm-musleabihf": { - "version": "1.57.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-1.57.0.tgz", - "integrity": "sha512-SQoIsBU7J0bDW15/f0/RvxHfY3Y0+eB/caKBQtNFbuerTiA6JCYx9P1MrrFTwY2dTm/lMgTSgskvCEYk2AtG/Q==", + "version": "1.61.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-1.61.0.tgz", + "integrity": "sha512-bwxrGCzTZkuB+THv2TQ1aTkVEfv5oz8sl+0XZZCpoYzErJD8OhPQOTA0ENPd1zJz8QsVdSzSrS2umKtPq4/JXg==", "cpu": [ "arm" ], @@ -550,9 +529,9 @@ } }, "node_modules/@oxlint/binding-linux-arm64-gnu": { - "version": "1.57.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.57.0.tgz", - "integrity": "sha512-jqxYd1W6WMeozsCmqe9Rzbu3SRrGTyGDAipRlRggetyYbUksJqJKvUNTQtZR/KFoJPb+grnSm5SHhdWrywv3RQ==", + "version": "1.61.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.61.0.tgz", + "integrity": "sha512-vkhb9/wKguMkLlrm3FoJW/Xmdv31GgYAE+x8lxxQ+7HeOxXUySI0q36a3NTVIuQUdLzxCI1zzMGsk1o37FOe3w==", "cpu": [ "arm64" ], @@ -567,9 +546,9 @@ } }, "node_modules/@oxlint/binding-linux-arm64-musl": { - "version": "1.57.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.57.0.tgz", - "integrity": "sha512-i66WyEPVEvq9bxRUCJ/MP5EBfnTDN3nhwEdFZFTO5MmLLvzngfWEG3NSdXQzTT3vk5B9i6C2XSIYBh+aG6uqyg==", + "version": "1.61.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.61.0.tgz", + "integrity": "sha512-bl1dQh8LnVqsj6oOQAcxwbuOmNJkwc4p6o//HTBZhNTzJy21TLDwAviMqUFNUxDHkPGpmdKTSN4tWTjLryP8xg==", "cpu": [ "arm64" ], @@ -584,9 +563,9 @@ } }, "node_modules/@oxlint/binding-linux-ppc64-gnu": { - "version": "1.57.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.57.0.tgz", - "integrity": "sha512-oMZDCwz4NobclZU3pH+V1/upVlJZiZvne4jQP+zhJwt+lmio4XXr4qG47CehvrW1Lx2YZiIHuxM2D4YpkG3KVA==", + "version": "1.61.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.61.0.tgz", + "integrity": "sha512-QoOX6KB2IiEpyOj/HKqaxi+NQHPnOgNgnr22n9N4ANJCzXkUlj1UmeAbFb4PpqdlHIzvGDM5xZ0OKtcLq9RhiQ==", "cpu": [ "ppc64" ], @@ -601,9 +580,9 @@ } }, "node_modules/@oxlint/binding-linux-riscv64-gnu": { - "version": "1.57.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-1.57.0.tgz", - "integrity": "sha512-uoBnjJ3MMEBbfnWC1jSFr7/nSCkcQYa72NYoNtLl1imshDnWSolYCjzb8LVCwYCCfLJXD+0gBLD7fyC14c0+0g==", + "version": "1.61.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-1.61.0.tgz", + "integrity": "sha512-1TGcTerjY6p152wCof3oKElccq3xHljS/Mucp04gV/4ATpP6nO7YNnp7opEg6SHkv2a57/b4b8Ndm9znJ1/qAw==", "cpu": [ "riscv64" ], @@ -618,9 +597,9 @@ } }, "node_modules/@oxlint/binding-linux-riscv64-musl": { - "version": "1.57.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-1.57.0.tgz", - "integrity": "sha512-BdrwD7haPZ8a9KrZhKJRSj6jwCor+Z8tHFZ3PT89Y3Jq5v3LfMfEePeAmD0LOTWpiTmzSzdmyw9ijneapiVHKQ==", + "version": "1.61.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-1.61.0.tgz", + "integrity": "sha512-65wXEmZIrX2ADwC8i/qFL4EWLSbeuBpAm3suuX1vu4IQkKd+wLT/HU/BOl84kp91u2SxPkPDyQgu4yrqp8vwVA==", "cpu": [ "riscv64" ], @@ -635,9 +614,9 @@ } }, "node_modules/@oxlint/binding-linux-s390x-gnu": { - "version": "1.57.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.57.0.tgz", - "integrity": "sha512-BNs+7ZNsRstVg2tpNxAXfMX/Iv5oZh204dVyb8Z37+/gCh+yZqNTlg6YwCLIMPSk5wLWIGOaQjT0GUOahKYImw==", + "version": "1.61.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.61.0.tgz", + "integrity": "sha512-TVvhgMvor7Qa6COeXxCJ7ENOM+lcAOGsQ0iUdPSCv2hxb9qSHLQ4XF1h50S6RE1gBOJ0WV3rNukg4JJJP1LWRA==", "cpu": [ "s390x" ], @@ -652,9 +631,9 @@ } }, "node_modules/@oxlint/binding-linux-x64-gnu": { - "version": "1.57.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.57.0.tgz", - "integrity": "sha512-AghS18w+XcENcAX0+BQGLiqjpqpaxKJa4cWWP0OWNLacs27vHBxu7TYkv9LUSGe5w8lOJHeMxcYfZNOAPqw2bg==", + "version": "1.61.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.61.0.tgz", + "integrity": "sha512-SjpS5uYuFoDnDdZPwZE59ndF95AsY47R5MliuneTWR1pDm2CxGJaYXbKULI71t5TVfLQUWmrHEGRL9xvuq6dnA==", "cpu": [ "x64" ], @@ -669,9 +648,9 @@ } }, "node_modules/@oxlint/binding-linux-x64-musl": { - "version": "1.57.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-musl/-/binding-linux-x64-musl-1.57.0.tgz", - "integrity": "sha512-E/FV3GB8phu/Rpkhz5T96hAiJlGzn91qX5yj5gU754P5cmVGXY1Jw/VSjDSlZBCY3VHjsVLdzgdkJaomEmcNOg==", + "version": "1.61.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-musl/-/binding-linux-x64-musl-1.61.0.tgz", + "integrity": "sha512-gGfAeGD4sNJGILZbc/yKcIimO9wQnPMoYp9swAaKeEtwsSQAbU+rsdQze5SBtIP6j0QDzeYd4XSSUCRCF+LIeQ==", "cpu": [ "x64" ], @@ -686,9 +665,9 @@ } }, "node_modules/@oxlint/binding-openharmony-arm64": { - "version": "1.57.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-openharmony-arm64/-/binding-openharmony-arm64-1.57.0.tgz", - "integrity": "sha512-xvZ2yZt0nUVfU14iuGv3V25jpr9pov5N0Wr28RXnHFxHCRxNDMtYPHV61gGLhN9IlXM96gI4pyYpLSJC5ClLCQ==", + "version": "1.61.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-openharmony-arm64/-/binding-openharmony-arm64-1.61.0.tgz", + "integrity": "sha512-OlVT0LrG/ct33EVtWRyR+B/othwmDWeRxfi13wUdPeb3lAT5TgTcFDcfLfarZtzB4W1nWF/zICMgYdkggX2WmQ==", "cpu": [ "arm64" ], @@ -703,9 +682,9 @@ } }, "node_modules/@oxlint/binding-win32-arm64-msvc": { - "version": "1.57.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.57.0.tgz", - "integrity": "sha512-Z4D8Pd0AyHBKeazhdIXeUUy5sIS3Mo0veOlzlDECg6PhRRKgEsBJCCV1n+keUZtQ04OP+i7+itS3kOykUyNhDg==", + "version": "1.61.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.61.0.tgz", + "integrity": "sha512-vI//NZPJk6DToiovPtaiwD4iQ7kO1r5ReWQD0sOOyKRtP3E2f6jxin4uvwi3OvDzHA2EFfd7DcZl5dtkQh7g1w==", "cpu": [ "arm64" ], @@ -720,9 +699,9 @@ } }, "node_modules/@oxlint/binding-win32-ia32-msvc": { - "version": "1.57.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-1.57.0.tgz", - "integrity": "sha512-StOZ9nFMVKvevicbQfql6Pouu9pgbeQnu60Fvhz2S6yfMaii+wnueLnqQ5I1JPgNF0Syew4voBlAaHD13wH6tw==", + "version": "1.61.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-1.61.0.tgz", + "integrity": "sha512-0ySj4/4zd2XjePs3XAQq7IigIstN4LPQZgCyigX5/ERMLjdWAJfnxcTsrtxZxuij8guJW8foXuHmhGxW0H4dDA==", "cpu": [ "ia32" ], @@ -737,9 +716,9 @@ } }, "node_modules/@oxlint/binding-win32-x64-msvc": { - "version": "1.57.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.57.0.tgz", - "integrity": "sha512-6PuxhYgth8TuW0+ABPOIkGdBYw+qYGxgIdXPHSVpiCDm+hqTTWCmC739St1Xni0DJBt8HnSHTG67i1y6gr8qrA==", + "version": "1.61.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.61.0.tgz", + "integrity": "sha512-0xgSiyeqDLDZxXoe9CVJrOx3TUVsfyoOY7cNi03JbItNcC9WCZqrSNdrAbHONxhSPaVh/lzfnDcON1RqSUMhHw==", "cpu": [ "x64" ], @@ -765,9 +744,9 @@ } }, "node_modules/@rolldown/binding-android-arm64": { - "version": "1.0.0-rc.11", - "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.0.0-rc.11.tgz", - "integrity": "sha512-SJ+/g+xNnOh6NqYxD0V3uVN4W3VfnrGsC9/hoglicgTNfABFG9JjISvkkU0dNY84MNHLWyOgxP9v9Y9pX4S7+A==", + "version": "1.0.0-rc.17", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.0.0-rc.17.tgz", + "integrity": "sha512-s70pVGhw4zqGeFnXWvAzJDlvxhlRollagdCCKRgOsgUOH3N1l0LIxf83AtGzmb5SiVM4Hjl5HyarMRfdfj3DaQ==", "cpu": [ "arm64" ], @@ -782,9 +761,9 @@ } }, "node_modules/@rolldown/binding-darwin-arm64": { - "version": "1.0.0-rc.11", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.0.0-rc.11.tgz", - "integrity": "sha512-7WQgR8SfOPwmDZGFkThUvsmd/nwAWv91oCO4I5LS7RKrssPZmOt7jONN0cW17ydGC1n/+puol1IpoieKqQidmg==", + "version": "1.0.0-rc.17", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.0.0-rc.17.tgz", + "integrity": "sha512-4ksWc9n0mhlZpZ9PMZgTGjeOPRu8MB1Z3Tz0Mo02eWfWCHMW1zN82Qz/pL/rC+yQa+8ZnutMF0JjJe7PjwasYw==", "cpu": [ "arm64" ], @@ -799,9 +778,9 @@ } }, "node_modules/@rolldown/binding-darwin-x64": { - "version": "1.0.0-rc.11", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.0.0-rc.11.tgz", - "integrity": "sha512-39Ks6UvIHq4rEogIfQBoBRusj0Q0nPVWIvqmwBLaT6aqQGIakHdESBVOPRRLacy4WwUPIx4ZKzfZ9PMW+IeyUQ==", + "version": "1.0.0-rc.17", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.0.0-rc.17.tgz", + "integrity": "sha512-SUSDOI6WwUVNcWxd02QEBjLdY1VPHvlEkw6T/8nYG322iYWCTxRb1vzk4E+mWWYehTp7ERibq54LSJGjmouOsw==", "cpu": [ "x64" ], @@ -816,9 +795,9 @@ } }, "node_modules/@rolldown/binding-freebsd-x64": { - "version": "1.0.0-rc.11", - "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.0.0-rc.11.tgz", - "integrity": "sha512-jfsm0ZHfhiqrvWjJAmzsqiIFPz5e7mAoCOPBNTcNgkiid/LaFKiq92+0ojH+nmJmKYkre4t71BWXUZDNp7vsag==", + "version": "1.0.0-rc.17", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.0.0-rc.17.tgz", + "integrity": "sha512-hwnz3nw9dbJ05EDO/PvcjaaewqqDy7Y1rn1UO81l8iIK1GjenME75dl16ajbvSSMfv66WXSRCYKIqfgq2KCfxw==", "cpu": [ "x64" ], @@ -833,9 +812,9 @@ } }, "node_modules/@rolldown/binding-linux-arm-gnueabihf": { - "version": "1.0.0-rc.11", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.0.0-rc.11.tgz", - "integrity": "sha512-zjQaUtSyq1nVe3nxmlSCuR96T1LPlpvmJ0SZy0WJFEsV4kFbXcq2u68L4E6O0XeFj4aex9bEauqjW8UQBeAvfQ==", + "version": "1.0.0-rc.17", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.0.0-rc.17.tgz", + "integrity": "sha512-IS+W7epTcwANmFSQFrS1SivEXHtl1JtuQA9wlxrZTcNi6mx+FDOYrakGevvvTwgj2JvWiK8B29/qD9BELZPyXQ==", "cpu": [ "arm" ], @@ -850,9 +829,9 @@ } }, "node_modules/@rolldown/binding-linux-arm64-gnu": { - "version": "1.0.0-rc.11", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.0.0-rc.11.tgz", - "integrity": "sha512-WMW1yE6IOnehTcFE9eipFkm3XN63zypWlrJQ2iF7NrQ9b2LDRjumFoOGJE8RJJTJCTBAdmLMnJ8uVitACUUo1Q==", + "version": "1.0.0-rc.17", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.0.0-rc.17.tgz", + "integrity": "sha512-e6usGaHKW5BMNZOymS1UcEYGowQMWcgZ71Z17Sl/h2+ZziNJ1a9n3Zvcz6LdRyIW5572wBCTH/Z+bKuZouGk9Q==", "cpu": [ "arm64" ], @@ -867,9 +846,9 @@ } }, "node_modules/@rolldown/binding-linux-arm64-musl": { - "version": "1.0.0-rc.11", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.0.0-rc.11.tgz", - "integrity": "sha512-jfndI9tsfm4APzjNt6QdBkYwre5lRPUgHeDHoI7ydKUuJvz3lZeCfMsI56BZj+7BYqiKsJm7cfd/6KYV7ubrBg==", + "version": "1.0.0-rc.17", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.0.0-rc.17.tgz", + "integrity": "sha512-b/CgbwAJpmrRLp02RPfhbudf5tZnN9nsPWK82znefso832etkem8H7FSZwxrOI9djcdTP7U6YfNhbRnh7djErg==", "cpu": [ "arm64" ], @@ -884,9 +863,9 @@ } }, "node_modules/@rolldown/binding-linux-ppc64-gnu": { - "version": "1.0.0-rc.11", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.0.0-rc.11.tgz", - "integrity": "sha512-ZlFgw46NOAGMgcdvdYwAGu2Q+SLFA9LzbJLW+iyMOJyhj5wk6P3KEE9Gct4xWwSzFoPI7JCdYmYMzVtlgQ+zfw==", + "version": "1.0.0-rc.17", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.0.0-rc.17.tgz", + "integrity": "sha512-4EII1iNGRUN5WwGbF/kOh/EIkoDN9HsupgLQoXfY+D1oyJm7/F4t5PYU5n8SWZgG0FEwakyM8pGgwcBYruGTlA==", "cpu": [ "ppc64" ], @@ -901,9 +880,9 @@ } }, "node_modules/@rolldown/binding-linux-s390x-gnu": { - "version": "1.0.0-rc.11", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.0.0-rc.11.tgz", - "integrity": "sha512-hIOYmuT6ofM4K04XAZd3OzMySEO4K0/nc9+jmNcxNAxRi6c5UWpqfw3KMFV4MVFWL+jQsSh+bGw2VqmaPMTLyw==", + "version": "1.0.0-rc.17", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.0.0-rc.17.tgz", + "integrity": "sha512-AH8oq3XqQo4IibpVXvPeLDI5pzkpYn0WiZAfT05kFzoJ6tQNzwRdDYQ45M8I/gslbodRZwW8uxLhbSBbkv96rA==", "cpu": [ "s390x" ], @@ -918,9 +897,9 @@ } }, "node_modules/@rolldown/binding-linux-x64-gnu": { - "version": "1.0.0-rc.11", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.0.0-rc.11.tgz", - "integrity": "sha512-qXBQQO9OvkjjQPLdUVr7Nr2t3QTZI7s4KZtfw7HzBgjbmAPSFwSv4rmET9lLSgq3rH/ndA3ngv3Qb8l2njoPNA==", + "version": "1.0.0-rc.17", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.0.0-rc.17.tgz", + "integrity": "sha512-cLnjV3xfo7KslbU41Z7z8BH/E1y5mzUYzAqih1d1MDaIGZRCMqTijqLv76/P7fyHuvUcfGsIpqCdddbxLLK9rA==", "cpu": [ "x64" ], @@ -935,9 +914,9 @@ } }, "node_modules/@rolldown/binding-linux-x64-musl": { - "version": "1.0.0-rc.11", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.0.0-rc.11.tgz", - "integrity": "sha512-/tpFfoSTzUkH9LPY+cYbqZBDyyX62w5fICq9qzsHLL8uTI6BHip3Q9Uzft0wylk/i8OOwKik8OxW+QAhDmzwmg==", + "version": "1.0.0-rc.17", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.0.0-rc.17.tgz", + "integrity": "sha512-0phclDw1spsL7dUB37sIARuis2tAgomCJXAHZlpt8PXZ4Ba0dRP1e+66lsRqrfhISeN9bEGNjQs+T/Fbd7oYGw==", "cpu": [ "x64" ], @@ -952,9 +931,9 @@ } }, "node_modules/@rolldown/binding-openharmony-arm64": { - "version": "1.0.0-rc.11", - "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.0.0-rc.11.tgz", - "integrity": "sha512-mcp3Rio2w72IvdZG0oQ4bM2c2oumtwHfUfKncUM6zGgz0KgPz4YmDPQfnXEiY5t3+KD/i8HG2rOB/LxdmieK2g==", + "version": "1.0.0-rc.17", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.0.0-rc.17.tgz", + "integrity": "sha512-0ag/hEgXOwgw4t8QyQvUCxvEg+V0KBcA6YuOx9g0r02MprutRF5dyljgm3EmR02O292UX7UeS6HzWHAl6KgyhA==", "cpu": [ "arm64" ], @@ -969,9 +948,9 @@ } }, "node_modules/@rolldown/binding-wasm32-wasi": { - "version": "1.0.0-rc.11", - "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.0.0-rc.11.tgz", - "integrity": "sha512-LXk5Hii1Ph9asuGRjBuz8TUxdc1lWzB7nyfdoRgI0WGPZKmCxvlKk8KfYysqtr4MfGElu/f/pEQRh8fcEgkrWw==", + "version": "1.0.0-rc.17", + "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.0.0-rc.17.tgz", + "integrity": "sha512-LEXei6vo0E5wTGwpkJ4KoT3OZJRnglwldt5ziLzOlc6qqb55z4tWNq2A+PFqCJuvWWdP53CVhG1Z9NtToDPJrA==", "cpu": [ "wasm32" ], @@ -979,16 +958,18 @@ "license": "MIT", "optional": true, "dependencies": { - "@napi-rs/wasm-runtime": "^1.1.1" + "@emnapi/core": "1.10.0", + "@emnapi/runtime": "1.10.0", + "@napi-rs/wasm-runtime": "^1.1.4" }, "engines": { - "node": ">=14.0.0" + "node": "^20.19.0 || >=22.12.0" } }, "node_modules/@rolldown/binding-win32-arm64-msvc": { - "version": "1.0.0-rc.11", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.0.0-rc.11.tgz", - "integrity": "sha512-dDwf5otnx0XgRY1yqxOC4ITizcdzS/8cQ3goOWv3jFAo4F+xQYni+hnMuO6+LssHHdJW7+OCVL3CoU4ycnh35Q==", + "version": "1.0.0-rc.17", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.0.0-rc.17.tgz", + "integrity": "sha512-gUmyzBl3SPMa6hrqFUth9sVfcLBlYsbMzBx5PlexMroZStgzGqlZ26pYG89rBb45Mnia+oil6YAIFeEWGWhoZA==", "cpu": [ "arm64" ], @@ -1003,9 +984,9 @@ } }, "node_modules/@rolldown/binding-win32-x64-msvc": { - "version": "1.0.0-rc.11", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.0.0-rc.11.tgz", - "integrity": "sha512-LN4/skhSggybX71ews7dAj6r2geaMJfm3kMbK2KhFMg9B10AZXnKoLCVVgzhMHL0S+aKtr4p8QbAW8k+w95bAA==", + "version": "1.0.0-rc.17", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.0.0-rc.17.tgz", + "integrity": "sha512-3hkiolcUAvPB9FLb3UZdfjVVNWherN1f/skkGWJP/fgSQhYUZpSIRr0/I8ZK9TkF3F7kxvJAk0+IcKvPHk9qQg==", "cpu": [ "x64" ], @@ -1020,9 +1001,9 @@ } }, "node_modules/@rolldown/pluginutils": { - "version": "1.0.0-rc.11", - "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.11.tgz", - "integrity": "sha512-xQO9vbwBecJRv9EUcQ/y0dzSTJgA7Q6UVN7xp6B81+tBGSLVAK03yJ9NkJaUA7JFD91kbjxRSC/mDnmvXzbHoQ==", + "version": "1.0.0-rc.17", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.17.tgz", + "integrity": "sha512-n8iosDOt6Ig1UhJ2AYqoIhHWh/isz0xpicHTzpKBeotdVsTEcxsSA/i3EVM7gQAj0rU27OLAxCjzlj15IWY7bg==", "dev": true, "license": "MIT" }, @@ -1712,9 +1693,9 @@ "license": "MIT" }, "node_modules/oxfmt": { - "version": "0.42.0", - "resolved": "https://registry.npmjs.org/oxfmt/-/oxfmt-0.42.0.tgz", - "integrity": "sha512-QhejGErLSMReNuZ6vxgFHDyGoPbjTRNi6uGHjy0cvIjOQFqD6xmr/T+3L41ixR3NIgzcNiJ6ylQKpvShTgDfqg==", + "version": "0.46.0", + "resolved": "https://registry.npmjs.org/oxfmt/-/oxfmt-0.46.0.tgz", + "integrity": "sha512-CopwJOwPAjZ9p76fCvz+mSOJTw9/NY3cSksZK3VO/bUQ8UoEcketNgUuYS0UB3p+R9XnXe7wGGXUmyFxc7QxJA==", "dev": true, "license": "MIT", "dependencies": { @@ -1730,31 +1711,31 @@ "url": "https://github.com/sponsors/Boshen" }, "optionalDependencies": { - "@oxfmt/binding-android-arm-eabi": "0.42.0", - "@oxfmt/binding-android-arm64": "0.42.0", - "@oxfmt/binding-darwin-arm64": "0.42.0", - "@oxfmt/binding-darwin-x64": "0.42.0", - "@oxfmt/binding-freebsd-x64": "0.42.0", - "@oxfmt/binding-linux-arm-gnueabihf": "0.42.0", - "@oxfmt/binding-linux-arm-musleabihf": "0.42.0", - "@oxfmt/binding-linux-arm64-gnu": "0.42.0", - "@oxfmt/binding-linux-arm64-musl": "0.42.0", - "@oxfmt/binding-linux-ppc64-gnu": "0.42.0", - "@oxfmt/binding-linux-riscv64-gnu": "0.42.0", - "@oxfmt/binding-linux-riscv64-musl": "0.42.0", - "@oxfmt/binding-linux-s390x-gnu": "0.42.0", - "@oxfmt/binding-linux-x64-gnu": "0.42.0", - "@oxfmt/binding-linux-x64-musl": "0.42.0", - "@oxfmt/binding-openharmony-arm64": "0.42.0", - "@oxfmt/binding-win32-arm64-msvc": "0.42.0", - "@oxfmt/binding-win32-ia32-msvc": "0.42.0", - "@oxfmt/binding-win32-x64-msvc": "0.42.0" + "@oxfmt/binding-android-arm-eabi": "0.46.0", + "@oxfmt/binding-android-arm64": "0.46.0", + "@oxfmt/binding-darwin-arm64": "0.46.0", + "@oxfmt/binding-darwin-x64": "0.46.0", + "@oxfmt/binding-freebsd-x64": "0.46.0", + "@oxfmt/binding-linux-arm-gnueabihf": "0.46.0", + "@oxfmt/binding-linux-arm-musleabihf": "0.46.0", + "@oxfmt/binding-linux-arm64-gnu": "0.46.0", + "@oxfmt/binding-linux-arm64-musl": "0.46.0", + "@oxfmt/binding-linux-ppc64-gnu": "0.46.0", + "@oxfmt/binding-linux-riscv64-gnu": "0.46.0", + "@oxfmt/binding-linux-riscv64-musl": "0.46.0", + "@oxfmt/binding-linux-s390x-gnu": "0.46.0", + "@oxfmt/binding-linux-x64-gnu": "0.46.0", + "@oxfmt/binding-linux-x64-musl": "0.46.0", + "@oxfmt/binding-openharmony-arm64": "0.46.0", + "@oxfmt/binding-win32-arm64-msvc": "0.46.0", + "@oxfmt/binding-win32-ia32-msvc": "0.46.0", + "@oxfmt/binding-win32-x64-msvc": "0.46.0" } }, "node_modules/oxlint": { - "version": "1.57.0", - "resolved": "https://registry.npmjs.org/oxlint/-/oxlint-1.57.0.tgz", - "integrity": "sha512-DGFsuBX5MFZX9yiDdtKjTrYPq45CZ8Fft6qCltJITYZxfwYjVdGf/6wycGYTACloauwIPxUnYhBVeZbHvleGhw==", + "version": "1.61.0", + "resolved": "https://registry.npmjs.org/oxlint/-/oxlint-1.61.0.tgz", + "integrity": "sha512-ZC0ALuhDZ6ivOFG+sy0D0pEDN49EvsId98zVlmYdkcXHsEM14m/qTNUEsUpiFiCVbpIxYtVBmmLE87nsbUHohQ==", "dev": true, "license": "MIT", "bin": { @@ -1767,28 +1748,28 @@ "url": "https://github.com/sponsors/Boshen" }, "optionalDependencies": { - "@oxlint/binding-android-arm-eabi": "1.57.0", - "@oxlint/binding-android-arm64": "1.57.0", - "@oxlint/binding-darwin-arm64": "1.57.0", - "@oxlint/binding-darwin-x64": "1.57.0", - "@oxlint/binding-freebsd-x64": "1.57.0", - "@oxlint/binding-linux-arm-gnueabihf": "1.57.0", - "@oxlint/binding-linux-arm-musleabihf": "1.57.0", - "@oxlint/binding-linux-arm64-gnu": "1.57.0", - "@oxlint/binding-linux-arm64-musl": "1.57.0", - "@oxlint/binding-linux-ppc64-gnu": "1.57.0", - "@oxlint/binding-linux-riscv64-gnu": "1.57.0", - "@oxlint/binding-linux-riscv64-musl": "1.57.0", - "@oxlint/binding-linux-s390x-gnu": "1.57.0", - "@oxlint/binding-linux-x64-gnu": "1.57.0", - "@oxlint/binding-linux-x64-musl": "1.57.0", - "@oxlint/binding-openharmony-arm64": "1.57.0", - "@oxlint/binding-win32-arm64-msvc": "1.57.0", - "@oxlint/binding-win32-ia32-msvc": "1.57.0", - "@oxlint/binding-win32-x64-msvc": "1.57.0" + "@oxlint/binding-android-arm-eabi": "1.61.0", + "@oxlint/binding-android-arm64": "1.61.0", + "@oxlint/binding-darwin-arm64": "1.61.0", + "@oxlint/binding-darwin-x64": "1.61.0", + "@oxlint/binding-freebsd-x64": "1.61.0", + "@oxlint/binding-linux-arm-gnueabihf": "1.61.0", + "@oxlint/binding-linux-arm-musleabihf": "1.61.0", + "@oxlint/binding-linux-arm64-gnu": "1.61.0", + "@oxlint/binding-linux-arm64-musl": "1.61.0", + "@oxlint/binding-linux-ppc64-gnu": "1.61.0", + "@oxlint/binding-linux-riscv64-gnu": "1.61.0", + "@oxlint/binding-linux-riscv64-musl": "1.61.0", + "@oxlint/binding-linux-s390x-gnu": "1.61.0", + "@oxlint/binding-linux-x64-gnu": "1.61.0", + "@oxlint/binding-linux-x64-musl": "1.61.0", + "@oxlint/binding-openharmony-arm64": "1.61.0", + "@oxlint/binding-win32-arm64-msvc": "1.61.0", + "@oxlint/binding-win32-ia32-msvc": "1.61.0", + "@oxlint/binding-win32-x64-msvc": "1.61.0" }, "peerDependencies": { - "oxlint-tsgolint": ">=0.15.0" + "oxlint-tsgolint": ">=0.18.0" }, "peerDependenciesMeta": { "oxlint-tsgolint": { @@ -1880,13 +1861,13 @@ "license": "ISC" }, "node_modules/playwright": { - "version": "1.58.2", - "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.58.2.tgz", - "integrity": "sha512-vA30H8Nvkq/cPBnNw4Q8TWz1EJyqgpuinBcHET0YVJVFldr8JDNiU9LaWAE1KqSkRYazuaBhTpB5ZzShOezQ6A==", + "version": "1.59.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.59.1.tgz", + "integrity": "sha512-C8oWjPR3F81yljW9o5OxcWzfh6avkVwDD2VYdwIGqTkl+OGFISgypqzfu7dOe4QNLL2aqcWBmI3PMtLIK233lw==", "dev": true, "license": "Apache-2.0", "dependencies": { - "playwright-core": "1.58.2" + "playwright-core": "1.59.1" }, "bin": { "playwright": "cli.js" @@ -1899,9 +1880,9 @@ } }, "node_modules/playwright-core": { - "version": "1.58.2", - "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.58.2.tgz", - "integrity": "sha512-yZkEtftgwS8CsfYo7nm0KE8jsvm6i/PTgVtB8DL726wNf6H2IMsDuxCpJj59KDaxCtSnrWan2AeDqM7JBaultg==", + "version": "1.59.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.59.1.tgz", + "integrity": "sha512-HBV/RJg81z5BiiZ9yPzIiClYV/QMsDCKUyogwH9p3MCP6IYjUFu/MActgYAvK0oWyV9NlwM3GLBjADyWgydVyg==", "dev": true, "license": "Apache-2.0", "bin": { @@ -1956,14 +1937,14 @@ } }, "node_modules/rolldown": { - "version": "1.0.0-rc.11", - "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.0.0-rc.11.tgz", - "integrity": "sha512-NRjoKMusSjfRbSYiH3VSumlkgFe7kYAa3pzVOsVYVFY3zb5d7nS+a3KGQ7hJKXuYWbzJKPVQ9Wxq2UvyK+ENpw==", + "version": "1.0.0-rc.17", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.0.0-rc.17.tgz", + "integrity": "sha512-ZrT53oAKrtA4+YtBWPQbtPOxIbVDbxT0orcYERKd63VJTF13zPcgXTvD4843L8pcsI7M6MErt8QtON6lrB9tyA==", "dev": true, "license": "MIT", "dependencies": { - "@oxc-project/types": "=0.122.0", - "@rolldown/pluginutils": "1.0.0-rc.11" + "@oxc-project/types": "=0.127.0", + "@rolldown/pluginutils": "1.0.0-rc.17" }, "bin": { "rolldown": "bin/cli.mjs" @@ -1972,21 +1953,21 @@ "node": "^20.19.0 || >=22.12.0" }, "optionalDependencies": { - "@rolldown/binding-android-arm64": "1.0.0-rc.11", - "@rolldown/binding-darwin-arm64": "1.0.0-rc.11", - "@rolldown/binding-darwin-x64": "1.0.0-rc.11", - "@rolldown/binding-freebsd-x64": "1.0.0-rc.11", - "@rolldown/binding-linux-arm-gnueabihf": "1.0.0-rc.11", - "@rolldown/binding-linux-arm64-gnu": "1.0.0-rc.11", - "@rolldown/binding-linux-arm64-musl": "1.0.0-rc.11", - "@rolldown/binding-linux-ppc64-gnu": "1.0.0-rc.11", - "@rolldown/binding-linux-s390x-gnu": "1.0.0-rc.11", - "@rolldown/binding-linux-x64-gnu": "1.0.0-rc.11", - "@rolldown/binding-linux-x64-musl": "1.0.0-rc.11", - "@rolldown/binding-openharmony-arm64": "1.0.0-rc.11", - "@rolldown/binding-wasm32-wasi": "1.0.0-rc.11", - "@rolldown/binding-win32-arm64-msvc": "1.0.0-rc.11", - "@rolldown/binding-win32-x64-msvc": "1.0.0-rc.11" + "@rolldown/binding-android-arm64": "1.0.0-rc.17", + "@rolldown/binding-darwin-arm64": "1.0.0-rc.17", + "@rolldown/binding-darwin-x64": "1.0.0-rc.17", + "@rolldown/binding-freebsd-x64": "1.0.0-rc.17", + "@rolldown/binding-linux-arm-gnueabihf": "1.0.0-rc.17", + "@rolldown/binding-linux-arm64-gnu": "1.0.0-rc.17", + "@rolldown/binding-linux-arm64-musl": "1.0.0-rc.17", + "@rolldown/binding-linux-ppc64-gnu": "1.0.0-rc.17", + "@rolldown/binding-linux-s390x-gnu": "1.0.0-rc.17", + "@rolldown/binding-linux-x64-gnu": "1.0.0-rc.17", + "@rolldown/binding-linux-x64-musl": "1.0.0-rc.17", + "@rolldown/binding-openharmony-arm64": "1.0.0-rc.17", + "@rolldown/binding-wasm32-wasi": "1.0.0-rc.17", + "@rolldown/binding-win32-arm64-msvc": "1.0.0-rc.17", + "@rolldown/binding-win32-x64-msvc": "1.0.0-rc.17" } }, "node_modules/safe-buffer": { @@ -2221,9 +2202,9 @@ "license": "0BSD" }, "node_modules/typescript": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.2.tgz", - "integrity": "sha512-bGdAIrZ0wiGDo5l8c++HWtbaNCWTS4UTv7RaTH/ThVIgjkveJt83m74bBHMJkuCbslY8ixgLBVZJIOiQlQTjfQ==", + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz", + "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==", "dev": true, "license": "Apache-2.0", "bin": { diff --git a/package.json b/package.json index 6b951a3..0a9a7dd 100755 --- a/package.json +++ b/package.json @@ -10,7 +10,7 @@ "build:wasm": "node utils/build-wasm", "start": "rolldown -w -c", "bench": "npm run build && node bench/index.js", - "test": "mocha --parallel --require ./test/boot.js test/*.test.js", + "test": "mocha --parallel --exit --require ./test/boot.js test/*.test.js", "luatests": "node --experimental-import-meta-resolve test/luatests.js", "build": "rolldown -c && tsc -d --emitDeclarationOnly --rootDir src --declarationDir dist", "clean": "rm -rf dist build", @@ -41,17 +41,17 @@ "webassembly" ], "devDependencies": { - "@types/node": "25.5.0", + "@types/node": "*", "chai": "6.2.2", "chai-as-promised": "8.0.2", "fengari": "0.1.5", "mocha": "11.7.5", - "oxfmt": "0.42.0", - "oxlint": "1.57.0", - "rolldown": "1.0.0-rc.11", + "oxfmt": "0.46.0", + "oxlint": "1.61.0", + "rolldown": "1.0.0-rc.17", "tslib": "2.8.1", - "typescript": "6.0.2", - "playwright": "1.58.2" + "typescript": "6.0.3", + "playwright": "1.59.1" }, "dependencies": { "@types/emscripten": "1.41.5" diff --git a/src/engine.ts b/src/engine.ts index bed0adf..1ad3109 100755 --- a/src/engine.ts +++ b/src/engine.ts @@ -62,7 +62,7 @@ export default class LuaEngine { * @returns A Promise that resolves to the result returned by the Lua script execution. */ public doString(script: string): Promise { - return this.callByteCode(thread => thread.loadString(script)) + return this.callByteCode((thread) => thread.loadString(script)) } /** @@ -71,7 +71,7 @@ export default class LuaEngine { * @returns - A Promise that resolves to the result returned by the Lua script execution. */ public doFile(filename: string): Promise { - return this.callByteCode(thread => thread.loadFile(filename)) + return this.callByteCode((thread) => thread.loadFile(filename)) } /** diff --git a/src/thread.ts b/src/thread.ts index b158efe..98110c0 100755 --- a/src/thread.ts +++ b/src/thread.ts @@ -14,6 +14,7 @@ import { LuaType, PointerSize, } from './types' +import { isPromise } from './utils' export interface OrderedExtension { // Bigger is more important @@ -121,7 +122,7 @@ export default class Thread { this.pop(resumeResult.resultCount) // If there's a result and it's a promise, then wait for it. - if (lastValue === Promise.resolve(lastValue)) { + if (isPromise(lastValue)) { await lastValue } else { // If it's a non-promise, then skip a tick to yield for promises, timers, etc. diff --git a/src/type-extensions/error.ts b/src/type-extensions/error.ts index ac2ed93..745fe6c 100644 --- a/src/type-extensions/error.ts +++ b/src/type-extensions/error.ts @@ -51,7 +51,7 @@ class ErrorTypeExtension extends TypeExtension { thread.lua.lua_pop(thread.address, 1) if (injectObject) { - // Lastly create a static Promise constructor. + // Lastly create a static Error constructor. thread.set('Error', { create: (message: string | undefined) => { if (message && typeof message !== 'string') { diff --git a/src/type-extensions/function.ts b/src/type-extensions/function.ts index 9625653..cf46286 100644 --- a/src/type-extensions/function.ts +++ b/src/type-extensions/function.ts @@ -52,8 +52,6 @@ class FunctionTypeExtension extends TypeExtension { // Throws a lua error which does a jump if it does not match. - thread.lua.luaL_checkudata(calledL, 1, this.name) - const userDataPointer = thread.lua.luaL_checkudata(calledL, 1, this.name) const referencePointer = thread.lua._emscripten.getValue(userDataPointer, '*') thread.lua.unref(referencePointer) diff --git a/test/browser.test.js b/test/browser.test.js index 1328803..2dd0afc 100644 --- a/test/browser.test.js +++ b/test/browser.test.js @@ -58,21 +58,15 @@ window.__ready = true } describe('Browser environment', () => { - let server, port, browser, context + let port, browser, context before(async function () { this.timeout(30_000) - ;({ server, port } = await startServer()) + ;({ port } = await startServer()) browser = await chromium.launch() context = await browser.newContext() }) - after(async () => { - await context?.close() - await browser?.close() - server?.close() - }) - async function runInBrowser(code) { const page = await context.newPage() const errors = [] diff --git a/test/engine.test.js b/test/engine.test.js index 1bd7789..639a8fd 100644 --- a/test/engine.test.js +++ b/test/engine.test.js @@ -22,7 +22,9 @@ class TestClass { describe('State', () => { let intervals = [] const setIntervalSafe = (callback, interval) => { - intervals.push(setInterval(() => callback(), interval)) + const handle = setInterval(() => callback(), interval) + intervals.push(handle) + return () => clearInterval(handle) } afterEach(() => { @@ -187,16 +189,26 @@ describe('State', () => { await state.doString(` test = "" - setInterval(function() + done = false + local stop + stop = setInterval(function() test = test .. "i" + if #test >= 5 then + stop() + done = true + end end, 1) `) - await setTimeout(20) - const test = state.global.get('test') - expect(test).length.above(3) - expect(test).length.below(21) - expect(test).to.be.equal(''.padEnd(test.length, 'i')) + const deadline = Date.now() + 1000 + while (!state.global.get('done')) { + if (Date.now() > deadline) { + throw new Error('timed out waiting for scheduled lua calls') + } + await setTimeout(5) + } + + expect(state.global.get('test')).to.be.equal('iiiii') }) it('scheduled lua calls should fail silently if invalid', async () => { From e2535b6e4e9d0712ec8da283ca7ca0085f7a20b9 Mon Sep 17 00:00:00 2001 From: Gabriel Francisco Date: Tue, 28 Jul 2026 17:32:28 -0300 Subject: [PATCH 39/83] bigint support and fixes Co-authored-by: Artur Koshtei --- bin/wasmoon | 6 +- src/engine.ts | 30 ++-- src/module.ts | 141 +++++++++++++++++-- src/thread.ts | 55 ++++++-- src/type-extensions/function.ts | 4 +- src/type-extensions/null.ts | 13 +- src/type-extensions/table.ts | 13 +- src/utils.ts | 21 +++ test/browser.test.js | 11 ++ test/engine.test.js | 237 ++++++++++++++++++++++++++++++++ test/node.test.js | 30 +++- utils/build-wasm.sh | 3 + 12 files changed, 516 insertions(+), 48 deletions(-) diff --git a/bin/wasmoon b/bin/wasmoon index db9cbb7..cc0138d 100755 --- a/bin/wasmoon +++ b/bin/wasmoon @@ -1,5 +1,5 @@ #!/usr/bin/env node -import { Lua, LuaReturn, LuaType, LUA_MULTRET, decorate } from '../dist/index.js' +import { Lua, LuaReturn, LuaType, LUA_MULTRET, decorateProxy } from '../dist/index.js' import pkg from '../package.json' with { type: 'json' } import fs from 'node:fs' import readline from 'node:readline' @@ -193,7 +193,9 @@ for (const snippet of executeSnippets) { await state.doString(snippet) } -state.global.set('arg', decorate(scriptArgs, { disableProxy: true })) +// A real Lua table rather than a JS proxy, so `#arg` and `ipairs(arg)` behave like the +// standalone interpreter. +state.global.set('arg', decorateProxy(scriptArgs, { proxy: false })) const isTTY = process.stdin.isTTY diff --git a/src/engine.ts b/src/engine.ts index 1ad3109..8381ab8 100755 --- a/src/engine.ts +++ b/src/engine.ts @@ -80,9 +80,7 @@ export default class LuaEngine { * @returns - The result returned by the Lua script. */ public doStringSync(script: string): any { - this.global.loadString(script) - const result = this.global.runSync() - return result[0] + return this.callByteCodeSync((thread) => thread.loadString(script)) } /** @@ -91,9 +89,20 @@ export default class LuaEngine { * @returns - The result returned by the Lua script. */ public doFileSync(filename: string): any { - this.global.loadFile(filename) - const result = this.global.runSync() - return result[0] + return this.callByteCodeSync((thread) => thread.loadFile(filename)) + } + + private callByteCodeSync(loader: (thread: Thread) => void): any { + // Runs on the global thread, so leftovers would accumulate for the lifetime of the state. + // runSync has already converted the results to JS, and anything that has to outlive them + // holds its own registry reference. + const startStackTop = this.global.getTop() + try { + loader(this.global) + return this.global.runSync()[0] + } finally { + this.global.setTop(startStackTop) + } } // WARNING: It will not wait for open handles and can potentially cause bugs if JS code tries to reference Lua after executed @@ -103,14 +112,7 @@ export default class LuaEngine { const ref = this.module.luaL_ref(this.global.address, LUA_REGISTRYINDEX) try { loader(thread) - const result = await thread.run(0) - if (result.length > 0) { - // The shenanigans here are to return the first result value on the stack. - // Say there's 2 values at stack indexes 1 and 2. Then top is 2, result.length is 2. - // That's why there's a + 1 sitting at the end. - return thread.getValue(thread.getTop() - result.length + 1) - } - return undefined + return (await thread.run(0))[0] } finally { this.module.luaL_unref(this.global.address, LUA_REGISTRYINDEX, ref) } diff --git a/src/module.ts b/src/module.ts index 4a01496..f9f92a0 100755 --- a/src/module.ts +++ b/src/module.ts @@ -1,5 +1,5 @@ import initWasmModule from '../build/glue.js' -import { LUA_REGISTRYINDEX, LuaReturn, LuaState, LuaType } from './types.js' +import { LUA_REGISTRYINDEX, LuaReturn, LuaState, LuaType, PointerSize } from './types.js' // A rolldown plugin will resolve this to the current version on package.json import version from 'package-version' @@ -30,6 +30,12 @@ interface LuaEmscriptenModule extends EmscriptenModule { _realloc: (pointer: number, size: number) => number } +// Above this a dedicated allocation is used, so one huge string cannot permanently retain the +// scratch buffer. +const REUSABLE_STRING_BUFFER_LIMIT = 64 * 1024 +// Worst case UTF-8 expansion for a JS (UTF-16) string. +const MAX_UTF8_BYTES_PER_CHAR = 3 + interface ReferenceMetadata { index: number refCount: number @@ -158,7 +164,6 @@ export default class LuaModule { public luaL_checkversion_: (L: LuaState, ver: number, sz: number) => void public luaL_getmetafield: (L: LuaState, obj: number, e: string | null) => LuaType public luaL_callmeta: (L: LuaState, obj: number, e: string | null) => number - public luaL_tolstring: (L: LuaState, idx: number, len: number | null) => string public luaL_argerror: (L: LuaState, arg: number, extramsg: string | null) => number public luaL_typeerror: (L: LuaState, arg: number, tname: string | null) => number public luaL_checklstring: (L: LuaState, arg: number, l: number | null) => string @@ -230,7 +235,6 @@ export default class LuaModule { public lua_tonumberx: (L: LuaState, idx: number, isnum: number | null) => number public lua_tointegerx: (L: LuaState, idx: number, isnum: number | null) => bigint public lua_toboolean: (L: LuaState, idx: number) => number - public lua_tolstring: (L: LuaState, idx: number, len: number | null) => string public lua_rawlen: (L: LuaState, idx: number) => bigint public lua_tocfunction: (L: LuaState, idx: number) => number public lua_touserdata: (L: LuaState, idx: number) => number @@ -242,8 +246,7 @@ export default class LuaModule { public lua_pushnil: (L: LuaState) => void public lua_pushnumber: (L: LuaState, n: number) => void public lua_pushinteger: (L: LuaState, n: bigint) => void - public lua_pushlstring: (L: LuaState, s: string | number | null, len: number) => string - public lua_pushstring: (L: LuaState, s: string | number | null) => string + public lua_pushlstring: (L: LuaState, s: number, len: number) => void public lua_pushcclosure: (L: LuaState, fn: number, n: number) => void public lua_pushboolean: (L: LuaState, b: number) => void public lua_pushlightuserdata: (L: LuaState, p: number | null) => void @@ -317,13 +320,25 @@ export default class LuaModule { private availableReferences: number[] = [] private lastRefIndex?: number + // Lua strings are byte arrays that may contain NUL, so they cannot go through Emscripten's + // NUL-terminated string marshalling. These work on pointers and explicit lengths instead. + private readonly rawLuaToLString: (L: LuaState, idx: number, len: number) => number + private readonly rawLuaLToLString: (L: LuaState, idx: number, len: number) => number + private readonly rawLuaPushString: (L: LuaState, s: number) => number + + private readonly textDecoder = new TextDecoder() + private readonly textEncoder = new TextEncoder() + // C writes it immediately before returning and we read it straight after with no interleaving + // await, so a single shared slot stays reentrancy safe. + private readonly sizeScratch: number + private stringBuffer = 0 + public constructor(module: LuaEmscriptenModule) { this._emscripten = module this.luaL_checkversion_ = this.cwrap('luaL_checkversion_', null, ['number', 'number', 'number']) this.luaL_getmetafield = this.cwrap('luaL_getmetafield', 'number', ['number', 'number', 'string']) this.luaL_callmeta = this.cwrap('luaL_callmeta', 'number', ['number', 'number', 'string']) - this.luaL_tolstring = this.cwrap('luaL_tolstring', 'string', ['number', 'number', 'number']) this.luaL_argerror = this.cwrap('luaL_argerror', 'number', ['number', 'number', 'string']) this.luaL_typeerror = this.cwrap('luaL_typeerror', 'number', ['number', 'number', 'string']) this.luaL_checklstring = this.cwrap('luaL_checklstring', 'string', ['number', 'number', 'number']) @@ -389,7 +404,6 @@ export default class LuaModule { this.lua_tonumberx = this.cwrap('lua_tonumberx', 'number', ['number', 'number', 'number']) this.lua_tointegerx = this.cwrap('lua_tointegerx', 'number', ['number', 'number', 'number']) this.lua_toboolean = this.cwrap('lua_toboolean', 'number', ['number', 'number']) - this.lua_tolstring = this.cwrap('lua_tolstring', 'string', ['number', 'number', 'number']) this.lua_rawlen = this.cwrap('lua_rawlen', 'number', ['number', 'number']) this.lua_tocfunction = this.cwrap('lua_tocfunction', 'number', ['number', 'number']) this.lua_touserdata = this.cwrap('lua_touserdata', 'number', ['number', 'number']) @@ -401,8 +415,6 @@ export default class LuaModule { this.lua_pushnil = this.cwrap('lua_pushnil', null, ['number']) this.lua_pushnumber = this.cwrap('lua_pushnumber', null, ['number', 'number']) this.lua_pushinteger = this.cwrap('lua_pushinteger', null, ['number', 'number']) - this.lua_pushlstring = this.cwrap('lua_pushlstring', 'string', ['number', 'string|number', 'number']) - this.lua_pushstring = this.cwrap('lua_pushstring', 'string', ['number', 'string|number']) this.lua_pushcclosure = this.cwrap('lua_pushcclosure', null, ['number', 'number', 'number']) this.lua_pushboolean = this.cwrap('lua_pushboolean', null, ['number', 'number']) this.lua_pushlightuserdata = this.cwrap('lua_pushlightuserdata', null, ['number', 'number']) @@ -471,6 +483,82 @@ export default class LuaModule { this.luaopen_debug = this.cwrap('luaopen_debug', 'number', ['number']) this.luaopen_package = this.cwrap('luaopen_package', 'number', ['number']) this.luaL_openlibs = (L) => this.luaL_openselectedlibs(L, -1, 0) + + this.rawLuaToLString = this.cwrap('lua_tolstring', 'number', ['number', 'number', 'number']) + this.rawLuaLToLString = this.cwrap('luaL_tolstring', 'number', ['number', 'number', 'number']) + this.rawLuaPushString = this.cwrap('lua_pushstring', 'number', ['number', 'number']) + this.lua_pushlstring = this.cwrap('lua_pushlstring', 'number', ['number', 'number', 'number']) + + this.sizeScratch = module._malloc(PointerSize) + if (!this.sizeScratch) { + throw new Error('failed to allocate the scratch buffer for string lengths') + } + } + + /** + * Bytes that aren't valid UTF-8 are replaced with U+FFFD. Use {@link lua_tobytes} when the + * value holds arbitrary binary data (`string.dump`, `string.pack`, ciphertext, ...). + */ + public lua_tolstring(L: LuaState, idx: number, len: number | null = null): string { + return this.toLString(this.rawLuaToLString, L, idx, len) + } + + /** Goes through the `__tostring` metamethod, which leaves the result on the stack. */ + public luaL_tolstring(L: LuaState, idx: number, len: number | null = null): string { + return this.toLString(this.rawLuaLToLString, L, idx, len) + } + + public lua_tobytes(L: LuaState, idx: number): Uint8Array | undefined { + const pointer = this.rawLuaToLString(L, idx, this.sizeScratch) + if (!pointer) { + return undefined + } + // Copied, because the caller may outlive the next heap growth. + return this.heap.slice(pointer, pointer + this.readSize(this.sizeScratch)) + } + + /** A number is a pointer to a NUL-terminated C string, and `null` pushes nil, as in C. */ + public lua_pushstring(L: LuaState, s: string | number | null): void { + if (s === null || s === undefined) { + this.lua_pushnil(L) + } else if (typeof s === 'number') { + this.rawLuaPushString(L, s) + } else if (s.length === 0) { + this.lua_pushlstring(L, 0, 0) + } else { + const capacity = s.length * MAX_UTF8_BYTES_PER_CHAR + const pointer = this.acquireStringBuffer(capacity) + try { + // encodeInto avoids materialising an intermediate Uint8Array for the whole string. + const { written } = this.textEncoder.encodeInto(s, this.heap.subarray(pointer, pointer + capacity)) + this.lua_pushlstring(L, pointer, written) + } finally { + this.releaseStringBuffer(pointer) + } + } + } + + public lua_pushbytes(L: LuaState, bytes: Uint8Array): void { + const pointer = this.acquireStringBuffer(bytes.length) + try { + this.heap.set(bytes, pointer) + this.lua_pushlstring(L, pointer, bytes.length) + } finally { + this.releaseStringBuffer(pointer) + } + } + + public readString(pointer: number, length: number): string { + if (!length) { + return '' + } + return this.textDecoder.decode(this.heap.subarray(pointer, pointer + length)) + } + + private toLString(raw: (L: LuaState, idx: number, len: number) => number, L: LuaState, idx: number, len: number | null): string { + const lengthPointer = len ?? this.sizeScratch + const pointer = raw(L, idx, lengthPointer) + return pointer ? this.readString(pointer, this.readSize(lengthPointer)) : '' } public lua_remove(luaState: LuaState, index: number): void { @@ -550,6 +638,41 @@ export default class LuaModule { } } + // Never cache this: ALLOW_MEMORY_GROWTH swaps the underlying buffer when the heap grows, and + // Emscripten reassigns HEAPU8 to match. + private get heap(): Uint8Array { + return this._emscripten.HEAPU8 + } + + private readSize(pointer: number): number { + return this._emscripten.HEAPU32[pointer >>> 2] + } + + private acquireStringBuffer(size: number): number { + if (size > REUSABLE_STRING_BUFFER_LIMIT) { + const pointer = this._emscripten._malloc(size) + if (!pointer) { + throw new Error(`failed to allocate ${size} bytes for a string`) + } + return pointer + } + + if (!this.stringBuffer) { + this.stringBuffer = this._emscripten._malloc(REUSABLE_STRING_BUFFER_LIMIT) + if (!this.stringBuffer) { + throw new Error(`failed to allocate ${REUSABLE_STRING_BUFFER_LIMIT} bytes for the string buffer`) + } + } + + return this.stringBuffer + } + + private releaseStringBuffer(pointer: number): void { + if (pointer !== this.stringBuffer) { + this._emscripten._free(pointer) + } + } + private cwrap( name: string, returnType: Emscripten.JSType | null, diff --git a/src/thread.ts b/src/thread.ts index 98110c0..274f570 100755 --- a/src/thread.ts +++ b/src/thread.ts @@ -14,7 +14,7 @@ import { LuaType, PointerSize, } from './types' -import { isPromise } from './utils' +import { isEmscriptenUnwind, isPromise, yieldToEventLoop } from './utils' export interface OrderedExtension { // Bigger is more important @@ -25,6 +25,8 @@ export interface OrderedExtension { // When the debug count hook is set, call it every X instructions. const INSTRUCTION_HOOK_COUNT = 1000 +const LUA_INTEGER_BITS = 64 + export default class Thread { public readonly address: LuaState public readonly lua: LuaModule @@ -126,11 +128,11 @@ export default class Thread { await lastValue } else { // If it's a non-promise, then skip a tick to yield for promises, timers, etc. - await new Promise((resolve) => setImmediate(resolve)) + await yieldToEventLoop() } } else { // If there's nothing to yield, then skip a tick to yield for promises, timers, etc. - await new Promise((resolve) => setImmediate(resolve)) + await yieldToEventLoop() } resumeResult = this.resume(0) @@ -205,12 +207,20 @@ export default class Thread { this.lua.lua_pushnil(this.address) break case 'number': - if (Number.isInteger(target)) { + // Only integers JS can represent exactly become Lua integers. Values like 1e300 + // are integral but far outside int64, and would wrap silently if pushed as one. + if (Number.isSafeInteger(target)) { this.lua.lua_pushinteger(this.address, BigInt(target)) } else { this.lua.lua_pushnumber(this.address, target) } break + case 'bigint': + if (BigInt.asIntN(LUA_INTEGER_BITS, target) !== target) { + throw new RangeError(`bigint ${target} does not fit in a 64 bit Lua integer`) + } + this.lua.lua_pushinteger(this.address, target) + break case 'string': this.lua.lua_pushstring(this.address, target) break @@ -279,8 +289,15 @@ export default class Thread { return undefined case LuaType.Nil: return null - case LuaType.Number: - return this.lua.lua_tonumberx(this.address, index, null) + case LuaType.Number: { + const value = this.lua.lua_tonumberx(this.address, index, null) + // Only outside the safe range can the integer subtype change the result, and + // checking that first keeps the common case to a single wasm call. + if (Number.isSafeInteger(value) || !this.lua.lua_isinteger(this.address, index)) { + return value + } + return this.lua.lua_tointegerx(this.address, index, null) + } case LuaType.String: return this.lua.lua_tolstring(this.address, index, null) case LuaType.Boolean: @@ -324,17 +341,18 @@ export default class Thread { if (timeout && timeout > 0) { if (!this.hookFunctionPointer) { this.hookFunctionPointer = this.lua._emscripten.addFunction((): void => { - if (Date.now() > timeout) { + // Reads this.timeout rather than closing over the argument, so a hook + // allocated for an earlier deadline still honours the current one. + if (this.timeout !== undefined && Date.now() > this.timeout) { this.pushValue(new LuaTimeoutError(`thread timeout exceeded`)) this.lua.lua_error(this.address) } }, 'vii') } - this.lua.lua_sethook(this.address, this.hookFunctionPointer!, LuaEventMasks.Count, INSTRUCTION_HOOK_COUNT) this.timeout = timeout - } else if (this.hookFunctionPointer) { - this.hookFunctionPointer = undefined + this.lua.lua_sethook(this.address, this.hookFunctionPointer, LuaEventMasks.Count, INSTRUCTION_HOOK_COUNT) + } else { this.timeout = undefined this.lua.lua_sethook(this.address, null, 0, 0) } @@ -359,6 +377,20 @@ export default class Thread { return str } + /** + * Values holding binary data (`string.dump`, `string.pack`, ciphertext, ...) cannot survive a + * round trip through a JS string, so use this and {@link pushStringBytes} for those instead + * of getValue/pushValue. + * @returns the bytes, or undefined if the value is neither a string nor a number. + */ + public getStringBytes(index: number): Uint8Array | undefined { + return this.lua.lua_tobytes(this.address, index) + } + + public pushStringBytes(bytes: Uint8Array): void { + this.lua.lua_pushbytes(this.address, bytes) + } + public dumpStack(log = console.log): void { const top = this.getTop() @@ -403,6 +435,9 @@ export default class Thread { } this.pop(1) // pop stack trace. } catch (err) { + if (isEmscriptenUnwind(err)) { + throw err + } console.warn('Failed to generate stack trace', err) } } diff --git a/src/type-extensions/function.ts b/src/type-extensions/function.ts index cf46286..db39794 100644 --- a/src/type-extensions/function.ts +++ b/src/type-extensions/function.ts @@ -5,6 +5,7 @@ import RawResult from '../raw-result' import Thread from '../thread' import TypeExtension from '../type-extension' import { LUA_REGISTRYINDEX, LuaReturn, LuaState, LuaType, PointerSize } from '../types' +import { isEmscriptenUnwind } from '../utils' export interface FunctionDecoration extends BaseDecorationOptions { receiveArgsQuantity?: boolean @@ -114,8 +115,7 @@ class FunctionTypeExtension extends TypeExtension { private gcPointer: number + private nullReference: number public constructor(thread: Global) { super(thread, 'js_null') @@ -46,7 +47,12 @@ class NullTypeExtension extends TypeExtension { // Create a new table, this is unique and will be the "null" value by attaching the // metatable created above. The first argument is the target, the second options. super.pushValue(thread, new Decoration({}, {})) - // Put it into the global field named null. + + // Lua code is free to reassign the `null` global, so marshalling anchors the sentinel in + // the registry instead of looking it up by name. + thread.lua.lua_pushvalue(thread.address, -1) + this.nullReference = thread.lua.luaL_ref(thread.address, LUA_REGISTRYINDEX) + thread.lua.lua_setglobal(thread.address, 'null') } @@ -63,8 +69,7 @@ class NullTypeExtension extends TypeExtension { if (decoration?.target !== null) { return false } - // Rather than pushing a new value, get the global "null" onto the stack. - thread.lua.lua_getglobal(thread.address, 'null') + thread.lua.lua_rawgeti(thread.address, LUA_REGISTRYINDEX, BigInt(this.nullReference)) return true } diff --git a/src/type-extensions/table.ts b/src/type-extensions/table.ts index 6fb4335..3ca449b 100644 --- a/src/type-extensions/table.ts +++ b/src/type-extensions/table.ts @@ -65,19 +65,20 @@ class TableTypeExtension extends TypeExtension { createTable(target.length, 0) for (let i = 0; i < target.length; i++) { - thread.pushValue(i + 1, seenMap) thread.pushValue(target[i], seenMap) - - thread.lua.lua_settable(thread.address, tableIndex) + // Raw, so the table being built cannot be observed through metamethods. + thread.lua.lua_rawseti(thread.address, tableIndex, BigInt(i + 1)) } } else { - createTable(0, Object.getOwnPropertyNames(target).length) + // A for..in loop would also walk the prototype chain and copy inherited members. + const keys = Object.keys(target) + createTable(0, keys.length) - for (const key in target) { + for (const key of keys) { thread.pushValue(key, seenMap) thread.pushValue((target as Record)[key], seenMap) - thread.lua.lua_settable(thread.address, tableIndex) + thread.lua.lua_rawset(thread.address, tableIndex) } } } finally { diff --git a/src/utils.ts b/src/utils.ts index 68b54c0..1e6744e 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,3 +1,24 @@ export const isPromise = (target: any): target is Promise => { return target && (Promise.resolve(target) === target || typeof target.then === 'function') } + +/** + * Emscripten unwinds a Lua longjmp by throwing from its internal EmscriptenEH hierarchy. The + * wasm caller gates on `instanceof EmscriptenEH` to resume unwinding, so these have to be + * rethrown rather than raised as Lua errors. The class is module local in the generated glue, + * which leaves the name as the only usable signal. + */ +export const isEmscriptenUnwind = (value: unknown): boolean => { + return typeof value === 'object' && value !== null && String(value.constructor?.name).startsWith('Emscripten') +} + +// Browsers have no setImmediate. The 4ms clamp on nested timers is acceptable here. +const scheduleMacrotask = typeof setImmediate === 'function' ? setImmediate : (task: () => void) => setTimeout(task, 0) + +/** + * A macrotask, so pending promise callbacks *and* timers get a chance to run before Lua is + * resumed. A microtask would starve timer driven code such as setTimeout based sleeps. + */ +export const yieldToEventLoop = (): Promise => { + return new Promise((resolve) => scheduleMacrotask(() => resolve())) +} diff --git a/test/browser.test.js b/test/browser.test.js index 2dd0afc..57d94e2 100644 --- a/test/browser.test.js +++ b/test/browser.test.js @@ -191,4 +191,15 @@ describe('Browser environment', () => { `) expect(result).to.be.equal(6) }) + + it('yielding at the top level in browser should succeed', async function () { + this.timeout(30_000) + // Browsers have no setImmediate, which the yield path used to depend on. + const result = await runInBrowser(` + const lua = await Lua.load({ wasmFile }) + const state = lua.createState() + return await state.doString('coroutine.yield() return 7') + `) + expect(result).to.be.equal(7) + }) }) diff --git a/test/engine.test.js b/test/engine.test.js index 639a8fd..c5846de 100644 --- a/test/engine.test.js +++ b/test/engine.test.js @@ -168,6 +168,41 @@ describe('State', () => { expect(value).to.be.equal('world') }) + it('inherited properties should not be copied into the lua table', async () => { + const state = await getState({ enableProxy: false }) + const obj = Object.create({ inherited: 'yes' }) + obj.own = 'mine' + state.global.set('t', obj) + + const keys = await state.doString(` + local out = {} + for key in pairs(t) do out[#out + 1] = key end + table.sort(out) + return table.concat(out, ',') + `) + + expect(keys).to.be.equal('own') + }) + + it('non enumerable properties should not be copied into the lua table', async () => { + const state = await getState({ enableProxy: false }) + const obj = { own: 'mine' } + Object.defineProperty(obj, 'hidden', { value: 1, enumerable: false }) + state.global.set('t', obj) + + expect(await state.doString('return t.hidden == nil')).to.be.true + expect(await state.doString('return t.own')).to.be.equal('mine') + }) + + it('nested arrays and objects should be copied into the lua table', async () => { + const state = await getState({ enableProxy: false }) + state.global.set('t', { list: [10, 20, 30], nested: { deep: [{ value: 5 }] } }) + + expect(await state.doString('return #t.list')).to.be.equal(3) + expect(await state.doString('return t.list[1]')).to.be.equal(10) + expect(await state.doString('return t.nested.deep[1].value')).to.be.equal(5) + }) + it('a lua error should throw on JS', async () => { const state = await getState() @@ -527,6 +562,31 @@ describe('State', () => { await expect(state.global.run(0, { timeout: 5 })).eventually.to.be.rejectedWith('thread timeout exceeded') }) + it('the most recently set timeout should be the one that applies', async function () { + this.timeout(30_000) + const state = await getState() + const thread = state.global.newThread() + + thread.setTimeout(Date.now() + 20) + thread.setTimeout(Date.now() + 20_000) + thread.loadString('local x = 0 for i = 1, 20000000 do x = x + 1 end return x') + + expect((await thread.run(0))[0]).to.be.equal(20000000) + }) + + it('clearing a timeout should disable the hook', async function () { + this.timeout(30_000) + const state = await getState() + const thread = state.global.newThread() + + thread.setTimeout(Date.now() + 10) + thread.setTimeout(undefined) + thread.loadString('local x = 0 for i = 1, 5000000 do x = x + 1 end return 7') + + expect(thread.getTimeout()).to.be.undefined + expect((await thread.run(0))[0]).to.be.equal(7) + }) + it('overwrite lib function', async () => { const state = await getState() @@ -681,6 +741,82 @@ describe('State', () => { expect(res).to.be.equal(str) }) + it('a large multibyte string should keep its byte length', async function () { + this.timeout(30_000) + const state = await getState() + const str = 'á'.repeat(500000) + + state.global.set('str', str) + + expect(await state.doString('return #str')).to.be.equal(1000000) + expect(await state.doString('return str')).to.be.equal(str) + }) + + it('a string containing NUL should be pushed with its full length', async () => { + const state = await getState() + state.global.set('str', 'a\0b') + + expect(await state.doString('return #str')).to.be.equal(3) + }) + + it('a string containing NUL should be retrieved with its full length', async () => { + const state = await getState() + + const res = await state.doString('return "x\\0y"') + + expect(res).to.be.equal('x\0y') + }) + + it('a string containing NUL should round trip unchanged', async () => { + const state = await getState() + const str = 'before\0middle\0after' + state.global.set('str', str) + + expect(await state.doString('return str')).to.be.equal(str) + }) + + it('an empty string should round trip unchanged', async () => { + const state = await getState() + state.global.set('str', '') + + expect(await state.doString('return #str')).to.be.equal(0) + expect(await state.doString('return str')).to.be.equal('') + }) + + it('getStringBytes should expose bytes that are not valid UTF-8', async () => { + const state = await getState() + await state.doString('value = string.char(0, 255, 128, 65)') + + state.global.lua.lua_getglobal(state.global.address, 'value') + const bytes = state.global.getStringBytes(-1) + state.global.pop() + + expect(Array.from(bytes)).to.be.eql([0, 255, 128, 65]) + }) + + it('getStringBytes should return undefined for a non string value', async () => { + const state = await getState() + state.global.pushValue({}) + + expect(state.global.getStringBytes(-1)).to.be.undefined + + state.global.pop() + }) + + it('bytecode should round trip through the byte accessors', async () => { + const state = await getState() + await state.doString('bytecode = string.dump(load("return 42"))') + + state.global.lua.lua_getglobal(state.global.address, 'bytecode') + const bytes = state.global.getStringBytes(-1) + state.global.pop() + + state.global.pushStringBytes(bytes) + state.global.lua.lua_setglobal(state.global.address, 'roundtripped') + + expect(await state.doString('return load(roundtripped)()')).to.be.equal(42) + }) + it('negative integers should be pushed and retrieved as string', async () => { const state = await getState() state.global.set('value', -1) @@ -748,6 +884,59 @@ describe('State', () => { expect(roundTrip).to.be.equal(value) }) + it('integers outside the JS safe range should be retrieved as bigint', async () => { + const state = await getState() + + expect(await state.doString('return math.maxinteger')).to.be.equal(9223372036854775807n) + expect(await state.doString('return math.mininteger')).to.be.equal(-9223372036854775808n) + }) + + it('integers inside the JS safe range should be retrieved as number', async () => { + const state = await getState() + + const res = await state.doString('return 1689031554550') + + expect(res).to.be.equal(1689031554550) + expect(res).to.be.a('number') + }) + + it('an integral number should be pushed as a lua integer', async () => { + const state = await getState() + state.global.set('value', 2) + + expect(await state.doString('return math.type(value)')).to.be.equal('integer') + }) + + it('floats should be retrieved as number', async () => { + const state = await getState() + + expect(await state.doString('return 1.5')).to.be.equal(1.5) + expect(await state.doString('return math.type(1.5)')).to.be.equal('float') + }) + + it('a bigint should be pushed as a 64 bit lua integer', async () => { + const state = await getState() + state.global.set('value', 9223372036854775807n) + + expect(await state.doString('return tostring(value)')).to.be.equal('9223372036854775807') + expect(await state.doString('return math.type(value)')).to.be.equal('integer') + expect(await state.doString('return value')).to.be.equal(9223372036854775807n) + }) + + it('a bigint outside the lua integer range should throw', async () => { + const state = await getState() + + expect(() => state.global.set('value', 2n ** 70n)).to.throw(RangeError) + }) + + it('an integral number too large for a lua integer should be pushed as a float', async () => { + const state = await getState() + state.global.set('value', 1e300) + + expect(await state.doString('return math.type(value)')).to.be.equal('float') + expect(await state.doString('return value')).to.be.equal(1e300) + }) + it('yielding in a JS callback into Lua does not break lua state', async () => { // When yielding within a callback the error 'attempt to yield across a C-call boundary'. // This test just checks that throwing that error still allows the lua global to be @@ -822,6 +1011,23 @@ describe('State', () => { expect(res).to.deep.equal([null, null, 'nil']) }) + it('reassigning the null global should not affect pushing null', async () => { + const state = await getState() + await state.doString('null = 5') + + state.global.set('value', null) + + expect(await state.doString('return type(value)')).to.be.equal('userdata') + expect(state.global.get('value')).to.be.null + }) + + it('a pushed null should equal the injected null global', async () => { + const state = await getState() + state.global.set('value', null) + + expect(await state.doString('return value == null')).to.be.true + }) + it('Nested callback from JS to Lua', async () => { const state = await getState() state.global.set('call', (fn) => fn()) @@ -847,6 +1053,37 @@ describe('State', () => { } }) + it('lots of doStringSync calls should not grow the lua stack', async function () { + this.timeout(30_000) + const state = await getState() + const startTop = state.global.getTop() + + for (let i = 0; i < 500; i++) { + expect(state.doStringSync(`return ${i}`)).to.be.equal(i) + } + + expect(state.global.getTop()).to.be.equal(startTop) + }) + + it('a failing doStringSync should not grow the lua stack', async () => { + const state = await getState() + const startTop = state.global.getTop() + + expect(() => state.doStringSync('error("boom")')).to.throw('boom') + + expect(state.global.getTop()).to.be.equal(startTop) + }) + + it('values returned by doStringSync should outlive the stack reset', async () => { + const state = await getState() + + const fn = state.doStringSync('return function() return 3 end') + const table = state.doStringSync('return { a = 1, b = { 2, 3 } }') + + expect(fn()).to.be.equal(3) + expect(table).to.be.eql({ a: 1, b: [2, 3] }) + }) + it('many concurrent doString calls should succeed', async function () { this.timeout(15000) const state = await getState() diff --git a/test/node.test.js b/test/node.test.js index 51d8dcb..1fd0ded 100644 --- a/test/node.test.js +++ b/test/node.test.js @@ -1,9 +1,24 @@ -import { readFileSync, writeFileSync, mkdirSync, rmSync } from 'node:fs' +import { readFileSync, writeFileSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs' import { join } from 'node:path' import { tmpdir } from 'node:os' +import { spawn } from 'node:child_process' import { expect } from 'chai' import { Lua } from '../dist/index.js' +// stdin stays closed, as it would be for a redirected or piped invocation. The CLI keeps a +// readline interface open otherwise and never exits. +const runCli = (args) => { + return new Promise((resolve, reject) => { + const child = spawn(process.execPath, ['bin/wasmoon', ...args], { stdio: ['ignore', 'pipe', 'pipe'] }) + let stdout = '' + let stderr = '' + child.stdout.on('data', (chunk) => (stdout += chunk)) + child.stderr.on('data', (chunk) => (stderr += chunk)) + child.on('error', reject) + child.on('close', (code) => resolve({ code, stdout, stderr })) + }) +} + describe('Node environment', () => { it('load Lua engine in node should succeed', async () => { const lua = await Lua.load() @@ -247,4 +262,17 @@ describe('Node environment', () => { `) expect(result).to.be.true }) + + it('cli should expose arg as a lua table', async function () { + this.timeout(30_000) + const directory = mkdtempSync(join(tmpdir(), 'wasmoon-cli-')) + const script = join(directory, 'args.lua') + writeFileSync(script, 'print(type(arg), #arg, arg[1], arg[2], table.concat(arg, "+"))') + + const { code, stdout, stderr } = await runCli([script, 'first', 'second']) + + expect(stderr).to.be.empty + expect(code).to.be.equal(0) + expect(stdout.trim()).to.be.equal('table\t2\tfirst\tsecond\tfirst+second') + }) }) diff --git a/utils/build-wasm.sh b/utils/build-wasm.sh index f64546f..046430c 100755 --- a/utils/build-wasm.sh +++ b/utils/build-wasm.sh @@ -4,6 +4,8 @@ mkdir -p ../build LUA_SRC=$(ls ../lua/*.c | grep -v "luac.c" | grep -v "lua.c" | tr "\n" " ") +# Do not add --closure here: isEmscriptenUnwind identifies in-flight longjmps by class name, so +# mangling them would silently turn every unwind into a Lua error. extension="" if [ "$1" == "dev" ]; then @@ -29,6 +31,7 @@ emcc \ 'stringToNewUTF8', \ 'intArrayFromString', \ 'UTF8ToString', \ + 'HEAPU8', \ 'HEAPU32' ]" \ -s DEFAULT_LIBRARY_FUNCS_TO_INCLUDE="[ From 29bde9ac027ddf767e279a4b097415417fdce435 Mon Sep 17 00:00:00 2001 From: Gabriel Francisco Date: Tue, 28 Jul 2026 17:49:09 -0300 Subject: [PATCH 40/83] chore: update packages --- .github/workflows/publish.yml | 18 +- .github/workflows/test.yml | 10 +- .oxlintrc.json | 5 + package-lock.json | 1009 +++++++++++++++++++++++---------- package.json | 16 +- 5 files changed, 747 insertions(+), 311 deletions(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 510a043..a9132c6 100755 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -9,17 +9,18 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout repository - uses: actions/checkout@v6 + uses: actions/checkout@v7 with: submodules: recursive - name: Setup EMSDK - uses: mymindstorm/setup-emsdk@v14 + uses: emscripten-core/setup-emsdk@v16 with: - version: 5.0.4 + version: 6.0.4 + actions-cache-folder: emsdk-cache - name: Use Node.js 24.x - uses: actions/setup-node@v6 + uses: actions/setup-node@v7 with: node-version: 24.x @@ -35,6 +36,9 @@ jobs: - name: Build project run: npm run build + - name: Install Playwright browsers + run: npx playwright install --with-deps chromium + - name: Run tests run: npm test @@ -57,7 +61,7 @@ jobs: needs: build steps: - name: Checkout repository - uses: actions/checkout@v6 + uses: actions/checkout@v7 - name: Download build artifact uses: actions/download-artifact@v8 @@ -69,7 +73,7 @@ jobs: run: cp -r build-artifact/* . - name: Publish to npm - uses: JS-DevTools/npm-publish@v3 + uses: JS-DevTools/npm-publish@v4 with: token: ${{ secrets.NPM_TOKEN }} @@ -82,7 +86,7 @@ jobs: # id-token: write # steps: # - name: Download build artifact - # uses: actions/download-artifact@v4 + # uses: actions/download-artifact@v8 # with: # name: build-artifact # path: build-artifact diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 06a732e..a588f0b 100755 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -13,16 +13,18 @@ jobs: node-version: [22, 24] steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v7 with: submodules: recursive - - uses: mymindstorm/setup-emsdk@v14 + - uses: emscripten-core/setup-emsdk@v16 with: - version: 5.0.4 + version: 6.0.4 + actions-cache-folder: emsdk-cache - name: Use Node.js ${{ matrix.node-version }} - uses: actions/setup-node@v6 + uses: actions/setup-node@v7 with: node-version: ${{ matrix.node-version }} + cache: npm - run: npm ci - run: npm run lint:nofix - run: npm run build:wasm diff --git a/.oxlintrc.json b/.oxlintrc.json index 1769aea..676a206 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -1,8 +1,13 @@ { "plugins": ["import", "promise", "node"], + "categories": { + "correctness": "deny", + "suspicious": "deny" + }, "rules": { "no-shadow": "off", "no-extend-native": "off", + "no-underscore-dangle": "off", "consistent-function-scoping": "off", "promise/always-return": "off" }, diff --git a/package-lock.json b/package-lock.json index 6c89b92..0e14f85 100644 --- a/package-lock.json +++ b/package-lock.json @@ -19,19 +19,19 @@ "chai": "6.2.2", "chai-as-promised": "8.0.2", "fengari": "0.1.5", - "mocha": "11.7.5", - "oxfmt": "0.46.0", - "oxlint": "1.61.0", - "playwright": "1.59.1", - "rolldown": "1.0.0-rc.17", + "mocha": "11.7.6", + "oxfmt": "0.61.0", + "oxlint": "1.76.0", + "playwright": "1.62.0", + "rolldown": "1.2.0", "tslib": "2.8.1", - "typescript": "6.0.3" + "typescript": "7.0.2" } }, "node_modules/@emnapi/wasi-threads": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.1.tgz", - "integrity": "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.0.1.tgz", + "integrity": "sha512-9DsSk+o5NBX0CCJT8s0EROGSGxjR/tKu6aBTaVyq+SjAEQH4XcdcRxPBRzsBLizTTJ49MJjF+jgu3qnO9GLQcQ==", "dev": true, "license": "MIT", "optional": true, @@ -58,28 +58,31 @@ } }, "node_modules/@napi-rs/wasm-runtime": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.4.tgz", - "integrity": "sha512-3NQNNgA1YSlJb/kMH1ildASP9HW7/7kYnRI2szWJaofaS1hWmbGI4H+d3+22aGzXXN9IJ+n+GiFVcGipJP18ow==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.0.tgz", + "integrity": "sha512-kDoONqMa+VnZ4vvvu/ZUurpJ4gkZU57e7g69qpNgWhYcZFPUHZM2CEMKm+cG6ufDVALbjMvfmMjFVqaK7uEMnA==", "dev": true, "license": "MIT", "optional": true, "dependencies": { - "@tybys/wasm-util": "^0.10.1" + "@tybys/wasm-util": "^0.10.3" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" }, "funding": { "type": "github", "url": "https://github.com/sponsors/Brooooooklyn" }, "peerDependencies": { - "@emnapi/core": "^1.7.1", - "@emnapi/runtime": "^1.7.1" + "@emnapi/core": "^2.0.0-alpha.3", + "@emnapi/runtime": "^2.0.0-alpha.3" } }, "node_modules/@oxc-project/types": { - "version": "0.127.0", - "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.127.0.tgz", - "integrity": "sha512-aIYXQBo4lCbO4z0R3FHeucQHpF46l2LbMdxRvqvuRuW2OxdnSkcng5B8+K12spgLDj93rtN3+J2Vac/TIO+ciQ==", + "version": "0.140.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.140.0.tgz", + "integrity": "sha512-h5LUOzGArYemnW1NMz/DuuQhBi96J6JL2Bk8zE4kvqxB5Sg3jxmCiH4uyOWHDkiKSt5vWlG4FIwCR/DbstcNRQ==", "dev": true, "license": "MIT", "funding": { @@ -87,9 +90,9 @@ } }, "node_modules/@oxfmt/binding-android-arm-eabi": { - "version": "0.46.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm-eabi/-/binding-android-arm-eabi-0.46.0.tgz", - "integrity": "sha512-b1doV4WRcJU+BESSlCvCjV+5CEr/T6h0frArAdV26Nir+gGNFNaylvDiiMPfF1pxeV0txZEs38ojzJaxBYg+ng==", + "version": "0.61.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm-eabi/-/binding-android-arm-eabi-0.61.0.tgz", + "integrity": "sha512-BaS+1OVvg9sr+Xav0+KdWedQRcAzrdoEcwMZeqoc2F6ieC1s/t5eM35YQoRPQ7vAqkZ+p3tbQb1r9I9mrV5oGA==", "cpu": [ "arm" ], @@ -104,9 +107,9 @@ } }, "node_modules/@oxfmt/binding-android-arm64": { - "version": "0.46.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm64/-/binding-android-arm64-0.46.0.tgz", - "integrity": "sha512-v6+HhjsoV3GO0u2u9jLSAZrvWfTraDxKofUIQ7/ktS7tzS+epVsxdHmeM+XxuNcAY/nWxxU1Sg4JcGTNRXraBA==", + "version": "0.61.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm64/-/binding-android-arm64-0.61.0.tgz", + "integrity": "sha512-of8atAV0M1egGcVOMbgZCvc10sFOP3ayQBNQV5h5G3fNq8gACdEswfFk9bzGrdbM23rtg0Coxi7np7oPLcueNw==", "cpu": [ "arm64" ], @@ -121,9 +124,9 @@ } }, "node_modules/@oxfmt/binding-darwin-arm64": { - "version": "0.46.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-arm64/-/binding-darwin-arm64-0.46.0.tgz", - "integrity": "sha512-3eeooJGrqGIlI5MyryDZsAcKXSmKIgAD4yYtfRrRJzXZ0UTFZtiSveIur56YPrGMYZwT4XyVhHsMqrNwr1XeFA==", + "version": "0.61.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-arm64/-/binding-darwin-arm64-0.61.0.tgz", + "integrity": "sha512-7l8+5ov4BGwtAcmpzvEik/TG3bciwyw/S3e6j5GKH7pcQqcgCVxD3AuJeP6upto+SOTBKQ4wrrdbMt0gq8fHSQ==", "cpu": [ "arm64" ], @@ -138,9 +141,9 @@ } }, "node_modules/@oxfmt/binding-darwin-x64": { - "version": "0.46.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-x64/-/binding-darwin-x64-0.46.0.tgz", - "integrity": "sha512-QG8BDM0CXWbu84k2SKmCqfEddPQPFiBicwtYnLqHRWZZl57HbtOLRMac/KTq2NO4AEc4ICCBpFxJIV9zcqYfkQ==", + "version": "0.61.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-x64/-/binding-darwin-x64-0.61.0.tgz", + "integrity": "sha512-Fnz4dDDXBb7udk+DmwelNjxbD6yptyxwCqwCH2ebo4RVLxVsRfFsn/AHJC49KIltPrVokamGv4SSOsiV50DTxQ==", "cpu": [ "x64" ], @@ -155,9 +158,9 @@ } }, "node_modules/@oxfmt/binding-freebsd-x64": { - "version": "0.46.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-freebsd-x64/-/binding-freebsd-x64-0.46.0.tgz", - "integrity": "sha512-9DdCqS/n2ncu/Chazvt3cpgAjAmIGQDz7hFKSrNItMApyV/Ja9mz3hD4JakIE3nS8PW9smEbPWnb389QLBY4nw==", + "version": "0.61.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-freebsd-x64/-/binding-freebsd-x64-0.61.0.tgz", + "integrity": "sha512-mddOebKNCP+AucmzfNsk3jgbr681qAUvgMqi865GW5gWLJ/AnzXbvjQRrny0e++NAN8aphav/aRSrfFxNsNjpA==", "cpu": [ "x64" ], @@ -172,9 +175,9 @@ } }, "node_modules/@oxfmt/binding-linux-arm-gnueabihf": { - "version": "0.46.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-0.46.0.tgz", - "integrity": "sha512-Dgs7VeE2jT0LHMhw6tPEt0xQYe54kBqHEovmWsv4FVQlegCOvlIJNx0S8n4vj8WUtpT+Z6BD2HhKJPLglLxvZg==", + "version": "0.61.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-0.61.0.tgz", + "integrity": "sha512-svx59iYL+DbaZGZUIoice4W0CjRXGExnbz7Re+awIb60rVxBS2KrU7Hnlx+nZYanLGLpjneUEgo/VFEKkSZAyQ==", "cpu": [ "arm" ], @@ -189,9 +192,9 @@ } }, "node_modules/@oxfmt/binding-linux-arm-musleabihf": { - "version": "0.46.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-0.46.0.tgz", - "integrity": "sha512-Zxn3adhTH13JKnU4xXJj8FeEfF680XjXh3gSShKl57HCMBRde2tUJTgogV/1MSHA80PJEVrDa7r66TLVq3Ia7Q==", + "version": "0.61.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-0.61.0.tgz", + "integrity": "sha512-BYK9MPJPCf6d+fLKMTruThmEyCtHzQ1zLcsrTlUVkmnoXIaHAbfpeLYQwX1tkjs7W11dyzoi6HFvKcdnvX1zNg==", "cpu": [ "arm" ], @@ -206,9 +209,9 @@ } }, "node_modules/@oxfmt/binding-linux-arm64-gnu": { - "version": "0.46.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-0.46.0.tgz", - "integrity": "sha512-+TWipjrgVM8D7aIdDD0tlr3teLTTvQTn7QTE5BpT10H1Fj82gfdn9X6nn2sDgx/MepuSCfSnzFNJq2paLL0OiA==", + "version": "0.61.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-0.61.0.tgz", + "integrity": "sha512-QUaCNLq2/EC6G5ljOuFanl9Lgw6ZWp4co7rs4+KOMUzbGfA4Lq58FHRjjF9sVIG+93XSbo343MxFATrOU1qctA==", "cpu": [ "arm64" ], @@ -223,9 +226,9 @@ } }, "node_modules/@oxfmt/binding-linux-arm64-musl": { - "version": "0.46.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-musl/-/binding-linux-arm64-musl-0.46.0.tgz", - "integrity": "sha512-aAUPBWJ1lGwwnxZUEDLJ94+Iy6MuwJwPxUgO4sCA5mEEyDk7b+cDQ+JpX1VR150Zoyd+D49gsrUzpUK5h587Eg==", + "version": "0.61.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-musl/-/binding-linux-arm64-musl-0.61.0.tgz", + "integrity": "sha512-S6uvJ6MXnRXl+zTs0CARNDvkE+cymj0EVWEKKsyKnlLlqTyQJBjw5s4D2pSIOZc+S46cy4STefzcr/sm0VzVPA==", "cpu": [ "arm64" ], @@ -240,9 +243,9 @@ } }, "node_modules/@oxfmt/binding-linux-ppc64-gnu": { - "version": "0.46.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-0.46.0.tgz", - "integrity": "sha512-ufBCJukyFX/UDrokP/r6BGDoTInnsDs7bxyzKAgMiZlt2Qu8GPJSJ6Zm6whIiJzKk0naxA8ilwmbO1LMw6Htxw==", + "version": "0.61.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-0.61.0.tgz", + "integrity": "sha512-6VDlRcytvZG6UlSIdAFKDLbppo9tvPxrWzle6vHldYFMeuDPQEfMKrkwezp7FaBq1wik9ra554ZZeRPsyIkFpg==", "cpu": [ "ppc64" ], @@ -257,9 +260,9 @@ } }, "node_modules/@oxfmt/binding-linux-riscv64-gnu": { - "version": "0.46.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-0.46.0.tgz", - "integrity": "sha512-eqtlC2YmPqjun76R1gVfGLuKWx7NuEnLEAudZ7n6ipSKbCZTqIKSs1b5Y8K/JHZsRpLkeSmAAjig5HOIg8fQzQ==", + "version": "0.61.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-0.61.0.tgz", + "integrity": "sha512-KkBTYbzExpbmn15XjKPLu2fRV2PVlq+KWt+brad5rwIa03vdYoaDRWiS7raHII/dCTR6Ro4UpYUCH4t6lif4WQ==", "cpu": [ "riscv64" ], @@ -274,9 +277,9 @@ } }, "node_modules/@oxfmt/binding-linux-riscv64-musl": { - "version": "0.46.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-0.46.0.tgz", - "integrity": "sha512-yccVOO2nMXkQLGgy0He3EQEwKD7NF0zEk+/OWmroznkqXyJdN6bfK0LtNnr6/14Bh3FjpYq7bP33l/VloCnxpA==", + "version": "0.61.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-0.61.0.tgz", + "integrity": "sha512-69tzIq7sJLVB9dxYYtvMzcSSsnZHSO+U2U19O2RqDqgj6+Q4O7HjSXdaszbcgqzhsUwzSH7z5kWvk8nmf6BHTg==", "cpu": [ "riscv64" ], @@ -291,9 +294,9 @@ } }, "node_modules/@oxfmt/binding-linux-s390x-gnu": { - "version": "0.46.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-0.46.0.tgz", - "integrity": "sha512-aAf7fG23OQCey6VRPj9IeCraoYtpgtx0ZyJ1CXkPyT1wjzBE7c3xtuxHe/AdHaJfVVb/SXpSk8Gl1LzyQupSqw==", + "version": "0.61.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-0.61.0.tgz", + "integrity": "sha512-Oqi/N0OvtOVXsPKAOOhKgGH3msRYF8BLJaNBbWiupRiKoKVyc8JRKPCfarkQJC+RgP9U8raUKLe+bNwd0HUMiA==", "cpu": [ "s390x" ], @@ -308,9 +311,9 @@ } }, "node_modules/@oxfmt/binding-linux-x64-gnu": { - "version": "0.46.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-gnu/-/binding-linux-x64-gnu-0.46.0.tgz", - "integrity": "sha512-q0JPsTMyJNjYrBvYFDz4WbVsafNZaPCZv4RnFypRotLqpKROtBZcEaXQW4eb9YmvLU3NckVemLJnzkSZSdmOxw==", + "version": "0.61.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-gnu/-/binding-linux-x64-gnu-0.61.0.tgz", + "integrity": "sha512-3TKwv/ed4uwJSemAA8P9XcoqETpjQI4waquF9UilhA9Mn/dhr1PdUEXWlL74mtc6ZNfmKPA9+NEJm01nRF8CVA==", "cpu": [ "x64" ], @@ -325,9 +328,9 @@ } }, "node_modules/@oxfmt/binding-linux-x64-musl": { - "version": "0.46.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-musl/-/binding-linux-x64-musl-0.46.0.tgz", - "integrity": "sha512-7LsLY9Cw57GPkhSR+duI3mt9baRczK/DtHYSldQ4BEU92da9igBQNl4z7Vq5U9NNPsh1FmpKvv1q9WDtiUQR1A==", + "version": "0.61.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-musl/-/binding-linux-x64-musl-0.61.0.tgz", + "integrity": "sha512-uFso4u4nLkVSlMCpgjyvWV60Gt7GvDQHnk1mmRxHIkZTMB0ljpUKwCD9FYGgN9H97x2wYl0UwEjgRZaPIuhEhw==", "cpu": [ "x64" ], @@ -342,9 +345,9 @@ } }, "node_modules/@oxfmt/binding-openharmony-arm64": { - "version": "0.46.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-openharmony-arm64/-/binding-openharmony-arm64-0.46.0.tgz", - "integrity": "sha512-lHiBOz8Duaku7JtRNLlps3j++eOaICPZSd8FCVmTDM4DFOPT71Bjn7g6iar1z7StXlKRweUKxWUs4sA+zWGDXg==", + "version": "0.61.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-openharmony-arm64/-/binding-openharmony-arm64-0.61.0.tgz", + "integrity": "sha512-keGLkzeOvkMpNmPp4hffXWpfoSsY6e1K8++KXD4mSSfxdvM8q9QUDsYY689TB1k6Co832DZn1MnaaVx6cIBMWQ==", "cpu": [ "arm64" ], @@ -359,9 +362,9 @@ } }, "node_modules/@oxfmt/binding-win32-arm64-msvc": { - "version": "0.46.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-0.46.0.tgz", - "integrity": "sha512-/5ktYUliP89RhgC37DBH1x20U5zPSZMy3cMEcO0j3793rbHP9MWsknBwQB6eozRzWmYrh0IFM/p20EbPvDlYlg==", + "version": "0.61.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-0.61.0.tgz", + "integrity": "sha512-VzsAISkFxmNhJ5LBDEL9VuH6tJsVJMtqYit2LyIUf/HLnsCe4Pg9SMOjjVQzGWt0bnpyfJ94CrqTqcpNZzK+ug==", "cpu": [ "arm64" ], @@ -376,9 +379,9 @@ } }, "node_modules/@oxfmt/binding-win32-ia32-msvc": { - "version": "0.46.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-0.46.0.tgz", - "integrity": "sha512-3WTnoiuIr8XvV0DIY7SN+1uJSwKf4sPpcbHfobcRT9JutGcLaef/miyBB87jxd3aqH+mS0+G5lsgHuXLUwjjpQ==", + "version": "0.61.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-0.61.0.tgz", + "integrity": "sha512-xv4t7yzwJoYaLB6Zv28B3W+j7brEjsyv50rLTAQgmxJzddce9fAMCxed8dSAkbWES0zz2J29nYK5FaTuD2YBHg==", "cpu": [ "ia32" ], @@ -393,9 +396,9 @@ } }, "node_modules/@oxfmt/binding-win32-x64-msvc": { - "version": "0.46.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-x64-msvc/-/binding-win32-x64-msvc-0.46.0.tgz", - "integrity": "sha512-IXxiQpkYnOwNfP23vzwSfhdpxJzyiPTY7eTn6dn3DsriKddESzM8i6kfq9R7CD/PUJwCvQT22NgtygBeug3KoA==", + "version": "0.61.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-x64-msvc/-/binding-win32-x64-msvc-0.61.0.tgz", + "integrity": "sha512-6EZXFkqOwxdDYjIn3TSNnPk3ST5E5GiYd4FiM6UF/mCL/LZSfr6D6UygTfW3R1PCQP2quCKpCEGRlij8E3VYbg==", "cpu": [ "x64" ], @@ -410,9 +413,9 @@ } }, "node_modules/@oxlint/binding-android-arm-eabi": { - "version": "1.61.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm-eabi/-/binding-android-arm-eabi-1.61.0.tgz", - "integrity": "sha512-6eZBPgiigK5txqoVgRqxbaxiom4lM8AP8CyKPPvpzKnQ3iFRFOIDc+0AapF+qsUSwjOzr5SGk4SxQDpQhkSJMQ==", + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm-eabi/-/binding-android-arm-eabi-1.76.0.tgz", + "integrity": "sha512-ZHIE5Zt9AsPDcY4nOlofXt0YfneEeo+QrKMPcPzLf2Z6Q8VtV2W73d7SFJ920WUwyik783u/doKCs3KXdwG+7w==", "cpu": [ "arm" ], @@ -427,9 +430,9 @@ } }, "node_modules/@oxlint/binding-android-arm64": { - "version": "1.61.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm64/-/binding-android-arm64-1.61.0.tgz", - "integrity": "sha512-CkwLR69MUnyv5wjzebvbbtTSUwqLxM35CXE79bHqDIK+NtKmPEUpStTcLQRZMCo4MP0qRT6TXIQVpK0ZVScnMA==", + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm64/-/binding-android-arm64-1.76.0.tgz", + "integrity": "sha512-shm/ngQilHK6bs+ElJWa4oHfNj5vL1Gl/iVEJldTQjpr0/67oSgr0KUpbmcnLig5Fo0v/l6j2567A7TOL89ONA==", "cpu": [ "arm64" ], @@ -444,9 +447,9 @@ } }, "node_modules/@oxlint/binding-darwin-arm64": { - "version": "1.61.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-arm64/-/binding-darwin-arm64-1.61.0.tgz", - "integrity": "sha512-8JbefTkbmvqkqWjmQrHke+MdpgT2UghhD/ktM4FOQSpGeCgbMToJEKdl9zwhr/YWTl92i4QI1KiTwVExpcUN8A==", + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-arm64/-/binding-darwin-arm64-1.76.0.tgz", + "integrity": "sha512-rvJmrAPKSQ9aWJ6wIS6CK2tJjwzfW0ApQH9qokq6sfDvmHwoyIHxHFMq7z7i7GiV6fdE6s8qvBqWKPTu8RmT6Q==", "cpu": [ "arm64" ], @@ -461,9 +464,9 @@ } }, "node_modules/@oxlint/binding-darwin-x64": { - "version": "1.61.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-x64/-/binding-darwin-x64-1.61.0.tgz", - "integrity": "sha512-uWpoxDT47hTnDLcdEh5jVbso8rlTTu5o0zuqa9J8E0JAKmIWn7kGFEIB03Pycn2hd2vKxybPGLhjURy/9We5FQ==", + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-x64/-/binding-darwin-x64-1.76.0.tgz", + "integrity": "sha512-U/zYdb7VYKGY6pA9Vd2rYl9O/HlCylcOlb5PGPvVLtg+oLGsk6H3XGKEMHKyqD3nmmtmlmwb/8SwU2vfSAtvMw==", "cpu": [ "x64" ], @@ -478,9 +481,9 @@ } }, "node_modules/@oxlint/binding-freebsd-x64": { - "version": "1.61.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-freebsd-x64/-/binding-freebsd-x64-1.61.0.tgz", - "integrity": "sha512-K/o4hEyW7flfMel0iBVznmMBt7VIMHGdjADocHKpK1DUF9erpWnJ+BSSWd2W0c8K3mPtpph+CuHzRU6CI3l9jQ==", + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-freebsd-x64/-/binding-freebsd-x64-1.76.0.tgz", + "integrity": "sha512-WvKG9CAriuo0XNiFzpXjDngUZcRGFNpaK2kLyMUsnJlShxkT96u+BpJQ3KqdQwGOrvI14L6V8bAwXwAYNNY6Jg==", "cpu": [ "x64" ], @@ -495,9 +498,9 @@ } }, "node_modules/@oxlint/binding-linux-arm-gnueabihf": { - "version": "1.61.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.61.0.tgz", - "integrity": "sha512-P6040ZkcyweJ0Po9yEFqJCdvZnf3VNCGs1SIHgXDf8AAQNC6ID/heXQs9iSgo2FH7gKaKq32VWc59XZwL34C5Q==", + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.76.0.tgz", + "integrity": "sha512-qJ5+RH99TqFRq3UCDxkW0zJJu9c+OAHFY72vGlxZLEpuO+MpKo3POgqb8sYipL9KYm8XY6ofb0HsOuvY6hQNqQ==", "cpu": [ "arm" ], @@ -512,9 +515,9 @@ } }, "node_modules/@oxlint/binding-linux-arm-musleabihf": { - "version": "1.61.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-1.61.0.tgz", - "integrity": "sha512-bwxrGCzTZkuB+THv2TQ1aTkVEfv5oz8sl+0XZZCpoYzErJD8OhPQOTA0ENPd1zJz8QsVdSzSrS2umKtPq4/JXg==", + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-1.76.0.tgz", + "integrity": "sha512-PvPCVptkgVARsucgIqFQQcSmJ6xc6GtnVB5bRBekRahTc9eObMtjHfMjy5M+C2tHt5UCMttWM9RuSk/H9NqYeg==", "cpu": [ "arm" ], @@ -529,9 +532,9 @@ } }, "node_modules/@oxlint/binding-linux-arm64-gnu": { - "version": "1.61.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.61.0.tgz", - "integrity": "sha512-vkhb9/wKguMkLlrm3FoJW/Xmdv31GgYAE+x8lxxQ+7HeOxXUySI0q36a3NTVIuQUdLzxCI1zzMGsk1o37FOe3w==", + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.76.0.tgz", + "integrity": "sha512-3KeFDx8Bu4HPAXbuHZOr/oHvN+QT+JQhMw/NYPz7Z071xLSsG27Jfh9PIQVEY7hk1I+jr43ExqRIeJ6VKk2yLw==", "cpu": [ "arm64" ], @@ -546,9 +549,9 @@ } }, "node_modules/@oxlint/binding-linux-arm64-musl": { - "version": "1.61.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.61.0.tgz", - "integrity": "sha512-bl1dQh8LnVqsj6oOQAcxwbuOmNJkwc4p6o//HTBZhNTzJy21TLDwAviMqUFNUxDHkPGpmdKTSN4tWTjLryP8xg==", + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.76.0.tgz", + "integrity": "sha512-oPFkkKTgl0K/EIg9fQ8oA3IGcI05/Mq1en04iFa41mmNPT+6KEiByVazTOZZJiHMBBrbsns1YJ2e1Scqwzesjw==", "cpu": [ "arm64" ], @@ -563,9 +566,9 @@ } }, "node_modules/@oxlint/binding-linux-ppc64-gnu": { - "version": "1.61.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.61.0.tgz", - "integrity": "sha512-QoOX6KB2IiEpyOj/HKqaxi+NQHPnOgNgnr22n9N4ANJCzXkUlj1UmeAbFb4PpqdlHIzvGDM5xZ0OKtcLq9RhiQ==", + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.76.0.tgz", + "integrity": "sha512-gN7yZ0eqflA5Fhf1wvHxGUltIV3FsvmB1zhNMDEK9vSHhc7E6qg9CuPeBgPZab66Tjzq6w6kHAtNEvnTHf4cyw==", "cpu": [ "ppc64" ], @@ -580,9 +583,9 @@ } }, "node_modules/@oxlint/binding-linux-riscv64-gnu": { - "version": "1.61.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-1.61.0.tgz", - "integrity": "sha512-1TGcTerjY6p152wCof3oKElccq3xHljS/Mucp04gV/4ATpP6nO7YNnp7opEg6SHkv2a57/b4b8Ndm9znJ1/qAw==", + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-1.76.0.tgz", + "integrity": "sha512-S/HqMbn22mQrjtErUxEoS/a55u8kIeXvreIxiJu5G7Le3UecEd6SQZxrDIpuhtgaFnsY/nVra3ytP+pRljDilA==", "cpu": [ "riscv64" ], @@ -597,9 +600,9 @@ } }, "node_modules/@oxlint/binding-linux-riscv64-musl": { - "version": "1.61.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-1.61.0.tgz", - "integrity": "sha512-65wXEmZIrX2ADwC8i/qFL4EWLSbeuBpAm3suuX1vu4IQkKd+wLT/HU/BOl84kp91u2SxPkPDyQgu4yrqp8vwVA==", + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-1.76.0.tgz", + "integrity": "sha512-ZIga3097VJZolGZk6SrIAUokIGfRkxRlhiHDUznZptGBfwrhD7pNfD1rzEzsCwvk/1DX0A1bLz+liuNh5QKIVQ==", "cpu": [ "riscv64" ], @@ -614,9 +617,9 @@ } }, "node_modules/@oxlint/binding-linux-s390x-gnu": { - "version": "1.61.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.61.0.tgz", - "integrity": "sha512-TVvhgMvor7Qa6COeXxCJ7ENOM+lcAOGsQ0iUdPSCv2hxb9qSHLQ4XF1h50S6RE1gBOJ0WV3rNukg4JJJP1LWRA==", + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.76.0.tgz", + "integrity": "sha512-ZGiiA7pFzMJSyMWYZTVlPgbTsx+Vl8ihLGMIujPwaslUF7kIPPWAbVmAlTc+9lWDV+DCiB8Ikixu+lSHeOIIWQ==", "cpu": [ "s390x" ], @@ -631,9 +634,9 @@ } }, "node_modules/@oxlint/binding-linux-x64-gnu": { - "version": "1.61.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.61.0.tgz", - "integrity": "sha512-SjpS5uYuFoDnDdZPwZE59ndF95AsY47R5MliuneTWR1pDm2CxGJaYXbKULI71t5TVfLQUWmrHEGRL9xvuq6dnA==", + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.76.0.tgz", + "integrity": "sha512-JLiy5WuvEBFTT6ErIFV35SLzi0R7Iri6MKU6dZbTxfIx8pndbbPs3Mj780nMipBFcPkti+okAPOJ9POKkHFEgg==", "cpu": [ "x64" ], @@ -648,9 +651,9 @@ } }, "node_modules/@oxlint/binding-linux-x64-musl": { - "version": "1.61.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-musl/-/binding-linux-x64-musl-1.61.0.tgz", - "integrity": "sha512-gGfAeGD4sNJGILZbc/yKcIimO9wQnPMoYp9swAaKeEtwsSQAbU+rsdQze5SBtIP6j0QDzeYd4XSSUCRCF+LIeQ==", + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-musl/-/binding-linux-x64-musl-1.76.0.tgz", + "integrity": "sha512-z7lgKQtbo/I1NIe8G5NHLesxJDv0tRSUWTpXKb9Pm3E9nKFKfO4IOSDtFroKgXtOYb0jQbcdH+0wzTyMXVes+A==", "cpu": [ "x64" ], @@ -665,9 +668,9 @@ } }, "node_modules/@oxlint/binding-openharmony-arm64": { - "version": "1.61.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-openharmony-arm64/-/binding-openharmony-arm64-1.61.0.tgz", - "integrity": "sha512-OlVT0LrG/ct33EVtWRyR+B/othwmDWeRxfi13wUdPeb3lAT5TgTcFDcfLfarZtzB4W1nWF/zICMgYdkggX2WmQ==", + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-openharmony-arm64/-/binding-openharmony-arm64-1.76.0.tgz", + "integrity": "sha512-JOjKymIpb9QcYfEhZsN6h4V9Ivd474W38cNIBRv6bg2TbIvogbMTH0Mg6YWW9TiRDqfcX+/Hyfsbo5vcSE5guQ==", "cpu": [ "arm64" ], @@ -682,9 +685,9 @@ } }, "node_modules/@oxlint/binding-win32-arm64-msvc": { - "version": "1.61.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.61.0.tgz", - "integrity": "sha512-vI//NZPJk6DToiovPtaiwD4iQ7kO1r5ReWQD0sOOyKRtP3E2f6jxin4uvwi3OvDzHA2EFfd7DcZl5dtkQh7g1w==", + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.76.0.tgz", + "integrity": "sha512-pqDWZiwcmByWUEm1NFUBNiT6aentCcaoMWJv0HbXEmuYermJ4sg8ppVrshubYP2MZ6SHccJJcpr6x469PuDFIw==", "cpu": [ "arm64" ], @@ -699,9 +702,9 @@ } }, "node_modules/@oxlint/binding-win32-ia32-msvc": { - "version": "1.61.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-1.61.0.tgz", - "integrity": "sha512-0ySj4/4zd2XjePs3XAQq7IigIstN4LPQZgCyigX5/ERMLjdWAJfnxcTsrtxZxuij8guJW8foXuHmhGxW0H4dDA==", + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-1.76.0.tgz", + "integrity": "sha512-Ba0O659kgMv6pwO3z9PdO+K3aMxQRaw9HnG+e6AtOfgwcKFvYilciQYBoUBmxfQvOCKZe1SwjMkuB542NkuDMQ==", "cpu": [ "ia32" ], @@ -716,9 +719,9 @@ } }, "node_modules/@oxlint/binding-win32-x64-msvc": { - "version": "1.61.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.61.0.tgz", - "integrity": "sha512-0xgSiyeqDLDZxXoe9CVJrOx3TUVsfyoOY7cNi03JbItNcC9WCZqrSNdrAbHONxhSPaVh/lzfnDcON1RqSUMhHw==", + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.76.0.tgz", + "integrity": "sha512-5qcirPHO8nKfkoowEVWtpAoVTcYDy6g0UT0NGic450Qv8J2NrOqg4uQ8QppRP4MDTC7Xx47lbZnmadTH03CGGA==", "cpu": [ "x64" ], @@ -744,9 +747,9 @@ } }, "node_modules/@rolldown/binding-android-arm64": { - "version": "1.0.0-rc.17", - "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.0.0-rc.17.tgz", - "integrity": "sha512-s70pVGhw4zqGeFnXWvAzJDlvxhlRollagdCCKRgOsgUOH3N1l0LIxf83AtGzmb5SiVM4Hjl5HyarMRfdfj3DaQ==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.0.tgz", + "integrity": "sha512-9yB1l95IrJuNGDFdOYe79vdApdz6WWBCObE+rQ2LUliYUlcyFwSYIb2xb5/Ifw7dAtMy2ZqNyd8QTSOc7duAKw==", "cpu": [ "arm64" ], @@ -761,9 +764,9 @@ } }, "node_modules/@rolldown/binding-darwin-arm64": { - "version": "1.0.0-rc.17", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.0.0-rc.17.tgz", - "integrity": "sha512-4ksWc9n0mhlZpZ9PMZgTGjeOPRu8MB1Z3Tz0Mo02eWfWCHMW1zN82Qz/pL/rC+yQa+8ZnutMF0JjJe7PjwasYw==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.0.tgz", + "integrity": "sha512-pexNaW9ACLUOaBITOpU6qVu4VrsOFIjTv6bzgu0YUATo4eUJx0V605PxwZfndpPOn0ilqGqvGQ0M8UW0IE24jg==", "cpu": [ "arm64" ], @@ -778,9 +781,9 @@ } }, "node_modules/@rolldown/binding-darwin-x64": { - "version": "1.0.0-rc.17", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.0.0-rc.17.tgz", - "integrity": "sha512-SUSDOI6WwUVNcWxd02QEBjLdY1VPHvlEkw6T/8nYG322iYWCTxRb1vzk4E+mWWYehTp7ERibq54LSJGjmouOsw==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.0.tgz", + "integrity": "sha512-NqKYaq0355ZmNMG4QGpxtEDxsc7tGDhjhCm4PpE0cwnBW+5Il95LJyq414niEiaKLVjnVHBEjSo1wngKxJNiFw==", "cpu": [ "x64" ], @@ -795,9 +798,9 @@ } }, "node_modules/@rolldown/binding-freebsd-x64": { - "version": "1.0.0-rc.17", - "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.0.0-rc.17.tgz", - "integrity": "sha512-hwnz3nw9dbJ05EDO/PvcjaaewqqDy7Y1rn1UO81l8iIK1GjenME75dl16ajbvSSMfv66WXSRCYKIqfgq2KCfxw==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.0.tgz", + "integrity": "sha512-3vPoHzh6eBTz9IbB0/qZdSr0Qeks2echn+I4cHu2joV74VriPDdldswksEDzrl1mBB+oPRi+67+3Ib59paxIPQ==", "cpu": [ "x64" ], @@ -812,9 +815,9 @@ } }, "node_modules/@rolldown/binding-linux-arm-gnueabihf": { - "version": "1.0.0-rc.17", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.0.0-rc.17.tgz", - "integrity": "sha512-IS+W7epTcwANmFSQFrS1SivEXHtl1JtuQA9wlxrZTcNi6mx+FDOYrakGevvvTwgj2JvWiK8B29/qD9BELZPyXQ==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.0.tgz", + "integrity": "sha512-E6NNefZ1bUVmKJq2tJkf45J4Zyczj7qm9rUT7NY+Xo2474Y13qWAwc2tvBt0BAVbmtXR1llkxXg0Ou1jbDf2SQ==", "cpu": [ "arm" ], @@ -829,9 +832,9 @@ } }, "node_modules/@rolldown/binding-linux-arm64-gnu": { - "version": "1.0.0-rc.17", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.0.0-rc.17.tgz", - "integrity": "sha512-e6usGaHKW5BMNZOymS1UcEYGowQMWcgZ71Z17Sl/h2+ZziNJ1a9n3Zvcz6LdRyIW5572wBCTH/Z+bKuZouGk9Q==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.0.tgz", + "integrity": "sha512-D+TgkdgM1vu+7/Fpf8+v0ARW+RXEP9Ccazgm8zQ4JFFd9Q7SrYQ2TakU5S5ihazQDgpKyAgZDOcIFsvoHmTZ8w==", "cpu": [ "arm64" ], @@ -846,9 +849,9 @@ } }, "node_modules/@rolldown/binding-linux-arm64-musl": { - "version": "1.0.0-rc.17", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.0.0-rc.17.tgz", - "integrity": "sha512-b/CgbwAJpmrRLp02RPfhbudf5tZnN9nsPWK82znefso832etkem8H7FSZwxrOI9djcdTP7U6YfNhbRnh7djErg==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.0.tgz", + "integrity": "sha512-wUqdwJBbAv0APN87GecstdMUtLjjNTs0hBALpxETD73mccFxdmt/XeizXDtN5RAlBwNKmI+Tg+blect2G+8IeQ==", "cpu": [ "arm64" ], @@ -863,9 +866,9 @@ } }, "node_modules/@rolldown/binding-linux-ppc64-gnu": { - "version": "1.0.0-rc.17", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.0.0-rc.17.tgz", - "integrity": "sha512-4EII1iNGRUN5WwGbF/kOh/EIkoDN9HsupgLQoXfY+D1oyJm7/F4t5PYU5n8SWZgG0FEwakyM8pGgwcBYruGTlA==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.0.tgz", + "integrity": "sha512-9DtF35qR9/NrfhM4oxLplCzVVjE+KKm8Pjemi0i/sdhAWkUasjmSo8WTTubNJClhSHCfyk2yeyoXDQEDPtDAAw==", "cpu": [ "ppc64" ], @@ -880,9 +883,9 @@ } }, "node_modules/@rolldown/binding-linux-s390x-gnu": { - "version": "1.0.0-rc.17", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.0.0-rc.17.tgz", - "integrity": "sha512-AH8oq3XqQo4IibpVXvPeLDI5pzkpYn0WiZAfT05kFzoJ6tQNzwRdDYQ45M8I/gslbodRZwW8uxLhbSBbkv96rA==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.0.tgz", + "integrity": "sha512-RzuHrBh8X8Hntd2N4VR02QGEciq/9JhcZoTpR/Cee6otRrlILGCf3cg2ygHuih+ZebUnWmMrDX6ITI85btO6rQ==", "cpu": [ "s390x" ], @@ -897,9 +900,9 @@ } }, "node_modules/@rolldown/binding-linux-x64-gnu": { - "version": "1.0.0-rc.17", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.0.0-rc.17.tgz", - "integrity": "sha512-cLnjV3xfo7KslbU41Z7z8BH/E1y5mzUYzAqih1d1MDaIGZRCMqTijqLv76/P7fyHuvUcfGsIpqCdddbxLLK9rA==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.0.tgz", + "integrity": "sha512-MK7L0018jjh1jR3mh21G2j1zAVcpscJBlPo2z19pRjv2XOYGRhaV4LyiD8HO6nCDdZln9IFgCMIV5yt4E3klGQ==", "cpu": [ "x64" ], @@ -914,9 +917,9 @@ } }, "node_modules/@rolldown/binding-linux-x64-musl": { - "version": "1.0.0-rc.17", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.0.0-rc.17.tgz", - "integrity": "sha512-0phclDw1spsL7dUB37sIARuis2tAgomCJXAHZlpt8PXZ4Ba0dRP1e+66lsRqrfhISeN9bEGNjQs+T/Fbd7oYGw==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.0.tgz", + "integrity": "sha512-gyrxLQ9NfGb/9LoVnC4kb9miUghw1mghnkfYvNHSnVIXriabnfgGPUP4RLcJm87q3KgYz4FYUG8IDiWUT+CpSw==", "cpu": [ "x64" ], @@ -931,9 +934,9 @@ } }, "node_modules/@rolldown/binding-openharmony-arm64": { - "version": "1.0.0-rc.17", - "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.0.0-rc.17.tgz", - "integrity": "sha512-0ag/hEgXOwgw4t8QyQvUCxvEg+V0KBcA6YuOx9g0r02MprutRF5dyljgm3EmR02O292UX7UeS6HzWHAl6KgyhA==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.0.tgz", + "integrity": "sha512-/6VFMQGRmrhP77KXDC+StIxGzcNp5JOIyYtw0CQ8gPlzhpiIRucYfoM5FaFamHd5BJYIdH86yfP46l1p3WdrFA==", "cpu": [ "arm64" ], @@ -948,9 +951,9 @@ } }, "node_modules/@rolldown/binding-wasm32-wasi": { - "version": "1.0.0-rc.17", - "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.0.0-rc.17.tgz", - "integrity": "sha512-LEXei6vo0E5wTGwpkJ4KoT3OZJRnglwldt5ziLzOlc6qqb55z4tWNq2A+PFqCJuvWWdP53CVhG1Z9NtToDPJrA==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.2.0.tgz", + "integrity": "sha512-rwdbUL465kisF24WEJLvP3JrEG6E5GRuIHt5wpMwHGERtHe4Wm2CIvtf5gTBgr2tGOHKh5NdKEAFS2VkOPE91g==", "cpu": [ "wasm32" ], @@ -958,18 +961,52 @@ "license": "MIT", "optional": true, "dependencies": { - "@emnapi/core": "1.10.0", - "@emnapi/runtime": "1.10.0", - "@napi-rs/wasm-runtime": "^1.1.4" + "@emnapi/core": "1.11.2", + "@emnapi/runtime": "1.11.2", + "@napi-rs/wasm-runtime": "^1.1.6" }, "engines": { "node": "^20.19.0 || >=22.12.0" } }, + "node_modules/@rolldown/binding-wasm32-wasi/node_modules/@emnapi/core": { + "version": "1.11.2", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.2.tgz", + "integrity": "sha512-TC8MkTuZUtcTSiFeuC0ksCh9QIJ5+F21MvZ4Wn4ORfYaFJ/0dsiudv5tVkejgwZlwQ39jL9WWDe2lz8x0WglOA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "1.2.2", + "tslib": "^2.4.0" + } + }, + "node_modules/@rolldown/binding-wasm32-wasi/node_modules/@emnapi/runtime": { + "version": "1.11.2", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.2.tgz", + "integrity": "sha512-kyOl3X0DuTiT1h2ft8r2fYO8JYtU9a9Xis/zBSiGArNaagCOWx90N1k2wxp18czFDH+OgcWGb5ZP/XMt3dcyPA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@rolldown/binding-wasm32-wasi/node_modules/@emnapi/wasi-threads": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.2.tgz", + "integrity": "sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, "node_modules/@rolldown/binding-win32-arm64-msvc": { - "version": "1.0.0-rc.17", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.0.0-rc.17.tgz", - "integrity": "sha512-gUmyzBl3SPMa6hrqFUth9sVfcLBlYsbMzBx5PlexMroZStgzGqlZ26pYG89rBb45Mnia+oil6YAIFeEWGWhoZA==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.0.tgz", + "integrity": "sha512-+5suHwRiKGmhwyUaNT8a5QbrBvLFh2DbO910TEmGRH1aSxwrCezodvGQnulv4uiWEIv1Kq4ypRsJ5+O+ry1DiA==", "cpu": [ "arm64" ], @@ -984,9 +1021,9 @@ } }, "node_modules/@rolldown/binding-win32-x64-msvc": { - "version": "1.0.0-rc.17", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.0.0-rc.17.tgz", - "integrity": "sha512-3hkiolcUAvPB9FLb3UZdfjVVNWherN1f/skkGWJP/fgSQhYUZpSIRr0/I8ZK9TkF3F7kxvJAk0+IcKvPHk9qQg==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.0.tgz", + "integrity": "sha512-WfFv6/qGufotqBSBzBYwgpCkJBk8Nj7697LL9vTz/XWc67e0r3oewu8iMRwQj3AUL45GVD7wVsPjCsAAtW66Wg==", "cpu": [ "x64" ], @@ -1001,16 +1038,16 @@ } }, "node_modules/@rolldown/pluginutils": { - "version": "1.0.0-rc.17", - "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.17.tgz", - "integrity": "sha512-n8iosDOt6Ig1UhJ2AYqoIhHWh/isz0xpicHTzpKBeotdVsTEcxsSA/i3EVM7gQAj0rU27OLAxCjzlj15IWY7bg==", + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", + "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", "dev": true, "license": "MIT" }, "node_modules/@tybys/wasm-util": { - "version": "0.10.1", - "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.1.tgz", - "integrity": "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg==", + "version": "0.10.3", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.3.tgz", + "integrity": "sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg==", "dev": true, "license": "MIT", "optional": true, @@ -1025,13 +1062,353 @@ "license": "MIT" }, "node_modules/@types/node": { - "version": "25.5.0", - "resolved": "https://registry.npmjs.org/@types/node/-/node-25.5.0.tgz", - "integrity": "sha512-jp2P3tQMSxWugkCUKLRPVUpGaL5MVFwF8RDuSRztfwgN1wmqJeMSbKlnEtQqU8UrhTmzEmZdu2I6v2dpp7XIxw==", + "version": "26.1.2", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.1.2.tgz", + "integrity": "sha512-Vu4a5UFA9rIIFJ7rB/Vaafh9lrCQszopTCx6KjFboXTGQbPNasehVR5TEiithSDGyd1DEiUByggTZsg8jukeIg==", "dev": true, "license": "MIT", "dependencies": { - "undici-types": "~7.18.0" + "undici-types": "~8.3.0" + } + }, + "node_modules/@typescript/typescript-aix-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", + "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz", + "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz", + "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz", + "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz", + "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz", + "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz", + "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-loong64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz", + "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-mips64el": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz", + "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz", + "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-riscv64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz", + "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-s390x": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz", + "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz", + "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz", + "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz", + "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz", + "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz", + "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-sunos-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz", + "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz", + "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz", + "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" } }, "node_modules/ansi-regex": { @@ -1078,9 +1455,9 @@ "license": "MIT" }, "node_modules/brace-expansion": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", - "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.3.tgz", + "integrity": "sha512-DRdx5neNsG/QXbniLFWi2YmC/68oeOOmKz6zOjVk6ZS1ZLXgLIKqVEc6hWsmkjBbgii0SwaBTcJ5XKj5gzY/4A==", "dev": true, "license": "MIT", "dependencies": { @@ -1447,9 +1824,10 @@ } }, "node_modules/glob": { - "version": "10.4.5", - "resolved": "https://registry.npmjs.org/glob/-/glob-10.4.5.tgz", - "integrity": "sha512-7Bv8RF0k6xjo7d4A/PxYLbUCfb6c+Vpd2/mB2yRDlew7Jb5hEXiCD9ibfO7wpk8i4sevK6DFny9h7EYbM3/sHg==", + "version": "10.5.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-10.5.0.tgz", + "integrity": "sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==", + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", "dev": true, "license": "ISC", "dependencies": { @@ -1554,10 +1932,20 @@ } }, "node_modules/js-yaml": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", - "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.0.tgz", + "integrity": "sha512-1td788aAnnZ5qs7V2QIRl1owjtYpbKt749Y3xauqQgwIIGF/xXWz1wMTEBx5O3LK3lXLVuqXPdPxj2BoFHaW9Q==", "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], "license": "MIT", "dependencies": { "argparse": "^2.0.1" @@ -1607,13 +1995,13 @@ "license": "ISC" }, "node_modules/minimatch": { - "version": "9.0.5", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz", - "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==", + "version": "9.0.9", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz", + "integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==", "dev": true, "license": "ISC", "dependencies": { - "brace-expansion": "^2.0.1" + "brace-expansion": "^2.0.2" }, "engines": { "node": ">=16 || 14 >=14.17" @@ -1633,9 +2021,9 @@ } }, "node_modules/mocha": { - "version": "11.7.5", - "resolved": "https://registry.npmjs.org/mocha/-/mocha-11.7.5.tgz", - "integrity": "sha512-mTT6RgopEYABzXWFx+GcJ+ZQ32kp4fMf0xvpZIIfSq9Z8lC/++MtcCnQ9t5FP2veYEP95FIYSvW+U9fV4xrlig==", + "version": "11.7.6", + "resolved": "https://registry.npmjs.org/mocha/-/mocha-11.7.6.tgz", + "integrity": "sha512-nS9xOGbw2I3cjCpxwZAEJ9xK9lmJ08vEkQvLtz4du9ZrF9UrjRpeJGiIgl2Z+Qs++pmB4ecDe48Fwsh+j+j7xA==", "dev": true, "license": "MIT", "dependencies": { @@ -1693,9 +2081,9 @@ "license": "MIT" }, "node_modules/oxfmt": { - "version": "0.46.0", - "resolved": "https://registry.npmjs.org/oxfmt/-/oxfmt-0.46.0.tgz", - "integrity": "sha512-CopwJOwPAjZ9p76fCvz+mSOJTw9/NY3cSksZK3VO/bUQ8UoEcketNgUuYS0UB3p+R9XnXe7wGGXUmyFxc7QxJA==", + "version": "0.61.0", + "resolved": "https://registry.npmjs.org/oxfmt/-/oxfmt-0.61.0.tgz", + "integrity": "sha512-DxdHBEMYpcEnHoUHjjOigUqV2TYKsvxLwUPXnVYBjgFdqrcQ/91OtwubtZ2PUodCs3sStI8R5Qw3fKNGK4e8wQ==", "dev": true, "license": "MIT", "dependencies": { @@ -1711,31 +2099,43 @@ "url": "https://github.com/sponsors/Boshen" }, "optionalDependencies": { - "@oxfmt/binding-android-arm-eabi": "0.46.0", - "@oxfmt/binding-android-arm64": "0.46.0", - "@oxfmt/binding-darwin-arm64": "0.46.0", - "@oxfmt/binding-darwin-x64": "0.46.0", - "@oxfmt/binding-freebsd-x64": "0.46.0", - "@oxfmt/binding-linux-arm-gnueabihf": "0.46.0", - "@oxfmt/binding-linux-arm-musleabihf": "0.46.0", - "@oxfmt/binding-linux-arm64-gnu": "0.46.0", - "@oxfmt/binding-linux-arm64-musl": "0.46.0", - "@oxfmt/binding-linux-ppc64-gnu": "0.46.0", - "@oxfmt/binding-linux-riscv64-gnu": "0.46.0", - "@oxfmt/binding-linux-riscv64-musl": "0.46.0", - "@oxfmt/binding-linux-s390x-gnu": "0.46.0", - "@oxfmt/binding-linux-x64-gnu": "0.46.0", - "@oxfmt/binding-linux-x64-musl": "0.46.0", - "@oxfmt/binding-openharmony-arm64": "0.46.0", - "@oxfmt/binding-win32-arm64-msvc": "0.46.0", - "@oxfmt/binding-win32-ia32-msvc": "0.46.0", - "@oxfmt/binding-win32-x64-msvc": "0.46.0" + "@oxfmt/binding-android-arm-eabi": "0.61.0", + "@oxfmt/binding-android-arm64": "0.61.0", + "@oxfmt/binding-darwin-arm64": "0.61.0", + "@oxfmt/binding-darwin-x64": "0.61.0", + "@oxfmt/binding-freebsd-x64": "0.61.0", + "@oxfmt/binding-linux-arm-gnueabihf": "0.61.0", + "@oxfmt/binding-linux-arm-musleabihf": "0.61.0", + "@oxfmt/binding-linux-arm64-gnu": "0.61.0", + "@oxfmt/binding-linux-arm64-musl": "0.61.0", + "@oxfmt/binding-linux-ppc64-gnu": "0.61.0", + "@oxfmt/binding-linux-riscv64-gnu": "0.61.0", + "@oxfmt/binding-linux-riscv64-musl": "0.61.0", + "@oxfmt/binding-linux-s390x-gnu": "0.61.0", + "@oxfmt/binding-linux-x64-gnu": "0.61.0", + "@oxfmt/binding-linux-x64-musl": "0.61.0", + "@oxfmt/binding-openharmony-arm64": "0.61.0", + "@oxfmt/binding-win32-arm64-msvc": "0.61.0", + "@oxfmt/binding-win32-ia32-msvc": "0.61.0", + "@oxfmt/binding-win32-x64-msvc": "0.61.0" + }, + "peerDependencies": { + "svelte": "^5.0.0", + "vite-plus": "*" + }, + "peerDependenciesMeta": { + "svelte": { + "optional": true + }, + "vite-plus": { + "optional": true + } } }, "node_modules/oxlint": { - "version": "1.61.0", - "resolved": "https://registry.npmjs.org/oxlint/-/oxlint-1.61.0.tgz", - "integrity": "sha512-ZC0ALuhDZ6ivOFG+sy0D0pEDN49EvsId98zVlmYdkcXHsEM14m/qTNUEsUpiFiCVbpIxYtVBmmLE87nsbUHohQ==", + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/oxlint/-/oxlint-1.76.0.tgz", + "integrity": "sha512-6QoFioEU4fNdiUx/2Eo6TRd6NG7H7njnRCz8rhB66cZmMHDTqcm1Rjvl8Wry+ZTQMBAmyb4Mlf62Mk5X+eHSOw==", "dev": true, "license": "MIT", "bin": { @@ -1748,32 +2148,36 @@ "url": "https://github.com/sponsors/Boshen" }, "optionalDependencies": { - "@oxlint/binding-android-arm-eabi": "1.61.0", - "@oxlint/binding-android-arm64": "1.61.0", - "@oxlint/binding-darwin-arm64": "1.61.0", - "@oxlint/binding-darwin-x64": "1.61.0", - "@oxlint/binding-freebsd-x64": "1.61.0", - "@oxlint/binding-linux-arm-gnueabihf": "1.61.0", - "@oxlint/binding-linux-arm-musleabihf": "1.61.0", - "@oxlint/binding-linux-arm64-gnu": "1.61.0", - "@oxlint/binding-linux-arm64-musl": "1.61.0", - "@oxlint/binding-linux-ppc64-gnu": "1.61.0", - "@oxlint/binding-linux-riscv64-gnu": "1.61.0", - "@oxlint/binding-linux-riscv64-musl": "1.61.0", - "@oxlint/binding-linux-s390x-gnu": "1.61.0", - "@oxlint/binding-linux-x64-gnu": "1.61.0", - "@oxlint/binding-linux-x64-musl": "1.61.0", - "@oxlint/binding-openharmony-arm64": "1.61.0", - "@oxlint/binding-win32-arm64-msvc": "1.61.0", - "@oxlint/binding-win32-ia32-msvc": "1.61.0", - "@oxlint/binding-win32-x64-msvc": "1.61.0" + "@oxlint/binding-android-arm-eabi": "1.76.0", + "@oxlint/binding-android-arm64": "1.76.0", + "@oxlint/binding-darwin-arm64": "1.76.0", + "@oxlint/binding-darwin-x64": "1.76.0", + "@oxlint/binding-freebsd-x64": "1.76.0", + "@oxlint/binding-linux-arm-gnueabihf": "1.76.0", + "@oxlint/binding-linux-arm-musleabihf": "1.76.0", + "@oxlint/binding-linux-arm64-gnu": "1.76.0", + "@oxlint/binding-linux-arm64-musl": "1.76.0", + "@oxlint/binding-linux-ppc64-gnu": "1.76.0", + "@oxlint/binding-linux-riscv64-gnu": "1.76.0", + "@oxlint/binding-linux-riscv64-musl": "1.76.0", + "@oxlint/binding-linux-s390x-gnu": "1.76.0", + "@oxlint/binding-linux-x64-gnu": "1.76.0", + "@oxlint/binding-linux-x64-musl": "1.76.0", + "@oxlint/binding-openharmony-arm64": "1.76.0", + "@oxlint/binding-win32-arm64-msvc": "1.76.0", + "@oxlint/binding-win32-ia32-msvc": "1.76.0", + "@oxlint/binding-win32-x64-msvc": "1.76.0" }, "peerDependencies": { - "oxlint-tsgolint": ">=0.18.0" + "oxlint-tsgolint": ">=7.0.2001", + "vite-plus": "*" }, "peerDependenciesMeta": { "oxlint-tsgolint": { "optional": true + }, + "vite-plus": { + "optional": true } } }, @@ -1861,35 +2265,35 @@ "license": "ISC" }, "node_modules/playwright": { - "version": "1.59.1", - "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.59.1.tgz", - "integrity": "sha512-C8oWjPR3F81yljW9o5OxcWzfh6avkVwDD2VYdwIGqTkl+OGFISgypqzfu7dOe4QNLL2aqcWBmI3PMtLIK233lw==", + "version": "1.62.0", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.62.0.tgz", + "integrity": "sha512-Z14dG305dgaLu6foB1TXQagFiW8JfSUIUaUuPaKQ6NtBPKF1P/qXcqfh6c6K/icPqdy37JmjbiBXf6JNg6Sylw==", "dev": true, "license": "Apache-2.0", "dependencies": { - "playwright-core": "1.59.1" + "playwright-core": "1.62.0" }, "bin": { "playwright": "cli.js" }, "engines": { - "node": ">=18" + "node": ">=20" }, "optionalDependencies": { "fsevents": "2.3.2" } }, "node_modules/playwright-core": { - "version": "1.59.1", - "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.59.1.tgz", - "integrity": "sha512-HBV/RJg81z5BiiZ9yPzIiClYV/QMsDCKUyogwH9p3MCP6IYjUFu/MActgYAvK0oWyV9NlwM3GLBjADyWgydVyg==", + "version": "1.62.0", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.62.0.tgz", + "integrity": "sha512-nsNRyq0r2zsG8AcRHWknc9QRA5XCueC7gWMrs+Gx2tlZn9hcl8zudfh00lhJPY1DE7NmZ6bDsT9g2yey8mXljA==", "dev": true, "license": "Apache-2.0", "bin": { "playwright-core": "cli.js" }, "engines": { - "node": ">=18" + "node": ">=20" } }, "node_modules/randombytes": { @@ -1937,14 +2341,14 @@ } }, "node_modules/rolldown": { - "version": "1.0.0-rc.17", - "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.0.0-rc.17.tgz", - "integrity": "sha512-ZrT53oAKrtA4+YtBWPQbtPOxIbVDbxT0orcYERKd63VJTF13zPcgXTvD4843L8pcsI7M6MErt8QtON6lrB9tyA==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.0.tgz", + "integrity": "sha512-u7tgm5l4Yw1iTqUL4EcYOAt7fFvCgQMLeidrnD4GALlC6aOznCjezYajgxeyKw27u0Q5N7fwgCzjVyPIWzwuBA==", "dev": true, "license": "MIT", "dependencies": { - "@oxc-project/types": "=0.127.0", - "@rolldown/pluginutils": "1.0.0-rc.17" + "@oxc-project/types": "=0.140.0", + "@rolldown/pluginutils": "^1.0.0" }, "bin": { "rolldown": "bin/cli.mjs" @@ -1953,21 +2357,21 @@ "node": "^20.19.0 || >=22.12.0" }, "optionalDependencies": { - "@rolldown/binding-android-arm64": "1.0.0-rc.17", - "@rolldown/binding-darwin-arm64": "1.0.0-rc.17", - "@rolldown/binding-darwin-x64": "1.0.0-rc.17", - "@rolldown/binding-freebsd-x64": "1.0.0-rc.17", - "@rolldown/binding-linux-arm-gnueabihf": "1.0.0-rc.17", - "@rolldown/binding-linux-arm64-gnu": "1.0.0-rc.17", - "@rolldown/binding-linux-arm64-musl": "1.0.0-rc.17", - "@rolldown/binding-linux-ppc64-gnu": "1.0.0-rc.17", - "@rolldown/binding-linux-s390x-gnu": "1.0.0-rc.17", - "@rolldown/binding-linux-x64-gnu": "1.0.0-rc.17", - "@rolldown/binding-linux-x64-musl": "1.0.0-rc.17", - "@rolldown/binding-openharmony-arm64": "1.0.0-rc.17", - "@rolldown/binding-wasm32-wasi": "1.0.0-rc.17", - "@rolldown/binding-win32-arm64-msvc": "1.0.0-rc.17", - "@rolldown/binding-win32-x64-msvc": "1.0.0-rc.17" + "@rolldown/binding-android-arm64": "1.2.0", + "@rolldown/binding-darwin-arm64": "1.2.0", + "@rolldown/binding-darwin-x64": "1.2.0", + "@rolldown/binding-freebsd-x64": "1.2.0", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.0", + "@rolldown/binding-linux-arm64-gnu": "1.2.0", + "@rolldown/binding-linux-arm64-musl": "1.2.0", + "@rolldown/binding-linux-ppc64-gnu": "1.2.0", + "@rolldown/binding-linux-s390x-gnu": "1.2.0", + "@rolldown/binding-linux-x64-gnu": "1.2.0", + "@rolldown/binding-linux-x64-musl": "1.2.0", + "@rolldown/binding-openharmony-arm64": "1.2.0", + "@rolldown/binding-wasm32-wasi": "1.2.0", + "@rolldown/binding-win32-arm64-msvc": "1.2.0", + "@rolldown/binding-win32-x64-msvc": "1.2.0" } }, "node_modules/safe-buffer": { @@ -2185,9 +2589,9 @@ } }, "node_modules/tmp": { - "version": "0.2.5", - "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.5.tgz", - "integrity": "sha512-voyz6MApa1rQGUxT3E+BK7/ROe8itEx7vD8/HEvt4xwXucvQ5G5oeEiHkmHZJuBO21RpOf+YYm9MOivj709jow==", + "version": "0.2.7", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.7.tgz", + "integrity": "sha512-e0votIpp4Uo2AJYSzVHV6xCcawuiez3DzqDAbrTc3YxBkplN6e+dM13ZeIcZnDg/QpSuU2zfZ3rzwY8ukEnaXw==", "dev": true, "license": "MIT", "engines": { @@ -2202,23 +2606,44 @@ "license": "0BSD" }, "node_modules/typescript": { - "version": "6.0.3", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz", - "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==", + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz", + "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==", "dev": true, "license": "Apache-2.0", "bin": { - "tsc": "bin/tsc", - "tsserver": "bin/tsserver" + "tsc": "bin/tsc" }, "engines": { - "node": ">=14.17" + "node": ">=16.20.0" + }, + "optionalDependencies": { + "@typescript/typescript-aix-ppc64": "7.0.2", + "@typescript/typescript-darwin-arm64": "7.0.2", + "@typescript/typescript-darwin-x64": "7.0.2", + "@typescript/typescript-freebsd-arm64": "7.0.2", + "@typescript/typescript-freebsd-x64": "7.0.2", + "@typescript/typescript-linux-arm": "7.0.2", + "@typescript/typescript-linux-arm64": "7.0.2", + "@typescript/typescript-linux-loong64": "7.0.2", + "@typescript/typescript-linux-mips64el": "7.0.2", + "@typescript/typescript-linux-ppc64": "7.0.2", + "@typescript/typescript-linux-riscv64": "7.0.2", + "@typescript/typescript-linux-s390x": "7.0.2", + "@typescript/typescript-linux-x64": "7.0.2", + "@typescript/typescript-netbsd-arm64": "7.0.2", + "@typescript/typescript-netbsd-x64": "7.0.2", + "@typescript/typescript-openbsd-arm64": "7.0.2", + "@typescript/typescript-openbsd-x64": "7.0.2", + "@typescript/typescript-sunos-x64": "7.0.2", + "@typescript/typescript-win32-arm64": "7.0.2", + "@typescript/typescript-win32-x64": "7.0.2" } }, "node_modules/undici-types": { - "version": "7.18.2", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz", - "integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==", + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz", + "integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==", "dev": true, "license": "MIT" }, diff --git a/package.json b/package.json index 0a9a7dd..5076a6b 100755 --- a/package.json +++ b/package.json @@ -14,8 +14,8 @@ "luatests": "node --experimental-import-meta-resolve test/luatests.js", "build": "rolldown -c && tsc -d --emitDeclarationOnly --rootDir src --declarationDir dist", "clean": "rm -rf dist build", - "lint": "oxfmt --write . && oxlint --config .oxlintrc.json -D suspicious --import-plugin --node-plugin --promise-plugin --fix .", - "lint:nofix": "oxfmt --check . && oxlint --config .oxlintrc.json -D suspicious --import-plugin --node-plugin --promise-plugin ." + "lint": "oxfmt --write . && oxlint --config .oxlintrc.json --fix .", + "lint:nofix": "oxfmt --check . && oxlint --config .oxlintrc.json ." }, "files": [ "bin/*", @@ -45,13 +45,13 @@ "chai": "6.2.2", "chai-as-promised": "8.0.2", "fengari": "0.1.5", - "mocha": "11.7.5", - "oxfmt": "0.46.0", - "oxlint": "1.61.0", - "rolldown": "1.0.0-rc.17", + "mocha": "11.7.6", + "oxfmt": "0.61.0", + "oxlint": "1.76.0", + "playwright": "1.62.0", + "rolldown": "1.2.0", "tslib": "2.8.1", - "typescript": "6.0.3", - "playwright": "1.59.1" + "typescript": "7.0.2" }, "dependencies": { "@types/emscripten": "1.41.5" From d71f6c95256d11fc29dbca7a5bce153d809c1442 Mon Sep 17 00:00:00 2001 From: Gabriel Francisco Date: Tue, 28 Jul 2026 19:28:41 -0300 Subject: [PATCH 41/83] fix utf-8, stdio, and api changes again --- .github/workflows/test.yml | 2 +- .oxlintrc.json | 2 +- bench/comparisons.js | 12 +- bench/steps.js | 34 +- bin/wasmoon | 157 ++++++--- package.json | 8 + src/decoration.ts | 45 ++- src/engine.ts | 120 ------- src/global.ts | 221 ------------- src/index.ts | 45 ++- src/lua.ts | 46 --- src/module.ts | 442 ++++++++++++++----------- src/runtime.ts | 70 ++++ src/state.ts | 296 +++++++++++++++++ src/thread.ts | 288 +++++++++++----- src/type-extension.ts | 12 +- src/type-extensions/error.ts | 10 +- src/type-extensions/function.ts | 40 +-- src/type-extensions/null.ts | 10 +- src/type-extensions/promise.ts | 22 +- src/type-extensions/proxy.ts | 35 +- src/type-extensions/table.ts | 6 +- src/type-extensions/userdata.ts | 26 +- src/types.ts | 212 ++++++++++-- test/browser.test.js | 34 +- test/debug.js | 4 +- test/errors.test.js | 70 ++++ test/filesystem.test.js | 2 +- test/initialization.test.js | 127 ++++++- test/limits.test.js | 75 +++++ test/luatests.js | 14 +- test/node.test.js | 176 ++++++++-- test/nodefs.test.js | 54 +-- test/promises.test.js | 56 ++-- test/{engine.test.js => state.test.js} | 394 ++++++++++++++-------- test/utils.js | 8 +- utils/build-wasm.sh | 1 - 37 files changed, 2040 insertions(+), 1136 deletions(-) delete mode 100755 src/engine.ts delete mode 100755 src/global.ts delete mode 100755 src/lua.ts create mode 100755 src/runtime.ts create mode 100755 src/state.ts create mode 100644 test/errors.test.js create mode 100644 test/limits.test.js rename test/{engine.test.js => state.test.js} (73%) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index a588f0b..f0519f5 100755 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -10,7 +10,7 @@ jobs: strategy: matrix: - node-version: [22, 24] + node-version: [24] steps: - uses: actions/checkout@v7 diff --git a/.oxlintrc.json b/.oxlintrc.json index 676a206..d39faa0 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -17,7 +17,7 @@ }, "overrides": [ { - "files": ["test/**"], + "files": ["**/test/**"], "rules": { "no-unused-expressions": "off" } diff --git a/bench/comparisons.js b/bench/comparisons.js index 5b6dd14..20d81d3 100644 --- a/bench/comparisons.js +++ b/bench/comparisons.js @@ -1,4 +1,4 @@ -import { Lua } from '../dist/index.js' +import { LuaRuntime } from '../dist/index.js' import fengari from 'fengari' import { isMainModule, parseBenchOptions, readBenchAsset, runBenchmarks } from './utils.js' @@ -20,11 +20,11 @@ function createWasmoonIteration(lua) { return function runWasmoonIteration() { const state = lua.createState() try { - assertStatus(state.global.lua.luaL_loadstring(state.global.address, heapsort), 'Wasmoon load') - assertStatus(state.global.lua.lua_pcallk(state.global.address, 0, 1, 0, 0, null), 'Wasmoon compile') - assertStatus(state.global.lua.lua_pcallk(state.global.address, 0, 1, 0, 0, null), 'Wasmoon execute') + assertStatus(state.lua.luaL_loadstring(state.address, heapsort), 'Wasmoon load') + assertStatus(state.lua.lua_pcallk(state.address, 0, 1, 0, 0, null), 'Wasmoon compile') + assertStatus(state.lua.lua_pcallk(state.address, 0, 1, 0, 0, null), 'Wasmoon execute') } finally { - state.global.close() + state.close() } } } @@ -36,7 +36,7 @@ function assertStatus(status, label) { } export async function runComparisonBench(options = {}) { - const lua = await Lua.load() + const lua = await LuaRuntime.load() return runBenchmarks({ title: 'Comparison benchmarks', benches: [ diff --git a/bench/steps.js b/bench/steps.js index 568a4f6..8a6d8a8 100644 --- a/bench/steps.js +++ b/bench/steps.js @@ -1,4 +1,4 @@ -import { Lua } from '../dist/index.js' +import { LuaRuntime } from '../dist/index.js' import assert from 'node:assert/strict' import { isMainModule, parseBenchOptions, readBenchAsset, runBenchmarks } from './utils.js' @@ -39,7 +39,7 @@ function createComplexObjects() { function createStateBenchmark(lua, stateOptions = {}) { return function runCreateState() { const state = lua.createState(stateOptions) - state.global.close() + state.close() } } @@ -47,11 +47,11 @@ function createRawHeapsortBenchmark(lua) { return function runRawHeapsort() { const state = lua.createState() try { - assertStatus(state.global.lua.luaL_loadstring(state.global.address, heapsort), 'Load raw heapsort') - assertStatus(state.global.lua.lua_pcallk(state.global.address, 0, 1, 0, 0, null), 'Compile raw heapsort') - assertStatus(state.global.lua.lua_pcallk(state.global.address, 0, 1, 0, 0, null), 'Execute raw heapsort') + assertStatus(state.lua.luaL_loadstring(state.address, heapsort), 'Load raw heapsort') + assertStatus(state.lua.lua_pcallk(state.address, 0, 1, 0, 0, null), 'Compile raw heapsort') + assertStatus(state.lua.lua_pcallk(state.address, 0, 1, 0, 0, null), 'Execute raw heapsort') } finally { - state.global.close() + state.close() } } } @@ -63,7 +63,7 @@ function createInteropHeapsortBenchmark(lua) { const executeHeapsort = await state.doString(heapsort) assert.equal(executeHeapsort(), 10) } finally { - state.global.close() + state.close() } } } @@ -72,9 +72,9 @@ function createInsertObjectsBenchmark(lua, stateOptions = {}) { return function runInsertObjects() { const state = lua.createState(stateOptions) try { - state.global.set('obj', createComplexObjects()) + state.set('obj', createComplexObjects()) } finally { - state.global.close() + state.close() } } } @@ -84,9 +84,9 @@ function createGetObjectsBenchmark(lua) { const state = lua.createState() try { await state.doString(luaObjectFixture) - state.global.get('obj') + state.get('obj') } finally { - state.global.close() + state.close() } } } @@ -98,19 +98,19 @@ function assertStatus(status, label) { } export async function runStepBench(options = {}) { - const lua = await Lua.load() + const lua = await LuaRuntime.load() return runBenchmarks({ title: 'Operation benchmarks', benches: [ - { name: 'Create factory', run: () => Lua.load() }, + { name: 'Create factory', run: () => LuaRuntime.load() }, { name: 'Create state', run: createStateBenchmark(lua) }, { name: 'Create state without superpowers', run: createStateBenchmark(lua, { - enableProxy: false, - injectObjects: false, - openStandardLibs: false, + objects: 'copy', + inject: false, + libs: false, }), }, { name: 'Run raw heapsort', run: createRawHeapsortBenchmark(lua) }, @@ -119,7 +119,7 @@ export async function runStepBench(options = {}) { { name: 'Insert complex objects without proxy', run: createInsertObjectsBenchmark(lua, { - enableProxy: false, + objects: 'copy', }), }, { name: 'Get complex objects', run: createGetObjectsBenchmark(lua) }, diff --git a/bin/wasmoon b/bin/wasmoon index cc0138d..3479141 100755 --- a/bin/wasmoon +++ b/bin/wasmoon @@ -1,5 +1,5 @@ #!/usr/bin/env node -import { Lua, LuaReturn, LuaType, LUA_MULTRET, decorateProxy } from '../dist/index.js' +import { LuaRuntime, LuaReturn, LuaType, LUA_MULTRET, decorate } from '../dist/index.js' import pkg from '../package.json' with { type: 'json' } import fs from 'node:fs' import readline from 'node:readline' @@ -114,57 +114,107 @@ let inputFD = 0 if (process.stdin.isTTY) { try { inputFD = fs.openSync('/dev/tty', 'r') - } catch (e) { + } catch { // If opening /dev/tty fails (or on non-Unix systems), fallback to fd 0. inputFD = 0 } } -const rl = readline.createInterface({ - input: process.stdin, - output: process.stdout, - terminal: true, - removeHistoryDuplicates: true, - prompt: '> ', -}) +// Created only for the REPL: an open interface holds process.stdin in flowing mode, which both +// steals the bytes io.read is after and keeps the process alive after a script is done. +let rl = null +// Lua's io.read and the REPL share the terminal, so they can't be listening at the same time. +const pauseReadline = () => rl && !rl.closed && rl.pause() +const resumeReadline = () => rl && !rl.closed && rl.resume() + +// Bytes read past the end of a line: a single read can return more than one line, and dropping +// the remainder would lose input. +const inputChunk = Buffer.alloc(1024) +let pendingLength = 0 +let pendingOffset = 0 +// Set when a line ended on CR, so the LF of a CRLF pair doesn't start an empty line. +let skipLineFeed = false + +// Reading ahead in raw mode would strand whatever the user typed past the end of the line in here, +// where the REPL (which reads process.stdin) can never see it. +const refillInputChunk = (isRaw) => { + try { + pendingLength = fs.readSync(inputFD, inputChunk, 0, isRaw ? 1 : inputChunk.length) + } catch (err) { + // Both mean "nothing more right now", which for a blocking read is the end of the input. + if (err.code !== 'EOF' && err.code !== 'EAGAIN') { + throw err + } + pendingLength = 0 + } + pendingOffset = 0 + return pendingLength > 0 +} -const lua = await Lua.load({ +const lua = await LuaRuntime.load({ env: ignoreEnv ? undefined : process.env, fs: 'node', stdin: () => { try { - rl.pause() - - let buffer = Buffer.alloc(0xff) - let content = '' - let current = 0 - - while (true) { - const bytesRead = fs.readSync(inputFD, buffer, current, buffer.length - current) - if (bytesRead > 0) { - const charcode = buffer[current++] - if (charcode === 127) { - current = Math.max(0, current - 2) - } else { - if (charcode === 13) { - break - } + pauseReadline() + + // Raw mode is what the REPL puts the terminal in, and it comes with no echo and no + // line editing, so both have to be done by hand. Any other input already has them. + const isRaw = process.stdin.isRaw === true + const line = [] + let terminated = false + + while (!terminated) { + if (pendingOffset >= pendingLength && !refillInputChunk(isRaw)) { + break + } + + const charcode = inputChunk[pendingOffset++] + + if (skipLineFeed) { + skipLineFeed = false + if (charcode === 10) { + continue } + } - content = buffer.subarray(0, current).toString('utf8') - process.stdout.write('\x1b[2K') - process.stdout.write('\x1b[0G') - process.stdout.write(content) + if (charcode === 10 || charcode === 13) { + skipLineFeed = charcode === 13 + terminated = true + } else if (isRaw && (charcode === 127 || charcode === 8)) { + // Erase a whole character rather than a single byte, or a multi byte one would + // be left as an invalid sequence. + while (line.length > 0 && (line[line.length - 1] & 0xc0) === 0x80) { + line.pop() + } + line.pop() } else { - break + line.push(charcode) + } + + if (isRaw) { + const echo = Buffer.from(line).toString('utf8') + // A character whose remaining bytes are still on their way would flash as a + // replacement character, so leave it for the next redraw. + if (terminated) { + process.stdout.write('\n') + } else if (!echo.endsWith('�')) { + process.stdout.write(`\x1b[2K\x1b[0G${echo}`) + } } } - rl.resume() - return content + const content = Buffer.from(line).toString('utf8') + // Lua looks for the line break to know the line is complete, and reading raw mode + // input stripped it. Adding one at the end of the input would invent a line that + // isn't there. + return terminated ? `${content}\n` : content } catch (err) { // the error will not be thrown to the top, its better to log it console.error(err) + return '' + } finally { + resumeReadline() } }, }) @@ -172,12 +222,12 @@ const lua = await Lua.load({ const state = lua.createState() if (showVersion) { - console.log(`wasmoon ${pkg.version} (${state.global.get('_VERSION')})`) + console.log(`wasmoon ${pkg.version} (${state.get('_VERSION')})`) process.exit(0) } if (warnings) { - lua.module.lua_warning(state.global.address, '@on', 0) + lua.module.lua_warning(state.address, '@on', 0) } for (const module of includeModules) { @@ -185,8 +235,8 @@ for (const module of includeModules) { if (!mod) { mod = global } - const require = state.global.get('require') - state.global.set(global, require(mod)) + const require = state.get('require') + state.set(global, require(mod)) } for (const snippet of executeSnippets) { @@ -195,9 +245,10 @@ for (const snippet of executeSnippets) { // A real Lua table rather than a JS proxy, so `#arg` and `ipairs(arg)` behave like the // standalone interpreter. -state.global.set('arg', decorateProxy(scriptArgs, { proxy: false })) +state.set('arg', decorate(scriptArgs, { as: 'value' })) const isTTY = process.stdin.isTTY +const hasProgram = Boolean(scriptFile) || executeSnippets.length > 0 if (scriptFile === '-') { const input = fs.readFileSync(0, 'utf-8') @@ -206,19 +257,26 @@ if (scriptFile === '-') { await state.doFile(scriptFile) } -const shouldInteractive = isTTY && (forceInteractive || (!scriptFile && !executeSnippets.length)) +const shouldInteractive = isTTY && (forceInteractive || !hasProgram) if (shouldInteractive) { // Bypass result verification for interactive mode const loadcode = (code) => { - state.global.setTop(0) - return lua.module.luaL_loadstring(state.global.address, code) === LuaReturn.Ok + state.setTop(0) + return lua.module.luaL_loadstring(state.address, code) === LuaReturn.Ok } const version = pkg.version - const luaversion = state.global.get('_VERSION') + const luaversion = state.get('_VERSION') console.log(`Welcome to Wasmoon ${version} (${luaversion})`) console.log('Type Lua code and press Enter to execute. Ctrl+C to exit.\n') + rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + terminal: true, + removeHistoryDuplicates: true, + prompt: '> ', + }) rl.prompt() for await (const line of rl) { @@ -226,31 +284,32 @@ if (shouldInteractive) { const loaded = loadcode(`return ${line}`) || loadcode(line) if (!loaded) { // Failed to parse - const err = state.global.getValue(-1, LuaType.String) + const err = state.getValue(-1, LuaType.String) console.log(err) rl.prompt() continue } - const result = lua.module.lua_pcallk(state.global.address, 0, LUA_MULTRET, 0, 0, null) + const result = lua.module.lua_pcallk(state.address, 0, LUA_MULTRET, 0, 0, null) if (result === LuaReturn.Ok) { - const count = state.global.getTop() + const count = state.getTop() if (count > 0) { const returnValues = [] for (let i = 1; i <= count; i++) { - returnValues.push(state.global.indexToString(i)) + returnValues.push(state.indexToString(i)) } console.log(...returnValues) } } else { - console.log(state.global.getValue(-1, LuaType.String)) + console.log(state.getValue(-1, LuaType.String)) } rl.prompt() } -} else if (!scriptFile) { - // If we're not interactive, and we did NOT run a file, +} else if (!hasProgram) { + // If we're not interactive, and we did NOT run a file or any -e snippet, // read from stdin until EOF. (Non-TTY or no -i, no file). + // With -e, stdin belongs to the script, as in the standalone interpreter. const input = fs.readFileSync(0, 'utf-8') await state.doString(input) } diff --git a/package.json b/package.json index 5076a6b..45023dd 100755 --- a/package.json +++ b/package.json @@ -21,6 +21,14 @@ "bin/*", "dist/*" ], + "engines": { + "node": ">=24" + }, + "browserslist": [ + "chrome >= 134", + "firefox >= 138", + "safari >= 26" + ], "bin": { "wasmoon": "bin/wasmoon" }, diff --git a/src/decoration.ts b/src/decoration.ts index 4d54179..ff77c32 100755 --- a/src/decoration.ts +++ b/src/decoration.ts @@ -1,14 +1,45 @@ -export interface BaseDecorationOptions { - metatable?: Record -} +/** + * How a value should be marshalled into Lua. + * + * - `'userdata'` wraps it in an opaque userdata holding a JS reference, with no members exposed. + * - `'proxy'` wraps it in a userdata whose metatable forwards index/call back into JS. + * - `'value'` skips the proxy layer, so objects are copied into Lua tables and functions are + * pushed as plain Lua functions. + * + * Leaving it undefined keeps the default behaviour for the state's `objects` option. + */ +export type DecorationTarget = 'userdata' | 'proxy' | 'value' -export class Decoration { +export class Decoration { public constructor( public target: T, - public options: K, + public options: DecorationOptions, ) {} } -export function decorate(target: unknown, options: T): Decoration { - return new Decoration(target, options) +export interface DecorationOptions { + /** Metatable to attach to the pushed value, itself decoratable to control how it is pushed. */ + metatable?: Record | Decoration + as?: DecorationTarget + /** Function only: bound as the receiver, and dropped from the argument list. */ + self?: any + /** Function only: receives the calling thread as the first argument. */ + receiveThread?: boolean + /** + * Function only: receives the argument count instead of the decoded arguments, and is + * expected to read the stack itself. This is a raw-level escape hatch. + */ + receiveArgsQuantity?: boolean +} + +/** + * Attaches marshalling instructions to a value before pushing it into Lua. + * + * ```js + * state.set('opaque', decorate(new Thing(), { as: 'userdata' })) + * state.set('bound', decorate(thing.method, { self: thing })) + * ``` + */ +export function decorate(target: T, options: DecorationOptions = {}): Decoration { + return new Decoration(target, options) } diff --git a/src/engine.ts b/src/engine.ts deleted file mode 100755 index 8381ab8..0000000 --- a/src/engine.ts +++ /dev/null @@ -1,120 +0,0 @@ -import { CreateEngineOptions, LUA_REGISTRYINDEX } from './types' -import Global from './global' -import type LuaModule from './module' -import Thread from './thread' -import createErrorType from './type-extensions/error' -import createFunctionType from './type-extensions/function' -import createNullType from './type-extensions/null' -import createPromiseType from './type-extensions/promise' -import createProxyType from './type-extensions/proxy' -import createTableType from './type-extensions/table' -import createUserdataType from './type-extensions/userdata' - -export default class LuaEngine { - public global: Global - - public constructor( - private module: LuaModule, - { - openStandardLibs = true, - injectObjects = false, - enableProxy = true, - traceAllocations = false, - functionTimeout = undefined as number | undefined, - }: CreateEngineOptions = {}, - ) { - this.global = new Global(this.module, traceAllocations) - - // Generic handlers - These may be required to be registered for additional types. - this.global.registerTypeExtension(0, createTableType(this.global)) - this.global.registerTypeExtension(0, createFunctionType(this.global, { functionTimeout })) - - // Contains the :await functionality. - this.global.registerTypeExtension(1, createPromiseType(this.global, injectObjects)) - - if (injectObjects) { - // Should be higher priority than table since that catches generic objects along - // with userdata so it doesn't end up a userdata type. - this.global.registerTypeExtension(5, createNullType(this.global)) - } - - if (enableProxy) { - // This extension only really overrides tables and arrays. - // When a function is looked up in one of it's tables it's bound and then - // handled by the function type extension. - this.global.registerTypeExtension(3, createProxyType(this.global)) - } else { - // No need to register this when the proxy is enabled. - this.global.registerTypeExtension(1, createErrorType(this.global, injectObjects)) - } - - // Higher priority than proxied objects to allow custom user data without exposing methods. - this.global.registerTypeExtension(4, createUserdataType(this.global)) - - if (openStandardLibs) { - this.module.luaL_openlibs(this.global.address) - } - } - - /** - * Executes Lua code from a string asynchronously. - * @param script - Lua script to execute. - * @returns A Promise that resolves to the result returned by the Lua script execution. - */ - public doString(script: string): Promise { - return this.callByteCode((thread) => thread.loadString(script)) - } - - /** - * Executes Lua code from a file asynchronously. - * @param filename - Path to the Lua script file. - * @returns - A Promise that resolves to the result returned by the Lua script execution. - */ - public doFile(filename: string): Promise { - return this.callByteCode((thread) => thread.loadFile(filename)) - } - - /** - * Executes Lua code from a string synchronously. - * @param script - Lua script to execute. - * @returns - The result returned by the Lua script. - */ - public doStringSync(script: string): any { - return this.callByteCodeSync((thread) => thread.loadString(script)) - } - - /** - * Executes Lua code from a file synchronously. - * @param filename - Path to the Lua script file. - * @returns - The result returned by the Lua script. - */ - public doFileSync(filename: string): any { - return this.callByteCodeSync((thread) => thread.loadFile(filename)) - } - - private callByteCodeSync(loader: (thread: Thread) => void): any { - // Runs on the global thread, so leftovers would accumulate for the lifetime of the state. - // runSync has already converted the results to JS, and anything that has to outlive them - // holds its own registry reference. - const startStackTop = this.global.getTop() - try { - loader(this.global) - return this.global.runSync()[0] - } finally { - this.global.setTop(startStackTop) - } - } - - // WARNING: It will not wait for open handles and can potentially cause bugs if JS code tries to reference Lua after executed - private async callByteCode(loader: (thread: Thread) => void): Promise { - const thread = this.global.newThread() - // Move the thread off the global stack and into the registry as a GC anchor so it doesn't pile threads up into the stack - const ref = this.module.luaL_ref(this.global.address, LUA_REGISTRYINDEX) - try { - loader(thread) - return (await thread.run(0))[0] - } finally { - this.module.luaL_unref(this.global.address, LUA_REGISTRYINDEX, ref) - } - } -} diff --git a/src/global.ts b/src/global.ts deleted file mode 100755 index 428aed5..0000000 --- a/src/global.ts +++ /dev/null @@ -1,221 +0,0 @@ -import type LuaModule from './module' -import Thread from './thread' -import LuaTypeExtension from './type-extension' -import { LuaLibraries, LuaType } from './types' - -interface LuaMemoryStats { - memoryUsed: number - memoryMax?: number -} - -/** - * Represents the global state of the Lua engine. - */ -export default class Global extends Thread { - private memoryStats: LuaMemoryStats | undefined - private allocatorFunctionPointer: number | undefined - - /** - * Constructs a new Global instance. - * @param cmodule - The Lua module. - * @param shouldTraceAllocations - Whether to trace memory allocations. - */ - public constructor(cmodule: LuaModule, shouldTraceAllocations: boolean) { - if (shouldTraceAllocations) { - const memoryStats: LuaMemoryStats = { memoryUsed: 0 } - const allocatorFunctionPointer = cmodule._emscripten.addFunction( - (_userData: number, pointer: number, oldSize: number, newSize: number): number => { - if (newSize === 0) { - if (pointer) { - memoryStats.memoryUsed -= oldSize - cmodule._emscripten._free(pointer) - } - return 0 - } - - const endMemoryDelta = pointer ? newSize - oldSize : newSize - const endMemory = memoryStats.memoryUsed + endMemoryDelta - - if (newSize > oldSize && memoryStats.memoryMax && endMemory > memoryStats.memoryMax) { - return 0 - } - - const reallocated = cmodule._emscripten._realloc(pointer, newSize) - if (reallocated) { - memoryStats.memoryUsed = endMemory - } - return reallocated - }, - 'iiiii', - ) - - const address = cmodule.lua_newstate( - allocatorFunctionPointer, - null, - ((Date.now() >>> 0) ^ Math.floor(Math.random() * 0x100000000)) >>> 0, - ) - if (!address) { - cmodule._emscripten.removeFunction(allocatorFunctionPointer) - throw new Error('lua_newstate returned a null pointer') - } - super(cmodule, [], address) - - this.memoryStats = memoryStats - this.allocatorFunctionPointer = allocatorFunctionPointer - } else { - super(cmodule, [], cmodule.luaL_newstate()) - } - - if (this.isClosed()) { - throw new Error('Global state could not be created (probably due to lack of memory)') - } - } - - /** - * Closes the global state of the Lua engine. - */ - public close(): void { - if (this.isClosed()) { - return - } - - super.close() - - // Do this before removing the gc to force. - // Here rather than in the threads because you don't - // actually close threads, just pop them. Only the top-level - // lua state needs closing. - this.lua.lua_close(this.address) - - if (this.allocatorFunctionPointer) { - this.lua._emscripten.removeFunction(this.allocatorFunctionPointer) - } - - for (const wrapper of this.typeExtensions) { - wrapper.extension.close() - } - } - - /** - * Registers a type extension for Lua objects. - * Higher priority is more important and will be evaluated first. - * Allows library users to specify custom types - * @param priority - Priority of the type extension. - * @param extension - The type extension to register. - */ - public registerTypeExtension(priority: number, extension: LuaTypeExtension): void { - this.typeExtensions.push({ extension, priority }) - this.typeExtensions.sort((a, b) => b.priority - a.priority) - } - - /** - * Loads a default Lua library. - * @param library - The Lua library to load. - */ - public loadLibrary(library: LuaLibraries): void { - switch (library) { - case LuaLibraries.Base: - this.lua.luaopen_base(this.address) - break - case LuaLibraries.Coroutine: - this.lua.luaopen_coroutine(this.address) - break - case LuaLibraries.Table: - this.lua.luaopen_table(this.address) - break - case LuaLibraries.IO: - this.lua.luaopen_io(this.address) - break - case LuaLibraries.OS: - this.lua.luaopen_os(this.address) - break - case LuaLibraries.String: - this.lua.luaopen_string(this.address) - break - case LuaLibraries.UTF8: - this.lua.luaopen_utf8(this.address) - break - case LuaLibraries.Math: - this.lua.luaopen_math(this.address) - break - case LuaLibraries.Debug: - this.lua.luaopen_debug(this.address) - break - case LuaLibraries.Package: - this.lua.luaopen_package(this.address) - break - } - this.lua.lua_setglobal(this.address, library) - } - - /** - * Retrieves the value of a global variable. - * @param name - The name of the global variable. - * @returns - The value of the global variable. - */ - public get(name: string): any { - const type = this.lua.lua_getglobal(this.address, name) - const value = this.getValue(-1, type) - this.pop() - return value - } - - /** - * Sets the value of a global variable. - * @param name - The name of the global variable. - * @param value - The value to set for the global variable. - */ - public set(name: string, value: unknown): void { - this.pushValue(value) - this.lua.lua_setglobal(this.address, name) - } - - public getTable(name: string, callback: (index: number) => void): void { - const startStackTop = this.getTop() - const type = this.lua.lua_getglobal(this.address, name) - try { - if (type !== LuaType.Table) { - throw new TypeError(`Unexpected type in ${name}. Expected ${LuaType[LuaType.Table]}. Got ${LuaType[type]}.`) - } - callback(startStackTop + 1) - } finally { - // +1 for the table - if (this.getTop() !== startStackTop + 1) { - console.warn(`getTable: expected stack size ${startStackTop + 1} got ${this.getTop()}`) - } - this.setTop(startStackTop) - } - } - - /** - * Gets the amount of memory used by the Lua engine. Can only be used if the state was created with the `traceAllocations` option set to true. - * @returns - The amount of memory used in bytes. - */ - public getMemoryUsed(): number { - return this.getMemoryStatsRef().memoryUsed - } - - /** - * Gets the maximum memory allowed for the Lua engine. Can only be used if the state was created with the `traceAllocations` option set to true. - * @returns - The maximum memory allowed in bytes, or undefined if not set. - */ - public getMemoryMax(): number | undefined { - return this.getMemoryStatsRef().memoryMax - } - - /** - * Sets the maximum memory allowed for the Lua engine. Can only be used if the state was created with the `traceAllocations` option set to true. - * @param max - The maximum memory allowed in bytes, or undefined for unlimited. - */ - public setMemoryMax(max: number | undefined): void { - this.getMemoryStatsRef().memoryMax = max - } - - private getMemoryStatsRef(): LuaMemoryStats { - if (!this.memoryStats) { - throw new Error('Memory allocations is not being traced, please build engine with { traceAllocations: true }') - } - - return this.memoryStats - } -} diff --git a/src/index.ts b/src/index.ts index 11cb4a6..bd40719 100755 --- a/src/index.ts +++ b/src/index.ts @@ -1,18 +1,41 @@ -export { default as LuaEngine } from './engine' -export { default as Lua } from './lua' -export { default as LuaGlobal } from './global' +export { default as LuaRuntime } from './runtime' +export { default as LuaState, type LuaMemory } from './state' +export { default as LuaThread } from './thread' export { default as LuaMultiReturn } from './multireturn' export { default as LuaRawResult } from './raw-result' -export { default as LuaThread } from './thread' +export { decorate, Decoration, type DecorationOptions, type DecorationTarget } from './decoration' // Export the underlying bindings to allow users to just // use the bindings rather than the wrappers. -export { decorate, Decoration } from './decoration' export { default as LuaModule } from './module' export { default as LuaTypeExtension } from './type-extension' -export { decorateFunction } from './type-extensions/function' -export { decorateProxy } from './type-extensions/proxy' -export { decorateUserdata } from './type-extensions/userdata' -export * from './types' +// Named rather than `export *`, so the library bitmask helpers and the warn default stay internal. +export { + LuaError, + LuaInterruptError, + LuaTimeoutError, + LuaInstructionLimitError, + LuaAbortError, + LuaReturn, + LuaType, + LuaEventCodes, + LuaEventMasks, + LUA_MULTRET, + LUA_REGISTRYINDEX, + LUAI_MAXSTACK, + LUA_LIB_BITS, + type LuaAddress, + type LuaLibName, + type LuaLoadMode, + type LuaWarnHandler, + type CreateStateOptions, + type LuaMemoryOptions, + type LuaLimitOptions, + type LuaRunOptions, + type LuaLoadOptions, + type LuaDoOptions, + type LuaThreadLimits, + type LuaResumeResult, +} from './types' -import Lua from './lua' -export default Lua +import LuaRuntime from './runtime' +export default LuaRuntime diff --git a/src/lua.ts b/src/lua.ts deleted file mode 100755 index ac799de..0000000 --- a/src/lua.ts +++ /dev/null @@ -1,46 +0,0 @@ -import LuaModule from './module' -import LuaEngine from './engine' -import { CreateEngineOptions } from './types' - -/** - * Represents a factory for creating and configuring Lua engines. - */ -export default class Lua { - /** - * Constructs a new LuaFactory instance. - * @param opts.wasmFile - Custom URI for the Lua WebAssembly module. - * @param opts.env - Environment variables for the Lua engine. - * @param opts.stdin - Standard input for the Lua engine. - * @param opts.fs - File system that should be used for the Lua engine. - * @param opts.stdout - Standard output for the Lua engine. - * @param opts.stderr - Standard error for the Lua engine. - */ - public static async load(luaModuleOpts: Parameters[0] = {}): Promise { - return new Lua(await LuaModule.initialize(luaModuleOpts)) - } - - public constructor(public readonly module: LuaModule) {} - - public createState(stateOpts: CreateEngineOptions = {}): LuaEngine { - return new LuaEngine(this.module, stateOpts) - } - - /** - * Mounts a file in the Lua environment synchronously. - * @param path - Path to the file in the Lua environment. - * @param content - Content of the file to be mounted. - */ - public mountFile(path: string, content: string | ArrayBufferView): void { - const dirname = this.module._emscripten.PATH.dirname(path) - this.module._emscripten.FS.mkdirTree(dirname) - this.module._emscripten.FS.writeFile(path, content) - } - - public get filesystem(): typeof this.module._emscripten.FS { - return this.module._emscripten.FS - } - - public get path(): typeof this.module._emscripten.PATH { - return this.module._emscripten.PATH - } -} diff --git a/src/module.ts b/src/module.ts index f9f92a0..4f46613 100755 --- a/src/module.ts +++ b/src/module.ts @@ -1,5 +1,5 @@ import initWasmModule from '../build/glue.js' -import { LUA_REGISTRYINDEX, LuaReturn, LuaState, LuaType, PointerSize } from './types.js' +import { defaultWarnHandler, LUA_REGISTRYINDEX, LuaAddress, LuaReturn, LuaType, LuaWarnHandler, PointerSize } from './types.js' // A rolldown plugin will resolve this to the current version on package.json import version from 'package-version' @@ -24,12 +24,16 @@ interface LuaEmscriptenModule extends EmscriptenModule { stringToNewUTF8: typeof stringToNewUTF8 lengthBytesUTF8: typeof lengthBytesUTF8 stringToUTF8: typeof stringToUTF8 - intArrayFromString: typeof intArrayFromString UTF8ToString: typeof UTF8ToString ENV: EnvironmentVariables _realloc: (pointer: number, size: number) => number } +// One-shot conversions, so a single stateless pair is shared by every module. Streaming output +// keeps its own decoder in createOutputWriter. +const textDecoder = new TextDecoder() +const textEncoder = new TextEncoder() + // Above this a dedicated allocation is used, so one huge string cannot permanently retain the // scratch buffer. const REUSABLE_STRING_BUFFER_LIMIT = 64 * 1024 @@ -47,10 +51,16 @@ export default class LuaModule { env?: EnvironmentVariables fs?: 'node' | 'memory' fsMountPaths?: string[] - stdin?: () => string + // Called once per read, and an empty string (or nothing) means EOF. + stdin?: () => string | null | undefined + // Called with each completed line, without the line break, and with a partial line when + // Lua flushes or suspends in the middle of one. stdout?: (content: string) => void stderr?: (content: string) => void + /** Where load time diagnostics go. Defaults to `console.warn`. */ + onWarn?: LuaWarnHandler }): Promise { + const warn = opts.onWarn ?? defaultWarnHandler const isBrowser = (typeof window === 'object' && typeof window.document !== 'undefined') || (typeof self === 'object' && self?.constructor?.name === 'DedicatedWorkerGlobalScope') @@ -115,7 +125,7 @@ export default class LuaModule { // (string .code) and Emscripten ErrnoError (numeric .errno) const isIgnorableError = ['EACCES', 'EPERM', 'ENOENT'].includes(err?.code) || err?.name === 'ErrnoError' if (!isIgnorableError) { - console.warn(`Failed to mount ${dir}:`, err) + warn(`Failed to mount ${dir}`, err) } } } @@ -128,28 +138,8 @@ export default class LuaModule { } if (opts.stdin || opts.stdout || opts.stderr) { - let bufferedInput: number[] | undefined initializedModule.FS.init( - opts.stdin - ? () => { - if (!bufferedInput) { - const input = opts.stdin?.() - if (typeof input === 'string') { - bufferedInput = initializedModule.intArrayFromString(input, true).concat([0]) - } else { - throw new Error('stdin must return a string') - } - } - - if (bufferedInput!.length === 0) { - bufferedInput = undefined - return null - } - - const item = bufferedInput!.shift() - return !item || item === 0 ? null : item - } - : null, + createInputReader(opts.stdin), createOutputWriter(opts.stdout), createOutputWriter(opts.stderr), ) @@ -161,159 +151,159 @@ export default class LuaModule { public _emscripten: LuaEmscriptenModule - public luaL_checkversion_: (L: LuaState, ver: number, sz: number) => void - public luaL_getmetafield: (L: LuaState, obj: number, e: string | null) => LuaType - public luaL_callmeta: (L: LuaState, obj: number, e: string | null) => number - public luaL_argerror: (L: LuaState, arg: number, extramsg: string | null) => number - public luaL_typeerror: (L: LuaState, arg: number, tname: string | null) => number - public luaL_checklstring: (L: LuaState, arg: number, l: number | null) => string - public luaL_optlstring: (L: LuaState, arg: number, def: string | null, l: number | null) => string - public luaL_checknumber: (L: LuaState, arg: number) => number - public luaL_optnumber: (L: LuaState, arg: number, def: number) => number - public luaL_checkinteger: (L: LuaState, arg: number) => number - public luaL_optinteger: (L: LuaState, arg: number, def: number) => number - public luaL_checkstack: (L: LuaState, sz: number, msg: string | null) => void - public luaL_checktype: (L: LuaState, arg: number, t: number) => void - public luaL_checkany: (L: LuaState, arg: number) => void - public luaL_newmetatable: (L: LuaState, tname: string | null) => number - public luaL_setmetatable: (L: LuaState, tname: string | null) => void - public luaL_testudata: (L: LuaState, ud: number, tname: string | null) => number - public luaL_checkudata: (L: LuaState, ud: number, tname: string | null) => number - public luaL_where: (L: LuaState, lvl: number) => void - public luaL_fileresult: (L: LuaState, stat: number, fname: string | null) => number - public luaL_execresult: (L: LuaState, stat: number) => number - public luaL_ref: (L: LuaState, t: number) => number - public luaL_unref: (L: LuaState, t: number, ref: number) => void - public luaL_loadfilex: (L: LuaState, filename: string | null, mode: string | null) => LuaReturn + public luaL_checkversion_: (L: LuaAddress, ver: number, sz: number) => void + public luaL_getmetafield: (L: LuaAddress, obj: number, e: string | null) => LuaType + public luaL_callmeta: (L: LuaAddress, obj: number, e: string | null) => number + public luaL_argerror: (L: LuaAddress, arg: number, extramsg: string | null) => number + public luaL_typeerror: (L: LuaAddress, arg: number, tname: string | null) => number + public luaL_checklstring: (L: LuaAddress, arg: number, l: number | null) => string + public luaL_optlstring: (L: LuaAddress, arg: number, def: string | null, l: number | null) => string + public luaL_checknumber: (L: LuaAddress, arg: number) => number + public luaL_optnumber: (L: LuaAddress, arg: number, def: number) => number + public luaL_checkinteger: (L: LuaAddress, arg: number) => number + public luaL_optinteger: (L: LuaAddress, arg: number, def: number) => number + public luaL_checkstack: (L: LuaAddress, sz: number, msg: string | null) => void + public luaL_checktype: (L: LuaAddress, arg: number, t: number) => void + public luaL_checkany: (L: LuaAddress, arg: number) => void + public luaL_newmetatable: (L: LuaAddress, tname: string | null) => number + public luaL_setmetatable: (L: LuaAddress, tname: string | null) => void + public luaL_testudata: (L: LuaAddress, ud: number, tname: string | null) => number + public luaL_checkudata: (L: LuaAddress, ud: number, tname: string | null) => number + public luaL_where: (L: LuaAddress, lvl: number) => void + public luaL_fileresult: (L: LuaAddress, stat: number, fname: string | null) => number + public luaL_execresult: (L: LuaAddress, stat: number) => number + public luaL_ref: (L: LuaAddress, t: number) => number + public luaL_unref: (L: LuaAddress, t: number, ref: number) => void + public luaL_loadfilex: (L: LuaAddress, filename: string | null, mode: string | null) => LuaReturn public luaL_loadbufferx: ( - L: LuaState, + L: LuaAddress, buff: string | number | null, sz: number, name: string | number | null, mode: string | null, ) => LuaReturn - public luaL_loadstring: (L: LuaState, s: string | null) => LuaReturn - public luaL_newstate: () => LuaState - public luaL_len: (L: LuaState, idx: number) => number + public luaL_loadstring: (L: LuaAddress, s: string | null) => LuaReturn + public luaL_newstate: () => LuaAddress + public luaL_len: (L: LuaAddress, idx: number) => number public luaL_addgsub: (b: number | null, s: string | null, p: string | null, r: string | null) => void - public luaL_gsub: (L: LuaState, s: string | null, p: string | null, r: string | null) => string - public luaL_setfuncs: (L: LuaState, l: number | null, nup: number) => void - public luaL_getsubtable: (L: LuaState, idx: number, fname: string | null) => number - public luaL_traceback: (L: LuaState, L1: LuaState, msg: string | null, level: number) => void - public luaL_requiref: (L: LuaState, modname: string | null, openf: number, glb: number) => void - public luaL_openselectedlibs: (L: LuaState, load: number, preload: number) => void - public luaL_buffinit: (L: LuaState, B: number | null) => void + public luaL_gsub: (L: LuaAddress, s: string | null, p: string | null, r: string | null) => string + public luaL_setfuncs: (L: LuaAddress, l: number | null, nup: number) => void + public luaL_getsubtable: (L: LuaAddress, idx: number, fname: string | null) => number + public luaL_traceback: (L: LuaAddress, L1: LuaAddress, msg: string | null, level: number) => void + public luaL_requiref: (L: LuaAddress, modname: string | null, openf: number, glb: number) => void + public luaL_openselectedlibs: (L: LuaAddress, load: number, preload: number) => void + public luaL_buffinit: (L: LuaAddress, B: number | null) => void public luaL_prepbuffsize: (B: number | null, sz: number) => string public luaL_addlstring: (B: number | null, s: string | null, l: number) => void public luaL_addstring: (B: number | null, s: string | null) => void public luaL_addvalue: (B: number | null) => void public luaL_pushresult: (B: number | null) => void public luaL_pushresultsize: (B: number | null, sz: number) => void - public luaL_buffinitsize: (L: LuaState, B: number | null, sz: number) => string - public lua_newstate: (f: number | null, ud: number | null, seed: number) => LuaState - public lua_close: (L: LuaState) => void - public lua_newthread: (L: LuaState) => LuaState - public lua_closethread: (L: LuaState, from: LuaState | null) => LuaReturn - public lua_resetthread: (L: LuaState) => LuaReturn - public lua_atpanic: (L: LuaState, panicf: number) => number - public lua_version: (L: LuaState) => number - public lua_absindex: (L: LuaState, idx: number) => number - public lua_gettop: (L: LuaState) => number - public lua_settop: (L: LuaState, idx: number) => void - public lua_pushvalue: (L: LuaState, idx: number) => void - public lua_rotate: (L: LuaState, idx: number, n: number) => void - public lua_copy: (L: LuaState, fromidx: number, toidx: number) => void - public lua_checkstack: (L: LuaState, n: number) => number - public lua_xmove: (from: LuaState, to: LuaState, n: number) => void - public lua_isnumber: (L: LuaState, idx: number) => number - public lua_isstring: (L: LuaState, idx: number) => number - public lua_iscfunction: (L: LuaState, idx: number) => number - public lua_isinteger: (L: LuaState, idx: number) => number - public lua_isuserdata: (L: LuaState, idx: number) => number - public lua_type: (L: LuaState, idx: number) => LuaType - public lua_typename: (L: LuaState, tp: number) => string - public lua_tonumberx: (L: LuaState, idx: number, isnum: number | null) => number - public lua_tointegerx: (L: LuaState, idx: number, isnum: number | null) => bigint - public lua_toboolean: (L: LuaState, idx: number) => number - public lua_rawlen: (L: LuaState, idx: number) => bigint - public lua_tocfunction: (L: LuaState, idx: number) => number - public lua_touserdata: (L: LuaState, idx: number) => number - public lua_tothread: (L: LuaState, idx: number) => LuaState - public lua_topointer: (L: LuaState, idx: number) => number - public lua_arith: (L: LuaState, op: number) => void - public lua_rawequal: (L: LuaState, idx1: number, idx2: number) => number - public lua_compare: (L: LuaState, idx1: number, idx2: number, op: number) => number - public lua_pushnil: (L: LuaState) => void - public lua_pushnumber: (L: LuaState, n: number) => void - public lua_pushinteger: (L: LuaState, n: bigint) => void - public lua_pushlstring: (L: LuaState, s: number, len: number) => void - public lua_pushcclosure: (L: LuaState, fn: number, n: number) => void - public lua_pushboolean: (L: LuaState, b: number) => void - public lua_pushlightuserdata: (L: LuaState, p: number | null) => void - public lua_pushthread: (L: LuaState) => number - public lua_getglobal: (L: LuaState, name: string | null) => LuaType - public lua_gettable: (L: LuaState, idx: number) => LuaType - public lua_getfield: (L: LuaState, idx: number, k: string | null) => LuaType - public lua_geti: (L: LuaState, idx: number, n: bigint) => LuaType - public lua_rawget: (L: LuaState, idx: number) => number - public lua_rawgeti: (L: LuaState, idx: number, n: bigint) => LuaType - public lua_rawgetp: (L: LuaState, idx: number, p: number | null) => LuaType - public lua_createtable: (L: LuaState, narr: number, nrec: number) => void - public lua_newuserdatauv: (L: LuaState, sz: number, nuvalue: number) => number - public lua_getmetatable: (L: LuaState, objindex: number) => number - public lua_getiuservalue: (L: LuaState, idx: number, n: number) => LuaType - public lua_setglobal: (L: LuaState, name: string | null) => void - public lua_settable: (L: LuaState, idx: number) => void - public lua_setfield: (L: LuaState, idx: number, k: string | null) => void - public lua_seti: (L: LuaState, idx: number, n: bigint) => void - public lua_rawset: (L: LuaState, idx: number) => void - public lua_rawseti: (L: LuaState, idx: number, n: bigint) => void - public lua_rawsetp: (L: LuaState, idx: number, p: number | null) => void - public lua_setmetatable: (L: LuaState, objindex: number) => number - public lua_setiuservalue: (L: LuaState, idx: number, n: number) => number - public lua_callk: (L: LuaState, nargs: number, nresults: number, ctx: number, k: number | null) => void - public lua_pcallk: (L: LuaState, nargs: number, nresults: number, errfunc: number, ctx: number, k: number | null) => number - public lua_load: (L: LuaState, reader: number | null, dt: number | null, chunkname: string | null, mode: string | null) => LuaReturn - public lua_dump: (L: LuaState, writer: number | null, data: number | null, strip: number) => number - public lua_yieldk: (L: LuaState, nresults: number, ctx: number, k: number | null) => number - public lua_resume: (L: LuaState, from: LuaState | null, narg: number, nres: number | null) => LuaReturn - public lua_status: (L: LuaState) => LuaReturn - public lua_isyieldable: (L: LuaState) => number - public lua_setwarnf: (L: LuaState, f: number | null, ud: number | null) => void - public lua_warning: (L: LuaState, msg: string | null, tocont: number) => void - public lua_error: (L: LuaState) => number - public lua_next: (L: LuaState, idx: number) => number - public lua_concat: (L: LuaState, n: number) => void - public lua_len: (L: LuaState, idx: number) => void - public lua_stringtonumber: (L: LuaState, s: string | null) => number - public lua_getallocf: (L: LuaState, ud: number | null) => number - public lua_setallocf: (L: LuaState, f: number | null, ud: number | null) => void - public lua_toclose: (L: LuaState, idx: number) => void - public lua_closeslot: (L: LuaState, idx: number) => void - public lua_getstack: (L: LuaState, level: number, ar: number | null) => number - public lua_getinfo: (L: LuaState, what: string | null, ar: number | null) => number - public lua_getlocal: (L: LuaState, ar: number | null, n: number) => string - public lua_setlocal: (L: LuaState, ar: number | null, n: number) => string - public lua_getupvalue: (L: LuaState, funcindex: number, n: number) => string - public lua_setupvalue: (L: LuaState, funcindex: number, n: number) => string - public lua_upvalueid: (L: LuaState, fidx: number, n: number) => number - public lua_upvaluejoin: (L: LuaState, fidx1: number, n1: number, fidx2: number, n2: number) => void - public lua_sethook: (L: LuaState, func: number | null, mask: number, count: number) => void - public lua_gethook: (L: LuaState) => number - public lua_gethookmask: (L: LuaState) => number - public lua_gethookcount: (L: LuaState) => number - public lua_setcstacklimit: (_L: LuaState, _limit: number) => number - public luaopen_base: (L: LuaState) => number - public luaopen_coroutine: (L: LuaState) => number - public luaopen_table: (L: LuaState) => number - public luaopen_io: (L: LuaState) => number - public luaopen_os: (L: LuaState) => number - public luaopen_string: (L: LuaState) => number - public luaopen_utf8: (L: LuaState) => number - public luaopen_math: (L: LuaState) => number - public luaopen_debug: (L: LuaState) => number - public luaopen_package: (L: LuaState) => number - public luaL_openlibs: (L: LuaState) => void + public luaL_buffinitsize: (L: LuaAddress, B: number | null, sz: number) => string + public lua_newstate: (f: number | null, ud: number | null, seed: number) => LuaAddress + public lua_close: (L: LuaAddress) => void + public lua_newthread: (L: LuaAddress) => LuaAddress + public lua_closethread: (L: LuaAddress, from: LuaAddress | null) => LuaReturn + public lua_resetthread: (L: LuaAddress) => LuaReturn + public lua_atpanic: (L: LuaAddress, panicf: number) => number + public lua_version: (L: LuaAddress) => number + public lua_absindex: (L: LuaAddress, idx: number) => number + public lua_gettop: (L: LuaAddress) => number + public lua_settop: (L: LuaAddress, idx: number) => void + public lua_pushvalue: (L: LuaAddress, idx: number) => void + public lua_rotate: (L: LuaAddress, idx: number, n: number) => void + public lua_copy: (L: LuaAddress, fromidx: number, toidx: number) => void + public lua_checkstack: (L: LuaAddress, n: number) => number + public lua_xmove: (from: LuaAddress, to: LuaAddress, n: number) => void + public lua_isnumber: (L: LuaAddress, idx: number) => number + public lua_isstring: (L: LuaAddress, idx: number) => number + public lua_iscfunction: (L: LuaAddress, idx: number) => number + public lua_isinteger: (L: LuaAddress, idx: number) => number + public lua_isuserdata: (L: LuaAddress, idx: number) => number + public lua_type: (L: LuaAddress, idx: number) => LuaType + public lua_typename: (L: LuaAddress, tp: number) => string + public lua_tonumberx: (L: LuaAddress, idx: number, isnum: number | null) => number + public lua_tointegerx: (L: LuaAddress, idx: number, isnum: number | null) => bigint + public lua_toboolean: (L: LuaAddress, idx: number) => number + public lua_rawlen: (L: LuaAddress, idx: number) => bigint + public lua_tocfunction: (L: LuaAddress, idx: number) => number + public lua_touserdata: (L: LuaAddress, idx: number) => number + public lua_tothread: (L: LuaAddress, idx: number) => LuaAddress + public lua_topointer: (L: LuaAddress, idx: number) => number + public lua_arith: (L: LuaAddress, op: number) => void + public lua_rawequal: (L: LuaAddress, idx1: number, idx2: number) => number + public lua_compare: (L: LuaAddress, idx1: number, idx2: number, op: number) => number + public lua_pushnil: (L: LuaAddress) => void + public lua_pushnumber: (L: LuaAddress, n: number) => void + public lua_pushinteger: (L: LuaAddress, n: bigint) => void + public lua_pushlstring: (L: LuaAddress, s: number, len: number) => void + public lua_pushcclosure: (L: LuaAddress, fn: number, n: number) => void + public lua_pushboolean: (L: LuaAddress, b: number) => void + public lua_pushlightuserdata: (L: LuaAddress, p: number | null) => void + public lua_pushthread: (L: LuaAddress) => number + public lua_getglobal: (L: LuaAddress, name: string | null) => LuaType + public lua_gettable: (L: LuaAddress, idx: number) => LuaType + public lua_getfield: (L: LuaAddress, idx: number, k: string | null) => LuaType + public lua_geti: (L: LuaAddress, idx: number, n: bigint) => LuaType + public lua_rawget: (L: LuaAddress, idx: number) => number + public lua_rawgeti: (L: LuaAddress, idx: number, n: bigint) => LuaType + public lua_rawgetp: (L: LuaAddress, idx: number, p: number | null) => LuaType + public lua_createtable: (L: LuaAddress, narr: number, nrec: number) => void + public lua_newuserdatauv: (L: LuaAddress, sz: number, nuvalue: number) => number + public lua_getmetatable: (L: LuaAddress, objindex: number) => number + public lua_getiuservalue: (L: LuaAddress, idx: number, n: number) => LuaType + public lua_setglobal: (L: LuaAddress, name: string | null) => void + public lua_settable: (L: LuaAddress, idx: number) => void + public lua_setfield: (L: LuaAddress, idx: number, k: string | null) => void + public lua_seti: (L: LuaAddress, idx: number, n: bigint) => void + public lua_rawset: (L: LuaAddress, idx: number) => void + public lua_rawseti: (L: LuaAddress, idx: number, n: bigint) => void + public lua_rawsetp: (L: LuaAddress, idx: number, p: number | null) => void + public lua_setmetatable: (L: LuaAddress, objindex: number) => number + public lua_setiuservalue: (L: LuaAddress, idx: number, n: number) => number + public lua_callk: (L: LuaAddress, nargs: number, nresults: number, ctx: number, k: number | null) => void + public lua_pcallk: (L: LuaAddress, nargs: number, nresults: number, errfunc: number, ctx: number, k: number | null) => number + public lua_load: (L: LuaAddress, reader: number | null, dt: number | null, chunkname: string | null, mode: string | null) => LuaReturn + public lua_dump: (L: LuaAddress, writer: number | null, data: number | null, strip: number) => number + public lua_yieldk: (L: LuaAddress, nresults: number, ctx: number, k: number | null) => number + public lua_resume: (L: LuaAddress, from: LuaAddress | null, narg: number, nres: number | null) => LuaReturn + public lua_status: (L: LuaAddress) => LuaReturn + public lua_isyieldable: (L: LuaAddress) => number + public lua_setwarnf: (L: LuaAddress, f: number | null, ud: number | null) => void + public lua_warning: (L: LuaAddress, msg: string | null, tocont: number) => void + public lua_error: (L: LuaAddress) => number + public lua_next: (L: LuaAddress, idx: number) => number + public lua_concat: (L: LuaAddress, n: number) => void + public lua_len: (L: LuaAddress, idx: number) => void + public lua_stringtonumber: (L: LuaAddress, s: string | null) => number + public lua_getallocf: (L: LuaAddress, ud: number | null) => number + public lua_setallocf: (L: LuaAddress, f: number | null, ud: number | null) => void + public lua_toclose: (L: LuaAddress, idx: number) => void + public lua_closeslot: (L: LuaAddress, idx: number) => void + public lua_getstack: (L: LuaAddress, level: number, ar: number | null) => number + public lua_getinfo: (L: LuaAddress, what: string | null, ar: number | null) => number + public lua_getlocal: (L: LuaAddress, ar: number | null, n: number) => string + public lua_setlocal: (L: LuaAddress, ar: number | null, n: number) => string + public lua_getupvalue: (L: LuaAddress, funcindex: number, n: number) => string + public lua_setupvalue: (L: LuaAddress, funcindex: number, n: number) => string + public lua_upvalueid: (L: LuaAddress, fidx: number, n: number) => number + public lua_upvaluejoin: (L: LuaAddress, fidx1: number, n1: number, fidx2: number, n2: number) => void + public lua_sethook: (L: LuaAddress, func: number | null, mask: number, count: number) => void + public lua_gethook: (L: LuaAddress) => number + public lua_gethookmask: (L: LuaAddress) => number + public lua_gethookcount: (L: LuaAddress) => number + public lua_setcstacklimit: (_L: LuaAddress, _limit: number) => number + public luaopen_base: (L: LuaAddress) => number + public luaopen_coroutine: (L: LuaAddress) => number + public luaopen_table: (L: LuaAddress) => number + public luaopen_io: (L: LuaAddress) => number + public luaopen_os: (L: LuaAddress) => number + public luaopen_string: (L: LuaAddress) => number + public luaopen_utf8: (L: LuaAddress) => number + public luaopen_math: (L: LuaAddress) => number + public luaopen_debug: (L: LuaAddress) => number + public luaopen_package: (L: LuaAddress) => number + public luaL_openlibs: (L: LuaAddress) => void private referenceTracker = new WeakMap() private referenceMap = new Map() @@ -322,12 +312,10 @@ export default class LuaModule { // Lua strings are byte arrays that may contain NUL, so they cannot go through Emscripten's // NUL-terminated string marshalling. These work on pointers and explicit lengths instead. - private readonly rawLuaToLString: (L: LuaState, idx: number, len: number) => number - private readonly rawLuaLToLString: (L: LuaState, idx: number, len: number) => number - private readonly rawLuaPushString: (L: LuaState, s: number) => number + private readonly rawLuaToLString: (L: LuaAddress, idx: number, len: number) => number + private readonly rawLuaLToLString: (L: LuaAddress, idx: number, len: number) => number + private readonly rawLuaPushString: (L: LuaAddress, s: number) => number - private readonly textDecoder = new TextDecoder() - private readonly textEncoder = new TextEncoder() // C writes it immediately before returning and we read it straight after with no interleaving // await, so a single shared slot stays reentrancy safe. private readonly sizeScratch: number @@ -499,16 +487,16 @@ export default class LuaModule { * Bytes that aren't valid UTF-8 are replaced with U+FFFD. Use {@link lua_tobytes} when the * value holds arbitrary binary data (`string.dump`, `string.pack`, ciphertext, ...). */ - public lua_tolstring(L: LuaState, idx: number, len: number | null = null): string { + public lua_tolstring(L: LuaAddress, idx: number, len: number | null = null): string { return this.toLString(this.rawLuaToLString, L, idx, len) } /** Goes through the `__tostring` metamethod, which leaves the result on the stack. */ - public luaL_tolstring(L: LuaState, idx: number, len: number | null = null): string { + public luaL_tolstring(L: LuaAddress, idx: number, len: number | null = null): string { return this.toLString(this.rawLuaLToLString, L, idx, len) } - public lua_tobytes(L: LuaState, idx: number): Uint8Array | undefined { + public lua_tobytes(L: LuaAddress, idx: number): Uint8Array | undefined { const pointer = this.rawLuaToLString(L, idx, this.sizeScratch) if (!pointer) { return undefined @@ -518,7 +506,7 @@ export default class LuaModule { } /** A number is a pointer to a NUL-terminated C string, and `null` pushes nil, as in C. */ - public lua_pushstring(L: LuaState, s: string | number | null): void { + public lua_pushstring(L: LuaAddress, s: string | number | null): void { if (s === null || s === undefined) { this.lua_pushnil(L) } else if (typeof s === 'number') { @@ -530,7 +518,7 @@ export default class LuaModule { const pointer = this.acquireStringBuffer(capacity) try { // encodeInto avoids materialising an intermediate Uint8Array for the whole string. - const { written } = this.textEncoder.encodeInto(s, this.heap.subarray(pointer, pointer + capacity)) + const { written } = textEncoder.encodeInto(s, this.heap.subarray(pointer, pointer + capacity)) this.lua_pushlstring(L, pointer, written) } finally { this.releaseStringBuffer(pointer) @@ -538,7 +526,7 @@ export default class LuaModule { } } - public lua_pushbytes(L: LuaState, bytes: Uint8Array): void { + public lua_pushbytes(L: LuaAddress, bytes: Uint8Array): void { const pointer = this.acquireStringBuffer(bytes.length) try { this.heap.set(bytes, pointer) @@ -552,29 +540,29 @@ export default class LuaModule { if (!length) { return '' } - return this.textDecoder.decode(this.heap.subarray(pointer, pointer + length)) + return textDecoder.decode(this.heap.subarray(pointer, pointer + length)) } - private toLString(raw: (L: LuaState, idx: number, len: number) => number, L: LuaState, idx: number, len: number | null): string { + private toLString(raw: (L: LuaAddress, idx: number, len: number) => number, L: LuaAddress, idx: number, len: number | null): string { const lengthPointer = len ?? this.sizeScratch const pointer = raw(L, idx, lengthPointer) return pointer ? this.readString(pointer, this.readSize(lengthPointer)) : '' } - public lua_remove(luaState: LuaState, index: number): void { + public lua_remove(luaState: LuaAddress, index: number): void { this.lua_rotate(luaState, index, -1) this.lua_pop(luaState, 1) } - public lua_pop(luaState: LuaState, count: number): void { + public lua_pop(luaState: LuaAddress, count: number): void { this.lua_settop(luaState, -count - 1) } - public luaL_getmetatable(luaState: LuaState, name: string): LuaType { + public luaL_getmetatable(luaState: LuaAddress, name: string): LuaType { return this.lua_getfield(luaState, LUA_REGISTRYINDEX, name) } - public lua_yield(luaState: LuaState, count: number): number { + public lua_yield(luaState: LuaAddress, count: number): number { return this.lua_yieldk(luaState, count, 0, null) } @@ -632,9 +620,9 @@ export default class LuaModule { return this.lastRefIndex } - public printRefs(): void { + public printRefs(log = console.log): void { for (const [key, value] of this.referenceMap.entries()) { - console.log(key, value) + log(key, value) } } @@ -717,21 +705,97 @@ export default class LuaModule { } } +/** + * The callback is asked for more input whenever the C side runs out, and each call satisfies a + * single read: once the returned text is consumed the read ends, so the next one asks again + * instead of blocking for a whole buffer worth of input. An empty string (or nothing at all) + * signals EOF. + */ +function createInputReader(reader?: () => string | null | undefined): (() => number | null) | null { + if (!reader) { + return null + } + + let pending: Uint8Array | undefined + let offset = 0 + + return (): number | null => { + if (pending === undefined) { + const input = reader() ?? '' + if (typeof input !== 'string') { + throw new Error('stdin must return a string') + } + // Not NUL terminated, so a NUL inside the input stays a regular byte. + pending = textEncoder.encode(input) + offset = 0 + } + + if (offset >= pending.length) { + // Ends the current read instead of asking for more, and makes the next one start over. + pending = undefined + return null + } + + return pending[offset++] + } +} + +// Emscripten hands output over one byte at a time, so it has to be reassembled before it can be +// decoded. Doubles from here as lines get longer. +const INITIAL_OUTPUT_CAPACITY = 256 + function createOutputWriter(writer?: (content: string) => void): ((charCode: number | null) => void) | null { if (!writer) { return null } - let buffer = '' + // Its own decoder, because a flush in the middle of a line can cut a multi byte character in + // half and the rest of it only arrives later. + const decoder = new TextDecoder() + let buffer = new Uint8Array(INITIAL_OUTPUT_CAPACITY) + let length = 0 + let flushScheduled = false + + const emit = (endOfLine: boolean): void => { + // A CR right before the line break is part of the terminator, but one anywhere else is + // content and has to survive. + if (endOfLine && length > 0 && buffer[length - 1] === 13) { + length-- + } + // Only the end of a line is a character boundary for sure, so anything else leaves a + // dangling character in the decoder to be completed by the next flush. + const content = decoder.decode(buffer.subarray(0, length), { stream: !endOfLine }) + length = 0 + // An empty line is worth reporting, an incomplete character is not. + if (endOfLine || content.length > 0) { + writer(content) + } + } + return (charCode: number | null): void => { if (charCode === null || charCode === 10) { - writer(buffer) - buffer = '' + emit(true) return } - if (charCode !== 13) { - buffer += String.fromCharCode(charCode) + if (length === buffer.length) { + const grown = new Uint8Array(buffer.length * 2) + grown.set(buffer) + buffer = grown + } + buffer[length++] = charCode + + if (!flushScheduled) { + flushScheduled = true + // Output that never ends in a newline (`io.write` without one, a prompt, ...) would + // otherwise sit here forever. Flushing on a microtask keeps it in the same line as + // whatever else the current run writes, while still handing it over once Lua is done. + queueMicrotask(() => { + flushScheduled = false + if (length > 0) { + emit(false) + } + }) } } } diff --git a/src/runtime.ts b/src/runtime.ts new file mode 100755 index 0000000..c012de8 --- /dev/null +++ b/src/runtime.ts @@ -0,0 +1,70 @@ +import LuaModule from './module' +import LuaState from './state' +import { CreateStateOptions } from './types' + +/** + * One loaded Lua wasm module, and the factory for the states that run on it. + * + * States created from the same runtime share the filesystem and the module level stdio, and are + * otherwise independent. + */ +export default class LuaRuntime { + /** + * Loads the Lua wasm module. + * @param opts.wasmFile - Custom URI for the Lua WebAssembly module. + * @param opts.env - Environment variables for the Lua states. + * @param opts.stdin - Standard input, shared by every state on this runtime. + * @param opts.fs - File system that should be used. + * @param opts.stdout - Standard output, shared by every state on this runtime. + * @param opts.stderr - Standard error, shared by every state on this runtime. + * @param opts.onWarn - Where load time diagnostics go. Defaults to `console.warn`. + */ + public static async load(luaModuleOpts: Parameters[0] = {}): Promise { + return new LuaRuntime(await LuaModule.initialize(luaModuleOpts)) + } + + private readonly states = new Set() + + public constructor(public readonly module: LuaModule) {} + + public createState(stateOpts: CreateStateOptions = {}): LuaState { + const state = new LuaState(this.module, stateOpts) + this.states.add(state) + state.onClose(() => this.states.delete(state)) + return state + } + + /** + * Closes every state created from this runtime. The wasm module itself cannot be unloaded, so + * this frees the states rather than the runtime. + */ + public close(): void { + for (const state of this.states) { + state.close() + } + this.states.clear() + } + + public async [Symbol.asyncDispose](): Promise { + this.close() + } + + /** + * Mounts a file in the Lua environment synchronously. + * @param path - Path to the file in the Lua environment. + * @param content - Content of the file to be mounted. + */ + public mountFile(path: string, content: string | ArrayBufferView): void { + const dirname = this.module._emscripten.PATH.dirname(path) + this.module._emscripten.FS.mkdirTree(dirname) + this.module._emscripten.FS.writeFile(path, content) + } + + public get filesystem(): typeof this.module._emscripten.FS { + return this.module._emscripten.FS + } + + public get path(): typeof this.module._emscripten.PATH { + return this.module._emscripten.PATH + } +} diff --git a/src/state.ts b/src/state.ts new file mode 100755 index 0000000..0bcca4a --- /dev/null +++ b/src/state.ts @@ -0,0 +1,296 @@ +import type LuaModule from './module' +import Thread from './thread' +import LuaTypeExtension from './type-extension' +import createErrorType from './type-extensions/error' +import createFunctionType from './type-extensions/function' +import createNullType from './type-extensions/null' +import createPromiseType from './type-extensions/promise' +import createProxyType from './type-extensions/proxy' +import createTableType from './type-extensions/table' +import createUserdataType from './type-extensions/userdata' +import { + CreateStateOptions, + LUA_REGISTRYINDEX, + LuaAddress, + LuaDoOptions, + LuaMemoryOptions, + LuaRunOptions, + LuaType, + resolveLibraryMask, +} from './types' + +/** + * Memory accounting for a state created with `{ memory: { trace: true } }`. On a state without + * tracing `state.memory` is undefined, so the absence is a type error rather than a runtime one. + */ +export interface LuaMemory { + /** Bytes currently allocated by this state. */ + readonly used: number + /** Allocation ceiling in bytes, or undefined for unlimited. */ + max: number | undefined +} + +interface CreatedState { + address: LuaAddress + memory?: LuaMemory + allocatorFunctionPointer?: number +} + +/** + * Tracing needs its own allocator, which has to exist before `lua_newstate`, so this runs ahead + * of the constructor body rather than branching around `super()` twice. + */ +function createAddress(cmodule: LuaModule, memory: LuaMemoryOptions | undefined): CreatedState { + if (!memory?.trace) { + if (memory?.max !== undefined) { + throw new Error('memory.max requires memory.trace to be enabled') + } + return { address: cmodule.luaL_newstate() } + } + + const stats = { used: 0, max: memory.max } + const allocatorFunctionPointer = cmodule._emscripten.addFunction( + (_userData: number, pointer: number, oldSize: number, newSize: number): number => { + if (newSize === 0) { + if (pointer) { + stats.used -= oldSize + cmodule._emscripten._free(pointer) + } + return 0 + } + + const endMemoryDelta = pointer ? newSize - oldSize : newSize + const endMemory = stats.used + endMemoryDelta + + if (newSize > oldSize && stats.max && endMemory > stats.max) { + return 0 + } + + const reallocated = cmodule._emscripten._realloc(pointer, newSize) + if (reallocated) { + stats.used = endMemory + } + return reallocated + }, + 'iiiii', + ) + + const address = cmodule.lua_newstate( + allocatorFunctionPointer, + null, + ((Date.now() >>> 0) ^ Math.floor(Math.random() * 0x100000000)) >>> 0, + ) + if (!address) { + cmodule._emscripten.removeFunction(allocatorFunctionPointer) + throw new Error('lua_newstate returned a null pointer') + } + + return { address, memory: stats, allocatorFunctionPointer } +} + +/** + * An independent Lua state: its globals, its standard libraries and its main thread. + * + * Created through `runtime.createState()`. Several states can share one runtime, and closing one + * does not affect the others. + */ +export default class LuaState extends Thread { + /** Present only when the state was created with `{ memory: { trace: true } }`. */ + public readonly memory: LuaMemory | undefined + + private readonly allocatorFunctionPointer: number | undefined + private readonly defaultMaxInstructions: number | undefined + private readonly closeListeners: (() => void)[] = [] + + public constructor(cmodule: LuaModule, options: CreateStateOptions = {}) { + const { libs = true, objects = 'proxy', errors = objects === 'copy', inject = false, memory, limits, onWarn } = options + + const created = createAddress(cmodule, memory) + super(cmodule, [], created.address) + + this.memory = created.memory + this.allocatorFunctionPointer = created.allocatorFunctionPointer + this.onWarn = onWarn + + if (this.isClosed()) { + throw new Error('Lua state could not be created (probably due to lack of memory)') + } + + // Generic handlers - These may be required to be registered for additional types. + this.registerTypeExtension(0, createTableType(this)) + this.registerTypeExtension(0, createFunctionType(this, { functionTimeout: limits?.functionTimeout })) + + // Contains the :await functionality. + this.registerTypeExtension(1, createPromiseType(this, inject)) + + if (inject) { + // Should be higher priority than table since that catches generic objects along + // with userdata so it doesn't end up a userdata type. + this.registerTypeExtension(5, createNullType(this)) + } + + if (errors) { + this.registerTypeExtension(1, createErrorType(this, inject)) + } + + if (objects === 'proxy') { + // This extension only really overrides tables and arrays. + // When a function is looked up in one of it's tables it's bound and then + // handled by the function type extension. + this.registerTypeExtension(3, createProxyType(this)) + } + + // Higher priority than proxied objects to allow custom user data without exposing methods. + this.registerTypeExtension(4, createUserdataType(this)) + + const libraryMask = resolveLibraryMask(libs) + if (libraryMask !== 0) { + this.lua.luaL_openselectedlibs(this.address, libraryMask, 0) + } + + this.defaultMaxInstructions = limits?.maxInstructions + } + + /** + * Executes Lua code from a string asynchronously. + * @returns A Promise that resolves to the result returned by the Lua script execution. + */ + public doString(script: string, options?: LuaDoOptions): Promise { + return this.callByteCode((thread) => thread.loadString(script, options), this.runOptions(options)) + } + + /** + * Executes Lua code from a file asynchronously. + * @returns A Promise that resolves to the result returned by the Lua script execution. + */ + public doFile(filename: string, options?: LuaDoOptions): Promise { + return this.callByteCode((thread) => thread.loadFile(filename, options), this.runOptions(options)) + } + + /** + * Executes Lua code from a string synchronously. The script cannot yield, so `:await()` and a + * top level `coroutine.yield` are errors here. + */ + public doStringSync(script: string, options?: LuaDoOptions): any { + return this.callByteCodeSync((thread) => thread.loadString(script, options), this.runOptions(options)) + } + + /** + * Executes Lua code from a file synchronously. The script cannot yield, so `:await()` and a + * top level `coroutine.yield` are errors here. + */ + public doFileSync(filename: string, options?: LuaDoOptions): any { + return this.callByteCodeSync((thread) => thread.loadFile(filename, options), this.runOptions(options)) + } + + /** + * Registers a type extension for Lua objects. + * Higher priority is more important and will be evaluated first. + * Allows library users to specify custom types + */ + public registerTypeExtension(priority: number, extension: LuaTypeExtension): void { + this.typeExtensions.push({ extension, priority }) + this.typeExtensions.sort((a, b) => b.priority - a.priority) + } + + /** Retrieves the value of a global variable. */ + public get(name: string): any { + const type = this.lua.lua_getglobal(this.address, name) + const value = this.getValue(-1, type) + this.pop() + return value + } + + /** Sets the value of a global variable. */ + public set(name: string, value: unknown): void { + this.pushValue(value) + this.lua.lua_setglobal(this.address, name) + } + + public getTable(name: string, callback: (index: number) => void): void { + const startStackTop = this.getTop() + const type = this.lua.lua_getglobal(this.address, name) + try { + if (type !== LuaType.Table) { + throw new TypeError(`Unexpected type in ${name}. Expected ${LuaType[LuaType.Table]}. Got ${LuaType[type]}.`) + } + callback(startStackTop + 1) + } finally { + // +1 for the table + if (this.getTop() !== startStackTop + 1) { + this.warn(`getTable: expected stack size ${startStackTop + 1} got ${this.getTop()}`) + } + this.setTop(startStackTop) + } + } + + /** Notified once when this state closes, so an owner can drop its reference. */ + public onClose(listener: () => void): void { + this.closeListeners.push(listener) + } + + /** Closes the state and frees everything it owns. Safe to call more than once. */ + public override close(): void { + if (this.isClosed()) { + return + } + + super.close() + + // Do this before removing the gc to force. + // Here rather than in the threads because you don't + // actually close threads, just pop them. Only the top-level + // lua state needs closing. + this.lua.lua_close(this.address) + + if (this.allocatorFunctionPointer) { + this.lua._emscripten.removeFunction(this.allocatorFunctionPointer) + } + + for (const wrapper of this.typeExtensions) { + wrapper.extension.close() + } + + for (const listener of this.closeListeners) { + listener() + } + this.closeListeners.length = 0 + } + + /** Folds the state wide budget in, so run() does the save and restore in one place. */ + private runOptions(options?: LuaDoOptions): LuaRunOptions | undefined { + if (this.defaultMaxInstructions === undefined) { + return options + } + return { maxInstructions: this.defaultMaxInstructions, ...options } + } + + private callByteCodeSync(loader: (thread: Thread) => void, options?: LuaRunOptions): any { + // Runs on the main thread so the script sees itself as the main coroutine, the way the + // reference implementation behaves. That makes leftovers outlive the call, hence the rewind. + const startStackTop = this.getTop() + try { + loader(this) + return this.runSync(0, options)[0] + } finally { + this.setTop(startStackTop) + } + } + + // WARNING: It will not wait for open handles and can potentially cause bugs if JS code tries to reference Lua after executed + private async callByteCode(loader: (thread: Thread) => void, options?: LuaRunOptions): Promise { + const thread = this.newThread() + // Move the thread off the global stack and into the registry as a GC anchor so it doesn't pile threads up into the stack + const ref = this.lua.luaL_ref(this.address, LUA_REGISTRYINDEX) + try { + // Seeded from the state so a state wide setLimits reaches the async path too, which + // runs on a child thread rather than on the state itself. + thread.setLimits(this.getLimits()) + loader(thread) + return (await thread.run(0, options))[0] + } finally { + thread.close() + this.lua.luaL_unref(this.address, LUA_REGISTRYINDEX, ref) + } + } +} diff --git a/src/thread.ts b/src/thread.ts index 274f570..be92daf 100755 --- a/src/thread.ts +++ b/src/thread.ts @@ -4,14 +4,22 @@ import MultiReturn from './multireturn' import { Pointer } from './pointer' import LuaTypeExtension from './type-extension' import { + defaultWarnHandler, LUA_MULTRET, + LuaAbortError, + LuaAddress, + LuaError, LuaEventMasks, + LuaInstructionLimitError, + LuaInterruptError, + LuaLoadOptions, LuaResumeResult, LuaReturn, - LuaState, - LuaThreadRunOptions, + LuaRunOptions, + LuaThreadLimits, LuaTimeoutError, LuaType, + LuaWarnHandler, PointerSize, } from './types' import { isEmscriptenUnwind, isPromise, yieldToEventLoop } from './utils' @@ -27,14 +35,20 @@ const INSTRUCTION_HOOK_COUNT = 1000 const LUA_INTEGER_BITS = 64 +const NO_RESTORE = (): void => undefined + export default class Thread { - public readonly address: LuaState + public readonly address: LuaAddress public readonly lua: LuaModule + /** Set on the root state; threads created from it delegate here. */ + public onWarn: LuaWarnHandler | undefined protected readonly typeExtensions: OrderedExtension[] + protected readonly parent?: Thread private closed = false private hookFunctionPointer: number | undefined - private timeout?: number - private readonly parent?: Thread + private hookCount = INSTRUCTION_HOOK_COUNT + private limits: LuaThreadLimits = {} + private instructionsUsed = 0 public constructor(lua: LuaModule, typeExtensions: OrderedExtension[], address: number, parent?: Thread) { this.lua = lua @@ -55,20 +69,24 @@ export default class Thread { this.assertOk(this.lua.lua_resetthread(this.address)) } - public loadString(luaCode: string, name?: string): void { + /** @param options.mode defaults to `'t'`. See {@link LuaLoadOptions.mode}. */ + public loadString(luaCode: string, options?: LuaLoadOptions): void { const size = this.lua._emscripten.lengthBytesUTF8(luaCode) const pointerSize = size + 1 const bufferPointer = this.lua._emscripten._malloc(pointerSize) try { this.lua._emscripten.stringToUTF8(luaCode, bufferPointer, pointerSize) - this.assertOk(this.lua.luaL_loadbufferx(this.address, bufferPointer, size, name ?? bufferPointer, null)) + this.assertOk( + this.lua.luaL_loadbufferx(this.address, bufferPointer, size, options?.name ?? bufferPointer, options?.mode ?? 't'), + ) } finally { this.lua._emscripten._free(bufferPointer) } } - public loadFile(filename: string): void { - this.assertOk(this.lua.luaL_loadfilex(this.address, filename, null)) + /** @param options.mode defaults to `'t'`. See {@link LuaLoadOptions.mode}. */ + public loadFile(filename: string, options?: LuaLoadOptions): void { + this.assertOk(this.lua.luaL_loadfilex(this.address, filename, options?.mode ?? 't')) } public resume(argCount = 0): LuaResumeResult { @@ -103,21 +121,19 @@ export default class Thread { this.lua.lua_setfield(this.address, index, name) } - public async run(argCount = 0, options?: Partial): Promise { - const originalTimeout = this.timeout + public async run(argCount = 0, options?: LuaRunOptions): Promise { + const restore = this.applyRunOptions(options) try { - if (options?.timeout !== undefined) { - this.setTimeout(Date.now() + options.timeout) - } let resumeResult: LuaResumeResult = this.resume(argCount) while (resumeResult.result === LuaReturn.Yield) { - // If it's yielded check the timeout. If it's completed no need to - // needlessly discard the output. - if (this.timeout && Date.now() > this.timeout) { + // If it's completed there's no need to needlessly discard the output. The hook + // only fires while Lua runs, so a parked thread is checked here instead. + const limitError = this.checkYieldLimits() + if (limitError) { if (resumeResult.resultCount > 0) { this.pop(resumeResult.resultCount) } - throw new LuaTimeoutError(`thread timeout exceeded`) + throw limitError } if (resumeResult.resultCount > 0) { const lastValue = this.getValue(-1) @@ -135,22 +151,32 @@ export default class Thread { await yieldToEventLoop() } + // The wait itself can outlast the deadline, and resuming would hand Lua another + // full slice before the hook noticed. + const waitError = this.checkYieldLimits() + if (waitError) { + throw waitError + } + resumeResult = this.resume(0) } this.assertOk(resumeResult.result) return this.getStackValues() } finally { - if (options?.timeout !== undefined) { - this.setTimeout(originalTimeout) - } + restore() } } - public runSync(argCount = 0): MultiReturn { - const base = this.getTop() - argCount - 1 // The 1 is for the function to run - this.assertOk(this.lua.lua_pcallk(this.address, argCount, LUA_MULTRET, 0, 0, null) as LuaReturn) - return this.getStackValues(base) + public runSync(argCount = 0, options?: LuaRunOptions): MultiReturn { + const restore = this.applyRunOptions(options) + try { + const base = this.getTop() - argCount - 1 // The 1 is for the function to run + this.assertOk(this.lua.lua_pcallk(this.address, argCount, LUA_MULTRET, 0, 0, null) as LuaReturn) + return this.getStackValues(base) + } finally { + restore() + } } public pop(count = 1): void { @@ -183,7 +209,7 @@ export default class Thread { return returnValues } - public stateToThread(L: LuaState): Thread { + public stateToThread(L: LuaAddress): Thread { return L === this.parent?.address ? this.parent : new Thread(this.lua, this.typeExtensions, L, this.parent || this) } @@ -317,9 +343,14 @@ export default class Thread { return typeExtensionWrapper.extension.getValue(this, index, userdata) } - // Fallthrough if unrecognised user data - console.warn(`The type '${this.lua.lua_typename(this.address, type)}' returned is not supported on JS`) - return new Pointer(this.lua.lua_topointer(this.address, index)) + // Handing back an opaque Pointer hid the failure until the value was used, and + // it could not be pushed back into Lua anyway. + const typeName = this.lua.lua_typename(this.address, type) + const withMetatable = metatableName ? ` with metatable '${metatableName}'` : '' + throw new TypeError( + `the Lua type '${typeName}'${withMetatable} has no JS representation; register a type ` + + `extension to handle it, or read the address with getPointer`, + ) } } } @@ -331,35 +362,44 @@ export default class Thread { if (this.hookFunctionPointer) { this.lua._emscripten.removeFunction(this.hookFunctionPointer) + this.hookFunctionPointer = undefined } this.closed = true } - // Set to > 0 to enable, otherwise disable. - public setTimeout(timeout: number | undefined): void { - if (timeout && timeout > 0) { - if (!this.hookFunctionPointer) { - this.hookFunctionPointer = this.lua._emscripten.addFunction((): void => { - // Reads this.timeout rather than closing over the argument, so a hook - // allocated for an earlier deadline still honours the current one. - if (this.timeout !== undefined && Date.now() > this.timeout) { - this.pushValue(new LuaTimeoutError(`thread timeout exceeded`)) - this.lua.lua_error(this.address) - } - }, 'vii') - } + public [Symbol.dispose](): void { + this.close() + } - this.timeout = timeout - this.lua.lua_sethook(this.address, this.hookFunctionPointer, LuaEventMasks.Count, INSTRUCTION_HOOK_COUNT) - } else { - this.timeout = undefined - this.lua.lua_sethook(this.address, null, 0, 0) - } + /** + * Installs the deadline, instruction budget and abort signal enforced while this thread runs. + * They share a single debug hook, because Lua only allows one hook per thread. + */ + public setLimits(limits: LuaThreadLimits | undefined): void { + this.limits = { ...limits } + this.instructionsUsed = 0 + this.applyHook() + } + + public getLimits(): LuaThreadLimits { + return { ...this.limits } + } + + /** Set to > 0 to enable, otherwise disable. Shorthand for the deadline in {@link setLimits}. */ + public setTimeout(timeout: number | undefined): void { + this.limits.deadline = timeout && timeout > 0 ? timeout : undefined + this.applyHook() } public getTimeout(): number | undefined { - return this.timeout + return this.limits.deadline + } + + /** Diagnostics the library would otherwise have written straight to the console. */ + public warn(message: string, cause?: unknown): void { + const root = this.parent ?? this + ;(root.onWarn ?? defaultWarnHandler)(message, cause) } public getPointer(index: number): Pointer { @@ -399,51 +439,139 @@ export default class Thread { const typename = this.lua.lua_typename(this.address, type) const pointer = this.getPointer(i) const name = this.indexToString(i) - const value = this.getValue(i, type) + let value: unknown + try { + value = this.getValue(i, type) + } catch (err) { + // A debugging aid should survive one unrepresentable slot. + value = `<${(err as Error).message}>` + } log(i, typename, pointer, name, value) } } public assertOk(result: LuaReturn): void { - if (result !== LuaReturn.Ok && result !== LuaReturn.Yield) { - const resultString = LuaReturn[result] - // This is the default message if there's nothing on the stack. - const error = new Error(`Lua Error(${resultString}/${result})`) - if (this.getTop() > 0) { - if (result === LuaReturn.ErrorMem) { - // If there's no memory just do a normal to string. - error.message = this.lua.lua_tolstring(this.address, -1, null) - } else { - const luaError = this.getValue(-1) - if (luaError instanceof Error) { - error.stack = luaError.stack - } + if (result === LuaReturn.Ok || result === LuaReturn.Yield) { + return + } + + // This is the default message if there's nothing on the stack. + let luaMessage = `Lua Error(${LuaReturn[result]}/${result})` + let luaValue: unknown - // Calls __tostring if it exists and pushes onto the stack. - error.message = this.indexToString(-1) + if (this.getTop() > 0) { + if (result === LuaReturn.ErrorMem) { + // If there's no memory just do a normal to string. + luaMessage = this.lua.lua_tolstring(this.address, -1, null) + } else { + try { + luaValue = this.getValue(-1) + } catch { + // An unrepresentable error value must not replace the error being reported. + luaValue = undefined } + + // Calls __tostring if it exists and pushes onto the stack. + luaMessage = this.indexToString(-1) } + } - // Also attempt to get a traceback - if (result !== LuaReturn.ErrorMem) { - try { - this.lua.luaL_traceback(this.address, this.address, null, 1) - const traceback = this.lua.lua_tolstring(this.address, -1, null) - if (traceback.trim() !== 'stack traceback:') { - error.message = `${error.message}\n${traceback}` - } - this.pop(1) // pop stack trace. - } catch (err) { - if (isEmscriptenUnwind(err)) { - throw err - } - console.warn('Failed to generate stack trace', err) + if (luaValue instanceof LuaInterruptError) { + throw luaValue + } + + let traceback: string | undefined + if (result !== LuaReturn.ErrorMem) { + try { + this.lua.luaL_traceback(this.address, this.address, null, 1) + const text = this.lua.lua_tolstring(this.address, -1, null) + if (text.trim() !== 'stack traceback:') { + traceback = text + } + this.pop(1) // pop stack trace. + } catch (err) { + if (isEmscriptenUnwind(err)) { + throw err + } + this.warn('Failed to generate stack trace', err) + } + } + + throw new LuaError(result, luaMessage, { traceback, luaValue }) + } + + private applyRunOptions(options: LuaRunOptions | undefined): () => void { + const overrides = + options !== undefined && + (options.timeout !== undefined || options.maxInstructions !== undefined || options.signal !== undefined) + + if (!overrides) { + return NO_RESTORE + } + + const previousLimits = this.limits + const previousUsed = this.instructionsUsed + + this.setLimits({ + deadline: options.timeout !== undefined ? Date.now() + options.timeout : previousLimits.deadline, + maxInstructions: options.maxInstructions ?? previousLimits.maxInstructions, + signal: options.signal ?? previousLimits.signal, + }) + + return () => { + this.limits = previousLimits + this.instructionsUsed = previousUsed + this.applyHook() + } + } + + private applyHook(): void { + const { deadline, maxInstructions, signal } = this.limits + if (deadline === undefined && maxInstructions === undefined && signal === undefined) { + this.lua.lua_sethook(this.address, null, 0, 0) + return + } + + // A budget smaller than the default period would only ever be noticed late. + this.hookCount = + maxInstructions !== undefined ? Math.max(1, Math.min(INSTRUCTION_HOOK_COUNT, maxInstructions)) : INSTRUCTION_HOOK_COUNT + + if (!this.hookFunctionPointer) { + this.hookFunctionPointer = this.lua._emscripten.addFunction((): void => { + // Reads this.limits rather than closing over them, so a hook allocated for an + // earlier configuration still honours the current one. + const error = this.checkHookLimits() + if (error) { + this.pushValue(error) + this.lua.lua_error(this.address) } + }, 'vii') + } + + this.lua.lua_sethook(this.address, this.hookFunctionPointer, LuaEventMasks.Count, this.hookCount) + } + + private checkHookLimits(): Error | undefined { + const { maxInstructions } = this.limits + if (maxInstructions !== undefined) { + this.instructionsUsed += this.hookCount + if (this.instructionsUsed > maxInstructions) { + return new LuaInstructionLimitError(`thread exceeded its budget of ${maxInstructions} instructions`) } + } + return this.checkYieldLimits() + } - throw error + private checkYieldLimits(): Error | undefined { + const { deadline, signal } = this.limits + if (signal?.aborted) { + return new LuaAbortError('thread aborted') + } + if (deadline !== undefined && Date.now() > deadline) { + return new LuaTimeoutError('thread timeout exceeded') } + return undefined } private getValueDecorations(value: any): Decoration { diff --git a/src/type-extension.ts b/src/type-extension.ts index e4929cc..3bac4ae 100644 --- a/src/type-extension.ts +++ b/src/type-extension.ts @@ -1,14 +1,14 @@ -import { BaseDecorationOptions, Decoration } from './decoration' -import Global from './global' +import { Decoration } from './decoration' +import type LuaState from './state' import Thread from './thread' import { LuaType, PointerSize } from './types' -export default abstract class LuaTypeExtension { +export default abstract class LuaTypeExtension { // Type name, for metatables and lookups. public readonly name: string - protected thread: Global + protected thread: LuaState - public constructor(thread: Global, name: string) { + public constructor(thread: LuaState, name: string) { this.thread = thread this.name = name } @@ -31,7 +31,7 @@ export default abstract class LuaTypeExtension, _userdata?: unknown): boolean { + public pushValue(thread: Thread, decoratedValue: Decoration, _userdata?: unknown): boolean { const { target } = decoratedValue const pointer = thread.lua.ref(target) diff --git a/src/type-extensions/error.ts b/src/type-extensions/error.ts index 745fe6c..a86f4dc 100644 --- a/src/type-extensions/error.ts +++ b/src/type-extensions/error.ts @@ -1,16 +1,16 @@ import { Decoration } from '../decoration' -import Global from '../global' +import type LuaState from '../state' import Thread from '../thread' import TypeExtension from '../type-extension' -import { LuaReturn, LuaState } from '../types' +import { LuaReturn, LuaAddress } from '../types' class ErrorTypeExtension extends TypeExtension { private gcPointer: number - public constructor(thread: Global, injectObject: boolean) { + public constructor(thread: LuaState, injectObject: boolean) { super(thread, 'js_error') - this.gcPointer = thread.lua._emscripten.addFunction((functionStateAddress: LuaState) => { + this.gcPointer = thread.lua._emscripten.addFunction((functionStateAddress: LuaAddress) => { // Throws a lua error which does a jump if it does not match. const userDataPointer = thread.lua.luaL_checkudata(functionStateAddress, 1, this.name) const referencePointer = thread.lua._emscripten.getValue(userDataPointer, '*') @@ -76,6 +76,6 @@ class ErrorTypeExtension extends TypeExtension { } } -export default function createTypeExtension(thread: Global, injectObject: boolean): TypeExtension { +export default function createTypeExtension(thread: LuaState, injectObject: boolean): TypeExtension { return new ErrorTypeExtension(thread, injectObject) } diff --git a/src/type-extensions/function.ts b/src/type-extensions/function.ts index db39794..ee2d9c5 100644 --- a/src/type-extensions/function.ts +++ b/src/type-extensions/function.ts @@ -1,29 +1,19 @@ -import { BaseDecorationOptions, Decoration } from '../decoration' -import Global from '../global' +import { Decoration } from '../decoration' +import type LuaState from '../state' import MultiReturn from '../multireturn' import RawResult from '../raw-result' import Thread from '../thread' import TypeExtension from '../type-extension' -import { LUA_REGISTRYINDEX, LuaReturn, LuaState, LuaType, PointerSize } from '../types' +import { LUA_REGISTRYINDEX, LuaReturn, LuaAddress, LuaType, PointerSize } from '../types' import { isEmscriptenUnwind } from '../utils' -export interface FunctionDecoration extends BaseDecorationOptions { - receiveArgsQuantity?: boolean - receiveThread?: boolean - self?: any -} - export type FunctionType = (...args: any[]) => Promise | any -export function decorateFunction(target: FunctionType, options: FunctionDecoration): Decoration { - return new Decoration(target, options) -} - export interface FunctionTypeExtensionOptions { functionTimeout?: number } -class FunctionTypeExtension extends TypeExtension { +class FunctionTypeExtension extends TypeExtension { private readonly functionRegistry = new FinalizationRegistry((func: number) => { if (!this.thread.isClosed()) { this.thread.lua.luaL_unref(this.thread.address, LUA_REGISTRYINDEX, func) @@ -36,7 +26,7 @@ class FunctionTypeExtension extends TypeExtension { + this.gcPointer = thread.lua._emscripten.addFunction((calledL: LuaAddress) => { // Throws a lua error which does a jump if it does not match. const userDataPointer = thread.lua.luaL_checkudata(calledL, 1, this.name) const referencePointer = thread.lua._emscripten.getValue(userDataPointer, '*') @@ -73,12 +63,12 @@ class FunctionTypeExtension extends TypeExtension { + this.functionWrapper = thread.lua._emscripten.addFunction((calledL: LuaAddress) => { const calledThread = thread.stateToThread(calledL) const refUserdata = thread.lua.luaL_checkudata(calledL, thread.lua.lua_upvalueindex(1), this.name) const refPointer = thread.lua._emscripten.getValue(refUserdata, '*') - const { target, options: decorationOptions } = thread.lua.getRef(refPointer) as Decoration + const { target, options: decorationOptions } = thread.lua.getRef(refPointer) as Decoration const argsQuantity = calledThread.getTop() const args = [] @@ -137,7 +127,7 @@ class FunctionTypeExtension extends TypeExtension): boolean { + public pushValue(thread: Thread, decoration: Decoration): boolean { if (typeof decoration.target !== 'function') { return false } @@ -181,8 +171,9 @@ class FunctionTypeExtension extends TypeExtension { +export default function createTypeExtension(thread: LuaState, options?: FunctionTypeExtensionOptions): TypeExtension { return new FunctionTypeExtension(thread, options) } diff --git a/src/type-extensions/null.ts b/src/type-extensions/null.ts index 5c35c50..b38e310 100644 --- a/src/type-extensions/null.ts +++ b/src/type-extensions/null.ts @@ -1,17 +1,17 @@ import { Decoration } from '../decoration' -import Global from '../global' +import type LuaState from '../state' import Thread from '../thread' import TypeExtension from '../type-extension' -import { LUA_REGISTRYINDEX, LuaReturn, LuaState } from '../types' +import { LUA_REGISTRYINDEX, LuaReturn, LuaAddress } from '../types' class NullTypeExtension extends TypeExtension { private gcPointer: number private nullReference: number - public constructor(thread: Global) { + public constructor(thread: LuaState) { super(thread, 'js_null') - this.gcPointer = thread.lua._emscripten.addFunction((functionStateAddress: LuaState) => { + this.gcPointer = thread.lua._emscripten.addFunction((functionStateAddress: LuaAddress) => { // Throws a lua error which does a jump if it does not match. const userDataPointer = thread.lua.luaL_checkudata(functionStateAddress, 1, this.name) const referencePointer = thread.lua._emscripten.getValue(userDataPointer, '*') @@ -78,6 +78,6 @@ class NullTypeExtension extends TypeExtension { } } -export default function createTypeExtension(thread: Global): TypeExtension { +export default function createTypeExtension(thread: LuaState): TypeExtension { return new NullTypeExtension(thread) } diff --git a/src/type-extensions/promise.ts b/src/type-extensions/promise.ts index 2130c6b..a10dead 100644 --- a/src/type-extensions/promise.ts +++ b/src/type-extensions/promise.ts @@ -1,20 +1,20 @@ import { Decoration } from '../decoration' -import Global from '../global' +import type LuaState from '../state' import MultiReturn from '../multireturn' import RawResult from '../raw-result' import Thread from '../thread' import TypeExtension from '../type-extension' -import { LuaReturn, LuaState } from '../types' +import { LuaReturn, LuaAddress } from '../types' import { isPromise } from '../utils' -import { decorateFunction } from './function' +import { decorate } from '../decoration' class PromiseTypeExtension extends TypeExtension> { private gcPointer: number - public constructor(thread: Global, injectObject: boolean) { + public constructor(thread: LuaState, injectObject: boolean) { super(thread, 'js_promise') - this.gcPointer = thread.lua._emscripten.addFunction((functionStateAddress: LuaState) => { + this.gcPointer = thread.lua._emscripten.addFunction((functionStateAddress: LuaAddress) => { // Throws a lua error which does a jump if it does not match. const userDataPointer = thread.lua.luaL_checkudata(functionStateAddress, 1, this.name) const referencePointer = thread.lua._emscripten.getValue(userDataPointer, '*') @@ -45,12 +45,14 @@ class PromiseTypeExtension extends TypeExtension> { next: (self: Promise, ...args: Parameters) => checkSelf(self) && self.then(...args), catch: (self: Promise, ...args: Parameters) => checkSelf(self) && self.catch(...args), finally: (self: Promise, ...args: Parameters) => checkSelf(self) && self.finally(...args), - await: decorateFunction( + await: decorate( (functionThread: Thread, self: Promise) => { checkSelf(self) - if (functionThread.address === thread.address) { - throw new Error('cannot await in the main thread') + // Asking Lua covers every non-resumable context, not just the main + // thread: anything entered through lua_pcall cannot yield either. + if (!thread.lua.lua_isyieldable(functionThread.address)) { + throw new Error('cannot await in a thread that cannot yield, use doString instead of doStringSync') } let promiseResult: { status: 'fulfilled' | 'rejected'; value: any } | undefined = undefined @@ -64,7 +66,7 @@ class PromiseTypeExtension extends TypeExtension> { promiseResult = { status: 'rejected', value: err } }) - const continuance = this.thread.lua._emscripten.addFunction((continuanceState: LuaState) => { + const continuance = this.thread.lua._emscripten.addFunction((continuanceState: LuaAddress) => { // If this yield has been called from within a coroutine and so manually resumed // then there may not yet be any results. In that case yield again. if (!promiseResult) { @@ -140,6 +142,6 @@ class PromiseTypeExtension extends TypeExtension> { } } -export default function createTypeExtension(thread: Global, injectObject: boolean): TypeExtension> { +export default function createTypeExtension(thread: LuaState, injectObject: boolean): TypeExtension> { return new PromiseTypeExtension(thread, injectObject) } diff --git a/src/type-extensions/proxy.ts b/src/type-extensions/proxy.ts index 9d4d76b..f151a0f 100644 --- a/src/type-extensions/proxy.ts +++ b/src/type-extensions/proxy.ts @@ -1,28 +1,18 @@ -import { BaseDecorationOptions, Decoration } from '../decoration' -import Global from '../global' +import { decorate, Decoration } from '../decoration' +import type LuaState from '../state' import MultiReturn from '../multireturn' import Thread from '../thread' import TypeExtension from '../type-extension' -import { LuaReturn, LuaState, LuaType } from '../types' +import { LuaReturn, LuaAddress, LuaType } from '../types' import { isPromise } from '../utils' -import { decorateFunction } from './function' -export interface ProxyDecorationOptions extends BaseDecorationOptions { - // If undefined, will try to figure out if should proxy - proxy?: boolean -} - -export function decorateProxy(target: unknown, options?: ProxyDecorationOptions): Decoration { - return new Decoration(target, options || {}) -} - -class ProxyTypeExtension extends TypeExtension { +class ProxyTypeExtension extends TypeExtension { private readonly gcPointer: number - public constructor(thread: Global) { + public constructor(thread: LuaState) { super(thread, 'js_proxy') - this.gcPointer = thread.lua._emscripten.addFunction((functionStateAddress: LuaState) => { + this.gcPointer = thread.lua._emscripten.addFunction((functionStateAddress: LuaAddress) => { // Throws a lua error which does a jump if it does not match. const userDataPointer = thread.lua.luaL_checkudata(functionStateAddress, 1, this.name) const referencePointer = thread.lua._emscripten.getValue(userDataPointer, '*') @@ -58,7 +48,7 @@ class ProxyTypeExtension extends TypeExtension { const value = self[key as string | number] if (typeof value === 'function') { - return decorateFunction(value as (...args: any[]) => any, { self }) + return decorate(value as (...args: any[]) => any, { self }) } return value @@ -135,9 +125,9 @@ class ProxyTypeExtension extends TypeExtension { return thread.lua.getRef(referencePointer) } - public pushValue(thread: Thread, decoratedValue: Decoration): boolean { + public pushValue(thread: Thread, decoratedValue: Decoration): boolean { const { target, options } = decoratedValue - if (options.proxy === undefined) { + if (options.as === undefined) { if (target === null || target === undefined) { return false } @@ -154,14 +144,15 @@ class ProxyTypeExtension extends TypeExtension { if (isPromise(target)) { return false } - } else if (options.proxy === false) { + } else if (options.as !== 'proxy') { + // Both 'userdata' and 'value' mean "do not go through the proxy layer". return false } if (options.metatable && !(options.metatable instanceof Decoration)) { // Otherwise the metatable will get converted into a JS ref rather than being set as a standard // table. This forces it to use the standard table type. - decoratedValue.options.metatable = decorateProxy(options.metatable, { proxy: false }) + decoratedValue.options.metatable = decorate(options.metatable, { as: 'value' }) return false } @@ -173,6 +164,6 @@ class ProxyTypeExtension extends TypeExtension { } } -export default function createTypeExtension(thread: Global): TypeExtension { +export default function createTypeExtension(thread: LuaState): TypeExtension { return new ProxyTypeExtension(thread) } diff --git a/src/type-extensions/table.ts b/src/type-extensions/table.ts index 3ca449b..e6e6bbf 100644 --- a/src/type-extensions/table.ts +++ b/src/type-extensions/table.ts @@ -1,5 +1,5 @@ import { Decoration } from '../decoration' -import Global from '../global' +import type LuaState from '../state' import Thread from '../thread' import TypeExtension from '../type-extension' import { LUA_REGISTRYINDEX, LuaType } from '../types' @@ -7,7 +7,7 @@ import { LUA_REGISTRYINDEX, LuaType } from '../types' export type TableType = Record | any[] class TableTypeExtension extends TypeExtension { - public constructor(thread: Global) { + public constructor(thread: LuaState) { super(thread, 'js_table') } @@ -126,6 +126,6 @@ class TableTypeExtension extends TypeExtension { } } -export default function createTypeExtension(thread: Global): TypeExtension { +export default function createTypeExtension(thread: LuaState): TypeExtension { return new TableTypeExtension(thread) } diff --git a/src/type-extensions/userdata.ts b/src/type-extensions/userdata.ts index 89a3811..ac9cd5a 100644 --- a/src/type-extensions/userdata.ts +++ b/src/type-extensions/userdata.ts @@ -1,24 +1,16 @@ -import { BaseDecorationOptions, Decoration } from '../decoration' -import Global from '../global' +import { Decoration } from '../decoration' +import type LuaState from '../state' import Thread from '../thread' import TypeExtension from '../type-extension' -import { LuaReturn, LuaState, LuaType } from '../types' +import { LuaReturn, LuaAddress, LuaType } from '../types' -export interface UserdataDecorationOptions extends BaseDecorationOptions { - reference?: boolean -} - -export function decorateUserdata(target: unknown): Decoration { - return new Decoration(target, { reference: true }) -} - -class UserdataTypeExtension extends TypeExtension { +class UserdataTypeExtension extends TypeExtension { private readonly gcPointer: number - public constructor(thread: Global) { + public constructor(thread: LuaState) { super(thread, 'js_userdata') - this.gcPointer = thread.lua._emscripten.addFunction((functionStateAddress: LuaState) => { + this.gcPointer = thread.lua._emscripten.addFunction((functionStateAddress: LuaAddress) => { // Throws a lua error which does a jump if it does not match. const userDataPointer = thread.lua.luaL_checkudata(functionStateAddress, 1, this.name) const referencePointer = thread.lua._emscripten.getValue(userDataPointer, '*') @@ -53,8 +45,8 @@ class UserdataTypeExtension extends TypeExtension): boolean { - if (!decoratedValue.options.reference) { + public pushValue(thread: Thread, decoratedValue: Decoration): boolean { + if (decoratedValue.options.as !== 'userdata') { return false } @@ -66,6 +58,6 @@ class UserdataTypeExtension extends TypeExtension { +export default function createTypeExtension(thread: LuaState): TypeExtension { return new UserdataTypeExtension(thread) } diff --git a/src/types.ts b/src/types.ts index 393c812..0985b9c 100755 --- a/src/types.ts +++ b/src/types.ts @@ -1,16 +1,138 @@ -export type LuaState = number - -export interface CreateEngineOptions { - /** Injects all the lua standard libraries (math, coroutine, debug) */ - openStandardLibs?: boolean - /** Injects some JS objects to the Lua environment: Error, Promise, null, Objects */ - injectObjects?: boolean - /** Enables the proxy for JS objects, useful for classes, etc... */ - enableProxy?: boolean - /** Whether to trace memory allocations. */ - traceAllocations?: boolean - /** Maximum time in milliseconds a Lua function can run before being interrupted. */ +/** A pointer to a `lua_State` inside the wasm heap. */ +export type LuaAddress = number + +/** Receives diagnostics the library would otherwise have written to the console. */ +export type LuaWarnHandler = (message: string, cause?: unknown) => void + +export const defaultWarnHandler: LuaWarnHandler = (message, cause) => { + if (cause === undefined) { + console.warn(message) + } else { + console.warn(message, cause) + } +} + +export type LuaLibName = 'base' | 'package' | 'coroutine' | 'debug' | 'io' | 'math' | 'os' | 'string' | 'table' | 'utf8' + +/** + * Mirrors the `LUA_*K` bitmask in `lualib.h`. These are transcribed rather than derived, so + * initialization.test.js opens each library alone and checks the global it installs, to catch a + * reordering on a Lua version bump. + */ +export const LUA_LIB_BITS: Record = { + base: 1, + package: 2, + coroutine: 4, + debug: 8, + io: 16, + math: 32, + os: 64, + string: 128, + table: 256, + utf8: 512, +} + +export const ALL_LUA_LIBS = ~0 + +export function resolveLibraryMask(libs: LuaLibName[] | boolean | undefined): number { + if (libs === undefined || libs === true) { + return ALL_LUA_LIBS + } + if (libs === false) { + return 0 + } + + let mask = 0 + for (const lib of libs) { + const bit = LUA_LIB_BITS[lib] + if (bit === undefined) { + throw new Error(`unknown Lua library: ${String(lib)}`) + } + mask |= bit + } + return mask +} + +/** `'t'` accepts text chunks only, `'bt'` also accepts precompiled bytecode. */ +export type LuaLoadMode = 't' | 'bt' + +export interface LuaMemoryOptions { + /** + * Installs a custom allocator so memory can be measured and capped. Without it `state.memory` + * is undefined. + */ + trace?: boolean + /** Maximum bytes the state may allocate. Requires `trace`. */ + max?: number +} + +export interface LuaLimitOptions { + /** Milliseconds a Lua function called from JS may run before being interrupted. */ functionTimeout?: number + /** Instructions a single run may execute before being interrupted. */ + maxInstructions?: number +} + +export interface CreateStateOptions { + /** + * Which standard libraries to open. `true` opens all of them, `false` opens none (which + * leaves the state without even `tostring`), or name them individually. + */ + libs?: LuaLibName[] | boolean + /** + * How plain JS objects and class instances cross into Lua. `'proxy'` keeps their identity and + * exposes their members, `'copy'` marshals them into plain Lua tables. + */ + objects?: 'proxy' | 'copy' + /** + * Registers the JS `Error` to Lua error bridge. Defaults to true when `objects` is `'copy'`, + * because the proxy already covers errors when it is enabled. + */ + errors?: boolean + /** Injects `Error`, `Promise` and `null` into the Lua globals. */ + inject?: boolean + memory?: LuaMemoryOptions + limits?: LuaLimitOptions + /** Where diagnostics go. Defaults to `console.warn`. */ + onWarn?: LuaWarnHandler +} + +export interface LuaRunOptions { + /** Milliseconds before the run is interrupted. */ + timeout?: number + /** Instructions the run may execute before being interrupted. */ + maxInstructions?: number + /** + * Interrupts the run when the signal aborts. + * + * The abort is observed at the debug hook and around every yield, which has two consequences. + * It cannot fire while the event loop is blocked, so a signal aborted from a timer will not + * interrupt a tight synchronous Lua loop; use `timeout` or `maxInstructions` for those, since + * the hook evaluates them on its own. And a run parked on a promise finishes awaiting that + * promise before the abort is seen, rather than abandoning it mid-flight. + */ + signal?: AbortSignal +} + +export interface LuaLoadOptions { + /** + * Defaults to `'t'`. Lua does not verify the consistency of binary chunks, so accepting + * bytecode from an untrusted source is a memory safety hole rather than a sandbox escape. + * Only widen this for chunks you produced yourself. + */ + mode?: LuaLoadMode + /** Chunk name used in error messages and tracebacks. */ + name?: string +} + +export type LuaDoOptions = LuaRunOptions & LuaLoadOptions + +/** Deadline and budget enforced by the debug hook while a thread runs. */ +export interface LuaThreadLimits { + /** Absolute timestamp, as returned by `Date.now()`. */ + deadline?: number + maxInstructions?: number + signal?: AbortSignal } export enum LuaReturn { @@ -28,10 +150,6 @@ export interface LuaResumeResult { resultCount: number } -export interface LuaThreadRunOptions { - timeout?: number -} - export const PointerSize = 4 export const LUA_MULTRET = -1 @@ -66,17 +184,55 @@ export enum LuaEventMasks { Count = 1 << LuaEventCodes.Count, } -export enum LuaLibraries { - Base = '_G', - Coroutine = 'coroutine', - Table = 'table', - IO = 'io', - OS = 'os', - String = 'string', - UTF8 = 'utf8', - Math = 'math', - Debug = 'debug', - Package = 'package', +/** + * An error raised by Lua itself. The pieces are kept apart rather than flattened into `message` + * so callers can match on `code`, re-raise `luaValue`, or render the traceback separately. + */ +export class LuaError extends Error { + public override readonly name: string = 'LuaError' + /** Which `lua_pcall`/`lua_resume` status produced this. */ + public readonly code: LuaReturn + /** The error text on its own, without the traceback appended. */ + public readonly luaMessage: string + public readonly traceback: string | undefined + /** The value Lua actually raised, which is not always a string. */ + public readonly luaValue: unknown + + public constructor(code: LuaReturn, luaMessage: string, options: { traceback?: string; luaValue?: unknown } = {}) { + super(luaMessage) + this.code = code + this.luaMessage = luaMessage + this.traceback = options.traceback + this.luaValue = options.luaValue + + if (options.luaValue instanceof Error && options.luaValue.stack) { + // A JS error that travelled through Lua keeps the stack from where it was thrown. + this.stack = options.luaValue.stack + } else if (options.traceback) { + // Default logging only prints `stack`, so the traceback still has to be reachable + // there even though it is no longer part of the message. + this.stack = `${this.name}: ${luaMessage}\n${options.traceback}` + } + } } -export class LuaTimeoutError extends Error {} +/** + * Raised by the debug hook to unwind a run that hit a limit. These are control flow rather than + * Lua errors, so they reach the caller unwrapped instead of inside a {@link LuaError}, and a + * single `catch` covers every way a run can be cut short. + */ +export class LuaInterruptError extends Error { + public override readonly name: string = 'LuaInterruptError' +} + +export class LuaTimeoutError extends LuaInterruptError { + public override readonly name: string = 'LuaTimeoutError' +} + +export class LuaInstructionLimitError extends LuaInterruptError { + public override readonly name: string = 'LuaInstructionLimitError' +} + +export class LuaAbortError extends LuaInterruptError { + public override readonly name: string = 'LuaAbortError' +} diff --git a/test/browser.test.js b/test/browser.test.js index 57d94e2..ea7bb3c 100644 --- a/test/browser.test.js +++ b/test/browser.test.js @@ -19,9 +19,9 @@ function startServer() { @@ -92,7 +92,7 @@ describe('Browser environment', () => { it('load Lua engine in browser should succeed', async function () { this.timeout(30_000) const result = await runInBrowser(` - const lua = await Lua.load({ wasmFile }) + const lua = await LuaRuntime.load({ wasmFile }) const state = lua.createState() return state !== undefined `) @@ -102,7 +102,7 @@ describe('Browser environment', () => { it('execute Lua code in browser should succeed', async function () { this.timeout(30_000) const result = await runInBrowser(` - const lua = await Lua.load({ wasmFile }) + const lua = await LuaRuntime.load({ wasmFile }) const state = lua.createState() return await state.doString('return 2 + 2') `) @@ -112,9 +112,9 @@ describe('Browser environment', () => { it('pass JS values to Lua and back in browser should succeed', async function () { this.timeout(30_000) const result = await runInBrowser(` - const lua = await Lua.load({ wasmFile }) - const state = lua.createState({ injectObjects: true }) - state.global.set('name', 'wasmoon') + const lua = await LuaRuntime.load({ wasmFile }) + const state = lua.createState({ inject: true }) + state.set('name', 'wasmoon') return await state.doString('return "hello " .. name') `) expect(result).to.be.equal('hello wasmoon') @@ -123,9 +123,9 @@ describe('Browser environment', () => { it('call JS function from Lua in browser should succeed', async function () { this.timeout(30_000) const result = await runInBrowser(` - const lua = await Lua.load({ wasmFile }) - const state = lua.createState({ injectObjects: true }) - state.global.set('add', (a, b) => a + b) + const lua = await LuaRuntime.load({ wasmFile }) + const state = lua.createState({ inject: true }) + state.set('add', (a, b) => a + b) return await state.doString('return add(10, 20)') `) expect(result).to.be.equal(30) @@ -134,7 +134,7 @@ describe('Browser environment', () => { it('mount and require a file in browser should succeed', async function () { this.timeout(30_000) const result = await runInBrowser(` - const lua = await Lua.load({ wasmFile }) + const lua = await LuaRuntime.load({ wasmFile }) lua.mountFile('mymodule.lua', 'return 42') const state = lua.createState() return await state.doString('return require("mymodule")') @@ -145,8 +145,8 @@ describe('Browser environment', () => { it('handle Lua tables as JS objects in browser should succeed', async function () { this.timeout(30_000) const result = await runInBrowser(` - const lua = await Lua.load({ wasmFile }) - const state = lua.createState({ injectObjects: true }) + const lua = await LuaRuntime.load({ wasmFile }) + const state = lua.createState({ inject: true }) const value = await state.doString('return { x = 10, y = 20 }') return { x: value.x, y: value.y } `) @@ -156,7 +156,7 @@ describe('Browser environment', () => { it('handle errors in browser should succeed', async function () { this.timeout(30_000) const result = await runInBrowser(` - const lua = await Lua.load({ wasmFile }) + const lua = await LuaRuntime.load({ wasmFile }) const state = lua.createState() try { await state.doString('error("test error")') @@ -171,7 +171,7 @@ describe('Browser environment', () => { it('use coroutines in browser should succeed', async function () { this.timeout(30_000) const result = await runInBrowser(` - const lua = await Lua.load({ wasmFile }) + const lua = await LuaRuntime.load({ wasmFile }) const state = lua.createState() return await state.doString(\` local co = coroutine.create(function() @@ -196,7 +196,7 @@ describe('Browser environment', () => { this.timeout(30_000) // Browsers have no setImmediate, which the yield path used to depend on. const result = await runInBrowser(` - const lua = await Lua.load({ wasmFile }) + const lua = await LuaRuntime.load({ wasmFile }) const state = lua.createState() return await state.doString('coroutine.yield() return 7') `) diff --git a/test/debug.js b/test/debug.js index 1373e84..9f6e871 100644 --- a/test/debug.js +++ b/test/debug.js @@ -2,9 +2,9 @@ import { getState } from './utils.js' // This file was created as a sandbox to test and debug on vscode const state = await getState() -state.global.set('potato', { +state.set('potato', { test: true, hello: ['world'], }) -state.global.get('potato') +state.get('potato') state.doStringSync('print(potato.hello[1])') diff --git a/test/errors.test.js b/test/errors.test.js new file mode 100644 index 0000000..2d9c9c6 --- /dev/null +++ b/test/errors.test.js @@ -0,0 +1,70 @@ +import { LuaRuntime, LuaError } from '../dist/index.js' +import { expect } from 'chai' +import { getState } from './utils.js' + +describe('LuaError', () => { + it('keeps the raised value, message and traceback apart', async () => { + const state = await getState() + + try { + await state.doString(`error({ code = 7 })`) + throw new Error('should not be reached') + } catch (err) { + expect(err).to.be.instanceOf(LuaError) + expect(err.code).to.be.equal(2) + expect(err.luaValue).to.be.eql({ code: 7 }) + expect(err.message).to.not.include('stack traceback:') + expect(err.traceback).to.include('stack traceback:') + } + }) + + it('a JS error thrown through Lua keeps its own stack', async () => { + const state = await getState() + const thrown = new Error('from js') + state.set('boom', () => { + throw thrown + }) + + try { + await state.doString('boom()') + throw new Error('should not be reached') + } catch (err) { + expect(err.luaValue).to.be.equal(thrown) + expect(err.stack).to.be.equal(thrown.stack) + } + }) +}) + +describe('Unrepresentable values', () => { + it('getValue throws instead of returning an opaque handle', async () => { + const state = await getState() + const thread = state.newThread() + thread.lua.lua_newuserdatauv(thread.address, 4, 0) + + expect(() => thread.getValue(-1)).to.throw('has no JS representation') + }) + + it('the address is still reachable through getPointer', async () => { + const state = await getState() + const thread = state.newThread() + thread.lua.lua_newuserdatauv(thread.address, 4, 0) + + expect(Number(thread.getPointer(-1))).to.be.greaterThan(0) + }) +}) + +describe('Warnings', () => { + it('onWarn receives diagnostics instead of the console', async () => { + const lua = await LuaRuntime.load() + const seen = [] + using state = lua.createState({ onWarn: (message) => seen.push(message) }) + + state.getTable('_G', () => { + // Leaves the stack unbalanced on purpose. + state.lua.lua_pushnil(state.address) + }) + + expect(seen).to.have.lengthOf(1) + expect(seen[0]).to.include('getTable: expected stack size') + }) +}) diff --git a/test/filesystem.test.js b/test/filesystem.test.js index d1c5f54..09a5f16 100644 --- a/test/filesystem.test.js +++ b/test/filesystem.test.js @@ -9,7 +9,7 @@ describe('Filesystem', () => { await state.doString('require("test")') - expect(state.global.get('answerToLifeTheUniverseAndEverything')).to.be.equal(42) + expect(state.get('answerToLifeTheUniverseAndEverything')).to.be.equal(42) }) it('mount a file in a complex directory and require inside lua should succeed', async () => { diff --git a/test/initialization.test.js b/test/initialization.test.js index 90952b4..ab8f214 100644 --- a/test/initialization.test.js +++ b/test/initialization.test.js @@ -1,27 +1,27 @@ -import { Lua } from '../dist/index.js' +import { LuaRuntime } from '../dist/index.js' import { expect } from 'chai' describe('Initialization', () => { it('create state should succeed', async () => { - const lua = await Lua.load() + const lua = await LuaRuntime.load() lua.createState() }) it('create multiple states should succeed', async () => { - const lua = await Lua.load() + const lua = await LuaRuntime.load() const state1 = lua.createState() const state2 = lua.createState() - expect(state1.global.address).to.not.be.equal(state2.global.address) + expect(state1.address).to.not.be.equal(state2.address) }) it('create state with options should succeed', async () => { - const lua = await Lua.load() + const lua = await LuaRuntime.load() lua.createState({ - enableProxy: true, - injectObjects: true, - openStandardLibs: true, - traceAllocations: true, + objects: 'proxy', + inject: true, + libs: true, + memory: { trace: true }, }) }) @@ -29,7 +29,7 @@ describe('Initialization', () => { const env = { ENV_TEST: 'test', } - const lua = await Lua.load({ env }) + const lua = await LuaRuntime.load({ env }) const state = lua.createState() const value = await state.doString('return os.getenv("ENV_TEST")') @@ -37,3 +37,110 @@ describe('Initialization', () => { expect(value).to.be.equal(env.ENV_TEST) }) }) + +describe('Standard libraries', () => { + // LUA_LIB_BITS is transcribed by hand from lualib.h, so each bit is checked against the + // global its library installs. A reordering on a Lua version bump fails here. + const cases = [ + ['base', 'print'], + ['package', 'require'], + ['coroutine', 'coroutine'], + ['debug', 'debug'], + ['io', 'io'], + ['math', 'math'], + ['os', 'os'], + ['string', 'string'], + ['table', 'table'], + ['utf8', 'utf8'], + ] + + for (const [lib, global] of cases) { + it(`libs: ['${lib}'] installs ${global} and nothing else`, async () => { + const lua = await LuaRuntime.load() + // base comes along so `type` exists; io holds FILE* userdata with no JS + // representation, so presence is asserted from Lua rather than marshalled. + using state = lua.createState({ libs: lib === 'base' ? ['base'] : ['base', lib] }) + const typeOf = (name) => state.doStringSync(`return type(${name})`) + + expect(typeOf(global), `${lib} should install ${global}`).to.not.be.equal('nil') + + for (const [otherLib, otherGlobal] of cases) { + if (otherLib === lib || otherLib === 'base' || otherGlobal === global) { + continue + } + expect(typeOf(otherGlobal), `${lib} should not install ${otherGlobal}`).to.be.equal('nil') + } + }) + } + + it('libs: false leaves the state empty', async () => { + const lua = await LuaRuntime.load() + using state = lua.createState({ libs: false }) + + // Without the base library there is no `type` either, so this reads the globals directly. + expect(state.get('print')).to.be.null + expect(state.get('tostring')).to.be.null + }) + + it('libs defaults to all of them', async () => { + const lua = await LuaRuntime.load() + using state = lua.createState() + + for (const [, global] of cases) { + expect(state.doStringSync(`return type(${global})`), global).to.not.be.equal('nil') + } + }) + + it('an unknown library name is rejected', async () => { + const lua = await LuaRuntime.load() + + expect(() => lua.createState({ libs: ['nope'] })).to.throw('unknown Lua library: nope') + }) +}) + +describe('Disposal', () => { + it('using closes the state at the end of the block', async () => { + const lua = await LuaRuntime.load() + let escaped + { + using state = lua.createState() + escaped = state + expect(state.isClosed()).to.be.false + } + + expect(escaped.isClosed()).to.be.true + }) + + it('closing the runtime closes every state it created', async () => { + const lua = await LuaRuntime.load() + const first = lua.createState() + const second = lua.createState() + + lua.close() + + expect(first.isClosed()).to.be.true + expect(second.isClosed()).to.be.true + }) + + it('a closed state is released by the runtime that made it', async () => { + const lua = await LuaRuntime.load() + + // Without this the Set grows for the runtime's lifetime, which a create/close loop hits. + for (let index = 0; index < 100; index++) { + lua.createState().close() + } + const retained = Object.values(lua).find((value) => value instanceof Set) + + expect(retained.size).to.be.equal(0) + }) + + it('await using disposes the runtime', async () => { + let escaped + { + await using lua = await LuaRuntime.load() + escaped = lua.createState() + } + + expect(escaped.isClosed()).to.be.true + }) +}) diff --git a/test/limits.test.js b/test/limits.test.js new file mode 100644 index 0000000..6a9323f --- /dev/null +++ b/test/limits.test.js @@ -0,0 +1,75 @@ +import { LuaInterruptError, LuaTimeoutError, LuaInstructionLimitError, LuaAbortError } from '../dist/index.js' +import { expect } from 'chai' +import { getState } from './utils.js' + +describe('Run limits', () => { + const busyLoop = 'local x = 0 for i = 1, 1e9 do x = x + 1 end return x' + + it('timeout interrupts a tight loop', async function () { + this.timeout(20_000) + const state = await getState() + + await expect(state.doString(busyLoop, { timeout: 20 })).to.eventually.be.rejectedWith(LuaTimeoutError) + }) + + it('maxInstructions interrupts a tight loop', async function () { + this.timeout(20_000) + const state = await getState() + + await expect(state.doString(busyLoop, { maxInstructions: 5_000 })).to.eventually.be.rejectedWith(LuaInstructionLimitError) + }) + + it('an already aborted signal stops the run', async function () { + this.timeout(20_000) + const state = await getState() + + await expect(state.doString(busyLoop, { signal: AbortSignal.abort() })).to.eventually.be.rejectedWith(LuaAbortError) + }) + + it('a signal aborted while parked on a promise stops the run', async function () { + this.timeout(20_000) + const state = await getState() + state.set('sleep', (ms) => new Promise((resolve) => setTimeout(resolve, ms))) + const controller = new AbortController() + setTimeout(() => controller.abort(), 5) + + await expect(state.doString('sleep(30):await() return 1', { signal: controller.signal })).to.eventually.be.rejectedWith( + LuaAbortError, + ) + }) + + it('maxInstructions from the state options applies to every run', async function () { + this.timeout(20_000) + using state = await getState({ limits: { maxInstructions: 5_000 } }) + + await expect(state.doString(busyLoop)).to.eventually.be.rejectedWith(LuaInstructionLimitError) + expect(await state.doString('return 1 + 1')).to.be.equal(2) + }) + + it('setLimits on the state reaches both the sync and the async path', async function () { + this.timeout(20_000) + using state = await getState() + state.setLimits({ maxInstructions: 5_000 }) + + await expect(state.doString(busyLoop)).to.eventually.be.rejectedWith(LuaInstructionLimitError) + expect(() => state.doStringSync(busyLoop)).to.throw(LuaInstructionLimitError) + }) + + it('every limit shares one catchable base', async function () { + this.timeout(20_000) + using state = await getState() + + for (const options of [{ timeout: 20 }, { maxInstructions: 5_000 }, { signal: AbortSignal.abort() }]) { + await expect(state.doString(busyLoop, options)).to.eventually.be.rejectedWith(LuaInterruptError) + } + }) + + it('limits are restored after a scoped run', async () => { + const state = await getState() + state.setLimits({ maxInstructions: 999 }) + + await state.doString('return 1', { maxInstructions: 10_000 }) + + expect(state.getLimits().maxInstructions).to.be.equal(999) + }) +}) diff --git a/test/luatests.js b/test/luatests.js index 27460f6..e873287 100644 --- a/test/luatests.js +++ b/test/luatests.js @@ -1,8 +1,8 @@ -import { Lua } from '../dist/index.js' +import { LuaRuntime } from '../dist/index.js' import { fileURLToPath } from 'node:url' import { readFile, glob } from 'node:fs/promises' -const lua = await Lua.load() +const lua = await LuaRuntime.load() const testsPath = import.meta.resolve('../lua/testes') const filePath = fileURLToPath(typeof testsPath === 'string' ? testsPath : await Promise.resolve(testsPath)) @@ -33,11 +33,11 @@ for await (const file of glob(`${filePath}/**/*.lua`)) { } const state = lua.createState() -lua.module.lua_warning(state.global.address, '@on', 0) -state.global.set('arg', ['lua', 'all.lua']) -state.global.set('_port', true) -state.global.getTable('os', (i) => { - state.global.setField(i, 'setlocale', (locale) => { +lua.module.lua_warning(state.address, '@on', 0) +state.set('arg', ['lua', 'all.lua']) +state.set('_port', true) +state.getTable('os', (i) => { + state.setField(i, 'setlocale', (locale) => { return locale && locale !== 'C' ? false : 'C' }) }) diff --git a/test/node.test.js b/test/node.test.js index 1fd0ded..c581084 100644 --- a/test/node.test.js +++ b/test/node.test.js @@ -3,25 +3,44 @@ import { join } from 'node:path' import { tmpdir } from 'node:os' import { spawn } from 'node:child_process' import { expect } from 'chai' -import { Lua } from '../dist/index.js' +import { LuaRuntime } from '../dist/index.js' -// stdin stays closed, as it would be for a redirected or piped invocation. The CLI keeps a -// readline interface open otherwise and never exits. -const runCli = (args) => { +// stdin is closed by default, as it would be for a redirected or piped invocation with nothing +// to read. +const runCli = (args, input) => { return new Promise((resolve, reject) => { - const child = spawn(process.execPath, ['bin/wasmoon', ...args], { stdio: ['ignore', 'pipe', 'pipe'] }) + const child = spawn(process.execPath, ['bin/wasmoon', ...args], { + stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'], + }) let stdout = '' let stderr = '' child.stdout.on('data', (chunk) => (stdout += chunk)) child.stderr.on('data', (chunk) => (stderr += chunk)) child.on('error', reject) child.on('close', (code) => resolve({ code, stdout, stderr })) + if (input !== undefined) { + child.stdin.end(input) + } }) } +// Collects everything the given script writes to the chosen stream. +const collectOutput = async (stream, script, opts = {}) => { + const output = [] + const lua = await LuaRuntime.load({ ...opts, [stream]: (content) => output.push(content) }) + await lua.createState().doString(script) + return output +} + +// Feeds one chunk per read, and then the empty string that stands for EOF. +const stdinFrom = (chunks) => { + let index = 0 + return () => chunks[index++] ?? '' +} + describe('Node environment', () => { it('load Lua engine in node should succeed', async () => { - const lua = await Lua.load() + const lua = await LuaRuntime.load() const state = lua.createState() const result = await state.doString('return 1 + 1') expect(result).to.be.equal(2) @@ -29,42 +48,32 @@ describe('Node environment', () => { it('access environment variables should succeed', async () => { const env = { MY_TEST_VAR: 'hello_from_node' } - const lua = await Lua.load({ env }) + const lua = await LuaRuntime.load({ env }) const state = lua.createState() const result = await state.doString('return os.getenv("MY_TEST_VAR")') expect(result).to.be.equal('hello_from_node') }) it('custom stdout should succeed', async () => { - const output = [] - const lua = await Lua.load({ - stdout: (content) => output.push(content), - }) - const state = lua.createState() - await state.doString('print("hello from node")') + const output = await collectOutput('stdout', 'print("hello from node")') expect(output.join('')).to.include('hello from node') }) it('custom stderr should succeed', async () => { - const errors = [] - const lua = await Lua.load({ - stderr: (content) => errors.push(content), - }) - const state = lua.createState() - await state.doString('io.stderr:write("error output\\n")') + const errors = await collectOutput('stderr', 'io.stderr:write("error output\\n")') expect(errors.join('')).to.include('error output') }) it('mount file and require in node should succeed', async () => { - const lua = await Lua.load() + const lua = await LuaRuntime.load() lua.mountFile('nodetest.lua', 'return { value = 99 }') - const state = lua.createState({ injectObjects: true }) + const state = lua.createState({ inject: true }) const result = await state.doString('local m = require("nodetest"); return m.value') expect(result).to.be.equal(99) }) it('mount file with binary content should succeed', async () => { - const lua = await Lua.load() + const lua = await LuaRuntime.load() const content = new Uint8Array([114, 101, 116, 117, 114, 110, 32, 52, 50]) // "return 42" lua.mountFile('binary.lua', content) const state = lua.createState() @@ -73,7 +82,7 @@ describe('Node environment', () => { }) it('mount file in nested directories should succeed', async () => { - const lua = await Lua.load() + const lua = await LuaRuntime.load() lua.mountFile('a/b/c/deep.lua', 'return "deep"') const state = lua.createState() const result = await state.doString('return require("a/b/c/deep")') @@ -81,7 +90,7 @@ describe('Node environment', () => { }) it('create multiple independent states should succeed', async () => { - const lua = await Lua.load() + const lua = await LuaRuntime.load() const state1 = lua.createState() const state2 = lua.createState() @@ -96,8 +105,8 @@ describe('Node environment', () => { }) it('pass complex JS objects to Lua should succeed', async () => { - const state = (await Lua.load()).createState({ injectObjects: true }) - state.global.set('data', { + const state = (await LuaRuntime.load()).createState({ inject: true }) + state.set('data', { name: 'test', nested: { value: 42 }, items: [1, 2, 3], @@ -107,8 +116,8 @@ describe('Node environment', () => { }) it('call JS async functions from Lua should succeed', async () => { - const state = (await Lua.load()).createState({ injectObjects: true }) - state.global.set('fetchData', async () => { + const state = (await LuaRuntime.load()).createState({ inject: true }) + state.set('fetchData', async () => { return 'async result' }) const result = await state.doString('return fetchData():await()') @@ -122,7 +131,7 @@ describe('Node environment', () => { writeFileSync(testFile, 'hello from host') try { - const lua = await Lua.load({ fs: 'node' }) + const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() const result = await state.doString(` local f = io.open("${testFile.replace(/\\/g, '/')}", "r") @@ -142,7 +151,7 @@ describe('Node environment', () => { const testFile = join(tempDir, 'output.txt') try { - const lua = await Lua.load({ fs: 'node' }) + const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() await state.doString(` local f = io.open("${testFile.replace(/\\/g, '/')}", "w") @@ -157,7 +166,7 @@ describe('Node environment', () => { }) it('NODEFS cwd should match process.cwd', async () => { - const lua = await Lua.load({ fs: 'node' }) + const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() // Write a temp file in the CWD and verify it can be read const markerFile = join(process.cwd(), `.wasmoon-cwd-test-${Date.now()}.tmp`) @@ -183,7 +192,7 @@ describe('Node environment', () => { writeFileSync(testFile, 'mounted content') try { - const lua = await Lua.load({ fs: 'node', fsMountPaths: [tmpdir()] }) + const lua = await LuaRuntime.load({ fs: 'node', fsMountPaths: [tmpdir()] }) const state = lua.createState() const result = await state.doString(` local f = io.open("${testFile.replace(/\\/g, '/')}", "r") @@ -199,7 +208,7 @@ describe('Node environment', () => { }) it('NODEFS opening nonexistent file should return nil', async () => { - const lua = await Lua.load({ fs: 'node' }) + const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() const result = await state.doString(` local f, err = io.open("/tmp/wasmoon_nonexistent_file_${Date.now()}.txt", "r") @@ -215,7 +224,7 @@ describe('Node environment', () => { writeFileSync(hostFile, 'from host') try { - const lua = await Lua.load({ fs: 'node' }) + const lua = await LuaRuntime.load({ fs: 'node' }) lua.mountFile('virtual.lua', 'return "from virtual"') const state = lua.createState() @@ -236,7 +245,7 @@ describe('Node environment', () => { }) it('standard libraries are available should succeed', async () => { - const state = (await Lua.load()).createState() + const state = (await LuaRuntime.load()).createState() const result = await state.doString(` local checks = {} checks[1] = type(string.format) == "function" @@ -253,7 +262,7 @@ describe('Node environment', () => { }) it('error handling with pcall should succeed', async () => { - const state = (await Lua.load()).createState() + const state = (await LuaRuntime.load()).createState() const result = await state.doString(` local ok, err = pcall(function() error("node test error") @@ -263,6 +272,101 @@ describe('Node environment', () => { expect(result).to.be.true }) + it('custom stdout should keep multi byte characters intact', async () => { + const output = await collectOutput('stdout', 'print("héllo 日本語 🎉")') + expect(output).to.be.deep.equal(['héllo 日本語 🎉']) + }) + + it('custom stderr should keep multi byte characters intact', async () => { + const errors = await collectOutput('stderr', 'io.stderr:write("erro ✗ 日本\\n")') + expect(errors).to.be.deep.equal(['erro ✗ 日本']) + }) + + it('custom stdout should keep a character that is flushed in the middle intact', async () => { + // The two halves of 日 land in different writes, with the engine handing control back to + // JS in between. + const output = [] + const lua = await LuaRuntime.load({ stdout: (content) => output.push(content) }) + const state = lua.createState() + state.set( + 'pause', + () => + new Promise((resolve) => { + setTimeout(resolve, 0) + }), + ) + await state.doString('io.write("\\xE6") io.flush() pause():await() io.write("\\x97\\xA5 ok\\n")') + expect(output).to.be.deep.equal(['日 ok']) + }) + + it('custom stdout should split on line breaks only', async () => { + const output = await collectOutput('stdout', 'print("first") print("") io.write("a\\rb\\n")') + expect(output).to.be.deep.equal(['first', '', 'a\rb']) + }) + + it('custom stdout should receive flushed output that does not end in a line break', async () => { + const output = await collectOutput('stdout', 'io.write("no newline") io.flush()') + expect(output).to.be.deep.equal(['no newline']) + }) + + it('custom stdout should not split a line that is written in parts', async () => { + const output = await collectOutput('stdout', 'io.write("one ") io.flush() io.write("line\\n")') + expect(output).to.be.deep.equal(['one line']) + }) + + it('custom stdout should handle lines longer than its buffer', async () => { + const output = await collectOutput('stdout', 'print(string.rep("ção ", 1000))') + expect(output).to.be.deep.equal(['ção '.repeat(1000)]) + }) + + it('custom stdin should be read line by line', async () => { + const lua = await LuaRuntime.load({ stdin: stdinFrom(['um\n', 'dois\n']) }) + const result = await lua.createState().doString('return { io.read("l"), io.read("l"), io.read("l") == nil }') + expect(result).to.be.deep.equal(['um', 'dois', true]) + }) + + it('custom stdin should keep multi byte characters intact', async () => { + const lua = await LuaRuntime.load({ stdin: stdinFrom(['héllo 日本語 🎉\n']) }) + const result = await lua.createState().doString('return io.read("l")') + expect(result).to.be.equal('héllo 日本語 🎉') + }) + + it('custom stdin should be read until it signals the end of the input', async () => { + const lua = await LuaRuntime.load({ stdin: stdinFrom(['abc\n', 'déf\n']) }) + const result = await lua.createState().doString('return io.read("a")') + expect(result).to.be.equal('abc\ndéf\n') + }) + + it('cli should read piped input from within a script', async function () { + this.timeout(30_000) + const { code, stdout, stderr } = await runCli( + ['-e', 'print(io.read("l")) print(io.read("l")) print(io.read("l") == nil)'], + 'olá mundo\nsegunda linha\n', + ) + + expect(stderr).to.be.empty + expect(code).to.be.equal(0) + expect(stdout).to.be.equal('olá mundo\nsegunda linha\ntrue\n') + }) + + it('cli should not add a line break to input that does not end with one', async function () { + this.timeout(30_000) + const { code, stdout, stderr } = await runCli(['-e', 'print(#io.read("a"))'], 'abc') + + expect(stderr).to.be.empty + expect(code).to.be.equal(0) + expect(stdout).to.be.equal('3\n') + }) + + it('cli should not run piped input as a script when -e is given', async function () { + this.timeout(30_000) + const { code, stdout, stderr } = await runCli(['-e', 'print("from -e")'], 'this is not lua code\n') + + expect(stderr).to.be.empty + expect(code).to.be.equal(0) + expect(stdout).to.be.equal('from -e\n') + }) + it('cli should expose arg as a lua table', async function () { this.timeout(30_000) const directory = mkdtempSync(join(tmpdir(), 'wasmoon-cli-')) diff --git a/test/nodefs.test.js b/test/nodefs.test.js index 27f5d9d..c83320e 100644 --- a/test/nodefs.test.js +++ b/test/nodefs.test.js @@ -2,7 +2,7 @@ import { readFileSync, writeFileSync, mkdirSync, rmSync, existsSync } from 'node import { join } from 'node:path' import { tmpdir } from 'node:os' import { expect } from 'chai' -import { Lua } from '../dist/index.js' +import { LuaRuntime } from '../dist/index.js' const createTempDir = () => { const dir = join(tmpdir(), `wasmoon-nodefs-${Date.now()}-${Math.random().toString(36).slice(2)}`) @@ -24,7 +24,7 @@ describe('Node FS', () => { it('read a host file should succeed', async () => { writeFileSync(join(tempDir, 'hello.txt'), 'hello world') - const lua = await Lua.load({ fs: 'node' }) + const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() const result = await state.doString(` local f = io.open("${join(tempDir, 'hello.txt').replace(/\\/g, '/')}", "r") @@ -39,7 +39,7 @@ describe('Node FS', () => { it('write a file to host should succeed', async () => { const filePath = join(tempDir, 'output.txt') - const lua = await Lua.load({ fs: 'node' }) + const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() await state.doString(` local f = io.open("${filePath.replace(/\\/g, '/')}", "w") @@ -54,7 +54,7 @@ describe('Node FS', () => { const filePath = join(tempDir, 'append.txt') writeFileSync(filePath, 'first line\n') - const lua = await Lua.load({ fs: 'node' }) + const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() await state.doString(` local f = io.open("${filePath.replace(/\\/g, '/')}", "a") @@ -68,7 +68,7 @@ describe('Node FS', () => { it('read file line by line should succeed', async () => { writeFileSync(join(tempDir, 'lines.txt'), 'alpha\nbeta\ngamma\n') - const lua = await Lua.load({ fs: 'node' }) + const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() const result = await state.doString(` local lines = {} @@ -85,7 +85,7 @@ describe('Node FS', () => { const buf = Buffer.from([0x00, 0x01, 0x02, 0xff, 0xfe]) writeFileSync(join(tempDir, 'binary.dat'), buf) - const lua = await Lua.load({ fs: 'node' }) + const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() const result = await state.doString(` local f = io.open("${join(tempDir, 'binary.dat').replace(/\\/g, '/')}", "rb") @@ -100,7 +100,7 @@ describe('Node FS', () => { it('write and read back binary data should succeed', async () => { const filePath = join(tempDir, 'binout.dat') - const lua = await Lua.load({ fs: 'node' }) + const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() await state.doString(` local f = io.open("${filePath.replace(/\\/g, '/')}", "wb") @@ -114,7 +114,7 @@ describe('Node FS', () => { it('check if file exists using io.open should succeed', async () => { writeFileSync(join(tempDir, 'exists.txt'), 'yes') - const lua = await Lua.load({ fs: 'node' }) + const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() const result = await state.doString(` local f = io.open("${join(tempDir, 'exists.txt').replace(/\\/g, '/')}", "r") @@ -134,7 +134,7 @@ describe('Node FS', () => { it('read file size should succeed', async () => { writeFileSync(join(tempDir, 'sized.txt'), 'abcdefghij') - const lua = await Lua.load({ fs: 'node' }) + const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() const result = await state.doString(` local f = io.open("${join(tempDir, 'sized.txt').replace(/\\/g, '/')}", "r") @@ -149,7 +149,7 @@ describe('Node FS', () => { it('seek within a file should succeed', async () => { writeFileSync(join(tempDir, 'seek.txt'), 'abcdefghij') - const lua = await Lua.load({ fs: 'node' }) + const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() const result = await state.doString(` local f = io.open("${join(tempDir, 'seek.txt').replace(/\\/g, '/')}", "r") @@ -165,7 +165,7 @@ describe('Node FS', () => { it('doFile from host filesystem should succeed', async () => { writeFileSync(join(tempDir, 'script.lua'), 'return 7 * 6') - const lua = await Lua.load({ fs: 'node' }) + const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() const result = await state.doFile(join(tempDir, 'script.lua').replace(/\\/g, '/')) @@ -177,8 +177,8 @@ describe('Node FS', () => { mkdirSync(luaDir, { recursive: true }) writeFileSync(join(luaDir, 'mymod.lua'), 'local M = {}; M.value = 99; return M') - const lua = await Lua.load({ fs: 'node' }) - const state = lua.createState({ injectObjects: true }) + const lua = await LuaRuntime.load({ fs: 'node' }) + const state = lua.createState({ inject: true }) const result = await state.doString(` package.path = "${luaDir.replace(/\\/g, '/')}/?.lua;" .. package.path local m = require("mymod") @@ -193,7 +193,7 @@ describe('Node FS', () => { mkdirSync(nested, { recursive: true }) writeFileSync(join(nested, 'deep.txt'), 'deep content') - const lua = await Lua.load({ fs: 'node' }) + const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() const result = await state.doString(` local f = io.open("${join(nested, 'deep.txt').replace(/\\/g, '/')}", "r") @@ -208,7 +208,7 @@ describe('Node FS', () => { it('create directory from lua with os.execute should succeed', async () => { const newDir = join(tempDir, 'newdir') - const lua = await Lua.load({ fs: 'node' }) + const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() await state.doString(` os.execute("mkdir -p '${newDir.replace(/\\/g, '/')}'") @@ -221,7 +221,7 @@ describe('Node FS', () => { const filePath = join(tempDir, 'removeme.txt') writeFileSync(filePath, 'to be deleted') - const lua = await Lua.load({ fs: 'node' }) + const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() const result = await state.doString(` return os.remove("${filePath.replace(/\\/g, '/')}") @@ -236,7 +236,7 @@ describe('Node FS', () => { const newPath = join(tempDir, 'new.txt') writeFileSync(oldPath, 'rename me') - const lua = await Lua.load({ fs: 'node' }) + const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() const result = await state.doString(` return os.rename("${oldPath.replace(/\\/g, '/')}", "${newPath.replace(/\\/g, '/')}") @@ -249,7 +249,7 @@ describe('Node FS', () => { it('doFile from cwd-relative path should succeed', async () => { // NODEFS sets cwd to process.cwd(), so relative doFile should work - const lua = await Lua.load({ fs: 'node' }) + const lua = await LuaRuntime.load({ fs: 'node' }) lua.mountFile('cwd_test.lua', 'return "from cwd"') try { const state = lua.createState() @@ -265,7 +265,7 @@ describe('Node FS', () => { const filePath = join(tempDir, 'large.txt') const lineCount = 10000 - const lua = await Lua.load({ fs: 'node' }) + const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() await state.doString(` local f = io.open("${filePath.replace(/\\/g, '/')}", "w") @@ -286,7 +286,7 @@ describe('Node FS', () => { const filePath = join(tempDir, 'overwrite.txt') writeFileSync(filePath, 'original content') - const lua = await Lua.load({ fs: 'node' }) + const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() await state.doString(` local f = io.open("${filePath.replace(/\\/g, '/')}", "w") @@ -301,7 +301,7 @@ describe('Node FS', () => { const content = 'héllo wörld 日本語 🌍' writeFileSync(join(tempDir, 'utf8.txt'), content) - const lua = await Lua.load({ fs: 'node' }) + const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() const result = await state.doString(` local f = io.open("${join(tempDir, 'utf8.txt').replace(/\\/g, '/')}", "r") @@ -316,7 +316,7 @@ describe('Node FS', () => { it('write UTF-8 content should succeed', async () => { const filePath = join(tempDir, 'utf8out.txt') - const lua = await Lua.load({ fs: 'node' }) + const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() await state.doString(` local f = io.open("${filePath.replace(/\\/g, '/')}", "w") @@ -330,7 +330,7 @@ describe('Node FS', () => { it('read empty file should succeed', async () => { writeFileSync(join(tempDir, 'empty.txt'), '') - const lua = await Lua.load({ fs: 'node' }) + const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() const result = await state.doString(` local f = io.open("${join(tempDir, 'empty.txt').replace(/\\/g, '/')}", "r") @@ -343,7 +343,7 @@ describe('Node FS', () => { }) it('open non-existent file for reading should return nil', async () => { - const lua = await Lua.load({ fs: 'node' }) + const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() const result = await state.doString(` local f, err = io.open("${join(tempDir, 'nonexistent.txt').replace(/\\/g, '/')}", "r") @@ -354,7 +354,7 @@ describe('Node FS', () => { }) it('io.tmpfile should succeed', async () => { - const lua = await Lua.load({ fs: 'node' }) + const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() const result = await state.doString(` local f = io.tmpfile() @@ -371,7 +371,7 @@ describe('Node FS', () => { it('multiple states sharing the same NODEFS should succeed', async () => { const filePath = join(tempDir, 'shared.txt') - const lua = await Lua.load({ fs: 'node' }) + const lua = await LuaRuntime.load({ fs: 'node' }) const state1 = lua.createState() const state2 = lua.createState() @@ -394,7 +394,7 @@ describe('Node FS', () => { it('read number from file should succeed', async () => { writeFileSync(join(tempDir, 'numbers.txt'), '42\n3.14\n100') - const lua = await Lua.load({ fs: 'node' }) + const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() const result = await state.doString(` local f = io.open("${join(tempDir, 'numbers.txt').replace(/\\/g, '/')}", "r") diff --git a/test/promises.test.js b/test/promises.test.js index 6227707..0058306 100644 --- a/test/promises.test.js +++ b/test/promises.test.js @@ -6,9 +6,9 @@ describe('Promises', () => { it('use promise next should succeed', async () => { const state = await getState() const check = mock.fn() - state.global.set('check', check) + state.set('check', check) const promise = new Promise((resolve) => setTimeout(() => resolve(60), 5)) - state.global.set('promise', promise) + state.set('promise', promise) const res = state.doString(` promise:next(check) @@ -23,9 +23,9 @@ describe('Promises', () => { it('chain promises with next should succeed', async () => { const state = await getState() const check = mock.fn() - state.global.set('check', check) + state.set('check', check) const promise = new Promise((resolve) => resolve(60)) - state.global.set('promise', promise) + state.set('promise', promise) const res = state.doString(` promise:next(function(value) @@ -43,9 +43,9 @@ describe('Promises', () => { it('call an async function should succeed', async () => { const state = await getState() - state.global.set('asyncFunction', async () => Promise.resolve(60)) + state.set('asyncFunction', async () => Promise.resolve(60)) const check = mock.fn() - state.global.set('check', check) + state.set('check', check) const res = state.doString(` asyncFunction():next(check) @@ -58,7 +58,7 @@ describe('Promises', () => { it('return an async function should succeed', async () => { const state = await getState() - state.global.set('asyncFunction', async () => Promise.resolve(60)) + state.set('asyncFunction', async () => Promise.resolve(60)) const asyncFunction = await state.doString(` return asyncFunction @@ -70,7 +70,7 @@ describe('Promises', () => { it('return a chained promise should succeed', async () => { const state = await getState() - state.global.set('asyncFunction', async () => Promise.resolve(60)) + state.set('asyncFunction', async () => Promise.resolve(60)) const asyncFunction = await state.doString(` return asyncFunction():next(function(x) return x * 2 end) @@ -83,9 +83,9 @@ describe('Promises', () => { it('await an promise inside coroutine should succeed', async () => { const state = await getState() const check = mock.fn() - state.global.set('check', check) + state.set('check', check) const promise = new Promise((resolve) => setTimeout(() => resolve(60), 5)) - state.global.set('promise', promise) + state.set('promise', promise) const res = state.doString(` local co = coroutine.create(function() @@ -110,9 +110,9 @@ describe('Promises', () => { it('awaited coroutines should ignore resume until it resolves the promise', async () => { const state = await getState() const check = mock.fn() - state.global.set('check', check) + state.set('check', check) const promise = new Promise((resolve) => setTimeout(() => resolve(60), 5)) - state.global.set('promise', promise) + state.set('promise', promise) const res = state.doString(` local co = coroutine.create(function() @@ -134,8 +134,8 @@ describe('Promises', () => { it('await a thread run with async calls should succeed', async () => { const state = await getState() - state.global.set('sleep', (input) => new Promise((resolve) => setTimeout(resolve, input))) - const asyncThread = state.global.newThread() + state.set('sleep', (input) => new Promise((resolve) => setTimeout(resolve, input))) + const asyncThread = state.newThread() asyncThread.loadString(` sleep(1):await() @@ -148,8 +148,8 @@ describe('Promises', () => { it('run thread with async calls and yields should succeed', async () => { const state = await getState() - state.global.set('sleep', (input) => new Promise((resolve) => setTimeout(resolve, input))) - const asyncThread = state.global.newThread() + state.set('sleep', (input) => new Promise((resolve) => setTimeout(resolve, input))) + const asyncThread = state.newThread() asyncThread.loadString(` coroutine.yield() @@ -166,8 +166,8 @@ describe('Promises', () => { it('reject a promise should succeed', async () => { const state = await getState() - state.global.set('throw', () => new Promise((_, reject) => reject(new Error('expected test error')))) - const asyncThread = state.global.newThread() + state.set('throw', () => new Promise((_, reject) => reject(new Error('expected test error')))) + const asyncThread = state.newThread() asyncThread.loadString(` throw():await() @@ -179,8 +179,8 @@ describe('Promises', () => { it('pcall a promise await should succeed', async () => { const state = await getState() - state.global.set('throw', () => new Promise((_, reject) => reject(new Error('expected test error')))) - const asyncThread = state.global.newThread() + state.set('throw', () => new Promise((_, reject) => reject(new Error('expected test error')))) + const asyncThread = state.newThread() asyncThread.loadString(` local succeed, err = pcall(function() throw():await() end) @@ -195,8 +195,8 @@ describe('Promises', () => { const state = await getState() const fulfilled = mock.fn() const rejected = mock.fn() - state.global.set('handlers', { fulfilled, rejected }) - state.global.set('throw', new Promise((_, reject) => reject(new Error('expected test error')))) + state.set('handlers', { fulfilled, rejected }) + state.set('throw', new Promise((_, reject) => reject(new Error('expected test error')))) const res = state.doString(` throw:next(handlers.fulfilled, handlers.rejected):catch(function() end) @@ -210,9 +210,9 @@ describe('Promises', () => { it('run with async callback', async () => { const state = await getState() - const thread = state.global.newThread() + const thread = state.newThread() - state.global.set('asyncCallback', async (input) => { + state.set('asyncCallback', async (input) => { return Promise.resolve(input * 2) }) @@ -262,7 +262,7 @@ describe('Promises', () => { it('resolve multiple promises with promise.all', async () => { const state = await getState() - state.global.set('sleep', (input) => new Promise((resolve) => setTimeout(resolve, input))) + state.set('sleep', (input) => new Promise((resolve) => setTimeout(resolve, input))) const resPromise = state.doString(` local promises = {} for i = 1, 10 do @@ -279,7 +279,7 @@ describe('Promises', () => { it('error in promise next catchable', async () => { const state = await getState() - state.global.set('sleep', (input) => new Promise((resolve) => setTimeout(resolve, input))) + state.set('sleep', (input) => new Promise((resolve) => setTimeout(resolve, input))) const resPromise = state.doString(` return sleep(1):next(function () error("sleep done") @@ -290,10 +290,10 @@ describe('Promises', () => { it('should not be possible to await in synchronous run', async () => { const state = await getState() - state.global.set('sleep', (input) => new Promise((resolve) => setTimeout(resolve, input))) + state.set('sleep', (input) => new Promise((resolve) => setTimeout(resolve, input))) expect(() => { state.doStringSync(`sleep(5):await()`) - }).to.throw('cannot await in the main thread') + }).to.throw('cannot await in a thread that cannot yield') }) }) diff --git a/test/engine.test.js b/test/state.test.js similarity index 73% rename from test/engine.test.js rename to test/state.test.js index c5846de..74c1c2d 100644 --- a/test/engine.test.js +++ b/test/state.test.js @@ -1,5 +1,5 @@ import { EventEmitter } from 'events' -import { LuaLibraries, LuaReturn, LuaThread, LuaType, decorate, decorateProxy, decorateUserdata } from '../dist/index.js' +import { LuaReturn, LuaThread, LuaType, decorate } from '../dist/index.js' import { expect } from 'chai' import { getState, getLua } from './utils.js' import { setTimeout } from 'node:timers/promises' @@ -36,20 +36,20 @@ describe('State', () => { it('receive lua table on JS function should succeed', async () => { const state = await getState() - state.global.set('stringify', (table) => { + state.set('stringify', (table) => { return JSON.stringify(table) }) await state.doString('value = stringify({ test = 1 })') - expect(state.global.get('value')).to.be.equal(JSON.stringify({ test: 1 })) + expect(state.get('value')).to.be.equal(JSON.stringify({ test: 1 })) }) it('get a global table inside a JS function called by lua should succeed', async () => { const state = await getState() - state.global.set('t', { test: 1 }) - state.global.set('test', () => { - return state.global.get('t') + state.set('t', { test: 1 }) + state.set('test', () => { + return state.get('t') }) const value = await state.doString('return test(2)') @@ -60,7 +60,7 @@ describe('State', () => { it('receive JS object on lua should succeed', async () => { const state = await getState() - state.global.set('test', () => { + state.set('test', () => { return { aaaa: 1, bbb: 'hey', @@ -80,7 +80,7 @@ describe('State', () => { hello: 'world', } obj.self = obj - state.global.set('obj', obj) + state.set('obj', obj) const value = await state.doString('return obj.self.self.self.hello') @@ -149,7 +149,7 @@ describe('State', () => { hello: 'everybody', } obj2.self = obj2 - state.global.set('obj', { obj1, obj2 }) + state.set('obj', { obj1, obj2 }) await state.doString(` assert(obj.obj1.self.self.hello == "world") @@ -161,7 +161,7 @@ describe('State', () => { const state = await getState() const obj = Object.create(null) obj.hello = 'world' - state.global.set('obj', obj) + state.set('obj', obj) const value = await state.doString(`return obj.hello`) @@ -169,10 +169,10 @@ describe('State', () => { }) it('inherited properties should not be copied into the lua table', async () => { - const state = await getState({ enableProxy: false }) + const state = await getState({ objects: 'copy' }) const obj = Object.create({ inherited: 'yes' }) obj.own = 'mine' - state.global.set('t', obj) + state.set('t', obj) const keys = await state.doString(` local out = {} @@ -185,18 +185,18 @@ describe('State', () => { }) it('non enumerable properties should not be copied into the lua table', async () => { - const state = await getState({ enableProxy: false }) + const state = await getState({ objects: 'copy' }) const obj = { own: 'mine' } Object.defineProperty(obj, 'hidden', { value: 1, enumerable: false }) - state.global.set('t', obj) + state.set('t', obj) expect(await state.doString('return t.hidden == nil')).to.be.true expect(await state.doString('return t.own')).to.be.equal('mine') }) it('nested arrays and objects should be copied into the lua table', async () => { - const state = await getState({ enableProxy: false }) - state.global.set('t', { list: [10, 20, 30], nested: { deep: [{ value: 5 }] } }) + const state = await getState({ objects: 'copy' }) + state.set('t', { list: [10, 20, 30], nested: { deep: [{ value: 5 }] } }) expect(await state.doString('return #t.list')).to.be.equal(3) expect(await state.doString('return t.list[1]')).to.be.equal(10) @@ -213,14 +213,14 @@ describe('State', () => { const state = await getState() await state.doString(`function sum(x, y) return x + y end`) - const sum = state.global.get('sum') + const sum = state.get('sum') expect(sum(10, 50)).to.be.equal(60) }) it('scheduled lua calls should succeed', async () => { const state = await getState() - state.global.set('setInterval', setIntervalSafe) + state.set('setInterval', setIntervalSafe) await state.doString(` test = "" @@ -236,31 +236,28 @@ describe('State', () => { `) const deadline = Date.now() + 1000 - while (!state.global.get('done')) { + while (!state.get('done')) { if (Date.now() > deadline) { throw new Error('timed out waiting for scheduled lua calls') } await setTimeout(5) } - expect(state.global.get('test')).to.be.equal('iiiii') + expect(state.get('test')).to.be.equal('iiiii') }) - it('scheduled lua calls should fail silently if invalid', async () => { + it('calling a lua function after close should throw', async () => { const state = await getState() - state.global.set('setInterval', setIntervalSafe) - const originalConsoleWarn = console.warn - console.warn = mock.fn() - await state.doString(` + const callback = await state.doString(` test = 0 - setInterval(function() + return function() test = test + 1 - end, 5) + end `) - state.global.close() - await setTimeout(5 + 5) - console.warn = originalConsoleWarn + state.close() + + expect(() => callback()).to.throw('cannot call a Lua function after its state has been closed') }) it('call lua function from JS passing an array argument should succeed', async () => { @@ -288,7 +285,7 @@ describe('State', () => { end `) - const returns = state.global.call('f', 10, 25) + const returns = state.call('f', 10, 25) expect(returns).to.have.length(6) expect(returns.slice(0, -1)).to.eql([1, 10, 25, 'Hello World', {}]) expect(returns.at(-1)).to.be.a('function') @@ -310,8 +307,8 @@ describe('State', () => { it('a JS error should pause lua execution', async () => { const state = await getState() const check = mock.fn() - state.global.set('check', check) - state.global.set('throw', () => { + state.set('check', check) + state.set('throw', () => { throw new Error('expected error') }) @@ -327,8 +324,8 @@ describe('State', () => { it('catch a JS error with pcall should succeed', async () => { const state = await getState() const check = mock.fn() - state.global.set('check', check) - state.global.set('throw', () => { + state.set('check', check) + state.set('throw', () => { throw new Error('expected error') }) @@ -345,7 +342,7 @@ describe('State', () => { it('call a JS function in a different thread should succeed', async () => { const state = await getState() const sum = mock.fn((x, y) => x + y) - state.global.set('sum', sum) + state.set('sum', sum) await state.doString(` coroutine.resume(coroutine.create(function() @@ -367,15 +364,15 @@ describe('State', () => { }) `) - state.global.lua.lua_getglobal(state.global.address, 'sum') - const sum = state.global.getValue(-1, LuaType.Function) + state.lua.lua_getglobal(state.address, 'sum') + const sum = state.getValue(-1, LuaType.Function) expect(sum(10, 30)).to.be.equal(40) }) it('lua_resume with yield succeeds', async () => { const state = await getState() - const thread = state.global.newThread() + const thread = state.newThread() thread.loadString(` local yieldRes = coroutine.yield(10) return yieldRes @@ -400,12 +397,12 @@ describe('State', () => { }) it('get memory with allocation tracing should succeeds', async () => { - const state = await getState({ traceAllocations: true }) - expect(state.global.getMemoryUsed()).to.be.greaterThan(0) + const state = await getState({ memory: { trace: true } }) + expect(state.memory.used).to.be.greaterThan(0) }) it('get memory should return correct', async () => { - const state = await getState({ traceAllocations: true }) + const state = await getState({ memory: { trace: true } }) const totalMemory = await state.doString(` collectgarbage() @@ -414,20 +411,20 @@ describe('State', () => { return collectgarbage('count') * 1024 `) - expect(state.global.getMemoryUsed()).to.be.equal(totalMemory) + expect(state.memory.used).to.be.equal(totalMemory) }) - it('get memory without tracing should throw', async () => { - const state = await getState({ traceAllocations: false }) + it('memory is undefined without tracing', async () => { + const state = await getState() - expect(() => state.global.getMemoryUsed()).to.throw() + expect(state.memory).to.be.undefined }) it('limit memory use causes program loading failure succeeds', async () => { - const state = await getState({ traceAllocations: true }) - state.global.setMemoryMax(state.global.getMemoryUsed()) + const state = await getState({ memory: { trace: true } }) + state.memory.max = state.memory.used expect(() => { - state.global.loadString(` + state.loadString(` local a = 10 local b = 20 return a + b @@ -435,8 +432,8 @@ describe('State', () => { }).to.throw('not enough memory') // Remove the limit and retry - state.global.setMemoryMax(undefined) - state.global.loadString(` + state.memory.max = undefined + state.loadString(` local a = 10 local b = 20 return a + b @@ -444,16 +441,16 @@ describe('State', () => { }) it('limit memory use causes program runtime failure succeeds', async () => { - const state = await getState({ traceAllocations: true }) - state.global.loadString(` + const state = await getState({ memory: { trace: true } }) + state.loadString(` local tab = {} for i = 1, 50, 1 do tab[i] = i end `) - state.global.setMemoryMax(state.global.getMemoryUsed()) + state.memory.max = state.memory.used - await expect(state.global.run()).to.eventually.be.rejectedWith('not enough memory') + await expect(state.run()).to.eventually.be.rejectedWith('not enough memory') }) it('table supported circular dependencies', async () => { @@ -464,19 +461,19 @@ describe('State', () => { b.a = a a.b = b - state.global.pushValue(a) - const res = state.global.getValue(-1) + state.pushValue(a) + const res = state.getValue(-1) expect(res.b.a).to.be.eql(res) }) it('wrap a js object (with metatable)', async () => { const state = await getState() - state.global.set('TestClass', { + state.set('TestClass', { create: (name) => { return decorate( { - instance: decorateUserdata(new TestClass(name)), + instance: decorate(new TestClass(name), { as: 'userdata' }), }, { metatable: { @@ -502,7 +499,7 @@ describe('State', () => { it('wrap a js object using proxy', async () => { const state = await getState() - state.global.set('TestClass', { + state.set('TestClass', { create: (name) => new TestClass(name), }) const res = await state.doString(` @@ -514,7 +511,7 @@ describe('State', () => { it('wrap a js object using proxy and apply metatable in lua', async () => { const state = await getState() - state.global.set('TestClass', { + state.set('TestClass', { create: (name) => new TestClass(name), }) const res = await state.doString(` @@ -543,7 +540,7 @@ describe('State', () => { it('classes should be a userdata when proxied', async () => { const state = await getState() - state.global.set('obj', { TestClass }) + state.set('obj', { TestClass }) const testClass = await state.doString(` return obj.TestClass @@ -554,18 +551,18 @@ describe('State', () => { it('timeout blocking lua program', async () => { const state = await getState() - state.global.loadString(` + state.loadString(` local i = 0 while true do i = i + 1 end `) - await expect(state.global.run(0, { timeout: 5 })).eventually.to.be.rejectedWith('thread timeout exceeded') + await expect(state.run(0, { timeout: 5 })).eventually.to.be.rejectedWith('thread timeout exceeded') }) it('the most recently set timeout should be the one that applies', async function () { this.timeout(30_000) const state = await getState() - const thread = state.global.newThread() + const thread = state.newThread() thread.setTimeout(Date.now() + 20) thread.setTimeout(Date.now() + 20_000) @@ -577,7 +574,7 @@ describe('State', () => { it('clearing a timeout should disable the hook', async function () { this.timeout(30_000) const state = await getState() - const thread = state.global.newThread() + const thread = state.newThread() thread.setTimeout(Date.now() + 10) thread.setTimeout(undefined) @@ -591,8 +588,8 @@ describe('State', () => { const state = await getState() let output = '' - state.global.getTable(LuaLibraries.Base, (index) => { - state.global.setField(index, 'print', (val) => { + state.getTable('_G', (index) => { + state.setField(index, 'print', (val) => { // Not a proper print implementation. output += `${val}\n` }) @@ -614,7 +611,7 @@ describe('State', () => { metatable: { __index: (_, k) => `Hello ${k}!` }, }, ) - state.global.set('obj', obj) + state.set('obj', obj) const res = await state.doString('return obj.World') @@ -624,9 +621,9 @@ describe('State', () => { it('a userdata should be collected', async () => { const state = await getState() const obj = {} - state.global.set('obj', obj) - const refIndex = state.global.lua.getLastRefIndex() - const oldRef = state.global.lua.getRef(refIndex) + state.set('obj', obj) + const refIndex = state.lua.getLastRefIndex() + const oldRef = state.lua.getRef(refIndex) await state.doString(` local weaktable = {} @@ -638,7 +635,7 @@ describe('State', () => { `) expect(oldRef).to.be.equal(obj) - const newRef = state.global.lua.getRef(refIndex) + const newRef = state.lua.getRef(refIndex) expect(newRef).to.be.equal(undefined) }) @@ -653,7 +650,7 @@ describe('State', () => { it('static methods should be callable on classes', async () => { const state = await getState() - state.global.set('TestClass', TestClass) + state.set('TestClass', TestClass) const testHello = await state.doString(`return TestClass.hello()`) @@ -664,7 +661,7 @@ describe('State', () => { const state = await getState() const testFunction = () => undefined testFunction.hello = 'world' - state.global.set('TestFunction', decorateProxy(testFunction, { proxy: true })) + state.set('TestFunction', decorate(testFunction, { as: 'proxy' })) const testHello = await state.doString(`return TestFunction.hello`) @@ -685,11 +682,15 @@ describe('State', () => { throw new Error('should not be reached') } catch (err) { expect(err.message).to.includes('[string "..."]:3: function a threw error') - expect(err.message).to.includes('stack traceback:') - expect(err.message).to.includes(`[string "..."]:3: in upvalue 'a'`) - expect(err.message).to.includes(`[string "..."]:5: in upvalue 'b'`) - expect(err.message).to.includes(`[string "..."]:6: in local 'c'`) - expect(err.message).to.includes(`[string "..."]:7: in main chunk`) + expect(err.message).to.not.includes('stack traceback:') + expect(err.luaMessage).to.be.equal(err.message) + expect(err.traceback).to.includes('stack traceback:') + expect(err.traceback).to.includes(`[string "..."]:3: in upvalue 'a'`) + expect(err.traceback).to.includes(`[string "..."]:5: in upvalue 'b'`) + expect(err.traceback).to.includes(`[string "..."]:6: in local 'c'`) + expect(err.traceback).to.includes(`[string "..."]:7: in main chunk`) + // Still reachable through the default logging path. + expect(err.stack).to.includes('stack traceback:') } }) @@ -709,11 +710,11 @@ describe('State', () => { it('should get only the return values on call function', async () => { const state = await getState() - state.global.set('hello', (name) => `Hello ${name}!`) + state.set('hello', (name) => `Hello ${name}!`) const a = await state.doString(`return 1`) const b = state.doStringSync(`return 5`) - const values = state.global.call('hello', 'joao') + const values = state.call('hello', 'joao') expect(a).to.be.equal(1) expect(b).to.be.equal(5) @@ -725,7 +726,7 @@ describe('State', () => { const state = await getState() const str = 'a'.repeat(1000000) - state.global.set('str', str) + state.set('str', str) const res = await state.doString('return str') @@ -746,7 +747,7 @@ describe('State', () => { const state = await getState() const str = 'á'.repeat(500000) - state.global.set('str', str) + state.set('str', str) expect(await state.doString('return #str')).to.be.equal(1000000) expect(await state.doString('return str')).to.be.equal(str) @@ -754,7 +755,7 @@ describe('State', () => { it('a string containing NUL should be pushed with its full length', async () => { const state = await getState() - state.global.set('str', 'a\0b') + state.set('str', 'a\0b') expect(await state.doString('return #str')).to.be.equal(3) }) @@ -770,14 +771,14 @@ describe('State', () => { it('a string containing NUL should round trip unchanged', async () => { const state = await getState() const str = 'before\0middle\0after' - state.global.set('str', str) + state.set('str', str) expect(await state.doString('return str')).to.be.equal(str) }) it('an empty string should round trip unchanged', async () => { const state = await getState() - state.global.set('str', '') + state.set('str', '') expect(await state.doString('return #str')).to.be.equal(0) expect(await state.doString('return str')).to.be.equal('') @@ -787,39 +788,39 @@ describe('State', () => { const state = await getState() await state.doString('value = string.char(0, 255, 128, 65)') - state.global.lua.lua_getglobal(state.global.address, 'value') - const bytes = state.global.getStringBytes(-1) - state.global.pop() + state.lua.lua_getglobal(state.address, 'value') + const bytes = state.getStringBytes(-1) + state.pop() expect(Array.from(bytes)).to.be.eql([0, 255, 128, 65]) }) it('getStringBytes should return undefined for a non string value', async () => { const state = await getState() - state.global.pushValue({}) + state.pushValue({}) - expect(state.global.getStringBytes(-1)).to.be.undefined + expect(state.getStringBytes(-1)).to.be.undefined - state.global.pop() + state.pop() }) it('bytecode should round trip through the byte accessors', async () => { const state = await getState() await state.doString('bytecode = string.dump(load("return 42"))') - state.global.lua.lua_getglobal(state.global.address, 'bytecode') - const bytes = state.global.getStringBytes(-1) - state.global.pop() + state.lua.lua_getglobal(state.address, 'bytecode') + const bytes = state.getStringBytes(-1) + state.pop() - state.global.pushStringBytes(bytes) - state.global.lua.lua_setglobal(state.global.address, 'roundtripped') + state.pushStringBytes(bytes) + state.lua.lua_setglobal(state.address, 'roundtripped') expect(await state.doString('return load(roundtripped)()')).to.be.equal(42) }) it('negative integers should be pushed and retrieved as string', async () => { const state = await getState() - state.global.set('value', -1) + state.set('value', -1) const res = await state.doString(`return tostring(value)`) @@ -828,7 +829,7 @@ describe('State', () => { it('negative integers should be pushed and retrieved as number', async () => { const state = await getState() - state.global.set('value', -1) + state.set('value', -1) const res = await state.doString(`return value`) @@ -838,7 +839,7 @@ describe('State', () => { it('number greater than 32 bit int should be pushed and retrieved as string', async () => { const state = await getState() const value = 1689031554550 - state.global.set('value', value) + state.set('value', value) const res = await state.doString(`return tostring(value)`) @@ -848,7 +849,7 @@ describe('State', () => { it('number greater than 32 bit int should be pushed and retrieved as number', async () => { const state = await getState() const value = 1689031554550 - state.global.set('value', value) + state.set('value', value) const res = await state.doString(`return value`) @@ -858,7 +859,7 @@ describe('State', () => { it('number greater than 32 bit int should be usable as a format argument', async () => { const state = await getState() const value = 1689031554550 - state.global.set('value', value) + state.set('value', value) const res = await state.doString(`return ("%d"):format(value)`) @@ -869,15 +870,15 @@ describe('State', () => { const state = await getState() const value = 9223372036854775807n - state.global.lua.lua_pushinteger(state.global.address, value) - state.global.lua.lua_setglobal(state.global.address, 'value') + state.lua.lua_pushinteger(state.address, value) + state.lua.lua_setglobal(state.address, 'value') const asString = await state.doString(`return tostring(value)`) const asFormatted = await state.doString(`return ("%d"):format(value)`) - state.global.lua.lua_getglobal(state.global.address, 'value') - const roundTrip = state.global.lua.lua_tointegerx(state.global.address, -1, null) - state.global.pop() + state.lua.lua_getglobal(state.address, 'value') + const roundTrip = state.lua.lua_tointegerx(state.address, -1, null) + state.pop() expect(asString).to.be.equal('9223372036854775807') expect(asFormatted).to.be.equal('9223372036854775807') @@ -902,7 +903,7 @@ describe('State', () => { it('an integral number should be pushed as a lua integer', async () => { const state = await getState() - state.global.set('value', 2) + state.set('value', 2) expect(await state.doString('return math.type(value)')).to.be.equal('integer') }) @@ -916,7 +917,7 @@ describe('State', () => { it('a bigint should be pushed as a 64 bit lua integer', async () => { const state = await getState() - state.global.set('value', 9223372036854775807n) + state.set('value', 9223372036854775807n) expect(await state.doString('return tostring(value)')).to.be.equal('9223372036854775807') expect(await state.doString('return math.type(value)')).to.be.equal('integer') @@ -926,12 +927,12 @@ describe('State', () => { it('a bigint outside the lua integer range should throw', async () => { const state = await getState() - expect(() => state.global.set('value', 2n ** 70n)).to.throw(RangeError) + expect(() => state.set('value', 2n ** 70n)).to.throw(RangeError) }) it('an integral number too large for a lua integer should be pushed as a float', async () => { const state = await getState() - state.global.set('value', 1e300) + state.set('value', 1e300) expect(await state.doString('return math.type(value)')).to.be.equal('float') expect(await state.doString('return value')).to.be.equal(1e300) @@ -943,7 +944,7 @@ describe('State', () => { // re-used and doesn't cause JS to abort or some nonsense. const state = await getState() const testEmitter = new EventEmitter() - state.global.set('yield', () => new Promise((resolve) => testEmitter.once('resolve', resolve))) + state.set('yield', () => new Promise((resolve) => testEmitter.once('resolve', resolve))) const resPromise = state.doString(` local res = yield():next(function () coroutine.yield() @@ -959,9 +960,9 @@ describe('State', () => { }) it('forced yield within JS callback from Lua doesnt cause vm to crash', async () => { - const state = await getState({ functionTimeout: 10 }) - state.global.set('promise', Promise.resolve()) - const thread = state.global.newThread() + const state = await getState({ limits: { functionTimeout: 10 } }) + state.set('promise', Promise.resolve()) + const thread = state.newThread() thread.loadString(` promise:next(function () while true do @@ -976,8 +977,8 @@ describe('State', () => { it('function callback timeout still allows timeout of caller thread', async () => { const state = await getState() - state.global.set('promise', Promise.resolve()) - const thread = state.global.newThread() + state.set('promise', Promise.resolve()) + const thread = state.newThread() thread.loadString(` promise:next(function () -- nothing @@ -989,25 +990,25 @@ describe('State', () => { it('null injected and valid', async () => { const state = await getState() - state.global.loadString(` + state.loadString(` local args = { ... } assert(args[1] == null, string.format("expected first argument to be null, got %s", tostring(args[1]))) return null, args[1], tostring(null) `) - state.global.pushValue(null) - const res = await state.global.run(1) + state.pushValue(null) + const res = await state.run(1) expect(res).to.deep.equal([null, null, 'null']) }) it('null injected as nil', async () => { - const state = await getState({ injectObjects: false }) - state.global.loadString(` + const state = await getState({ inject: false }) + state.loadString(` local args = { ... } assert(type(args[1]) == "nil", string.format("expected first argument to be nil, got %s", type(args[1]))) return nil, args[1], tostring(nil) `) - state.global.pushValue(null) - const res = await state.global.run(1) + state.pushValue(null) + const res = await state.run(1) expect(res).to.deep.equal([null, null, 'nil']) }) @@ -1015,22 +1016,22 @@ describe('State', () => { const state = await getState() await state.doString('null = 5') - state.global.set('value', null) + state.set('value', null) expect(await state.doString('return type(value)')).to.be.equal('userdata') - expect(state.global.get('value')).to.be.null + expect(state.get('value')).to.be.null }) it('a pushed null should equal the injected null global', async () => { const state = await getState() - state.global.set('value', null) + state.set('value', null) expect(await state.doString('return value == null')).to.be.true }) it('Nested callback from JS to Lua', async () => { const state = await getState() - state.global.set('call', (fn) => fn()) + state.set('call', (fn) => fn()) const res = await state.doString(` return call(function () return call(function () @@ -1056,22 +1057,22 @@ describe('State', () => { it('lots of doStringSync calls should not grow the lua stack', async function () { this.timeout(30_000) const state = await getState() - const startTop = state.global.getTop() + const startTop = state.getTop() for (let i = 0; i < 500; i++) { expect(state.doStringSync(`return ${i}`)).to.be.equal(i) } - expect(state.global.getTop()).to.be.equal(startTop) + expect(state.getTop()).to.be.equal(startTop) }) it('a failing doStringSync should not grow the lua stack', async () => { const state = await getState() - const startTop = state.global.getTop() + const startTop = state.getTop() expect(() => state.doStringSync('error("boom")')).to.throw('boom') - expect(state.global.getTop()).to.be.equal(startTop) + expect(state.getTop()).to.be.equal(startTop) }) it('values returned by doStringSync should outlive the stack reset', async () => { @@ -1100,3 +1101,130 @@ describe('State', () => { } }) }) + +describe('Load mode', () => { + it('loadString refuses bytecode by default', async () => { + const state = await getState() + // Produced and reloaded inside Lua so the bytes never round trip through a JS string. + expect( + state.doStringSync(` + local d = string.dump(function() return 42 end) + local f, err = load(d, 'c', 't') + return err + `), + ).to.include('attempt to load a binary chunk') + }) + + it('the host loader refuses a binary chunk by default', async () => { + const state = await getState() + + expect(() => state.loadString('\x1bLua\x55\x00')).to.throw('attempt to load a binary chunk') + }) + + it('mode bt opts back in', async () => { + const state = await getState() + + expect( + state.doStringSync(` + local d = string.dump(function() return 42 end) + return load(d, 'c', 'bt')() + `), + ).to.be.equal(42) + }) +}) + +describe('Decoration', () => { + class Thing { + constructor(name) { + this.name = name + } + getName() { + return this.name + } + } + + it('as userdata hides the members', async () => { + const state = await getState() + state.set('thing', decorate(new Thing('bob'), { as: 'userdata' })) + + // An opaque userdata has no __index of its own, so Lua refuses to index it at all. + await expect(state.doString('return thing.name')).to.eventually.be.rejectedWith('attempt to index a js_userdata value') + }) + + it('as userdata still cannot take a metatable of its own', async () => { + const state = await getState() + + // The userdata extension owns the metatable slot. That is a constraint of the extension, + // not of the decoration API, so a custom metatable has to go on a wrapper. + expect(() => state.set('thing', decorate(new Thing('bob'), { as: 'userdata', metatable: { __name: 'js_thing' } }))).to.throw( + 'data already has associated metatable: js_userdata', + ) + }) + + it('a wrapper carries the metatable around an opaque userdata', async () => { + const state = await getState() + state.set( + 'thing', + decorate( + { inner: decorate(new Thing('bob'), { as: 'userdata' }) }, + { metatable: { __name: 'js_thing', __index: (self, key) => (key === 'name' ? self.inner.getName() : null) } }, + ), + ) + + expect(await state.doString('return thing.name')).to.be.equal('bob') + }) + + it('as value copies an object instead of proxying it', async () => { + const state = await getState() + state.set('plain', decorate({ a: 1 }, { as: 'value' })) + + expect(await state.doString('return type(plain)')).to.be.equal('table') + }) + + it('as proxy forces a function through the proxy layer', async () => { + const state = await getState() + const fn = () => undefined + fn.hello = 'world' + state.set('fn', decorate(fn, { as: 'proxy' })) + + expect(await state.doString('return fn.hello')).to.be.equal('world') + }) +}) + +describe('Memory', () => { + it('memory.max rejects without tracing', async () => { + const lua = await getLua() + + expect(() => lua.createState({ memory: { max: 1000 } })).to.throw('requires memory.trace') + }) + + it('memory is a live view', async () => { + using state = await getState({ memory: { trace: true } }) + + const before = state.memory.used + await state.doString('big = {} for i = 1, 5000 do big[i] = i end') + + expect(state.memory.used).to.be.greaterThan(before) + }) +}) + +describe('Synchronous runs', () => { + it('do not leak stack onto the state between calls', async () => { + const state = await getState() + const top = state.getTop() + + for (let i = 0; i < 50; i++) { + state.doStringSync('return 1') + } + + expect(state.getTop()).to.be.equal(top) + }) + + it('a hook installed for a sync run does not outlive it', async () => { + const state = await getState() + + state.doStringSync('return 1', { timeout: 1000 }) + + expect(state.getTimeout()).to.be.undefined + }) +}) diff --git a/test/utils.js b/test/utils.js index 8a0e97d..ee59609 100644 --- a/test/utils.js +++ b/test/utils.js @@ -1,13 +1,13 @@ -import { Lua } from '../dist/index.js' +import { LuaRuntime } from '../dist/index.js' export const getLua = (env) => { - return Lua.load({ env }) + return LuaRuntime.load({ env }) } export const getState = async (config = {}) => { - const lua = await Lua.load() + const lua = await LuaRuntime.load() return lua.createState({ - injectObjects: true, + inject: true, ...config, }) } diff --git a/utils/build-wasm.sh b/utils/build-wasm.sh index 046430c..c234f59 100755 --- a/utils/build-wasm.sh +++ b/utils/build-wasm.sh @@ -29,7 +29,6 @@ emcc \ 'lengthBytesUTF8', \ 'stringToUTF8', \ 'stringToNewUTF8', \ - 'intArrayFromString', \ 'UTF8ToString', \ 'HEAPU8', \ 'HEAPU32' From bba4cf14f27256644325529141115cc962ff0e16 Mon Sep 17 00:00:00 2001 From: Gabriel Francisco Date: Tue, 28 Jul 2026 20:30:16 -0300 Subject: [PATCH 42/83] better types --- .oxlintrc.json | 10 +--- package.json | 4 +- src/declarations.d.ts | 12 ++++- src/decoration.ts | 16 ++++-- src/index.ts | 19 +++++-- src/module.ts | 96 +++++++++++++++++++-------------- src/multireturn.ts | 23 +++++++- src/pointer.ts | 1 - src/runtime.ts | 19 ++----- src/state.ts | 27 +++++----- src/thread.ts | 50 +++++++++-------- src/type-extension.ts | 34 ++++++++---- src/type-extensions/error.ts | 48 +++++++---------- src/type-extensions/function.ts | 80 ++++++++++++--------------- src/type-extensions/null.ts | 62 ++++++++++----------- src/type-extensions/promise.ts | 80 +++++++++++++-------------- src/type-extensions/proxy.ts | 67 +++++++++++------------ src/type-extensions/table.ts | 27 +++++----- src/type-extensions/userdata.ts | 39 ++++++-------- src/types.ts | 59 ++++++++++++-------- src/utils.ts | 11 +++- test/.oxlintrc.json | 5 ++ test/errors.test.js | 2 +- test/state.test.js | 12 ++--- tsconfig.json | 5 +- 25 files changed, 434 insertions(+), 374 deletions(-) delete mode 100644 src/pointer.ts create mode 100644 test/.oxlintrc.json diff --git a/.oxlintrc.json b/.oxlintrc.json index d39faa0..c9c4b84 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -14,13 +14,5 @@ "ignorePatterns": ["dist/**", "build/**", "rolldown.config.ts", "rolldown.config.*.js", "utils/**"], "env": { "builtin": true - }, - "overrides": [ - { - "files": ["**/test/**"], - "rules": { - "no-unused-expressions": "off" - } - } - ] + } } diff --git a/package.json b/package.json index 45023dd..2724d80 100755 --- a/package.json +++ b/package.json @@ -14,8 +14,8 @@ "luatests": "node --experimental-import-meta-resolve test/luatests.js", "build": "rolldown -c && tsc -d --emitDeclarationOnly --rootDir src --declarationDir dist", "clean": "rm -rf dist build", - "lint": "oxfmt --write . && oxlint --config .oxlintrc.json --fix .", - "lint:nofix": "oxfmt --check . && oxlint --config .oxlintrc.json ." + "lint": "oxfmt --write . && oxlint --fix .", + "lint:nofix": "oxfmt --check . && oxlint ." }, "files": [ "bin/*", diff --git a/src/declarations.d.ts b/src/declarations.d.ts index 2f74c40..d1df7e0 100644 --- a/src/declarations.d.ts +++ b/src/declarations.d.ts @@ -3,7 +3,17 @@ declare module '*.wasm' { export default value } -declare module '*.js' +// The emscripten glue is generated JS, so it has no types of its own. Declaring the factory rather +// than the whole module keeps the init options checked against what the build actually accepts +// (see INCOMING_MODULE_JS_API in utils/build-wasm.sh). +declare module '*/glue.js' { + const initWasmModule: ( + moduleArg?: Partial> & { + preRun?: (module: import('./module').LuaEmscriptenModule) => void + }, + ) => Promise + export default initWasmModule +} declare module 'package-version' { const value: string diff --git a/src/decoration.ts b/src/decoration.ts index ff77c32..04d57ac 100755 --- a/src/decoration.ts +++ b/src/decoration.ts @@ -17,19 +17,25 @@ export class Decoration { ) {} } +/** + * A metatable to attach to a pushed value. Decorating it controls how it is pushed; on its own it + * is copied into a plain Lua table. + */ +export type LuaMetatable = object | Decoration + export interface DecorationOptions { /** Metatable to attach to the pushed value, itself decoratable to control how it is pushed. */ - metatable?: Record | Decoration - as?: DecorationTarget + metatable?: LuaMetatable | undefined + as?: DecorationTarget | undefined /** Function only: bound as the receiver, and dropped from the argument list. */ - self?: any + self?: unknown /** Function only: receives the calling thread as the first argument. */ - receiveThread?: boolean + receiveThread?: boolean | undefined /** * Function only: receives the argument count instead of the decoded arguments, and is * expected to read the stack itself. This is a raw-level escape hatch. */ - receiveArgsQuantity?: boolean + receiveArgsQuantity?: boolean | undefined } /** diff --git a/src/index.ts b/src/index.ts index bd40719..81cc3d4 100755 --- a/src/index.ts +++ b/src/index.ts @@ -1,13 +1,23 @@ export { default as LuaRuntime } from './runtime' export { default as LuaState, type LuaMemory } from './state' -export { default as LuaThread } from './thread' +export { default as LuaThread, type OrderedExtension } from './thread' export { default as LuaMultiReturn } from './multireturn' export { default as LuaRawResult } from './raw-result' -export { decorate, Decoration, type DecorationOptions, type DecorationTarget } from './decoration' +export { decorate, Decoration, type DecorationOptions, type DecorationTarget, type LuaMetatable } from './decoration' // Export the underlying bindings to allow users to just // use the bindings rather than the wrappers. -export { default as LuaModule } from './module' +export { + default as LuaModule, + type EmscriptenPath, + type EnvironmentVariables, + type LuaEmscriptenModule, + type LuaModuleOptions, +} from './module' export { default as LuaTypeExtension } from './type-extension' +// The built in extensions are not exported, but the value types they marshal are, so a custom +// extension can describe what it handles. +export type { FunctionType } from './type-extensions/function' +export type { TableType } from './type-extensions/table' // Named rather than `export *`, so the library bitmask helpers and the warn default stay internal. export { LuaError, @@ -23,6 +33,7 @@ export { LUA_REGISTRYINDEX, LUAI_MAXSTACK, LUA_LIB_BITS, + PointerSize, type LuaAddress, type LuaLibName, type LuaLoadMode, @@ -35,6 +46,8 @@ export { type LuaDoOptions, type LuaThreadLimits, type LuaResumeResult, + type LuaGetCache, + type LuaPushCache, } from './types' import LuaRuntime from './runtime' diff --git a/src/module.ts b/src/module.ts index 4f46613..5e096de 100755 --- a/src/module.ts +++ b/src/module.ts @@ -1,26 +1,34 @@ import initWasmModule from '../build/glue.js' -import { defaultWarnHandler, LUA_REGISTRYINDEX, LuaAddress, LuaReturn, LuaType, LuaWarnHandler, PointerSize } from './types.js' +import { defaultWarnHandler, LUA_REGISTRYINDEX, type LuaAddress, LuaReturn, LuaType, type LuaWarnHandler, PointerSize } from './types' // A rolldown plugin will resolve this to the current version on package.json import version from 'package-version' -type EnvironmentVariables = Record +export type EnvironmentVariables = Record -interface LuaEmscriptenModule extends EmscriptenModule { +/** Emscripten's own path helpers, which work on the virtual filesystem rather than the host one. */ +export interface EmscriptenPath { + isAbs: (path: string) => boolean + normalize: (path: string) => string + dirname: (path: string) => string + basename: (path: string) => string + join: (...paths: string[]) => string + join2: (left: string, right: string) => string +} + +export interface LuaEmscriptenModule extends EmscriptenModule { ccall: typeof ccall addFunction: typeof addFunction removeFunction: typeof removeFunction setValue: typeof setValue getValue: typeof getValue + // `filesystems` is the only member missing upstream; mkdirTree and the rest come from typeof FS. FS: typeof FS & { filesystems: { NODEFS: Emscripten.FileSystemType MEMFS: Emscripten.FileSystemType } - mkdirTree: (path: string) => void - } - PATH: { - dirname: (typeof import('node:path'))['dirname'] } + PATH: EmscriptenPath stringToNewUTF8: typeof stringToNewUTF8 lengthBytesUTF8: typeof lengthBytesUTF8 stringToUTF8: typeof stringToUTF8 @@ -29,6 +37,27 @@ interface LuaEmscriptenModule extends EmscriptenModule { _realloc: (pointer: number, size: number) => number } +export interface LuaModuleOptions { + /** Custom URI for the Lua WebAssembly module. Defaults to unpkg in the browser. */ + wasmFile?: string | undefined + /** Environment variables for the Lua states. */ + env?: EnvironmentVariables | undefined + /** File system that should be used. */ + fs?: 'node' | 'memory' | undefined + /** Host directories to mount when `fs` is `'node'`. Defaults to the drive holding the CWD. */ + fsMountPaths?: string[] | undefined + /** Called once per read. An empty string (or nothing) means EOF. */ + stdin?: (() => string | null | undefined) | undefined + /** + * Called with each completed line, without the line break, and with a partial line when Lua + * flushes or suspends in the middle of one. + */ + stdout?: ((content: string) => void) | undefined + stderr?: ((content: string) => void) | undefined + /** Where load time diagnostics go. Defaults to `console.warn`. */ + onWarn?: LuaWarnHandler | undefined +} + // One-shot conversions, so a single stateless pair is shared by every module. Streaming output // keeps its own decoder in createOutputWriter. const textDecoder = new TextDecoder() @@ -46,35 +75,23 @@ interface ReferenceMetadata { } export default class LuaModule { - public static async initialize(opts: { - wasmFile?: string - env?: EnvironmentVariables - fs?: 'node' | 'memory' - fsMountPaths?: string[] - // Called once per read, and an empty string (or nothing) means EOF. - stdin?: () => string | null | undefined - // Called with each completed line, without the line break, and with a partial line when - // Lua flushes or suspends in the middle of one. - stdout?: (content: string) => void - stderr?: (content: string) => void - /** Where load time diagnostics go. Defaults to `console.warn`. */ - onWarn?: LuaWarnHandler - }): Promise { + public static async initialize(opts: Readonly = {}): Promise { const warn = opts.onWarn ?? defaultWarnHandler const isBrowser = (typeof window === 'object' && typeof window.document !== 'undefined') || (typeof self === 'object' && self?.constructor?.name === 'DedicatedWorkerGlobalScope') - if (opts.wasmFile === undefined && isBrowser) { - opts.wasmFile = `https://unpkg.com/wasmoon@${version}/dist/glue.wasm` - } - const useNodeFS = !isBrowser && opts.fs === 'node' && typeof process !== 'undefined' const fs = useNodeFS ? await import('node:fs') : null - const module: LuaEmscriptenModule = await initWasmModule({ + const module = await initWasmModule({ locateFile: (path: string, scriptDirectory: string) => { - return opts.wasmFile || scriptDirectory + path + // The wasm sits next to the bundle when it was built alongside it, which is not the + // case for a browser loading the published package. + if (opts.wasmFile) { + return opts.wasmFile + } + return isBrowser ? `https://unpkg.com/wasmoon@${version}/dist/glue.wasm` : scriptDirectory + path }, preRun: (initializedModule: LuaEmscriptenModule) => { if (typeof opts?.env === 'object') { @@ -160,15 +177,16 @@ export default class LuaModule { public luaL_optlstring: (L: LuaAddress, arg: number, def: string | null, l: number | null) => string public luaL_checknumber: (L: LuaAddress, arg: number) => number public luaL_optnumber: (L: LuaAddress, arg: number, def: number) => number - public luaL_checkinteger: (L: LuaAddress, arg: number) => number - public luaL_optinteger: (L: LuaAddress, arg: number, def: number) => number + // lua_Integer is 64 bit, and the module is built with WASM_BIGINT, so these cross as BigInt. + public luaL_checkinteger: (L: LuaAddress, arg: number) => bigint + public luaL_optinteger: (L: LuaAddress, arg: number, def: bigint) => bigint public luaL_checkstack: (L: LuaAddress, sz: number, msg: string | null) => void public luaL_checktype: (L: LuaAddress, arg: number, t: number) => void public luaL_checkany: (L: LuaAddress, arg: number) => void public luaL_newmetatable: (L: LuaAddress, tname: string | null) => number public luaL_setmetatable: (L: LuaAddress, tname: string | null) => void - public luaL_testudata: (L: LuaAddress, ud: number, tname: string | null) => number - public luaL_checkudata: (L: LuaAddress, ud: number, tname: string | null) => number + public luaL_testudata: (L: LuaAddress, ud: number, tname: string | null) => LuaAddress + public luaL_checkudata: (L: LuaAddress, ud: number, tname: string | null) => LuaAddress public luaL_where: (L: LuaAddress, lvl: number) => void public luaL_fileresult: (L: LuaAddress, stat: number, fname: string | null) => number public luaL_execresult: (L: LuaAddress, stat: number) => number @@ -184,7 +202,7 @@ export default class LuaModule { ) => LuaReturn public luaL_loadstring: (L: LuaAddress, s: string | null) => LuaReturn public luaL_newstate: () => LuaAddress - public luaL_len: (L: LuaAddress, idx: number) => number + public luaL_len: (L: LuaAddress, idx: number) => bigint public luaL_addgsub: (b: number | null, s: string | null, p: string | null, r: string | null) => void public luaL_gsub: (L: LuaAddress, s: string | null, p: string | null, r: string | null) => string public luaL_setfuncs: (L: LuaAddress, l: number | null, nup: number) => void @@ -227,9 +245,9 @@ export default class LuaModule { public lua_toboolean: (L: LuaAddress, idx: number) => number public lua_rawlen: (L: LuaAddress, idx: number) => bigint public lua_tocfunction: (L: LuaAddress, idx: number) => number - public lua_touserdata: (L: LuaAddress, idx: number) => number + public lua_touserdata: (L: LuaAddress, idx: number) => LuaAddress public lua_tothread: (L: LuaAddress, idx: number) => LuaAddress - public lua_topointer: (L: LuaAddress, idx: number) => number + public lua_topointer: (L: LuaAddress, idx: number) => LuaAddress public lua_arith: (L: LuaAddress, op: number) => void public lua_rawequal: (L: LuaAddress, idx1: number, idx2: number) => number public lua_compare: (L: LuaAddress, idx1: number, idx2: number, op: number) => number @@ -245,11 +263,11 @@ export default class LuaModule { public lua_gettable: (L: LuaAddress, idx: number) => LuaType public lua_getfield: (L: LuaAddress, idx: number, k: string | null) => LuaType public lua_geti: (L: LuaAddress, idx: number, n: bigint) => LuaType - public lua_rawget: (L: LuaAddress, idx: number) => number + public lua_rawget: (L: LuaAddress, idx: number) => LuaType public lua_rawgeti: (L: LuaAddress, idx: number, n: bigint) => LuaType public lua_rawgetp: (L: LuaAddress, idx: number, p: number | null) => LuaType public lua_createtable: (L: LuaAddress, narr: number, nrec: number) => void - public lua_newuserdatauv: (L: LuaAddress, sz: number, nuvalue: number) => number + public lua_newuserdatauv: (L: LuaAddress, sz: number, nuvalue: number) => LuaAddress public lua_getmetatable: (L: LuaAddress, objindex: number) => number public lua_getiuservalue: (L: LuaAddress, idx: number, n: number) => LuaType public lua_setglobal: (L: LuaAddress, name: string | null) => void @@ -262,7 +280,7 @@ export default class LuaModule { public lua_setmetatable: (L: LuaAddress, objindex: number) => number public lua_setiuservalue: (L: LuaAddress, idx: number, n: number) => number public lua_callk: (L: LuaAddress, nargs: number, nresults: number, ctx: number, k: number | null) => void - public lua_pcallk: (L: LuaAddress, nargs: number, nresults: number, errfunc: number, ctx: number, k: number | null) => number + public lua_pcallk: (L: LuaAddress, nargs: number, nresults: number, errfunc: number, ctx: number, k: number | null) => LuaReturn public lua_load: (L: LuaAddress, reader: number | null, dt: number | null, chunkname: string | null, mode: string | null) => LuaReturn public lua_dump: (L: LuaAddress, writer: number | null, data: number | null, strip: number) => number public lua_yieldk: (L: LuaAddress, nresults: number, ctx: number, k: number | null) => number @@ -286,7 +304,7 @@ export default class LuaModule { public lua_setlocal: (L: LuaAddress, ar: number | null, n: number) => string public lua_getupvalue: (L: LuaAddress, funcindex: number, n: number) => string public lua_setupvalue: (L: LuaAddress, funcindex: number, n: number) => string - public lua_upvalueid: (L: LuaAddress, fidx: number, n: number) => number + public lua_upvalueid: (L: LuaAddress, fidx: number, n: number) => LuaAddress public lua_upvaluejoin: (L: LuaAddress, fidx1: number, n1: number, fidx2: number, n2: number) => void public lua_sethook: (L: LuaAddress, func: number | null, mask: number, count: number) => void public lua_gethook: (L: LuaAddress) => number @@ -611,7 +629,7 @@ export default class LuaModule { } } - public getRef(index: number): any | undefined { + public getRef(index: number): unknown { return this.referenceMap.get(index) } diff --git a/src/multireturn.ts b/src/multireturn.ts index 5d0c7a6..a3085bc 100644 --- a/src/multireturn.ts +++ b/src/multireturn.ts @@ -1 +1,22 @@ -export default class MultiReturn extends Array {} +/** + * Several values returned from one JS function, pushed as several Lua values rather than as a + * single table. + * + * ```js + * state.set('divide', (a, b) => MultiReturn.of(Math.floor(a / b), a % b)) + * ``` + */ +export default class MultiReturn extends Array { + /** + * Nominal marker. Whether a returned array becomes several Lua values or one Lua table is + * decided by `instanceof`, so the type has to be distinguishable from a plain array too. It is + * declared rather than assigned, so nothing is added to the instance at runtime. + */ + declare protected readonly multiReturn: undefined + + /** + * Only the type differs from the inherited `Array.of`, which already constructs through `this` + * and so already returns a MultiReturn. + */ + declare public static of: (...items: T[]) => MultiReturn +} diff --git a/src/pointer.ts b/src/pointer.ts deleted file mode 100644 index 8e0688c..0000000 --- a/src/pointer.ts +++ /dev/null @@ -1 +0,0 @@ -export class Pointer extends Number {} diff --git a/src/runtime.ts b/src/runtime.ts index c012de8..30ca443 100755 --- a/src/runtime.ts +++ b/src/runtime.ts @@ -1,6 +1,6 @@ -import LuaModule from './module' +import LuaModule, { type EmscriptenPath, type LuaModuleOptions } from './module' import LuaState from './state' -import { CreateStateOptions } from './types' +import type { CreateStateOptions } from './types' /** * One loaded Lua wasm module, and the factory for the states that run on it. @@ -9,17 +9,8 @@ import { CreateStateOptions } from './types' * otherwise independent. */ export default class LuaRuntime { - /** - * Loads the Lua wasm module. - * @param opts.wasmFile - Custom URI for the Lua WebAssembly module. - * @param opts.env - Environment variables for the Lua states. - * @param opts.stdin - Standard input, shared by every state on this runtime. - * @param opts.fs - File system that should be used. - * @param opts.stdout - Standard output, shared by every state on this runtime. - * @param opts.stderr - Standard error, shared by every state on this runtime. - * @param opts.onWarn - Where load time diagnostics go. Defaults to `console.warn`. - */ - public static async load(luaModuleOpts: Parameters[0] = {}): Promise { + /** Loads the Lua wasm module. Stdio and the filesystem are shared by every state on it. */ + public static async load(luaModuleOpts: Readonly = {}): Promise { return new LuaRuntime(await LuaModule.initialize(luaModuleOpts)) } @@ -64,7 +55,7 @@ export default class LuaRuntime { return this.module._emscripten.FS } - public get path(): typeof this.module._emscripten.PATH { + public get path(): EmscriptenPath { return this.module._emscripten.PATH } } diff --git a/src/state.ts b/src/state.ts index 0bcca4a..c7abc93 100755 --- a/src/state.ts +++ b/src/state.ts @@ -1,6 +1,6 @@ import type LuaModule from './module' import Thread from './thread' -import LuaTypeExtension from './type-extension' +import type LuaTypeExtension from './type-extension' import createErrorType from './type-extensions/error' import createFunctionType from './type-extensions/function' import createNullType from './type-extensions/null' @@ -9,12 +9,12 @@ import createProxyType from './type-extensions/proxy' import createTableType from './type-extensions/table' import createUserdataType from './type-extensions/userdata' import { - CreateStateOptions, + type CreateStateOptions, LUA_REGISTRYINDEX, - LuaAddress, - LuaDoOptions, - LuaMemoryOptions, - LuaRunOptions, + type LuaAddress, + type LuaDoOptions, + type LuaMemoryOptions, + type LuaRunOptions, LuaType, resolveLibraryMask, } from './types' @@ -118,7 +118,7 @@ export default class LuaState extends Thread { // Generic handlers - These may be required to be registered for additional types. this.registerTypeExtension(0, createTableType(this)) - this.registerTypeExtension(0, createFunctionType(this, { functionTimeout: limits?.functionTimeout })) + this.registerTypeExtension(0, createFunctionType(this, limits?.functionTimeout)) // Contains the :await functionality. this.registerTypeExtension(1, createPromiseType(this, inject)) @@ -153,9 +153,10 @@ export default class LuaState extends Thread { /** * Executes Lua code from a string asynchronously. - * @returns A Promise that resolves to the result returned by the Lua script execution. + * @returns A Promise that resolves to the result returned by the Lua script execution. Nothing + * checks it against `T`, which only saves the caller a cast. */ - public doString(script: string, options?: LuaDoOptions): Promise { + public doString(script: string, options?: LuaDoOptions): Promise { return this.callByteCode((thread) => thread.loadString(script, options), this.runOptions(options)) } @@ -163,7 +164,7 @@ export default class LuaState extends Thread { * Executes Lua code from a file asynchronously. * @returns A Promise that resolves to the result returned by the Lua script execution. */ - public doFile(filename: string, options?: LuaDoOptions): Promise { + public doFile(filename: string, options?: LuaDoOptions): Promise { return this.callByteCode((thread) => thread.loadFile(filename, options), this.runOptions(options)) } @@ -171,7 +172,7 @@ export default class LuaState extends Thread { * Executes Lua code from a string synchronously. The script cannot yield, so `:await()` and a * top level `coroutine.yield` are errors here. */ - public doStringSync(script: string, options?: LuaDoOptions): any { + public doStringSync(script: string, options?: LuaDoOptions): T { return this.callByteCodeSync((thread) => thread.loadString(script, options), this.runOptions(options)) } @@ -179,7 +180,7 @@ export default class LuaState extends Thread { * Executes Lua code from a file synchronously. The script cannot yield, so `:await()` and a * top level `coroutine.yield` are errors here. */ - public doFileSync(filename: string, options?: LuaDoOptions): any { + public doFileSync(filename: string, options?: LuaDoOptions): T { return this.callByteCodeSync((thread) => thread.loadFile(filename, options), this.runOptions(options)) } @@ -194,7 +195,7 @@ export default class LuaState extends Thread { } /** Retrieves the value of a global variable. */ - public get(name: string): any { + public get(name: string): T { const type = this.lua.lua_getglobal(this.address, name) const value = this.getValue(-1, type) this.pop() diff --git a/src/thread.ts b/src/thread.ts index be92daf..b49c346 100755 --- a/src/thread.ts +++ b/src/thread.ts @@ -1,25 +1,26 @@ -import { Decoration } from './decoration' +import { Decoration, type LuaMetatable } from './decoration' import type LuaModule from './module' import MultiReturn from './multireturn' -import { Pointer } from './pointer' -import LuaTypeExtension from './type-extension' +import type LuaTypeExtension from './type-extension' import { defaultWarnHandler, LUA_MULTRET, LuaAbortError, - LuaAddress, + type LuaAddress, LuaError, LuaEventMasks, + type LuaGetCache, LuaInstructionLimitError, LuaInterruptError, - LuaLoadOptions, - LuaResumeResult, + type LuaLoadOptions, + type LuaPushCache, + type LuaResumeResult, LuaReturn, - LuaRunOptions, - LuaThreadLimits, + type LuaRunOptions, + type LuaThreadLimits, LuaTimeoutError, LuaType, - LuaWarnHandler, + type LuaWarnHandler, PointerSize, } from './types' import { isEmscriptenUnwind, isPromise, yieldToEventLoop } from './utils' @@ -43,7 +44,7 @@ export default class Thread { /** Set on the root state; threads created from it delegate here. */ public onWarn: LuaWarnHandler | undefined protected readonly typeExtensions: OrderedExtension[] - protected readonly parent?: Thread + protected readonly parent: Thread | undefined private closed = false private hookFunctionPointer: number | undefined private hookCount = INSTRUCTION_HOOK_COUNT @@ -172,7 +173,7 @@ export default class Thread { const restore = this.applyRunOptions(options) try { const base = this.getTop() - argCount - 1 // The 1 is for the function to run - this.assertOk(this.lua.lua_pcallk(this.address, argCount, LUA_MULTRET, 0, 0, null) as LuaReturn) + this.assertOk(this.lua.lua_pcallk(this.address, argCount, LUA_MULTRET, 0, 0, null)) return this.getStackValues(base) } finally { restore() @@ -213,7 +214,7 @@ export default class Thread { return L === this.parent?.address ? this.parent : new Thread(this.lua, this.typeExtensions, L, this.parent || this) } - public pushValue(rawValue: unknown, userdata?: unknown): void { + public pushValue(rawValue: unknown, cache?: LuaPushCache): void { const decoratedValue = this.getValueDecorations(rawValue) const target = decoratedValue.target @@ -254,7 +255,7 @@ export default class Thread { this.lua.lua_pushboolean(this.address, target ? 1 : 0) break default: - if (this.typeExtensions.find((wrapper) => wrapper.extension.pushValue(this, decoratedValue, userdata))) { + if (this.typeExtensions.find((wrapper) => wrapper.extension.pushValue(this, decoratedValue, cache))) { break } if (target === null) { @@ -273,7 +274,7 @@ export default class Thread { } } - public setMetatable(index: number, metatable: Record): void { + public setMetatable(index: number, metatable: LuaMetatable): void { index = this.lua.lua_absindex(this.address, index) if (this.lua.lua_getmetatable(this.address, index)) { @@ -305,7 +306,7 @@ export default class Thread { return name } - public getValue(index: number, inputType?: LuaType, userdata?: unknown): any { + public getValue(index: number, inputType?: LuaType, cache?: LuaGetCache): any { index = this.lua.lua_absindex(this.address, index) const type: LuaType = inputType ?? this.lua.lua_type(this.address, index) @@ -340,7 +341,7 @@ export default class Thread { wrapper.extension.isType(this, index, type, metatableName), ) if (typeExtensionWrapper) { - return typeExtensionWrapper.extension.getValue(this, index, userdata) + return typeExtensionWrapper.extension.getValue(this, index, cache) } // Handing back an opaque Pointer hid the failure until the value was used, and @@ -386,13 +387,17 @@ export default class Thread { return { ...this.limits } } - /** Set to > 0 to enable, otherwise disable. Shorthand for the deadline in {@link setLimits}. */ - public setTimeout(timeout: number | undefined): void { - this.limits.deadline = timeout && timeout > 0 ? timeout : undefined + /** + * Shorthand for the deadline in {@link setLimits}. The argument is an absolute timestamp as + * returned by `Date.now()`, not a duration — pass `Date.now() + ms`, or undefined to disable. + * `LuaRunOptions.timeout` is the per-run equivalent that does take a duration. + */ + public setDeadline(deadline: number | undefined): void { + this.limits.deadline = deadline && deadline > 0 ? deadline : undefined this.applyHook() } - public getTimeout(): number | undefined { + public getDeadline(): number | undefined { return this.limits.deadline } @@ -402,8 +407,9 @@ export default class Thread { ;(root.onWarn ?? defaultWarnHandler)(message, cause) } - public getPointer(index: number): Pointer { - return new Pointer(this.lua.lua_topointer(this.address, index)) + /** For identity checks on values JS cannot represent. */ + public getPointer(index: number): LuaAddress { + return this.lua.lua_topointer(this.address, index) } public isClosed(): boolean { diff --git a/src/type-extension.ts b/src/type-extension.ts index 3bac4ae..95c1940 100644 --- a/src/type-extension.ts +++ b/src/type-extension.ts @@ -1,15 +1,16 @@ -import { Decoration } from './decoration' +import type { Decoration } from './decoration' import type LuaState from './state' -import Thread from './thread' -import { LuaType, PointerSize } from './types' +import type Thread from './thread' +import { type LuaAddress, type LuaGetCache, type LuaPushCache, LuaReturn, LuaType, PointerSize } from './types' export default abstract class LuaTypeExtension { // Type name, for metatables and lookups. public readonly name: string - protected thread: LuaState + /** Owns this extension's metatable and function pointers, so its lifetime bounds theirs. */ + protected state: LuaState - public constructor(thread: LuaState, name: string) { - this.thread = thread + public constructor(state: LuaState, name: string) { + this.state = state this.name = name } @@ -19,19 +20,34 @@ export default abstract class LuaTypeExtension { public abstract close(): void + /** + * The `__gc` handler every reference holding extension needs. The caller owns the returned + * pointer and has to release it with `removeFunction` in {@link close}. + */ + protected createGcFunction(): number { + return this.state.lua._emscripten.addFunction((calledL: LuaAddress) => { + // Throws a lua error which does a jump if it does not match. + const userDataPointer = this.state.lua.luaL_checkudata(calledL, 1, this.name) + const referencePointer = this.state.lua._emscripten.getValue(userDataPointer, '*') + this.state.lua.unref(referencePointer) + + return LuaReturn.Ok + }, 'ii') + } + // A base implementation that assumes user data serialisation - public getValue(thread: Thread, index: number, _userdata?: unknown): T { + public getValue(thread: Thread, index: number, _cache?: LuaGetCache): T { const refUserdata = thread.lua.luaL_testudata(thread.address, index, this.name) if (!refUserdata) { throw new Error(`data does not have the expected metatable: ${this.name}`) } const referencePointer = thread.lua._emscripten.getValue(refUserdata, '*') - return thread.lua.getRef(referencePointer) + return thread.lua.getRef(referencePointer) as T } // Return false if type not matched, otherwise true. This base method does not // check the type. That must be done by the class extending this. - public pushValue(thread: Thread, decoratedValue: Decoration, _userdata?: unknown): boolean { + public pushValue(thread: Thread, decoratedValue: Decoration, _cache?: LuaPushCache): boolean { const { target } = decoratedValue const pointer = thread.lua.ref(target) diff --git a/src/type-extensions/error.ts b/src/type-extensions/error.ts index a86f4dc..d376312 100644 --- a/src/type-extensions/error.ts +++ b/src/type-extensions/error.ts @@ -1,58 +1,50 @@ import { Decoration } from '../decoration' import type LuaState from '../state' -import Thread from '../thread' +import type Thread from '../thread' import TypeExtension from '../type-extension' -import { LuaReturn, LuaAddress } from '../types' class ErrorTypeExtension extends TypeExtension { private gcPointer: number - public constructor(thread: LuaState, injectObject: boolean) { - super(thread, 'js_error') + public constructor(state: LuaState, injectObject: boolean) { + super(state, 'js_error') - this.gcPointer = thread.lua._emscripten.addFunction((functionStateAddress: LuaAddress) => { - // Throws a lua error which does a jump if it does not match. - const userDataPointer = thread.lua.luaL_checkudata(functionStateAddress, 1, this.name) - const referencePointer = thread.lua._emscripten.getValue(userDataPointer, '*') - thread.lua.unref(referencePointer) + this.gcPointer = this.createGcFunction() - return LuaReturn.Ok - }, 'ii') - - if (thread.lua.luaL_newmetatable(thread.address, this.name)) { - const metatableIndex = thread.lua.lua_gettop(thread.address) + if (state.lua.luaL_newmetatable(state.address, this.name)) { + const metatableIndex = state.lua.lua_gettop(state.address) // Mark it as uneditable - thread.lua.lua_pushstring(thread.address, 'protected metatable') - thread.lua.lua_setfield(thread.address, metatableIndex, '__metatable') + state.lua.lua_pushstring(state.address, 'protected metatable') + state.lua.lua_setfield(state.address, metatableIndex, '__metatable') // Add the gc function - thread.lua.lua_pushcclosure(thread.address, this.gcPointer, 0) - thread.lua.lua_setfield(thread.address, metatableIndex, '__gc') + state.lua.lua_pushcclosure(state.address, this.gcPointer, 0) + state.lua.lua_setfield(state.address, metatableIndex, '__gc') // Add an __index method that returns the message field - thread.pushValue((jsRefError: Error, key: unknown) => { + state.pushValue((jsRefError: Error, key: unknown) => { if (key === 'message') { return jsRefError.message } return null }) - thread.lua.lua_setfield(thread.address, metatableIndex, '__index') + state.lua.lua_setfield(state.address, metatableIndex, '__index') // Add a tostring method that returns the message. - thread.pushValue((jsRefError: Error) => { + state.pushValue((jsRefError: Error) => { // The message rather than toString to avoid the Error: prefix being // added. This fits better with Lua errors. return jsRefError.message }) - thread.lua.lua_setfield(thread.address, metatableIndex, '__tostring') + state.lua.lua_setfield(state.address, metatableIndex, '__tostring') } // Pop the metatable from the stack. - thread.lua.lua_pop(thread.address, 1) + state.lua.lua_pop(state.address, 1) if (injectObject) { // Lastly create a static Error constructor. - thread.set('Error', { + state.set('Error', { create: (message: string | undefined) => { if (message && typeof message !== 'string') { throw new Error('message must be a string') @@ -64,7 +56,7 @@ class ErrorTypeExtension extends TypeExtension { } } - public pushValue(thread: Thread, decoration: Decoration): boolean { + public pushValue(thread: Thread, decoration: Decoration): boolean { if (!(decoration.target instanceof Error)) { return false } @@ -72,10 +64,10 @@ class ErrorTypeExtension extends TypeExtension { } public close(): void { - this.thread.lua._emscripten.removeFunction(this.gcPointer) + this.state.lua._emscripten.removeFunction(this.gcPointer) } } -export default function createTypeExtension(thread: LuaState, injectObject: boolean): TypeExtension { - return new ErrorTypeExtension(thread, injectObject) +export default function createTypeExtension(state: LuaState, injectObject: boolean): TypeExtension { + return new ErrorTypeExtension(state, injectObject) } diff --git a/src/type-extensions/function.ts b/src/type-extensions/function.ts index ee2d9c5..1ed4a57 100644 --- a/src/type-extensions/function.ts +++ b/src/type-extensions/function.ts @@ -2,21 +2,17 @@ import { Decoration } from '../decoration' import type LuaState from '../state' import MultiReturn from '../multireturn' import RawResult from '../raw-result' -import Thread from '../thread' +import type Thread from '../thread' import TypeExtension from '../type-extension' -import { LUA_REGISTRYINDEX, LuaReturn, LuaAddress, LuaType, PointerSize } from '../types' +import { LUA_REGISTRYINDEX, LuaReturn, type LuaAddress, LuaType, PointerSize } from '../types' import { isEmscriptenUnwind } from '../utils' export type FunctionType = (...args: any[]) => Promise | any -export interface FunctionTypeExtensionOptions { - functionTimeout?: number -} - class FunctionTypeExtension extends TypeExtension { private readonly functionRegistry = new FinalizationRegistry((func: number) => { - if (!this.thread.isClosed()) { - this.thread.lua.luaL_unref(this.thread.address, LUA_REGISTRYINDEX, func) + if (!this.state.isClosed()) { + this.state.lua.luaL_unref(this.state.address, LUA_REGISTRYINDEX, func) } }) @@ -24,51 +20,45 @@ class FunctionTypeExtension extends TypeExtension { private functionWrapper: number private callbackContext: Thread private callbackContextIndex: number - private options?: FunctionTypeExtensionOptions + /** Milliseconds a Lua function called from JS may run before being interrupted. */ + private readonly functionTimeout: number | undefined - public constructor(thread: LuaState, options?: FunctionTypeExtensionOptions) { - super(thread, 'js_function') + public constructor(state: LuaState, functionTimeout?: number) { + super(state, 'js_function') - this.options = options + this.functionTimeout = functionTimeout // Create a thread off of the global thread to be used to create function call threads without // interfering with the global context. This creates a callback context that will always exist // even if the thread that called getValue() has been destroyed. - this.callbackContext = thread.newThread() + this.callbackContext = state.newThread() // Pops it from the global stack but keeps it alive - this.callbackContextIndex = this.thread.lua.luaL_ref(thread.address, LUA_REGISTRYINDEX) + this.callbackContextIndex = this.state.lua.luaL_ref(state.address, LUA_REGISTRYINDEX) if (!this.functionRegistry) { - thread.warn('FunctionTypeExtension: FinalizationRegistry not found. Memory leaks likely.') + state.warn('FunctionTypeExtension: FinalizationRegistry not found. Memory leaks likely.') } - this.gcPointer = thread.lua._emscripten.addFunction((calledL: LuaAddress) => { - // Throws a lua error which does a jump if it does not match. - const userDataPointer = thread.lua.luaL_checkudata(calledL, 1, this.name) - const referencePointer = thread.lua._emscripten.getValue(userDataPointer, '*') - thread.lua.unref(referencePointer) - - return LuaReturn.Ok - }, 'ii') + this.gcPointer = this.createGcFunction() // Creates metatable if it doesn't exist, always pushes it onto the stack. - if (thread.lua.luaL_newmetatable(thread.address, this.name)) { - thread.lua.lua_pushstring(thread.address, '__gc') - thread.lua.lua_pushcclosure(thread.address, this.gcPointer, 0) - thread.lua.lua_settable(thread.address, -3) - - thread.lua.lua_pushstring(thread.address, '__metatable') - thread.lua.lua_pushstring(thread.address, 'protected metatable') - thread.lua.lua_settable(thread.address, -3) + if (state.lua.luaL_newmetatable(state.address, this.name)) { + state.lua.lua_pushstring(state.address, '__gc') + state.lua.lua_pushcclosure(state.address, this.gcPointer, 0) + state.lua.lua_settable(state.address, -3) + + state.lua.lua_pushstring(state.address, '__metatable') + state.lua.lua_pushstring(state.address, 'protected metatable') + state.lua.lua_settable(state.address, -3) } // Pop the metatable from the stack. - thread.lua.lua_pop(thread.address, 1) + state.lua.lua_pop(state.address, 1) - this.functionWrapper = thread.lua._emscripten.addFunction((calledL: LuaAddress) => { - const calledThread = thread.stateToThread(calledL) + this.functionWrapper = state.lua._emscripten.addFunction((calledL: LuaAddress) => { + const calledThread = state.stateToThread(calledL) - const refUserdata = thread.lua.luaL_checkudata(calledL, thread.lua.lua_upvalueindex(1), this.name) - const refPointer = thread.lua._emscripten.getValue(refUserdata, '*') - const { target, options: decorationOptions } = thread.lua.getRef(refPointer) as Decoration + const refUserdata = state.lua.luaL_checkudata(calledL, state.lua.lua_upvalueindex(1), this.name) + const refPointer = state.lua._emscripten.getValue(refUserdata, '*') + const { target, options: decorationOptions } = state.lua.getRef(refPointer) as Decoration const argsQuantity = calledThread.getTop() const args = [] @@ -115,8 +105,8 @@ class FunctionTypeExtension extends TypeExtension { } public close(): void { - this.thread.lua._emscripten.removeFunction(this.gcPointer) - this.thread.lua._emscripten.removeFunction(this.functionWrapper) + this.state.lua._emscripten.removeFunction(this.gcPointer) + this.state.lua._emscripten.removeFunction(this.functionWrapper) // Doesn't destroy the Lua thread, just function pointers. this.callbackContext.close() // Destroy the Lua thread @@ -127,7 +117,7 @@ class FunctionTypeExtension extends TypeExtension { return type === LuaType.Function } - public pushValue(thread: Thread, decoration: Decoration): boolean { + public pushValue(thread: Thread, decoration: Decoration): boolean { if (typeof decoration.target !== 'function') { return false } @@ -193,11 +183,11 @@ class FunctionTypeExtension extends TypeExtension { callThread.pushValue(arg) } - if (this.options?.functionTimeout) { - callThread.setTimeout(Date.now() + this.options.functionTimeout) + if (this.functionTimeout) { + callThread.setDeadline(Date.now() + this.functionTimeout) } - const status: LuaReturn = callThread.lua.lua_pcallk(callThread.address, args.length, 1, 0, 0, null) + const status = callThread.lua.lua_pcallk(callThread.address, args.length, 1, 0, 0, null) if (status === LuaReturn.Yield) { throw new Error('cannot yield in callbacks from javascript') } @@ -220,6 +210,6 @@ class FunctionTypeExtension extends TypeExtension { } } -export default function createTypeExtension(thread: LuaState, options?: FunctionTypeExtensionOptions): TypeExtension { - return new FunctionTypeExtension(thread, options) +export default function createTypeExtension(state: LuaState, functionTimeout?: number): TypeExtension { + return new FunctionTypeExtension(state, functionTimeout) } diff --git a/src/type-extensions/null.ts b/src/type-extensions/null.ts index b38e310..d6f9c34 100644 --- a/src/type-extensions/null.ts +++ b/src/type-extensions/null.ts @@ -1,59 +1,52 @@ import { Decoration } from '../decoration' import type LuaState from '../state' -import Thread from '../thread' +import type Thread from '../thread' import TypeExtension from '../type-extension' -import { LUA_REGISTRYINDEX, LuaReturn, LuaAddress } from '../types' +import { LUA_REGISTRYINDEX } from '../types' class NullTypeExtension extends TypeExtension { private gcPointer: number private nullReference: number - public constructor(thread: LuaState) { - super(thread, 'js_null') + public constructor(state: LuaState) { + super(state, 'js_null') - this.gcPointer = thread.lua._emscripten.addFunction((functionStateAddress: LuaAddress) => { - // Throws a lua error which does a jump if it does not match. - const userDataPointer = thread.lua.luaL_checkudata(functionStateAddress, 1, this.name) - const referencePointer = thread.lua._emscripten.getValue(userDataPointer, '*') - thread.lua.unref(referencePointer) + this.gcPointer = this.createGcFunction() - return LuaReturn.Ok - }, 'ii') - - if (thread.lua.luaL_newmetatable(thread.address, this.name)) { - const metatableIndex = thread.lua.lua_gettop(thread.address) + if (state.lua.luaL_newmetatable(state.address, this.name)) { + const metatableIndex = state.lua.lua_gettop(state.address) // Mark it as uneditable - thread.lua.lua_pushstring(thread.address, 'protected metatable') - thread.lua.lua_setfield(thread.address, metatableIndex, '__metatable') + state.lua.lua_pushstring(state.address, 'protected metatable') + state.lua.lua_setfield(state.address, metatableIndex, '__metatable') // Add the gc function - thread.lua.lua_pushcclosure(thread.address, this.gcPointer, 0) - thread.lua.lua_setfield(thread.address, metatableIndex, '__gc') + state.lua.lua_pushcclosure(state.address, this.gcPointer, 0) + state.lua.lua_setfield(state.address, metatableIndex, '__gc') // Add an __index method that returns nothing. - thread.pushValue(() => null) - thread.lua.lua_setfield(thread.address, metatableIndex, '__index') + state.pushValue(() => null) + state.lua.lua_setfield(state.address, metatableIndex, '__index') - thread.pushValue(() => 'null') - thread.lua.lua_setfield(thread.address, metatableIndex, '__tostring') + state.pushValue(() => 'null') + state.lua.lua_setfield(state.address, metatableIndex, '__tostring') - thread.pushValue((self: unknown, other: unknown) => self === other) - thread.lua.lua_setfield(thread.address, metatableIndex, '__eq') + state.pushValue((self: unknown, other: unknown) => self === other) + state.lua.lua_setfield(state.address, metatableIndex, '__eq') } // Pop the metatable from the stack. - thread.lua.lua_pop(thread.address, 1) + state.lua.lua_pop(state.address, 1) // Create a new table, this is unique and will be the "null" value by attaching the // metatable created above. The first argument is the target, the second options. - super.pushValue(thread, new Decoration({}, {})) + super.pushValue(state, new Decoration({}, {})) // Lua code is free to reassign the `null` global, so marshalling anchors the sentinel in // the registry instead of looking it up by name. - thread.lua.lua_pushvalue(thread.address, -1) - this.nullReference = thread.lua.luaL_ref(thread.address, LUA_REGISTRYINDEX) + state.lua.lua_pushvalue(state.address, -1) + this.nullReference = state.lua.luaL_ref(state.address, LUA_REGISTRYINDEX) - thread.lua.lua_setglobal(thread.address, 'null') + state.lua.lua_setglobal(state.address, 'null') } public getValue(thread: Thread, index: number): null { @@ -64,9 +57,8 @@ class NullTypeExtension extends TypeExtension { return null } - // any because LuaDecoration is not exported from the Lua lib. - public pushValue(thread: Thread, decoration: any): boolean { - if (decoration?.target !== null) { + public pushValue(thread: Thread, decoration: Decoration): boolean { + if (decoration.target !== null) { return false } thread.lua.lua_rawgeti(thread.address, LUA_REGISTRYINDEX, BigInt(this.nullReference)) @@ -74,10 +66,10 @@ class NullTypeExtension extends TypeExtension { } public close(): void { - this.thread.lua._emscripten.removeFunction(this.gcPointer) + this.state.lua._emscripten.removeFunction(this.gcPointer) } } -export default function createTypeExtension(thread: LuaState): TypeExtension { - return new NullTypeExtension(thread) +export default function createTypeExtension(state: LuaState): TypeExtension { + return new NullTypeExtension(state) } diff --git a/src/type-extensions/promise.ts b/src/type-extensions/promise.ts index a10dead..ad393bd 100644 --- a/src/type-extensions/promise.ts +++ b/src/type-extensions/promise.ts @@ -2,56 +2,52 @@ import { Decoration } from '../decoration' import type LuaState from '../state' import MultiReturn from '../multireturn' import RawResult from '../raw-result' -import Thread from '../thread' +import type Thread from '../thread' import TypeExtension from '../type-extension' -import { LuaReturn, LuaAddress } from '../types' +import type { LuaAddress } from '../types' import { isPromise } from '../utils' import { decorate } from '../decoration' class PromiseTypeExtension extends TypeExtension> { private gcPointer: number - public constructor(thread: LuaState, injectObject: boolean) { - super(thread, 'js_promise') + public constructor(state: LuaState, injectObject: boolean) { + super(state, 'js_promise') - this.gcPointer = thread.lua._emscripten.addFunction((functionStateAddress: LuaAddress) => { - // Throws a lua error which does a jump if it does not match. - const userDataPointer = thread.lua.luaL_checkudata(functionStateAddress, 1, this.name) - const referencePointer = thread.lua._emscripten.getValue(userDataPointer, '*') - thread.lua.unref(referencePointer) + this.gcPointer = this.createGcFunction() - return LuaReturn.Ok - }, 'ii') - - if (thread.lua.luaL_newmetatable(thread.address, this.name)) { - const metatableIndex = thread.lua.lua_gettop(thread.address) + if (state.lua.luaL_newmetatable(state.address, this.name)) { + const metatableIndex = state.lua.lua_gettop(state.address) // Mark it as uneditable - thread.lua.lua_pushstring(thread.address, 'protected metatable') - thread.lua.lua_setfield(thread.address, metatableIndex, '__metatable') + state.lua.lua_pushstring(state.address, 'protected metatable') + state.lua.lua_setfield(state.address, metatableIndex, '__metatable') // Add the gc function - thread.lua.lua_pushcclosure(thread.address, this.gcPointer, 0) - thread.lua.lua_setfield(thread.address, metatableIndex, '__gc') + state.lua.lua_pushcclosure(state.address, this.gcPointer, 0) + state.lua.lua_setfield(state.address, metatableIndex, '__gc') - const checkSelf = (self: Promise): true => { + // A bare thenable reaches here too, and only `then` is guaranteed on one. Adopting it + // into a real promise is what makes catch/finally/await work on it, and is a no-op for + // the native promises that make up almost every case. + const asPromise = (self: unknown): Promise => { if (!isPromise(self)) { throw new Error('self instance is not a promise') } - return true + return Promise.resolve(self) } - thread.pushValue({ - next: (self: Promise, ...args: Parameters) => checkSelf(self) && self.then(...args), - catch: (self: Promise, ...args: Parameters) => checkSelf(self) && self.catch(...args), - finally: (self: Promise, ...args: Parameters) => checkSelf(self) && self.finally(...args), + state.pushValue({ + next: (self: unknown, ...args: Parameters['then']>) => asPromise(self).then(...args), + catch: (self: unknown, ...args: Parameters['catch']>) => asPromise(self).catch(...args), + finally: (self: unknown, ...args: Parameters['finally']>) => asPromise(self).finally(...args), await: decorate( - (functionThread: Thread, self: Promise) => { - checkSelf(self) + (functionThread: Thread, rawSelf: unknown) => { + const self = asPromise(rawSelf) // Asking Lua covers every non-resumable context, not just the main // thread: anything entered through lua_pcall cannot yield either. - if (!thread.lua.lua_isyieldable(functionThread.address)) { + if (!state.lua.lua_isyieldable(functionThread.address)) { throw new Error('cannot await in a thread that cannot yield, use doString instead of doStringSync') } @@ -66,7 +62,7 @@ class PromiseTypeExtension extends TypeExtension> { promiseResult = { status: 'rejected', value: err } }) - const continuance = this.thread.lua._emscripten.addFunction((continuanceState: LuaAddress) => { + const continuance = this.state.lua._emscripten.addFunction((continuanceState: LuaAddress) => { // If this yield has been called from within a coroutine and so manually resumed // then there may not yet be any results. In that case yield again. if (!promiseResult) { @@ -75,16 +71,16 @@ class PromiseTypeExtension extends TypeExtension> { // 0 because this is called between resumes so the first one should've // popped the promise before returning the result. This is true within // Lua's coroutine.resume too. - return thread.lua.lua_yieldk(functionThread.address, 0, 0, continuance) + return state.lua.lua_yieldk(functionThread.address, 0, 0, continuance) } - this.thread.lua._emscripten.removeFunction(continuance) + this.state.lua._emscripten.removeFunction(continuance) - const continuanceThread = thread.stateToThread(continuanceState) + const continuanceThread = state.stateToThread(continuanceState) if (promiseResult.status === 'rejected') { continuanceThread.pushValue(promiseResult.value || new Error('promise rejected with no error')) - return this.thread.lua.lua_error(continuanceState) + return this.state.lua.lua_error(continuanceState) } if (promiseResult.value instanceof RawResult) { @@ -101,22 +97,22 @@ class PromiseTypeExtension extends TypeExtension> { }, 'iiii') functionThread.pushValue(awaitPromise) - return new RawResult(thread.lua.lua_yieldk(functionThread.address, 1, 0, continuance)) + return new RawResult(state.lua.lua_yieldk(functionThread.address, 1, 0, continuance)) }, { receiveThread: true }, ), }) - thread.lua.lua_setfield(thread.address, metatableIndex, '__index') + state.lua.lua_setfield(state.address, metatableIndex, '__index') - thread.pushValue((self: Promise, other: Promise) => self === other) - thread.lua.lua_setfield(thread.address, metatableIndex, '__eq') + state.pushValue((self: Promise, other: Promise) => self === other) + state.lua.lua_setfield(state.address, metatableIndex, '__eq') } // Pop the metatable from the stack. - thread.lua.lua_pop(thread.address, 1) + state.lua.lua_pop(state.address, 1) if (injectObject) { // Lastly create a static Promise constructor. - thread.set('Promise', { + state.set('Promise', { create: (callback: ConstructorParameters[0]) => new Promise(callback), all: (promiseArray: any) => { if (!Array.isArray(promiseArray)) { @@ -131,10 +127,10 @@ class PromiseTypeExtension extends TypeExtension> { } public close(): void { - this.thread.lua._emscripten.removeFunction(this.gcPointer) + this.state.lua._emscripten.removeFunction(this.gcPointer) } - public pushValue(thread: Thread, decoration: Decoration>): boolean { + public pushValue(thread: Thread, decoration: Decoration): boolean { if (!isPromise(decoration.target)) { return false } @@ -142,6 +138,6 @@ class PromiseTypeExtension extends TypeExtension> { } } -export default function createTypeExtension(thread: LuaState, injectObject: boolean): TypeExtension> { - return new PromiseTypeExtension(thread, injectObject) +export default function createTypeExtension(state: LuaState, injectObject: boolean): TypeExtension> { + return new PromiseTypeExtension(state, injectObject) } diff --git a/src/type-extensions/proxy.ts b/src/type-extensions/proxy.ts index f151a0f..a059d18 100644 --- a/src/type-extensions/proxy.ts +++ b/src/type-extensions/proxy.ts @@ -1,38 +1,31 @@ import { decorate, Decoration } from '../decoration' import type LuaState from '../state' import MultiReturn from '../multireturn' -import Thread from '../thread' +import type Thread from '../thread' import TypeExtension from '../type-extension' -import { LuaReturn, LuaAddress, LuaType } from '../types' +import { LuaType } from '../types' import { isPromise } from '../utils' class ProxyTypeExtension extends TypeExtension { private readonly gcPointer: number - public constructor(thread: LuaState) { - super(thread, 'js_proxy') + public constructor(state: LuaState) { + super(state, 'js_proxy') - this.gcPointer = thread.lua._emscripten.addFunction((functionStateAddress: LuaAddress) => { - // Throws a lua error which does a jump if it does not match. - const userDataPointer = thread.lua.luaL_checkudata(functionStateAddress, 1, this.name) - const referencePointer = thread.lua._emscripten.getValue(userDataPointer, '*') - thread.lua.unref(referencePointer) + this.gcPointer = this.createGcFunction() - return LuaReturn.Ok - }, 'ii') - - if (thread.lua.luaL_newmetatable(thread.address, this.name)) { - const metatableIndex = thread.lua.lua_gettop(thread.address) + if (state.lua.luaL_newmetatable(state.address, this.name)) { + const metatableIndex = state.lua.lua_gettop(state.address) // Mark it as uneditable - thread.lua.lua_pushstring(thread.address, 'protected metatable') - thread.lua.lua_setfield(thread.address, metatableIndex, '__metatable') + state.lua.lua_pushstring(state.address, 'protected metatable') + state.lua.lua_setfield(state.address, metatableIndex, '__metatable') // Add the gc function - thread.lua.lua_pushcclosure(thread.address, this.gcPointer, 0) - thread.lua.lua_setfield(thread.address, metatableIndex, '__gc') + state.lua.lua_pushcclosure(state.address, this.gcPointer, 0) + state.lua.lua_setfield(state.address, metatableIndex, '__gc') - thread.pushValue((self: any, key: unknown) => { + state.pushValue((self: any, key: unknown) => { switch (typeof key) { case 'number': // Map from Lua's 1 based indexing to JS's 0. @@ -53,9 +46,9 @@ class ProxyTypeExtension extends TypeExtension { return value }) - thread.lua.lua_setfield(thread.address, metatableIndex, '__index') + state.lua.lua_setfield(state.address, metatableIndex, '__index') - thread.pushValue((self: any, key: unknown, value: any) => { + state.pushValue((self: any, key: unknown, value: any) => { switch (typeof key) { case 'number': // Map from Lua's 1 based indexing to JS's 0. @@ -68,19 +61,19 @@ class ProxyTypeExtension extends TypeExtension { } self[key as string | number] = value }) - thread.lua.lua_setfield(thread.address, metatableIndex, '__newindex') + state.lua.lua_setfield(state.address, metatableIndex, '__newindex') - thread.pushValue((self: any) => { + state.pushValue((self: any) => { return self.toString?.() ?? typeof self }) - thread.lua.lua_setfield(thread.address, metatableIndex, '__tostring') + state.lua.lua_setfield(state.address, metatableIndex, '__tostring') - thread.pushValue((self: any) => { + state.pushValue((self: any) => { return self.length || 0 }) - thread.lua.lua_setfield(thread.address, metatableIndex, '__len') + state.lua.lua_setfield(state.address, metatableIndex, '__len') - thread.pushValue((self: any) => { + state.pushValue((self: any) => { const keys = Object.getOwnPropertyNames(self) let i = 0 // Stateful rather than stateless. First call is with nil. @@ -94,24 +87,24 @@ class ProxyTypeExtension extends TypeExtension { null, ) }) - thread.lua.lua_setfield(thread.address, metatableIndex, '__pairs') + state.lua.lua_setfield(state.address, metatableIndex, '__pairs') - thread.pushValue((self: any, other: any) => { + state.pushValue((self: any, other: any) => { return self === other }) - thread.lua.lua_setfield(thread.address, metatableIndex, '__eq') + state.lua.lua_setfield(state.address, metatableIndex, '__eq') - thread.pushValue((self: any, ...args: any[]) => { + state.pushValue((self: any, ...args: any[]) => { if (args[0] === self) { args.shift() } return self(...args) }) - thread.lua.lua_setfield(thread.address, metatableIndex, '__call') + state.lua.lua_setfield(state.address, metatableIndex, '__call') } // Pop the metatable from the stack. - thread.lua.lua_pop(thread.address, 1) + state.lua.lua_pop(state.address, 1) } public isType(_thread: Thread, _index: number, type: LuaType, name?: string): boolean { @@ -125,7 +118,7 @@ class ProxyTypeExtension extends TypeExtension { return thread.lua.getRef(referencePointer) } - public pushValue(thread: Thread, decoratedValue: Decoration): boolean { + public pushValue(thread: Thread, decoratedValue: Decoration): boolean { const { target, options } = decoratedValue if (options.as === undefined) { if (target === null || target === undefined) { @@ -160,10 +153,10 @@ class ProxyTypeExtension extends TypeExtension { } public close(): void { - this.thread.lua._emscripten.removeFunction(this.gcPointer) + this.state.lua._emscripten.removeFunction(this.gcPointer) } } -export default function createTypeExtension(thread: LuaState): TypeExtension { - return new ProxyTypeExtension(thread) +export default function createTypeExtension(state: LuaState): TypeExtension { + return new ProxyTypeExtension(state) } diff --git a/src/type-extensions/table.ts b/src/type-extensions/table.ts index e6e6bbf..2501735 100644 --- a/src/type-extensions/table.ts +++ b/src/type-extensions/table.ts @@ -1,14 +1,14 @@ import { Decoration } from '../decoration' import type LuaState from '../state' -import Thread from '../thread' +import type Thread from '../thread' import TypeExtension from '../type-extension' -import { LUA_REGISTRYINDEX, LuaType } from '../types' +import { LUA_REGISTRYINDEX, type LuaGetCache, type LuaPushCache, LuaType } from '../types' export type TableType = Record | any[] class TableTypeExtension extends TypeExtension { - public constructor(thread: LuaState) { - super(thread, 'js_table') + public constructor(state: LuaState) { + super(state, 'js_table') } public close(): void { @@ -19,12 +19,12 @@ class TableTypeExtension extends TypeExtension { return type === LuaType.Table } - public getValue(thread: Thread, index: number, userdata?: any): TableType { + public getValue(thread: Thread, index: number, cache?: LuaGetCache): TableType { // This is a map of Lua pointers to JS objects. - const seenMap: Map = userdata || new Map() + const seenMap: LuaGetCache = cache ?? new Map() const pointer = thread.lua.lua_topointer(thread.address, index) - let table = seenMap.get(pointer) + let table = seenMap.get(pointer) as TableType | undefined if (!table) { const keys = this.readTableKeys(thread, index) @@ -38,13 +38,13 @@ class TableTypeExtension extends TypeExtension { return table } - public pushValue(thread: Thread, { target }: Decoration, userdata?: Map): boolean { + public pushValue(thread: Thread, { target }: Decoration, cache?: LuaPushCache): boolean { if (typeof target !== 'object' || target === null) { return false } // This is a map of JS objects to luaL references. - const seenMap = userdata || new Map() + const seenMap: LuaPushCache = cache ?? new Map() const existingReference = seenMap.get(target) if (existingReference !== undefined) { thread.lua.lua_rawgeti(thread.address, LUA_REGISTRYINDEX, BigInt(existingReference)) @@ -82,7 +82,8 @@ class TableTypeExtension extends TypeExtension { } } } finally { - if (userdata === undefined) { + // Only the outermost push owns the anchors it created for the values below it. + if (cache === undefined) { for (const reference of seenMap.values()) { thread.lua.luaL_unref(thread.address, LUA_REGISTRYINDEX, reference) } @@ -107,7 +108,7 @@ class TableTypeExtension extends TypeExtension { return keys } - private readTableValues(thread: Thread, index: number, seenMap: Map, table: TableType): void { + private readTableValues(thread: Thread, index: number, seenMap: LuaGetCache, table: TableType): void { const isArray = Array.isArray(table) thread.lua.lua_pushnil(thread.address) @@ -126,6 +127,6 @@ class TableTypeExtension extends TypeExtension { } } -export default function createTypeExtension(thread: LuaState): TypeExtension { - return new TableTypeExtension(thread) +export default function createTypeExtension(state: LuaState): TypeExtension { + return new TableTypeExtension(state) } diff --git a/src/type-extensions/userdata.ts b/src/type-extensions/userdata.ts index ac9cd5a..3d83d16 100644 --- a/src/type-extensions/userdata.ts +++ b/src/type-extensions/userdata.ts @@ -1,38 +1,31 @@ import { Decoration } from '../decoration' import type LuaState from '../state' -import Thread from '../thread' +import type Thread from '../thread' import TypeExtension from '../type-extension' -import { LuaReturn, LuaAddress, LuaType } from '../types' +import { LuaType } from '../types' class UserdataTypeExtension extends TypeExtension { private readonly gcPointer: number - public constructor(thread: LuaState) { - super(thread, 'js_userdata') + public constructor(state: LuaState) { + super(state, 'js_userdata') - this.gcPointer = thread.lua._emscripten.addFunction((functionStateAddress: LuaAddress) => { - // Throws a lua error which does a jump if it does not match. - const userDataPointer = thread.lua.luaL_checkudata(functionStateAddress, 1, this.name) - const referencePointer = thread.lua._emscripten.getValue(userDataPointer, '*') - thread.lua.unref(referencePointer) + this.gcPointer = this.createGcFunction() - return LuaReturn.Ok - }, 'ii') - - if (thread.lua.luaL_newmetatable(thread.address, this.name)) { - const metatableIndex = thread.lua.lua_gettop(thread.address) + if (state.lua.luaL_newmetatable(state.address, this.name)) { + const metatableIndex = state.lua.lua_gettop(state.address) // Mark it as uneditable - thread.lua.lua_pushstring(thread.address, 'protected metatable') - thread.lua.lua_setfield(thread.address, metatableIndex, '__metatable') + state.lua.lua_pushstring(state.address, 'protected metatable') + state.lua.lua_setfield(state.address, metatableIndex, '__metatable') // Add the gc function - thread.lua.lua_pushcclosure(thread.address, this.gcPointer, 0) - thread.lua.lua_setfield(thread.address, metatableIndex, '__gc') + state.lua.lua_pushcclosure(state.address, this.gcPointer, 0) + state.lua.lua_setfield(state.address, metatableIndex, '__gc') } // Pop the metatable from the stack. - thread.lua.lua_pop(thread.address, 1) + state.lua.lua_pop(state.address, 1) } public isType(_thread: Thread, _index: number, type: LuaType, name?: string): boolean { @@ -45,7 +38,7 @@ class UserdataTypeExtension extends TypeExtension { return thread.lua.getRef(referencePointer) } - public pushValue(thread: Thread, decoratedValue: Decoration): boolean { + public pushValue(thread: Thread, decoratedValue: Decoration): boolean { if (decoratedValue.options.as !== 'userdata') { return false } @@ -54,10 +47,10 @@ class UserdataTypeExtension extends TypeExtension { } public close(): void { - this.thread.lua._emscripten.removeFunction(this.gcPointer) + this.state.lua._emscripten.removeFunction(this.gcPointer) } } -export default function createTypeExtension(thread: LuaState): TypeExtension { - return new UserdataTypeExtension(thread) +export default function createTypeExtension(state: LuaState): TypeExtension { + return new UserdataTypeExtension(state) } diff --git a/src/types.ts b/src/types.ts index 0985b9c..abccc7b 100755 --- a/src/types.ts +++ b/src/types.ts @@ -1,4 +1,7 @@ -/** A pointer to a `lua_State` inside the wasm heap. */ +/** + * An address in the wasm heap: a `lua_State`, or the storage behind a Lua value. Emscripten + * function pointers are table indices rather than addresses, so those stay plain numbers. + */ export type LuaAddress = number /** Receives diagnostics the library would otherwise have written to the console. */ @@ -61,16 +64,16 @@ export interface LuaMemoryOptions { * Installs a custom allocator so memory can be measured and capped. Without it `state.memory` * is undefined. */ - trace?: boolean + trace?: boolean | undefined /** Maximum bytes the state may allocate. Requires `trace`. */ - max?: number + max?: number | undefined } export interface LuaLimitOptions { /** Milliseconds a Lua function called from JS may run before being interrupted. */ - functionTimeout?: number + functionTimeout?: number | undefined /** Instructions a single run may execute before being interrupted. */ - maxInstructions?: number + maxInstructions?: number | undefined } export interface CreateStateOptions { @@ -78,30 +81,30 @@ export interface CreateStateOptions { * Which standard libraries to open. `true` opens all of them, `false` opens none (which * leaves the state without even `tostring`), or name them individually. */ - libs?: LuaLibName[] | boolean + libs?: LuaLibName[] | boolean | undefined /** * How plain JS objects and class instances cross into Lua. `'proxy'` keeps their identity and * exposes their members, `'copy'` marshals them into plain Lua tables. */ - objects?: 'proxy' | 'copy' + objects?: 'proxy' | 'copy' | undefined /** * Registers the JS `Error` to Lua error bridge. Defaults to true when `objects` is `'copy'`, * because the proxy already covers errors when it is enabled. */ - errors?: boolean + errors?: boolean | undefined /** Injects `Error`, `Promise` and `null` into the Lua globals. */ - inject?: boolean - memory?: LuaMemoryOptions - limits?: LuaLimitOptions + inject?: boolean | undefined + memory?: LuaMemoryOptions | undefined + limits?: LuaLimitOptions | undefined /** Where diagnostics go. Defaults to `console.warn`. */ - onWarn?: LuaWarnHandler + onWarn?: LuaWarnHandler | undefined } export interface LuaRunOptions { /** Milliseconds before the run is interrupted. */ - timeout?: number + timeout?: number | undefined /** Instructions the run may execute before being interrupted. */ - maxInstructions?: number + maxInstructions?: number | undefined /** * Interrupts the run when the signal aborts. * @@ -111,7 +114,7 @@ export interface LuaRunOptions { * the hook evaluates them on its own. And a run parked on a promise finishes awaiting that * promise before the abort is seen, rather than abandoning it mid-flight. */ - signal?: AbortSignal + signal?: AbortSignal | undefined } export interface LuaLoadOptions { @@ -120,19 +123,22 @@ export interface LuaLoadOptions { * bytecode from an untrusted source is a memory safety hole rather than a sandbox escape. * Only widen this for chunks you produced yourself. */ - mode?: LuaLoadMode + mode?: LuaLoadMode | undefined /** Chunk name used in error messages and tracebacks. */ - name?: string + name?: string | undefined } export type LuaDoOptions = LuaRunOptions & LuaLoadOptions -/** Deadline and budget enforced by the debug hook while a thread runs. */ +/** + * Deadline and budget enforced by the debug hook while a thread runs. Every field accepts an + * explicit undefined, which clears that one limit. + */ export interface LuaThreadLimits { /** Absolute timestamp, as returned by `Date.now()`. */ - deadline?: number - maxInstructions?: number - signal?: AbortSignal + deadline?: number | undefined + maxInstructions?: number | undefined + signal?: AbortSignal | undefined } export enum LuaReturn { @@ -150,6 +156,15 @@ export interface LuaResumeResult { resultCount: number } +/** + * Memo threaded through a recursive read, keyed by the address of the Lua value, so a cyclic table + * produces a cyclic JS object instead of recursing forever. + */ +export type LuaGetCache = Map + +/** The mirror of {@link LuaGetCache}, holding a registry reference to anchor each pushed value. */ +export type LuaPushCache = Map + export const PointerSize = 4 export const LUA_MULTRET = -1 @@ -198,7 +213,7 @@ export class LuaError extends Error { /** The value Lua actually raised, which is not always a string. */ public readonly luaValue: unknown - public constructor(code: LuaReturn, luaMessage: string, options: { traceback?: string; luaValue?: unknown } = {}) { + public constructor(code: LuaReturn, luaMessage: string, options: { traceback?: string | undefined; luaValue?: unknown } = {}) { super(luaMessage) this.code = code this.luaMessage = luaMessage diff --git a/src/utils.ts b/src/utils.ts index 1e6744e..3f10fc4 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,5 +1,12 @@ -export const isPromise = (target: any): target is Promise => { - return target && (Promise.resolve(target) === target || typeof target.then === 'function') +/** + * Any thenable, not just a native promise. Callers that need `catch`/`finally` rather than only + * `await` have to normalise with `Promise.resolve` first. + */ +export const isPromise = (target: unknown): target is PromiseLike => { + // A `Promise.resolve(target) === target` identity check would also answer this, but it + // allocates a promise for every value that turns out not to be one, and for a bare thenable it + // calls the user's `then` just to find out. + return typeof target === 'object' && target !== null && typeof (target as PromiseLike).then === 'function' } /** diff --git a/test/.oxlintrc.json b/test/.oxlintrc.json new file mode 100644 index 0000000..a2a6ace --- /dev/null +++ b/test/.oxlintrc.json @@ -0,0 +1,5 @@ +{ + "rules": { + "no-unused-expressions": "off" + } +} diff --git a/test/errors.test.js b/test/errors.test.js index 2d9c9c6..dc247dc 100644 --- a/test/errors.test.js +++ b/test/errors.test.js @@ -49,7 +49,7 @@ describe('Unrepresentable values', () => { const thread = state.newThread() thread.lua.lua_newuserdatauv(thread.address, 4, 0) - expect(Number(thread.getPointer(-1))).to.be.greaterThan(0) + expect(thread.getPointer(-1)).to.be.greaterThan(0) }) }) diff --git a/test/state.test.js b/test/state.test.js index 74c1c2d..82bcf02 100644 --- a/test/state.test.js +++ b/test/state.test.js @@ -564,8 +564,8 @@ describe('State', () => { const state = await getState() const thread = state.newThread() - thread.setTimeout(Date.now() + 20) - thread.setTimeout(Date.now() + 20_000) + thread.setDeadline(Date.now() + 20) + thread.setDeadline(Date.now() + 20_000) thread.loadString('local x = 0 for i = 1, 20000000 do x = x + 1 end return x') expect((await thread.run(0))[0]).to.be.equal(20000000) @@ -576,11 +576,11 @@ describe('State', () => { const state = await getState() const thread = state.newThread() - thread.setTimeout(Date.now() + 10) - thread.setTimeout(undefined) + thread.setDeadline(Date.now() + 10) + thread.setDeadline(undefined) thread.loadString('local x = 0 for i = 1, 5000000 do x = x + 1 end return 7') - expect(thread.getTimeout()).to.be.undefined + expect(thread.getDeadline()).to.be.undefined expect((await thread.run(0))[0]).to.be.equal(7) }) @@ -1225,6 +1225,6 @@ describe('Synchronous runs', () => { state.doStringSync('return 1', { timeout: 1000 }) - expect(state.getTimeout()).to.be.undefined + expect(state.getDeadline()).to.be.undefined }) }) diff --git a/tsconfig.json b/tsconfig.json index 54b02dd..94f684f 100755 --- a/tsconfig.json +++ b/tsconfig.json @@ -18,8 +18,11 @@ "noUnusedLocals": true, "importHelpers": true, "strict": true, + "exactOptionalPropertyTypes": true, + "verbatimModuleSyntax": true, "resolveJsonModule": true }, - "include": ["src/**/*", "test/**/*", "bench/**/*"], + // test/ and bench/ are plain JS, so without allowJs they were only nominally covered. + "include": ["src/**/*"], "exclude": ["node_modules"] } From e128f8d45d03e4d2ea9c416a361fba865ac08476 Mon Sep 17 00:00:00 2001 From: Gabriel Francisco Date: Tue, 28 Jul 2026 22:13:29 -0300 Subject: [PATCH 43/83] better browser support --- .prettierignore | 6 -- README.md | 162 +++++++++++++++++------------------ package.json | 16 +++- rolldown.config.ts | 41 +++++++-- src/module.ts | 195 ++++++++++++++++++++++++++---------------- src/utils.ts | 12 +-- test/browser.test.js | 154 ++++++++++++++++++++++++++++++--- test/bundling.test.js | 84 ++++++++++++++++++ utils/build-wasm.sh | 4 +- 9 files changed, 485 insertions(+), 189 deletions(-) delete mode 100644 .prettierignore create mode 100644 test/bundling.test.js diff --git a/.prettierignore b/.prettierignore deleted file mode 100644 index 39d09df..0000000 --- a/.prettierignore +++ /dev/null @@ -1,6 +0,0 @@ -dist/ -node_modules/ -.rollup.cache/ -package-lock.json -build/ -.eslintrc.json diff --git a/README.md b/README.md index f8f2543..d5d12ba 100644 --- a/README.md +++ b/README.md @@ -12,36 +12,42 @@ This package aims to provide a way to: ## API Usage -To initialize, create a new Lua state, register the standard library, set a global variable, execute a code and get a global variable: +Load the wasm module once, create a state on it, then set a global, run some Lua and read a global back: ```js -const { LuaFactory } = require('wasmoon') +import { LuaRuntime } from 'wasmoon' -// Initialize a new lua environment factory -// You can pass the wasm location as the first argument, useful if you are using wasmoon on a web environment and want to host the file by yourself -const factory = new LuaFactory() -// Create a standalone lua environment from the factory -const lua = await factory.createEngine() +// Loads the Lua wasm module. Every state created from it shares the filesystem and stdio. +const lua = await LuaRuntime.load() +// A standalone Lua state, with the standard library open +const state = lua.createState() try { // Set a JS function to be a global lua function - lua.global.set('sum', (x, y) => x + y) + state.set('sum', (x, y) => x + y) // Run a lua string - await lua.doString(` + await state.doString(` print(sum(10, 10)) function multiply(x, y) return x * y end `) // Get a global lua function as a JS function - const multiply = lua.global.get('multiply') + const multiply = state.get('multiply') console.log(multiply(10, 10)) } finally { - // Close the lua environment, so it can be freed - lua.global.close() + // Close the state, so it can be freed + state.close() } ``` +Loading the module is the expensive part, so keep one `LuaRuntime` around and create a state per +sandbox. `lua.close()` closes every state created from it, and both types support `using`: + +```js +await using lua = await LuaRuntime.load() +``` + ## CLI Usage Although Wasmoon has been designed to be embedded, you can run it on command line as well, but, if you want something more robust on this, we recommend to take a look at [demoon](https://github.com/ceifa/demoon). @@ -89,122 +95,114 @@ Wasmoon is **~10x faster** than fengari for pure Lua execution. If your use case ### Size -Fengari is smaller than wasmoon, which can improve the user experience if in web environments: +Fengari is smaller than wasmoon, which can improve the user experience if in web environments. +Both minified, and wasmoon counted as its JS plus `glue.wasm`: -| | wasmoon | fengari | -| ----------- | ------- | ------- | -| **plain** | 357kB | 211kB | -| **gzipped** | 123kB | 69kB | +| | wasmoon | fengari | +| ----------- | ---------------- | ------- | +| **plain** | 294kB (97 + 197) | 228kB | +| **gzipped** | 124kB (29 + 95) | 74kB | -## Fixing common errors on web environment +Almost all of wasmoon's weight is the wasm, which is a separate file: it is fetched in parallel +with your JS rather than parsed as part of it, and it caches on its own across releases of your app. -Bundle/require errors can happen because wasmoon tries to safely import some node modules even in a browser environment, the bundler is not prepared to that since it tries to statically resolve everything on build time. -Polyfilling these modules is not the right solution because they are not actually being used, you just have to ignore them: +## Web environment -### Webpack +Bundlers need no configuration. wasmoon ships as ESM and marks the two node builtins it touches so +that a bundler targeting the browser skips them instead of failing to resolve them, and every +supported bundler produces a working browser build out of the box. -Add the `resolve.fallback` snippet to your config: +### Where `glue.wasm` comes from -```js -module.exports = { - entry: './src/index.js', // Here is your entry file - resolve: { - fallback: { - path: false, - fs: false, - child_process: false, - crypto: false, - url: false, - module: false, - }, - }, -} -``` +The wasm is resolved next to the bundle, with `new URL('glue.wasm', import.meta.url)`. What that +means depends on your bundler: -### Rollup +| bundler | what happens | +| ------- | ------------------------------------------------------------------ | +| Vite | inlines the wasm into the bundle, nothing else to do | +| webpack | emits the wasm as an asset next to your output, nothing else to do | +| esbuild | does not handle the asset, see below | +| Rollup | does not handle the asset, see below | -With the package [rollup-plugin-ignore](https://www.npmjs.com/package/rollup-plugin-ignore), add this snippet to your config: +esbuild and Rollup leave nothing beside the bundle to fetch, so wasmoon falls back to unpkg with a +warning. That works, but it is a request to a third party pinned to wasmoon's version, so prefer +copying the wasm next to your output as part of the build, after which nothing else is needed: ```js -export default { - input: 'src/index.js', // Here is your entry file, - plugins: [ignore(['path', 'fs', 'child_process', 'crypto', 'url', 'module'])], -} +import { copyFile } from 'node:fs/promises' +import { fileURLToPath } from 'node:url' + +await copyFile(fileURLToPath(import.meta.resolve('wasmoon/glue.wasm')), 'dist/glue.wasm') ``` -### Angular - -Add the section browser on `package.json`: - -```json -{ - "main": "src/index.js", - "browser": { - "child_process": false, - "fs": false, - "path": false, - "crypto": false, - "url": false, - "module": false - } -} +Or host it wherever you like and say where it is: + +```js +const lua = await LuaRuntime.load({ wasmFile: '/assets/glue.wasm' }) ``` -## How to build +With Vite and webpack you want neither, since they already handle the asset. Asking for it again +(`wasmoon/glue.wasm?url` and friends) makes them ship the wasm twice. -Firstly download the lua submodule and install the other Node.JS dependencies: +### A page opened from `file://` -```sh -git submodule update --init # download lua submodule -npm i # install dependencies +A page loaded over `file://` cannot fetch anything next to it, so the wasm has to come from +somewhere else and wasmoon falls back to unpkg. To keep such a page self contained, inline the wasm +and hand it over as a data URL: + +```js +const lua = await LuaRuntime.load({ wasmFile: 'data:application/wasm;base64,...' }) ``` -### Windows / Linux / MacOS (Docker way) +Note that Chromium also refuses to load ES modules over `file://`, so the page has to carry your +bundle inline rather than in a ` ` + // A module worker resolves the wasm the same way a page does, but with no `window` in scope. + const workerScript = ` +import LuaRuntime from './index.js' +self.onmessage = async () => { + try { + const lua = await LuaRuntime.load() + const state = lua.createState() + self.postMessage({ ok: await state.doString('return 2 + 5') }) + } catch (err) { + self.postMessage({ error: String(err) }) + } +} +` + const server = createServer(async (req, res) => { const url = new URL(req.url, `http://localhost`) @@ -36,6 +52,12 @@ window.__ready = true return } + if (url.pathname === '/worker.js') { + res.writeHead(200, { 'Content-Type': 'application/javascript' }) + res.end(workerScript) + return + } + const filePath = join(DIST_DIR, url.pathname) try { @@ -58,31 +80,54 @@ window.__ready = true } describe('Browser environment', () => { - let port, browser, context + let port, server, browser, context before(async function () { this.timeout(30_000) - ;({ port } = await startServer()) + ;({ server, port } = await startServer()) browser = await chromium.launch() context = await browser.newContext() }) - async function runInBrowser(code) { + after(async () => { + await browser?.close() + server?.close() + }) + + /** Every URL the page asked for, so a test can tell where the wasm was fetched from. */ + let requested = [] + + async function openPage() { const page = await context.newPage() + requested = [] + page.on('request', (req) => requested.push(req.url())) + const errors = [] page.on('pageerror', (err) => errors.push(err)) + page.assertNoErrors = () => { + if (errors.length > 0) { + throw errors[0] + } + } - try { - await page.goto(`http://127.0.0.1:${port}/`) - await page.waitForFunction(() => window.__ready === true, null, { timeout: 15_000 }) + await page.goto(`http://127.0.0.1:${port}/`) + await page.waitForFunction(() => window.__ready === true, null, { timeout: 15_000 }) + return page + } + + function expectNoExternalRequests() { + expect(requested.filter((url) => !url.startsWith(`http://127.0.0.1:${port}/`))).to.be.empty + } + async function runInBrowser(code) { + const page = await openPage() + + try { const result = await page.evaluate(async (c) => { return await window.__runTest(c) }, code) - if (errors.length > 0) { - throw errors[0] - } + page.assertNoErrors() return result } finally { await page.close() @@ -202,4 +247,91 @@ describe('Browser environment', () => { `) expect(result).to.be.equal(7) }) + + // Every test above passes an explicit wasmFile, which a consumer does not. Without one, the + // wrong default is a request to a CDN pinned to whatever version is in package.json. + describe('default wasm resolution', () => { + it('loads the wasm from the same origin when served over http', async function () { + this.timeout(30_000) + const result = await runInBrowser('await LuaRuntime.load(); return 1') + + expect(result).to.be.equal(1) + expect(requested).to.include(`http://127.0.0.1:${port}/glue.wasm`) + expectNoExternalRequests() + }) + + it('loads the wasm from the same origin inside a module worker', async function () { + this.timeout(30_000) + const page = await openPage() + + try { + const result = await page.evaluate(async () => { + const worker = new Worker('/worker.js', { type: 'module' }) + const message = new Promise((resolve) => worker.addEventListener('message', (e) => resolve(e.data))) + worker.postMessage('go') + return await message + }) + + page.assertNoErrors() + expect(result).to.be.eql({ ok: 7 }) + expectNoExternalRequests() + } finally { + await page.close() + } + }) + + it('falls back to the CDN for a page opened from file:', async function () { + this.timeout(60_000) + // Served locally rather than for real, to keep the suite offline and because the + // published wasm belongs to another version. + const { htmlFile, cleanup } = await writeInlinedPage() + const page = await context.newPage() + const cdnRequests = [] + + try { + await page.route('https://unpkg.com/**', async (route) => { + cdnRequests.push(route.request().url()) + await route.fulfill({ contentType: 'application/wasm', body: await readFile(join(DIST_DIR, 'glue.wasm')) }) + }) + + await page.goto(`file://${htmlFile}`) + await page.waitForFunction(() => window.__ready === true, null, { timeout: 15_000 }) + const result = await page.evaluate(async () => { + const lua = await window.__LuaRuntime.load() + return await lua.createState().doString('return 3 * 3') + }) + + expect(result).to.be.equal(9) + expect(cdnRequests).to.have.lengthOf(1) + expect(cdnRequests[0]).to.match(/^https:\/\/unpkg\.com\/wasmoon@[^/]+\/dist\/glue\.wasm$/) + } finally { + await page.close() + await cleanup() + } + }) + }) }) + +/** + * A single self contained HTML file, the only shape that works from `file:`: Chromium refuses to + * load an ES module over that protocol, so the bundle is inlined. It is already a single chunk, and + * its exported bindings are in scope of the inline module. + */ +async function writeInlinedPage() { + const tempDir = await mkdtemp(join(tmpdir(), 'wasmoon-file-')) + const bundle = await readFile(join(DIST_DIR, 'index.js'), 'utf8') + + const htmlFile = join(tempDir, 'page.html') + await writeFile( + htmlFile, + ` + +`, + ) + + return { htmlFile, cleanup: () => rm(tempDir, { recursive: true, force: true }) } +} diff --git a/test/bundling.test.js b/test/bundling.test.js new file mode 100644 index 0000000..5eec36e --- /dev/null +++ b/test/bundling.test.js @@ -0,0 +1,84 @@ +import { mkdtemp, readFile, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { EventEmitter } from 'node:events' +import { expect } from 'chai' +import { rolldown } from 'rolldown' + +const DIST_DIR = fileURLToPath(new URL('../dist', import.meta.url)) +const WASM_FILE = join(DIST_DIR, 'glue.wasm') + +/** + * Consumers bundle us through a minifier, so anything in the published bundle that depends on a name + * surviving breaks in their build and not in ours. These run it against a minified copy. + */ +describe('Bundling', () => { + let tempDir + let minified + + before(async function () { + this.timeout(60_000) + tempDir = await mkdtemp(join(tmpdir(), 'wasmoon-bundling-')) + + const bundle = await rolldown({ + input: join(DIST_DIR, 'index.js'), + external: ['node:module', 'node:fs'], + }) + await bundle.write({ file: join(tempDir, 'index.js'), format: 'esm', minify: true }) + await bundle.close() + + minified = await import(join(tempDir, 'index.js')) + }) + + after(async () => { + if (tempDir) { + await rm(tempDir, { recursive: true, force: true }) + } + }) + + const getMinifiedState = async (config = {}) => { + const lua = await minified.LuaRuntime.load({ wasmFile: WASM_FILE }) + return lua.createState({ inject: true, ...config }) + } + + it('minifying the bundle renames the unwind classes', async () => { + // The premise of the tests below: a check by class name has nothing left to match on. + const code = await readFile(join(tempDir, 'index.js'), 'utf8') + expect(code).to.not.match(/class Emscripten/) + }) + + it('a yield across a C-call boundary still surfaces as an error when minified', async () => { + const state = await getMinifiedState() + const emitter = new EventEmitter() + state.set('yield', () => new Promise((resolve) => emitter.once('resolve', resolve))) + const resPromise = state.doString(` + local res = yield():next(function () + coroutine.yield() + return 15 + end) + print("res", res:await()) + `) + + emitter.emit('resolve') + await expect(resPromise).to.eventually.be.rejectedWith('Error: attempt to yield across a C-call boundary') + + expect(await state.doString('return 42')).to.equal(42) + }) + + it('a thread timeout inside a JS callback still surfaces as an error when minified', async () => { + const state = await getMinifiedState({ limits: { functionTimeout: 10 } }) + state.set('promise', Promise.resolve()) + const thread = state.newThread() + thread.loadString(` + promise:next(function () + while true do + -- nothing + end + end):await() + `) + await expect(thread.run(0, { timeout: 5 })).to.eventually.be.rejectedWith('thread timeout exceeded') + + expect(await state.doString('return 42')).to.equal(42) + }) +}) diff --git a/utils/build-wasm.sh b/utils/build-wasm.sh index c234f59..921f1d5 100755 --- a/utils/build-wasm.sh +++ b/utils/build-wasm.sh @@ -4,8 +4,8 @@ mkdir -p ../build LUA_SRC=$(ls ../lua/*.c | grep -v "luac.c" | grep -v "lua.c" | tr "\n" " ") -# Do not add --closure here: isEmscriptenUnwind identifies in-flight longjmps by class name, so -# mangling them would silently turn every unwind into a Lua error. +# Do not add --closure here: it renames properties, which would strip the brand the JS build puts on +# the glue's longjmp unwind classes (see rolldown.config.ts) and turn every unwind into a Lua error. extension="" if [ "$1" == "dev" ]; then From 779ab407f15a9431f327ea58714bf126dee64a57 Mon Sep 17 00:00:00 2001 From: Gabriel Francisco Date: Tue, 28 Jul 2026 22:48:12 -0300 Subject: [PATCH 44/83] tests ovehaul --- bin/wasmoon | 8 +- package.json | 1 + src/state.ts | 34 +++- src/type-extensions/error.ts | 4 + test/api.test.js | 213 +++++++++++++++++++ test/browser.test.js | 1 + test/cli.test.js | 192 ++++++++++++++++++ test/errors.test.js | 90 ++++++++- test/filesystem.test.js | 39 +++- test/initialization.test.js | 23 ++- test/limits.test.js | 10 +- test/node.test.js | 382 ----------------------------------- test/nodefs.test.js | 136 ++++++++----- test/promises.test.js | 36 ++-- test/state.test.js | 186 ++++++++--------- test/stdio.test.js | 112 ++++++++++ test/utils.js | 7 +- 17 files changed, 893 insertions(+), 581 deletions(-) create mode 100644 test/api.test.js create mode 100644 test/cli.test.js delete mode 100644 test/node.test.js create mode 100644 test/stdio.test.js diff --git a/bin/wasmoon b/bin/wasmoon index 3479141..b80cf70 100755 --- a/bin/wasmoon +++ b/bin/wasmoon @@ -230,6 +230,10 @@ if (warnings) { lua.module.lua_warning(state.address, '@on', 0) } +// Decorated as a value so `#arg` and `ipairs(arg)` behave like the standalone interpreter, and +// set before -l and -e run, as it does, so those can read it. +state.set('arg', decorate(scriptArgs, { as: 'value' })) + for (const module of includeModules) { let [global, mod] = module.split('=') if (!mod) { @@ -243,10 +247,6 @@ for (const snippet of executeSnippets) { await state.doString(snippet) } -// A real Lua table rather than a JS proxy, so `#arg` and `ipairs(arg)` behave like the -// standalone interpreter. -state.set('arg', decorate(scriptArgs, { as: 'value' })) - const isTTY = process.stdin.isTTY const hasProgram = Boolean(scriptFile) || executeSnippets.length > 0 diff --git a/package.json b/package.json index c7e0849..f416ecb 100755 --- a/package.json +++ b/package.json @@ -24,6 +24,7 @@ "build:wasm": "node utils/build-wasm", "start": "rolldown -w -c", "bench": "npm run build && node bench/index.js", + "pretest": "npm run build", "test": "mocha --parallel --exit --require ./test/boot.js test/*.test.js", "luatests": "node --experimental-import-meta-resolve test/luatests.js", "build": "rm -rf dist && rolldown -c && tsc -d --emitDeclarationOnly --rootDir src --declarationDir dist", diff --git a/src/state.ts b/src/state.ts index c7abc93..a55c6d9 100755 --- a/src/state.ts +++ b/src/state.ts @@ -30,6 +30,23 @@ export interface LuaMemory { max: number | undefined } +/** + * A more specific handler has to be consulted before a more general one. The values themselves + * cannot be renumbered: they are the scale {@link LuaState.registerTypeExtension} exposes, so + * anything a user registered against them would move too. + */ +const BUILT_IN_PRIORITY = { + table: 0, + function: 0, + promise: 1, + proxy: 3, + /** Beats proxy, which would otherwise claim every Error before this one is consulted. */ + error: 3.5, + /** Lets a custom userdata be exposed without its methods coming along. */ + userdata: 4, + null: 5, +} as const + interface CreatedState { address: LuaAddress memory?: LuaMemory @@ -117,31 +134,28 @@ export default class LuaState extends Thread { } // Generic handlers - These may be required to be registered for additional types. - this.registerTypeExtension(0, createTableType(this)) - this.registerTypeExtension(0, createFunctionType(this, limits?.functionTimeout)) + this.registerTypeExtension(BUILT_IN_PRIORITY.table, createTableType(this)) + this.registerTypeExtension(BUILT_IN_PRIORITY.function, createFunctionType(this, limits?.functionTimeout)) // Contains the :await functionality. - this.registerTypeExtension(1, createPromiseType(this, inject)) + this.registerTypeExtension(BUILT_IN_PRIORITY.promise, createPromiseType(this, inject)) if (inject) { - // Should be higher priority than table since that catches generic objects along - // with userdata so it doesn't end up a userdata type. - this.registerTypeExtension(5, createNullType(this)) + this.registerTypeExtension(BUILT_IN_PRIORITY.null, createNullType(this)) } if (errors) { - this.registerTypeExtension(1, createErrorType(this, inject)) + this.registerTypeExtension(BUILT_IN_PRIORITY.error, createErrorType(this, inject)) } if (objects === 'proxy') { // This extension only really overrides tables and arrays. // When a function is looked up in one of it's tables it's bound and then // handled by the function type extension. - this.registerTypeExtension(3, createProxyType(this)) + this.registerTypeExtension(BUILT_IN_PRIORITY.proxy, createProxyType(this)) } - // Higher priority than proxied objects to allow custom user data without exposing methods. - this.registerTypeExtension(4, createUserdataType(this)) + this.registerTypeExtension(BUILT_IN_PRIORITY.userdata, createUserdataType(this)) const libraryMask = resolveLibraryMask(libs) if (libraryMask !== 0) { diff --git a/src/type-extensions/error.ts b/src/type-extensions/error.ts index d376312..770ea15 100644 --- a/src/type-extensions/error.ts +++ b/src/type-extensions/error.ts @@ -60,6 +60,10 @@ class ErrorTypeExtension extends TypeExtension { if (!(decoration.target instanceof Error)) { return false } + // An explicit `as` names a representation this extension does not provide. + if (decoration.options.as !== undefined) { + return false + } return super.pushValue(thread, decoration) } diff --git a/test/api.test.js b/test/api.test.js new file mode 100644 index 0000000..6d7ba51 --- /dev/null +++ b/test/api.test.js @@ -0,0 +1,213 @@ +import { expect } from 'chai' +import { LuaMultiReturn, LuaRawResult, LuaTypeExtension, decorate } from '../dist/index.js' +import { getLua, getState } from './utils.js' + +describe('MultiReturn', () => { + it('should push several lua values from one JS function', async () => { + using state = await getState() + state.set('divide', (a, b) => LuaMultiReturn.of(Math.floor(a / b), a % b)) + + const result = await state.doString('local q, r = divide(7, 2) return ("%d,%d"):format(q, r)') + + expect(result).to.be.equal('3,1') + }) + + it('should report its length to lua', async () => { + using state = await getState() + state.set('three', () => LuaMultiReturn.of('a', 'b', 'c')) + + expect(await state.doString('return select("#", three())')).to.be.equal(3) + }) + + it('should be distinguishable from a plain array, which stays one table', async () => { + using state = await getState({ objects: 'copy' }) + state.set('plain', () => ['a', 'b', 'c']) + + expect(await state.doString('return select("#", plain())')).to.be.equal(1) + expect(await state.doString('return type(plain())')).to.be.equal('table') + }) + + it('should push nothing for an empty one', async () => { + using state = await getState() + state.set('none', () => LuaMultiReturn.of()) + + expect(await state.doString('return select("#", none())')).to.be.equal(0) + }) +}) + +describe('RawResult', () => { + it('should hand back values the function pushed itself', async () => { + using state = await getState() + state.set( + 'raw', + decorate( + (thread) => { + thread.pushValue('a') + thread.pushValue('b') + return new LuaRawResult(2) + }, + { receiveThread: true }, + ), + ) + + expect(await state.doString('local x, y = raw() return x .. y')).to.be.equal('ab') + expect(await state.doString('return select("#", raw())')).to.be.equal(2) + }) +}) + +describe('Decoration options', () => { + it('self should bind the receiver and drop it from the arguments', async () => { + using state = await getState() + const counter = { + n: 41, + bump(by) { + this.n += by ?? 1 + return this.n + }, + } + state.set('bump', decorate(counter.bump, { self: counter })) + + expect(await state.doString('return bump()')).to.be.equal(42) + expect(await state.doString('return bump(8)')).to.be.equal(50) + expect(counter.n).to.be.equal(50) + }) + + it('receiveThread should pass the calling thread as the first argument', async () => { + using state = await getState() + state.set( + 'grab', + decorate((thread, ...args) => `${typeof thread.address}:${args.join(',')}`, { receiveThread: true }), + ) + + expect(await state.doString('return grab("a", "b")')).to.be.equal('number:a,b') + }) + + it('receiveArgsQuantity should pass the count instead of the arguments', async () => { + using state = await getState() + state.set( + 'count', + decorate((quantity) => quantity, { receiveArgsQuantity: true }), + ) + + expect(await state.doString('return count(1, 2, 3)')).to.be.equal(3) + expect(await state.doString('return count()')).to.be.equal(0) + }) +}) + +describe('Custom type extensions', () => { + class Point { + constructor(x) { + this.x = x + } + } + + // A dedicated metatable name is the thing no built in provides, and what proves the custom + // extension ran rather than the userdata one. + class PointExtension extends LuaTypeExtension { + constructor(state) { + super(state, 'js_point') + this.gcPointer = this.createGcFunction() + + if (state.lua.luaL_newmetatable(state.address, this.name)) { + const metatableIndex = state.lua.lua_gettop(state.address) + state.lua.lua_pushcclosure(state.address, this.gcPointer, 0) + state.lua.lua_setfield(state.address, metatableIndex, '__gc') + state.pushValue((point) => `Point(${point.x})`) + state.lua.lua_setfield(state.address, metatableIndex, '__tostring') + } + state.lua.lua_pop(state.address, 1) + } + + close() { + this.state.lua._emscripten.removeFunction(this.gcPointer) + } + + pushValue(thread, decoration) { + return decoration.target instanceof Point ? super.pushValue(thread, decoration) : false + } + } + + it('should take priority over the built in handling and round trip', async () => { + using state = await getState() + state.registerTypeExtension(6, new PointExtension(state)) + const point = new Point(9) + state.set('pt', point) + + expect(await state.doString('return type(pt)')).to.be.equal('userdata') + expect(await state.doString('return tostring(pt)')).to.be.equal('Point(9)') + expect(state.get('pt')).to.be.equal(point) + }) + + it('should leave values it refuses to the built in handling', async () => { + using state = await getState() + state.registerTypeExtension(6, new PointExtension(state)) + state.set('other', { x: 1 }) + + expect(await state.doString('return other.x')).to.be.equal(1) + }) +}) + +describe('Thread lifecycle', () => { + it('resetThread should let a finished thread be loaded again', async () => { + using state = await getState() + const thread = state.newThread() + thread.loadString('return 1') + expect(await thread.run()).to.be.eql([1]) + + thread.resetThread() + thread.loadString('return 42') + + expect(await thread.run()).to.be.eql([42]) + }) + + it('resetThread should surface the error that stopped the thread', async () => { + // lua_resetthread reports the status the thread died with. + using state = await getState() + const thread = state.newThread() + thread.loadString('error("boom")') + await expect(thread.run()).to.eventually.be.rejectedWith('boom') + + expect(() => thread.resetThread()).to.throw('boom') + }) + + it('loadString name should set the chunk name used in errors', async () => { + using state = await getState() + const thread = state.newThread() + thread.loadString('error("named")', { name: '@mychunk.lua' }) + + await expect(thread.run()).to.eventually.be.rejectedWith('mychunk.lua:1: named') + }) + + it('onClose should fire once when the state closes', async () => { + const lua = await getLua() + const state = lua.createState() + let closed = 0 + state.onClose(() => closed++) + + state.close() + state.close() + + expect(closed).to.be.equal(1) + }) + + it('indexToString should render a value the way lua would', async () => { + using state = await getState() + state.pushValue(12) + state.pushValue('hi') + + expect(state.indexToString(-2)).to.be.equal('12') + expect(state.indexToString(-1)).to.be.equal('hi') + + state.pop(2) + }) + + it('indexToString should call __tostring when there is one', async () => { + using state = await getState() + state.set('thing', decorate({}, { metatable: { __tostring: () => 'rendered' } })) + state.lua.lua_getglobal(state.address, 'thing') + + expect(state.indexToString(-1)).to.be.equal('rendered') + + state.pop() + }) +}) diff --git a/test/browser.test.js b/test/browser.test.js index 9bda74e..aa28806 100644 --- a/test/browser.test.js +++ b/test/browser.test.js @@ -274,6 +274,7 @@ describe('Browser environment', () => { page.assertNoErrors() expect(result).to.be.eql({ ok: 7 }) + expect(requested).to.include(`http://127.0.0.1:${port}/glue.wasm`) expectNoExternalRequests() } finally { await page.close() diff --git a/test/cli.test.js b/test/cli.test.js new file mode 100644 index 0000000..6b491f6 --- /dev/null +++ b/test/cli.test.js @@ -0,0 +1,192 @@ +import { mkdtempSync, writeFileSync, rmSync } from 'node:fs' +import { join } from 'node:path' +import { tmpdir } from 'node:os' +import { spawn } from 'node:child_process' +import { fileURLToPath } from 'node:url' +import { expect } from 'chai' +import pkg from '../package.json' with { type: 'json' } + +// Absolute, so a test can hand the child a cwd of its own. +const CLI = fileURLToPath(new URL('../bin/wasmoon', import.meta.url)) + +// stdin defaults to closed, matching a piped invocation with nothing to read. Never a TTY here, +// so the REPL branch and `-i` stay out of reach. +const runCli = (args, { input, ...options } = {}) => { + return new Promise((resolve, reject) => { + const child = spawn(process.execPath, [CLI, ...args], { + stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'], + ...options, + }) + let stdout = '' + let stderr = '' + child.stdout.on('data', (chunk) => (stdout += chunk)) + child.stderr.on('data', (chunk) => (stderr += chunk)) + child.on('error', reject) + child.on('close', (code) => resolve({ code, stdout, stderr })) + if (input !== undefined) { + child.stdin.end(input) + } + }) +} + +describe('CLI', function () { + this.timeout(30_000) + + let tempDir + + beforeEach(() => { + tempDir = mkdtempSync(join(tmpdir(), 'wasmoon-cli-')) + }) + + afterEach(() => { + rmSync(tempDir, { recursive: true, force: true }) + }) + + describe('scripts and snippets', () => { + // Covers the single snippet case too, which is why there is no separate test for it. + it('should run several -e snippets in order', async () => { + const { code, stdout, stderr } = await runCli(['-e', 'print("first")', '-e', 'print("second")']) + + expect(stderr).to.be.empty + expect(code).to.be.equal(0) + expect(stdout).to.be.equal('first\nsecond\n') + }) + + it('should run a script file', async () => { + const script = join(tempDir, 'hello.lua') + writeFileSync(script, 'print("from file")') + + const { code, stdout } = await runCli([script]) + + expect(code).to.be.equal(0) + expect(stdout).to.be.equal('from file\n') + }) + + it('should run a script piped to stdin', async () => { + const { code, stdout } = await runCli([], { input: 'print("from bare stdin")\n' }) + + expect(code).to.be.equal(0) + expect(stdout).to.be.equal('from bare stdin\n') + }) + + it('should run a script piped to stdin when given -', async () => { + const { code, stdout } = await runCli(['-'], { input: 'print("from dash")\n' }) + + expect(code).to.be.equal(0) + expect(stdout).to.be.equal('from dash\n') + }) + }) + + describe('arg table', () => { + it('should expose arg as a lua table to a script', async () => { + const script = join(tempDir, 'args.lua') + writeFileSync(script, 'print(type(arg), #arg, arg[1], arg[2], table.concat(arg, "+"))') + + const { code, stdout, stderr } = await runCli([script, 'first', 'second']) + + expect(stderr).to.be.empty + expect(code).to.be.equal(0) + expect(stdout.trim()).to.be.equal('table\t2\tfirst\tsecond\tfirst+second') + }) + + // arg used to be built after the -e loop ran, so a snippet saw a nil global. + it('should expose arg to a -e snippet', async () => { + const { code, stdout, stderr } = await runCli(['-e', 'print(type(arg), #arg)']) + + expect(stderr).to.be.empty + expect(code).to.be.equal(0) + expect(stdout.trim()).to.be.equal('table\t0') + }) + + it('should pass arguments after -- through to arg', async () => { + const { code, stdout, stderr } = await runCli(['-e', 'print(arg[1])', '--', '--notaflag']) + + expect(stderr).to.be.empty + expect(code).to.be.equal(0) + expect(stdout.trim()).to.be.equal('--notaflag') + }) + }) + + describe('options', () => { + it('-v should report both versions', async () => { + const { code, stdout } = await runCli(['-v']) + + expect(code).to.be.equal(0) + expect(stdout.trim()).to.match(/^wasmoon \S+ \(Lua [\d.]+\)$/) + expect(stdout).to.include(`wasmoon ${pkg.version} `) + }) + + it('-l should require a module into a global of the same name', async () => { + writeFileSync(join(tempDir, 'mymod.lua'), 'return { v = 5 }') + + const { code, stdout } = await runCli(['-l', 'mymod', '-e', 'print(mymod.v)'], { cwd: tempDir }) + + expect(code).to.be.equal(0) + expect(stdout.trim()).to.be.equal('5') + }) + + it('-l g=mod should require a module into a renamed global', async () => { + writeFileSync(join(tempDir, 'mymod.lua'), 'return { v = 5 }') + + const { code, stdout } = await runCli(['-l', 'g=mymod', '-e', 'print(g.v, mymod)'], { cwd: tempDir }) + + expect(code).to.be.equal(0) + expect(stdout.trim()).to.be.equal('5\tnil') + }) + + it('-E should hide the host environment', async () => { + const env = { ...process.env, WASMOON_CLI_TEST: 'secret' } + + const [withEnv, without] = await Promise.all([ + runCli(['-e', 'print(os.getenv("WASMOON_CLI_TEST"))'], { env }), + runCli(['-E', '-e', 'print(os.getenv("WASMOON_CLI_TEST"))'], { env }), + ]) + + expect(withEnv.stdout.trim()).to.be.equal('secret') + expect(without.stdout.trim()).to.be.equal('nil') + }) + + it('an unrecognized option should print usage and fail', async () => { + const { code, stdout } = await runCli(['-Z']) + + expect(code).to.be.equal(1) + expect(stdout).to.include(`unrecognized option: '-Z'`) + expect(stdout).to.include('usage: wasmoon') + }) + + it('a missing argument after -e should fail', async () => { + const { code, stderr } = await runCli(['-e']) + + expect(code).to.be.equal(1) + expect(stderr).to.include('Missing argument after -e') + }) + }) + + describe('stdin', () => { + it('should read piped input from within a script', async () => { + const { code, stdout, stderr } = await runCli(['-e', 'print(io.read("l")) print(io.read("l")) print(io.read("l") == nil)'], { + input: 'olá mundo\nsegunda linha\n', + }) + + expect(stderr).to.be.empty + expect(code).to.be.equal(0) + expect(stdout).to.be.equal('olá mundo\nsegunda linha\ntrue\n') + }) + + it('should not add a line break to input that does not end with one', async () => { + const { code, stdout, stderr } = await runCli(['-e', 'print(#io.read("a"))'], { input: 'abc' }) + + expect(stderr).to.be.empty + expect(code).to.be.equal(0) + expect(stdout).to.be.equal('3\n') + }) + + it('should not run piped input as a script when -e is given', async () => { + const { code, stdout, stderr } = await runCli(['-e', 'print("from -e")'], { input: 'this is not lua code\n' }) + + expect(stderr).to.be.empty + expect(code).to.be.equal(0) + expect(stdout).to.be.equal('from -e\n') + }) + }) +}) diff --git a/test/errors.test.js b/test/errors.test.js index dc247dc..f82b69c 100644 --- a/test/errors.test.js +++ b/test/errors.test.js @@ -1,10 +1,10 @@ -import { LuaRuntime, LuaError } from '../dist/index.js' +import { LuaRuntime, LuaError, decorate } from '../dist/index.js' import { expect } from 'chai' import { getState } from './utils.js' describe('LuaError', () => { it('keeps the raised value, message and traceback apart', async () => { - const state = await getState() + using state = await getState() try { await state.doString(`error({ code = 7 })`) @@ -19,7 +19,7 @@ describe('LuaError', () => { }) it('a JS error thrown through Lua keeps its own stack', async () => { - const state = await getState() + using state = await getState() const thrown = new Error('from js') state.set('boom', () => { throw thrown @@ -35,9 +35,89 @@ describe('LuaError', () => { }) }) +describe('errors option', () => { + const setThrow = (state) => + state.set('boom', () => { + throw new Error('kaboom') + }) + const catchIt = (expression) => `local ok, err = pcall(boom) return ${expression}` + + // The "Error: " prefix is the tell: js_error renders the bare message, the proxy layer + // leaves tostring to Error.prototype. + const matrix = [ + ['off by default', undefined, 'Error: kaboom'], + ['on when asked for', { errors: true }, 'kaboom'], + // errors used to sit below proxy, so opting in while leaving objects alone did nothing. + ['on when asked for even though objects is proxy', { objects: 'proxy', errors: true }, 'kaboom'], + ['on by default when objects is copy', { objects: 'copy' }, 'kaboom'], + ] + + for (const [name, options, expected] of matrix) { + it(`should be ${name}`, async () => { + using state = await getState(options) + setThrow(state) + + expect(await state.doString(catchIt('tostring(err)'))).to.be.equal(expected) + }) + } + + it('should leave the real properties reachable when off', async () => { + using state = await getState() + setThrow(state) + + expect(await state.doString(catchIt('type(err.stack)'))).to.be.equal('string') + }) + + it('should expose the message when on', async () => { + using state = await getState({ errors: true }) + setThrow(state) + + expect(await state.doString(catchIt('err.message'))).to.be.equal('kaboom') + }) + + it('should be overridable to off when objects is copy', async () => { + using state = await getState({ objects: 'copy', errors: false }) + setThrow(state) + + expect(await state.doString(catchIt('type(err)'))).to.be.equal('table') + }) + + // Claiming every Error on type alone would swallow these, the way proxy used to swallow it. + describe('should defer to an explicit decoration', () => { + const cases = [ + ['userdata', 'userdata', 'js_userdata'], + ['proxy', 'userdata', 'Error: kaboom'], + ['value', 'table', 'table:'], + ] + + for (const [as, luaType, rendering] of cases) { + it(`as: '${as}'`, async () => { + using state = await getState({ errors: true }) + state.set('decorated', decorate(new Error('kaboom'), { as })) + + expect(await state.doString('return type(decorated)')).to.be.equal(luaType) + expect(await state.doString('return tostring(decorated)')).to.include(rendering) + }) + } + }) + + it('should expose an Error constructor to lua when injecting', async () => { + using state = await getState({ errors: true }) + + expect(await state.doString('return tostring(Error.create("made in lua"))')).to.be.equal('made in lua') + expect(await state.doString('return Error.create("made in lua").message')).to.be.equal('made in lua') + }) + + it('should not expose the Error constructor when the extension is off', async () => { + using state = await getState() + + expect(await state.doString('return type(Error)')).to.be.equal('nil') + }) +}) + describe('Unrepresentable values', () => { it('getValue throws instead of returning an opaque handle', async () => { - const state = await getState() + using state = await getState() const thread = state.newThread() thread.lua.lua_newuserdatauv(thread.address, 4, 0) @@ -45,7 +125,7 @@ describe('Unrepresentable values', () => { }) it('the address is still reachable through getPointer', async () => { - const state = await getState() + using state = await getState() const thread = state.newThread() thread.lua.lua_newuserdatauv(thread.address, 4, 0) diff --git a/test/filesystem.test.js b/test/filesystem.test.js index 09a5f16..3846d72 100644 --- a/test/filesystem.test.js +++ b/test/filesystem.test.js @@ -33,9 +33,9 @@ describe('Filesystem', () => { }) it('require a file which is not mounted should throw', async () => { - const state = await getState() + using state = await getState() - await expect(state.doString('require("nothing")')).to.eventually.be.rejected + await expect(state.doString('require("nothing")')).to.eventually.be.rejectedWith(/module 'nothing' not found/) }) it('mount a file and run it should succeed', async () => { @@ -49,9 +49,40 @@ describe('Filesystem', () => { }) it('run a file which is not mounted should throw', async () => { - const state = await getState() + using state = await getState() - await expect(state.doFile('init.lua')).to.eventually.be.rejected + await expect(state.doFile('init.lua')).to.eventually.be.rejectedWith(/cannot open init\.lua/) + }) + + it('mount a file with binary content should succeed', async () => { + const lua = await getLua() + using state = lua.createState() + + lua.mountFile('binary.lua', new Uint8Array([114, 101, 116, 117, 114, 110, 32, 52, 50])) // "return 42" + + expect(await state.doString('return dofile("binary.lua")')).to.be.equal(42) + }) + + it('doFileSync should run a mounted file synchronously', async () => { + const lua = await getLua() + lua.mountFile('sync.lua', 'return 5 * 5') + using state = lua.createState() + + expect(state.doFileSync('sync.lua')).to.be.equal(25) + }) + + it('filesystem should expose the shared emscripten FS', async () => { + const lua = await getLua() + lua.mountFile('fs-probe.lua', 'return 1') + + expect(lua.filesystem.analyzePath('/fs-probe.lua').exists).to.be.true + }) + + it('path should expose the emscripten path helpers', async () => { + const lua = await getLua() + + expect(lua.path.dirname('/a/b/c.lua')).to.be.equal('/a/b') + expect(lua.path.basename('/a/b/c.lua')).to.be.equal('c.lua') }) it('mount a file with a large content should succeed', async () => { diff --git a/test/initialization.test.js b/test/initialization.test.js index ab8f214..4aca780 100644 --- a/test/initialization.test.js +++ b/test/initialization.test.js @@ -4,25 +4,36 @@ import { expect } from 'chai' describe('Initialization', () => { it('create state should succeed', async () => { const lua = await LuaRuntime.load() - lua.createState() + using state = lua.createState() + + expect(state.isClosed()).to.be.false + expect(state.address).to.be.greaterThan(0) }) - it('create multiple states should succeed', async () => { + it('create multiple states should keep their globals independent', async () => { const lua = await LuaRuntime.load() - const state1 = lua.createState() - const state2 = lua.createState() + using state1 = lua.createState() + using state2 = lua.createState() + + await state1.doString('x = 10') + await state2.doString('x = 20') expect(state1.address).to.not.be.equal(state2.address) + expect(await state1.doString('return x')).to.be.equal(10) + expect(await state2.doString('return x')).to.be.equal(20) }) - it('create state with options should succeed', async () => { + it('create state with options should apply them', async () => { const lua = await LuaRuntime.load() - lua.createState({ + using state = lua.createState({ objects: 'proxy', inject: true, libs: true, memory: { trace: true }, }) + + expect(state.memory.used).to.be.greaterThan(0) + expect(await state.doString('return type(null)')).to.be.equal('userdata') }) it('create with environment variables should succeed', async () => { diff --git a/test/limits.test.js b/test/limits.test.js index 6a9323f..0fb0d32 100644 --- a/test/limits.test.js +++ b/test/limits.test.js @@ -7,28 +7,28 @@ describe('Run limits', () => { it('timeout interrupts a tight loop', async function () { this.timeout(20_000) - const state = await getState() + using state = await getState() await expect(state.doString(busyLoop, { timeout: 20 })).to.eventually.be.rejectedWith(LuaTimeoutError) }) it('maxInstructions interrupts a tight loop', async function () { this.timeout(20_000) - const state = await getState() + using state = await getState() await expect(state.doString(busyLoop, { maxInstructions: 5_000 })).to.eventually.be.rejectedWith(LuaInstructionLimitError) }) it('an already aborted signal stops the run', async function () { this.timeout(20_000) - const state = await getState() + using state = await getState() await expect(state.doString(busyLoop, { signal: AbortSignal.abort() })).to.eventually.be.rejectedWith(LuaAbortError) }) it('a signal aborted while parked on a promise stops the run', async function () { this.timeout(20_000) - const state = await getState() + using state = await getState() state.set('sleep', (ms) => new Promise((resolve) => setTimeout(resolve, ms))) const controller = new AbortController() setTimeout(() => controller.abort(), 5) @@ -65,7 +65,7 @@ describe('Run limits', () => { }) it('limits are restored after a scoped run', async () => { - const state = await getState() + using state = await getState() state.setLimits({ maxInstructions: 999 }) await state.doString('return 1', { maxInstructions: 10_000 }) diff --git a/test/node.test.js b/test/node.test.js deleted file mode 100644 index c581084..0000000 --- a/test/node.test.js +++ /dev/null @@ -1,382 +0,0 @@ -import { readFileSync, writeFileSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs' -import { join } from 'node:path' -import { tmpdir } from 'node:os' -import { spawn } from 'node:child_process' -import { expect } from 'chai' -import { LuaRuntime } from '../dist/index.js' - -// stdin is closed by default, as it would be for a redirected or piped invocation with nothing -// to read. -const runCli = (args, input) => { - return new Promise((resolve, reject) => { - const child = spawn(process.execPath, ['bin/wasmoon', ...args], { - stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'], - }) - let stdout = '' - let stderr = '' - child.stdout.on('data', (chunk) => (stdout += chunk)) - child.stderr.on('data', (chunk) => (stderr += chunk)) - child.on('error', reject) - child.on('close', (code) => resolve({ code, stdout, stderr })) - if (input !== undefined) { - child.stdin.end(input) - } - }) -} - -// Collects everything the given script writes to the chosen stream. -const collectOutput = async (stream, script, opts = {}) => { - const output = [] - const lua = await LuaRuntime.load({ ...opts, [stream]: (content) => output.push(content) }) - await lua.createState().doString(script) - return output -} - -// Feeds one chunk per read, and then the empty string that stands for EOF. -const stdinFrom = (chunks) => { - let index = 0 - return () => chunks[index++] ?? '' -} - -describe('Node environment', () => { - it('load Lua engine in node should succeed', async () => { - const lua = await LuaRuntime.load() - const state = lua.createState() - const result = await state.doString('return 1 + 1') - expect(result).to.be.equal(2) - }) - - it('access environment variables should succeed', async () => { - const env = { MY_TEST_VAR: 'hello_from_node' } - const lua = await LuaRuntime.load({ env }) - const state = lua.createState() - const result = await state.doString('return os.getenv("MY_TEST_VAR")') - expect(result).to.be.equal('hello_from_node') - }) - - it('custom stdout should succeed', async () => { - const output = await collectOutput('stdout', 'print("hello from node")') - expect(output.join('')).to.include('hello from node') - }) - - it('custom stderr should succeed', async () => { - const errors = await collectOutput('stderr', 'io.stderr:write("error output\\n")') - expect(errors.join('')).to.include('error output') - }) - - it('mount file and require in node should succeed', async () => { - const lua = await LuaRuntime.load() - lua.mountFile('nodetest.lua', 'return { value = 99 }') - const state = lua.createState({ inject: true }) - const result = await state.doString('local m = require("nodetest"); return m.value') - expect(result).to.be.equal(99) - }) - - it('mount file with binary content should succeed', async () => { - const lua = await LuaRuntime.load() - const content = new Uint8Array([114, 101, 116, 117, 114, 110, 32, 52, 50]) // "return 42" - lua.mountFile('binary.lua', content) - const state = lua.createState() - const result = await state.doString('return dofile("binary.lua")') - expect(result).to.be.equal(42) - }) - - it('mount file in nested directories should succeed', async () => { - const lua = await LuaRuntime.load() - lua.mountFile('a/b/c/deep.lua', 'return "deep"') - const state = lua.createState() - const result = await state.doString('return require("a/b/c/deep")') - expect(result).to.be.equal('deep') - }) - - it('create multiple independent states should succeed', async () => { - const lua = await LuaRuntime.load() - const state1 = lua.createState() - const state2 = lua.createState() - - await state1.doString('x = 10') - await state2.doString('x = 20') - - const val1 = await state1.doString('return x') - const val2 = await state2.doString('return x') - - expect(val1).to.be.equal(10) - expect(val2).to.be.equal(20) - }) - - it('pass complex JS objects to Lua should succeed', async () => { - const state = (await LuaRuntime.load()).createState({ inject: true }) - state.set('data', { - name: 'test', - nested: { value: 42 }, - items: [1, 2, 3], - }) - const result = await state.doString('return data.nested.value') - expect(result).to.be.equal(42) - }) - - it('call JS async functions from Lua should succeed', async () => { - const state = (await LuaRuntime.load()).createState({ inject: true }) - state.set('fetchData', async () => { - return 'async result' - }) - const result = await state.doString('return fetchData():await()') - expect(result).to.be.equal('async result') - }) - - it('use NODEFS to read host files should succeed', async () => { - const tempDir = join(tmpdir(), `wasmoon-test-${Date.now()}`) - mkdirSync(tempDir, { recursive: true }) - const testFile = join(tempDir, 'test.txt') - writeFileSync(testFile, 'hello from host') - - try { - const lua = await LuaRuntime.load({ fs: 'node' }) - const state = lua.createState() - const result = await state.doString(` - local f = io.open("${testFile.replace(/\\/g, '/')}", "r") - local content = f:read("*a") - f:close() - return content - `) - expect(result).to.be.equal('hello from host') - } finally { - rmSync(tempDir, { recursive: true, force: true }) - } - }) - - it('use NODEFS to write and read back files should succeed', async () => { - const tempDir = join(tmpdir(), `wasmoon-test-${Date.now()}`) - mkdirSync(tempDir, { recursive: true }) - const testFile = join(tempDir, 'output.txt') - - try { - const lua = await LuaRuntime.load({ fs: 'node' }) - const state = lua.createState() - await state.doString(` - local f = io.open("${testFile.replace(/\\/g, '/')}", "w") - f:write("written from lua") - f:close() - `) - const content = readFileSync(testFile, 'utf8') - expect(content).to.be.equal('written from lua') - } finally { - rmSync(tempDir, { recursive: true, force: true }) - } - }) - - it('NODEFS cwd should match process.cwd', async () => { - const lua = await LuaRuntime.load({ fs: 'node' }) - const state = lua.createState() - // Write a temp file in the CWD and verify it can be read - const markerFile = join(process.cwd(), `.wasmoon-cwd-test-${Date.now()}.tmp`) - writeFileSync(markerFile, 'cwd-marker') - try { - const result = await state.doString(` - local f = io.open("${markerFile.replace(/\\/g, '/')}", "r") - if not f then return nil end - local content = f:read("*a") - f:close() - return content - `) - expect(result).to.be.equal('cwd-marker') - } finally { - rmSync(markerFile, { force: true }) - } - }) - - it('NODEFS with fsMountPaths should only mount specified paths', async () => { - const tempDir = join(tmpdir(), `wasmoon-mount-test-${Date.now()}`) - mkdirSync(tempDir, { recursive: true }) - const testFile = join(tempDir, 'specific.txt') - writeFileSync(testFile, 'mounted content') - - try { - const lua = await LuaRuntime.load({ fs: 'node', fsMountPaths: [tmpdir()] }) - const state = lua.createState() - const result = await state.doString(` - local f = io.open("${testFile.replace(/\\/g, '/')}", "r") - if not f then return nil end - local content = f:read("*a") - f:close() - return content - `) - expect(result).to.be.equal('mounted content') - } finally { - rmSync(tempDir, { recursive: true, force: true }) - } - }) - - it('NODEFS opening nonexistent file should return nil', async () => { - const lua = await LuaRuntime.load({ fs: 'node' }) - const state = lua.createState() - const result = await state.doString(` - local f, err = io.open("/tmp/wasmoon_nonexistent_file_${Date.now()}.txt", "r") - return f == nil and type(err) == "string" - `) - expect(result).to.be.true - }) - - it('mountFile and NODEFS should coexist', async () => { - const tempDir = join(tmpdir(), `wasmoon-coexist-${Date.now()}`) - mkdirSync(tempDir, { recursive: true }) - const hostFile = join(tempDir, 'host.txt') - writeFileSync(hostFile, 'from host') - - try { - const lua = await LuaRuntime.load({ fs: 'node' }) - lua.mountFile('virtual.lua', 'return "from virtual"') - const state = lua.createState() - - const hostContent = await state.doString(` - local f = io.open("${hostFile.replace(/\\/g, '/')}", "r") - local content = f:read("*a") - f:close() - return content - `) - const virtualContent = await state.doString('return dofile("virtual.lua")') - - expect(hostContent).to.be.equal('from host') - expect(virtualContent).to.be.equal('from virtual') - } finally { - rmSync(tempDir, { recursive: true, force: true }) - rmSync('virtual.lua', { force: true }) - } - }) - - it('standard libraries are available should succeed', async () => { - const state = (await LuaRuntime.load()).createState() - const result = await state.doString(` - local checks = {} - checks[1] = type(string.format) == "function" - checks[2] = type(table.insert) == "function" - checks[3] = type(math.floor) == "function" - checks[4] = type(os.time) == "function" - checks[5] = type(coroutine.create) == "function" - for _, v in ipairs(checks) do - if not v then return false end - end - return true - `) - expect(result).to.be.true - }) - - it('error handling with pcall should succeed', async () => { - const state = (await LuaRuntime.load()).createState() - const result = await state.doString(` - local ok, err = pcall(function() - error("node test error") - end) - return not ok and string.find(err, "node test error") ~= nil - `) - expect(result).to.be.true - }) - - it('custom stdout should keep multi byte characters intact', async () => { - const output = await collectOutput('stdout', 'print("héllo 日本語 🎉")') - expect(output).to.be.deep.equal(['héllo 日本語 🎉']) - }) - - it('custom stderr should keep multi byte characters intact', async () => { - const errors = await collectOutput('stderr', 'io.stderr:write("erro ✗ 日本\\n")') - expect(errors).to.be.deep.equal(['erro ✗ 日本']) - }) - - it('custom stdout should keep a character that is flushed in the middle intact', async () => { - // The two halves of 日 land in different writes, with the engine handing control back to - // JS in between. - const output = [] - const lua = await LuaRuntime.load({ stdout: (content) => output.push(content) }) - const state = lua.createState() - state.set( - 'pause', - () => - new Promise((resolve) => { - setTimeout(resolve, 0) - }), - ) - await state.doString('io.write("\\xE6") io.flush() pause():await() io.write("\\x97\\xA5 ok\\n")') - expect(output).to.be.deep.equal(['日 ok']) - }) - - it('custom stdout should split on line breaks only', async () => { - const output = await collectOutput('stdout', 'print("first") print("") io.write("a\\rb\\n")') - expect(output).to.be.deep.equal(['first', '', 'a\rb']) - }) - - it('custom stdout should receive flushed output that does not end in a line break', async () => { - const output = await collectOutput('stdout', 'io.write("no newline") io.flush()') - expect(output).to.be.deep.equal(['no newline']) - }) - - it('custom stdout should not split a line that is written in parts', async () => { - const output = await collectOutput('stdout', 'io.write("one ") io.flush() io.write("line\\n")') - expect(output).to.be.deep.equal(['one line']) - }) - - it('custom stdout should handle lines longer than its buffer', async () => { - const output = await collectOutput('stdout', 'print(string.rep("ção ", 1000))') - expect(output).to.be.deep.equal(['ção '.repeat(1000)]) - }) - - it('custom stdin should be read line by line', async () => { - const lua = await LuaRuntime.load({ stdin: stdinFrom(['um\n', 'dois\n']) }) - const result = await lua.createState().doString('return { io.read("l"), io.read("l"), io.read("l") == nil }') - expect(result).to.be.deep.equal(['um', 'dois', true]) - }) - - it('custom stdin should keep multi byte characters intact', async () => { - const lua = await LuaRuntime.load({ stdin: stdinFrom(['héllo 日本語 🎉\n']) }) - const result = await lua.createState().doString('return io.read("l")') - expect(result).to.be.equal('héllo 日本語 🎉') - }) - - it('custom stdin should be read until it signals the end of the input', async () => { - const lua = await LuaRuntime.load({ stdin: stdinFrom(['abc\n', 'déf\n']) }) - const result = await lua.createState().doString('return io.read("a")') - expect(result).to.be.equal('abc\ndéf\n') - }) - - it('cli should read piped input from within a script', async function () { - this.timeout(30_000) - const { code, stdout, stderr } = await runCli( - ['-e', 'print(io.read("l")) print(io.read("l")) print(io.read("l") == nil)'], - 'olá mundo\nsegunda linha\n', - ) - - expect(stderr).to.be.empty - expect(code).to.be.equal(0) - expect(stdout).to.be.equal('olá mundo\nsegunda linha\ntrue\n') - }) - - it('cli should not add a line break to input that does not end with one', async function () { - this.timeout(30_000) - const { code, stdout, stderr } = await runCli(['-e', 'print(#io.read("a"))'], 'abc') - - expect(stderr).to.be.empty - expect(code).to.be.equal(0) - expect(stdout).to.be.equal('3\n') - }) - - it('cli should not run piped input as a script when -e is given', async function () { - this.timeout(30_000) - const { code, stdout, stderr } = await runCli(['-e', 'print("from -e")'], 'this is not lua code\n') - - expect(stderr).to.be.empty - expect(code).to.be.equal(0) - expect(stdout).to.be.equal('from -e\n') - }) - - it('cli should expose arg as a lua table', async function () { - this.timeout(30_000) - const directory = mkdtempSync(join(tmpdir(), 'wasmoon-cli-')) - const script = join(directory, 'args.lua') - writeFileSync(script, 'print(type(arg), #arg, arg[1], arg[2], table.concat(arg, "+"))') - - const { code, stdout, stderr } = await runCli([script, 'first', 'second']) - - expect(stderr).to.be.empty - expect(code).to.be.equal(0) - expect(stdout.trim()).to.be.equal('table\t2\tfirst\tsecond\tfirst+second') - }) -}) diff --git a/test/nodefs.test.js b/test/nodefs.test.js index c83320e..6c85826 100644 --- a/test/nodefs.test.js +++ b/test/nodefs.test.js @@ -1,13 +1,21 @@ -import { readFileSync, writeFileSync, mkdirSync, rmSync, existsSync } from 'node:fs' +import { readFileSync, writeFileSync, mkdirSync, mkdtempSync, rmSync, existsSync } from 'node:fs' import { join } from 'node:path' import { tmpdir } from 'node:os' import { expect } from 'chai' import { LuaRuntime } from '../dist/index.js' - -const createTempDir = () => { - const dir = join(tmpdir(), `wasmoon-nodefs-${Date.now()}-${Math.random().toString(36).slice(2)}`) - mkdirSync(dir, { recursive: true }) - return dir +import { luaPath } from './utils.js' + +const createTempDir = () => mkdtempSync(join(tmpdir(), 'wasmoon-nodefs-')) + +// The sentinel distinguishes "empty" from "not reachable at all", which a bare read cannot. +const readFileFromLua = (state, path) => { + return state.doString(` + local f = io.open("${luaPath(path)}", "r") + if not f then return "BLOCKED" end + local content = f:read("*a") + f:close() + return content + `) } describe('Node FS', () => { @@ -26,12 +34,7 @@ describe('Node FS', () => { const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() - const result = await state.doString(` - local f = io.open("${join(tempDir, 'hello.txt').replace(/\\/g, '/')}", "r") - local content = f:read("*a") - f:close() - return content - `) + const result = await readFileFromLua(state, join(tempDir, 'hello.txt')) expect(result).to.be.equal('hello world') }) @@ -42,7 +45,7 @@ describe('Node FS', () => { const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() await state.doString(` - local f = io.open("${filePath.replace(/\\/g, '/')}", "w") + local f = io.open("${luaPath(filePath)}", "w") f:write("written from lua") f:close() `) @@ -57,7 +60,7 @@ describe('Node FS', () => { const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() await state.doString(` - local f = io.open("${filePath.replace(/\\/g, '/')}", "a") + local f = io.open("${luaPath(filePath)}", "a") f:write("second line\\n") f:close() `) @@ -72,7 +75,7 @@ describe('Node FS', () => { const state = lua.createState() const result = await state.doString(` local lines = {} - for line in io.lines("${join(tempDir, 'lines.txt').replace(/\\/g, '/')}") do + for line in io.lines("${luaPath(join(tempDir, 'lines.txt'))}") do lines[#lines + 1] = line end return table.concat(lines, ",") @@ -88,7 +91,7 @@ describe('Node FS', () => { const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() const result = await state.doString(` - local f = io.open("${join(tempDir, 'binary.dat').replace(/\\/g, '/')}", "rb") + local f = io.open("${luaPath(join(tempDir, 'binary.dat'))}", "rb") local data = f:read("*a") f:close() return #data @@ -103,7 +106,7 @@ describe('Node FS', () => { const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() await state.doString(` - local f = io.open("${filePath.replace(/\\/g, '/')}", "wb") + local f = io.open("${luaPath(filePath)}", "wb") f:write(string.char(72, 101, 108, 108, 111)) f:close() `) @@ -117,11 +120,11 @@ describe('Node FS', () => { const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() const result = await state.doString(` - local f = io.open("${join(tempDir, 'exists.txt').replace(/\\/g, '/')}", "r") + local f = io.open("${luaPath(join(tempDir, 'exists.txt'))}", "r") local exists = f ~= nil if f then f:close() end - local f2 = io.open("${join(tempDir, 'nope.txt').replace(/\\/g, '/')}", "r") + local f2 = io.open("${luaPath(join(tempDir, 'nope.txt'))}", "r") local not_exists = f2 == nil if f2 then f2:close() end @@ -137,7 +140,7 @@ describe('Node FS', () => { const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() const result = await state.doString(` - local f = io.open("${join(tempDir, 'sized.txt').replace(/\\/g, '/')}", "r") + local f = io.open("${luaPath(join(tempDir, 'sized.txt'))}", "r") local size = f:seek("end") f:close() return size @@ -152,7 +155,7 @@ describe('Node FS', () => { const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() const result = await state.doString(` - local f = io.open("${join(tempDir, 'seek.txt').replace(/\\/g, '/')}", "r") + local f = io.open("${luaPath(join(tempDir, 'seek.txt'))}", "r") f:seek("set", 3) local chunk = f:read(4) f:close() @@ -167,7 +170,7 @@ describe('Node FS', () => { const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() - const result = await state.doFile(join(tempDir, 'script.lua').replace(/\\/g, '/')) + const result = await state.doFile(luaPath(join(tempDir, 'script.lua'))) expect(result).to.be.equal(42) }) @@ -180,7 +183,7 @@ describe('Node FS', () => { const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState({ inject: true }) const result = await state.doString(` - package.path = "${luaDir.replace(/\\/g, '/')}/?.lua;" .. package.path + package.path = "${luaPath(luaDir)}/?.lua;" .. package.path local m = require("mymod") return m.value `) @@ -195,12 +198,7 @@ describe('Node FS', () => { const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() - const result = await state.doString(` - local f = io.open("${join(nested, 'deep.txt').replace(/\\/g, '/')}", "r") - local content = f:read("*a") - f:close() - return content - `) + const result = await readFileFromLua(state, join(nested, 'deep.txt')) expect(result).to.be.equal('deep content') }) @@ -211,7 +209,7 @@ describe('Node FS', () => { const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() await state.doString(` - os.execute("mkdir -p '${newDir.replace(/\\/g, '/')}'") + os.execute("mkdir -p '${luaPath(newDir)}'") `) expect(existsSync(newDir)).to.be.true @@ -224,7 +222,7 @@ describe('Node FS', () => { const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() const result = await state.doString(` - return os.remove("${filePath.replace(/\\/g, '/')}") + return os.remove("${luaPath(filePath)}") `) expect(result).to.be.true @@ -239,7 +237,7 @@ describe('Node FS', () => { const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() const result = await state.doString(` - return os.rename("${oldPath.replace(/\\/g, '/')}", "${newPath.replace(/\\/g, '/')}") + return os.rename("${luaPath(oldPath)}", "${luaPath(newPath)}") `) expect(result).to.be.true @@ -247,20 +245,59 @@ describe('Node FS', () => { expect(readFileSync(newPath, 'utf8')).to.be.equal('rename me') }) + it('NODEFS should start in the host process cwd', async () => { + const lua = await LuaRuntime.load({ fs: 'node' }) + + expect(lua.filesystem.cwd()).to.be.equal(process.cwd().replace(/\\/g, '/')) + }) + it('doFile from cwd-relative path should succeed', async () => { - // NODEFS sets cwd to process.cwd(), so relative doFile should work const lua = await LuaRuntime.load({ fs: 'node' }) + // chdir first, or the mounted file lands in the repo the suite runs from. + lua.filesystem.chdir(tempDir) lua.mountFile('cwd_test.lua', 'return "from cwd"') + const state = lua.createState() + + expect(existsSync(join(tempDir, 'cwd_test.lua'))).to.be.true + expect(await state.doFile('cwd_test.lua')).to.be.equal('from cwd') + }) + + it('fsMountPaths should mount the listed path', async () => { + writeFileSync(join(tempDir, 'inside.txt'), 'mounted content') + + const lua = await LuaRuntime.load({ fs: 'node', fsMountPaths: [tempDir] }) + const state = lua.createState() + + expect(await readFileFromLua(state, join(tempDir, 'inside.txt'))).to.be.equal('mounted content') + }) + + it('fsMountPaths should leave everything else unreachable', async () => { + // Without this the default mounts the whole drive, so the case above passes either way. + const unmounted = createTempDir() + writeFileSync(join(unmounted, 'outside.txt'), 'should not be readable') + try { + const lua = await LuaRuntime.load({ fs: 'node', fsMountPaths: [tempDir] }) const state = lua.createState() - const result = await state.doFile('cwd_test.lua') - expect(result).to.be.equal('from cwd') + expect(await readFileFromLua(state, join(unmounted, 'outside.txt'))).to.be.equal('BLOCKED') } finally { - rmSync('cwd_test.lua', { force: true }) + rmSync(unmounted, { recursive: true, force: true }) } }) + it('mountFile and NODEFS should coexist', async () => { + writeFileSync(join(tempDir, 'host.txt'), 'from host') + + const lua = await LuaRuntime.load({ fs: 'node' }) + lua.filesystem.chdir(tempDir) + lua.mountFile('virtual.lua', 'return "from virtual"') + const state = lua.createState() + + expect(await readFileFromLua(state, join(tempDir, 'host.txt'))).to.be.equal('from host') + expect(await state.doString('return dofile("virtual.lua")')).to.be.equal('from virtual') + }) + it('write large file should succeed', async () => { const filePath = join(tempDir, 'large.txt') const lineCount = 10000 @@ -268,7 +305,7 @@ describe('Node FS', () => { const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() await state.doString(` - local f = io.open("${filePath.replace(/\\/g, '/')}", "w") + local f = io.open("${luaPath(filePath)}", "w") for i = 1, ${lineCount} do f:write("line " .. i .. "\\n") end @@ -289,7 +326,7 @@ describe('Node FS', () => { const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() await state.doString(` - local f = io.open("${filePath.replace(/\\/g, '/')}", "w") + local f = io.open("${luaPath(filePath)}", "w") f:write("new content") f:close() `) @@ -303,12 +340,7 @@ describe('Node FS', () => { const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() - const result = await state.doString(` - local f = io.open("${join(tempDir, 'utf8.txt').replace(/\\/g, '/')}", "r") - local data = f:read("*a") - f:close() - return data - `) + const result = await readFileFromLua(state, join(tempDir, 'utf8.txt')) expect(result).to.be.equal(content) }) @@ -319,7 +351,7 @@ describe('Node FS', () => { const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() await state.doString(` - local f = io.open("${filePath.replace(/\\/g, '/')}", "w") + local f = io.open("${luaPath(filePath)}", "w") f:write("café ñ 中文") f:close() `) @@ -333,7 +365,7 @@ describe('Node FS', () => { const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() const result = await state.doString(` - local f = io.open("${join(tempDir, 'empty.txt').replace(/\\/g, '/')}", "r") + local f = io.open("${luaPath(join(tempDir, 'empty.txt'))}", "r") local data = f:read("*a") f:close() return #data @@ -342,12 +374,12 @@ describe('Node FS', () => { expect(result).to.be.equal(0) }) - it('open non-existent file for reading should return nil', async () => { + it('open non-existent file for reading should return nil and a message', async () => { const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() const result = await state.doString(` - local f, err = io.open("${join(tempDir, 'nonexistent.txt').replace(/\\/g, '/')}", "r") - return f == nil + local f, err = io.open("${luaPath(join(tempDir, 'nonexistent.txt'))}", "r") + return f == nil and type(err) == "string" and #err > 0 `) expect(result).to.be.true @@ -376,13 +408,13 @@ describe('Node FS', () => { const state2 = lua.createState() await state1.doString(` - local f = io.open("${filePath.replace(/\\/g, '/')}", "w") + local f = io.open("${luaPath(filePath)}", "w") f:write("from state1") f:close() `) const result = await state2.doString(` - local f = io.open("${filePath.replace(/\\/g, '/')}", "r") + local f = io.open("${luaPath(filePath)}", "r") local data = f:read("*a") f:close() return data @@ -397,7 +429,7 @@ describe('Node FS', () => { const lua = await LuaRuntime.load({ fs: 'node' }) const state = lua.createState() const result = await state.doString(` - local f = io.open("${join(tempDir, 'numbers.txt').replace(/\\/g, '/')}", "r") + local f = io.open("${luaPath(join(tempDir, 'numbers.txt'))}", "r") local n1 = f:read("*n") local n2 = f:read("*n") local n3 = f:read("*n") diff --git a/test/promises.test.js b/test/promises.test.js index 0058306..17947fc 100644 --- a/test/promises.test.js +++ b/test/promises.test.js @@ -4,7 +4,7 @@ import { mock } from 'node:test' describe('Promises', () => { it('use promise next should succeed', async () => { - const state = await getState() + using state = await getState() const check = mock.fn() state.set('check', check) const promise = new Promise((resolve) => setTimeout(() => resolve(60), 5)) @@ -21,7 +21,7 @@ describe('Promises', () => { }) it('chain promises with next should succeed', async () => { - const state = await getState() + using state = await getState() const check = mock.fn() state.set('check', check) const promise = new Promise((resolve) => resolve(60)) @@ -42,7 +42,7 @@ describe('Promises', () => { }) it('call an async function should succeed', async () => { - const state = await getState() + using state = await getState() state.set('asyncFunction', async () => Promise.resolve(60)) const check = mock.fn() state.set('check', check) @@ -57,7 +57,7 @@ describe('Promises', () => { }) it('return an async function should succeed', async () => { - const state = await getState() + using state = await getState() state.set('asyncFunction', async () => Promise.resolve(60)) const asyncFunction = await state.doString(` @@ -69,7 +69,7 @@ describe('Promises', () => { }) it('return a chained promise should succeed', async () => { - const state = await getState() + using state = await getState() state.set('asyncFunction', async () => Promise.resolve(60)) const asyncFunction = await state.doString(` @@ -81,7 +81,7 @@ describe('Promises', () => { }) it('await an promise inside coroutine should succeed', async () => { - const state = await getState() + using state = await getState() const check = mock.fn() state.set('check', check) const promise = new Promise((resolve) => setTimeout(() => resolve(60), 5)) @@ -108,7 +108,7 @@ describe('Promises', () => { }) it('awaited coroutines should ignore resume until it resolves the promise', async () => { - const state = await getState() + using state = await getState() const check = mock.fn() state.set('check', check) const promise = new Promise((resolve) => setTimeout(() => resolve(60), 5)) @@ -133,7 +133,7 @@ describe('Promises', () => { }) it('await a thread run with async calls should succeed', async () => { - const state = await getState() + using state = await getState() state.set('sleep', (input) => new Promise((resolve) => setTimeout(resolve, input))) const asyncThread = state.newThread() @@ -147,7 +147,7 @@ describe('Promises', () => { }) it('run thread with async calls and yields should succeed', async () => { - const state = await getState() + using state = await getState() state.set('sleep', (input) => new Promise((resolve) => setTimeout(resolve, input))) const asyncThread = state.newThread() @@ -165,7 +165,7 @@ describe('Promises', () => { }) it('reject a promise should succeed', async () => { - const state = await getState() + using state = await getState() state.set('throw', () => new Promise((_, reject) => reject(new Error('expected test error')))) const asyncThread = state.newThread() @@ -178,7 +178,7 @@ describe('Promises', () => { }) it('pcall a promise await should succeed', async () => { - const state = await getState() + using state = await getState() state.set('throw', () => new Promise((_, reject) => reject(new Error('expected test error')))) const asyncThread = state.newThread() @@ -192,7 +192,7 @@ describe('Promises', () => { }) it('catch a promise rejection should succeed', async () => { - const state = await getState() + using state = await getState() const fulfilled = mock.fn() const rejected = mock.fn() state.set('handlers', { fulfilled, rejected }) @@ -209,7 +209,7 @@ describe('Promises', () => { }) it('run with async callback', async () => { - const state = await getState() + using state = await getState() const thread = state.newThread() state.set('asyncCallback', async (input) => { @@ -232,7 +232,7 @@ describe('Promises', () => { }) it('promise creation from js', async () => { - const state = await getState() + using state = await getState() const res = await state.doString(` local promise = Promise.create(function (resolve) resolve(10) @@ -248,7 +248,7 @@ describe('Promises', () => { }) it('reject promise creation from js', async () => { - const state = await getState() + using state = await getState() const res = await state.doString(` local rejection = Promise.create(function (resolve, reject) reject("expected rejection") @@ -261,7 +261,7 @@ describe('Promises', () => { }) it('resolve multiple promises with promise.all', async () => { - const state = await getState() + using state = await getState() state.set('sleep', (input) => new Promise((resolve) => setTimeout(resolve, input))) const resPromise = state.doString(` local promises = {} @@ -278,7 +278,7 @@ describe('Promises', () => { }) it('error in promise next catchable', async () => { - const state = await getState() + using state = await getState() state.set('sleep', (input) => new Promise((resolve) => setTimeout(resolve, input))) const resPromise = state.doString(` return sleep(1):next(function () @@ -289,7 +289,7 @@ describe('Promises', () => { }) it('should not be possible to await in synchronous run', async () => { - const state = await getState() + using state = await getState() state.set('sleep', (input) => new Promise((resolve) => setTimeout(resolve, input))) expect(() => { diff --git a/test/state.test.js b/test/state.test.js index 82bcf02..92decdd 100644 --- a/test/state.test.js +++ b/test/state.test.js @@ -35,7 +35,7 @@ describe('State', () => { }) it('receive lua table on JS function should succeed', async () => { - const state = await getState() + using state = await getState() state.set('stringify', (table) => { return JSON.stringify(table) }) @@ -46,7 +46,7 @@ describe('State', () => { }) it('get a global table inside a JS function called by lua should succeed', async () => { - const state = await getState() + using state = await getState() state.set('t', { test: 1 }) state.set('test', () => { return state.get('t') @@ -58,7 +58,7 @@ describe('State', () => { }) it('receive JS object on lua should succeed', async () => { - const state = await getState() + using state = await getState() state.set('test', () => { return { @@ -75,7 +75,7 @@ describe('State', () => { }) it('receive JS object with circular references on lua should succeed', async () => { - const state = await getState() + using state = await getState() const obj = { hello: 'world', } @@ -88,7 +88,7 @@ describe('State', () => { }) it('receive Lua object with circular references on JS should succeed', async () => { - const state = await getState() + using state = await getState() const value = await state.doString(` local obj1 = { hello = 'world', @@ -124,7 +124,7 @@ describe('State', () => { }) it('receive lua array with circular references on JS should succeed', async () => { - const state = await getState() + using state = await getState() const value = await state.doString(` obj = { "hello", @@ -140,7 +140,7 @@ describe('State', () => { }) it('receive JS object with multiple circular references on lua should succeed', async () => { - const state = await getState() + using state = await getState() const obj1 = { hello: 'world', } @@ -158,7 +158,7 @@ describe('State', () => { }) it('receive JS object with null prototype on lua should succeed', async () => { - const state = await getState() + using state = await getState() const obj = Object.create(null) obj.hello = 'world' state.set('obj', obj) @@ -169,7 +169,7 @@ describe('State', () => { }) it('inherited properties should not be copied into the lua table', async () => { - const state = await getState({ objects: 'copy' }) + using state = await getState({ objects: 'copy' }) const obj = Object.create({ inherited: 'yes' }) obj.own = 'mine' state.set('t', obj) @@ -185,7 +185,7 @@ describe('State', () => { }) it('non enumerable properties should not be copied into the lua table', async () => { - const state = await getState({ objects: 'copy' }) + using state = await getState({ objects: 'copy' }) const obj = { own: 'mine' } Object.defineProperty(obj, 'hidden', { value: 1, enumerable: false }) state.set('t', obj) @@ -195,7 +195,7 @@ describe('State', () => { }) it('nested arrays and objects should be copied into the lua table', async () => { - const state = await getState({ objects: 'copy' }) + using state = await getState({ objects: 'copy' }) state.set('t', { list: [10, 20, 30], nested: { deep: [{ value: 5 }] } }) expect(await state.doString('return #t.list')).to.be.equal(3) @@ -203,14 +203,14 @@ describe('State', () => { expect(await state.doString('return t.nested.deep[1].value')).to.be.equal(5) }) - it('a lua error should throw on JS', async () => { - const state = await getState() + it('a lua syntax error should throw on JS', async () => { + using state = await getState() - await expect(state.doString(`x -`)).to.eventually.be.rejected + await expect(state.doString(`x -`)).to.eventually.be.rejectedWith(/syntax error near/) }) it('call a lua function from JS should succeed', async () => { - const state = await getState() + using state = await getState() await state.doString(`function sum(x, y) return x + y end`) const sum = state.get('sum') @@ -219,7 +219,7 @@ describe('State', () => { }) it('scheduled lua calls should succeed', async () => { - const state = await getState() + using state = await getState() state.set('setInterval', setIntervalSafe) await state.doString(` @@ -247,7 +247,7 @@ describe('State', () => { }) it('calling a lua function after close should throw', async () => { - const state = await getState() + using state = await getState() const callback = await state.doString(` test = 0 @@ -261,7 +261,7 @@ describe('State', () => { }) it('call lua function from JS passing an array argument should succeed', async () => { - const state = await getState() + using state = await getState() const sum = await state.doString(` return function(arr) @@ -277,7 +277,7 @@ describe('State', () => { }) it('call a global function with multiple returns should succeed', async () => { - const state = await getState() + using state = await getState() await state.doString(` function f(x,y) @@ -292,7 +292,7 @@ describe('State', () => { }) it('get a lua thread should succeed', async () => { - const state = await getState() + using state = await getState() const thread = await state.doString(` return coroutine.create(function() @@ -305,7 +305,7 @@ describe('State', () => { }) it('a JS error should pause lua execution', async () => { - const state = await getState() + using state = await getState() const check = mock.fn() state.set('check', check) state.set('throw', () => { @@ -322,7 +322,7 @@ describe('State', () => { }) it('catch a JS error with pcall should succeed', async () => { - const state = await getState() + using state = await getState() const check = mock.fn() state.set('check', check) state.set('throw', () => { @@ -340,7 +340,7 @@ describe('State', () => { }) it('call a JS function in a different thread should succeed', async () => { - const state = await getState() + using state = await getState() const sum = mock.fn((x, y) => x + y) state.set('sum', sum) @@ -355,7 +355,7 @@ describe('State', () => { }) it('get callable table as function should succeed', async () => { - const state = await getState() + using state = await getState() await state.doString(` _G['sum'] = setmetatable({}, { __call = function(self, x, y) @@ -371,7 +371,7 @@ describe('State', () => { }) it('lua_resume with yield succeeds', async () => { - const state = await getState() + using state = await getState() const thread = state.newThread() thread.loadString(` local yieldRes = coroutine.yield(10) @@ -397,12 +397,12 @@ describe('State', () => { }) it('get memory with allocation tracing should succeeds', async () => { - const state = await getState({ memory: { trace: true } }) + using state = await getState({ memory: { trace: true } }) expect(state.memory.used).to.be.greaterThan(0) }) it('get memory should return correct', async () => { - const state = await getState({ memory: { trace: true } }) + using state = await getState({ memory: { trace: true } }) const totalMemory = await state.doString(` collectgarbage() @@ -415,13 +415,13 @@ describe('State', () => { }) it('memory is undefined without tracing', async () => { - const state = await getState() + using state = await getState() expect(state.memory).to.be.undefined }) it('limit memory use causes program loading failure succeeds', async () => { - const state = await getState({ memory: { trace: true } }) + using state = await getState({ memory: { trace: true } }) state.memory.max = state.memory.used expect(() => { state.loadString(` @@ -441,7 +441,7 @@ describe('State', () => { }) it('limit memory use causes program runtime failure succeeds', async () => { - const state = await getState({ memory: { trace: true } }) + using state = await getState({ memory: { trace: true } }) state.loadString(` local tab = {} for i = 1, 50, 1 do @@ -454,7 +454,7 @@ describe('State', () => { }) it('table supported circular dependencies', async () => { - const state = await getState() + using state = await getState() const a = { name: 'a' } const b = { name: 'b' } @@ -468,7 +468,7 @@ describe('State', () => { }) it('wrap a js object (with metatable)', async () => { - const state = await getState() + using state = await getState() state.set('TestClass', { create: (name) => { return decorate( @@ -498,7 +498,7 @@ describe('State', () => { }) it('wrap a js object using proxy', async () => { - const state = await getState() + using state = await getState() state.set('TestClass', { create: (name) => new TestClass(name), }) @@ -510,7 +510,7 @@ describe('State', () => { }) it('wrap a js object using proxy and apply metatable in lua', async () => { - const state = await getState() + using state = await getState() state.set('TestClass', { create: (name) => new TestClass(name), }) @@ -539,7 +539,7 @@ describe('State', () => { }) it('classes should be a userdata when proxied', async () => { - const state = await getState() + using state = await getState() state.set('obj', { TestClass }) const testClass = await state.doString(` @@ -550,7 +550,7 @@ describe('State', () => { }) it('timeout blocking lua program', async () => { - const state = await getState() + using state = await getState() state.loadString(` local i = 0 while true do i = i + 1 end @@ -561,7 +561,7 @@ describe('State', () => { it('the most recently set timeout should be the one that applies', async function () { this.timeout(30_000) - const state = await getState() + using state = await getState() const thread = state.newThread() thread.setDeadline(Date.now() + 20) @@ -573,7 +573,7 @@ describe('State', () => { it('clearing a timeout should disable the hook', async function () { this.timeout(30_000) - const state = await getState() + using state = await getState() const thread = state.newThread() thread.setDeadline(Date.now() + 10) @@ -585,7 +585,7 @@ describe('State', () => { }) it('overwrite lib function', async () => { - const state = await getState() + using state = await getState() let output = '' state.getTable('_G', (index) => { @@ -604,7 +604,7 @@ describe('State', () => { }) it('inject a userdata with a metatable should succeed', async () => { - const state = await getState() + using state = await getState() const obj = decorate( {}, { @@ -619,7 +619,7 @@ describe('State', () => { }) it('a userdata should be collected', async () => { - const state = await getState() + using state = await getState() const obj = {} state.set('obj', obj) const refIndex = state.lua.getLastRefIndex() @@ -640,7 +640,7 @@ describe('State', () => { }) it('environment variables should be set', async () => { - const lua = await getLua({ TEST: 'true' }) + const lua = await getLua({ env: { TEST: 'true' } }) const state = lua.createState() const testEnvVar = await state.doString(`return os.getenv('TEST')`) @@ -649,7 +649,7 @@ describe('State', () => { }) it('static methods should be callable on classes', async () => { - const state = await getState() + using state = await getState() state.set('TestClass', TestClass) const testHello = await state.doString(`return TestClass.hello()`) @@ -658,7 +658,7 @@ describe('State', () => { }) it('should be possible to access function properties', async () => { - const state = await getState() + using state = await getState() const testFunction = () => undefined testFunction.hello = 'world' state.set('TestFunction', decorate(testFunction, { as: 'proxy' })) @@ -669,7 +669,7 @@ describe('State', () => { }) it('throw error includes stack trace', async () => { - const state = await getState() + using state = await getState() try { await state.doString(` local function a() @@ -695,7 +695,7 @@ describe('State', () => { }) it('should get only the last result on run', async () => { - const state = await getState() + using state = await getState() const a = await state.doString(`return 1`) const b = await state.doString(`return 3`) @@ -709,7 +709,7 @@ describe('State', () => { }) it('should get only the return values on call function', async () => { - const state = await getState() + using state = await getState() state.set('hello', (name) => `Hello ${name}!`) const a = await state.doString(`return 1`) @@ -723,7 +723,7 @@ describe('State', () => { }) it('create a large string variable should succeed', async () => { - const state = await getState() + using state = await getState() const str = 'a'.repeat(1000000) state.set('str', str) @@ -734,7 +734,7 @@ describe('State', () => { }) it('execute a large string should succeed', async () => { - const state = await getState() + using state = await getState() const str = 'a'.repeat(1000000) const res = await state.doString(`return [[${str}]]`) @@ -744,7 +744,7 @@ describe('State', () => { it('a large multibyte string should keep its byte length', async function () { this.timeout(30_000) - const state = await getState() + using state = await getState() const str = 'á'.repeat(500000) state.set('str', str) @@ -754,14 +754,14 @@ describe('State', () => { }) it('a string containing NUL should be pushed with its full length', async () => { - const state = await getState() + using state = await getState() state.set('str', 'a\0b') expect(await state.doString('return #str')).to.be.equal(3) }) it('a string containing NUL should be retrieved with its full length', async () => { - const state = await getState() + using state = await getState() const res = await state.doString('return "x\\0y"') @@ -769,7 +769,7 @@ describe('State', () => { }) it('a string containing NUL should round trip unchanged', async () => { - const state = await getState() + using state = await getState() const str = 'before\0middle\0after' state.set('str', str) @@ -777,7 +777,7 @@ describe('State', () => { }) it('an empty string should round trip unchanged', async () => { - const state = await getState() + using state = await getState() state.set('str', '') expect(await state.doString('return #str')).to.be.equal(0) @@ -785,7 +785,7 @@ describe('State', () => { }) it('getStringBytes should expose bytes that are not valid UTF-8', async () => { - const state = await getState() + using state = await getState() await state.doString('value = string.char(0, 255, 128, 65)') state.lua.lua_getglobal(state.address, 'value') @@ -796,7 +796,7 @@ describe('State', () => { }) it('getStringBytes should return undefined for a non string value', async () => { - const state = await getState() + using state = await getState() state.pushValue({}) expect(state.getStringBytes(-1)).to.be.undefined @@ -805,7 +805,7 @@ describe('State', () => { }) it('bytecode should round trip through the byte accessors', async () => { - const state = await getState() + using state = await getState() await state.doString('bytecode = string.dump(load("return 42"))') state.lua.lua_getglobal(state.address, 'bytecode') @@ -819,7 +819,7 @@ describe('State', () => { }) it('negative integers should be pushed and retrieved as string', async () => { - const state = await getState() + using state = await getState() state.set('value', -1) const res = await state.doString(`return tostring(value)`) @@ -828,7 +828,7 @@ describe('State', () => { }) it('negative integers should be pushed and retrieved as number', async () => { - const state = await getState() + using state = await getState() state.set('value', -1) const res = await state.doString(`return value`) @@ -837,7 +837,7 @@ describe('State', () => { }) it('number greater than 32 bit int should be pushed and retrieved as string', async () => { - const state = await getState() + using state = await getState() const value = 1689031554550 state.set('value', value) @@ -847,7 +847,7 @@ describe('State', () => { }) it('number greater than 32 bit int should be pushed and retrieved as number', async () => { - const state = await getState() + using state = await getState() const value = 1689031554550 state.set('value', value) @@ -857,7 +857,7 @@ describe('State', () => { }) it('number greater than 32 bit int should be usable as a format argument', async () => { - const state = await getState() + using state = await getState() const value = 1689031554550 state.set('value', value) @@ -867,7 +867,7 @@ describe('State', () => { }) it('64-bit integers pushed through the raw Lua API should keep integer semantics', async () => { - const state = await getState() + using state = await getState() const value = 9223372036854775807n state.lua.lua_pushinteger(state.address, value) @@ -886,14 +886,14 @@ describe('State', () => { }) it('integers outside the JS safe range should be retrieved as bigint', async () => { - const state = await getState() + using state = await getState() expect(await state.doString('return math.maxinteger')).to.be.equal(9223372036854775807n) expect(await state.doString('return math.mininteger')).to.be.equal(-9223372036854775808n) }) it('integers inside the JS safe range should be retrieved as number', async () => { - const state = await getState() + using state = await getState() const res = await state.doString('return 1689031554550') @@ -902,21 +902,21 @@ describe('State', () => { }) it('an integral number should be pushed as a lua integer', async () => { - const state = await getState() + using state = await getState() state.set('value', 2) expect(await state.doString('return math.type(value)')).to.be.equal('integer') }) it('floats should be retrieved as number', async () => { - const state = await getState() + using state = await getState() expect(await state.doString('return 1.5')).to.be.equal(1.5) expect(await state.doString('return math.type(1.5)')).to.be.equal('float') }) it('a bigint should be pushed as a 64 bit lua integer', async () => { - const state = await getState() + using state = await getState() state.set('value', 9223372036854775807n) expect(await state.doString('return tostring(value)')).to.be.equal('9223372036854775807') @@ -925,13 +925,13 @@ describe('State', () => { }) it('a bigint outside the lua integer range should throw', async () => { - const state = await getState() + using state = await getState() expect(() => state.set('value', 2n ** 70n)).to.throw(RangeError) }) it('an integral number too large for a lua integer should be pushed as a float', async () => { - const state = await getState() + using state = await getState() state.set('value', 1e300) expect(await state.doString('return math.type(value)')).to.be.equal('float') @@ -942,7 +942,7 @@ describe('State', () => { // When yielding within a callback the error 'attempt to yield across a C-call boundary'. // This test just checks that throwing that error still allows the lua global to be // re-used and doesn't cause JS to abort or some nonsense. - const state = await getState() + using state = await getState() const testEmitter = new EventEmitter() state.set('yield', () => new Promise((resolve) => testEmitter.once('resolve', resolve))) const resPromise = state.doString(` @@ -960,7 +960,7 @@ describe('State', () => { }) it('forced yield within JS callback from Lua doesnt cause vm to crash', async () => { - const state = await getState({ limits: { functionTimeout: 10 } }) + using state = await getState({ limits: { functionTimeout: 10 } }) state.set('promise', Promise.resolve()) const thread = state.newThread() thread.loadString(` @@ -976,7 +976,7 @@ describe('State', () => { }) it('function callback timeout still allows timeout of caller thread', async () => { - const state = await getState() + using state = await getState() state.set('promise', Promise.resolve()) const thread = state.newThread() thread.loadString(` @@ -989,7 +989,7 @@ describe('State', () => { }) it('null injected and valid', async () => { - const state = await getState() + using state = await getState() state.loadString(` local args = { ... } assert(args[1] == null, string.format("expected first argument to be null, got %s", tostring(args[1]))) @@ -1001,7 +1001,7 @@ describe('State', () => { }) it('null injected as nil', async () => { - const state = await getState({ inject: false }) + using state = await getState({ inject: false }) state.loadString(` local args = { ... } assert(type(args[1]) == "nil", string.format("expected first argument to be nil, got %s", type(args[1]))) @@ -1013,7 +1013,7 @@ describe('State', () => { }) it('reassigning the null global should not affect pushing null', async () => { - const state = await getState() + using state = await getState() await state.doString('null = 5') state.set('value', null) @@ -1023,14 +1023,14 @@ describe('State', () => { }) it('a pushed null should equal the injected null global', async () => { - const state = await getState() + using state = await getState() state.set('value', null) expect(await state.doString('return value == null')).to.be.true }) it('Nested callback from JS to Lua', async () => { - const state = await getState() + using state = await getState() state.set('call', (fn) => fn()) const res = await state.doString(` return call(function () @@ -1043,7 +1043,7 @@ describe('State', () => { }) it('lots of doString calls should succeed', async () => { - const state = await getState() + using state = await getState() const length = 10000 for (let i = 0; i < length; i++) { @@ -1056,7 +1056,7 @@ describe('State', () => { it('lots of doStringSync calls should not grow the lua stack', async function () { this.timeout(30_000) - const state = await getState() + using state = await getState() const startTop = state.getTop() for (let i = 0; i < 500; i++) { @@ -1067,7 +1067,7 @@ describe('State', () => { }) it('a failing doStringSync should not grow the lua stack', async () => { - const state = await getState() + using state = await getState() const startTop = state.getTop() expect(() => state.doStringSync('error("boom")')).to.throw('boom') @@ -1076,7 +1076,7 @@ describe('State', () => { }) it('values returned by doStringSync should outlive the stack reset', async () => { - const state = await getState() + using state = await getState() const fn = state.doStringSync('return function() return 3 end') const table = state.doStringSync('return { a = 1, b = { 2, 3 } }') @@ -1087,7 +1087,7 @@ describe('State', () => { it('many concurrent doString calls should succeed', async function () { this.timeout(15000) - const state = await getState() + using state = await getState() const length = 55 const promises = [] @@ -1104,7 +1104,7 @@ describe('State', () => { describe('Load mode', () => { it('loadString refuses bytecode by default', async () => { - const state = await getState() + using state = await getState() // Produced and reloaded inside Lua so the bytes never round trip through a JS string. expect( state.doStringSync(` @@ -1116,13 +1116,13 @@ describe('Load mode', () => { }) it('the host loader refuses a binary chunk by default', async () => { - const state = await getState() + using state = await getState() expect(() => state.loadString('\x1bLua\x55\x00')).to.throw('attempt to load a binary chunk') }) it('mode bt opts back in', async () => { - const state = await getState() + using state = await getState() expect( state.doStringSync(` @@ -1144,7 +1144,7 @@ describe('Decoration', () => { } it('as userdata hides the members', async () => { - const state = await getState() + using state = await getState() state.set('thing', decorate(new Thing('bob'), { as: 'userdata' })) // An opaque userdata has no __index of its own, so Lua refuses to index it at all. @@ -1152,7 +1152,7 @@ describe('Decoration', () => { }) it('as userdata still cannot take a metatable of its own', async () => { - const state = await getState() + using state = await getState() // The userdata extension owns the metatable slot. That is a constraint of the extension, // not of the decoration API, so a custom metatable has to go on a wrapper. @@ -1162,7 +1162,7 @@ describe('Decoration', () => { }) it('a wrapper carries the metatable around an opaque userdata', async () => { - const state = await getState() + using state = await getState() state.set( 'thing', decorate( @@ -1175,14 +1175,14 @@ describe('Decoration', () => { }) it('as value copies an object instead of proxying it', async () => { - const state = await getState() + using state = await getState() state.set('plain', decorate({ a: 1 }, { as: 'value' })) expect(await state.doString('return type(plain)')).to.be.equal('table') }) it('as proxy forces a function through the proxy layer', async () => { - const state = await getState() + using state = await getState() const fn = () => undefined fn.hello = 'world' state.set('fn', decorate(fn, { as: 'proxy' })) @@ -1210,7 +1210,7 @@ describe('Memory', () => { describe('Synchronous runs', () => { it('do not leak stack onto the state between calls', async () => { - const state = await getState() + using state = await getState() const top = state.getTop() for (let i = 0; i < 50; i++) { @@ -1221,7 +1221,7 @@ describe('Synchronous runs', () => { }) it('a hook installed for a sync run does not outlive it', async () => { - const state = await getState() + using state = await getState() state.doStringSync('return 1', { timeout: 1000 }) diff --git a/test/stdio.test.js b/test/stdio.test.js new file mode 100644 index 0000000..f34e000 --- /dev/null +++ b/test/stdio.test.js @@ -0,0 +1,112 @@ +import { expect } from 'chai' +import { LuaRuntime } from '../dist/index.js' + +const collectOutput = async (stream, script) => { + const output = [] + const lua = await LuaRuntime.load({ [stream]: (content) => output.push(content) }) + await lua.createState().doString(script) + return output +} + +// The empty string is what signals EOF, so reads past the end have to return it rather than undefined. +const stdinFrom = (chunks) => { + let index = 0 + return () => chunks[index++] ?? '' +} + +describe('Custom stdout', () => { + it('should receive what the script prints', async () => { + const output = await collectOutput('stdout', 'print("hello from node")') + + expect(output).to.be.deep.equal(['hello from node']) + }) + + it('should keep multi byte characters intact', async () => { + const output = await collectOutput('stdout', 'print("héllo 日本語 🎉")') + + expect(output).to.be.deep.equal(['héllo 日本語 🎉']) + }) + + it('should keep a character that is flushed in the middle intact', async () => { + // The two halves of 日 land in different writes, with the engine handing control back to + // JS in between. + const output = [] + const lua = await LuaRuntime.load({ stdout: (content) => output.push(content) }) + const state = lua.createState() + state.set( + 'pause', + () => + new Promise((resolve) => { + setTimeout(resolve, 0) + }), + ) + + await state.doString('io.write("\\xE6") io.flush() pause():await() io.write("\\x97\\xA5 ok\\n")') + + expect(output).to.be.deep.equal(['日 ok']) + }) + + it('should split on line breaks only', async () => { + const output = await collectOutput('stdout', 'print("first") print("") io.write("a\\rb\\n")') + + expect(output).to.be.deep.equal(['first', '', 'a\rb']) + }) + + it('should receive flushed output that does not end in a line break', async () => { + const output = await collectOutput('stdout', 'io.write("no newline") io.flush()') + + expect(output).to.be.deep.equal(['no newline']) + }) + + it('should not split a line that is written in parts', async () => { + const output = await collectOutput('stdout', 'io.write("one ") io.flush() io.write("line\\n")') + + expect(output).to.be.deep.equal(['one line']) + }) + + it('should handle lines longer than its buffer', async () => { + const output = await collectOutput('stdout', 'print(string.rep("ção ", 1000))') + + expect(output).to.be.deep.equal(['ção '.repeat(1000)]) + }) +}) + +describe('Custom stderr', () => { + it('should receive what the script writes', async () => { + const errors = await collectOutput('stderr', 'io.stderr:write("error output\\n")') + + expect(errors).to.be.deep.equal(['error output']) + }) + + it('should keep multi byte characters intact', async () => { + const errors = await collectOutput('stderr', 'io.stderr:write("erro ✗ 日本\\n")') + + expect(errors).to.be.deep.equal(['erro ✗ 日本']) + }) +}) + +describe('Custom stdin', () => { + it('should be read line by line', async () => { + const lua = await LuaRuntime.load({ stdin: stdinFrom(['um\n', 'dois\n']) }) + + const result = await lua.createState().doString('return { io.read("l"), io.read("l"), io.read("l") == nil }') + + expect(result).to.be.deep.equal(['um', 'dois', true]) + }) + + it('should keep multi byte characters intact', async () => { + const lua = await LuaRuntime.load({ stdin: stdinFrom(['héllo 日本語 🎉\n']) }) + + const result = await lua.createState().doString('return io.read("l")') + + expect(result).to.be.equal('héllo 日本語 🎉') + }) + + it('should be read until it signals the end of the input', async () => { + const lua = await LuaRuntime.load({ stdin: stdinFrom(['abc\n', 'déf\n']) }) + + const result = await lua.createState().doString('return io.read("a")') + + expect(result).to.be.equal('abc\ndéf\n') + }) +}) diff --git a/test/utils.js b/test/utils.js index ee59609..f0343b9 100644 --- a/test/utils.js +++ b/test/utils.js @@ -1,7 +1,7 @@ import { LuaRuntime } from '../dist/index.js' -export const getLua = (env) => { - return LuaRuntime.load({ env }) +export const getLua = (options) => { + return LuaRuntime.load(options) } export const getState = async (config = {}) => { @@ -16,3 +16,6 @@ export const getState = async (config = {}) => { export const tick = () => { return new Promise((resolve) => setImmediate(resolve)) } + +/** Windows paths cannot go into a Lua string literal as they are. */ +export const luaPath = (path) => path.replace(/\\/g, '/') From 85491abe4554e7af2e69ad6b40cf457c493253ec Mon Sep 17 00:00:00 2001 From: Gabriel Francisco Date: Tue, 28 Jul 2026 23:21:20 -0300 Subject: [PATCH 45/83] small api changes --- bench/comparisons.js | 6 +- bench/steps.js | 6 +- package.json | 2 +- src/index.ts | 1 + src/module.ts | 41 +++++++--- src/runtime.ts | 15 ++-- src/state.ts | 44 +++++----- src/thread.ts | 141 +++++++++++++++++--------------- src/type-extension.ts | 24 +++--- src/type-extensions/error.ts | 20 ++--- src/type-extensions/function.ts | 64 +++++++-------- src/type-extensions/null.ts | 32 ++++---- src/type-extensions/promise.ts | 32 ++++---- src/type-extensions/proxy.ts | 36 ++++---- src/type-extensions/table.ts | 24 +++--- src/type-extensions/userdata.ts | 22 ++--- src/types.ts | 10 +-- test/api.test.js | 16 ++-- test/errors.test.js | 6 +- test/initialization.test.js | 7 +- test/state.test.js | 35 +++++--- utils/reference-types.js | 17 ++++ 22 files changed, 326 insertions(+), 275 deletions(-) create mode 100644 utils/reference-types.js diff --git a/bench/comparisons.js b/bench/comparisons.js index 20d81d3..8ee2d52 100644 --- a/bench/comparisons.js +++ b/bench/comparisons.js @@ -20,9 +20,9 @@ function createWasmoonIteration(lua) { return function runWasmoonIteration() { const state = lua.createState() try { - assertStatus(state.lua.luaL_loadstring(state.address, heapsort), 'Wasmoon load') - assertStatus(state.lua.lua_pcallk(state.address, 0, 1, 0, 0, null), 'Wasmoon compile') - assertStatus(state.lua.lua_pcallk(state.address, 0, 1, 0, 0, null), 'Wasmoon execute') + assertStatus(state.module.luaL_loadstring(state.address, heapsort), 'Wasmoon load') + assertStatus(state.module.lua_pcallk(state.address, 0, 1, 0, 0, null), 'Wasmoon compile') + assertStatus(state.module.lua_pcallk(state.address, 0, 1, 0, 0, null), 'Wasmoon execute') } finally { state.close() } diff --git a/bench/steps.js b/bench/steps.js index 8a6d8a8..19ea962 100644 --- a/bench/steps.js +++ b/bench/steps.js @@ -47,9 +47,9 @@ function createRawHeapsortBenchmark(lua) { return function runRawHeapsort() { const state = lua.createState() try { - assertStatus(state.lua.luaL_loadstring(state.address, heapsort), 'Load raw heapsort') - assertStatus(state.lua.lua_pcallk(state.address, 0, 1, 0, 0, null), 'Compile raw heapsort') - assertStatus(state.lua.lua_pcallk(state.address, 0, 1, 0, 0, null), 'Execute raw heapsort') + assertStatus(state.module.luaL_loadstring(state.address, heapsort), 'Load raw heapsort') + assertStatus(state.module.lua_pcallk(state.address, 0, 1, 0, 0, null), 'Compile raw heapsort') + assertStatus(state.module.lua_pcallk(state.address, 0, 1, 0, 0, null), 'Execute raw heapsort') } finally { state.close() } diff --git a/package.json b/package.json index f416ecb..d46f859 100755 --- a/package.json +++ b/package.json @@ -27,7 +27,7 @@ "pretest": "npm run build", "test": "mocha --parallel --exit --require ./test/boot.js test/*.test.js", "luatests": "node --experimental-import-meta-resolve test/luatests.js", - "build": "rm -rf dist && rolldown -c && tsc -d --emitDeclarationOnly --rootDir src --declarationDir dist", + "build": "rm -rf dist && rolldown -c && tsc -d --emitDeclarationOnly --rootDir src --declarationDir dist && node utils/reference-types.js", "clean": "rm -rf dist build", "lint": "oxfmt --write . && oxlint --fix .", "lint:nofix": "oxfmt --check . && oxlint ." diff --git a/src/index.ts b/src/index.ts index 81cc3d4..06b2efb 100755 --- a/src/index.ts +++ b/src/index.ts @@ -8,6 +8,7 @@ export { decorate, Decoration, type DecorationOptions, type DecorationTarget, ty // use the bindings rather than the wrappers. export { default as LuaModule, + type EmscriptenFS, type EmscriptenPath, type EnvironmentVariables, type LuaEmscriptenModule, diff --git a/src/module.ts b/src/module.ts index 53414b3..e359191 100755 --- a/src/module.ts +++ b/src/module.ts @@ -1,3 +1,7 @@ +// The types below are `@types/emscripten`'s ambient globals. They only resolve for a consumer who +// lists "emscripten" in their own tsconfig `types`, so utils/reference-types.js puts a +// `/// ` at the top of the emitted declarations to cover everyone +// else. tsc drops the directive when it is written here, hence the build step. import initWasmModule from '../build/glue.js' import { defaultWarnHandler, LUA_REGISTRYINDEX, type LuaAddress, LuaReturn, LuaType, type LuaWarnHandler, PointerSize } from './types' // A rolldown plugin will resolve this to the current version on package.json @@ -15,6 +19,7 @@ export interface EmscriptenPath { join2: (left: string, right: string) => string } +/** The instantiated wasm module, as {@link LuaModule.emscripten}. */ export interface LuaEmscriptenModule extends EmscriptenModule { ccall: typeof ccall addFunction: typeof addFunction @@ -37,6 +42,9 @@ export interface LuaEmscriptenModule extends EmscriptenModule { _realloc: (pointer: number, size: number) => number } +/** The virtual filesystem every state on a runtime shares, as {@link LuaModule.emscripten}'s `FS`. */ +export type EmscriptenFS = LuaEmscriptenModule['FS'] + export interface LuaModuleOptions { /** * Where to load `glue.wasm` from. Defaults to next to this module, falling back to unpkg when @@ -57,7 +65,10 @@ export interface LuaModuleOptions { */ stdout?: ((content: string) => void) | undefined stderr?: ((content: string) => void) | undefined - /** Where load time diagnostics go. Defaults to `console.warn`. */ + /** + * Where diagnostics go, both while loading and from every state created on the runtime unless + * that state overrides it. Defaults to `console.warn`. + */ onWarn?: LuaWarnHandler | undefined } @@ -164,6 +175,7 @@ export default class LuaModule { const load = async (wasmFile?: string): Promise => { return new LuaModule( await initWasmModule({ ...(wasmFile === undefined ? {} : { locateFile: () => wasmFile }), preRun, printErr }), + opts.onWarn, ) } @@ -209,7 +221,9 @@ export default class LuaModule { } } - public _emscripten: LuaEmscriptenModule + public emscripten: LuaEmscriptenModule + /** The handler passed to {@link LuaModule.initialize}, which states created on it inherit. */ + public readonly onWarn: LuaWarnHandler | undefined public luaL_checkversion_: (L: LuaAddress, ver: number, sz: number) => void public luaL_getmetafield: (L: LuaAddress, obj: number, e: string | null) => LuaType @@ -382,8 +396,9 @@ export default class LuaModule { private readonly sizeScratch: number private stringBuffer = 0 - public constructor(module: LuaEmscriptenModule) { - this._emscripten = module + public constructor(module: LuaEmscriptenModule, onWarn?: LuaWarnHandler) { + this.emscripten = module + this.onWarn = onWarn this.luaL_checkversion_ = this.cwrap('luaL_checkversion_', null, ['number', 'number', 'number']) this.luaL_getmetafield = this.cwrap('luaL_getmetafield', 'number', ['number', 'number', 'string']) @@ -690,16 +705,16 @@ export default class LuaModule { // Never cache this: ALLOW_MEMORY_GROWTH swaps the underlying buffer when the heap grows, and // Emscripten reassigns HEAPU8 to match. private get heap(): Uint8Array { - return this._emscripten.HEAPU8 + return this.emscripten.HEAPU8 } private readSize(pointer: number): number { - return this._emscripten.HEAPU32[pointer >>> 2] + return this.emscripten.HEAPU32[pointer >>> 2] } private acquireStringBuffer(size: number): number { if (size > REUSABLE_STRING_BUFFER_LIMIT) { - const pointer = this._emscripten._malloc(size) + const pointer = this.emscripten._malloc(size) if (!pointer) { throw new Error(`failed to allocate ${size} bytes for a string`) } @@ -707,7 +722,7 @@ export default class LuaModule { } if (!this.stringBuffer) { - this.stringBuffer = this._emscripten._malloc(REUSABLE_STRING_BUFFER_LIMIT) + this.stringBuffer = this.emscripten._malloc(REUSABLE_STRING_BUFFER_LIMIT) if (!this.stringBuffer) { throw new Error(`failed to allocate ${REUSABLE_STRING_BUFFER_LIMIT} bytes for the string buffer`) } @@ -718,7 +733,7 @@ export default class LuaModule { private releaseStringBuffer(pointer: number): void { if (pointer !== this.stringBuffer) { - this._emscripten._free(pointer) + this.emscripten._free(pointer) } } @@ -731,7 +746,7 @@ export default class LuaModule { const hasStringOrNumber = argTypes.some((argType) => argType === 'string|number') if (!hasStringOrNumber) { return (...args: any[]) => - this._emscripten.ccall(name, returnType, argTypes as Emscripten.JSType[], args as Emscripten.TypeCompatibleWithC[]) + this.emscripten.ccall(name, returnType, argTypes as Emscripten.JSType[], args as Emscripten.TypeCompatibleWithC[]) } return (...args: any[]) => { @@ -743,7 +758,7 @@ export default class LuaModule { } else { // because it will be freed later, this can only be used on functions that lua internally copies the string if (args[i]?.length > 1024) { - const bufferPointer = this._emscripten.stringToNewUTF8(args[i] as string) + const bufferPointer = this.emscripten.stringToNewUTF8(args[i] as string) args[i] = bufferPointer pointersToBeFreed.push(bufferPointer) return 'number' @@ -756,10 +771,10 @@ export default class LuaModule { }) try { - return this._emscripten.ccall(name, returnType, resolvedArgTypes, args as Emscripten.TypeCompatibleWithC[]) + return this.emscripten.ccall(name, returnType, resolvedArgTypes, args as Emscripten.TypeCompatibleWithC[]) } finally { for (const pointer of pointersToBeFreed) { - this._emscripten._free(pointer) + this.emscripten._free(pointer) } } } diff --git a/src/runtime.ts b/src/runtime.ts index 30ca443..527a879 100755 --- a/src/runtime.ts +++ b/src/runtime.ts @@ -1,4 +1,4 @@ -import LuaModule, { type EmscriptenPath, type LuaModuleOptions } from './module' +import LuaModule, { type EmscriptenFS, type EmscriptenPath, type LuaModuleOptions } from './module' import LuaState from './state' import type { CreateStateOptions } from './types' @@ -41,21 +41,20 @@ export default class LuaRuntime { } /** - * Mounts a file in the Lua environment synchronously. + * Writes a file into the Lua environment, creating its directories as needed. * @param path - Path to the file in the Lua environment. * @param content - Content of the file to be mounted. */ public mountFile(path: string, content: string | ArrayBufferView): void { - const dirname = this.module._emscripten.PATH.dirname(path) - this.module._emscripten.FS.mkdirTree(dirname) - this.module._emscripten.FS.writeFile(path, content) + this.filesystem.mkdirTree(this.path.dirname(path)) + this.filesystem.writeFile(path, content) } - public get filesystem(): typeof this.module._emscripten.FS { - return this.module._emscripten.FS + public get filesystem(): EmscriptenFS { + return this.module.emscripten.FS } public get path(): EmscriptenPath { - return this.module._emscripten.PATH + return this.module.emscripten.PATH } } diff --git a/src/state.ts b/src/state.ts index a55c6d9..e1fccd8 100755 --- a/src/state.ts +++ b/src/state.ts @@ -20,8 +20,8 @@ import { } from './types' /** - * Memory accounting for a state created with `{ memory: { trace: true } }`. On a state without - * tracing `state.memory` is undefined, so the absence is a type error rather than a runtime one. + * Memory accounting for a state created with `memory.trace` or `memory.max`. Without either + * `state.memory` is undefined, so the absence is a type error rather than a runtime one. */ export interface LuaMemory { /** Bytes currently allocated by this state. */ @@ -58,20 +58,18 @@ interface CreatedState { * of the constructor body rather than branching around `super()` twice. */ function createAddress(cmodule: LuaModule, memory: LuaMemoryOptions | undefined): CreatedState { - if (!memory?.trace) { - if (memory?.max !== undefined) { - throw new Error('memory.max requires memory.trace to be enabled') - } + // A cap can only be enforced by the tracing allocator, so asking for one asks for tracing. + if (!memory?.trace && memory?.max === undefined) { return { address: cmodule.luaL_newstate() } } const stats = { used: 0, max: memory.max } - const allocatorFunctionPointer = cmodule._emscripten.addFunction( + const allocatorFunctionPointer = cmodule.emscripten.addFunction( (_userData: number, pointer: number, oldSize: number, newSize: number): number => { if (newSize === 0) { if (pointer) { stats.used -= oldSize - cmodule._emscripten._free(pointer) + cmodule.emscripten._free(pointer) } return 0 } @@ -83,7 +81,7 @@ function createAddress(cmodule: LuaModule, memory: LuaMemoryOptions | undefined) return 0 } - const reallocated = cmodule._emscripten._realloc(pointer, newSize) + const reallocated = cmodule.emscripten._realloc(pointer, newSize) if (reallocated) { stats.used = endMemory } @@ -98,8 +96,14 @@ function createAddress(cmodule: LuaModule, memory: LuaMemoryOptions | undefined) ((Date.now() >>> 0) ^ Math.floor(Math.random() * 0x100000000)) >>> 0, ) if (!address) { - cmodule._emscripten.removeFunction(allocatorFunctionPointer) - throw new Error('lua_newstate returned a null pointer') + cmodule.emscripten.removeFunction(allocatorFunctionPointer) + // A cap the state cannot even be built under is the overwhelmingly likely cause, and it is + // the one thing the caller can act on. + throw new Error( + memory.max === undefined + ? 'lua_newstate returned a null pointer' + : `a memory.max of ${memory.max} bytes is too small to create a Lua state`, + ) } return { address, memory: stats, allocatorFunctionPointer } @@ -112,7 +116,7 @@ function createAddress(cmodule: LuaModule, memory: LuaMemoryOptions | undefined) * does not affect the others. */ export default class LuaState extends Thread { - /** Present only when the state was created with `{ memory: { trace: true } }`. */ + /** Present only when the state was created with `memory.trace` or `memory.max`. */ public readonly memory: LuaMemory | undefined private readonly allocatorFunctionPointer: number | undefined @@ -159,7 +163,7 @@ export default class LuaState extends Thread { const libraryMask = resolveLibraryMask(libs) if (libraryMask !== 0) { - this.lua.luaL_openselectedlibs(this.address, libraryMask, 0) + this.module.luaL_openselectedlibs(this.address, libraryMask, 0) } this.defaultMaxInstructions = limits?.maxInstructions @@ -210,7 +214,7 @@ export default class LuaState extends Thread { /** Retrieves the value of a global variable. */ public get(name: string): T { - const type = this.lua.lua_getglobal(this.address, name) + const type = this.module.lua_getglobal(this.address, name) const value = this.getValue(-1, type) this.pop() return value @@ -219,12 +223,12 @@ export default class LuaState extends Thread { /** Sets the value of a global variable. */ public set(name: string, value: unknown): void { this.pushValue(value) - this.lua.lua_setglobal(this.address, name) + this.module.lua_setglobal(this.address, name) } public getTable(name: string, callback: (index: number) => void): void { const startStackTop = this.getTop() - const type = this.lua.lua_getglobal(this.address, name) + const type = this.module.lua_getglobal(this.address, name) try { if (type !== LuaType.Table) { throw new TypeError(`Unexpected type in ${name}. Expected ${LuaType[LuaType.Table]}. Got ${LuaType[type]}.`) @@ -256,10 +260,10 @@ export default class LuaState extends Thread { // Here rather than in the threads because you don't // actually close threads, just pop them. Only the top-level // lua state needs closing. - this.lua.lua_close(this.address) + this.module.lua_close(this.address) if (this.allocatorFunctionPointer) { - this.lua._emscripten.removeFunction(this.allocatorFunctionPointer) + this.module.emscripten.removeFunction(this.allocatorFunctionPointer) } for (const wrapper of this.typeExtensions) { @@ -296,7 +300,7 @@ export default class LuaState extends Thread { private async callByteCode(loader: (thread: Thread) => void, options?: LuaRunOptions): Promise { const thread = this.newThread() // Move the thread off the global stack and into the registry as a GC anchor so it doesn't pile threads up into the stack - const ref = this.lua.luaL_ref(this.address, LUA_REGISTRYINDEX) + const ref = this.module.luaL_ref(this.address, LUA_REGISTRYINDEX) try { // Seeded from the state so a state wide setLimits reaches the async path too, which // runs on a child thread rather than on the state itself. @@ -305,7 +309,7 @@ export default class LuaState extends Thread { return (await thread.run(0, options))[0] } finally { thread.close() - this.lua.luaL_unref(this.address, LUA_REGISTRYINDEX, ref) + this.module.luaL_unref(this.address, LUA_REGISTRYINDEX, ref) } } } diff --git a/src/thread.ts b/src/thread.ts index b49c346..dcac9ee 100755 --- a/src/thread.ts +++ b/src/thread.ts @@ -40,8 +40,9 @@ const NO_RESTORE = (): void => undefined export default class Thread { public readonly address: LuaAddress - public readonly lua: LuaModule - /** Set on the root state; threads created from it delegate here. */ + /** The raw bindings, shared by every state and thread on the same runtime. */ + public readonly module: LuaModule + /** Set on the root state; threads created from it delegate here, as does {@link warn}. */ public onWarn: LuaWarnHandler | undefined protected readonly typeExtensions: OrderedExtension[] protected readonly parent: Thread | undefined @@ -51,75 +52,75 @@ export default class Thread { private limits: LuaThreadLimits = {} private instructionsUsed = 0 - public constructor(lua: LuaModule, typeExtensions: OrderedExtension[], address: number, parent?: Thread) { - this.lua = lua + public constructor(cmodule: LuaModule, typeExtensions: OrderedExtension[], address: number, parent?: Thread) { + this.module = cmodule this.typeExtensions = typeExtensions this.address = address this.parent = parent } public newThread(): Thread { - const address = this.lua.lua_newthread(this.address) + const address = this.module.lua_newthread(this.address) if (!address) { throw new Error('lua_newthread returned a null pointer') } - return new Thread(this.lua, this.typeExtensions, address, this.parent || this) + return new Thread(this.module, this.typeExtensions, address, this.parent || this) } public resetThread(): void { - this.assertOk(this.lua.lua_resetthread(this.address)) + this.assertOk(this.module.lua_resetthread(this.address)) } /** @param options.mode defaults to `'t'`. See {@link LuaLoadOptions.mode}. */ public loadString(luaCode: string, options?: LuaLoadOptions): void { - const size = this.lua._emscripten.lengthBytesUTF8(luaCode) + const size = this.module.emscripten.lengthBytesUTF8(luaCode) const pointerSize = size + 1 - const bufferPointer = this.lua._emscripten._malloc(pointerSize) + const bufferPointer = this.module.emscripten._malloc(pointerSize) try { - this.lua._emscripten.stringToUTF8(luaCode, bufferPointer, pointerSize) + this.module.emscripten.stringToUTF8(luaCode, bufferPointer, pointerSize) this.assertOk( - this.lua.luaL_loadbufferx(this.address, bufferPointer, size, options?.name ?? bufferPointer, options?.mode ?? 't'), + this.module.luaL_loadbufferx(this.address, bufferPointer, size, options?.name ?? bufferPointer, options?.mode ?? 't'), ) } finally { - this.lua._emscripten._free(bufferPointer) + this.module.emscripten._free(bufferPointer) } } /** @param options.mode defaults to `'t'`. See {@link LuaLoadOptions.mode}. */ public loadFile(filename: string, options?: LuaLoadOptions): void { - this.assertOk(this.lua.luaL_loadfilex(this.address, filename, options?.mode ?? 't')) + this.assertOk(this.module.luaL_loadfilex(this.address, filename, options?.mode ?? 't')) } public resume(argCount = 0): LuaResumeResult { - const dataPointer = this.lua._emscripten._malloc(PointerSize) + const dataPointer = this.module.emscripten._malloc(PointerSize) try { - this.lua._emscripten.setValue(dataPointer, 0, 'i32') - const luaResult = this.lua.lua_resume(this.address, null, argCount, dataPointer) + this.module.emscripten.setValue(dataPointer, 0, 'i32') + const luaResult = this.module.lua_resume(this.address, null, argCount, dataPointer) return { result: luaResult, - resultCount: this.lua._emscripten.getValue(dataPointer, 'i32'), + resultCount: this.module.emscripten.getValue(dataPointer, 'i32'), } } finally { - this.lua._emscripten._free(dataPointer) + this.module.emscripten._free(dataPointer) } } public getTop(): number { - return this.lua.lua_gettop(this.address) + return this.module.lua_gettop(this.address) } public setTop(index: number): void { - this.lua.lua_settop(this.address, index) + this.module.lua_settop(this.address, index) } public remove(index: number): void { - return this.lua.lua_remove(this.address, index) + return this.module.lua_remove(this.address, index) } public setField(index: number, name: string, value: unknown): void { - index = this.lua.lua_absindex(this.address, index) + index = this.module.lua_absindex(this.address, index) this.pushValue(value) - this.lua.lua_setfield(this.address, index, name) + this.module.lua_setfield(this.address, index, name) } public async run(argCount = 0, options?: LuaRunOptions): Promise { @@ -173,7 +174,7 @@ export default class Thread { const restore = this.applyRunOptions(options) try { const base = this.getTop() - argCount - 1 // The 1 is for the function to run - this.assertOk(this.lua.lua_pcallk(this.address, argCount, LUA_MULTRET, 0, 0, null)) + this.assertOk(this.module.lua_pcallk(this.address, argCount, LUA_MULTRET, 0, 0, null)) return this.getStackValues(base) } finally { restore() @@ -181,13 +182,13 @@ export default class Thread { } public pop(count = 1): void { - this.lua.lua_pop(this.address, count) + this.module.lua_pop(this.address, count) } public call(name: string, ...args: any[]): MultiReturn { - const type = this.lua.lua_getglobal(this.address, name) + const type = this.module.lua_getglobal(this.address, name) if (type !== LuaType.Function) { - throw new Error(`A function of type '${type}' was pushed, expected is ${LuaType.Function}`) + throw new TypeError(`cannot call '${name}': expected a function, got ${LuaType[type]}`) } for (const arg of args) { @@ -195,7 +196,7 @@ export default class Thread { } const base = this.getTop() - args.length - 1 // The 1 is for the function to run - this.lua.lua_callk(this.address, args.length, LUA_MULTRET, 0, null) + this.module.lua_callk(this.address, args.length, LUA_MULTRET, 0, null) return this.getStackValues(base) } @@ -211,7 +212,7 @@ export default class Thread { } public stateToThread(L: LuaAddress): Thread { - return L === this.parent?.address ? this.parent : new Thread(this.lua, this.typeExtensions, L, this.parent || this) + return L === this.parent?.address ? this.parent : new Thread(this.module, this.typeExtensions, L, this.parent || this) } public pushValue(rawValue: unknown, cache?: LuaPushCache): void { @@ -219,9 +220,9 @@ export default class Thread { const target = decoratedValue.target if (target instanceof Thread) { - const isMain = this.lua.lua_pushthread(target.address) === 1 + const isMain = this.module.lua_pushthread(target.address) === 1 if (!isMain) { - this.lua.lua_xmove(target.address, this.address, 1) + this.module.lua_xmove(target.address, this.address, 1) } return } @@ -231,35 +232,35 @@ export default class Thread { // Handle primitive types switch (typeof target) { case 'undefined': - this.lua.lua_pushnil(this.address) + this.module.lua_pushnil(this.address) break case 'number': // Only integers JS can represent exactly become Lua integers. Values like 1e300 // are integral but far outside int64, and would wrap silently if pushed as one. if (Number.isSafeInteger(target)) { - this.lua.lua_pushinteger(this.address, BigInt(target)) + this.module.lua_pushinteger(this.address, BigInt(target)) } else { - this.lua.lua_pushnumber(this.address, target) + this.module.lua_pushnumber(this.address, target) } break case 'bigint': if (BigInt.asIntN(LUA_INTEGER_BITS, target) !== target) { throw new RangeError(`bigint ${target} does not fit in a 64 bit Lua integer`) } - this.lua.lua_pushinteger(this.address, target) + this.module.lua_pushinteger(this.address, target) break case 'string': - this.lua.lua_pushstring(this.address, target) + this.module.lua_pushstring(this.address, target) break case 'boolean': - this.lua.lua_pushboolean(this.address, target ? 1 : 0) + this.module.lua_pushboolean(this.address, target ? 1 : 0) break default: if (this.typeExtensions.find((wrapper) => wrapper.extension.pushValue(this, decoratedValue, cache))) { break } if (target === null) { - this.lua.lua_pushnil(this.address) + this.module.lua_pushnil(this.address) break } throw new Error(`The type '${typeof target}' is not supported by Lua`) @@ -275,20 +276,20 @@ export default class Thread { } public setMetatable(index: number, metatable: LuaMetatable): void { - index = this.lua.lua_absindex(this.address, index) + index = this.module.lua_absindex(this.address, index) - if (this.lua.lua_getmetatable(this.address, index)) { + if (this.module.lua_getmetatable(this.address, index)) { this.pop(1) const name = this.getMetatableName(index) throw new Error(`data already has associated metatable: ${name || 'unknown name'}`) } this.pushValue(metatable) - this.lua.lua_setmetatable(this.address, index) + this.module.lua_setmetatable(this.address, index) } public getMetatableName(index: number): string | undefined { - const metatableNameType = this.lua.luaL_getmetafield(this.address, index, '__name') + const metatableNameType = this.module.luaL_getmetafield(this.address, index, '__name') if (metatableNameType === LuaType.Nil) { return undefined } @@ -299,7 +300,7 @@ export default class Thread { return undefined } - const name = this.lua.lua_tolstring(this.address, -1, null) + const name = this.module.lua_tolstring(this.address, -1, null) // This is popping the luaL_getmetafield result which only pushes with type is not nil. this.pop(1) @@ -307,9 +308,9 @@ export default class Thread { } public getValue(index: number, inputType?: LuaType, cache?: LuaGetCache): any { - index = this.lua.lua_absindex(this.address, index) + index = this.module.lua_absindex(this.address, index) - const type: LuaType = inputType ?? this.lua.lua_type(this.address, index) + const type: LuaType = inputType ?? this.module.lua_type(this.address, index) switch (type) { case LuaType.None: @@ -317,20 +318,20 @@ export default class Thread { case LuaType.Nil: return null case LuaType.Number: { - const value = this.lua.lua_tonumberx(this.address, index, null) + const value = this.module.lua_tonumberx(this.address, index, null) // Only outside the safe range can the integer subtype change the result, and // checking that first keeps the common case to a single wasm call. - if (Number.isSafeInteger(value) || !this.lua.lua_isinteger(this.address, index)) { + if (Number.isSafeInteger(value) || !this.module.lua_isinteger(this.address, index)) { return value } - return this.lua.lua_tointegerx(this.address, index, null) + return this.module.lua_tointegerx(this.address, index, null) } case LuaType.String: - return this.lua.lua_tolstring(this.address, index, null) + return this.module.lua_tolstring(this.address, index, null) case LuaType.Boolean: - return Boolean(this.lua.lua_toboolean(this.address, index)) + return Boolean(this.module.lua_toboolean(this.address, index)) case LuaType.Thread: - return this.stateToThread(this.lua.lua_tothread(this.address, index)) + return this.stateToThread(this.module.lua_tothread(this.address, index)) default: { let metatableName: string | undefined if (type === LuaType.Table || type === LuaType.Userdata) { @@ -346,7 +347,7 @@ export default class Thread { // Handing back an opaque Pointer hid the failure until the value was used, and // it could not be pushed back into Lua anyway. - const typeName = this.lua.lua_typename(this.address, type) + const typeName = this.module.lua_typename(this.address, type) const withMetatable = metatableName ? ` with metatable '${metatableName}'` : '' throw new TypeError( `the Lua type '${typeName}'${withMetatable} has no JS representation; register a type ` + @@ -362,7 +363,7 @@ export default class Thread { } if (this.hookFunctionPointer) { - this.lua._emscripten.removeFunction(this.hookFunctionPointer) + this.module.emscripten.removeFunction(this.hookFunctionPointer) this.hookFunctionPointer = undefined } @@ -401,15 +402,19 @@ export default class Thread { return this.limits.deadline } - /** Diagnostics the library would otherwise have written straight to the console. */ + /** + * Diagnostics the library would otherwise have written straight to the console. Resolved on + * every call rather than snapshotted, so clearing a state's handler falls back to the + * runtime's rather than straight to the console. + */ public warn(message: string, cause?: unknown): void { const root = this.parent ?? this - ;(root.onWarn ?? defaultWarnHandler)(message, cause) + ;(root.onWarn ?? this.module.onWarn ?? defaultWarnHandler)(message, cause) } /** For identity checks on values JS cannot represent. */ public getPointer(index: number): LuaAddress { - return this.lua.lua_topointer(this.address, index) + return this.module.lua_topointer(this.address, index) } public isClosed(): boolean { @@ -417,7 +422,7 @@ export default class Thread { } public indexToString(index: number): string { - const str = this.lua.luaL_tolstring(this.address, index, null) + const str = this.module.luaL_tolstring(this.address, index, null) // Pops the string pushed by luaL_tolstring this.pop() return str @@ -430,19 +435,19 @@ export default class Thread { * @returns the bytes, or undefined if the value is neither a string nor a number. */ public getStringBytes(index: number): Uint8Array | undefined { - return this.lua.lua_tobytes(this.address, index) + return this.module.lua_tobytes(this.address, index) } public pushStringBytes(bytes: Uint8Array): void { - this.lua.lua_pushbytes(this.address, bytes) + this.module.lua_pushbytes(this.address, bytes) } public dumpStack(log = console.log): void { const top = this.getTop() for (let i = 1; i <= top; i++) { - const type = this.lua.lua_type(this.address, i) - const typename = this.lua.lua_typename(this.address, type) + const type = this.module.lua_type(this.address, i) + const typename = this.module.lua_typename(this.address, type) const pointer = this.getPointer(i) const name = this.indexToString(i) let value: unknown @@ -469,7 +474,7 @@ export default class Thread { if (this.getTop() > 0) { if (result === LuaReturn.ErrorMem) { // If there's no memory just do a normal to string. - luaMessage = this.lua.lua_tolstring(this.address, -1, null) + luaMessage = this.module.lua_tolstring(this.address, -1, null) } else { try { luaValue = this.getValue(-1) @@ -490,8 +495,8 @@ export default class Thread { let traceback: string | undefined if (result !== LuaReturn.ErrorMem) { try { - this.lua.luaL_traceback(this.address, this.address, null, 1) - const text = this.lua.lua_tolstring(this.address, -1, null) + this.module.luaL_traceback(this.address, this.address, null, 1) + const text = this.module.lua_tolstring(this.address, -1, null) if (text.trim() !== 'stack traceback:') { traceback = text } @@ -535,7 +540,7 @@ export default class Thread { private applyHook(): void { const { deadline, maxInstructions, signal } = this.limits if (deadline === undefined && maxInstructions === undefined && signal === undefined) { - this.lua.lua_sethook(this.address, null, 0, 0) + this.module.lua_sethook(this.address, null, 0, 0) return } @@ -544,18 +549,18 @@ export default class Thread { maxInstructions !== undefined ? Math.max(1, Math.min(INSTRUCTION_HOOK_COUNT, maxInstructions)) : INSTRUCTION_HOOK_COUNT if (!this.hookFunctionPointer) { - this.hookFunctionPointer = this.lua._emscripten.addFunction((): void => { + this.hookFunctionPointer = this.module.emscripten.addFunction((): void => { // Reads this.limits rather than closing over them, so a hook allocated for an // earlier configuration still honours the current one. const error = this.checkHookLimits() if (error) { this.pushValue(error) - this.lua.lua_error(this.address) + this.module.lua_error(this.address) } }, 'vii') } - this.lua.lua_sethook(this.address, this.hookFunctionPointer, LuaEventMasks.Count, this.hookCount) + this.module.lua_sethook(this.address, this.hookFunctionPointer, LuaEventMasks.Count, this.hookCount) } private checkHookLimits(): Error | undefined { diff --git a/src/type-extension.ts b/src/type-extension.ts index 95c1940..580bbf6 100644 --- a/src/type-extension.ts +++ b/src/type-extension.ts @@ -25,11 +25,11 @@ export default abstract class LuaTypeExtension { * pointer and has to release it with `removeFunction` in {@link close}. */ protected createGcFunction(): number { - return this.state.lua._emscripten.addFunction((calledL: LuaAddress) => { + return this.state.module.emscripten.addFunction((calledL: LuaAddress) => { // Throws a lua error which does a jump if it does not match. - const userDataPointer = this.state.lua.luaL_checkudata(calledL, 1, this.name) - const referencePointer = this.state.lua._emscripten.getValue(userDataPointer, '*') - this.state.lua.unref(referencePointer) + const userDataPointer = this.state.module.luaL_checkudata(calledL, 1, this.name) + const referencePointer = this.state.module.emscripten.getValue(userDataPointer, '*') + this.state.module.unref(referencePointer) return LuaReturn.Ok }, 'ii') @@ -37,12 +37,12 @@ export default abstract class LuaTypeExtension { // A base implementation that assumes user data serialisation public getValue(thread: Thread, index: number, _cache?: LuaGetCache): T { - const refUserdata = thread.lua.luaL_testudata(thread.address, index, this.name) + const refUserdata = thread.module.luaL_testudata(thread.address, index, this.name) if (!refUserdata) { throw new Error(`data does not have the expected metatable: ${this.name}`) } - const referencePointer = thread.lua._emscripten.getValue(refUserdata, '*') - return thread.lua.getRef(referencePointer) as T + const referencePointer = thread.module.emscripten.getValue(refUserdata, '*') + return thread.module.getRef(referencePointer) as T } // Return false if type not matched, otherwise true. This base method does not @@ -50,12 +50,12 @@ export default abstract class LuaTypeExtension { public pushValue(thread: Thread, decoratedValue: Decoration, _cache?: LuaPushCache): boolean { const { target } = decoratedValue - const pointer = thread.lua.ref(target) + const pointer = thread.module.ref(target) // 4 = size of pointer in wasm. - const userDataPointer = thread.lua.lua_newuserdatauv(thread.address, PointerSize, 0) - thread.lua._emscripten.setValue(userDataPointer, pointer, '*') + const userDataPointer = thread.module.lua_newuserdatauv(thread.address, PointerSize, 0) + thread.module.emscripten.setValue(userDataPointer, pointer, '*') - if (LuaType.Nil === thread.lua.luaL_getmetatable(thread.address, this.name)) { + if (LuaType.Nil === thread.module.luaL_getmetatable(thread.address, this.name)) { // Pop the pushed nil value and the user data. Don't need to unref because it's // already associated with the user data pointer. thread.pop(2) @@ -64,7 +64,7 @@ export default abstract class LuaTypeExtension { // Set as the metatable for the userdata. // -1 is the metatable, -2 is the user data. - thread.lua.lua_setmetatable(thread.address, -2) + thread.module.lua_setmetatable(thread.address, -2) return true } diff --git a/src/type-extensions/error.ts b/src/type-extensions/error.ts index 770ea15..82a374f 100644 --- a/src/type-extensions/error.ts +++ b/src/type-extensions/error.ts @@ -11,16 +11,16 @@ class ErrorTypeExtension extends TypeExtension { this.gcPointer = this.createGcFunction() - if (state.lua.luaL_newmetatable(state.address, this.name)) { - const metatableIndex = state.lua.lua_gettop(state.address) + if (state.module.luaL_newmetatable(state.address, this.name)) { + const metatableIndex = state.module.lua_gettop(state.address) // Mark it as uneditable - state.lua.lua_pushstring(state.address, 'protected metatable') - state.lua.lua_setfield(state.address, metatableIndex, '__metatable') + state.module.lua_pushstring(state.address, 'protected metatable') + state.module.lua_setfield(state.address, metatableIndex, '__metatable') // Add the gc function - state.lua.lua_pushcclosure(state.address, this.gcPointer, 0) - state.lua.lua_setfield(state.address, metatableIndex, '__gc') + state.module.lua_pushcclosure(state.address, this.gcPointer, 0) + state.module.lua_setfield(state.address, metatableIndex, '__gc') // Add an __index method that returns the message field state.pushValue((jsRefError: Error, key: unknown) => { @@ -29,7 +29,7 @@ class ErrorTypeExtension extends TypeExtension { } return null }) - state.lua.lua_setfield(state.address, metatableIndex, '__index') + state.module.lua_setfield(state.address, metatableIndex, '__index') // Add a tostring method that returns the message. state.pushValue((jsRefError: Error) => { @@ -37,10 +37,10 @@ class ErrorTypeExtension extends TypeExtension { // added. This fits better with Lua errors. return jsRefError.message }) - state.lua.lua_setfield(state.address, metatableIndex, '__tostring') + state.module.lua_setfield(state.address, metatableIndex, '__tostring') } // Pop the metatable from the stack. - state.lua.lua_pop(state.address, 1) + state.module.lua_pop(state.address, 1) if (injectObject) { // Lastly create a static Error constructor. @@ -68,7 +68,7 @@ class ErrorTypeExtension extends TypeExtension { } public close(): void { - this.state.lua._emscripten.removeFunction(this.gcPointer) + this.state.module.emscripten.removeFunction(this.gcPointer) } } diff --git a/src/type-extensions/function.ts b/src/type-extensions/function.ts index 1ed4a57..f7f0919 100644 --- a/src/type-extensions/function.ts +++ b/src/type-extensions/function.ts @@ -12,7 +12,7 @@ export type FunctionType = (...args: any[]) => Promise | any class FunctionTypeExtension extends TypeExtension { private readonly functionRegistry = new FinalizationRegistry((func: number) => { if (!this.state.isClosed()) { - this.state.lua.luaL_unref(this.state.address, LUA_REGISTRYINDEX, func) + this.state.module.luaL_unref(this.state.address, LUA_REGISTRYINDEX, func) } }) @@ -32,7 +32,7 @@ class FunctionTypeExtension extends TypeExtension { // even if the thread that called getValue() has been destroyed. this.callbackContext = state.newThread() // Pops it from the global stack but keeps it alive - this.callbackContextIndex = this.state.lua.luaL_ref(state.address, LUA_REGISTRYINDEX) + this.callbackContextIndex = this.state.module.luaL_ref(state.address, LUA_REGISTRYINDEX) if (!this.functionRegistry) { state.warn('FunctionTypeExtension: FinalizationRegistry not found. Memory leaks likely.') @@ -41,24 +41,24 @@ class FunctionTypeExtension extends TypeExtension { this.gcPointer = this.createGcFunction() // Creates metatable if it doesn't exist, always pushes it onto the stack. - if (state.lua.luaL_newmetatable(state.address, this.name)) { - state.lua.lua_pushstring(state.address, '__gc') - state.lua.lua_pushcclosure(state.address, this.gcPointer, 0) - state.lua.lua_settable(state.address, -3) - - state.lua.lua_pushstring(state.address, '__metatable') - state.lua.lua_pushstring(state.address, 'protected metatable') - state.lua.lua_settable(state.address, -3) + if (state.module.luaL_newmetatable(state.address, this.name)) { + state.module.lua_pushstring(state.address, '__gc') + state.module.lua_pushcclosure(state.address, this.gcPointer, 0) + state.module.lua_settable(state.address, -3) + + state.module.lua_pushstring(state.address, '__metatable') + state.module.lua_pushstring(state.address, 'protected metatable') + state.module.lua_settable(state.address, -3) } // Pop the metatable from the stack. - state.lua.lua_pop(state.address, 1) + state.module.lua_pop(state.address, 1) - this.functionWrapper = state.lua._emscripten.addFunction((calledL: LuaAddress) => { + this.functionWrapper = state.module.emscripten.addFunction((calledL: LuaAddress) => { const calledThread = state.stateToThread(calledL) - const refUserdata = state.lua.luaL_checkudata(calledL, state.lua.lua_upvalueindex(1), this.name) - const refPointer = state.lua._emscripten.getValue(refUserdata, '*') - const { target, options: decorationOptions } = state.lua.getRef(refPointer) as Decoration + const refUserdata = state.module.luaL_checkudata(calledL, state.module.lua_upvalueindex(1), this.name) + const refPointer = state.module.emscripten.getValue(refUserdata, '*') + const { target, options: decorationOptions } = state.module.getRef(refPointer) as Decoration const argsQuantity = calledThread.getTop() const args = [] @@ -99,18 +99,18 @@ class FunctionTypeExtension extends TypeExtension { throw err } calledThread.pushValue(err) - return calledThread.lua.lua_error(calledThread.address) + return calledThread.module.lua_error(calledThread.address) } }, 'ii') } public close(): void { - this.state.lua._emscripten.removeFunction(this.gcPointer) - this.state.lua._emscripten.removeFunction(this.functionWrapper) + this.state.module.emscripten.removeFunction(this.gcPointer) + this.state.module.emscripten.removeFunction(this.functionWrapper) // Doesn't destroy the Lua thread, just function pointers. this.callbackContext.close() // Destroy the Lua thread - this.callbackContext.lua.luaL_unref(this.callbackContext.address, LUA_REGISTRYINDEX, this.callbackContextIndex) + this.callbackContext.module.luaL_unref(this.callbackContext.address, LUA_REGISTRYINDEX, this.callbackContextIndex) } public isType(_thread: Thread, _index: number, type: LuaType): boolean { @@ -126,33 +126,33 @@ class FunctionTypeExtension extends TypeExtension { // function which stays solely in JS. The cfunction called from Lua is created at the top of the class // and it accesses the JS data through an upvalue. - const pointer = thread.lua.ref(decoration) + const pointer = thread.module.ref(decoration) // 4 = size of pointer in wasm. - const userDataPointer = thread.lua.lua_newuserdatauv(thread.address, PointerSize, 0) - thread.lua._emscripten.setValue(userDataPointer, pointer, '*') + const userDataPointer = thread.module.lua_newuserdatauv(thread.address, PointerSize, 0) + thread.module.emscripten.setValue(userDataPointer, pointer, '*') - if (LuaType.Nil === thread.lua.luaL_getmetatable(thread.address, this.name)) { + if (LuaType.Nil === thread.module.luaL_getmetatable(thread.address, this.name)) { // Pop the pushed userdata. thread.pop(1) - thread.lua.unref(pointer) + thread.module.unref(pointer) throw new Error(`metatable not found: ${this.name}`) } // Set as the metatable for the function. // -1 is the metatable, -2 is the userdata - thread.lua.lua_setmetatable(thread.address, -2) + thread.module.lua_setmetatable(thread.address, -2) // Pass 1 to associate the closure with the userdata, pops the userdata. - thread.lua.lua_pushcclosure(thread.address, this.functionWrapper, 1) + thread.module.lua_pushcclosure(thread.address, this.functionWrapper, 1) return true } public getValue(thread: Thread, index: number): FunctionType { // Create a copy of the function - thread.lua.lua_pushvalue(thread.address, index) + thread.module.lua_pushvalue(thread.address, index) // Create a reference to the function which pops it from the stack - const func = thread.lua.luaL_ref(thread.address, LUA_REGISTRYINDEX) + const func = thread.module.luaL_ref(thread.address, LUA_REGISTRYINDEX) const jsFunc = (...args: any[]): any => { // Calling a function would ideally be in the Lua context that's calling it. For example if the JS function @@ -170,12 +170,12 @@ class FunctionTypeExtension extends TypeExtension { // they can be left in inconsistent states. const callThread = this.callbackContext.newThread() try { - const internalType = callThread.lua.lua_rawgeti(callThread.address, LUA_REGISTRYINDEX, BigInt(func)) + const internalType = callThread.module.lua_rawgeti(callThread.address, LUA_REGISTRYINDEX, BigInt(func)) if (internalType !== LuaType.Function) { - const callMetafieldType = callThread.lua.luaL_getmetafield(callThread.address, -1, '__call') + const callMetafieldType = callThread.module.luaL_getmetafield(callThread.address, -1, '__call') callThread.pop() if (callMetafieldType !== LuaType.Function) { - throw new Error(`A value of type '${internalType}' was pushed but it is not callable`) + throw new TypeError(`cannot call a value of type ${LuaType[internalType]}: it has no __call metamethod`) } } @@ -187,7 +187,7 @@ class FunctionTypeExtension extends TypeExtension { callThread.setDeadline(Date.now() + this.functionTimeout) } - const status = callThread.lua.lua_pcallk(callThread.address, args.length, 1, 0, 0, null) + const status = callThread.module.lua_pcallk(callThread.address, args.length, 1, 0, 0, null) if (status === LuaReturn.Yield) { throw new Error('cannot yield in callbacks from javascript') } diff --git a/src/type-extensions/null.ts b/src/type-extensions/null.ts index d6f9c34..ea3453c 100644 --- a/src/type-extensions/null.ts +++ b/src/type-extensions/null.ts @@ -13,29 +13,29 @@ class NullTypeExtension extends TypeExtension { this.gcPointer = this.createGcFunction() - if (state.lua.luaL_newmetatable(state.address, this.name)) { - const metatableIndex = state.lua.lua_gettop(state.address) + if (state.module.luaL_newmetatable(state.address, this.name)) { + const metatableIndex = state.module.lua_gettop(state.address) // Mark it as uneditable - state.lua.lua_pushstring(state.address, 'protected metatable') - state.lua.lua_setfield(state.address, metatableIndex, '__metatable') + state.module.lua_pushstring(state.address, 'protected metatable') + state.module.lua_setfield(state.address, metatableIndex, '__metatable') // Add the gc function - state.lua.lua_pushcclosure(state.address, this.gcPointer, 0) - state.lua.lua_setfield(state.address, metatableIndex, '__gc') + state.module.lua_pushcclosure(state.address, this.gcPointer, 0) + state.module.lua_setfield(state.address, metatableIndex, '__gc') // Add an __index method that returns nothing. state.pushValue(() => null) - state.lua.lua_setfield(state.address, metatableIndex, '__index') + state.module.lua_setfield(state.address, metatableIndex, '__index') state.pushValue(() => 'null') - state.lua.lua_setfield(state.address, metatableIndex, '__tostring') + state.module.lua_setfield(state.address, metatableIndex, '__tostring') state.pushValue((self: unknown, other: unknown) => self === other) - state.lua.lua_setfield(state.address, metatableIndex, '__eq') + state.module.lua_setfield(state.address, metatableIndex, '__eq') } // Pop the metatable from the stack. - state.lua.lua_pop(state.address, 1) + state.module.lua_pop(state.address, 1) // Create a new table, this is unique and will be the "null" value by attaching the // metatable created above. The first argument is the target, the second options. @@ -43,14 +43,14 @@ class NullTypeExtension extends TypeExtension { // Lua code is free to reassign the `null` global, so marshalling anchors the sentinel in // the registry instead of looking it up by name. - state.lua.lua_pushvalue(state.address, -1) - this.nullReference = state.lua.luaL_ref(state.address, LUA_REGISTRYINDEX) + state.module.lua_pushvalue(state.address, -1) + this.nullReference = state.module.luaL_ref(state.address, LUA_REGISTRYINDEX) - state.lua.lua_setglobal(state.address, 'null') + state.module.lua_setglobal(state.address, 'null') } public getValue(thread: Thread, index: number): null { - const refUserData = thread.lua.luaL_testudata(thread.address, index, this.name) + const refUserData = thread.module.luaL_testudata(thread.address, index, this.name) if (!refUserData) { throw new Error(`data does not have the expected metatable: ${this.name}`) } @@ -61,12 +61,12 @@ class NullTypeExtension extends TypeExtension { if (decoration.target !== null) { return false } - thread.lua.lua_rawgeti(thread.address, LUA_REGISTRYINDEX, BigInt(this.nullReference)) + thread.module.lua_rawgeti(thread.address, LUA_REGISTRYINDEX, BigInt(this.nullReference)) return true } public close(): void { - this.state.lua._emscripten.removeFunction(this.gcPointer) + this.state.module.emscripten.removeFunction(this.gcPointer) } } diff --git a/src/type-extensions/promise.ts b/src/type-extensions/promise.ts index ad393bd..19b4605 100644 --- a/src/type-extensions/promise.ts +++ b/src/type-extensions/promise.ts @@ -16,16 +16,16 @@ class PromiseTypeExtension extends TypeExtension> { this.gcPointer = this.createGcFunction() - if (state.lua.luaL_newmetatable(state.address, this.name)) { - const metatableIndex = state.lua.lua_gettop(state.address) + if (state.module.luaL_newmetatable(state.address, this.name)) { + const metatableIndex = state.module.lua_gettop(state.address) // Mark it as uneditable - state.lua.lua_pushstring(state.address, 'protected metatable') - state.lua.lua_setfield(state.address, metatableIndex, '__metatable') + state.module.lua_pushstring(state.address, 'protected metatable') + state.module.lua_setfield(state.address, metatableIndex, '__metatable') // Add the gc function - state.lua.lua_pushcclosure(state.address, this.gcPointer, 0) - state.lua.lua_setfield(state.address, metatableIndex, '__gc') + state.module.lua_pushcclosure(state.address, this.gcPointer, 0) + state.module.lua_setfield(state.address, metatableIndex, '__gc') // A bare thenable reaches here too, and only `then` is guaranteed on one. Adopting it // into a real promise is what makes catch/finally/await work on it, and is a no-op for @@ -47,7 +47,7 @@ class PromiseTypeExtension extends TypeExtension> { // Asking Lua covers every non-resumable context, not just the main // thread: anything entered through lua_pcall cannot yield either. - if (!state.lua.lua_isyieldable(functionThread.address)) { + if (!state.module.lua_isyieldable(functionThread.address)) { throw new Error('cannot await in a thread that cannot yield, use doString instead of doStringSync') } @@ -62,7 +62,7 @@ class PromiseTypeExtension extends TypeExtension> { promiseResult = { status: 'rejected', value: err } }) - const continuance = this.state.lua._emscripten.addFunction((continuanceState: LuaAddress) => { + const continuance = this.state.module.emscripten.addFunction((continuanceState: LuaAddress) => { // If this yield has been called from within a coroutine and so manually resumed // then there may not yet be any results. In that case yield again. if (!promiseResult) { @@ -71,16 +71,16 @@ class PromiseTypeExtension extends TypeExtension> { // 0 because this is called between resumes so the first one should've // popped the promise before returning the result. This is true within // Lua's coroutine.resume too. - return state.lua.lua_yieldk(functionThread.address, 0, 0, continuance) + return state.module.lua_yieldk(functionThread.address, 0, 0, continuance) } - this.state.lua._emscripten.removeFunction(continuance) + this.state.module.emscripten.removeFunction(continuance) const continuanceThread = state.stateToThread(continuanceState) if (promiseResult.status === 'rejected') { continuanceThread.pushValue(promiseResult.value || new Error('promise rejected with no error')) - return this.state.lua.lua_error(continuanceState) + return this.state.module.lua_error(continuanceState) } if (promiseResult.value instanceof RawResult) { @@ -97,18 +97,18 @@ class PromiseTypeExtension extends TypeExtension> { }, 'iiii') functionThread.pushValue(awaitPromise) - return new RawResult(state.lua.lua_yieldk(functionThread.address, 1, 0, continuance)) + return new RawResult(state.module.lua_yieldk(functionThread.address, 1, 0, continuance)) }, { receiveThread: true }, ), }) - state.lua.lua_setfield(state.address, metatableIndex, '__index') + state.module.lua_setfield(state.address, metatableIndex, '__index') state.pushValue((self: Promise, other: Promise) => self === other) - state.lua.lua_setfield(state.address, metatableIndex, '__eq') + state.module.lua_setfield(state.address, metatableIndex, '__eq') } // Pop the metatable from the stack. - state.lua.lua_pop(state.address, 1) + state.module.lua_pop(state.address, 1) if (injectObject) { // Lastly create a static Promise constructor. @@ -127,7 +127,7 @@ class PromiseTypeExtension extends TypeExtension> { } public close(): void { - this.state.lua._emscripten.removeFunction(this.gcPointer) + this.state.module.emscripten.removeFunction(this.gcPointer) } public pushValue(thread: Thread, decoration: Decoration): boolean { diff --git a/src/type-extensions/proxy.ts b/src/type-extensions/proxy.ts index a059d18..2346aaa 100644 --- a/src/type-extensions/proxy.ts +++ b/src/type-extensions/proxy.ts @@ -14,16 +14,16 @@ class ProxyTypeExtension extends TypeExtension { this.gcPointer = this.createGcFunction() - if (state.lua.luaL_newmetatable(state.address, this.name)) { - const metatableIndex = state.lua.lua_gettop(state.address) + if (state.module.luaL_newmetatable(state.address, this.name)) { + const metatableIndex = state.module.lua_gettop(state.address) // Mark it as uneditable - state.lua.lua_pushstring(state.address, 'protected metatable') - state.lua.lua_setfield(state.address, metatableIndex, '__metatable') + state.module.lua_pushstring(state.address, 'protected metatable') + state.module.lua_setfield(state.address, metatableIndex, '__metatable') // Add the gc function - state.lua.lua_pushcclosure(state.address, this.gcPointer, 0) - state.lua.lua_setfield(state.address, metatableIndex, '__gc') + state.module.lua_pushcclosure(state.address, this.gcPointer, 0) + state.module.lua_setfield(state.address, metatableIndex, '__gc') state.pushValue((self: any, key: unknown) => { switch (typeof key) { @@ -46,7 +46,7 @@ class ProxyTypeExtension extends TypeExtension { return value }) - state.lua.lua_setfield(state.address, metatableIndex, '__index') + state.module.lua_setfield(state.address, metatableIndex, '__index') state.pushValue((self: any, key: unknown, value: any) => { switch (typeof key) { @@ -61,17 +61,17 @@ class ProxyTypeExtension extends TypeExtension { } self[key as string | number] = value }) - state.lua.lua_setfield(state.address, metatableIndex, '__newindex') + state.module.lua_setfield(state.address, metatableIndex, '__newindex') state.pushValue((self: any) => { return self.toString?.() ?? typeof self }) - state.lua.lua_setfield(state.address, metatableIndex, '__tostring') + state.module.lua_setfield(state.address, metatableIndex, '__tostring') state.pushValue((self: any) => { return self.length || 0 }) - state.lua.lua_setfield(state.address, metatableIndex, '__len') + state.module.lua_setfield(state.address, metatableIndex, '__len') state.pushValue((self: any) => { const keys = Object.getOwnPropertyNames(self) @@ -87,12 +87,12 @@ class ProxyTypeExtension extends TypeExtension { null, ) }) - state.lua.lua_setfield(state.address, metatableIndex, '__pairs') + state.module.lua_setfield(state.address, metatableIndex, '__pairs') state.pushValue((self: any, other: any) => { return self === other }) - state.lua.lua_setfield(state.address, metatableIndex, '__eq') + state.module.lua_setfield(state.address, metatableIndex, '__eq') state.pushValue((self: any, ...args: any[]) => { if (args[0] === self) { @@ -100,11 +100,11 @@ class ProxyTypeExtension extends TypeExtension { } return self(...args) }) - state.lua.lua_setfield(state.address, metatableIndex, '__call') + state.module.lua_setfield(state.address, metatableIndex, '__call') } // Pop the metatable from the stack. - state.lua.lua_pop(state.address, 1) + state.module.lua_pop(state.address, 1) } public isType(_thread: Thread, _index: number, type: LuaType, name?: string): boolean { @@ -113,9 +113,9 @@ class ProxyTypeExtension extends TypeExtension { } public getValue(thread: Thread, index: number): any { - const refUserdata = thread.lua.lua_touserdata(thread.address, index) - const referencePointer = thread.lua._emscripten.getValue(refUserdata, '*') - return thread.lua.getRef(referencePointer) + const refUserdata = thread.module.lua_touserdata(thread.address, index) + const referencePointer = thread.module.emscripten.getValue(refUserdata, '*') + return thread.module.getRef(referencePointer) } public pushValue(thread: Thread, decoratedValue: Decoration): boolean { @@ -153,7 +153,7 @@ class ProxyTypeExtension extends TypeExtension { } public close(): void { - this.state.lua._emscripten.removeFunction(this.gcPointer) + this.state.module.emscripten.removeFunction(this.gcPointer) } } diff --git a/src/type-extensions/table.ts b/src/type-extensions/table.ts index 2501735..3564020 100644 --- a/src/type-extensions/table.ts +++ b/src/type-extensions/table.ts @@ -22,7 +22,7 @@ class TableTypeExtension extends TypeExtension { public getValue(thread: Thread, index: number, cache?: LuaGetCache): TableType { // This is a map of Lua pointers to JS objects. const seenMap: LuaGetCache = cache ?? new Map() - const pointer = thread.lua.lua_topointer(thread.address, index) + const pointer = thread.module.lua_topointer(thread.address, index) let table = seenMap.get(pointer) as TableType | undefined if (!table) { @@ -47,7 +47,7 @@ class TableTypeExtension extends TypeExtension { const seenMap: LuaPushCache = cache ?? new Map() const existingReference = seenMap.get(target) if (existingReference !== undefined) { - thread.lua.lua_rawgeti(thread.address, LUA_REGISTRYINDEX, BigInt(existingReference)) + thread.module.lua_rawgeti(thread.address, LUA_REGISTRYINDEX, BigInt(existingReference)) return true } @@ -55,10 +55,10 @@ class TableTypeExtension extends TypeExtension { const tableIndex = thread.getTop() + 1 const createTable = (arrayCount: number, keyCount: number): void => { - thread.lua.lua_createtable(thread.address, arrayCount, keyCount) - const ref = thread.lua.luaL_ref(thread.address, LUA_REGISTRYINDEX) + thread.module.lua_createtable(thread.address, arrayCount, keyCount) + const ref = thread.module.luaL_ref(thread.address, LUA_REGISTRYINDEX) seenMap.set(target, ref) - thread.lua.lua_rawgeti(thread.address, LUA_REGISTRYINDEX, BigInt(ref)) + thread.module.lua_rawgeti(thread.address, LUA_REGISTRYINDEX, BigInt(ref)) } if (Array.isArray(target)) { @@ -67,7 +67,7 @@ class TableTypeExtension extends TypeExtension { for (let i = 0; i < target.length; i++) { thread.pushValue(target[i], seenMap) // Raw, so the table being built cannot be observed through metamethods. - thread.lua.lua_rawseti(thread.address, tableIndex, BigInt(i + 1)) + thread.module.lua_rawseti(thread.address, tableIndex, BigInt(i + 1)) } } else { // A for..in loop would also walk the prototype chain and copy inherited members. @@ -78,14 +78,14 @@ class TableTypeExtension extends TypeExtension { thread.pushValue(key, seenMap) thread.pushValue((target as Record)[key], seenMap) - thread.lua.lua_rawset(thread.address, tableIndex) + thread.module.lua_rawset(thread.address, tableIndex) } } } finally { // Only the outermost push owns the anchors it created for the values below it. if (cache === undefined) { for (const reference of seenMap.values()) { - thread.lua.luaL_unref(thread.address, LUA_REGISTRYINDEX, reference) + thread.module.luaL_unref(thread.address, LUA_REGISTRYINDEX, reference) } } } @@ -96,8 +96,8 @@ class TableTypeExtension extends TypeExtension { private readTableKeys(thread: Thread, index: number): string[] { const keys = [] - thread.lua.lua_pushnil(thread.address) - while (thread.lua.lua_next(thread.address, index)) { + thread.module.lua_pushnil(thread.address) + while (thread.module.lua_next(thread.address, index)) { // JS only supports string keys in objects. const key = thread.indexToString(-2) keys.push(key) @@ -111,8 +111,8 @@ class TableTypeExtension extends TypeExtension { private readTableValues(thread: Thread, index: number, seenMap: LuaGetCache, table: TableType): void { const isArray = Array.isArray(table) - thread.lua.lua_pushnil(thread.address) - while (thread.lua.lua_next(thread.address, index)) { + thread.module.lua_pushnil(thread.address) + while (thread.module.lua_next(thread.address, index)) { const key = thread.indexToString(-2) const value = thread.getValue(-1, undefined, seenMap) diff --git a/src/type-extensions/userdata.ts b/src/type-extensions/userdata.ts index 3d83d16..1e9cae3 100644 --- a/src/type-extensions/userdata.ts +++ b/src/type-extensions/userdata.ts @@ -12,20 +12,20 @@ class UserdataTypeExtension extends TypeExtension { this.gcPointer = this.createGcFunction() - if (state.lua.luaL_newmetatable(state.address, this.name)) { - const metatableIndex = state.lua.lua_gettop(state.address) + if (state.module.luaL_newmetatable(state.address, this.name)) { + const metatableIndex = state.module.lua_gettop(state.address) // Mark it as uneditable - state.lua.lua_pushstring(state.address, 'protected metatable') - state.lua.lua_setfield(state.address, metatableIndex, '__metatable') + state.module.lua_pushstring(state.address, 'protected metatable') + state.module.lua_setfield(state.address, metatableIndex, '__metatable') // Add the gc function - state.lua.lua_pushcclosure(state.address, this.gcPointer, 0) - state.lua.lua_setfield(state.address, metatableIndex, '__gc') + state.module.lua_pushcclosure(state.address, this.gcPointer, 0) + state.module.lua_setfield(state.address, metatableIndex, '__gc') } // Pop the metatable from the stack. - state.lua.lua_pop(state.address, 1) + state.module.lua_pop(state.address, 1) } public isType(_thread: Thread, _index: number, type: LuaType, name?: string): boolean { @@ -33,9 +33,9 @@ class UserdataTypeExtension extends TypeExtension { } public getValue(thread: Thread, index: number): any { - const refUserdata = thread.lua.lua_touserdata(thread.address, index) - const referencePointer = thread.lua._emscripten.getValue(refUserdata, '*') - return thread.lua.getRef(referencePointer) + const refUserdata = thread.module.lua_touserdata(thread.address, index) + const referencePointer = thread.module.emscripten.getValue(refUserdata, '*') + return thread.module.getRef(referencePointer) } public pushValue(thread: Thread, decoratedValue: Decoration): boolean { @@ -47,7 +47,7 @@ class UserdataTypeExtension extends TypeExtension { } public close(): void { - this.state.lua._emscripten.removeFunction(this.gcPointer) + this.state.module.emscripten.removeFunction(this.gcPointer) } } diff --git a/src/types.ts b/src/types.ts index abccc7b..9278754 100755 --- a/src/types.ts +++ b/src/types.ts @@ -49,7 +49,7 @@ export function resolveLibraryMask(libs: LuaLibName[] | boolean | undefined): nu for (const lib of libs) { const bit = LUA_LIB_BITS[lib] if (bit === undefined) { - throw new Error(`unknown Lua library: ${String(lib)}`) + throw new Error(`unknown Lua library '${String(lib)}', expected one of: ${Object.keys(LUA_LIB_BITS).join(', ')}`) } mask |= bit } @@ -61,11 +61,11 @@ export type LuaLoadMode = 't' | 'bt' export interface LuaMemoryOptions { /** - * Installs a custom allocator so memory can be measured and capped. Without it `state.memory` - * is undefined. + * Installs a custom allocator so memory can be measured through `state.memory`, which is + * undefined on a state that has neither this nor `max`. */ trace?: boolean | undefined - /** Maximum bytes the state may allocate. Requires `trace`. */ + /** Maximum bytes the state may allocate. Implies `trace`, since the allocator enforces it. */ max?: number | undefined } @@ -96,7 +96,7 @@ export interface CreateStateOptions { inject?: boolean | undefined memory?: LuaMemoryOptions | undefined limits?: LuaLimitOptions | undefined - /** Where diagnostics go. Defaults to `console.warn`. */ + /** Where diagnostics go. Defaults to the runtime's handler, and then to `console.warn`. */ onWarn?: LuaWarnHandler | undefined } diff --git a/test/api.test.js b/test/api.test.js index 6d7ba51..e557538 100644 --- a/test/api.test.js +++ b/test/api.test.js @@ -108,18 +108,18 @@ describe('Custom type extensions', () => { super(state, 'js_point') this.gcPointer = this.createGcFunction() - if (state.lua.luaL_newmetatable(state.address, this.name)) { - const metatableIndex = state.lua.lua_gettop(state.address) - state.lua.lua_pushcclosure(state.address, this.gcPointer, 0) - state.lua.lua_setfield(state.address, metatableIndex, '__gc') + if (state.module.luaL_newmetatable(state.address, this.name)) { + const metatableIndex = state.module.lua_gettop(state.address) + state.module.lua_pushcclosure(state.address, this.gcPointer, 0) + state.module.lua_setfield(state.address, metatableIndex, '__gc') state.pushValue((point) => `Point(${point.x})`) - state.lua.lua_setfield(state.address, metatableIndex, '__tostring') + state.module.lua_setfield(state.address, metatableIndex, '__tostring') } - state.lua.lua_pop(state.address, 1) + state.module.lua_pop(state.address, 1) } close() { - this.state.lua._emscripten.removeFunction(this.gcPointer) + this.state.module.emscripten.removeFunction(this.gcPointer) } pushValue(thread, decoration) { @@ -204,7 +204,7 @@ describe('Thread lifecycle', () => { it('indexToString should call __tostring when there is one', async () => { using state = await getState() state.set('thing', decorate({}, { metatable: { __tostring: () => 'rendered' } })) - state.lua.lua_getglobal(state.address, 'thing') + state.module.lua_getglobal(state.address, 'thing') expect(state.indexToString(-1)).to.be.equal('rendered') diff --git a/test/errors.test.js b/test/errors.test.js index f82b69c..9a7b19a 100644 --- a/test/errors.test.js +++ b/test/errors.test.js @@ -119,7 +119,7 @@ describe('Unrepresentable values', () => { it('getValue throws instead of returning an opaque handle', async () => { using state = await getState() const thread = state.newThread() - thread.lua.lua_newuserdatauv(thread.address, 4, 0) + thread.module.lua_newuserdatauv(thread.address, 4, 0) expect(() => thread.getValue(-1)).to.throw('has no JS representation') }) @@ -127,7 +127,7 @@ describe('Unrepresentable values', () => { it('the address is still reachable through getPointer', async () => { using state = await getState() const thread = state.newThread() - thread.lua.lua_newuserdatauv(thread.address, 4, 0) + thread.module.lua_newuserdatauv(thread.address, 4, 0) expect(thread.getPointer(-1)).to.be.greaterThan(0) }) @@ -141,7 +141,7 @@ describe('Warnings', () => { state.getTable('_G', () => { // Leaves the stack unbalanced on purpose. - state.lua.lua_pushnil(state.address) + state.module.lua_pushnil(state.address) }) expect(seen).to.have.lengthOf(1) diff --git a/test/initialization.test.js b/test/initialization.test.js index 4aca780..46cf787 100644 --- a/test/initialization.test.js +++ b/test/initialization.test.js @@ -1,4 +1,4 @@ -import { LuaRuntime } from '../dist/index.js' +import { LUA_LIB_BITS, LuaRuntime } from '../dist/index.js' import { expect } from 'chai' describe('Initialization', () => { @@ -102,10 +102,11 @@ describe('Standard libraries', () => { } }) - it('an unknown library name is rejected', async () => { + it('an unknown library name is rejected, naming the valid ones', async () => { const lua = await LuaRuntime.load() - expect(() => lua.createState({ libs: ['nope'] })).to.throw('unknown Lua library: nope') + expect(() => lua.createState({ libs: ['nope'] })).to.throw("unknown Lua library 'nope'") + expect(() => lua.createState({ libs: ['nope'] })).to.throw(Object.keys(LUA_LIB_BITS).join(', ')) }) }) diff --git a/test/state.test.js b/test/state.test.js index 92decdd..8fc1c08 100644 --- a/test/state.test.js +++ b/test/state.test.js @@ -364,7 +364,7 @@ describe('State', () => { }) `) - state.lua.lua_getglobal(state.address, 'sum') + state.module.lua_getglobal(state.address, 'sum') const sum = state.getValue(-1, LuaType.Function) expect(sum(10, 30)).to.be.equal(40) @@ -622,8 +622,8 @@ describe('State', () => { using state = await getState() const obj = {} state.set('obj', obj) - const refIndex = state.lua.getLastRefIndex() - const oldRef = state.lua.getRef(refIndex) + const refIndex = state.module.getLastRefIndex() + const oldRef = state.module.getRef(refIndex) await state.doString(` local weaktable = {} @@ -635,7 +635,7 @@ describe('State', () => { `) expect(oldRef).to.be.equal(obj) - const newRef = state.lua.getRef(refIndex) + const newRef = state.module.getRef(refIndex) expect(newRef).to.be.equal(undefined) }) @@ -788,7 +788,7 @@ describe('State', () => { using state = await getState() await state.doString('value = string.char(0, 255, 128, 65)') - state.lua.lua_getglobal(state.address, 'value') + state.module.lua_getglobal(state.address, 'value') const bytes = state.getStringBytes(-1) state.pop() @@ -808,12 +808,12 @@ describe('State', () => { using state = await getState() await state.doString('bytecode = string.dump(load("return 42"))') - state.lua.lua_getglobal(state.address, 'bytecode') + state.module.lua_getglobal(state.address, 'bytecode') const bytes = state.getStringBytes(-1) state.pop() state.pushStringBytes(bytes) - state.lua.lua_setglobal(state.address, 'roundtripped') + state.module.lua_setglobal(state.address, 'roundtripped') expect(await state.doString('return load(roundtripped)()')).to.be.equal(42) }) @@ -870,14 +870,14 @@ describe('State', () => { using state = await getState() const value = 9223372036854775807n - state.lua.lua_pushinteger(state.address, value) - state.lua.lua_setglobal(state.address, 'value') + state.module.lua_pushinteger(state.address, value) + state.module.lua_setglobal(state.address, 'value') const asString = await state.doString(`return tostring(value)`) const asFormatted = await state.doString(`return ("%d"):format(value)`) - state.lua.lua_getglobal(state.address, 'value') - const roundTrip = state.lua.lua_tointegerx(state.address, -1, null) + state.module.lua_getglobal(state.address, 'value') + const roundTrip = state.module.lua_tointegerx(state.address, -1, null) state.pop() expect(asString).to.be.equal('9223372036854775807') @@ -1192,10 +1192,19 @@ describe('Decoration', () => { }) describe('Memory', () => { - it('memory.max rejects without tracing', async () => { + it('memory.max turns tracing on by itself', async () => { const lua = await getLua() + using state = lua.createState({ memory: { max: 4 * 1024 * 1024 } }) - expect(() => lua.createState({ memory: { max: 1000 } })).to.throw('requires memory.trace') + expect(state.memory).to.not.be.undefined + expect(state.memory.max).to.be.equal(4 * 1024 * 1024) + expect(state.memory.used).to.be.greaterThan(0) + }) + + it('a max too small to hold a state is reported as such', async () => { + const lua = await getLua() + + expect(() => lua.createState({ memory: { max: 1000 } })).to.throw('memory.max of 1000 bytes') }) it('memory is a live view', async () => { diff --git a/utils/reference-types.js b/utils/reference-types.js new file mode 100644 index 0000000..4fd1fc1 --- /dev/null +++ b/utils/reference-types.js @@ -0,0 +1,17 @@ +// The public declarations use `@types/emscripten`'s ambient globals (EmscriptenModule, FS, +// Emscripten.*). Those only resolve for a consumer whose own tsconfig happens to list +// "emscripten" in `types`, which nothing about depending on wasmoon makes them do -- so without +// this the published .d.ts fails to compile under, say, `"types": ["node"]`. +// +// A `/// ` in the entry declaration pulls the package in for everyone. +// It has to be added here rather than written in the source, because tsc drops the directive on +// its way through declaration emit. +import { readFile, writeFile } from 'node:fs/promises' + +const ENTRY = 'dist/index.d.ts' +const DIRECTIVE = '/// ' + +const contents = await readFile(ENTRY, 'utf8') +if (!contents.startsWith(DIRECTIVE)) { + await writeFile(ENTRY, `${DIRECTIVE}\n${contents}`) +} From d15a105b6ccfdbc560049173cee61b248dca0be9 Mon Sep 17 00:00:00 2001 From: Gabriel Francisco Date: Tue, 28 Jul 2026 23:41:46 -0300 Subject: [PATCH 46/83] fix some cli unparity with official lua cli --- bin/wasmoon | 501 +++++++++++++++++++++++++++++------------------ test/cli.test.js | 237 ++++++++++++++++------ 2 files changed, 479 insertions(+), 259 deletions(-) diff --git a/bin/wasmoon b/bin/wasmoon index b80cf70..e3f754b 100755 --- a/bin/wasmoon +++ b/bin/wasmoon @@ -1,13 +1,21 @@ #!/usr/bin/env node -import { LuaRuntime, LuaReturn, LuaType, LUA_MULTRET, decorate } from '../dist/index.js' +import { LuaRuntime, LuaReturn, LuaType, LUA_MULTRET, LuaError } from '../dist/index.js' import pkg from '../package.json' with { type: 'json' } import fs from 'node:fs' import readline from 'node:readline' +// Prefixes diagnostics, the way the standalone interpreter prefixes them with its own argv[0]. +const PROGNAME = 'wasmoon' + +/** An argument the interpreter could not make sense of, which is reported with the usage text. */ +class UsageError extends Error {} + function printUsage() { - console.log( + // Diagnostics go to stderr, as they do in the reference implementation, so a caller piping the + // interpreter's output never has to filter them out. + console.error( ` -usage: wasmoon [options] [script [args]] +usage: ${PROGNAME} [options] [script [args]] Available options are: -e stat execute string 'stat' -i enter interactive mode after executing 'script' @@ -20,143 +28,143 @@ Available options are: - stop handling options and execute stdin `.trim(), ) - process.exit(1) } -function parseArgs(args) { - const executeSnippets = [] - const includeModules = [] +/** + * @param argv the interpreter name followed by its arguments, mirroring the reference + * interpreter's argv so `arg` can be built with the same offsets. + */ +function parseArgs(argv) { + // -e, -l and -W all run in the order they were given, so they share one list. + const actions = [] let forceInteractive = false - let warnings = false - let ignoreEnv = false let showVersion = false - let scriptFile = null + let ignoreEnv = false + // Index into argv of the script name, or 0 for no script, as in the reference implementation. + let scriptIndex = 0 + // A '-' script means stdin, unless it came after '--', which makes it an ordinary file name. + let scriptIsStdin = false - const outArgs = [] + for (let i = 1; i < argv.length; i++) { + const arg = argv[i] - let i = 0 - for (; i < args.length; i++) { - const arg = args[i] + if (!arg.startsWith('-')) { + scriptIndex = i + break + } - if (arg === '--') { - i++ + if (arg === '-') { + scriptIndex = i + scriptIsStdin = true break } - if (arg.startsWith('-') && arg.length > 1) { - switch (arg) { - case '-v': - showVersion = true - break - case '-W': - warnings = true - break - case '-E': - ignoreEnv = true - break - case '-i': - forceInteractive = true - break - case '-e': - i++ - if (i >= args.length) { - console.error('Missing argument after -e') - printUsage() - } - executeSnippets.push(args[i]) - break - case '-l': - i++ - if (i >= args.length) { - console.error('Missing argument after -l') - printUsage() - } - includeModules.push(args[i]) - break - case '-': - scriptFile = '-' - i++ - break - default: - console.log(`unrecognized option: '${arg}'`) - printUsage() - break - } - } else { - scriptFile = arg - i++ + if (arg === '--') { + // Whatever follows is the script, even when it looks like an option. + scriptIndex = i + 1 < argv.length ? i + 1 : 0 break } - } - outArgs.push(...args.slice(i)) - - return { - executeSnippets, - includeModules, - forceInteractive, - warnings, - showVersion, - scriptFile, - scriptArgs: outArgs, - ignoreEnv, + switch (arg) { + case '-v': + showVersion = true + break + case '-W': + actions.push({ type: 'W' }) + break + case '-E': + ignoreEnv = true + break + case '-i': + forceInteractive = true + break + case '-e': + case '-l': + i++ + if (i >= argv.length) { + throw new UsageError(`Missing argument after ${arg}`) + } + actions.push({ type: arg[1], value: argv[i] }) + break + default: + throw new UsageError(`unrecognized option: '${arg}'`) + } } + + return { argv, actions, forceInteractive, showVersion, ignoreEnv, scriptIndex, scriptIsStdin } } -const { executeSnippets, includeModules, ignoreEnv, forceInteractive, warnings, showVersion, scriptFile, scriptArgs } = parseArgs( - process.argv.slice(2), -) +// os.exit unwinds by throwing rather than returning, so its status has to be picked back up here. +const isExitStatus = (err) => Boolean(err) && err.name === 'ExitStatus' && typeof err.status === 'number' + +/** + * Reports the way the reference implementation does: the message goes to stderr behind the program + * name, and the interpreter stops with a failing status. + */ +function reportError(err) { + if (err instanceof UsageError) { + console.error(err.message) + printUsage() + return + } -// When running interactively, process.stdin is used by readline. -// To allow Lua’s io.read to work (even in interactive mode), we open -// a separate file descriptor to the terminal (e.g. '/dev/tty' on Unix). -let inputFD = 0 -if (process.stdin.isTTY) { - try { - inputFD = fs.openSync('/dev/tty', 'r') - } catch { - // If opening /dev/tty fails (or on non-Unix systems), fallback to fd 0. - inputFD = 0 + process.stderr.write(`${PROGNAME}: ${err instanceof LuaError ? err.luaMessage : (err?.message ?? String(err))}\n`) + if (err instanceof LuaError && err.traceback) { + process.stderr.write(`${err.traceback}\n`) } } -// Created only for the REPL: an open interface holds process.stdin in flowing mode, which both -// steals the bytes io.read is after and keeps the process alive after a script is done. -let rl = null -// Lua's io.read and the REPL share the terminal, so they can't be listening at the same time. -const pauseReadline = () => rl && !rl.closed && rl.pause() -const resumeReadline = () => rl && !rl.closed && rl.resume() - -// Bytes read past the end of a line: a single read can return more than one line, and dropping -// the remainder would lose input. -const inputChunk = Buffer.alloc(1024) -let pendingLength = 0 -let pendingOffset = 0 -// Set when a line ended on CR, so the LF of a CRLF pair doesn't start an empty line. -let skipLineFeed = false - -// Reading ahead in raw mode would strand whatever the user typed past the end of the line in here, -// where the REPL (which reads process.stdin) can never see it. -const refillInputChunk = (isRaw) => { - try { - pendingLength = fs.readSync(inputFD, inputChunk, 0, isRaw ? 1 : inputChunk.length) - } catch (err) { - // Both mean "nothing more right now", which for a blocking read is the end of the input. - if (err.code !== 'EOF' && err.code !== 'EAGAIN') { - throw err +/** + * Reads lines from the terminal for Lua's own io.read, which cannot share process.stdin with the + * REPL: an open readline interface holds it in flowing mode and would steal the bytes io.read is + * after. Owns the interface too, so the two take turns rather than listening at once. + */ +function createTerminalInput() { + // When running interactively, process.stdin is used by readline. + // To allow Lua’s io.read to work (even in interactive mode), we open + // a separate file descriptor to the terminal (e.g. '/dev/tty' on Unix). + let inputFD = 0 + if (process.stdin.isTTY) { + try { + inputFD = fs.openSync('/dev/tty', 'r') + } catch { + // If opening /dev/tty fails (or on non-Unix systems), fallback to fd 0. + inputFD = 0 } - pendingLength = 0 } - pendingOffset = 0 - return pendingLength > 0 -} -const lua = await LuaRuntime.load({ - env: ignoreEnv ? undefined : process.env, - fs: 'node', - stdin: () => { + // Created only for the REPL: an open interface also keeps the process alive after a script is done. + let rl = null + + // Bytes read past the end of a line: a single read can return more than one line, and dropping + // the remainder would lose input. + const inputChunk = Buffer.alloc(1024) + let pendingLength = 0 + let pendingOffset = 0 + // Set when a line ended on CR, so the LF of a CRLF pair doesn't start an empty line. + let skipLineFeed = false + + // Reading ahead in raw mode would strand whatever the user typed past the end of the line in here, + // where the REPL (which reads process.stdin) can never see it. + const refillInputChunk = (isRaw) => { + try { + pendingLength = fs.readSync(inputFD, inputChunk, 0, isRaw ? 1 : inputChunk.length) + } catch (err) { + // Both mean "nothing more right now", which for a blocking read is the end of the input. + if (err.code !== 'EOF' && err.code !== 'EAGAIN') { + throw err + } + pendingLength = 0 + } + pendingOffset = 0 + return pendingLength > 0 + } + + const readLine = () => { try { - pauseReadline() + if (rl && !rl.closed) { + rl.pause() + } // Raw mode is what the REPL puts the terminal in, and it comes with no echo and no // line editing, so both have to be done by hand. Any other input already has them. @@ -193,13 +201,15 @@ const lua = await LuaRuntime.load({ } if (isRaw) { - const echo = Buffer.from(line).toString('utf8') - // A character whose remaining bytes are still on their way would flash as a - // replacement character, so leave it for the next redraw. if (terminated) { process.stdout.write('\n') - } else if (!echo.endsWith('�')) { - process.stdout.write(`\x1b[2K\x1b[0G${echo}`) + } else { + const echo = Buffer.from(line).toString('utf8') + // A character whose remaining bytes are still on their way would flash as a + // replacement character, so leave it for the next redraw. + if (!echo.endsWith('�')) { + process.stdout.write(`\x1b[2K\x1b[0G${echo}`) + } } } } @@ -214,102 +224,201 @@ const lua = await LuaRuntime.load({ console.error(err) return '' } finally { - resumeReadline() + if (rl && !rl.closed) { + rl.resume() + } } - }, -}) + } -const state = lua.createState() + const openReadline = () => { + rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + terminal: true, + removeHistoryDuplicates: true, + prompt: '> ', + }) + return rl + } -if (showVersion) { - console.log(`wasmoon ${pkg.version} (${state.get('_VERSION')})`) - process.exit(0) + return { readLine, openReadline } } -if (warnings) { - lua.module.lua_warning(state.address, '@on', 0) -} +async function repl(lua, state, terminal) { + // Bypass result verification for interactive mode + const loadcode = (code) => { + state.setTop(0) + return lua.module.luaL_loadstring(state.address, code) === LuaReturn.Ok + } -// Decorated as a value so `#arg` and `ipairs(arg)` behave like the standalone interpreter, and -// set before -l and -e run, as it does, so those can read it. -state.set('arg', decorate(scriptArgs, { as: 'value' })) + console.log(`Welcome to Wasmoon ${pkg.version} (${state.get('_VERSION')})`) + console.log('Type Lua code and press Enter to execute. Ctrl+C to exit.\n') -for (const module of includeModules) { - let [global, mod] = module.split('=') - if (!mod) { - mod = global - } - const require = state.get('require') - state.set(global, require(mod)) -} + const rl = terminal.openReadline() -for (const snippet of executeSnippets) { - await state.doString(snippet) -} + try { + rl.prompt() -const isTTY = process.stdin.isTTY -const hasProgram = Boolean(scriptFile) || executeSnippets.length > 0 + for await (const line of rl) { + // try to load (compile) it first as an expression (return ) and second as a statement + const loaded = loadcode(`return ${line}`) || loadcode(line) + if (!loaded) { + // Failed to parse + const err = state.getValue(-1, LuaType.String) + console.log(err) + rl.prompt() + continue + } + + const result = lua.module.lua_pcallk(state.address, 0, LUA_MULTRET, 0, 0, null) + if (result === LuaReturn.Ok) { + const count = state.getTop() + if (count > 0) { + const returnValues = [] + for (let i = 1; i <= count; i++) { + returnValues.push(state.indexToString(i)) + } + console.log(...returnValues) + } + } else { + console.log(state.getValue(-1, LuaType.String)) + } -if (scriptFile === '-') { - const input = fs.readFileSync(0, 'utf-8') - await state.doString(input) -} else if (scriptFile) { - await state.doFile(scriptFile) + rl.prompt() + } + } finally { + // os.exit inside the REPL leaves the interface holding stdin open, which would keep the + // process alive long after the code it was running asked to end it. + rl.close() + process.stdin.pause() + } } -const shouldInteractive = isTTY && (forceInteractive || !hasProgram) -if (shouldInteractive) { - // Bypass result verification for interactive mode - const loadcode = (code) => { - state.setTop(0) - return lua.module.luaL_loadstring(state.address, code) === LuaReturn.Ok +/** + * Builds the global 'arg' the way 'createargtable' does, aligned on the script name so it sits at + * index 0, the arguments meant for it at positive indices and everything that came before it at + * negative ones. Filled through the raw bindings because no JS value maps to those indices. + */ +function setArgTable(state, argv, scriptIndex) { + const { module, address } = state + + module.lua_createtable(address, Math.max(argv.length - scriptIndex - 1, 0), scriptIndex + 1) + for (let i = 0; i < argv.length; i++) { + module.lua_pushstring(address, argv[i]) + module.lua_rawseti(address, -2, BigInt(i - scriptIndex)) } + module.lua_setglobal(address, 'arg') +} - const version = pkg.version - const luaversion = state.get('_VERSION') - console.log(`Welcome to Wasmoon ${version} (${luaversion})`) - console.log('Type Lua code and press Enter to execute. Ctrl+C to exit.\n') +/** + * Runs `globname = require(modname)` for a '-l' option, entirely inside Lua so the global ends up + * holding the very table 'package.loaded' has rather than a copy of it. + */ +function doLibrary(state, spec) { + const { module, address } = state + const separator = spec.indexOf('=') + const global = separator === -1 ? spec : spec.slice(0, separator) + const mod = separator === -1 ? spec : spec.slice(separator + 1) + + module.lua_getglobal(address, 'require') + module.lua_pushstring(address, mod) + state.assertOk(module.lua_pcallk(address, 1, 1, 0, 0, null)) + module.lua_setglobal(address, global) +} + +async function run({ argv, actions, forceInteractive, showVersion, ignoreEnv, scriptIndex, scriptIsStdin }) { + const terminal = createTerminalInput() - rl = readline.createInterface({ - input: process.stdin, - output: process.stdout, - terminal: true, - removeHistoryDuplicates: true, - prompt: '> ', + const lua = await LuaRuntime.load({ + env: ignoreEnv ? undefined : process.env, + fs: 'node', + stdin: terminal.readLine, }) - rl.prompt() - - for await (const line of rl) { - // try to load (compile) it first as an expression (return ) and second as a statement - const loaded = loadcode(`return ${line}`) || loadcode(line) - if (!loaded) { - // Failed to parse - const err = state.getValue(-1, LuaType.String) - console.log(err) - rl.prompt() - continue + + const state = lua.createState() + + // Unlike the other options, -v does not stop the interpreter: the reference implementation + // prints the version and carries on with whatever else was asked for. + if (showVersion) { + console.log(`${PROGNAME} ${pkg.version} (${state.get('_VERSION')})`) + } + + setArgTable(state, argv, scriptIndex) + + for (const action of actions) { + switch (action.type) { + case 'W': + lua.module.lua_warning(state.address, '@on', 0) + break + case 'l': + doLibrary(state, action.value) + break + case 'e': + await state.doString(action.value, { name: '=(command line)' }) + break } + } - const result = lua.module.lua_pcallk(state.address, 0, LUA_MULTRET, 0, 0, null) - if (result === LuaReturn.Ok) { - const count = state.getTop() - if (count > 0) { - const returnValues = [] - for (let i = 1; i <= count; i++) { - returnValues.push(state.indexToString(i)) - } - console.log(...returnValues) + const hasScript = scriptIndex > 0 + const hasSnippet = actions.some((action) => action.type === 'e') + // Only a named script is called with arguments. Stdin falling in as the program when nothing + // else was named is run bare, as the reference implementation runs it. + const scriptArgs = hasScript ? argv.slice(scriptIndex + 1) : [] + + // doString and doFile call the chunk with no arguments, and the reference implementation hands + // the script everything in 'arg', so the chunk is loaded and resumed here instead. A thread of + // its own is what those two do as well, and it is what lets the script await. + const runScript = async (load) => { + // newThread leaves the thread on the state's stack, which is what keeps it from being + // collected while it runs. + const stackTop = state.getTop() + const thread = state.newThread() + try { + thread.setLimits(state.getLimits()) + load(thread) + for (const scriptArg of scriptArgs) { + thread.pushValue(scriptArg) } + await thread.run(scriptArgs.length) + } finally { + thread.close() + state.setTop(stackTop) + } + } + + // Reading stdin to EOF and loading it as one chunk is what 'luaL_loadfile(L, NULL)' does. + const runStdin = () => runScript((thread) => thread.loadString(fs.readFileSync(0, 'utf-8'), { name: '=stdin' })) + + if (hasScript) { + await (scriptIsStdin ? runStdin() : runScript((thread) => thread.loadFile(argv[scriptIndex]))) + } + + const isTTY = process.stdin.isTTY + + if (forceInteractive) { + if (isTTY) { + await repl(lua, state, terminal) + } + } else if (!hasScript && !hasSnippet && !showVersion) { + // Nothing to run was named, so stdin is the program. On a terminal that means the REPL, + // and anywhere else it is a script read to EOF. + if (isTTY) { + await repl(lua, state, terminal) } else { - console.log(state.getValue(-1, LuaType.String)) + await runStdin() } + } +} - rl.prompt() +try { + // The interpreter's own argv, the first entry being its name, so 'arg' can be built with the + // same offsets the reference implementation uses. + await run(parseArgs([process.argv[1], ...process.argv.slice(2)])) +} catch (err) { + if (isExitStatus(err)) { + process.exitCode = err.status + } else { + reportError(err) + process.exitCode = 1 } -} else if (!hasProgram) { - // If we're not interactive, and we did NOT run a file or any -e snippet, - // read from stdin until EOF. (Non-TTY or no -i, no file). - // With -e, stdin belongs to the script, as in the standalone interpreter. - const input = fs.readFileSync(0, 'utf-8') - await state.doString(input) } diff --git a/test/cli.test.js b/test/cli.test.js index 6b491f6..736ca71 100644 --- a/test/cli.test.js +++ b/test/cli.test.js @@ -29,6 +29,16 @@ const runCli = (args, { input, ...options } = {}) => { }) } +// For the runs that are expected to succeed, which is most of them: the only interesting part is +// what reached stdout. +const runOk = async (args, options) => { + const { code, stdout, stderr } = await runCli(args, options) + + expect(stderr, 'stderr').to.be.empty + expect(code, 'exit code').to.be.equal(0) + return stdout +} + describe('CLI', function () { this.timeout(30_000) @@ -42,95 +52,126 @@ describe('CLI', function () { rmSync(tempDir, { recursive: true, force: true }) }) + const writeScript = (name, body) => { + const path = join(tempDir, name) + writeFileSync(path, body) + return path + } + describe('scripts and snippets', () => { // Covers the single snippet case too, which is why there is no separate test for it. it('should run several -e snippets in order', async () => { - const { code, stdout, stderr } = await runCli(['-e', 'print("first")', '-e', 'print("second")']) - - expect(stderr).to.be.empty - expect(code).to.be.equal(0) - expect(stdout).to.be.equal('first\nsecond\n') + expect(await runOk(['-e', 'print("first")', '-e', 'print("second")'])).to.be.equal('first\nsecond\n') }) it('should run a script file', async () => { - const script = join(tempDir, 'hello.lua') - writeFileSync(script, 'print("from file")') + const script = writeScript('hello.lua', 'print("from file")') - const { code, stdout } = await runCli([script]) - - expect(code).to.be.equal(0) - expect(stdout).to.be.equal('from file\n') + expect(await runOk([script])).to.be.equal('from file\n') }) it('should run a script piped to stdin', async () => { - const { code, stdout } = await runCli([], { input: 'print("from bare stdin")\n' }) - - expect(code).to.be.equal(0) - expect(stdout).to.be.equal('from bare stdin\n') + expect(await runOk([], { input: 'print("from bare stdin")\n' })).to.be.equal('from bare stdin\n') }) it('should run a script piped to stdin when given -', async () => { - const { code, stdout } = await runCli(['-'], { input: 'print("from dash")\n' }) - - expect(code).to.be.equal(0) - expect(stdout).to.be.equal('from dash\n') + expect(await runOk(['-'], { input: 'print("from dash")\n' })).to.be.equal('from dash\n') }) }) describe('arg table', () => { it('should expose arg as a lua table to a script', async () => { - const script = join(tempDir, 'args.lua') - writeFileSync(script, 'print(type(arg), #arg, arg[1], arg[2], table.concat(arg, "+"))') + const script = writeScript('args.lua', 'print(type(arg), #arg, arg[1], arg[2], table.concat(arg, "+"))') - const { code, stdout, stderr } = await runCli([script, 'first', 'second']) + const stdout = await runOk([script, 'first', 'second']) - expect(stderr).to.be.empty - expect(code).to.be.equal(0) expect(stdout.trim()).to.be.equal('table\t2\tfirst\tsecond\tfirst+second') }) - // arg used to be built after the -e loop ran, so a snippet saw a nil global. - it('should expose arg to a -e snippet', async () => { - const { code, stdout, stderr } = await runCli(['-e', 'print(type(arg), #arg)']) + // The table is aligned on the script name, so it sits at index 0 with the interpreter and + // the options that came before it at negative indices. + it('should align arg on the script name', async () => { + const script = writeScript('align.lua', 'print(arg[0], arg[-1], arg[-2])') - expect(stderr).to.be.empty - expect(code).to.be.equal(0) - expect(stdout.trim()).to.be.equal('table\t0') + const stdout = await runOk(['-e', '', script]) + + expect(stdout.trim().split('\t')).to.deep.equal([script, '', '-e']) }) - it('should pass arguments after -- through to arg', async () => { - const { code, stdout, stderr } = await runCli(['-e', 'print(arg[1])', '--', '--notaflag']) + // Without a script the alignment falls back to the interpreter, which puts the options + // themselves at positive indices. + it('should align arg on the interpreter when there is no script', async () => { + const stdout = await runOk(['-e', 'print(type(arg), #arg, arg[1], arg[2])']) - expect(stderr).to.be.empty - expect(code).to.be.equal(0) - expect(stdout.trim()).to.be.equal('--notaflag') + expect(stdout.trim()).to.be.equal('table\t2\t-e\tprint(type(arg), #arg, arg[1], arg[2])') + }) + + it('should pass the script arguments to the script as varargs', async () => { + const script = writeScript('varargs.lua', 'print(...)') + + expect((await runOk([script, 'first', 'second'])).trim()).to.be.equal('first\tsecond') + }) + + it('should treat whatever follows -- as the script, even when it looks like an option', async () => { + const script = writeScript('-notaflag.lua', 'print("ran", ...)') + + expect((await runOk(['--', script, 'tail'])).trim()).to.be.equal('ran\ttail') + }) + + it('should run nothing but the options when -- ends the arguments', async () => { + expect(await runOk(['-e', 'print("only e")', '--'])).to.be.equal('only e\n') }) }) describe('options', () => { it('-v should report both versions', async () => { - const { code, stdout } = await runCli(['-v']) + const stdout = await runOk(['-v']) - expect(code).to.be.equal(0) expect(stdout.trim()).to.match(/^wasmoon \S+ \(Lua [\d.]+\)$/) expect(stdout).to.include(`wasmoon ${pkg.version} `) }) + // -v reports and carries on, rather than being a request to do nothing else. + it('-v should still run whatever else was asked for', async () => { + const stdout = await runOk(['-v', '-e', 'print("ran")']) + + expect(stdout.trim().split('\n')).to.have.lengthOf(2) + expect(stdout).to.match(/^wasmoon .*\nran\n$/) + }) + + // It still counts as something to do, so stdin is not read as a program on top of it. + it('-v alone should not run stdin', async () => { + expect(await runOk(['-v'], { input: 'print("should not run")\n' })).to.not.include('should not run') + }) + + it('should run -e and -l in the order they were given', async () => { + writeScript('noisy.lua', 'print("module") return {}') + + const [eFirst, lFirst] = await Promise.all([ + runOk(['-e', 'print("snippet")', '-l', 'noisy'], { cwd: tempDir }), + runOk(['-l', 'noisy', '-e', 'print("snippet")'], { cwd: tempDir }), + ]) + + expect(eFirst).to.be.equal('snippet\nmodule\n') + expect(lFirst).to.be.equal('module\nsnippet\n') + }) + + // The global has to hold the very table package.loaded does, not a copy of it. it('-l should require a module into a global of the same name', async () => { - writeFileSync(join(tempDir, 'mymod.lua'), 'return { v = 5 }') + writeScript('mymod.lua', 'return { v = 5 }') - const { code, stdout } = await runCli(['-l', 'mymod', '-e', 'print(mymod.v)'], { cwd: tempDir }) + const stdout = await runOk(['-l', 'mymod', '-e', 'print(mymod.v, type(mymod), mymod == package.loaded.mymod)'], { + cwd: tempDir, + }) - expect(code).to.be.equal(0) - expect(stdout.trim()).to.be.equal('5') + expect(stdout.trim()).to.be.equal('5\ttable\ttrue') }) it('-l g=mod should require a module into a renamed global', async () => { - writeFileSync(join(tempDir, 'mymod.lua'), 'return { v = 5 }') + writeScript('mymod.lua', 'return { v = 5 }') - const { code, stdout } = await runCli(['-l', 'g=mymod', '-e', 'print(g.v, mymod)'], { cwd: tempDir }) + const stdout = await runOk(['-l', 'g=mymod', '-e', 'print(g.v, mymod)'], { cwd: tempDir }) - expect(code).to.be.equal(0) expect(stdout.trim()).to.be.equal('5\tnil') }) @@ -138,20 +179,21 @@ describe('CLI', function () { const env = { ...process.env, WASMOON_CLI_TEST: 'secret' } const [withEnv, without] = await Promise.all([ - runCli(['-e', 'print(os.getenv("WASMOON_CLI_TEST"))'], { env }), - runCli(['-E', '-e', 'print(os.getenv("WASMOON_CLI_TEST"))'], { env }), + runOk(['-e', 'print(os.getenv("WASMOON_CLI_TEST"))'], { env }), + runOk(['-E', '-e', 'print(os.getenv("WASMOON_CLI_TEST"))'], { env }), ]) - expect(withEnv.stdout.trim()).to.be.equal('secret') - expect(without.stdout.trim()).to.be.equal('nil') + expect(withEnv.trim()).to.be.equal('secret') + expect(without.trim()).to.be.equal('nil') }) it('an unrecognized option should print usage and fail', async () => { - const { code, stdout } = await runCli(['-Z']) + const { code, stdout, stderr } = await runCli(['-Z']) expect(code).to.be.equal(1) - expect(stdout).to.include(`unrecognized option: '-Z'`) - expect(stdout).to.include('usage: wasmoon') + expect(stdout).to.be.empty + expect(stderr).to.include(`unrecognized option: '-Z'`) + expect(stderr).to.include('usage: wasmoon') }) it('a missing argument after -e should fail', async () => { @@ -162,31 +204,100 @@ describe('CLI', function () { }) }) + describe('errors', () => { + it('should report a runtime error with a traceback and fail', async () => { + const { code, stdout, stderr } = await runCli(['-e', 'error("boom")']) + + expect(code).to.be.equal(1) + expect(stdout).to.be.empty + expect(stderr).to.include('wasmoon: (command line):1: boom') + expect(stderr).to.include('stack traceback:') + // A Lua error is a diagnostic, not a crash of the interpreter itself. + expect(stderr).to.not.include('LuaError') + }) + + it('should report a script that cannot be opened without a traceback', async () => { + const missing = join(tempDir, 'missing.lua') + + const { code, stdout, stderr } = await runCli([missing]) + + expect(code).to.be.equal(1) + expect(stdout).to.be.empty + expect(stderr).to.include(`wasmoon: cannot open ${missing}`) + expect(stderr).to.not.include('stack traceback:') + }) + + it('should stop before the script when a -e snippet fails', async () => { + const script = writeScript('unreached.lua', 'print("unreached")') + + const { code, stdout } = await runCli(['-e', 'error("boom")', script]) + + expect(code).to.be.equal(1) + expect(stdout).to.be.empty + }) + + it('should report a failing -l without running the rest', async () => { + const { code, stdout, stderr } = await runCli(['-l', 'nosuchmodule', '-e', 'print("unreached")']) + + expect(code).to.be.equal(1) + expect(stdout).to.be.empty + expect(stderr).to.include("wasmoon: module 'nosuchmodule' not found") + }) + }) + + describe('os.exit', () => { + it('should exit with the status the script asked for', async () => { + const { code, stdout, stderr } = await runCli(['-e', 'print("bye") os.exit(3)']) + + expect(stderr).to.be.empty + expect(code).to.be.equal(3) + expect(stdout).to.be.equal('bye\n') + }) + + it('should treat a boolean status the way lua does', async () => { + const [ok, notOk] = await Promise.all([runCli(['-e', 'os.exit(true)']), runCli(['-e', 'os.exit(false)'])]) + + expect(ok.code).to.be.equal(0) + expect(notOk.code).to.be.equal(1) + expect(ok.stderr).to.be.empty + expect(notOk.stderr).to.be.empty + }) + + it('should exit successfully with no status', async () => { + const { code, stderr } = await runCli(['-e', 'os.exit()']) + + expect(stderr).to.be.empty + expect(code).to.be.equal(0) + }) + }) + describe('stdin', () => { it('should read piped input from within a script', async () => { - const { code, stdout, stderr } = await runCli(['-e', 'print(io.read("l")) print(io.read("l")) print(io.read("l") == nil)'], { + const stdout = await runOk(['-e', 'print(io.read("l")) print(io.read("l")) print(io.read("l") == nil)'], { input: 'olá mundo\nsegunda linha\n', }) - expect(stderr).to.be.empty - expect(code).to.be.equal(0) expect(stdout).to.be.equal('olá mundo\nsegunda linha\ntrue\n') }) it('should not add a line break to input that does not end with one', async () => { - const { code, stdout, stderr } = await runCli(['-e', 'print(#io.read("a"))'], { input: 'abc' }) + expect(await runOk(['-e', 'print(#io.read("a"))'], { input: 'abc' })).to.be.equal('3\n') + }) - expect(stderr).to.be.empty - expect(code).to.be.equal(0) - expect(stdout).to.be.equal('3\n') + // A named '-' is a script and is called like one; stdin falling in because nothing else was + // named is not, so the options in front of it are not arguments to it. + it('should only pass varargs to stdin when it was named with -', async () => { + const [named, fallback] = await Promise.all([ + runOk(['-', 'one', 'two'], { input: 'print("varargs:", ...)\n' }), + runOk(['-W'], { input: 'print("varargs:", ...)\n' }), + ]) + + expect(named.trim()).to.be.equal('varargs:\tone\ttwo') + expect(fallback.trim()).to.be.equal('varargs:') }) it('should not run piped input as a script when -e is given', async () => { - const { code, stdout, stderr } = await runCli(['-e', 'print("from -e")'], { input: 'this is not lua code\n' }) - - expect(stderr).to.be.empty - expect(code).to.be.equal(0) - expect(stdout).to.be.equal('from -e\n') + expect(await runOk(['-e', 'print("from -e")'], { input: 'this is not lua code\n' })).to.be.equal('from -e\n') }) }) }) From 8fea035c8f661d9e95f85ecf0ce485b56324245e Mon Sep 17 00:00:00 2001 From: Gabriel Francisco Date: Wed, 29 Jul 2026 08:22:49 -0300 Subject: [PATCH 47/83] perf --- bench/index.js | 5 + bench/interop.js | 136 ++++++++++++++ bench/utils.js | 6 +- rolldown.config.ts | 28 +++ src/module.ts | 304 +++++++++++++++++++++++++++++--- src/state.ts | 43 +++-- src/thread.ts | 122 +++++++------ src/type-extension.ts | 10 +- src/type-extensions/error.ts | 2 +- src/type-extensions/function.ts | 14 +- src/type-extensions/null.ts | 2 +- src/type-extensions/promise.ts | 6 +- src/type-extensions/proxy.ts | 4 +- src/type-extensions/table.ts | 35 ++-- src/type-extensions/userdata.ts | 4 +- utils/build-wasm.sh | 7 +- 16 files changed, 593 insertions(+), 135 deletions(-) create mode 100644 bench/interop.js diff --git a/bench/index.js b/bench/index.js index f2555a9..630b047 100644 --- a/bench/index.js +++ b/bench/index.js @@ -1,4 +1,5 @@ import { runComparisonBench } from './comparisons.js' +import { runInteropBench } from './interop.js' import { runStepBench } from './steps.js' import { parseBenchOptions, printArtifactSizes, printBenchUsage } from './utils.js' @@ -15,6 +16,10 @@ if (options.suite === 'all' || options.suite === 'steps') { await runStepBench(options) } +if (options.suite === 'all' || options.suite === 'interop') { + await runInteropBench(options) +} + if (options.suite === 'all' || options.suite === 'comparisons') { await runComparisonBench(options) } diff --git a/bench/interop.js b/bench/interop.js new file mode 100644 index 0000000..251a431 --- /dev/null +++ b/bench/interop.js @@ -0,0 +1,136 @@ +import { LuaRuntime } from '../dist/index.js' +import assert from 'node:assert/strict' +import { isMainModule, parseBenchOptions, runBenchmarks } from './utils.js' + +// Every bench here keeps its Lua work trivial so the timings are dominated by the JS side of the +// boundary: pushValue/getValue, the type extension lookup and the ccall wrappers around the C API. +const CALL_COUNT = 20000 +const TABLE_SIZE = 2000 + +function withState(lua, options, body) { + return () => { + const state = lua.createState(options) + try { + return body(state) + } finally { + state.close() + } + } +} + +function createGlobalRoundTripBenchmark(lua) { + return withState(lua, {}, (state) => { + for (let i = 0; i < CALL_COUNT; i++) { + state.set('value', i) + if (state.get('value') !== i) { + throw new Error('global round trip returned the wrong value') + } + } + }) +} + +// Both directions switch between an inline copy and the built in codecs by length, so the sizes +// on either side of those thresholds are measured rather than one arbitrary string. +function createStringRoundTripBenchmark(lua, length) { + const value = 'abcdefghij'.repeat(Math.ceil(length / 10)).slice(0, length) + return withState(lua, {}, (state) => { + for (let i = 0; i < CALL_COUNT; i++) { + state.set('value', value) + if (state.get('value') !== value) { + throw new Error('string round trip returned the wrong value') + } + } + }) +} + +function createCallLuaFromJsBenchmark(lua) { + return withState(lua, {}, (state) => { + state.doStringSync('function add(a, b) return a + b end') + const add = state.get('add') + let sum = 0 + for (let i = 0; i < CALL_COUNT; i++) { + sum += add(i, 1) + } + assert.equal(sum, (CALL_COUNT * (CALL_COUNT - 1)) / 2 + CALL_COUNT) + }) +} + +function createCallJsFromLuaBenchmark(lua) { + return withState(lua, {}, (state) => { + state.set('add', (a, b) => a + b) + const total = state.doStringSync(` + local sum = 0 + for i = 1, ${CALL_COUNT} do sum = sum + add(i, 1) end + return sum + `) + assert.equal(total, (CALL_COUNT * (CALL_COUNT + 1)) / 2 + CALL_COUNT) + }) +} + +function createReadTableBenchmark(lua) { + return withState(lua, { objects: 'copy' }, (state) => { + state.doStringSync(` + data = {} + for i = 1, ${TABLE_SIZE} do data[i] = { id = i, name = "item" .. i, active = i % 2 == 0 } end + `) + const data = state.get('data') + assert.equal(data.length, TABLE_SIZE) + }) +} + +function createPushTableBenchmark(lua) { + const data = Array.from({ length: TABLE_SIZE }, (_, index) => ({ + id: index, + name: `item${index}`, + active: index % 2 === 0, + })) + return withState(lua, { objects: 'copy' }, (state) => { + state.set('data', data) + }) +} + +function createProxyAccessBenchmark(lua) { + const data = { counter: 0, nested: { value: 1 } } + return withState(lua, {}, (state) => { + state.set('data', data) + const total = state.doStringSync(` + local sum = 0 + for i = 1, ${CALL_COUNT} do sum = sum + data.nested.value end + return sum + `) + assert.equal(total, CALL_COUNT) + }) +} + +function createDoStringBenchmark(lua) { + return withState(lua, {}, (state) => { + for (let i = 0; i < 200; i++) { + state.doStringSync('return 1 + 1') + } + }) +} + +export async function runInteropBench(options = {}) { + const lua = await LuaRuntime.load() + + return runBenchmarks({ + title: 'Interop benchmarks', + benches: [ + { name: 'Global round trip (number)', run: createGlobalRoundTripBenchmark(lua) }, + { name: 'Global round trip (string, 8)', run: createStringRoundTripBenchmark(lua, 8) }, + { name: 'Global round trip (string, 24)', run: createStringRoundTripBenchmark(lua, 24) }, + { name: 'Global round trip (string, 200)', run: createStringRoundTripBenchmark(lua, 200) }, + { name: 'Call Lua from JS', run: createCallLuaFromJsBenchmark(lua) }, + { name: 'Call JS from Lua', run: createCallJsFromLuaBenchmark(lua) }, + { name: 'Read table into JS', run: createReadTableBenchmark(lua) }, + { name: 'Push table into Lua', run: createPushTableBenchmark(lua) }, + { name: 'Proxy field access from Lua', run: createProxyAccessBenchmark(lua) }, + { name: 'doStringSync', run: createDoStringBenchmark(lua) }, + ], + options, + }) +} + +if (isMainModule(import.meta.url)) { + await runInteropBench(parseBenchOptions()) +} diff --git a/bench/utils.js b/bench/utils.js index 4c6c757..5804245 100644 --- a/bench/utils.js +++ b/bench/utils.js @@ -64,7 +64,7 @@ export function printBenchUsage() { Options: -i, --iterations Measured iterations per benchmark (default: ${DEFAULT_OPTIONS.iterations}) -w, --warmup Warmup iterations per benchmark (default: ${DEFAULT_OPTIONS.warmup}) - -s, --suite Which suite to run: all, steps, comparisons + -s, --suite Which suite to run: all, steps, interop, comparisons -f, --filter Only run benchmarks whose name includes the given text -h, --help Show this help message`) } @@ -221,8 +221,8 @@ function parseIntegerOption(rawValue, flagName, { min }) { function parseSuiteOption(rawValue, flagName) { const value = parseStringOption(rawValue, flagName) - if (!['all', 'comparisons', 'steps'].includes(value)) { - throw new Error(`${flagName} must be one of: all, comparisons, steps`) + if (!['all', 'comparisons', 'interop', 'steps'].includes(value)) { + throw new Error(`${flagName} must be one of: all, comparisons, interop, steps`) } return value } diff --git a/rolldown.config.ts b/rolldown.config.ts index d5cf55e..f6e553a 100644 --- a/rolldown.config.ts +++ b/rolldown.config.ts @@ -58,6 +58,34 @@ export default defineConfig({ return { code: annotated, map: null } }, }, + { + // The glue is generated and already minified onto one line, so carrying its 85 KB of + // source in the published sourcemap costs a tenth of the package to map frames nobody + // reads. The mappings stay, only the inlined copy of the file goes. + name: 'drop-glue-source-content', + generateBundle(_options, bundle) { + // Rewritten through the emitted asset rather than the written file, because + // `chunk.map` is a snapshot of the Rust side and mutating it does not carry over. + let dropped = false + for (const file of Object.values(bundle)) { + if (file.type !== 'asset' || !file.fileName.endsWith('.map')) { + continue + } + const map = JSON.parse(file.source as string) + const index = map.sources.findIndex((source: string) => source?.endsWith('glue.js')) + if (index < 0 || !map.sourcesContent?.[index]) { + continue + } + map.sourcesContent[index] = null + file.source = JSON.stringify(map) + dropped = true + } + if (!dropped) { + // A silent miss would quietly put the 85 KB back into every published package. + this.error('the glue source was not found in any sourcemap, so nothing was dropped') + } + }, + }, { name: 'copy-glue-wasm', async writeBundle() { diff --git a/src/module.ts b/src/module.ts index e359191..184cc2e 100755 --- a/src/module.ts +++ b/src/module.ts @@ -37,7 +37,12 @@ export interface LuaEmscriptenModule extends EmscriptenModule { stringToNewUTF8: typeof stringToNewUTF8 lengthBytesUTF8: typeof lengthBytesUTF8 stringToUTF8: typeof stringToUTF8 - UTF8ToString: typeof UTF8ToString + UTF8ToString: (ptr: number, maxBytesToRead?: number, ignoreNul?: boolean) => string + // The scratch space `ccall` uses for its own C string arguments. Unwound by stackRestore + // rather than freed, so it stays correct when a Lua error longjmps out of the call. + stringToUTF8OnStack: (str: string) => number + stackSave: () => number + stackRestore: (pointer: number) => void ENV: EnvironmentVariables _realloc: (pointer: number, size: number) => number } @@ -72,9 +77,9 @@ export interface LuaModuleOptions { onWarn?: LuaWarnHandler | undefined } -// One-shot conversions, so a single stateless pair is shared by every module. Streaming output -// keeps its own decoder in createOutputWriter. -const textDecoder = new TextDecoder() +// One-shot conversions, so a single stateless encoder is shared by every module. Decoding goes +// through Emscripten's UTF8ToString, and streaming output keeps its own decoder in +// createOutputWriter. const textEncoder = new TextEncoder() // Above this a dedicated allocation is used, so one huge string cannot permanently retain the @@ -83,6 +88,51 @@ const REUSABLE_STRING_BUFFER_LIMIT = 64 * 1024 // Worst case UTF-8 expansion for a JS (UTF-16) string. const MAX_UTF8_BYTES_PER_CHAR = 3 +// C string arguments are nearly always a fixed name -- a metatable name, '__name', a global or a +// table key -- so their encoded form is kept instead of being rebuilt on every call. Bounded in +// both directions because a caller can also index with arbitrary strings; past either bound the +// wasm stack is used the way ccall does it. +const C_STRING_CACHE_LIMIT = 512 +const C_STRING_CACHE_MAX_LENGTH = 128 + +// Above this, TextEncoder beats copying byte by byte in JS (measured; TEXTDECODER=1 covers the +// other direction upstream). +const INLINE_ENCODE_LIMIT = 40 + +// The wasm value types Emscripten's function signature letters map to. `p` is a pointer, which is +// an i32 in a build without MEMORY64. +const WASM_SIGNATURE_TYPES: Record = { i: 0x7f, p: 0x7f, j: 0x7e, f: 0x7d, d: 0x7c, e: 0x6f } + +function wasmType(signature: string, letter: string): number { + const type = WASM_SIGNATURE_TYPES[letter] + if (type === undefined) { + throw new Error(`unsupported wasm signature '${signature}': no type for '${letter}'`) + } + return type +} + +/** + * A wasm module exporting a single imported function unchanged, which is how a JS callback is + * given the wasm identity the indirect function table requires. See {@link LuaModule.addFunction}. + */ +function buildTrampolineModule(signature: string): WebAssembly.Module { + const parameters = [...signature.slice(1)].map((letter) => wasmType(signature, letter)) + const results = signature[0] === 'v' ? [] : [wasmType(signature, signature[0])] + // Every count below is written as one byte, which LEB128 agrees with under 128. + if (parameters.length > 0x7f) { + throw new Error(`unsupported wasm signature '${signature}': ${parameters.length} parameters`) + } + + // func type: params -> results + const functionType = [0x60, parameters.length, ...parameters, results.length, ...results] + const typeSection = [0x01, functionType.length + 1, 0x01, ...functionType] + // import "e"."f" as function 0, then export it as "f" + const importSection = [0x02, 0x07, 0x01, 0x01, 0x65, 0x01, 0x66, 0x00, 0x00] + const exportSection = [0x07, 0x05, 0x01, 0x01, 0x66, 0x00, 0x00] + + return new WebAssembly.Module(Uint8Array.from([0, 0x61, 0x73, 0x6d, 1, 0, 0, 0, ...typeSection, ...importSection, ...exportSection])) +} + interface ReferenceMetadata { index: number refCount: number @@ -380,6 +430,8 @@ export default class LuaModule { public luaopen_package: (L: LuaAddress) => number public luaL_openlibs: (L: LuaAddress) => void + private readonly cStringCache = new Map() + private readonly trampolineModules = new Map() private referenceTracker = new WeakMap() private referenceMap = new Map() private availableReferences: number[] = [] @@ -391,9 +443,11 @@ export default class LuaModule { private readonly rawLuaLToLString: (L: LuaAddress, idx: number, len: number) => number private readonly rawLuaPushString: (L: LuaAddress, s: number) => number - // C writes it immediately before returning and we read it straight after with no interleaving - // await, so a single shared slot stays reentrancy safe. + // C writes these immediately before returning and we read them straight after with no + // interleaving await, so a single shared slot each stays reentrancy safe. private readonly sizeScratch: number + /** The `nresults` out parameter for {@link lua_resume}, read by `Thread.resume`. */ + public readonly resultCountScratch: number private stringBuffer = 0 public constructor(module: LuaEmscriptenModule, onWarn?: LuaWarnHandler) { @@ -554,8 +608,9 @@ export default class LuaModule { this.lua_pushlstring = this.cwrap('lua_pushlstring', 'number', ['number', 'number', 'number']) this.sizeScratch = module._malloc(PointerSize) - if (!this.sizeScratch) { - throw new Error('failed to allocate the scratch buffer for string lengths') + this.resultCountScratch = module._malloc(PointerSize) + if (!this.sizeScratch || !this.resultCountScratch) { + throw new Error('failed to allocate the scratch buffers for C out parameters') } } @@ -578,7 +633,7 @@ export default class LuaModule { return undefined } // Copied, because the caller may outlive the next heap growth. - return this.heap.slice(pointer, pointer + this.readSize(this.sizeScratch)) + return this.heap.slice(pointer, pointer + this.readPointer(this.sizeScratch)) } /** A number is a pointer to a NUL-terminated C string, and `null` pushes nil, as in C. */ @@ -593,9 +648,7 @@ export default class LuaModule { const capacity = s.length * MAX_UTF8_BYTES_PER_CHAR const pointer = this.acquireStringBuffer(capacity) try { - // encodeInto avoids materialising an intermediate Uint8Array for the whole string. - const { written } = textEncoder.encodeInto(s, this.heap.subarray(pointer, pointer + capacity)) - this.lua_pushlstring(L, pointer, written) + this.lua_pushlstring(L, pointer, this.writeString(s, pointer, capacity)) } finally { this.releaseStringBuffer(pointer) } @@ -616,13 +669,104 @@ export default class LuaModule { if (!length) { return '' } - return textDecoder.decode(this.heap.subarray(pointer, pointer + length)) + // The third argument keeps it from stopping at a NUL, since a Lua string can contain them + // and the length is already known. Built with TEXTDECODER=1 so this skips TextDecoder for + // the short names and keys that most of these are -- see utils/build-wasm.sh. + return this.emscripten.UTF8ToString(pointer, length, true) + } + + /** + * Calls `use` with a NUL terminated copy of `value` in wasm memory, valid only for that call. + * Reuses the shared string buffer, so `use` must not push another string of its own. + */ + public withCString(value: string, use: (pointer: number, length: number) => T): T { + // The NUL is not part of the length, but a caller that reads the pointer as a C string + // (a chunk name, say) needs it there. + const capacity = value.length * MAX_UTF8_BYTES_PER_CHAR + 1 + const pointer = this.acquireStringBuffer(capacity) + try { + const written = this.writeString(value, pointer, capacity - 1) + this.heap[pointer + written] = 0 + return use(pointer, written) + } finally { + this.releaseStringBuffer(pointer) + } + } + + /** + * Encodes `value` at `pointer` and returns the number of bytes written. The counterpart to + * {@link readString}: short ASCII takes a straight copy, because the subarray view TextEncoder + * needs costs more than the encoding does at that size. + */ + private writeString(value: string, pointer: number, capacity: number): number { + const heap = this.heap + const length = value.length + if (length <= INLINE_ENCODE_LIMIT) { + let index = 0 + while (index < length) { + const code = value.charCodeAt(index) + if (code > 0x7f) { + break + } + heap[pointer + index] = code + index++ + } + if (index === length) { + return length + } + // Anything non-ASCII is re-encoded from the start, overwriting what was copied above. + } + + return textEncoder.encodeInto(value, heap.subarray(pointer, pointer + capacity)).written + } + + /** + * The 32 bit word at `pointer`, without going through Emscripten's typed getValue. Also reads + * the out parameters the C API writes sizes and counts into, which are the same width. + */ + public readPointer(pointer: number): number { + return this.emscripten.HEAPU32[pointer >>> 2] + } + + /** The counterpart to {@link readPointer}. */ + public writePointer(pointer: number, value: number): void { + this.emscripten.HEAPU32[pointer >>> 2] = value + } + + /** + * Puts a JS callback in the indirect function table and returns the pointer Lua calls it + * through. Release it with {@link removeFunction}. + * + * A plain JS function cannot go into the table, so it has to be wrapped by a wasm module that + * imports and re-exports it. Emscripten's addFunction builds that module per callback, after + * first provoking a TypeError to discover it is needed. The module depends only on the + * signature, so compiling it once per signature is most of the cost: a state installs five + * callbacks, which was over half of what creating one cost. + * + * Each call takes a slot of its own. Unlike Emscripten's, these are not deduplicated by + * callback identity, so registering the same callback twice needs releasing twice. + */ + public addFunction(callback: (...args: any[]) => any, signature: string): number { + let trampoline = this.trampolineModules.get(signature) + if (trampoline === undefined) { + trampoline = buildTrampolineModule(signature) + this.trampolineModules.set(signature, trampoline) + } + + const wrapped = new WebAssembly.Instance(trampoline, { e: { f: callback } }).exports.f as (...args: any[]) => any + // Already a wasm function, so this now takes Emscripten's slot bookkeeping and nothing else. + return this.emscripten.addFunction(wrapped, signature) + } + + /** Frees a table slot taken by {@link addFunction}. */ + public removeFunction(pointer: number): void { + this.emscripten.removeFunction(pointer) } private toLString(raw: (L: LuaAddress, idx: number, len: number) => number, L: LuaAddress, idx: number, len: number | null): string { const lengthPointer = len ?? this.sizeScratch const pointer = raw(L, idx, lengthPointer) - return pointer ? this.readString(pointer, this.readSize(lengthPointer)) : '' + return pointer ? this.readString(pointer, this.readPointer(lengthPointer)) : '' } public lua_remove(luaState: LuaAddress, index: number): void { @@ -708,10 +852,6 @@ export default class LuaModule { return this.emscripten.HEAPU8 } - private readSize(pointer: number): number { - return this.emscripten.HEAPU32[pointer >>> 2] - } - private acquireStringBuffer(size: number): number { if (size > REUSABLE_STRING_BUFFER_LIMIT) { const pointer = this.emscripten._malloc(size) @@ -742,11 +882,24 @@ export default class LuaModule { returnType: Emscripten.JSType | null, argTypes: Array, ): (...args: any[]) => any { - // optimization for common case - const hasStringOrNumber = argTypes.some((argType) => argType === 'string|number') - if (!hasStringOrNumber) { - return (...args: any[]) => - this.emscripten.ccall(name, returnType, argTypes as Emscripten.JSType[], args as Emscripten.TypeCompatibleWithC[]) + const raw = (this.emscripten as unknown as Record any>)[`_${name}`] + if (typeof raw !== 'function') { + throw new Error(`the wasm module does not export '${name}'`) + } + + // Emscripten's own cwrap specializes exactly this case and nothing else, so it is inlined + // here rather than exported: a signature that needs nothing marshalled in either direction + // is just the wasm export. + if (argTypes.every((argType) => argType === 'number') && returnType !== 'string') { + return raw + } + + // Everything else, C string arguments included, goes through one hand rolled wrapper, since + // upstream would fall back to ccall -- which rebuilds its converter table, argument array + // and return handler on every call. That is most of the cost of the small C API functions, + // and these are hot: metatable names, globals, table fields. + if (!argTypes.includes('string|number')) { + return this.wrapWithStringArguments(raw, returnType, argTypes as Emscripten.JSType[]) } return (...args: any[]) => { @@ -779,6 +932,111 @@ export default class LuaModule { } } } + + /** + * Rest arguments and a spread call would land on every C API call that takes a name, so the + * arguments are named and both the argument positions and the arity are unrolled. Which slots + * hold a C string is fixed when the binding is wrapped, so it is not worked out per call. + */ + private wrapWithStringArguments( + raw: (...args: any[]) => any, + returnType: Emscripten.JSType | null, + argTypes: Emscripten.JSType[], + ): (...args: any[]) => any { + const emscripten = this.emscripten + const arity = argTypes.length + if (arity < 2 || arity > 5) { + throw new Error(`wrapWithStringArguments only unrolls arities 2 to 5, not ${arity}`) + } + if (argTypes[0] === 'string') { + // Every binding takes the lua_State there, so that slot is not unrolled below. + throw new Error('wrapWithStringArguments does not marshal the first argument') + } + + const returnsString = returnType === 'string' + const [, s1, s2, s3, s4] = argTypes.map((argType) => argType === 'string') + + return (a?: any, b?: any, c?: any, d?: any, e?: any): any => { + // Only an argument that misses the cache needs scratch space, and the fixed names that + // dominate these calls all hit it, so the stack is only touched when it is used. + let stack = 0 + try { + let pointer: number + if (s1) { + if ((pointer = this.toCString(b)) >= 0) { + b = pointer + } else { + stack ||= emscripten.stackSave() + b = emscripten.stringToUTF8OnStack(b) + } + } + if (s2) { + if ((pointer = this.toCString(c)) >= 0) { + c = pointer + } else { + stack ||= emscripten.stackSave() + c = emscripten.stringToUTF8OnStack(c) + } + } + if (s3) { + if ((pointer = this.toCString(d)) >= 0) { + d = pointer + } else { + stack ||= emscripten.stackSave() + d = emscripten.stringToUTF8OnStack(d) + } + } + if (s4) { + if ((pointer = this.toCString(e)) >= 0) { + e = pointer + } else { + stack ||= emscripten.stackSave() + e = emscripten.stringToUTF8OnStack(e) + } + } + + const result = arity === 2 ? raw(a, b) : arity === 3 ? raw(a, b, c) : arity === 4 ? raw(a, b, c, d) : raw(a, b, c, d, e) + return returnsString ? emscripten.UTF8ToString(result) : result + } finally { + if (stack) { + emscripten.stackRestore(stack) + } + } + } + } + + /** + * The C string pointer for a marshalled argument, or -1 when it has to go on the wasm stack + * instead. Cached pointers are kept for the lifetime of the module, so they stay valid across + * the reentrant calls a metamethod can make while one of them is still in flight. + */ + private toCString(value: unknown): number { + // Matches ccall: a nullish argument is a null pointer rather than the text "null". A number + // is already one, which is what the `string|number` bindings pass. + if (value === null || value === undefined) { + return 0 + } + if (typeof value === 'number') { + return value + } + + // Checked before the lookup, because hashing a long string costs more than the call saves. + const text = value as string + if (text.length > C_STRING_CACHE_MAX_LENGTH) { + return -1 + } + const cached = this.cStringCache.get(text) + if (cached !== undefined) { + return cached + } + if (this.cStringCache.size >= C_STRING_CACHE_LIMIT) { + return -1 + } + + const pointer = this.emscripten.stringToNewUTF8(text) + this.cStringCache.set(text, pointer) + return pointer + } } /** diff --git a/src/state.ts b/src/state.ts index e1fccd8..d4bab6c 100755 --- a/src/state.ts +++ b/src/state.ts @@ -64,31 +64,28 @@ function createAddress(cmodule: LuaModule, memory: LuaMemoryOptions | undefined) } const stats = { used: 0, max: memory.max } - const allocatorFunctionPointer = cmodule.emscripten.addFunction( - (_userData: number, pointer: number, oldSize: number, newSize: number): number => { - if (newSize === 0) { - if (pointer) { - stats.used -= oldSize - cmodule.emscripten._free(pointer) - } - return 0 + const allocatorFunctionPointer = cmodule.addFunction((_userData: number, pointer: number, oldSize: number, newSize: number): number => { + if (newSize === 0) { + if (pointer) { + stats.used -= oldSize + cmodule.emscripten._free(pointer) } + return 0 + } - const endMemoryDelta = pointer ? newSize - oldSize : newSize - const endMemory = stats.used + endMemoryDelta + const endMemoryDelta = pointer ? newSize - oldSize : newSize + const endMemory = stats.used + endMemoryDelta - if (newSize > oldSize && stats.max && endMemory > stats.max) { - return 0 - } + if (newSize > oldSize && stats.max && endMemory > stats.max) { + return 0 + } - const reallocated = cmodule.emscripten._realloc(pointer, newSize) - if (reallocated) { - stats.used = endMemory - } - return reallocated - }, - 'iiiii', - ) + const reallocated = cmodule.emscripten._realloc(pointer, newSize) + if (reallocated) { + stats.used = endMemory + } + return reallocated + }, 'iiiii') const address = cmodule.lua_newstate( allocatorFunctionPointer, @@ -96,7 +93,7 @@ function createAddress(cmodule: LuaModule, memory: LuaMemoryOptions | undefined) ((Date.now() >>> 0) ^ Math.floor(Math.random() * 0x100000000)) >>> 0, ) if (!address) { - cmodule.emscripten.removeFunction(allocatorFunctionPointer) + cmodule.removeFunction(allocatorFunctionPointer) // A cap the state cannot even be built under is the overwhelmingly likely cause, and it is // the one thing the caller can act on. throw new Error( @@ -263,7 +260,7 @@ export default class LuaState extends Thread { this.module.lua_close(this.address) if (this.allocatorFunctionPointer) { - this.module.emscripten.removeFunction(this.allocatorFunctionPointer) + this.module.removeFunction(this.allocatorFunctionPointer) } for (const wrapper of this.typeExtensions) { diff --git a/src/thread.ts b/src/thread.ts index dcac9ee..16e35bf 100755 --- a/src/thread.ts +++ b/src/thread.ts @@ -21,7 +21,6 @@ import { LuaTimeoutError, LuaType, type LuaWarnHandler, - PointerSize, } from './types' import { isEmscriptenUnwind, isPromise, yieldToEventLoop } from './utils' @@ -73,17 +72,13 @@ export default class Thread { /** @param options.mode defaults to `'t'`. See {@link LuaLoadOptions.mode}. */ public loadString(luaCode: string, options?: LuaLoadOptions): void { - const size = this.module.emscripten.lengthBytesUTF8(luaCode) - const pointerSize = size + 1 - const bufferPointer = this.module.emscripten._malloc(pointerSize) - try { - this.module.emscripten.stringToUTF8(luaCode, bufferPointer, pointerSize) - this.assertOk( - this.module.luaL_loadbufferx(this.address, bufferPointer, size, options?.name ?? bufferPointer, options?.mode ?? 't'), - ) - } finally { - this.module.emscripten._free(bufferPointer) - } + // Lua copies the chunk while loading, so the shared buffer can be handed straight to it + // rather than encoded into an allocation of its own. + this.assertOk( + this.module.withCString(luaCode, (pointer, size) => + this.module.luaL_loadbufferx(this.address, pointer, size, options?.name ?? pointer, options?.mode ?? 't'), + ), + ) } /** @param options.mode defaults to `'t'`. See {@link LuaLoadOptions.mode}. */ @@ -92,16 +87,15 @@ export default class Thread { } public resume(argCount = 0): LuaResumeResult { - const dataPointer = this.module.emscripten._malloc(PointerSize) - try { - this.module.emscripten.setValue(dataPointer, 0, 'i32') - const luaResult = this.module.lua_resume(this.address, null, argCount, dataPointer) - return { - result: luaResult, - resultCount: this.module.emscripten.getValue(dataPointer, 'i32'), - } - } finally { - this.module.emscripten._free(dataPointer) + // The shared slot is safe for the same reason the one behind it is: C writes the count as it + // returns and it is read straight after, with nothing interleaved. A nested resume has + // finished with the slot by the time this one's lua_resume writes to it. + const dataPointer = this.module.resultCountScratch + this.module.writePointer(dataPointer, 0) + const luaResult = this.module.lua_resume(this.address, null, argCount, dataPointer) + return { + result: luaResult, + resultCount: this.module.readPointer(dataPointer), } } @@ -118,7 +112,7 @@ export default class Thread { } public setField(index: number, name: string, value: unknown): void { - index = this.module.lua_absindex(this.address, index) + index = this.absIndex(index) this.pushValue(value) this.module.lua_setfield(this.address, index, name) } @@ -212,12 +206,17 @@ export default class Thread { } public stateToThread(L: LuaAddress): Thread { + if (L === this.address) { + return this + } return L === this.parent?.address ? this.parent : new Thread(this.module, this.typeExtensions, L, this.parent || this) } public pushValue(rawValue: unknown, cache?: LuaPushCache): void { - const decoratedValue = this.getValueDecorations(rawValue) - const target = decoratedValue.target + // Only the type extensions take a decoration, so pushing a plain primitive never has to + // allocate one. The default branch below synthesises one for the values that do need it. + const decoration = rawValue instanceof Decoration ? rawValue : undefined + const target = decoration ? decoration.target : rawValue if (target instanceof Thread) { const isMain = this.module.lua_pushthread(target.address) === 1 @@ -227,8 +226,6 @@ export default class Thread { return } - const startTop = this.getTop() - // Handle primitive types switch (typeof target) { case 'undefined': @@ -255,28 +252,35 @@ export default class Thread { case 'boolean': this.module.lua_pushboolean(this.address, target ? 1 : 0) break - default: - if (this.typeExtensions.find((wrapper) => wrapper.extension.pushValue(this, decoratedValue, cache))) { - break - } - if (target === null) { + default: { + // A type extension can be supplied by the caller, so unlike the pushes above it is + // not guaranteed to leave exactly one value behind. That is worth the two + // lua_gettop calls here, and not worth them on every primitive push. + const startTop = this.getTop() + if (this.pushWithExtension(decoration ?? new Decoration(target, {}), cache)) { + const endTop = this.getTop() + if (endTop !== startTop + 1) { + throw new Error(`pushValue expected stack size ${startTop + 1}, got ${endTop}`) + } + } else if (target === null) { this.module.lua_pushnil(this.address) - break + } else { + throw new Error(`The type '${typeof target}' is not supported by Lua`) } - throw new Error(`The type '${typeof target}' is not supported by Lua`) - } - - if (decoratedValue.options.metatable) { - this.setMetatable(-1, decoratedValue.options.metatable) + break + } } - if (this.getTop() !== startTop + 1) { - throw new Error(`pushValue expected stack size ${startTop + 1}, got ${this.getTop()}`) + // A synthesised decoration always has empty options, so this only ever acts on one the + // caller supplied. + const metatable = decoration?.options.metatable + if (metatable) { + this.setMetatable(-1, metatable) } } public setMetatable(index: number, metatable: LuaMetatable): void { - index = this.module.lua_absindex(this.address, index) + index = this.absIndex(index) if (this.module.lua_getmetatable(this.address, index)) { this.pop(1) @@ -308,7 +312,7 @@ export default class Thread { } public getValue(index: number, inputType?: LuaType, cache?: LuaGetCache): any { - index = this.module.lua_absindex(this.address, index) + index = this.absIndex(index) const type: LuaType = inputType ?? this.module.lua_type(this.address, index) @@ -338,11 +342,12 @@ export default class Thread { metatableName = this.getMetatableName(index) } - const typeExtensionWrapper = this.typeExtensions.find((wrapper) => - wrapper.extension.isType(this, index, type, metatableName), - ) - if (typeExtensionWrapper) { - return typeExtensionWrapper.extension.getValue(this, index, cache) + const extensions = this.typeExtensions + for (let i = 0; i < extensions.length; i++) { + const extension = extensions[i].extension + if (extension.isType(this, index, type, metatableName)) { + return extension.getValue(this, index, cache) + } } // Handing back an opaque Pointer hid the failure until the value was used, and @@ -363,7 +368,7 @@ export default class Thread { } if (this.hookFunctionPointer) { - this.module.emscripten.removeFunction(this.hookFunctionPointer) + this.module.removeFunction(this.hookFunctionPointer) this.hookFunctionPointer = undefined } @@ -549,7 +554,7 @@ export default class Thread { maxInstructions !== undefined ? Math.max(1, Math.min(INSTRUCTION_HOOK_COUNT, maxInstructions)) : INSTRUCTION_HOOK_COUNT if (!this.hookFunctionPointer) { - this.hookFunctionPointer = this.module.emscripten.addFunction((): void => { + this.hookFunctionPointer = this.module.addFunction((): void => { // Reads this.limits rather than closing over them, so a hook allocated for an // earlier configuration still honours the current one. const error = this.checkHookLimits() @@ -585,7 +590,22 @@ export default class Thread { return undefined } - private getValueDecorations(value: any): Decoration { - return value instanceof Decoration ? value : new Decoration(value, {}) + /** + * `lua_absindex` is the identity for an index that is already absolute, so the common case + * skips the call into wasm. + */ + private absIndex(index: number): number { + return index > 0 ? index : this.module.lua_absindex(this.address, index) + } + + /** Offers the value to each extension by descending priority. False if none claimed it. */ + private pushWithExtension(decoration: Decoration, cache: LuaPushCache | undefined): boolean { + const extensions = this.typeExtensions + for (let i = 0; i < extensions.length; i++) { + if (extensions[i].extension.pushValue(this, decoration, cache)) { + return true + } + } + return false } } diff --git a/src/type-extension.ts b/src/type-extension.ts index 580bbf6..e3d61bb 100644 --- a/src/type-extension.ts +++ b/src/type-extension.ts @@ -22,13 +22,13 @@ export default abstract class LuaTypeExtension { /** * The `__gc` handler every reference holding extension needs. The caller owns the returned - * pointer and has to release it with `removeFunction` in {@link close}. + * pointer and has to release it with the module's `removeFunction` in {@link close}. */ protected createGcFunction(): number { - return this.state.module.emscripten.addFunction((calledL: LuaAddress) => { + return this.state.module.addFunction((calledL: LuaAddress) => { // Throws a lua error which does a jump if it does not match. const userDataPointer = this.state.module.luaL_checkudata(calledL, 1, this.name) - const referencePointer = this.state.module.emscripten.getValue(userDataPointer, '*') + const referencePointer = this.state.module.readPointer(userDataPointer) this.state.module.unref(referencePointer) return LuaReturn.Ok @@ -41,7 +41,7 @@ export default abstract class LuaTypeExtension { if (!refUserdata) { throw new Error(`data does not have the expected metatable: ${this.name}`) } - const referencePointer = thread.module.emscripten.getValue(refUserdata, '*') + const referencePointer = thread.module.readPointer(refUserdata) return thread.module.getRef(referencePointer) as T } @@ -53,7 +53,7 @@ export default abstract class LuaTypeExtension { const pointer = thread.module.ref(target) // 4 = size of pointer in wasm. const userDataPointer = thread.module.lua_newuserdatauv(thread.address, PointerSize, 0) - thread.module.emscripten.setValue(userDataPointer, pointer, '*') + thread.module.writePointer(userDataPointer, pointer) if (LuaType.Nil === thread.module.luaL_getmetatable(thread.address, this.name)) { // Pop the pushed nil value and the user data. Don't need to unref because it's diff --git a/src/type-extensions/error.ts b/src/type-extensions/error.ts index 82a374f..ba39174 100644 --- a/src/type-extensions/error.ts +++ b/src/type-extensions/error.ts @@ -68,7 +68,7 @@ class ErrorTypeExtension extends TypeExtension { } public close(): void { - this.state.module.emscripten.removeFunction(this.gcPointer) + this.state.module.removeFunction(this.gcPointer) } } diff --git a/src/type-extensions/function.ts b/src/type-extensions/function.ts index f7f0919..53366e1 100644 --- a/src/type-extensions/function.ts +++ b/src/type-extensions/function.ts @@ -53,11 +53,11 @@ class FunctionTypeExtension extends TypeExtension { // Pop the metatable from the stack. state.module.lua_pop(state.address, 1) - this.functionWrapper = state.module.emscripten.addFunction((calledL: LuaAddress) => { + this.functionWrapper = state.module.addFunction((calledL: LuaAddress) => { const calledThread = state.stateToThread(calledL) const refUserdata = state.module.luaL_checkudata(calledL, state.module.lua_upvalueindex(1), this.name) - const refPointer = state.module.emscripten.getValue(refUserdata, '*') + const refPointer = state.module.readPointer(refUserdata) const { target, options: decorationOptions } = state.module.getRef(refPointer) as Decoration const argsQuantity = calledThread.getTop() @@ -105,8 +105,8 @@ class FunctionTypeExtension extends TypeExtension { } public close(): void { - this.state.module.emscripten.removeFunction(this.gcPointer) - this.state.module.emscripten.removeFunction(this.functionWrapper) + this.state.module.removeFunction(this.gcPointer) + this.state.module.removeFunction(this.functionWrapper) // Doesn't destroy the Lua thread, just function pointers. this.callbackContext.close() // Destroy the Lua thread @@ -129,7 +129,7 @@ class FunctionTypeExtension extends TypeExtension { const pointer = thread.module.ref(decoration) // 4 = size of pointer in wasm. const userDataPointer = thread.module.lua_newuserdatauv(thread.address, PointerSize, 0) - thread.module.emscripten.setValue(userDataPointer, pointer, '*') + thread.module.writePointer(userDataPointer, pointer) if (LuaType.Nil === thread.module.luaL_getmetatable(thread.address, this.name)) { // Pop the pushed userdata. @@ -153,6 +153,8 @@ class FunctionTypeExtension extends TypeExtension { thread.module.lua_pushvalue(thread.address, index) // Create a reference to the function which pops it from the stack const func = thread.module.luaL_ref(thread.address, LUA_REGISTRYINDEX) + // The reference never changes, so the bigint the i64 parameter needs is built once. + const funcReference = BigInt(func) const jsFunc = (...args: any[]): any => { // Calling a function would ideally be in the Lua context that's calling it. For example if the JS function @@ -170,7 +172,7 @@ class FunctionTypeExtension extends TypeExtension { // they can be left in inconsistent states. const callThread = this.callbackContext.newThread() try { - const internalType = callThread.module.lua_rawgeti(callThread.address, LUA_REGISTRYINDEX, BigInt(func)) + const internalType = callThread.module.lua_rawgeti(callThread.address, LUA_REGISTRYINDEX, funcReference) if (internalType !== LuaType.Function) { const callMetafieldType = callThread.module.luaL_getmetafield(callThread.address, -1, '__call') callThread.pop() diff --git a/src/type-extensions/null.ts b/src/type-extensions/null.ts index ea3453c..35c2e2e 100644 --- a/src/type-extensions/null.ts +++ b/src/type-extensions/null.ts @@ -66,7 +66,7 @@ class NullTypeExtension extends TypeExtension { } public close(): void { - this.state.module.emscripten.removeFunction(this.gcPointer) + this.state.module.removeFunction(this.gcPointer) } } diff --git a/src/type-extensions/promise.ts b/src/type-extensions/promise.ts index 19b4605..9dcffea 100644 --- a/src/type-extensions/promise.ts +++ b/src/type-extensions/promise.ts @@ -62,7 +62,7 @@ class PromiseTypeExtension extends TypeExtension> { promiseResult = { status: 'rejected', value: err } }) - const continuance = this.state.module.emscripten.addFunction((continuanceState: LuaAddress) => { + const continuance = this.state.module.addFunction((continuanceState: LuaAddress) => { // If this yield has been called from within a coroutine and so manually resumed // then there may not yet be any results. In that case yield again. if (!promiseResult) { @@ -74,7 +74,7 @@ class PromiseTypeExtension extends TypeExtension> { return state.module.lua_yieldk(functionThread.address, 0, 0, continuance) } - this.state.module.emscripten.removeFunction(continuance) + this.state.module.removeFunction(continuance) const continuanceThread = state.stateToThread(continuanceState) @@ -127,7 +127,7 @@ class PromiseTypeExtension extends TypeExtension> { } public close(): void { - this.state.module.emscripten.removeFunction(this.gcPointer) + this.state.module.removeFunction(this.gcPointer) } public pushValue(thread: Thread, decoration: Decoration): boolean { diff --git a/src/type-extensions/proxy.ts b/src/type-extensions/proxy.ts index 2346aaa..6b82e53 100644 --- a/src/type-extensions/proxy.ts +++ b/src/type-extensions/proxy.ts @@ -114,7 +114,7 @@ class ProxyTypeExtension extends TypeExtension { public getValue(thread: Thread, index: number): any { const refUserdata = thread.module.lua_touserdata(thread.address, index) - const referencePointer = thread.module.emscripten.getValue(refUserdata, '*') + const referencePointer = thread.module.readPointer(refUserdata) return thread.module.getRef(referencePointer) } @@ -153,7 +153,7 @@ class ProxyTypeExtension extends TypeExtension { } public close(): void { - this.state.module.emscripten.removeFunction(this.gcPointer) + this.state.module.removeFunction(this.gcPointer) } } diff --git a/src/type-extensions/table.ts b/src/type-extensions/table.ts index 3564020..a725c48 100644 --- a/src/type-extensions/table.ts +++ b/src/type-extensions/table.ts @@ -26,11 +26,10 @@ class TableTypeExtension extends TypeExtension { let table = seenMap.get(pointer) as TableType | undefined if (!table) { - const keys = this.readTableKeys(thread, index) - - const isSequential = keys.length > 0 && keys.every((key, keyIndex) => key === String(keyIndex + 1)) - table = isSequential ? [] : {} + table = this.isSequential(thread, index) ? [] : {} + // Registered before the values are read, so a table that contains itself resolves to + // this same object rather than to a second copy of it. seenMap.set(pointer, table) this.readTableValues(thread, index, seenMap, table) } @@ -93,19 +92,28 @@ class TableTypeExtension extends TypeExtension { return true } - private readTableKeys(thread: Thread, index: number): string[] { - const keys = [] + /** + * A table becomes a JS array only when `lua_next` walks exactly the keys "1".."n" in that + * order. Converting keys stops as soon as that is ruled out, because the keys this pass looks + * at are read again alongside the values. + */ + private isSequential(thread: Thread, index: number): boolean { + let count = 0 thread.module.lua_pushnil(thread.address) while (thread.module.lua_next(thread.address, index)) { // JS only supports string keys in objects. - const key = thread.indexToString(-2) - keys.push(key) + if (thread.indexToString(-2) !== String(count + 1)) { + // Pop the key and the value, since the walk is being abandoned part way. + thread.pop(2) + return false + } + count++ // Pop the value. thread.pop() } - return keys + return count > 0 } private readTableValues(thread: Thread, index: number, seenMap: LuaGetCache, table: TableType): void { @@ -113,13 +121,12 @@ class TableTypeExtension extends TypeExtension { thread.module.lua_pushnil(thread.address) while (thread.module.lua_next(thread.address, index)) { - const key = thread.indexToString(-2) - const value = thread.getValue(-1, undefined, seenMap) - if (isArray) { - table.push(value) + // An array takes its order from the walk, so its keys are never converted. + table.push(thread.getValue(-1, undefined, seenMap)) } else { - table[key] = value + const key = thread.indexToString(-2) + table[key] = thread.getValue(-1, undefined, seenMap) } thread.pop() diff --git a/src/type-extensions/userdata.ts b/src/type-extensions/userdata.ts index 1e9cae3..4a87082 100644 --- a/src/type-extensions/userdata.ts +++ b/src/type-extensions/userdata.ts @@ -34,7 +34,7 @@ class UserdataTypeExtension extends TypeExtension { public getValue(thread: Thread, index: number): any { const refUserdata = thread.module.lua_touserdata(thread.address, index) - const referencePointer = thread.module.emscripten.getValue(refUserdata, '*') + const referencePointer = thread.module.readPointer(refUserdata) return thread.module.getRef(referencePointer) } @@ -47,7 +47,7 @@ class UserdataTypeExtension extends TypeExtension { } public close(): void { - this.state.module.emscripten.removeFunction(this.gcPointer) + this.state.module.removeFunction(this.gcPointer) } } diff --git a/utils/build-wasm.sh b/utils/build-wasm.sh index 921f1d5..9d8db45 100755 --- a/utils/build-wasm.sh +++ b/utils/build-wasm.sh @@ -11,7 +11,9 @@ if [ "$1" == "dev" ]; then extension="-O0 -g3 -s ASSERTIONS=1 -s SAFE_HEAP=1 -s STACK_OVERFLOW_CHECK=2" else - extension="-Oz -fno-inline-functions -s BINARYEN_EXTRA_PASSES=gufa-optimizing" + # TEXTDECODER=1 keeps Emscripten's short string decode path, which -Oz would otherwise drop + # in favour of always calling TextDecoder. LuaModule.readString relies on it. + extension="-Oz -fno-inline-functions -s TEXTDECODER=1 -s BINARYEN_EXTRA_PASSES=gufa-optimizing" fi emcc \ @@ -29,6 +31,9 @@ emcc \ 'lengthBytesUTF8', \ 'stringToUTF8', \ 'stringToNewUTF8', \ + 'stringToUTF8OnStack', \ + 'stackSave', \ + 'stackRestore', \ 'UTF8ToString', \ 'HEAPU8', \ 'HEAPU32' From 8dcdab2524cfed7c963a79edfe38bb7dddb06e06 Mon Sep 17 00:00:00 2001 From: Gabriel Francisco Date: Wed, 29 Jul 2026 09:50:04 -0300 Subject: [PATCH 48/83] fix: memory leaks --- src/module.ts | 14 ++++- src/type-extension.ts | 15 ++++- src/type-extensions/function.ts | 11 ++-- src/type-extensions/promise.ts | 105 ++++++++++++++++++++------------ test/promises.test.js | 71 ++++++++++++++++++++- 5 files changed, 168 insertions(+), 48 deletions(-) diff --git a/src/module.ts b/src/module.ts index 184cc2e..3cc2207 100755 --- a/src/module.ts +++ b/src/module.ts @@ -818,7 +818,10 @@ export default class LuaModule { } const metadata = this.referenceTracker.get(ref) if (metadata === undefined) { - this.referenceTracker.delete(ref) + // Dropping the map entry too, both to release the value and to keep the invariant the + // index allocation above relies on: every index below the high water mark is either + // live in referenceMap or waiting in availableReferences, never neither and never both. + this.referenceMap.delete(index) this.availableReferences.push(index) return } @@ -1077,6 +1080,12 @@ function createInputReader(reader?: () => string | null | undefined): (() => num // Emscripten hands output over one byte at a time, so it has to be reassembled before it can be // decoded. Doubles from here as lines get longer. const INITIAL_OUTPUT_CAPACITY = 256 +// Grown past this the buffer is dropped back to it once the line is out, rather than kept for the +// module's lifetime: a single huge `io.write` would otherwise retain its whole capacity forever, +// twice over for a runtime with both stdout and stderr. Dropping all the way back to the initial +// capacity instead would make a script that writes long lines in a loop regrow from 256 bytes on +// every one. +const MAX_RETAINED_OUTPUT_CAPACITY = 64 * 1024 function createOutputWriter(writer?: (content: string) => void): ((charCode: number | null) => void) | null { if (!writer) { @@ -1100,6 +1109,9 @@ function createOutputWriter(writer?: (content: string) => void): ((charCode: num // dangling character in the decoder to be completed by the next flush. const content = decoder.decode(buffer.subarray(0, length), { stream: !endOfLine }) length = 0 + if (buffer.length > MAX_RETAINED_OUTPUT_CAPACITY) { + buffer = new Uint8Array(MAX_RETAINED_OUTPUT_CAPACITY) + } // An empty line is worth reporting, an incomplete character is not. if (endOfLine || content.length > 0) { writer(content) diff --git a/src/type-extension.ts b/src/type-extension.ts index e3d61bb..6d5d377 100644 --- a/src/type-extension.ts +++ b/src/type-extension.ts @@ -18,6 +18,16 @@ export default abstract class LuaTypeExtension { return type === LuaType.Userdata && name === this.name } + /** + * Releases what the extension owns outside Lua: the function pointers it took from + * `addFunction`, and any JS side bookkeeping. + * + * Called only from {@link LuaState.close}, and only after `lua_close` has already run every + * `__gc` handler and freed the state along with its registry and every thread anchored there. + * So the pointers are still valid here and the `__gc` handlers still needed them a moment ago, + * but nothing may touch the state itself -- unreffing a registry slot or calling into a thread + * at this point is a use after free. + */ public abstract close(): void /** @@ -56,9 +66,10 @@ export default abstract class LuaTypeExtension { thread.module.writePointer(userDataPointer, pointer) if (LuaType.Nil === thread.module.luaL_getmetatable(thread.address, this.name)) { - // Pop the pushed nil value and the user data. Don't need to unref because it's - // already associated with the user data pointer. + // Pop the pushed nil value and the user data. The reference has to be released by hand: + // without a metatable the userdata has no __gc, so nothing else ever would. thread.pop(2) + thread.module.unref(pointer) throw new Error(`metatable not found: ${this.name}`) } diff --git a/src/type-extensions/function.ts b/src/type-extensions/function.ts index 53366e1..ebae0f5 100644 --- a/src/type-extensions/function.ts +++ b/src/type-extensions/function.ts @@ -19,7 +19,6 @@ class FunctionTypeExtension extends TypeExtension { private gcPointer: number private functionWrapper: number private callbackContext: Thread - private callbackContextIndex: number /** Milliseconds a Lua function called from JS may run before being interrupted. */ private readonly functionTimeout: number | undefined @@ -31,8 +30,9 @@ class FunctionTypeExtension extends TypeExtension { // interfering with the global context. This creates a callback context that will always exist // even if the thread that called getValue() has been destroyed. this.callbackContext = state.newThread() - // Pops it from the global stack but keeps it alive - this.callbackContextIndex = this.state.module.luaL_ref(state.address, LUA_REGISTRYINDEX) + // Pops it from the global stack but keeps it alive. The reference is never released, for the + // reason given on LuaTypeExtension.close. + this.state.module.luaL_ref(state.address, LUA_REGISTRYINDEX) if (!this.functionRegistry) { state.warn('FunctionTypeExtension: FinalizationRegistry not found. Memory leaks likely.') @@ -107,10 +107,9 @@ class FunctionTypeExtension extends TypeExtension { public close(): void { this.state.module.removeFunction(this.gcPointer) this.state.module.removeFunction(this.functionWrapper) - // Doesn't destroy the Lua thread, just function pointers. + // Doesn't destroy the Lua thread, just function pointers. The thread itself went with the + // state. this.callbackContext.close() - // Destroy the Lua thread - this.callbackContext.module.luaL_unref(this.callbackContext.address, LUA_REGISTRYINDEX, this.callbackContextIndex) } public isType(_thread: Thread, _index: number, type: LuaType): boolean { diff --git a/src/type-extensions/promise.ts b/src/type-extensions/promise.ts index 9dcffea..63e8c4a 100644 --- a/src/type-extensions/promise.ts +++ b/src/type-extensions/promise.ts @@ -8,13 +8,68 @@ import type { LuaAddress } from '../types' import { isPromise } from '../utils' import { decorate } from '../decoration' +/** The half of an in flight `:await()` the continuation needs once the promise has settled. */ +interface PendingAwait { + result: { status: 'fulfilled' | 'rejected'; value: any } | undefined +} + class PromiseTypeExtension extends TypeExtension> { private gcPointer: number + /** + * Keyed by the address of the thread parked in the await. A thread suspended in `lua_yieldk` + * cannot reach another `:await()`, so at most one is ever in flight per thread. + */ + private readonly pendingAwaits = new Map() + /** + * One continuation for every await on this state. Building one per await meant compiling and + * instantiating a wasm trampoline each time, and leaked the table slot whenever the coroutine + * was abandoned before the continuation ran -- a run cut short by a deadline, say. + */ + private readonly continuancePointer: number public constructor(state: LuaState, injectObject: boolean) { super(state, 'js_promise') this.gcPointer = this.createGcFunction() + this.continuancePointer = state.module.addFunction((continuanceState: LuaAddress): number => { + const pending = this.pendingAwaits.get(continuanceState) + if (!pending) { + // Nothing sensible is left to resume with, and returning would hand Lua a stack it + // does not expect. + throw new Error('a promise continuation ran without a pending await') + } + + // If this yield has been called from within a coroutine and so manually resumed + // then there may not yet be any results. In that case yield again. The continuation + // runs on the thread that yielded, so this is the address the await parked on. + if (!pending.result) { + // 0 because this is called between resumes so the first one should've popped the + // promise before returning the result. This is true within Lua's coroutine.resume + // too. + return state.module.lua_yieldk(continuanceState, 0, 0, this.continuancePointer) + } + + const { status, value } = pending.result + this.pendingAwaits.delete(continuanceState) + const continuanceThread = state.stateToThread(continuanceState) + + if (status === 'rejected') { + continuanceThread.pushValue(value || new Error('promise rejected with no error')) + return state.module.lua_error(continuanceState) + } + + if (value instanceof RawResult) { + return value.count + } else if (value instanceof MultiReturn) { + for (const arg of value) { + continuanceThread.pushValue(arg) + } + return value.length + } else { + continuanceThread.pushValue(value) + return 1 + } + }, 'iiii') if (state.module.luaL_newmetatable(state.address, this.name)) { const metatableIndex = state.module.lua_gettop(state.address) @@ -51,53 +106,22 @@ class PromiseTypeExtension extends TypeExtension> { throw new Error('cannot await in a thread that cannot yield, use doString instead of doStringSync') } - let promiseResult: { status: 'fulfilled' | 'rejected'; value: any } | undefined = undefined + const pending: PendingAwait = { result: undefined } + this.pendingAwaits.set(functionThread.address, pending) const awaitPromise = self .then((res) => { - promiseResult = { status: 'fulfilled', value: res } + pending.result = { status: 'fulfilled', value: res } return res }) .catch((err) => { - promiseResult = { status: 'rejected', value: err } + pending.result = { status: 'rejected', value: err } }) - const continuance = this.state.module.addFunction((continuanceState: LuaAddress) => { - // If this yield has been called from within a coroutine and so manually resumed - // then there may not yet be any results. In that case yield again. - if (!promiseResult) { - // 1 is because the initial yield pushed a promise reference so this pops - // it and re-returns it. - // 0 because this is called between resumes so the first one should've - // popped the promise before returning the result. This is true within - // Lua's coroutine.resume too. - return state.module.lua_yieldk(functionThread.address, 0, 0, continuance) - } - - this.state.module.removeFunction(continuance) - - const continuanceThread = state.stateToThread(continuanceState) - - if (promiseResult.status === 'rejected') { - continuanceThread.pushValue(promiseResult.value || new Error('promise rejected with no error')) - return this.state.module.lua_error(continuanceState) - } - - if (promiseResult.value instanceof RawResult) { - return promiseResult.value.count - } else if (promiseResult.value instanceof MultiReturn) { - for (const arg of promiseResult.value) { - continuanceThread.pushValue(arg) - } - return promiseResult.value.length - } else { - continuanceThread.pushValue(promiseResult.value) - return 1 - } - }, 'iiii') - + // 1 result, because the yield hands the promise reference back so the + // resume that follows can wait on it. functionThread.pushValue(awaitPromise) - return new RawResult(state.module.lua_yieldk(functionThread.address, 1, 0, continuance)) + return new RawResult(state.module.lua_yieldk(functionThread.address, 1, 0, this.continuancePointer)) }, { receiveThread: true }, ), @@ -128,6 +152,11 @@ class PromiseTypeExtension extends TypeExtension> { public close(): void { this.state.module.removeFunction(this.gcPointer) + this.state.module.removeFunction(this.continuancePointer) + // A coroutine abandoned mid await never reaches its continuation, so its record is still + // here holding whatever the promise settled with. Nothing tells us when Lua's own GC took + // that coroutine, so these are bounded by the state's lifetime rather than the await's. + this.pendingAwaits.clear() } public pushValue(thread: Thread, decoration: Decoration): boolean { diff --git a/test/promises.test.js b/test/promises.test.js index 17947fc..c839f88 100644 --- a/test/promises.test.js +++ b/test/promises.test.js @@ -1,5 +1,5 @@ import { expect } from 'chai' -import { getState, tick } from './utils.js' +import { getLua, getState, tick } from './utils.js' import { mock } from 'node:test' describe('Promises', () => { @@ -296,4 +296,73 @@ describe('Promises', () => { state.doStringSync(`sleep(5):await()`) }).to.throw('cannot await in a thread that cannot yield') }) + + it('an await abandoned mid flight should not leak a function table slot', async function () { + // Building the trampolines the probe needs is what makes this slow, not the Lua work. + this.timeout(30000) + const lua = await getLua() + // The table object itself is not exported, so its length is probed instead: Emscripten + // reuses freed slots before growing the table, so a batch bigger than any plausible + // freelist exhausts that and the highest index handed out tracks the real length. + const tableHighWater = () => { + const pointers = [] + for (let i = 0; i < 200; i++) { + pointers.push(lua.module.addFunction(() => 0, 'ii')) + } + const max = Math.max(...pointers) + for (const pointer of pointers) { + lua.module.removeFunction(pointer) + } + return max + } + + const runAbandonedAwait = async () => { + using state = lua.createState({ inject: true }) + state.set('slow', () => new Promise((resolve) => setTimeout(resolve, 50))) + await expect(state.doString('slow():await()', { timeout: 5 })).eventually.to.be.rejectedWith('timeout') + } + + // Once first, so nothing the first state builds is counted as growth. + await runAbandonedAwait() + const before = tableHighWater() + for (let i = 0; i < 10; i++) { + await runAbandonedAwait() + } + + expect(tableHighWater()).to.equal(before) + }) + + it('several coroutines awaiting at once should each get their own result', async () => { + using state = await getState() + state.set('sleep', (ms) => new Promise((resolve) => setTimeout(() => resolve(ms), ms))) + + // Resumed in the opposite order to the one they settle in, so a continuation that mixed up + // which thread it belonged to would show up here. + const res = await state.doString(` + local threads, results = {}, {} + for i = 1, 5 do + threads[i] = coroutine.create(function() + return sleep((6 - i) * 5):await() + end) + end + local done = 0 + while done < 5 do + -- Hand control back to JS so the timers behind the promises can fire. + coroutine.yield() + for i = 1, 5 do + if coroutine.status(threads[i]) == 'suspended' then + local ok, value = coroutine.resume(threads[i]) + if not ok then error(value) end + if coroutine.status(threads[i]) == 'dead' then + done = done + 1 + results[i] = value + end + end + end + end + return table.concat(results, ',') + `) + + expect(res).to.equal('25,20,15,10,5') + }) }) From 491321751005fa6cb7af70c31d35a072f66602a1 Mon Sep 17 00:00:00 2001 From: Gabriel Francisco Date: Wed, 29 Jul 2026 11:40:01 -0300 Subject: [PATCH 49/83] better fs support --- README.md | 40 ++++ bin/wasmoon | 3 +- package-lock.json | 3 + package.json | 7 +- rolldown.config.ts | 101 +++++--- src/index.ts | 1 + src/module.ts | 283 ++++++++++++++++------ src/runtime.ts | 52 ++++- test/browser.test.js | 2 +- test/bundling.test.js | 26 ++- test/filesystem.test.js | 75 ++++-- test/host-filesystem.test.js | 341 +++++++++++++++++++++++++++ test/luatests.js | 4 +- test/mounts.test.js | 141 +++++++++++ test/nodefs.test.js | 442 ----------------------------------- test/utils.js | 38 +++ utils/build-wasm.sh | 73 ++++-- 17 files changed, 1041 insertions(+), 591 deletions(-) create mode 100644 test/host-filesystem.test.js create mode 100644 test/mounts.test.js delete mode 100644 test/nodefs.test.js diff --git a/README.md b/README.md index d5d12ba..cee9827 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,46 @@ sandbox. `lua.close()` closes every state created from it, and both types suppor await using lua = await LuaRuntime.load() ``` +## Filesystem + +Every state on a runtime shares one filesystem. By default it is in memory: the same in Node, the +browser and a worker, and it holds nothing but what you put in it. + +```js +const lua = await LuaRuntime.load() +lua.writeFile('/scripts/greet.lua', 'return "hello"') + +const state = lua.createState() +await state.doString('return require("scripts.greet")') +``` + +`writeFile`, `readFile`, `readTextFile`, `exists`, `cwd` and `chdir` cover the everyday cases; +`lua.filesystem` is Emscripten's own API for everything else. + +### Reaching the host + +Two ways, and neither is the default: + +```js +// One host directory, at a path you choose. Node only. Nothing else on the host is reachable. +const lua = await LuaRuntime.load({ mounts: { '/scripts': './lua' } }) +await lua.createState().doString('return dofile("/scripts/init.lua")') + +// Or the real filesystem, with the process working directory, absolute paths and symlinks. +// Node only, and not a sandbox: Lua can read and write whatever the process can. +const cli = await LuaRuntime.load({ fs: 'host' }) +``` + +`mounts` maps the path Lua sees to a host directory that has to exist; mount points cannot nest, and +`lua.mount(virtualPath, hostPath)` / `lua.unmount(virtualPath)` do the same after loading. With +`fs: 'host'` there is nothing to mount, because every host path already resolves — and `lua.chdir` +moves the Node process itself, since a process has only one working directory. + +> [!WARNING] +> A filesystem is not a sandbox on its own. Lua's `os.execute` runs a real command through the shell +> in Node whichever filesystem you pick, and `os.exit` sets the host process exit code. Leave `os` +> out of the state (`createState({ libs: [...] })`) if untrusted code must not do either. + ## CLI Usage Although Wasmoon has been designed to be embedded, you can run it on command line as well, but, if you want something more robust on this, we recommend to take a look at [demoon](https://github.com/ceifa/demoon). diff --git a/bin/wasmoon b/bin/wasmoon index e3f754b..47611a9 100755 --- a/bin/wasmoon +++ b/bin/wasmoon @@ -331,7 +331,8 @@ async function run({ argv, actions, forceInteractive, showVersion, ignoreEnv, sc const lua = await LuaRuntime.load({ env: ignoreEnv ? undefined : process.env, - fs: 'node', + // An interpreter is expected to see the files the shell that started it sees. + fs: 'host', stdin: terminal.readLine, }) diff --git a/package-lock.json b/package-lock.json index 0e14f85..68cd436 100644 --- a/package-lock.json +++ b/package-lock.json @@ -26,6 +26,9 @@ "rolldown": "1.2.0", "tslib": "2.8.1", "typescript": "7.0.2" + }, + "engines": { + "node": ">=24" } }, "node_modules/@emnapi/wasi-threads": { diff --git a/package.json b/package.json index d46f859..c997139 100755 --- a/package.json +++ b/package.json @@ -15,8 +15,8 @@ "./package.json": "./package.json" }, "browser": { - "node:fs": false, - "node:module": false + "node:module": false, + "./dist/glue-host.js": false }, "sideEffects": false, "scripts": { @@ -34,7 +34,8 @@ }, "files": [ "bin/*", - "dist/*" + "dist/*", + "!dist/*.map" ], "engines": { "node": ">=24" diff --git a/rolldown.config.ts b/rolldown.config.ts index f6e553a..6a8ca3a 100644 --- a/rolldown.config.ts +++ b/rolldown.config.ts @@ -6,11 +6,24 @@ import { UNWIND_BRAND } from './src/utils' export default defineConfig({ input: './src/index.ts', output: { - file: 'dist/index.js', + // A directory rather than a single file, because the host filesystem glue that module.ts + // imports on demand has to stay a chunk of its own: a browser bundle then leaves it alone, + // and Node loads it only when someone asks for `fs: 'host'`. + dir: 'dist', + entryFileNames: 'index.js', + // Named rather than hashed, so the `browser` field in package.json can point at it. + chunkFileNames: 'glue-host.js', format: 'esm', sourcemap: true, + // The glue arrives from emcc already minified and rolldown would otherwise re-print it + // several kilobytes larger than it started. Consumers minify us anyway -- which the + // Bundling suite covers -- so doing it here only decides what the package and a CDN + // consumer download. The sourcemap keeps our own frames readable. + minify: { mangle: { toplevel: false } }, }, - external: ['node:module', 'node:fs'], + // Only the glue imports a node builtin now; the mounts reach node:fs through + // process.getBuiltinModule, which a bundler never has to resolve. + external: ['node:module'], plugins: [ { name: 'package-version', @@ -45,44 +58,76 @@ export default defineConfig({ }, }, { - // Both node builtins are imported behind a runtime check for Node, which a bundler - // targeting the browser does not see, so it refuses to resolve them. webpack takes the - // comment; the others go by the `browser` field in package.json. + // A node builtin is imported behind a runtime check for Node, which a bundler targeting + // the browser does not see, so it refuses to resolve it. webpack takes the comment; the + // others go by the `browser` field in package.json. + // + // In generateBundle rather than renderChunk because minification runs in between and + // strips comments: annotating earlier would leave the guard below passing while the + // published chunk had no annotation left in it. Column mappings on the one line this + // touches shift by the length of the comment, which only ever falls inside the glue -- + // whose source the next plugin drops from the sourcemap anyway. name: 'annotate-node-imports', - renderChunk(code) { - const annotated = code.replace(/import\((['"])(node:[^'"]+)\1\)/g, 'import(/* webpackIgnore: true */ $1$2$1)') - const missed = /import\((?!\s*\/\*)(['"])node:/.exec(annotated) - if (missed) { - this.error(`a node builtin import was left unannotated: ${missed[0]}`) + generateBundle(_options, bundle) { + for (const chunk of Object.values(bundle)) { + if (chunk.type !== 'chunk') { + continue + } + // Quotes of either kind, since a minifier picks its own, and the whitespace is + // not optional to match: an import the output happens to wrap over several lines + // is the same import, and skipping it would ship it unannotated. + chunk.code = chunk.code.replace(/import\(\s*(['"`])(node:[^'"`]+)\1\s*\)/g, 'import(/* webpackIgnore: true */ $1$2$1)') + const missed = /import\(\s*(?!\/\*)(['"`])node:/.exec(chunk.code) + if (missed) { + this.error(`${chunk.fileName} ships a node builtin import with no annotation: ${missed[0]}`) + } } - return { code: annotated, map: null } }, }, { - // The glue is generated and already minified onto one line, so carrying its 85 KB of - // source in the published sourcemap costs a tenth of the package to map frames nobody - // reads. The mappings stay, only the inlined copy of the file goes. - name: 'drop-glue-source-content', + // The glue is generated and already minified onto one line, so its source is not worth + // publishing: carrying it costs a tenth of the package to map frames nobody reads. What + // is left of each sourcemap depends on whether anything else is in the chunk. + name: 'trim-glue-sourcemaps', generateBundle(_options, bundle) { - // Rewritten through the emitted asset rather than the written file, because + // Rewritten through the emitted files rather than the written ones, because // `chunk.map` is a snapshot of the Rust side and mutating it does not carry over. - let dropped = false - for (const file of Object.values(bundle)) { - if (file.type !== 'asset' || !file.fileName.endsWith('.map')) { + // Counted per sourcemap: there is one for each glue now, and a single flag would + // call it a success while the other still shipped its copy. + let trimmed = 0 + for (const chunk of Object.values(bundle)) { + const map = bundle[`${chunk.fileName}.map`] + if (chunk.type !== 'chunk' || map?.type !== 'asset') { continue } - const map = JSON.parse(file.source as string) - const index = map.sources.findIndex((source: string) => source?.endsWith('glue.js')) - if (index < 0 || !map.sourcesContent?.[index]) { + const parsed = JSON.parse(map.source as string) + const index = parsed.sources.findIndex((source: string) => source?.endsWith('glue.js')) + if (index < 0) { continue } - map.sourcesContent[index] = null - file.source = JSON.stringify(map) - dropped = true + + if (parsed.sources.length === 1) { + // Nothing but the glue in this chunk, so the mappings lead only to a file + // that is not published and whose content is dropped below anyway. The whole + // sourcemap goes, and with it the comment pointing at it. + delete bundle[`${chunk.fileName}.map`] + chunk.code = chunk.code.replace(/\n?\/\/# sourceMappingURL=.*$/, '\n') + trimmed++ + continue + } + + if (!parsed.sourcesContent?.[index]) { + // A silent miss would quietly put the 85 KB back into every published package. + this.error(`${map.fileName} maps a glue but carries no source to drop`) + } + // Our own sources are in here too, so only the glue's copy of itself goes. + parsed.sourcesContent[index] = null + map.source = JSON.stringify(parsed) + trimmed++ } - if (!dropped) { - // A silent miss would quietly put the 85 KB back into every published package. - this.error('the glue source was not found in any sourcemap, so nothing was dropped') + // One for the entry's inlined glue, one for the host glue chunk. + if (trimmed !== 2) { + this.error(`expected to trim the glue out of 2 sourcemaps, trimmed ${trimmed}`) } }, }, diff --git a/src/index.ts b/src/index.ts index 06b2efb..b3f5360 100755 --- a/src/index.ts +++ b/src/index.ts @@ -12,6 +12,7 @@ export { type EmscriptenPath, type EnvironmentVariables, type LuaEmscriptenModule, + type LuaFileSystem, type LuaModuleOptions, } from './module' export { default as LuaTypeExtension } from './type-extension' diff --git a/src/module.ts b/src/module.ts index 3cc2207..69c26c9 100755 --- a/src/module.ts +++ b/src/module.ts @@ -9,6 +9,18 @@ import version from 'package-version' export type EnvironmentVariables = Record +/** + * Which filesystem the Lua states see. + * + * - `'memory'`: Emscripten's in-memory filesystem, holding nothing but `/tmp`, `/home` and `/dev`. + * Identical in every environment, and reaches nothing on the host until a directory is handed to + * it through {@link LuaModuleOptions.mounts}. + * - `'host'`: the real filesystem, through Node. Paths, the working directory, symlinks and + * permissions are the host's own, because every operation goes straight to `node:fs`. Node only, + * and no sandbox: Lua can read and write anything the process can. + */ +export type LuaFileSystem = 'memory' | 'host' + /** Emscripten's own path helpers, which work on the virtual filesystem rather than the host one. */ export interface EmscriptenPath { isAbs: (path: string) => boolean @@ -47,7 +59,10 @@ export interface LuaEmscriptenModule extends EmscriptenModule { _realloc: (pointer: number, size: number) => number } -/** The virtual filesystem every state on a runtime shares, as {@link LuaModule.emscripten}'s `FS`. */ +/** + * The filesystem every state on a runtime shares, as {@link LuaModule.emscripten}'s `FS`. In memory + * unless the module was loaded with `fs: 'host'`, where the same API acts on the real one. + */ export type EmscriptenFS = LuaEmscriptenModule['FS'] export interface LuaModuleOptions { @@ -58,10 +73,16 @@ export interface LuaModuleOptions { wasmFile?: string | undefined /** Environment variables for the Lua states. */ env?: EnvironmentVariables | undefined - /** File system that should be used. */ - fs?: 'node' | 'memory' | undefined - /** Host directories to mount when `fs` is `'node'`. Defaults to the drive holding the CWD. */ - fsMountPaths?: string[] | undefined + /** Which filesystem the Lua states see. Defaults to `'memory'`. */ + fs?: LuaFileSystem | undefined + /** + * Host directories to expose in the in-memory filesystem, keyed by the absolute path Lua sees. + * `{ '/scripts': './lua' }` makes `./lua/init.lua` readable and writable as `/scripts/init.lua` + * and leaves the rest of the host unreachable. Node only, and only with `fs: 'memory'`. + * + * Mount points cannot nest, and a host path has to name a directory that already exists. + */ + mounts?: Readonly> | undefined /** Called once per read. An empty string (or nothing) means EOF. */ stdin?: (() => string | null | undefined) | undefined /** @@ -138,6 +159,122 @@ interface ReferenceMetadata { refCount: number } +/** A {@link LuaModuleOptions.mounts} entry with both sides checked, ready for `FS.mount`. */ +interface ResolvedMount { + /** Absolute, with no trailing slash and no `.` or `..` in it. */ + virtualPath: string + /** Absolute host path of a directory that exists. */ + hostPath: string +} + +// The only rule about `mounts` that is not about a single mount, so both the option and the method +// report it with one voice. +const MOUNTS_NEED_MEMORY_FS = `mounts belong to fs: 'memory'; with 'host' every host path is already reachable` + +/** + * Synchronous and lazy, which is what lets a mount be added after loading without the load path + * paying for a `node:fs` import it usually has no use for. Null anywhere but Node. + */ +function nodeBuiltin(name: string): T | null { + return (globalThis.process?.getBuiltinModule?.(name) as T | undefined) ?? null +} + +/** + * Nothing here is left to fail later: an unreadable host path, or a mount point Emscripten would + * put somewhere unexpected, is an error at once rather than a directory that silently turns up empty. + */ +function resolveMount(virtualPath: string, hostPath: string): ResolvedMount { + const where = `cannot mount '${hostPath}' at '${virtualPath}'` + + const fs = nodeBuiltin('node:fs') + const path = nodeBuiltin('node:path') + if (!fs || !path) { + throw new Error(`${where}: reaching a host directory needs node:fs, which only Node has`) + } + + // Absolute, at least one segment deep, and nothing that would move the mount elsewhere. Not + // normalized on the caller's behalf, so a path that means something else is refused rather than + // quietly changed. + const mountPoint = virtualPath.replace(/\/+$/, '') + if (!/^(\/[^/]+)+$/.test(mountPoint)) { + throw new Error(`${where}: the mount point has to be an absolute path below the root, such as '/scripts'`) + } + if (mountPoint.split('/').some((segment) => segment === '.' || segment === '..')) { + throw new Error(`${where}: the mount point has to be a normalized path, with no '.' or '..' segments`) + } + + if (hostPath.startsWith('~')) { + // Expanded by a shell rather than by node:path, so it would resolve to a directory named + // '~' below the cwd -- which is never what the caller meant. + throw new Error(`${where}: '~' is not expanded, so pass an absolute path (os.homedir() and a join)`) + } + const root = path.resolve(hostPath) + + let isDirectory: boolean + try { + isDirectory = fs.statSync(root).isDirectory() + } catch (err) { + throw new Error(`${where}: '${root}' could not be read`, { cause: err }) + } + if (!isDirectory) { + // NODEFS mounts lazily and would not notice until the first lookup inside it failed. + throw new Error(`${where}: '${root}' is not a directory`) + } + + return { virtualPath: mountPoint, hostPath: root } +} + +/** + * A mount inside another one would have its mount point created on the host it is mounted from, so + * the two have to be disjoint. Checked against the mounts that are already live, which is what makes + * the rule the same whether a mount arrives with the options or afterwards. + */ +function assertMountFits(live: readonly ResolvedMount[], candidate: ResolvedMount): void { + // The trailing slash on both sides keeps '/scripts2' from counting as being inside '/scripts', + // and an equal pair matches in both directions, so a mount point is never claimed twice. + const overlapping = live.find( + (mount) => + `${candidate.virtualPath}/`.startsWith(`${mount.virtualPath}/`) || + `${mount.virtualPath}/`.startsWith(`${candidate.virtualPath}/`), + ) + if (overlapping) { + throw new Error(`cannot mount at '${candidate.virtualPath}': it overlaps the mount point '${overlapping.virtualPath}'`) + } +} + +/** Everything the wasm module needs before it starts, and nothing that outlives that. */ +interface PreRunConfig { + env: EnvironmentVariables | undefined + mounts: readonly ResolvedMount[] + stdin: LuaModuleOptions['stdin'] + stdout: LuaModuleOptions['stdout'] + stderr: LuaModuleOptions['stderr'] +} + +/** + * Built from a record rather than closed over `initialize`'s scope, because Emscripten keeps + * `Module.preRun` for the module's lifetime and a closure would pin everything around it with it. + */ +function createPreRun(config: PreRunConfig): (initializedModule: LuaEmscriptenModule) => void { + return (initializedModule: LuaEmscriptenModule): void => { + if (typeof config.env === 'object') { + Object.assign(initializedModule.ENV, config.env) + } + + // Nothing to do for `fs: 'host'`: that glue is NODERAWFS, so the filesystem already is the + // host's, working directory included. + for (const { virtualPath, hostPath } of config.mounts) { + const fs = initializedModule.FS + fs.mkdirTree(virtualPath) + fs.mount(fs.filesystems.NODEFS, { root: hostPath }, virtualPath) + } + + if (config.stdin || config.stdout || config.stderr) { + initializedModule.FS.init(createInputReader(config.stdin), createOutputWriter(config.stdout), createOutputWriter(config.stderr)) + } + } +} + export default class LuaModule { public static async initialize(opts: Readonly = {}): Promise { const warn = opts.onWarn ?? defaultWarnHandler @@ -145,7 +282,25 @@ export default class LuaModule { // Node with a DOM bolted on, and asking about `window` gets those wrong. const isNode = typeof globalThis.process?.versions?.node === 'string' - const fs = isNode && opts.fs === 'node' ? await import('node:fs') : null + const fs = opts.fs ?? 'memory' + const mountEntries = Object.entries(opts.mounts ?? {}) + + if (fs === 'host' && !isNode) { + throw new Error(`fs: 'host' is the real filesystem, which only Node has; elsewhere use the default 'memory' one`) + } + if (fs === 'host' && mountEntries.length > 0) { + throw new Error(MOUNTS_NEED_MEMORY_FS) + } + + // Resolved before the wasm is instantiated, so a mount that cannot work fails the load + // rather than leaving a module behind. Each one is checked against those already accepted, + // which is the same rule LuaModule.mount applies to a later arrival. + const mounts: ResolvedMount[] = [] + for (const [virtualPath, hostPath] of mountEntries) { + const mount = resolveMount(virtualPath, hostPath) + assertMountFits(mounts, mount) + mounts.push(mount) + } // Emscripten reports load failures itself, which is noise while one can still be recovered // from below, so they are held until the outcome is known. Null once handed over. @@ -158,74 +313,23 @@ export default class LuaModule { } } - const preRun = (initializedModule: LuaEmscriptenModule): void => { - if (typeof opts?.env === 'object') { - Object.assign(initializedModule.ENV, opts.env) - } - - if (fs) { - const cwd = process.cwd().replace(/\\/g, '/') - // Default to mounting the drive containing the CWD - const cwdDrive = process.platform === 'win32' ? cwd.slice(0, 3) : '/' - const mountPaths = opts.fsMountPaths ?? [cwdDrive] - - // Deduplicate and remove paths that are children of other mount paths - const normalized = [...new Set(mountPaths.map((p) => p.replace(/\\/g, '/')))] - const filtered = normalized.filter((path) => !normalized.some((other) => other !== path && path.startsWith(other + '/'))) - - // Expand drive roots into their subdirectories, since - // Emscripten's VFS already owns "/" and cannot be mounted over. - // Skip virtual/system filesystems that cause issues with NODEFS. - const skipDirs = ['dev', 'proc', 'sys', 'run', 'snap', 'System Volume Information', '$Recycle.Bin', 'Recovery'] - const expanded: string[] = [] - for (const dir of filtered) { - const isDriveRoot = dir === '/' || /^[A-Za-z]:\/$/.test(dir) - if (isDriveRoot) { - try { - const children = fs - .readdirSync(dir) - .filter((child: string) => !skipDirs.includes(child)) - .map((child: string) => (dir === '/' ? `/${child}` : `${dir}${child}`.replace(/\\/g, '/'))) - expanded.push(...children) - } catch { - // drive not readable - } - } else { - expanded.push(dir) - } - } + const preRun = createPreRun({ env: opts.env, mounts, stdin: opts.stdin, stdout: opts.stdout, stderr: opts.stderr }) - for (const dir of expanded) { - try { - const moduleFS = initializedModule.FS - moduleFS.mkdirTree(dir) - moduleFS.mount(moduleFS.filesystems.NODEFS, { root: dir }, dir) - } catch (err: any) { - // Ignore permission/not-found errors from both Node.js - // (string .code) and Emscripten ErrnoError (numeric .errno) - const isIgnorableError = ['EACCES', 'EPERM', 'ENOENT'].includes(err?.code) || err?.name === 'ErrnoError' - if (!isIgnorableError) { - warn(`Failed to mount ${dir}`, err) - } - } - } - - try { - initializedModule.FS.chdir(cwd) - } catch { - // CWD may not be within mounted paths - } - } - - if (opts.stdin || opts.stdout || opts.stderr) { - initializedModule.FS.init(createInputReader(opts.stdin), createOutputWriter(opts.stdout), createOutputWriter(opts.stderr)) - } + // Two glues over the one wasm, differing only in their filesystem (see + // utils/build-wasm.sh). The host one is imported on demand, both because it throws outside + // Node and so that a browser bundle leaves it in a chunk it never loads. + const init = fs === 'host' ? (await import('../build/host/glue.js')).default : initWasmModule + if (typeof init !== 'function') { + // The `browser` field points bundlers at a stub, since the glue only runs under Node. + throw new Error(`fs: 'host' needs glue-host.js, which the bundle replaced with a stub because it targets the browser`) } const load = async (wasmFile?: string): Promise => { return new LuaModule( - await initWasmModule({ ...(wasmFile === undefined ? {} : { locateFile: () => wasmFile }), preRun, printErr }), + await init({ ...(wasmFile === undefined ? {} : { locateFile: () => wasmFile }), preRun, printErr }), opts.onWarn, + fs, + mounts, ) } @@ -274,6 +378,8 @@ export default class LuaModule { public emscripten: LuaEmscriptenModule /** The handler passed to {@link LuaModule.initialize}, which states created on it inherit. */ public readonly onWarn: LuaWarnHandler | undefined + /** Which filesystem this module was loaded with, as {@link LuaModuleOptions.fs}. */ + public readonly fs: LuaFileSystem public luaL_checkversion_: (L: LuaAddress, ver: number, sz: number) => void public luaL_getmetafield: (L: LuaAddress, obj: number, e: string | null) => LuaType @@ -430,6 +536,9 @@ export default class LuaModule { public luaopen_package: (L: LuaAddress) => number public luaL_openlibs: (L: LuaAddress) => void + /** The mounts that are live, so a later one can be checked against them. */ + private readonly mounts: ResolvedMount[] + private readonly cStringCache = new Map() private readonly trampolineModules = new Map() private referenceTracker = new WeakMap() @@ -450,9 +559,16 @@ export default class LuaModule { public readonly resultCountScratch: number private stringBuffer = 0 - public constructor(module: LuaEmscriptenModule, onWarn?: LuaWarnHandler) { + public constructor( + module: LuaEmscriptenModule, + onWarn?: LuaWarnHandler, + fs: LuaFileSystem = 'memory', + mounts: readonly ResolvedMount[] = [], + ) { this.emscripten = module this.onWarn = onWarn + this.fs = fs + this.mounts = [...mounts] this.luaL_checkversion_ = this.cwrap('luaL_checkversion_', null, ['number', 'number', 'number']) this.luaL_getmetafield = this.cwrap('luaL_getmetafield', 'number', ['number', 'number', 'string']) @@ -614,6 +730,35 @@ export default class LuaModule { } } + /** + * Exposes a host directory in the in-memory filesystem, the way {@link LuaModuleOptions.mounts} + * does at load time and with the same checks. Node only, and only with `fs: 'memory'`. + */ + public mount(virtualPath: string, hostPath: string): void { + if (this.fs === 'host') { + throw new Error(MOUNTS_NEED_MEMORY_FS) + } + + const mount = resolveMount(virtualPath, hostPath) + assertMountFits(this.mounts, mount) + + const fs = this.emscripten.FS + fs.mkdirTree(mount.virtualPath) + fs.mount(fs.filesystems.NODEFS, { root: mount.hostPath }, mount.virtualPath) + this.mounts.push(mount) + } + + /** Detaches a {@link LuaModule.mount}, leaving its mount point behind as an empty directory. */ + public unmount(virtualPath: string): void { + this.emscripten.FS.unmount(virtualPath) + // Dropped only once Emscripten agrees it was a mount point, so a failed unmount leaves the + // bookkeeping matching what is actually mounted. + const index = this.mounts.findIndex((mount) => mount.virtualPath === virtualPath) + if (index >= 0) { + this.mounts.splice(index, 1) + } + } + /** * Bytes that aren't valid UTF-8 are replaced with U+FFFD. Use {@link lua_tobytes} when the * value holds arbitrary binary data (`string.dump`, `string.pack`, ciphertext, ...). diff --git a/src/runtime.ts b/src/runtime.ts index 527a879..e60de6a 100755 --- a/src/runtime.ts +++ b/src/runtime.ts @@ -41,15 +41,57 @@ export default class LuaRuntime { } /** - * Writes a file into the Lua environment, creating its directories as needed. - * @param path - Path to the file in the Lua environment. - * @param content - Content of the file to be mounted. + * Writes a file the Lua states can read, creating its directories as needed. A relative path is + * resolved against {@link cwd}. + * + * With `fs: 'host'`, and inside a mount, this writes to the real filesystem. */ - public mountFile(path: string, content: string | ArrayBufferView): void { - this.filesystem.mkdirTree(this.path.dirname(path)) + public writeFile(path: string, content: string | ArrayBufferView): void { + // Only when it is missing: mkdirTree walks every level and finds out by way of a thrown + // EEXIST, which costs several times the write itself once the directory is there -- and a + // real syscall per level with `fs: 'host'`. + const parent = this.path.dirname(path) + if (!this.exists(parent)) { + this.filesystem.mkdirTree(parent) + } this.filesystem.writeFile(path, content) } + /** The bytes of a file, for content that is not text. */ + public readFile(path: string): Uint8Array { + return this.filesystem.readFile(path) + } + + /** A file decoded as UTF-8, with invalid bytes replaced by U+FFFD. */ + public readTextFile(path: string): string { + return this.filesystem.readFile(path, { encoding: 'utf8' }) + } + + public exists(path: string): boolean { + return this.filesystem.analyzePath(path).exists + } + + /** Where relative paths resolve from, `/` unless something changed it or `fs` is `'host'`. */ + public cwd(): string { + return this.filesystem.cwd() + } + + /** With `fs: 'host'` this moves the Node process itself, since there is only one working directory. */ + public chdir(path: string): void { + this.filesystem.chdir(path) + } + + /** See {@link LuaModuleOptions.mounts}, whose entries this is the after-the-fact equivalent of. */ + public mount(virtualPath: string, hostPath: string): void { + this.module.mount(virtualPath, hostPath) + } + + /** See {@link LuaModule.unmount}. */ + public unmount(virtualPath: string): void { + this.module.unmount(virtualPath) + } + + /** Emscripten's own filesystem API, for everything the methods above do not cover. */ public get filesystem(): EmscriptenFS { return this.module.emscripten.FS } diff --git a/test/browser.test.js b/test/browser.test.js index aa28806..df3a134 100644 --- a/test/browser.test.js +++ b/test/browser.test.js @@ -180,7 +180,7 @@ describe('Browser environment', () => { this.timeout(30_000) const result = await runInBrowser(` const lua = await LuaRuntime.load({ wasmFile }) - lua.mountFile('mymodule.lua', 'return 42') + lua.writeFile('mymodule.lua', 'return 42') const state = lua.createState() return await state.doString('return require("mymodule")') `) diff --git a/test/bundling.test.js b/test/bundling.test.js index 5eec36e..05010f6 100644 --- a/test/bundling.test.js +++ b/test/bundling.test.js @@ -1,3 +1,4 @@ +import { existsSync } from 'node:fs' import { mkdtemp, readFile, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -23,9 +24,17 @@ describe('Bundling', () => { const bundle = await rolldown({ input: join(DIST_DIR, 'index.js'), - external: ['node:module', 'node:fs'], + external: ['node:module'], + }) + // A directory rather than a single file, because the host filesystem glue stays a chunk of + // its own -- which is also how a consumer has to bundle us when they target Node. + await bundle.write({ + dir: tempDir, + entryFileNames: 'index.js', + chunkFileNames: 'glue-host.js', + format: 'esm', + minify: true, }) - await bundle.write({ file: join(tempDir, 'index.js'), format: 'esm', minify: true }) await bundle.close() minified = await import(join(tempDir, 'index.js')) @@ -42,6 +51,19 @@ describe('Bundling', () => { return lua.createState({ inject: true, ...config }) } + it('the published host glue is the one the browser field stubs out', async () => { + // The name lives in three places that nothing else connects: rolldown's chunkFileNames, the + // `browser` field, and the import in module.ts. A rename in one of them would either ship + // the node-only glue into browser bundles or break fs: 'host', both of them quietly. + const pkg = JSON.parse(await readFile(fileURLToPath(new URL('../package.json', import.meta.url)), 'utf8')) + const stubbed = Object.keys(pkg.browser).filter((key) => key.includes('glue')) + + expect(stubbed).to.have.lengthOf(1) + expect(pkg.browser[stubbed[0]]).to.be.false + expect(join(DIST_DIR, stubbed[0].replace('./dist/', ''))).to.satisfy(existsSync) + expect(await readFile(join(DIST_DIR, 'index.js'), 'utf8')).to.include(stubbed[0].replace('./dist/', './')) + }) + it('minifying the bundle renames the unwind classes', async () => { // The premise of the tests below: a check by class name has nothing left to match on. const code = await readFile(join(tempDir, 'index.js'), 'utf8') diff --git a/test/filesystem.test.js b/test/filesystem.test.js index 3846d72..19da1a8 100644 --- a/test/filesystem.test.js +++ b/test/filesystem.test.js @@ -2,9 +2,9 @@ import { expect } from 'chai' import { getState, getLua } from './utils.js' describe('Filesystem', () => { - it('mount a file and require inside lua should succeed', async () => { + it('write a file and require inside lua should succeed', async () => { const lua = await getLua() - lua.mountFile('test.lua', 'answerToLifeTheUniverseAndEverything = 42') + lua.writeFile('test.lua', 'answerToLifeTheUniverseAndEverything = 42') const state = lua.createState() await state.doString('require("test")') @@ -12,9 +12,9 @@ describe('Filesystem', () => { expect(state.get('answerToLifeTheUniverseAndEverything')).to.be.equal(42) }) - it('mount a file in a complex directory and require inside lua should succeed', async () => { + it('write a file in a complex directory and require inside lua should succeed', async () => { const lua = await getLua() - lua.mountFile('yolo/sofancy/test.lua', 'return 42') + lua.writeFile('yolo/sofancy/test.lua', 'return 42') const state = lua.createState() const value = await state.doString('return require("yolo/sofancy/test")') @@ -22,9 +22,9 @@ describe('Filesystem', () => { expect(value).to.be.equal(42) }) - it('mount a init file and require the module inside lua should succeed', async () => { + it('write a init file and require the module inside lua should succeed', async () => { const lua = await getLua() - lua.mountFile('hello/init.lua', 'return 42') + lua.writeFile('hello/init.lua', 'return 42') const state = lua.createState() const value = await state.doString('return require("hello")') @@ -32,48 +32,89 @@ describe('Filesystem', () => { expect(value).to.be.equal(42) }) - it('require a file which is not mounted should throw', async () => { + it('require a file which was not written should throw', async () => { using state = await getState() await expect(state.doString('require("nothing")')).to.eventually.be.rejectedWith(/module 'nothing' not found/) }) - it('mount a file and run it should succeed', async () => { + it('write a file and run it should succeed', async () => { const lua = await getLua() const state = lua.createState() - lua.mountFile('init.lua', `return 42`) + lua.writeFile('init.lua', `return 42`) const value = await state.doFile('init.lua') expect(value).to.be.equal(42) }) - it('run a file which is not mounted should throw', async () => { + it('run a file which was not written should throw', async () => { using state = await getState() await expect(state.doFile('init.lua')).to.eventually.be.rejectedWith(/cannot open init\.lua/) }) - it('mount a file with binary content should succeed', async () => { + it('write a file with binary content should succeed', async () => { const lua = await getLua() using state = lua.createState() - lua.mountFile('binary.lua', new Uint8Array([114, 101, 116, 117, 114, 110, 32, 52, 50])) // "return 42" + lua.writeFile('binary.lua', new Uint8Array([114, 101, 116, 117, 114, 110, 32, 52, 50])) // "return 42" expect(await state.doString('return dofile("binary.lua")')).to.be.equal(42) }) - it('doFileSync should run a mounted file synchronously', async () => { + it('doFileSync should run a written file synchronously', async () => { const lua = await getLua() - lua.mountFile('sync.lua', 'return 5 * 5') + lua.writeFile('sync.lua', 'return 5 * 5') using state = lua.createState() expect(state.doFileSync('sync.lua')).to.be.equal(25) }) + it('the default filesystem should be the in-memory one', async () => { + const lua = await getLua() + + expect(lua.module.fs).to.be.equal('memory') + // Nothing of the host is reachable, and relative paths resolve from the root. + expect(lua.cwd()).to.be.equal('/') + }) + + it('readFile should return what lua wrote', async () => { + const lua = await getLua() + using state = lua.createState() + + await state.doString(` + local f = io.open("/written.txt", "w") + f:write("from lua") + f:close() + `) + + expect(lua.readTextFile('/written.txt')).to.be.equal('from lua') + expect(lua.readFile('/written.txt')).to.be.deep.equal(new Uint8Array([102, 114, 111, 109, 32, 108, 117, 97])) + }) + + it('exists should report both a written and a missing file', async () => { + const lua = await getLua() + lua.writeFile('/present.lua', 'return 1') + + expect(lua.exists('/present.lua')).to.be.true + expect(lua.exists('/absent.lua')).to.be.false + }) + + it('chdir should move where relative paths resolve from', async () => { + const lua = await getLua() + lua.writeFile('/somewhere/mod.lua', 'return "found"') + using state = lua.createState() + + lua.chdir('/somewhere') + + expect(lua.cwd()).to.be.equal('/somewhere') + expect(await state.doFile('mod.lua')).to.be.equal('found') + }) + it('filesystem should expose the shared emscripten FS', async () => { const lua = await getLua() - lua.mountFile('fs-probe.lua', 'return 1') + lua.writeFile('fs-probe.lua', 'return 1') expect(lua.filesystem.analyzePath('/fs-probe.lua').exists).to.be.true }) @@ -85,12 +126,12 @@ describe('Filesystem', () => { expect(lua.path.basename('/a/b/c.lua')).to.be.equal('c.lua') }) - it('mount a file with a large content should succeed', async () => { + it('write a file with a large content should succeed', async () => { const lua = await getLua() const state = lua.createState() const content = 'a'.repeat(1000000) - lua.mountFile('init.lua', `local a = "${content}" return a`) + lua.writeFile('init.lua', `local a = "${content}" return a`) const value = await state.doFile('init.lua') expect(value).to.be.equal(content) diff --git a/test/host-filesystem.test.js b/test/host-filesystem.test.js new file mode 100644 index 0000000..51c007d --- /dev/null +++ b/test/host-filesystem.test.js @@ -0,0 +1,341 @@ +import { readFileSync, writeFileSync, mkdirSync, existsSync, symlinkSync, realpathSync } from 'node:fs' +import { join } from 'node:path' +import { expect } from 'chai' +import { LuaRuntime } from '../dist/index.js' +import { luaPath, readFileFromLua, useTempDirs } from './utils.js' + +describe('Host filesystem', () => { + // fs: 'host' has no working directory of its own -- chdir moves the Node process, so a test that + // moves into a temp directory has to come back. Registered before useTempDirs so it runs before + // the directory the process may be sitting in is removed. + const originalCwd = process.cwd() + afterEach(() => process.chdir(originalCwd)) + + const createTempDir = useTempDirs('host') + let tempDir + let lua + let state + + beforeEach(async () => { + tempDir = createTempDir() + lua = await LuaRuntime.load({ fs: 'host' }) + state = lua.createState() + }) + + afterEach(() => lua.close()) + + /** Absolute host path of `name` inside the temp directory, as a Lua string literal. */ + const at = (...name) => luaPath(join(tempDir, ...name)) + + it('read a host file should succeed', () => { + writeFileSync(join(tempDir, 'hello.txt'), 'hello world') + + expect(readFileFromLua(state, at('hello.txt'))).to.be.equal('hello world') + }) + + it('write a file to host should succeed', async () => { + await state.doString(` + local f = io.open("${at('output.txt')}", "w") + f:write("written from lua") + f:close() + `) + + expect(readFileSync(join(tempDir, 'output.txt'), 'utf8')).to.be.equal('written from lua') + }) + + it('append to a host file should succeed', async () => { + writeFileSync(join(tempDir, 'append.txt'), 'first line\n') + + await state.doString(` + local f = io.open("${at('append.txt')}", "a") + f:write("second line\\n") + f:close() + `) + + expect(readFileSync(join(tempDir, 'append.txt'), 'utf8')).to.be.equal('first line\nsecond line\n') + }) + + it('read file line by line should succeed', async () => { + writeFileSync(join(tempDir, 'lines.txt'), 'alpha\nbeta\ngamma\n') + + const result = await state.doString(` + local lines = {} + for line in io.lines("${at('lines.txt')}") do + lines[#lines + 1] = line + end + return table.concat(lines, ",") + `) + + expect(result).to.be.equal('alpha,beta,gamma') + }) + + it('read binary file should succeed', async () => { + writeFileSync(join(tempDir, 'binary.dat'), Buffer.from([0x00, 0x01, 0x02, 0xff, 0xfe])) + + const result = await state.doString(` + local f = io.open("${at('binary.dat')}", "rb") + local data = f:read("*a") + f:close() + return #data + `) + + expect(result).to.be.equal(5) + }) + + it('write and read back binary data should succeed', async () => { + await state.doString(` + local f = io.open("${at('binout.dat')}", "wb") + f:write(string.char(72, 101, 108, 108, 111)) + f:close() + `) + + expect(readFileSync(join(tempDir, 'binout.dat'), 'utf8')).to.be.equal('Hello') + }) + + it('check if file exists using io.open should succeed', async () => { + writeFileSync(join(tempDir, 'exists.txt'), 'yes') + + const result = await state.doString(` + local f = io.open("${at('exists.txt')}", "r") + local exists = f ~= nil + if f then f:close() end + + local f2 = io.open("${at('nope.txt')}", "r") + local not_exists = f2 == nil + if f2 then f2:close() end + + return exists and not_exists + `) + + expect(result).to.be.true + }) + + it('read file size should succeed', async () => { + writeFileSync(join(tempDir, 'sized.txt'), 'abcdefghij') + + const result = await state.doString(` + local f = io.open("${at('sized.txt')}", "r") + local size = f:seek("end") + f:close() + return size + `) + + expect(result).to.be.equal(10) + }) + + it('seek within a file should succeed', async () => { + writeFileSync(join(tempDir, 'seek.txt'), 'abcdefghij') + + const result = await state.doString(` + local f = io.open("${at('seek.txt')}", "r") + f:seek("set", 3) + local chunk = f:read(4) + f:close() + return chunk + `) + + expect(result).to.be.equal('defg') + }) + + it('doFile from host filesystem should succeed', async () => { + writeFileSync(join(tempDir, 'script.lua'), 'return 7 * 6') + + expect(await state.doFile(at('script.lua'))).to.be.equal(42) + }) + + it('require a host lua file should succeed', async () => { + const luaDir = join(tempDir, 'lualibs') + mkdirSync(luaDir, { recursive: true }) + writeFileSync(join(luaDir, 'mymod.lua'), 'local M = {}; M.value = 99; return M') + + using injected = lua.createState({ inject: true }) + const result = await injected.doString(` + package.path = "${at('lualibs')}/?.lua;" .. package.path + local m = require("mymod") + return m.value + `) + + expect(result).to.be.equal(99) + }) + + it('read from nested directories should succeed', () => { + const nested = join(tempDir, 'a', 'b', 'c') + mkdirSync(nested, { recursive: true }) + writeFileSync(join(nested, 'deep.txt'), 'deep content') + + expect(readFileFromLua(state, join(nested, 'deep.txt'))).to.be.equal('deep content') + }) + + it('read through a host symlink should succeed', () => { + // A mirror of the host namespace resolves an absolute symlink target against itself rather + // than against the host, so this only works when the filesystem really is the host's. + writeFileSync(join(tempDir, 'target.txt'), 'behind the link') + symlinkSync(join(tempDir, 'target.txt'), join(tempDir, 'absolute.link')) + symlinkSync('target.txt', join(tempDir, 'relative.link')) + + expect(readFileFromLua(state, at('absolute.link'))).to.be.equal('behind the link') + expect(readFileFromLua(state, at('relative.link'))).to.be.equal('behind the link') + }) + + it('create directory from lua with os.execute should succeed', async () => { + await state.doString(`os.execute("mkdir -p '${at('newdir')}'")`) + + expect(existsSync(join(tempDir, 'newdir'))).to.be.true + }) + + it('remove a host file from lua with os.remove should succeed', async () => { + writeFileSync(join(tempDir, 'removeme.txt'), 'to be deleted') + + expect(await state.doString(`return os.remove("${at('removeme.txt')}")`)).to.be.true + expect(existsSync(join(tempDir, 'removeme.txt'))).to.be.false + }) + + it('rename a host file from lua with os.rename should succeed', async () => { + writeFileSync(join(tempDir, 'old.txt'), 'rename me') + + const result = await state.doString(`return os.rename("${at('old.txt')}", "${at('new.txt')}")`) + + expect(result).to.be.true + expect(existsSync(join(tempDir, 'old.txt'))).to.be.false + expect(readFileSync(join(tempDir, 'new.txt'), 'utf8')).to.be.equal('rename me') + }) + + it('the working directory should be the host process one', () => { + expect(lua.cwd()).to.be.equal(process.cwd()) + }) + + it('a relative path should resolve against the host working directory', async () => { + writeFileSync(join(tempDir, 'relative.lua'), 'return "from cwd"') + + lua.chdir(tempDir) + + // realpath, because the temp directory sits behind a symlink on macOS and the working + // directory is always the resolved one. + expect(lua.cwd()).to.be.equal(realpathSync(tempDir)) + // chdir moved the process, so Node agrees on where "here" is. + expect(process.cwd()).to.be.equal(realpathSync(tempDir)) + expect(await state.doFile('relative.lua')).to.be.equal('from cwd') + }) + + it('writeFile should write to the real filesystem', async () => { + lua.writeFile(at('nested', 'written.lua'), 'return "written"') + + expect(readFileSync(join(tempDir, 'nested', 'written.lua'), 'utf8')).to.be.equal('return "written"') + expect(await state.doFile(at('nested', 'written.lua'))).to.be.equal('written') + }) + + it('write large file should succeed', async () => { + const lineCount = 10000 + + await state.doString(` + local f = io.open("${at('large.txt')}", "w") + for i = 1, ${lineCount} do + f:write("line " .. i .. "\\n") + end + f:close() + `) + + const lines = readFileSync(join(tempDir, 'large.txt'), 'utf8').trimEnd().split('\n') + expect(lines.length).to.be.equal(lineCount) + expect(lines[0]).to.be.equal('line 1') + expect(lines[lineCount - 1]).to.be.equal(`line ${lineCount}`) + }) + + it('overwrite existing file should succeed', async () => { + writeFileSync(join(tempDir, 'overwrite.txt'), 'original content') + + await state.doString(` + local f = io.open("${at('overwrite.txt')}", "w") + f:write("new content") + f:close() + `) + + expect(readFileSync(join(tempDir, 'overwrite.txt'), 'utf8')).to.be.equal('new content') + }) + + it('read UTF-8 content should succeed', () => { + const content = 'héllo wörld 日本語 🌍' + writeFileSync(join(tempDir, 'utf8.txt'), content) + + expect(readFileFromLua(state, at('utf8.txt'))).to.be.equal(content) + }) + + it('write UTF-8 content should succeed', async () => { + await state.doString(` + local f = io.open("${at('utf8out.txt')}", "w") + f:write("café ñ 中文") + f:close() + `) + + expect(readFileSync(join(tempDir, 'utf8out.txt'), 'utf8')).to.be.equal('café ñ 中文') + }) + + it('read empty file should succeed', async () => { + writeFileSync(join(tempDir, 'empty.txt'), '') + + const result = await state.doString(` + local f = io.open("${at('empty.txt')}", "r") + local data = f:read("*a") + f:close() + return #data + `) + + expect(result).to.be.equal(0) + }) + + it('open non-existent file for reading should return nil and a message', async () => { + const result = await state.doString(` + local f, err = io.open("${at('nonexistent.txt')}", "r") + return f == nil and type(err) == "string" and #err > 0 + `) + + expect(result).to.be.true + }) + + it('io.tmpfile should succeed', async () => { + const result = await state.doString(` + local f = io.tmpfile() + f:write("temp data") + f:seek("set") + local data = f:read("*a") + f:close() + return data + `) + + expect(result).to.be.equal('temp data') + }) + + it('multiple states sharing the same filesystem should succeed', async () => { + using other = lua.createState() + + await state.doString(` + local f = io.open("${at('shared.txt')}", "w") + f:write("from state1") + f:close() + `) + + expect(readFileFromLua(other, at('shared.txt'))).to.be.equal('from state1') + }) + + it('read number from file should succeed', async () => { + writeFileSync(join(tempDir, 'numbers.txt'), '42\n3.14\n100') + + const result = await state.doString(` + local f = io.open("${at('numbers.txt')}", "r") + local n1 = f:read("*n") + local n2 = f:read("*n") + local n3 = f:read("*n") + f:close() + return n1 + n2 + n3 + `) + + expect(result).to.be.closeTo(145.14, 0.001) + }) + + it('mounts should be rejected, since every host path is already reachable', async () => { + await expect(LuaRuntime.load({ fs: 'host', mounts: { '/scripts': tempDir } })).to.eventually.be.rejectedWith( + /mounts belong to fs: 'memory'/, + ) + expect(() => lua.mount('/scripts', tempDir)).to.throw(/mounts belong to fs: 'memory'/) + }) +}) diff --git a/test/luatests.js b/test/luatests.js index e873287..c75a8a8 100644 --- a/test/luatests.js +++ b/test/luatests.js @@ -6,7 +6,7 @@ const lua = await LuaRuntime.load() const testsPath = import.meta.resolve('../lua/testes') const filePath = fileURLToPath(typeof testsPath === 'string' ? testsPath : await Promise.resolve(testsPath)) -if (!lua.filesystem.analyzePath('/dev/full').exists) { +if (!lua.exists('/dev/full')) { const deviceMode = lua.filesystem.lookupPath('/dev/null').node.mode const fullDevice = lua.filesystem.makedev(64, 0) lua.filesystem.registerDevice(fullDevice, { @@ -29,7 +29,7 @@ if (!lua.filesystem.analyzePath('/dev/full').exists) { for await (const file of glob(`${filePath}/**/*.lua`)) { const relativeFile = file.replace(`${filePath}/`, '') - lua.mountFile(relativeFile, await readFile(file)) + lua.writeFile(relativeFile, await readFile(file)) } const state = lua.createState() diff --git a/test/mounts.test.js b/test/mounts.test.js new file mode 100644 index 0000000..1c3bf46 --- /dev/null +++ b/test/mounts.test.js @@ -0,0 +1,141 @@ +import { readFileSync, writeFileSync, mkdirSync } from 'node:fs' +import { join } from 'node:path' +import { expect } from 'chai' +import { LuaRuntime } from '../dist/index.js' +import { readFileFromLua, useTempDirs } from './utils.js' + +describe('Mounts', () => { + const createTempDir = useTempDirs('mounts') + let hostDir + let outsideDir + + beforeEach(() => { + hostDir = createTempDir() + outsideDir = createTempDir() + writeFileSync(join(hostDir, 'inside.txt'), 'mounted content') + writeFileSync(join(outsideDir, 'outside.txt'), 'should stay unreachable') + }) + + it('the in-memory filesystem alone should reach nothing on the host', async () => { + const lua = await LuaRuntime.load() + using state = lua.createState() + + expect(readFileFromLua(state, join(hostDir, 'inside.txt'))).to.be.equal('BLOCKED') + }) + + it('a mount should expose the host directory at the given path', async () => { + const lua = await LuaRuntime.load({ mounts: { '/scripts': hostDir } }) + using state = lua.createState() + + expect(readFileFromLua(state, '/scripts/inside.txt')).to.be.equal('mounted content') + }) + + it('a mount should leave the rest of the host unreachable', async () => { + const lua = await LuaRuntime.load({ mounts: { '/scripts': hostDir } }) + using state = lua.createState() + + expect(readFileFromLua(state, join(outsideDir, 'outside.txt'))).to.be.equal('BLOCKED') + // Not even the host path the mount points at, since only the mount point leads there. + expect(readFileFromLua(state, join(hostDir, 'inside.txt'))).to.be.equal('BLOCKED') + }) + + it('a write through a mount should land on the host', async () => { + const lua = await LuaRuntime.load({ mounts: { '/scripts': hostDir } }) + using state = lua.createState() + + state.doStringSync(` + local f = io.open("/scripts/written.txt", "w") + f:write("from lua") + f:close() + `) + + expect(readFileSync(join(hostDir, 'written.txt'), 'utf8')).to.be.equal('from lua') + }) + + it('several mounts should coexist with files written to memory', async () => { + const other = createTempDir() + writeFileSync(join(other, 'other.txt'), 'the other one') + + const lua = await LuaRuntime.load({ mounts: { '/a': hostDir, '/b/deeper': other } }) + using state = lua.createState() + lua.writeFile('/virtual/only.txt', 'in memory') + + expect(readFileFromLua(state, '/a/inside.txt')).to.be.equal('mounted content') + expect(readFileFromLua(state, '/b/deeper/other.txt')).to.be.equal('the other one') + expect(readFileFromLua(state, '/virtual/only.txt')).to.be.equal('in memory') + }) + + it('a relative host path should resolve against the process working directory', async () => { + const lua = await LuaRuntime.load({ mounts: { '/here': '.' } }) + using state = lua.createState() + + expect(readFileFromLua(state, '/here/package.json')).to.match(/"name": "wasmoon"/) + }) + + it('require should find a module inside a mount', async () => { + mkdirSync(join(hostDir, 'lib'), { recursive: true }) + writeFileSync(join(hostDir, 'lib', 'mymod.lua'), 'return { value = 7 }') + + const lua = await LuaRuntime.load({ mounts: { '/scripts': hostDir } }) + using state = lua.createState({ inject: true }) + + expect( + state.doStringSync(` + package.path = "/scripts/lib/?.lua;" .. package.path + return require("mymod").value + `), + ).to.be.equal(7) + }) + + it('mounting after loading should expose the directory', async () => { + const lua = await LuaRuntime.load() + using state = lua.createState() + + expect(readFileFromLua(state, '/late/inside.txt')).to.be.equal('BLOCKED') + + lua.mount('/late', hostDir) + + expect(readFileFromLua(state, '/late/inside.txt')).to.be.equal('mounted content') + }) + + it('unmounting should make the directory unreachable again, and free the mount point', async () => { + const lua = await LuaRuntime.load({ mounts: { '/scripts': hostDir } }) + using state = lua.createState() + + lua.unmount('/scripts') + + expect(readFileFromLua(state, '/scripts/inside.txt')).to.be.equal('BLOCKED') + + // The mount point is no longer taken, so the same path can be mounted again. + lua.mount('/scripts', outsideDir) + expect(readFileFromLua(state, '/scripts/outside.txt')).to.be.equal('should stay unreachable') + }) + + describe('validation', () => { + // Each case is the same call with a different mounts object, so they are listed rather than + // written out: [what is wrong, mounts, the message it has to be reported with]. + const cases = [ + ['a host directory that does not exist', () => ({ '/scripts': join(hostDir, 'missing') }), /could not be read/], + ['a host path that is a file', () => ({ '/scripts': join(hostDir, 'inside.txt') }), /is not a directory/], + ['a mount point that is not absolute', () => ({ scripts: hostDir }), /has to be an absolute path below the root/], + ['the root as a mount point', () => ({ '/': hostDir }), /has to be an absolute path below the root/], + ['an empty segment in the mount point', () => ({ '//scripts': hostDir }), /has to be an absolute path below the root/], + ['a mount point that is not normalized', () => ({ '/scripts/../etc': hostDir }), /has to be a normalized path/], + ['nested mount points', () => ({ '/scripts': hostDir, '/scripts/inner': outsideDir }), /it overlaps the mount point/], + ['the same mount point twice', () => ({ '/scripts': hostDir, '/scripts/': outsideDir }), /it overlaps the mount point/], + ['a host path starting with ~', () => ({ '/home': '~/wasmoon' }), /'~' is not expanded/], + ] + + for (const [what, mounts, message] of cases) { + it(`${what} should throw`, async () => { + await expect(LuaRuntime.load({ mounts: mounts() })).to.eventually.be.rejectedWith(message) + }) + } + + it('a mount that overlaps one already made should throw', async () => { + const lua = await LuaRuntime.load({ mounts: { '/scripts': hostDir } }) + + expect(() => lua.mount('/scripts/inner', outsideDir)).to.throw(/it overlaps the mount point '\/scripts'/) + }) + }) +}) diff --git a/test/nodefs.test.js b/test/nodefs.test.js deleted file mode 100644 index 6c85826..0000000 --- a/test/nodefs.test.js +++ /dev/null @@ -1,442 +0,0 @@ -import { readFileSync, writeFileSync, mkdirSync, mkdtempSync, rmSync, existsSync } from 'node:fs' -import { join } from 'node:path' -import { tmpdir } from 'node:os' -import { expect } from 'chai' -import { LuaRuntime } from '../dist/index.js' -import { luaPath } from './utils.js' - -const createTempDir = () => mkdtempSync(join(tmpdir(), 'wasmoon-nodefs-')) - -// The sentinel distinguishes "empty" from "not reachable at all", which a bare read cannot. -const readFileFromLua = (state, path) => { - return state.doString(` - local f = io.open("${luaPath(path)}", "r") - if not f then return "BLOCKED" end - local content = f:read("*a") - f:close() - return content - `) -} - -describe('Node FS', () => { - let tempDir - - beforeEach(() => { - tempDir = createTempDir() - }) - - afterEach(() => { - rmSync(tempDir, { recursive: true, force: true }) - }) - - it('read a host file should succeed', async () => { - writeFileSync(join(tempDir, 'hello.txt'), 'hello world') - - const lua = await LuaRuntime.load({ fs: 'node' }) - const state = lua.createState() - const result = await readFileFromLua(state, join(tempDir, 'hello.txt')) - - expect(result).to.be.equal('hello world') - }) - - it('write a file to host should succeed', async () => { - const filePath = join(tempDir, 'output.txt') - - const lua = await LuaRuntime.load({ fs: 'node' }) - const state = lua.createState() - await state.doString(` - local f = io.open("${luaPath(filePath)}", "w") - f:write("written from lua") - f:close() - `) - - expect(readFileSync(filePath, 'utf8')).to.be.equal('written from lua') - }) - - it('append to a host file should succeed', async () => { - const filePath = join(tempDir, 'append.txt') - writeFileSync(filePath, 'first line\n') - - const lua = await LuaRuntime.load({ fs: 'node' }) - const state = lua.createState() - await state.doString(` - local f = io.open("${luaPath(filePath)}", "a") - f:write("second line\\n") - f:close() - `) - - expect(readFileSync(filePath, 'utf8')).to.be.equal('first line\nsecond line\n') - }) - - it('read file line by line should succeed', async () => { - writeFileSync(join(tempDir, 'lines.txt'), 'alpha\nbeta\ngamma\n') - - const lua = await LuaRuntime.load({ fs: 'node' }) - const state = lua.createState() - const result = await state.doString(` - local lines = {} - for line in io.lines("${luaPath(join(tempDir, 'lines.txt'))}") do - lines[#lines + 1] = line - end - return table.concat(lines, ",") - `) - - expect(result).to.be.equal('alpha,beta,gamma') - }) - - it('read binary file should succeed', async () => { - const buf = Buffer.from([0x00, 0x01, 0x02, 0xff, 0xfe]) - writeFileSync(join(tempDir, 'binary.dat'), buf) - - const lua = await LuaRuntime.load({ fs: 'node' }) - const state = lua.createState() - const result = await state.doString(` - local f = io.open("${luaPath(join(tempDir, 'binary.dat'))}", "rb") - local data = f:read("*a") - f:close() - return #data - `) - - expect(result).to.be.equal(5) - }) - - it('write and read back binary data should succeed', async () => { - const filePath = join(tempDir, 'binout.dat') - - const lua = await LuaRuntime.load({ fs: 'node' }) - const state = lua.createState() - await state.doString(` - local f = io.open("${luaPath(filePath)}", "wb") - f:write(string.char(72, 101, 108, 108, 111)) - f:close() - `) - - expect(readFileSync(filePath, 'utf8')).to.be.equal('Hello') - }) - - it('check if file exists using io.open should succeed', async () => { - writeFileSync(join(tempDir, 'exists.txt'), 'yes') - - const lua = await LuaRuntime.load({ fs: 'node' }) - const state = lua.createState() - const result = await state.doString(` - local f = io.open("${luaPath(join(tempDir, 'exists.txt'))}", "r") - local exists = f ~= nil - if f then f:close() end - - local f2 = io.open("${luaPath(join(tempDir, 'nope.txt'))}", "r") - local not_exists = f2 == nil - if f2 then f2:close() end - - return exists and not_exists - `) - - expect(result).to.be.true - }) - - it('read file size should succeed', async () => { - writeFileSync(join(tempDir, 'sized.txt'), 'abcdefghij') - - const lua = await LuaRuntime.load({ fs: 'node' }) - const state = lua.createState() - const result = await state.doString(` - local f = io.open("${luaPath(join(tempDir, 'sized.txt'))}", "r") - local size = f:seek("end") - f:close() - return size - `) - - expect(result).to.be.equal(10) - }) - - it('seek within a file should succeed', async () => { - writeFileSync(join(tempDir, 'seek.txt'), 'abcdefghij') - - const lua = await LuaRuntime.load({ fs: 'node' }) - const state = lua.createState() - const result = await state.doString(` - local f = io.open("${luaPath(join(tempDir, 'seek.txt'))}", "r") - f:seek("set", 3) - local chunk = f:read(4) - f:close() - return chunk - `) - - expect(result).to.be.equal('defg') - }) - - it('doFile from host filesystem should succeed', async () => { - writeFileSync(join(tempDir, 'script.lua'), 'return 7 * 6') - - const lua = await LuaRuntime.load({ fs: 'node' }) - const state = lua.createState() - const result = await state.doFile(luaPath(join(tempDir, 'script.lua'))) - - expect(result).to.be.equal(42) - }) - - it('require a host lua file should succeed', async () => { - const luaDir = join(tempDir, 'lualibs') - mkdirSync(luaDir, { recursive: true }) - writeFileSync(join(luaDir, 'mymod.lua'), 'local M = {}; M.value = 99; return M') - - const lua = await LuaRuntime.load({ fs: 'node' }) - const state = lua.createState({ inject: true }) - const result = await state.doString(` - package.path = "${luaPath(luaDir)}/?.lua;" .. package.path - local m = require("mymod") - return m.value - `) - - expect(result).to.be.equal(99) - }) - - it('read from nested directories should succeed', async () => { - const nested = join(tempDir, 'a', 'b', 'c') - mkdirSync(nested, { recursive: true }) - writeFileSync(join(nested, 'deep.txt'), 'deep content') - - const lua = await LuaRuntime.load({ fs: 'node' }) - const state = lua.createState() - const result = await readFileFromLua(state, join(nested, 'deep.txt')) - - expect(result).to.be.equal('deep content') - }) - - it('create directory from lua with os.execute should succeed', async () => { - const newDir = join(tempDir, 'newdir') - - const lua = await LuaRuntime.load({ fs: 'node' }) - const state = lua.createState() - await state.doString(` - os.execute("mkdir -p '${luaPath(newDir)}'") - `) - - expect(existsSync(newDir)).to.be.true - }) - - it('remove a host file from lua with os.remove should succeed', async () => { - const filePath = join(tempDir, 'removeme.txt') - writeFileSync(filePath, 'to be deleted') - - const lua = await LuaRuntime.load({ fs: 'node' }) - const state = lua.createState() - const result = await state.doString(` - return os.remove("${luaPath(filePath)}") - `) - - expect(result).to.be.true - expect(existsSync(filePath)).to.be.false - }) - - it('rename a host file from lua with os.rename should succeed', async () => { - const oldPath = join(tempDir, 'old.txt') - const newPath = join(tempDir, 'new.txt') - writeFileSync(oldPath, 'rename me') - - const lua = await LuaRuntime.load({ fs: 'node' }) - const state = lua.createState() - const result = await state.doString(` - return os.rename("${luaPath(oldPath)}", "${luaPath(newPath)}") - `) - - expect(result).to.be.true - expect(existsSync(oldPath)).to.be.false - expect(readFileSync(newPath, 'utf8')).to.be.equal('rename me') - }) - - it('NODEFS should start in the host process cwd', async () => { - const lua = await LuaRuntime.load({ fs: 'node' }) - - expect(lua.filesystem.cwd()).to.be.equal(process.cwd().replace(/\\/g, '/')) - }) - - it('doFile from cwd-relative path should succeed', async () => { - const lua = await LuaRuntime.load({ fs: 'node' }) - // chdir first, or the mounted file lands in the repo the suite runs from. - lua.filesystem.chdir(tempDir) - lua.mountFile('cwd_test.lua', 'return "from cwd"') - const state = lua.createState() - - expect(existsSync(join(tempDir, 'cwd_test.lua'))).to.be.true - expect(await state.doFile('cwd_test.lua')).to.be.equal('from cwd') - }) - - it('fsMountPaths should mount the listed path', async () => { - writeFileSync(join(tempDir, 'inside.txt'), 'mounted content') - - const lua = await LuaRuntime.load({ fs: 'node', fsMountPaths: [tempDir] }) - const state = lua.createState() - - expect(await readFileFromLua(state, join(tempDir, 'inside.txt'))).to.be.equal('mounted content') - }) - - it('fsMountPaths should leave everything else unreachable', async () => { - // Without this the default mounts the whole drive, so the case above passes either way. - const unmounted = createTempDir() - writeFileSync(join(unmounted, 'outside.txt'), 'should not be readable') - - try { - const lua = await LuaRuntime.load({ fs: 'node', fsMountPaths: [tempDir] }) - const state = lua.createState() - - expect(await readFileFromLua(state, join(unmounted, 'outside.txt'))).to.be.equal('BLOCKED') - } finally { - rmSync(unmounted, { recursive: true, force: true }) - } - }) - - it('mountFile and NODEFS should coexist', async () => { - writeFileSync(join(tempDir, 'host.txt'), 'from host') - - const lua = await LuaRuntime.load({ fs: 'node' }) - lua.filesystem.chdir(tempDir) - lua.mountFile('virtual.lua', 'return "from virtual"') - const state = lua.createState() - - expect(await readFileFromLua(state, join(tempDir, 'host.txt'))).to.be.equal('from host') - expect(await state.doString('return dofile("virtual.lua")')).to.be.equal('from virtual') - }) - - it('write large file should succeed', async () => { - const filePath = join(tempDir, 'large.txt') - const lineCount = 10000 - - const lua = await LuaRuntime.load({ fs: 'node' }) - const state = lua.createState() - await state.doString(` - local f = io.open("${luaPath(filePath)}", "w") - for i = 1, ${lineCount} do - f:write("line " .. i .. "\\n") - end - f:close() - `) - - const content = readFileSync(filePath, 'utf8') - const lines = content.trimEnd().split('\n') - expect(lines.length).to.be.equal(lineCount) - expect(lines[0]).to.be.equal('line 1') - expect(lines[lineCount - 1]).to.be.equal(`line ${lineCount}`) - }) - - it('overwrite existing file should succeed', async () => { - const filePath = join(tempDir, 'overwrite.txt') - writeFileSync(filePath, 'original content') - - const lua = await LuaRuntime.load({ fs: 'node' }) - const state = lua.createState() - await state.doString(` - local f = io.open("${luaPath(filePath)}", "w") - f:write("new content") - f:close() - `) - - expect(readFileSync(filePath, 'utf8')).to.be.equal('new content') - }) - - it('read UTF-8 content should succeed', async () => { - const content = 'héllo wörld 日本語 🌍' - writeFileSync(join(tempDir, 'utf8.txt'), content) - - const lua = await LuaRuntime.load({ fs: 'node' }) - const state = lua.createState() - const result = await readFileFromLua(state, join(tempDir, 'utf8.txt')) - - expect(result).to.be.equal(content) - }) - - it('write UTF-8 content should succeed', async () => { - const filePath = join(tempDir, 'utf8out.txt') - - const lua = await LuaRuntime.load({ fs: 'node' }) - const state = lua.createState() - await state.doString(` - local f = io.open("${luaPath(filePath)}", "w") - f:write("café ñ 中文") - f:close() - `) - - expect(readFileSync(filePath, 'utf8')).to.be.equal('café ñ 中文') - }) - - it('read empty file should succeed', async () => { - writeFileSync(join(tempDir, 'empty.txt'), '') - - const lua = await LuaRuntime.load({ fs: 'node' }) - const state = lua.createState() - const result = await state.doString(` - local f = io.open("${luaPath(join(tempDir, 'empty.txt'))}", "r") - local data = f:read("*a") - f:close() - return #data - `) - - expect(result).to.be.equal(0) - }) - - it('open non-existent file for reading should return nil and a message', async () => { - const lua = await LuaRuntime.load({ fs: 'node' }) - const state = lua.createState() - const result = await state.doString(` - local f, err = io.open("${luaPath(join(tempDir, 'nonexistent.txt'))}", "r") - return f == nil and type(err) == "string" and #err > 0 - `) - - expect(result).to.be.true - }) - - it('io.tmpfile should succeed', async () => { - const lua = await LuaRuntime.load({ fs: 'node' }) - const state = lua.createState() - const result = await state.doString(` - local f = io.tmpfile() - f:write("temp data") - f:seek("set") - local data = f:read("*a") - f:close() - return data - `) - - expect(result).to.be.equal('temp data') - }) - - it('multiple states sharing the same NODEFS should succeed', async () => { - const filePath = join(tempDir, 'shared.txt') - - const lua = await LuaRuntime.load({ fs: 'node' }) - const state1 = lua.createState() - const state2 = lua.createState() - - await state1.doString(` - local f = io.open("${luaPath(filePath)}", "w") - f:write("from state1") - f:close() - `) - - const result = await state2.doString(` - local f = io.open("${luaPath(filePath)}", "r") - local data = f:read("*a") - f:close() - return data - `) - - expect(result).to.be.equal('from state1') - }) - - it('read number from file should succeed', async () => { - writeFileSync(join(tempDir, 'numbers.txt'), '42\n3.14\n100') - - const lua = await LuaRuntime.load({ fs: 'node' }) - const state = lua.createState() - const result = await state.doString(` - local f = io.open("${luaPath(join(tempDir, 'numbers.txt'))}", "r") - local n1 = f:read("*n") - local n2 = f:read("*n") - local n3 = f:read("*n") - f:close() - return n1 + n2 + n3 - `) - - expect(result).to.be.closeTo(145.14, 0.001) - }) -}) diff --git a/test/utils.js b/test/utils.js index f0343b9..7650f16 100644 --- a/test/utils.js +++ b/test/utils.js @@ -1,3 +1,6 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' import { LuaRuntime } from '../dist/index.js' export const getLua = (options) => { @@ -19,3 +22,38 @@ export const tick = () => { /** Windows paths cannot go into a Lua string literal as they are. */ export const luaPath = (path) => path.replace(/\\/g, '/') + +/** + * Hands out temporary directories and removes every one of them afterwards, so a test that needs a + * second or third one does not have to carry its own try/finally. + */ +export const useTempDirs = (prefix) => { + const created = [] + const createTempDir = () => { + const dir = mkdtempSync(join(tmpdir(), `wasmoon-${prefix}-`)) + created.push(dir) + return dir + } + + afterEach(() => { + for (const dir of created.splice(0)) { + rmSync(dir, { recursive: true, force: true }) + } + }) + + return createTempDir +} + +/** + * Reads a file from inside Lua. The sentinel distinguishes "empty" from "not reachable at all", + * which a bare read cannot. + */ +export const readFileFromLua = (state, path) => { + return state.doStringSync(` + local f = io.open("${luaPath(path)}", "r") + if not f then return "BLOCKED" end + local content = f:read("*a") + f:close() + return content + `) +} diff --git a/utils/build-wasm.sh b/utils/build-wasm.sh index 9d8db45..75e643d 100755 --- a/utils/build-wasm.sh +++ b/utils/build-wasm.sh @@ -1,24 +1,25 @@ #!/bin/bash -e cd $(dirname $0) -mkdir -p ../build +mkdir -p ../build/host LUA_SRC=$(ls ../lua/*.c | grep -v "luac.c" | grep -v "lua.c" | tr "\n" " ") # Do not add --closure here: it renames properties, which would strip the brand the JS build puts on # the glue's longjmp unwind classes (see rolldown.config.ts) and turn every unwind into a Lua error. -extension="" if [ "$1" == "dev" ]; then - extension="-O0 -g3 -s ASSERTIONS=1 -s SAFE_HEAP=1 -s STACK_OVERFLOW_CHECK=2" + extension=(-O0 -g3 -s ASSERTIONS=1 -s SAFE_HEAP=1 -s STACK_OVERFLOW_CHECK=2) else # TEXTDECODER=1 keeps Emscripten's short string decode path, which -Oz would otherwise drop # in favour of always calling TextDecoder. LuaModule.readString relies on it. - extension="-Oz -fno-inline-functions -s TEXTDECODER=1 -s BINARYEN_EXTRA_PASSES=gufa-optimizing" + extension=(-Oz -fno-inline-functions -s TEXTDECODER=1 -s BINARYEN_EXTRA_PASSES=gufa-optimizing) fi -emcc \ - -lnodefs.js \ - -s WASM=1 $extension -o ../build/glue.js \ +# Everything that is not about the filesystem, shared by both glues below so they can share one +# `glue.wasm`. +COMMON=( + -s WASM=1 + "${extension[@]}" -s EXPORTED_RUNTIME_METHODS="[ 'ccall', \ 'addFunction', \ @@ -37,28 +38,27 @@ emcc \ 'UTF8ToString', \ 'HEAPU8', \ 'HEAPU32' - ]" \ + ]" -s DEFAULT_LIBRARY_FUNCS_TO_INCLUDE="[ '\$FS_mkdirTree', \ '\$PATH', \ '\$PATH_FS' - ]" \ + ]" -s INCOMING_MODULE_JS_API="[ 'locateFile', \ 'preRun', \ 'print', \ 'printErr' \ - ]" \ - -s ENVIRONMENT="web,worker,node" \ - -s MODULARIZE=1 \ - -s ALLOW_TABLE_GROWTH=1 \ - -s EXPORT_NAME="initWasmModule" \ - -s ALLOW_MEMORY_GROWTH=1 \ - -s STRICT=1 \ - -s EXPORT_ES6=1 \ - -s MALLOC=emmalloc \ - -s STACK_SIZE=1MB \ - -s WASM_BIGINT \ + ]" + -s MODULARIZE=1 + -s ALLOW_TABLE_GROWTH=1 + -s EXPORT_NAME="initWasmModule" + -s ALLOW_MEMORY_GROWTH=1 + -s STRICT=1 + -s EXPORT_ES6=1 + -s MALLOC=emmalloc + -s STACK_SIZE=1MB + -s WASM_BIGINT -s EXPORTED_FUNCTIONS="[ '_malloc', \ '_free', \ @@ -210,5 +210,36 @@ emcc \ '_luaopen_debug', \ '_luaopen_package', \ '_luaL_openselectedlibs' \ - ]" \ + ]" +) + +# The default glue, for every environment. Its filesystem is Emscripten's in-memory one, and +# -lnodefs.js adds the NODEFS backend so a host directory can be mounted into it (LuaModuleOptions +# `mounts`). Nothing here reaches the host on its own. +emcc "${COMMON[@]}" \ + -lnodefs.js \ + -s ENVIRONMENT="web,worker,node" \ + -o ../build/glue.js \ ${LUA_SRC} + +# The glue for `filesystem: 'host'`, which Emscripten only supports under Node. NODERAWFS forwards +# every file operation straight to node:fs, so paths, the working directory, symlinks and +# permissions are the host's rather than a mirror of them. NODE_HOST_ENV stays off so the +# environment is still whatever LuaModuleOptions `env` says, as it is in the default glue. +emcc "${COMMON[@]}" \ + -s NODERAWFS=1 \ + -s NODE_HOST_ENV=0 \ + -s ENVIRONMENT="node" \ + -o ../build/host/glue.js \ + ${LUA_SRC} + +# Both glues are the same wasm with a different filesystem bolted on in JS, which is what lets the +# package ship one binary and pick a glue at load time. Checked rather than assumed, because a +# divergence would otherwise surface as a corrupt module for host users only. +if ! cmp -s ../build/glue.wasm ../build/host/glue.wasm; then + echo "build-wasm: the host glue produced a different glue.wasm, so the two cannot share one binary" >&2 + exit 1 +fi +# Dropped so only one copy is published; the host glue resolves 'glue.wasm' next to itself, and the +# bundle puts both of them in dist/ beside the shared binary. +rm ../build/host/glue.wasm From 691022b67833dfecee5c24ed2c5a20fc69cb67e5 Mon Sep 17 00:00:00 2001 From: Gabriel Francisco Date: Wed, 29 Jul 2026 12:23:46 -0300 Subject: [PATCH 50/83] perf --- src/module.ts | 113 ++++++++++++++++++++++++-------------------- src/thread.ts | 39 ++++++++++++++- test/api.test.js | 79 ++++++++++++++++++++++++++++++- utils/build-wasm.sh | 1 - 4 files changed, 179 insertions(+), 53 deletions(-) diff --git a/src/module.ts b/src/module.ts index 69c26c9..4e87a74 100755 --- a/src/module.ts +++ b/src/module.ts @@ -33,7 +33,6 @@ export interface EmscriptenPath { /** The instantiated wasm module, as {@link LuaModule.emscripten}. */ export interface LuaEmscriptenModule extends EmscriptenModule { - ccall: typeof ccall addFunction: typeof addFunction removeFunction: typeof removeFunction setValue: typeof setValue @@ -50,8 +49,8 @@ export interface LuaEmscriptenModule extends EmscriptenModule { lengthBytesUTF8: typeof lengthBytesUTF8 stringToUTF8: typeof stringToUTF8 UTF8ToString: (ptr: number, maxBytesToRead?: number, ignoreNul?: boolean) => string - // The scratch space `ccall` uses for its own C string arguments. Unwound by stackRestore - // rather than freed, so it stays correct when a Lua error longjmps out of the call. + // Scratch space for a C string argument, on the wasm stack. Unwound by stackRestore rather + // than freed, so it stays correct when a Lua error longjmps out of the call. stringToUTF8OnStack: (str: string) => number stackSave: () => number stackRestore: (pointer: number) => void @@ -116,6 +115,20 @@ const MAX_UTF8_BYTES_PER_CHAR = 3 const C_STRING_CACHE_LIMIT = 512 const C_STRING_CACHE_MAX_LENGTH = 128 +/** How a marshalled string argument is turned into a pointer. Ordered so `None` is falsy. */ +const enum StringArgument { + None = 0, + /** A fixed name, worth keeping the encoded form of. */ + Cached = 1, + /** A one-off, encoded into scratch space every time so it cannot fill the cache. */ + Uncached = 2, +} + +// Past this a marshalled string is put on the heap and freed as the call returns, rather than on the +// wasm stack: that is 1MB, shared with the Lua calls made through it, and a whole chunk of source +// passed to one of these would overflow it. +const STACK_STRING_LIMIT = 1024 + // Above this, TextEncoder beats copying byte by byte in JS (measured; TEXTDECODER=1 covers the // other direction upstream). const INLINE_ENCODE_LIMIT = 40 @@ -1046,39 +1059,7 @@ export default class LuaModule { // upstream would fall back to ccall -- which rebuilds its converter table, argument array // and return handler on every call. That is most of the cost of the small C API functions, // and these are hot: metatable names, globals, table fields. - if (!argTypes.includes('string|number')) { - return this.wrapWithStringArguments(raw, returnType, argTypes as Emscripten.JSType[]) - } - - return (...args: any[]) => { - const pointersToBeFreed: number[] = [] - const resolvedArgTypes: Emscripten.JSType[] = argTypes.map((argType, i) => { - if (argType === 'string|number') { - if (typeof args[i] === 'number') { - return 'number' - } else { - // because it will be freed later, this can only be used on functions that lua internally copies the string - if (args[i]?.length > 1024) { - const bufferPointer = this.emscripten.stringToNewUTF8(args[i] as string) - args[i] = bufferPointer - pointersToBeFreed.push(bufferPointer) - return 'number' - } else { - return 'string' - } - } - } - return argType - }) - - try { - return this.emscripten.ccall(name, returnType, resolvedArgTypes, args as Emscripten.TypeCompatibleWithC[]) - } finally { - for (const pointer of pointersToBeFreed) { - this.emscripten._free(pointer) - } - } - } + return this.wrapWithStringArguments(raw, returnType, argTypes) } /** @@ -1089,54 +1070,69 @@ export default class LuaModule { private wrapWithStringArguments( raw: (...args: any[]) => any, returnType: Emscripten.JSType | null, - argTypes: Emscripten.JSType[], + argTypes: Array, ): (...args: any[]) => any { const emscripten = this.emscripten const arity = argTypes.length if (arity < 2 || arity > 5) { throw new Error(`wrapWithStringArguments only unrolls arities 2 to 5, not ${arity}`) } - if (argTypes[0] === 'string') { + if (argTypes[0] !== 'number') { // Every binding takes the lua_State there, so that slot is not unrolled below. throw new Error('wrapWithStringArguments does not marshal the first argument') } const returnsString = returnType === 'string' - const [, s1, s2, s3, s4] = argTypes.map((argType) => argType === 'string') + // `string` is a fixed name worth caching; `string|number` is a chunk of source or another + // one-off, which would fill the cache and push the names that dominate these calls out of it. + const [, s1, s2, s3, s4] = argTypes.map((argType) => + argType === 'string' ? StringArgument.Cached : argType === 'string|number' ? StringArgument.Uncached : StringArgument.None, + ) return (a?: any, b?: any, c?: any, d?: any, e?: any): any => { // Only an argument that misses the cache needs scratch space, and the fixed names that // dominate these calls all hit it, so the stack is only touched when it is used. let stack = 0 + // Lazily, so the common path where nothing is long enough to need the heap allocates + // nothing of its own. + let owned: number[] | undefined try { let pointer: number if (s1) { - if ((pointer = this.toCString(b)) >= 0) { + if ((pointer = this.toCString(b, s1)) >= 0) { b = pointer + } else if (b.length > STACK_STRING_LIMIT) { + b = this.ownCString(b, (owned ??= [])) } else { stack ||= emscripten.stackSave() b = emscripten.stringToUTF8OnStack(b) } } if (s2) { - if ((pointer = this.toCString(c)) >= 0) { + if ((pointer = this.toCString(c, s2)) >= 0) { c = pointer + } else if (c.length > STACK_STRING_LIMIT) { + c = this.ownCString(c, (owned ??= [])) } else { stack ||= emscripten.stackSave() c = emscripten.stringToUTF8OnStack(c) } } if (s3) { - if ((pointer = this.toCString(d)) >= 0) { + if ((pointer = this.toCString(d, s3)) >= 0) { d = pointer + } else if (d.length > STACK_STRING_LIMIT) { + d = this.ownCString(d, (owned ??= [])) } else { stack ||= emscripten.stackSave() d = emscripten.stringToUTF8OnStack(d) } } if (s4) { - if ((pointer = this.toCString(e)) >= 0) { + if ((pointer = this.toCString(e, s4)) >= 0) { e = pointer + } else if (e.length > STACK_STRING_LIMIT) { + e = this.ownCString(e, (owned ??= [])) } else { stack ||= emscripten.stackSave() e = emscripten.stringToUTF8OnStack(e) @@ -1149,18 +1145,35 @@ export default class LuaModule { if (stack) { emscripten.stackRestore(stack) } + if (owned) { + // Only reached by a binding Lua copies the string in, which is what lets these be + // freed as the call returns. + for (const allocated of owned) { + emscripten._free(allocated) + } + } } } } /** - * The C string pointer for a marshalled argument, or -1 when it has to go on the wasm stack - * instead. Cached pointers are kept for the lifetime of the module, so they stay valid across - * the reentrant calls a metamethod can make while one of them is still in flight. + * A string too long to put on the wasm stack, on the heap instead and recorded so the call that + * marshalled it can free it as it returns. + */ + private ownCString(value: string, owned: number[]): number { + const pointer = this.emscripten.stringToNewUTF8(value) + owned.push(pointer) + return pointer + } + + /** + * The C string pointer for a marshalled argument, or -1 when the caller has to put it in + * scratch space instead. Cached pointers are kept for the lifetime of the module, so they stay + * valid across the reentrant calls a metamethod can make while one of them is still in flight. */ - private toCString(value: unknown): number { - // Matches ccall: a nullish argument is a null pointer rather than the text "null". A number - // is already one, which is what the `string|number` bindings pass. + private toCString(value: unknown, mode: StringArgument): number { + // A nullish argument is a null pointer rather than the text "null", as it was under ccall. A + // number is already one, which is what the `string|number` bindings pass. if (value === null || value === undefined) { return 0 } @@ -1170,7 +1183,7 @@ export default class LuaModule { // Checked before the lookup, because hashing a long string costs more than the call saves. const text = value as string - if (text.length > C_STRING_CACHE_MAX_LENGTH) { + if (mode === StringArgument.Uncached || text.length > C_STRING_CACHE_MAX_LENGTH) { return -1 } const cached = this.cStringCache.get(text) diff --git a/src/thread.ts b/src/thread.ts index 16e35bf..b9dc484 100755 --- a/src/thread.ts +++ b/src/thread.ts @@ -35,6 +35,10 @@ const INSTRUCTION_HOOK_COUNT = 1000 const LUA_INTEGER_BITS = 64 +// LUAI_MAXSHORTLEN. At or below it Lua interns the string, which is what lets getMetatableName treat +// an address as the identity of a name. +const LUA_MAX_SHORT_STRING = 40 + const NO_RESTORE = (): void => undefined export default class Thread { @@ -45,6 +49,11 @@ export default class Thread { public onWarn: LuaWarnHandler | undefined protected readonly typeExtensions: OrderedExtension[] protected readonly parent: Thread | undefined + /** + * Shared with every thread on the same state, and only ever holding names anchored by that + * state, so it goes when the state does and nothing in it can outlive what it describes. + */ + private readonly metatableNames: Map private closed = false private hookFunctionPointer: number | undefined private hookCount = INSTRUCTION_HOOK_COUNT @@ -56,6 +65,7 @@ export default class Thread { this.typeExtensions = typeExtensions this.address = address this.parent = parent + this.metatableNames = parent ? parent.metatableNames : new Map() } public newThread(): Thread { @@ -304,7 +314,19 @@ export default class Thread { return undefined } - const name = this.module.lua_tolstring(this.address, -1, null) + // Decoding this again on every table and userdata read is most of what getValue spends on + // its dispatch, and it is nearly always one of a handful of extension names. Lua interns a + // short string, so the address of the characters is the identity of the name: an extension's + // own copy is anchored in the registry for as long as the state lives, which both keeps the + // address from being reused and makes it the one every equal name resolves to. + const pointer = this.module.lua_topointer(this.address, -1) + let name = this.metatableNames.get(pointer) + if (name === undefined) { + name = this.module.lua_tolstring(this.address, -1, null) + if (name.length <= LUA_MAX_SHORT_STRING && this.isExtensionName(name)) { + this.metatableNames.set(pointer, name) + } + } // This is popping the luaL_getmetafield result which only pushes with type is not nil. this.pop(1) @@ -598,6 +620,21 @@ export default class Thread { return index > 0 ? index : this.module.lua_absindex(this.address, index) } + /** + * Whether a name belongs to a registered extension, which is what makes it safe to remember the + * address of: those are the only ones the state keeps alive itself. Only reached the first time + * a name is seen. + */ + private isExtensionName(name: string): boolean { + const extensions = this.typeExtensions + for (let i = 0; i < extensions.length; i++) { + if (extensions[i].extension.name === name) { + return true + } + } + return false + } + /** Offers the value to each extension by descending priority. False if none claimed it. */ private pushWithExtension(decoration: Decoration, cache: LuaPushCache | undefined): boolean { const extensions = this.typeExtensions diff --git a/test/api.test.js b/test/api.test.js index e557538..3b64d6a 100644 --- a/test/api.test.js +++ b/test/api.test.js @@ -1,5 +1,5 @@ import { expect } from 'chai' -import { LuaMultiReturn, LuaRawResult, LuaTypeExtension, decorate } from '../dist/index.js' +import { LuaMultiReturn, LuaRawResult, LuaReturn, LuaTypeExtension, decorate } from '../dist/index.js' import { getLua, getState } from './utils.js' describe('MultiReturn', () => { @@ -211,3 +211,80 @@ describe('Thread lifecycle', () => { state.pop() }) }) + +// A lua_Integer is an i64, so pushValue converts a safe integer to a BigInt and anything outside +// that range becomes a float. These cover both ends of the range, and the raw bindings, which take +// the BigInt directly. +describe('Lua integer arguments', () => { + const edges = [0, 1, -1, 2 ** 31, -(2 ** 31), 2 ** 32, Number.MAX_SAFE_INTEGER, -Number.MAX_SAFE_INTEGER] + + it('should push every safe integer exactly, as an integer', async () => { + using state = await getState() + + for (const value of edges) { + state.set('value', value) + + expect(await state.doString('return math.type(value)'), `math.type of ${value}`).to.be.equal('integer') + expect(await state.doString('return value'), `round trip of ${value}`).to.be.equal(value) + } + }) + + it('should push negative zero as the integer zero, the way a bigint does', async () => { + using state = await getState() + state.set('value', -0) + + expect(await state.doString('return math.type(value)')).to.be.equal('integer') + expect(await state.doString('return value == 0')).to.be.equal(true) + }) + + it('should take a raw table index as a bigint', async () => { + using state = await getState() + state.module.lua_createtable(state.address, 3, 0) + + for (const [index, text] of ['a', 'b', 'c'].entries()) { + state.pushValue(text) + state.module.lua_rawseti(state.address, -2, BigInt(index + 1)) + } + state.module.lua_setglobal(state.address, 'letters') + + expect(await state.doString('return table.concat(letters, ",")')).to.be.equal('a,b,c') + }) + + it('should reach an index a double cannot hold exactly through a bigint', async () => { + using state = await getState() + const index = 2n ** 62n + + state.module.lua_createtable(state.address, 0, 1) + state.pushValue('far') + state.module.lua_rawseti(state.address, -2, index) + state.module.lua_setglobal(state.address, 'sparse') + + expect(await state.doString('return sparse[4611686018427387904]')).to.be.equal('far') + }) +}) + +// A marshalled string goes on the wasm stack, which is 1MB and shared with the Lua calls made +// through it, so one longer than that has to be put on the heap instead. +describe('C string arguments', () => { + const OVER_STACK = 1_500_000 + + it('should marshal a name longer than the wasm stack', async () => { + using state = await getState() + const name = `long_${'n'.repeat(OVER_STACK)}` + + // lua_setglobal and lua_getglobal both take the name as a C string. + state.set(name, 'reached') + + expect(state.get(name)).to.be.equal('reached') + }) + + it('should marshal a chunk longer than the wasm stack', async () => { + using state = await getState() + // luaL_loadstring takes the whole chunk as a C string, unlike doString which hands over a + // pointer of its own. + const script = `${'-- padding\n'.repeat(OVER_STACK / 10)}return 'compiled'` + + expect(state.module.luaL_loadstring(state.address, script)).to.be.equal(LuaReturn.Ok) + expect(state.runSync()[0]).to.be.equal('compiled') + }) +}) diff --git a/utils/build-wasm.sh b/utils/build-wasm.sh index 75e643d..c7d5f98 100755 --- a/utils/build-wasm.sh +++ b/utils/build-wasm.sh @@ -21,7 +21,6 @@ COMMON=( -s WASM=1 "${extension[@]}" -s EXPORTED_RUNTIME_METHODS="[ - 'ccall', \ 'addFunction', \ 'removeFunction', \ 'FS', \ From 78e23f34ff94e492d486c66615e91294bf2abc2e Mon Sep 17 00:00:00 2001 From: Gabriel Francisco Date: Wed, 29 Jul 2026 13:06:59 -0300 Subject: [PATCH 51/83] perf --- src/module.ts | 5 ++ src/state.ts | 14 ++++-- src/thread.ts | 71 ++++++++++++---------------- src/type-extension.ts | 62 +++++++++++++++++++----- src/type-extensions/function.ts | 84 ++++++++++++++++++++++++++------- 5 files changed, 164 insertions(+), 72 deletions(-) diff --git a/src/module.ts b/src/module.ts index 4e87a74..107625a 100755 --- a/src/module.ts +++ b/src/module.ts @@ -996,6 +996,11 @@ export default class LuaModule { return this.referenceMap.get(index) } + /** The index {@link ref} already holds for `data`, without taking a count, or undefined. */ + public getRefIndex(data: unknown): number | undefined { + return this.referenceTracker.get(data)?.index + } + // This is needed for some tests public getLastRefIndex(): number | undefined { return this.lastRefIndex diff --git a/src/state.ts b/src/state.ts index d4bab6c..c7a5ca4 100755 --- a/src/state.ts +++ b/src/state.ts @@ -207,6 +207,13 @@ export default class LuaState extends Thread { public registerTypeExtension(priority: number, extension: LuaTypeExtension): void { this.typeExtensions.push({ extension, priority }) this.typeExtensions.sort((a, b) => b.priority - a.priority) + + // The extension's metatable is registry anchored for the life of the state, so from here + // on its address alone identifies its name -- getMetatableName's fast path. + if (this.module.luaL_getmetatable(this.address, extension.name) !== LuaType.Nil) { + this.metatableNames.set(this.getPointer(-1), extension.name) + } + this.pop(1) } /** Retrieves the value of a global variable. */ @@ -295,9 +302,8 @@ export default class LuaState extends Thread { // WARNING: It will not wait for open handles and can potentially cause bugs if JS code tries to reference Lua after executed private async callByteCode(loader: (thread: Thread) => void, options?: LuaRunOptions): Promise { - const thread = this.newThread() - // Move the thread off the global stack and into the registry as a GC anchor so it doesn't pile threads up into the stack - const ref = this.module.luaL_ref(this.address, LUA_REGISTRYINDEX) + // Anchored so the run doesn't pile threads up on the global stack. + const { thread, reference } = this.newAnchoredThread() try { // Seeded from the state so a state wide setLimits reaches the async path too, which // runs on a child thread rather than on the state itself. @@ -306,7 +312,7 @@ export default class LuaState extends Thread { return (await thread.run(0, options))[0] } finally { thread.close() - this.module.luaL_unref(this.address, LUA_REGISTRYINDEX, ref) + this.module.luaL_unref(this.address, LUA_REGISTRYINDEX, reference) } } } diff --git a/src/thread.ts b/src/thread.ts index b9dc484..53f2d9f 100755 --- a/src/thread.ts +++ b/src/thread.ts @@ -5,6 +5,7 @@ import type LuaTypeExtension from './type-extension' import { defaultWarnHandler, LUA_MULTRET, + LUA_REGISTRYINDEX, LuaAbortError, type LuaAddress, LuaError, @@ -35,10 +36,6 @@ const INSTRUCTION_HOOK_COUNT = 1000 const LUA_INTEGER_BITS = 64 -// LUAI_MAXSHORTLEN. At or below it Lua interns the string, which is what lets getMetatableName treat -// an address as the identity of a name. -const LUA_MAX_SHORT_STRING = 40 - const NO_RESTORE = (): void => undefined export default class Thread { @@ -50,10 +47,12 @@ export default class Thread { protected readonly typeExtensions: OrderedExtension[] protected readonly parent: Thread | undefined /** - * Shared with every thread on the same state, and only ever holding names anchored by that - * state, so it goes when the state does and nothing in it can outlive what it describes. + * The address of each registered extension's metatable, mapped to the extension's name. + * Populated by `LuaState.registerTypeExtension` and shared with every thread on the same + * state: those metatables are registry anchored for the state's whole life, so an address in + * here can never be reused by anything else while the map exists. */ - private readonly metatableNames: Map + protected readonly metatableNames: Map private closed = false private hookFunctionPointer: number | undefined private hookCount = INSTRUCTION_HOOK_COUNT @@ -76,6 +75,18 @@ export default class Thread { return new Thread(this.module, this.typeExtensions, address, this.parent || this) } + /** + * A new thread anchored in the registry instead of left on this thread's stack. The reference + * is what keeps it alive: `luaL_unref` it to let the thread go, or keep it forever for a + * thread meant to live as long as the state. + */ + public newAnchoredThread(): { thread: Thread; reference: number } { + const thread = this.newThread() + // Taken on this thread's stack, where newThread left the new one. + const reference = this.module.luaL_ref(this.address, LUA_REGISTRYINDEX) + return { thread, reference } + } + public resetThread(): void { this.assertOk(this.module.lua_resetthread(this.address)) } @@ -303,33 +314,26 @@ export default class Thread { } public getMetatableName(index: number): string | undefined { - const metatableNameType = this.module.luaL_getmetafield(this.address, index, '__name') - if (metatableNameType === LuaType.Nil) { + // Resolving __name on every table and userdata read is most of what getValue spends on its + // dispatch, and it is nearly always one of the extension metatables that registration + // already recorded in metatableNames -- so the common case is these three raw calls and a + // map hit, with no string crossing the boundary in either direction. + if (!this.module.lua_getmetatable(this.address, index)) { return undefined } + const pointer = this.module.lua_topointer(this.address, -1) - if (metatableNameType !== LuaType.String) { - // Pop the metafield if it's not a string + let name = this.metatableNames.get(pointer) + if (name !== undefined) { this.pop(1) - return undefined + return name } - // Decoding this again on every table and userdata read is most of what getValue spends on - // its dispatch, and it is nearly always one of a handful of extension names. Lua interns a - // short string, so the address of the characters is the identity of the name: an extension's - // own copy is anchored in the registry for as long as the state lives, which both keeps the - // address from being reused and makes it the one every equal name resolves to. - const pointer = this.module.lua_topointer(this.address, -1) - let name = this.metatableNames.get(pointer) - if (name === undefined) { + // Anything else reads __name off the metatable that is still on the stack. + if (this.module.lua_getfield(this.address, -1, '__name') === LuaType.String) { name = this.module.lua_tolstring(this.address, -1, null) - if (name.length <= LUA_MAX_SHORT_STRING && this.isExtensionName(name)) { - this.metatableNames.set(pointer, name) - } } - // This is popping the luaL_getmetafield result which only pushes with type is not nil. - this.pop(1) - + this.pop(2) return name } @@ -620,21 +624,6 @@ export default class Thread { return index > 0 ? index : this.module.lua_absindex(this.address, index) } - /** - * Whether a name belongs to a registered extension, which is what makes it safe to remember the - * address of: those are the only ones the state keeps alive itself. Only reached the first time - * a name is seen. - */ - private isExtensionName(name: string): boolean { - const extensions = this.typeExtensions - for (let i = 0; i < extensions.length; i++) { - if (extensions[i].extension.name === name) { - return true - } - } - return false - } - /** Offers the value to each extension by descending priority. False if none claimed it. */ private pushWithExtension(decoration: Decoration, cache: LuaPushCache | undefined): boolean { const extensions = this.typeExtensions diff --git a/src/type-extension.ts b/src/type-extension.ts index 6d5d377..4dcd8fa 100644 --- a/src/type-extension.ts +++ b/src/type-extension.ts @@ -1,17 +1,34 @@ import type { Decoration } from './decoration' import type LuaState from './state' import type Thread from './thread' -import { type LuaAddress, type LuaGetCache, type LuaPushCache, LuaReturn, LuaType, PointerSize } from './types' +import { LUA_REGISTRYINDEX, type LuaAddress, type LuaGetCache, type LuaPushCache, LuaReturn, LuaType, PointerSize } from './types' export default abstract class LuaTypeExtension { // Type name, for metatables and lookups. public readonly name: string /** Owns this extension's metatable and function pointers, so its lifetime bounds theirs. */ protected state: LuaState + /** + * A weak valued table in the registry mapping a reference index to the userdata pushed for it, + * so pushing the same value again returns that userdata instead of allocating another one -- + * which also gives it a stable identity in Lua. Weak, so the cache never keeps a userdata + * alive: an entry goes as soon as Lua drops the userdata, before its `__gc` releases the + * reference index it is keyed by. Per extension, because the same value pushed through two + * extensions must not share a userdata carrying the wrong metatable. + */ + private readonly userdataCacheReference: bigint public constructor(state: LuaState, name: string) { this.state = state this.name = name + + const module = state.module + module.lua_createtable(state.address, 0, 0) + module.lua_createtable(state.address, 0, 1) + module.lua_pushstring(state.address, 'v') + module.lua_setfield(state.address, -2, '__mode') + module.lua_setmetatable(state.address, -2) + this.userdataCacheReference = BigInt(module.luaL_ref(state.address, LUA_REGISTRYINDEX)) } public isType(_thread: Thread, _index: number, type: LuaType, name?: string): boolean { @@ -59,23 +76,46 @@ export default abstract class LuaTypeExtension { // check the type. That must be done by the class extending this. public pushValue(thread: Thread, decoratedValue: Decoration, _cache?: LuaPushCache): boolean { const { target } = decoratedValue + const module = thread.module + + // The cache table stays at the bottom for the whole push, so the probe and the store + // below share the one registry fetch. + module.lua_rawgeti(thread.address, LUA_REGISTRYINDEX, this.userdataCacheReference) - const pointer = thread.module.ref(target) + const existingIndex = module.getRefIndex(target) + if (existingIndex !== undefined) { + if (module.lua_rawgeti(thread.address, -1, BigInt(existingIndex)) === LuaType.Userdata) { + // Drop the cache table, keeping the userdata. + module.lua_remove(thread.address, -2) + return true + } + // Pop the miss; the cache table stays for the store. + thread.pop(1) + } + + const pointer = module.ref(target) // 4 = size of pointer in wasm. - const userDataPointer = thread.module.lua_newuserdatauv(thread.address, PointerSize, 0) - thread.module.writePointer(userDataPointer, pointer) - - if (LuaType.Nil === thread.module.luaL_getmetatable(thread.address, this.name)) { - // Pop the pushed nil value and the user data. The reference has to be released by hand: - // without a metatable the userdata has no __gc, so nothing else ever would. - thread.pop(2) - thread.module.unref(pointer) + const userDataPointer = module.lua_newuserdatauv(thread.address, PointerSize, 0) + module.writePointer(userDataPointer, pointer) + + if (LuaType.Nil === module.luaL_getmetatable(thread.address, this.name)) { + // Pop the pushed nil value, the user data and the cache table. The reference has to be + // released by hand: without a metatable the userdata has no __gc, so nothing else ever + // would. + thread.pop(3) + module.unref(pointer) throw new Error(`metatable not found: ${this.name}`) } // Set as the metatable for the userdata. // -1 is the metatable, -2 is the user data. - thread.module.lua_setmetatable(thread.address, -2) + module.lua_setmetatable(thread.address, -2) + + // Remember the userdata for the next push of the same value, then drop the cache table + // from under it. + module.lua_pushvalue(thread.address, -1) + module.lua_rawseti(thread.address, -3, BigInt(pointer)) + module.lua_remove(thread.address, -2) return true } diff --git a/src/type-extensions/function.ts b/src/type-extensions/function.ts index ebae0f5..350c2f5 100644 --- a/src/type-extensions/function.ts +++ b/src/type-extensions/function.ts @@ -19,6 +19,14 @@ class FunctionTypeExtension extends TypeExtension { private gcPointer: number private functionWrapper: number private callbackContext: Thread + /** + * One call thread kept ready instead of a `lua_newthread` per call, which was most of the cost + * of calling a Lua function from JS. Anchored in the registry rather than on the callback + * context's stack, and handed out only when no other call is using it: a reentrant call (Lua → + * JS → Lua) falls back to a thread of its own. + */ + private readonly pooledCallThread: Thread + private pooledCallThreadInUse = false /** Milliseconds a Lua function called from JS may run before being interrupted. */ private readonly functionTimeout: number | undefined @@ -28,11 +36,10 @@ class FunctionTypeExtension extends TypeExtension { this.functionTimeout = functionTimeout // Create a thread off of the global thread to be used to create function call threads without // interfering with the global context. This creates a callback context that will always exist - // even if the thread that called getValue() has been destroyed. - this.callbackContext = state.newThread() - // Pops it from the global stack but keeps it alive. The reference is never released, for the - // reason given on LuaTypeExtension.close. - this.state.module.luaL_ref(state.address, LUA_REGISTRYINDEX) + // even if the thread that called getValue() has been destroyed. Neither anchor is ever + // released, for the reason given on LuaTypeExtension.close. + this.callbackContext = state.newAnchoredThread().thread + this.pooledCallThread = this.callbackContext.newAnchoredThread().thread if (!this.functionRegistry) { state.warn('FunctionTypeExtension: FinalizationRegistry not found. Memory leaks likely.') @@ -56,9 +63,20 @@ class FunctionTypeExtension extends TypeExtension { this.functionWrapper = state.module.addFunction((calledL: LuaAddress) => { const calledThread = state.stateToThread(calledL) - const refUserdata = state.module.luaL_checkudata(calledL, state.module.lua_upvalueindex(1), this.name) - const refPointer = state.module.readPointer(refUserdata) - const { target, options: decorationOptions } = state.module.getRef(refPointer) as Decoration + // The upvalue is always the userdata pushValue closed this wrapper over, so the + // metatable check luaL_checkudata does (and the name it marshals) is saved on every + // call. Only a ref that does not resolve to a function decoration -- the upvalue + // replaced through the debug library -- falls back to it, for the error the C API + // would have raised. + const upvalueIndex = state.module.lua_upvalueindex(1) + const refUserdata = state.module.lua_touserdata(calledL, upvalueIndex) + const reference = refUserdata ? state.module.getRef(state.module.readPointer(refUserdata)) : undefined + if (!(reference instanceof Decoration) || typeof reference.target !== 'function') { + // Raises the error the C API would have; the throw below is unreachable. + state.module.luaL_checkudata(calledL, upvalueIndex, this.name) + throw new Error('a js_function upvalue does not hold a function reference') + } + const { target, options: decorationOptions } = reference const argsQuantity = calledThread.getTop() const args = [] @@ -107,11 +125,43 @@ class FunctionTypeExtension extends TypeExtension { public close(): void { this.state.module.removeFunction(this.gcPointer) this.state.module.removeFunction(this.functionWrapper) - // Doesn't destroy the Lua thread, just function pointers. The thread itself went with the - // state. + // Doesn't destroy the Lua threads, just function pointers. The threads themselves went + // with the state. + this.pooledCallThread.close() this.callbackContext.close() } + private acquireCallThread(): Thread { + if (this.pooledCallThreadInUse) { + return this.callbackContext.newThread() + } + + this.pooledCallThreadInUse = true + return this.pooledCallThread + } + + private releaseCallThread(callThread: Thread, failed: boolean): void { + if (callThread !== this.pooledCallThread) { + callThread.close() + // Pop thread used for function call. + this.callbackContext.pop() + return + } + + if (failed) { + // A failed call can leave more behind than stack values: a suspended coroutine, or + // pending to-be-closed variables. Resetting closes those, so the thread is always + // reusable afterwards. Not on every release, because a reset also shrinks the stack + // just to regrow it on the next call; and not Thread.resetThread, whose status + // assertion would throw out of the finally this runs in while the call error is + // already propagating -- the setTop clears the error object a failed reset leaves + // behind instead. + this.state.module.lua_resetthread(callThread.address) + } + callThread.setTop(0) + this.pooledCallThreadInUse = false + } + public isType(_thread: Thread, _index: number, type: LuaType): boolean { return type === LuaType.Function } @@ -167,9 +217,10 @@ class FunctionTypeExtension extends TypeExtension { throw new Error('cannot call a Lua function after its state has been closed') } - // Function calls back to value should always be within a new thread because - // they can be left in inconsistent states. - const callThread = this.callbackContext.newThread() + // A call can leave its thread in an inconsistent state, so each one gets a thread that + // is either fresh or has been reset since the last call. + const callThread = this.acquireCallThread() + let failed = false try { const internalType = callThread.module.lua_rawgeti(callThread.address, LUA_REGISTRYINDEX, funcReference) if (internalType !== LuaType.Function) { @@ -198,10 +249,11 @@ class FunctionTypeExtension extends TypeExtension { return callThread.getValue(-1) } return undefined + } catch (err) { + failed = true + throw err } finally { - callThread.close() - // Pop thread used for function call. - this.callbackContext.pop() + this.releaseCallThread(callThread, failed) } } From 031c7cc887abb56fc3dd3f14b87746d013231ea5 Mon Sep 17 00:00:00 2001 From: Gabriel Francisco Date: Wed, 29 Jul 2026 14:07:32 -0300 Subject: [PATCH 52/83] fixes --- src/module.ts | 17 +++++- src/state.ts | 33 +++++++++--- src/thread.ts | 100 ++++++++++++++++++++++++++++++++---- test/initialization.test.js | 72 ++++++++++++++++++++++++++ test/limits.test.js | 47 +++++++++++++++++ 5 files changed, 253 insertions(+), 16 deletions(-) diff --git a/src/module.ts b/src/module.ts index 107625a..02a0d23 100755 --- a/src/module.ts +++ b/src/module.ts @@ -570,6 +570,19 @@ export default class LuaModule { private readonly sizeScratch: number /** The `nresults` out parameter for {@link lua_resume}, read by `Thread.resume`. */ public readonly resultCountScratch: number + /** + * The light userdata a run interrupted by the debug hook is unwound with. Nothing but the hook + * ever pushes this address, and no Lua object can live at it, so finding it on the stack is + * proof that the error came from a limit rather than from the script -- see `Thread.assertOk`. + * + * Pushing the error itself is what this replaced: it goes through pushValue, and a state with no + * error extension registered marshals it into a plain table, losing the identity the recovery + * needs. `decorate(error, { as: 'userdata' })` would survive that, but not this: light userdata + * allocates nothing, and the hook fires at an arbitrary instruction, including under a + * `memory.max` tight enough that a real userdata would fail and report a memory error in place + * of the limit that was actually hit. + */ + public readonly interruptToken: number private stringBuffer = 0 public constructor( @@ -738,7 +751,9 @@ export default class LuaModule { this.sizeScratch = module._malloc(PointerSize) this.resultCountScratch = module._malloc(PointerSize) - if (!this.sizeScratch || !this.resultCountScratch) { + // Never read or written, only compared: it exists so that the address is ours alone. + this.interruptToken = module._malloc(1) + if (!this.sizeScratch || !this.resultCountScratch || !this.interruptToken) { throw new Error('failed to allocate the scratch buffers for C out parameters') } } diff --git a/src/state.ts b/src/state.ts index c7a5ca4..8d0b1a8 100755 --- a/src/state.ts +++ b/src/state.ts @@ -218,6 +218,9 @@ export default class LuaState extends Thread { /** Retrieves the value of a global variable. */ public get(name: string): T { + // Without this a read from a closed state returns whatever the freed memory now holds, + // which is the one failure mode with nothing to notice it by. + this.assertNotClosed() const type = this.module.lua_getglobal(this.address, name) const value = this.getValue(-1, type) this.pop() @@ -226,11 +229,13 @@ export default class LuaState extends Thread { /** Sets the value of a global variable. */ public set(name: string, value: unknown): void { + this.assertNotClosed() this.pushValue(value) this.module.lua_setglobal(this.address, name) } public getTable(name: string, callback: (index: number) => void): void { + this.assertNotClosed() const startStackTop = this.getTop() const type = this.module.lua_getglobal(this.address, name) try { @@ -239,11 +244,14 @@ export default class LuaState extends Thread { } callback(startStackTop + 1) } finally { - // +1 for the table - if (this.getTop() !== startStackTop + 1) { - this.warn(`getTable: expected stack size ${startStackTop + 1} got ${this.getTop()}`) + // Nothing to check or rewind on a state the callback closed, the same as the do* paths. + if (!this.isClosed()) { + // +1 for the table + if (this.getTop() !== startStackTop + 1) { + this.warn(`getTable: expected stack size ${startStackTop + 1} got ${this.getTop()}`) + } + this.setTop(startStackTop) } - this.setTop(startStackTop) } } @@ -289,6 +297,10 @@ export default class LuaState extends Thread { } private callByteCodeSync(loader: (thread: Thread) => void, options?: LuaRunOptions): any { + // Ahead of the stack bookkeeping below rather than left to the loader, so that a closed + // state is refused before anything reads or rewinds the freed one. + this.assertNotClosed() + // Runs on the main thread so the script sees itself as the main coroutine, the way the // reference implementation behaves. That makes leftovers outlive the call, hence the rewind. const startStackTop = this.getTop() @@ -296,12 +308,17 @@ export default class LuaState extends Thread { loader(this) return this.runSync(0, options)[0] } finally { - this.setTop(startStackTop) + // Closing runs the state's own teardown, which leaves nothing here to rewind. + if (!this.isClosed()) { + this.setTop(startStackTop) + } } } // WARNING: It will not wait for open handles and can potentially cause bugs if JS code tries to reference Lua after executed private async callByteCode(loader: (thread: Thread) => void, options?: LuaRunOptions): Promise { + this.assertNotClosed() + // Anchored so the run doesn't pile threads up on the global stack. const { thread, reference } = this.newAnchoredThread() try { @@ -312,7 +329,11 @@ export default class LuaState extends Thread { return (await thread.run(0, options))[0] } finally { thread.close() - this.module.luaL_unref(this.address, LUA_REGISTRYINDEX, reference) + // The await above gives anything else a chance to close the state, and lua_close has + // already released the registry this would be unreferencing from. + if (!this.isClosed()) { + this.module.luaL_unref(this.address, LUA_REGISTRYINDEX, reference) + } } } } diff --git a/src/thread.ts b/src/thread.ts index 53f2d9f..301e3a7 100755 --- a/src/thread.ts +++ b/src/thread.ts @@ -46,6 +46,12 @@ export default class Thread { public onWarn: LuaWarnHandler | undefined protected readonly typeExtensions: OrderedExtension[] protected readonly parent: Thread | undefined + /** + * The state this thread belongs to, or itself when it is the state. Resolved once here rather + * than walked on demand: it is what {@link isClosed} and the shared slots below consult, and + * those sit in front of the entry points the interop benchmarks measure. + */ + protected readonly rootThread: Thread /** * The address of each registered extension's metatable, mapped to the extension's name. * Populated by `LuaState.registerTypeExtension` and shared with every thread on the same @@ -58,21 +64,30 @@ export default class Thread { private hookCount = INSTRUCTION_HOOK_COUNT private limits: LuaThreadLimits = {} private instructionsUsed = 0 + /** + * The error the debug hook unwound the current run with. See {@link LuaModule.interruptToken} + * for why it is held here rather than pushed into Lua. Kept on the root thread, because the + * hook fires with whichever thread Lua is running -- a coroutine inherits it -- while the + * {@link assertOk} that reports it is the one the run was started on. + */ + private pendingInterrupt: LuaInterruptError | undefined public constructor(cmodule: LuaModule, typeExtensions: OrderedExtension[], address: number, parent?: Thread) { this.module = cmodule this.typeExtensions = typeExtensions this.address = address this.parent = parent + this.rootThread = parent ?? this this.metatableNames = parent ? parent.metatableNames : new Map() } public newThread(): Thread { + this.assertNotClosed() const address = this.module.lua_newthread(this.address) if (!address) { throw new Error('lua_newthread returned a null pointer') } - return new Thread(this.module, this.typeExtensions, address, this.parent || this) + return new Thread(this.module, this.typeExtensions, address, this.rootThread) } /** @@ -88,11 +103,13 @@ export default class Thread { } public resetThread(): void { + this.assertNotClosed() this.assertOk(this.module.lua_resetthread(this.address)) } /** @param options.mode defaults to `'t'`. See {@link LuaLoadOptions.mode}. */ public loadString(luaCode: string, options?: LuaLoadOptions): void { + this.assertNotClosed() // Lua copies the chunk while loading, so the shared buffer can be handed straight to it // rather than encoded into an allocation of its own. this.assertOk( @@ -104,10 +121,14 @@ export default class Thread { /** @param options.mode defaults to `'t'`. See {@link LuaLoadOptions.mode}. */ public loadFile(filename: string, options?: LuaLoadOptions): void { + this.assertNotClosed() this.assertOk(this.module.luaL_loadfilex(this.address, filename, options?.mode ?? 't')) } public resume(argCount = 0): LuaResumeResult { + // Also covers the resumes `run` makes after an await, where the state can have been closed + // by anything else that got to run in the meantime. + this.assertNotClosed() // The shared slot is safe for the same reason the one behind it is: C writes the count as it // returns and it is read straight after, with nothing interleaved. A nested resume has // finished with the slot by the time this one's lua_resume writes to it. @@ -139,6 +160,7 @@ export default class Thread { } public async run(argCount = 0, options?: LuaRunOptions): Promise { + this.assertNotClosed() const restore = this.applyRunOptions(options) try { let resumeResult: LuaResumeResult = this.resume(argCount) @@ -186,6 +208,7 @@ export default class Thread { } public runSync(argCount = 0, options?: LuaRunOptions): MultiReturn { + this.assertNotClosed() const restore = this.applyRunOptions(options) try { const base = this.getTop() - argCount - 1 // The 1 is for the function to run @@ -201,6 +224,7 @@ export default class Thread { } public call(name: string, ...args: any[]): MultiReturn { + this.assertNotClosed() const type = this.module.lua_getglobal(this.address, name) if (type !== LuaType.Function) { throw new TypeError(`cannot call '${name}': expected a function, got ${LuaType[type]}`) @@ -230,7 +254,7 @@ export default class Thread { if (L === this.address) { return this } - return L === this.parent?.address ? this.parent : new Thread(this.module, this.typeExtensions, L, this.parent || this) + return L === this.parent?.address ? this.parent : new Thread(this.module, this.typeExtensions, L, this.rootThread) } public pushValue(rawValue: unknown, cache?: LuaPushCache): void { @@ -410,6 +434,7 @@ export default class Thread { * They share a single debug hook, because Lua only allows one hook per thread. */ public setLimits(limits: LuaThreadLimits | undefined): void { + this.assertNotClosed() this.limits = { ...limits } this.instructionsUsed = 0 this.applyHook() @@ -425,6 +450,7 @@ export default class Thread { * `LuaRunOptions.timeout` is the per-run equivalent that does take a duration. */ public setDeadline(deadline: number | undefined): void { + this.assertNotClosed() this.limits.deadline = deadline && deadline > 0 ? deadline : undefined this.applyHook() } @@ -439,8 +465,7 @@ export default class Thread { * runtime's rather than straight to the console. */ public warn(message: string, cause?: unknown): void { - const root = this.parent ?? this - ;(root.onWarn ?? this.module.onWarn ?? defaultWarnHandler)(message, cause) + ;(this.rootThread.onWarn ?? this.module.onWarn ?? defaultWarnHandler)(message, cause) } /** For identity checks on values JS cannot represent. */ @@ -449,7 +474,26 @@ export default class Thread { } public isClosed(): boolean { - return !this.address || this.closed || Boolean(this.parent?.isClosed()) + // A thread's parent is always the state, so this is the whole chain rather than one step of + // it, and the guard in front of the benchmarked entry points is three field reads. + return !this.address || this.closed || this.rootThread.closed + } + + /** + * Guards the calls that begin a Lua operation. `lua_close` frees the `lua_State` on the wasm + * heap, so without this one made afterwards reads and writes memory that has been handed back + * to the allocator: it might trap, might return a plausible value, or might corrupt whatever + * now owns those bytes. + * + * The rule is one check per operation, none per stack value: the primitives `getTop`, `setTop`, + * `pop`, `remove`, `pushValue`, `getValue` and the readers around them stay unguarded so an + * extension pays nothing for them, and everything that puts them to work is guarded here. A new + * method belongs on one side or the other of that line. + */ + protected assertNotClosed(): void { + if (this.isClosed()) { + throw new Error('the Lua state is closed') + } } public indexToString(index: number): string { @@ -498,11 +542,18 @@ export default class Thread { return } + const stackTop = this.getTop() + + const interrupt = this.takePendingInterrupt(stackTop) + if (interrupt) { + throw interrupt + } + // This is the default message if there's nothing on the stack. let luaMessage = `Lua Error(${LuaReturn[result]}/${result})` let luaValue: unknown - if (this.getTop() > 0) { + if (stackTop > 0) { if (result === LuaReturn.ErrorMem) { // If there's no memory just do a normal to string. luaMessage = this.module.lua_tolstring(this.address, -1, null) @@ -519,6 +570,9 @@ export default class Thread { } } + // Not the hook's interrupts, which takePendingInterrupt above has already claimed: this is a + // JS function that threw one itself, marshalled back by reference through the extension that + // pushed it. Reported as thrown rather than wrapped, the same as one the hook raised. if (luaValue instanceof LuaInterruptError) { throw luaValue } @@ -543,6 +597,26 @@ export default class Thread { throw new LuaError(result, luaMessage, { traceback, luaValue }) } + /** + * The interrupt the hook unwound the run with, claimed only when the error being reported is + * the token it pushed. A script that pcalled the interrupt away leaves the slot set with the + * token nowhere on the stack, so whatever error did surface is still reported as itself. + */ + private takePendingInterrupt(stackTop: number): LuaInterruptError | undefined { + const root = this.rootThread + if (root.pendingInterrupt === undefined || stackTop === 0) { + return undefined + } + // The token is a heap address the module never hands to Lua, so nothing else can be at it. + if (this.getPointer(-1) !== this.module.interruptToken) { + return undefined + } + + const interrupt = root.pendingInterrupt + root.pendingInterrupt = undefined + return interrupt + } + private applyRunOptions(options: LuaRunOptions | undefined): () => void { const overrides = options !== undefined && @@ -569,6 +643,13 @@ export default class Thread { } private applyHook(): void { + // The restore that `applyRunOptions` hands back runs in a finally, so it reaches here after + // a state closed midway through its own run. Returning rather than throwing, because that + // finally must not replace whatever error is already on its way out. + if (this.isClosed()) { + return + } + const { deadline, maxInstructions, signal } = this.limits if (deadline === undefined && maxInstructions === undefined && signal === undefined) { this.module.lua_sethook(this.address, null, 0, 0) @@ -585,7 +666,8 @@ export default class Thread { // earlier configuration still honours the current one. const error = this.checkHookLimits() if (error) { - this.pushValue(error) + this.rootThread.pendingInterrupt = error + this.module.lua_pushlightuserdata(this.address, this.module.interruptToken) this.module.lua_error(this.address) } }, 'vii') @@ -594,7 +676,7 @@ export default class Thread { this.module.lua_sethook(this.address, this.hookFunctionPointer, LuaEventMasks.Count, this.hookCount) } - private checkHookLimits(): Error | undefined { + private checkHookLimits(): LuaInterruptError | undefined { const { maxInstructions } = this.limits if (maxInstructions !== undefined) { this.instructionsUsed += this.hookCount @@ -605,7 +687,7 @@ export default class Thread { return this.checkYieldLimits() } - private checkYieldLimits(): Error | undefined { + private checkYieldLimits(): LuaInterruptError | undefined { const { deadline, signal } = this.limits if (signal?.aborted) { return new LuaAbortError('thread aborted') diff --git a/test/initialization.test.js b/test/initialization.test.js index 46cf787..3042477 100644 --- a/test/initialization.test.js +++ b/test/initialization.test.js @@ -1,5 +1,6 @@ import { LUA_LIB_BITS, LuaRuntime } from '../dist/index.js' import { expect } from 'chai' +import { getLua, getState } from './utils.js' describe('Initialization', () => { it('create state should succeed', async () => { @@ -155,4 +156,75 @@ describe('Disposal', () => { expect(escaped.isClosed()).to.be.true }) + + // lua_close hands the lua_State back to the wasm allocator, so a call that gets through + // afterwards is reading and writing memory something else may already own. These used to reach + // the bindings: some trapped with `table index is out of bounds`, `get` returned whatever was + // in the freed struct, and `call` reported the global as missing. + describe('use after close', () => { + // The guard is one check per operation and none per stack value, so these are every entry + // point on the guarded side of that line. Split by shape rather than wrapped in a promise, + // to hold each one to throwing the way it does when the state is open. + const syncEntryPoints = { + get: (state) => state.get('print'), + set: (state) => state.set('x', 1), + doStringSync: (state) => state.doStringSync('return 1'), + doFileSync: (state) => state.doFileSync('script.lua'), + call: (state) => state.call('print', 'hi'), + getTable: (state) => state.getTable('_G', () => undefined), + loadString: (state) => state.loadString('return 1'), + loadFile: (state) => state.loadFile('script.lua'), + newThread: (state) => state.newThread(), + resetThread: (state) => state.resetThread(), + resume: (state) => state.resume(), + runSync: (state) => state.runSync(), + setLimits: (state) => state.setLimits({ maxInstructions: 10 }), + setDeadline: (state) => state.setDeadline(Date.now() + 10), + } + + for (const [name, use] of Object.entries(syncEntryPoints)) { + it(`${name} throws on a closed state instead of using freed memory`, async () => { + using state = await getState() + state.close() + + expect(() => use(state)).to.throw('the Lua state is closed') + }) + } + + for (const name of ['doString', 'doFile']) { + it(`${name} rejects on a closed state instead of using freed memory`, async () => { + using state = await getState() + state.close() + + await expect(state[name]('return 1')).to.eventually.be.rejectedWith('the Lua state is closed') + }) + } + + it('a state closed by its runtime is refused the same way', async () => { + const lua = await getLua() + const state = lua.createState() + lua.close() + + expect(() => state.doStringSync('return 1')).to.throw('the Lua state is closed') + }) + + it('a thread outlives neither the state nor the check', async () => { + using state = await getState() + const thread = state.newThread() + state.close() + + expect(thread.isClosed()).to.be.true + expect(() => thread.loadString('return 1')).to.throw('the Lua state is closed') + }) + + it('a state closed while a run is parked stops rather than resuming into freed memory', async () => { + using state = await getState() + state.set('sleep', (ms) => new Promise((resolve) => setTimeout(resolve, ms))) + + const running = state.doString('sleep(10):await() return 1') + state.close() + + await expect(running).to.eventually.be.rejectedWith('the Lua state is closed') + }) + }) }) diff --git a/test/limits.test.js b/test/limits.test.js index 0fb0d32..16f9c16 100644 --- a/test/limits.test.js +++ b/test/limits.test.js @@ -72,4 +72,51 @@ describe('Run limits', () => { expect(state.getLimits().maxInstructions).to.be.equal(999) }) + + // An interrupt used to be pushed into Lua as a JS error and recognised on the way back out by + // its identity, which only survived in a state whose extensions marshal an Error by reference. + // `objects: 'copy'` with `errors: false` -- a sandbox that keeps JS errors away from Lua, and so + // exactly the state most likely to set a limit in the first place -- turned every interrupt into + // an opaque `LuaError: table: 0x...`. + describe('state configurations', () => { + const configs = [ + ['the default proxy state', {}], + ['objects: copy', { objects: 'copy' }], + ['objects: copy with errors off', { objects: 'copy', errors: false }], + ['no injected globals', { inject: false }], + ['no standard libraries', { libs: false }], + ['no libraries and nothing to marshal errors', { libs: false, objects: 'copy', errors: false, inject: false }], + ] + + for (const [description, config] of configs) { + it(`reports every interrupt as itself in ${description}`, async function () { + this.timeout(20_000) + using state = await getState(config) + + await expect(state.doString(busyLoop, { maxInstructions: 5_000 })).to.eventually.be.rejectedWith(LuaInstructionLimitError) + await expect(state.doString(busyLoop, { timeout: 20 })).to.eventually.be.rejectedWith(LuaTimeoutError) + await expect(state.doString(busyLoop, { signal: AbortSignal.abort() })).to.eventually.be.rejectedWith(LuaAbortError) + expect(() => state.doStringSync(busyLoop, { maxInstructions: 5_000 })).to.throw(LuaInstructionLimitError) + }) + } + }) + + it('an interrupt the script caught does not stand in for the error that followed', async function () { + this.timeout(20_000) + using state = await getState({ objects: 'copy', errors: false }) + + // The budget is spent inside the pcall, so the interrupt is raised and swallowed there. The + // hook re-raises within another hookCount instructions, which is room enough for the error + // below and nothing much else. + const failure = state.doString( + `pcall(function () ${busyLoop} end) + error('raised after the interrupt was caught')`, + { maxInstructions: 5_000 }, + ) + + await expect(failure).to.eventually.be.rejected.then((error) => { + expect(error).to.not.be.an.instanceOf(LuaInterruptError) + expect(error.message).to.contain('raised after the interrupt was caught') + }) + }) }) From 836053bd6012d1faeedc2455a14719bd5d4ae5e9 Mon Sep 17 00:00:00 2001 From: ceifa Date: Tue, 1 Sep 2026 20:40:44 -0300 Subject: [PATCH 53/83] fix object identified as array by mistake --- package-lock.json | 27 +++++++++++++++++++- src/type-extensions/table.ts | 48 +++++++++++++++++++++++++++--------- test/state.test.js | 25 +++++++++++++++++++ 3 files changed, 87 insertions(+), 13 deletions(-) diff --git a/package-lock.json b/package-lock.json index 68cd436..ee77e18 100644 --- a/package-lock.json +++ b/package-lock.json @@ -31,6 +31,31 @@ "node": ">=24" } }, + "node_modules/@emnapi/core": { + "version": "2.0.0-alpha.4", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-alpha.4.tgz", + "integrity": "sha512-KjoUR6mNvjT+z5bKMy+a5QDI+kTNTiMZi6uPKzWuWjwZGNa0UPwIVduTfeBRdf6v8Ws5fmHDh7Usf15w/ANfkg==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "@emnapi/wasi-threads": "2.0.1", + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/runtime": { + "version": "2.0.0-alpha.4", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-alpha.4.tgz", + "integrity": "sha512-Wy1TQ99obRP3Ah7cf/OOtK1zD9t3pYTWz+G/SpAwTFMhG5hoMdlvfzBpYoHUigS/izu3q+VhYMKhJd7Ii/trpg==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, "node_modules/@emnapi/wasi-threads": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.0.1.tgz", @@ -38,6 +63,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "tslib": "^2.4.0" } @@ -1493,7 +1519,6 @@ "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=18" } diff --git a/src/type-extensions/table.ts b/src/type-extensions/table.ts index a725c48..611ffe7 100644 --- a/src/type-extensions/table.ts +++ b/src/type-extensions/table.ts @@ -93,17 +93,26 @@ class TableTypeExtension extends TypeExtension { } /** - * A table becomes a JS array only when `lua_next` walks exactly the keys "1".."n" in that - * order. Converting keys stops as soon as that is ruled out, because the keys this pass looks - * at are read again alongside the values. + * A table becomes a JS array only when `lua_next` walks exactly the integer keys 1..n in that + * order, which is Lua's own notion of a sequence. The keys this pass looks at are read again + * alongside the values, so it stops as soon as that is ruled out. */ private isSequential(thread: Thread, index: number): boolean { - let count = 0 + const module = thread.module - thread.module.lua_pushnil(thread.address) - while (thread.module.lua_next(thread.address, index)) { - // JS only supports string keys in objects. - if (thread.indexToString(-2) !== String(count + 1)) { + // A border of 0 means t[1] is nil, which settles every table read as an object -- the + // common case -- with one call instead of starting a walk. + if (module.lua_rawlen(thread.address, index) === 0n) { + return false + } + + let count = 0 + module.lua_pushnil(thread.address) + while (module.lua_next(thread.address, index)) { + // Compared as a number rather than through tostring, which would format the key in C + // and decode it in JS for every element. A float key with an integral value is stored + // as an integer, so this is the same test. + if (module.lua_type(thread.address, -2) !== LuaType.Number || module.lua_tonumberx(thread.address, -2, null) !== count + 1) { // Pop the key and the value, since the walk is being abandoned part way. thread.pop(2) return false @@ -113,25 +122,40 @@ class TableTypeExtension extends TypeExtension { thread.pop() } - return count > 0 + // Non-empty, since a border above 0 means some element is present. + return true } private readTableValues(thread: Thread, index: number, seenMap: LuaGetCache, table: TableType): void { const isArray = Array.isArray(table) + // lua_next leaves each key and value in the same two slots, so the indexes are resolved + // once here rather than by a lua_absindex per entry. + const keyIndex = thread.getTop() + 1 + const valueIndex = keyIndex + 1 thread.module.lua_pushnil(thread.address) while (thread.module.lua_next(thread.address, index)) { if (isArray) { // An array takes its order from the walk, so its keys are never converted. - table.push(thread.getValue(-1, undefined, seenMap)) + table.push(thread.getValue(valueIndex, undefined, seenMap)) } else { - const key = thread.indexToString(-2) - table[key] = thread.getValue(-1, undefined, seenMap) + table[this.readKey(thread, keyIndex)] = thread.getValue(valueIndex, undefined, seenMap) } thread.pop() } } + + /** + * A key as the JS property name, which is how Lua would print it. A string, the usual case, is + * read in place: luaL_tolstring would look for a __tostring on it, push a copy and need a pop. + */ + private readKey(thread: Thread, index: number): string { + if (thread.module.lua_type(thread.address, index) === LuaType.String) { + return thread.module.lua_tolstring(thread.address, index, null) + } + return thread.indexToString(index) + } } export default function createTypeExtension(state: LuaState): TypeExtension { diff --git a/test/state.test.js b/test/state.test.js index 8fc1c08..70e43e2 100644 --- a/test/state.test.js +++ b/test/state.test.js @@ -139,6 +139,31 @@ describe('State', () => { expect(value).to.be.eql(arr) }) + it('only a lua sequence becomes a JS array', async () => { + using state = await getState() + const value = await state.doString(` + return { + sequence = { 10, 20, 30 }, + float_keys = { [1.0] = 'a', [2.0] = 'b' }, + hole = { [2] = 'b' }, + string_keys = { ['1'] = 'a', ['2'] = 'b' }, + mixed = { 'a', 'b', name = 'c' }, + empty = {}, + } + `) + + expect(value).to.be.eql({ + sequence: [10, 20, 30], + float_keys: ['a', 'b'], + hole: { 2: 'b' }, + string_keys: { 1: 'a', 2: 'b' }, + mixed: { 1: 'a', 2: 'b', name: 'c' }, + empty: {}, + }) + expect(Array.isArray(value.string_keys)).to.be.false + expect(Array.isArray(value.empty)).to.be.false + }) + it('receive JS object with multiple circular references on lua should succeed', async () => { using state = await getState() const obj1 = { From 9d4467fca2d6b5cebf00c150ffa3c7b7738bc402 Mon Sep 17 00:00:00 2001 From: ceifa Date: Tue, 1 Sep 2026 20:42:59 -0300 Subject: [PATCH 54/83] update packages --- package-lock.json | 1633 +++++++++++---------------------------------- package.json | 12 +- 2 files changed, 412 insertions(+), 1233 deletions(-) diff --git a/package-lock.json b/package-lock.json index ee77e18..9416a0d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,7 +9,7 @@ "version": "1.16.0", "license": "MIT", "dependencies": { - "@types/emscripten": "1.41.5" + "@types/emscripten": "1.41.6" }, "bin": { "wasmoon": "bin/wasmoon" @@ -19,11 +19,11 @@ "chai": "6.2.2", "chai-as-promised": "8.0.2", "fengari": "0.1.5", - "mocha": "11.7.6", - "oxfmt": "0.61.0", - "oxlint": "1.76.0", - "playwright": "1.62.0", - "rolldown": "1.2.0", + "mocha": "12.0.0", + "oxfmt": "0.66.0", + "oxlint": "1.81.0", + "playwright": "1.62.1", + "rolldown": "1.2.6", "tslib": "2.8.1", "typescript": "7.0.2" }, @@ -31,87 +31,10 @@ "node": ">=24" } }, - "node_modules/@emnapi/core": { - "version": "2.0.0-alpha.4", - "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-alpha.4.tgz", - "integrity": "sha512-KjoUR6mNvjT+z5bKMy+a5QDI+kTNTiMZi6uPKzWuWjwZGNa0UPwIVduTfeBRdf6v8Ws5fmHDh7Usf15w/ANfkg==", - "dev": true, - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "@emnapi/wasi-threads": "2.0.1", - "tslib": "^2.4.0" - } - }, - "node_modules/@emnapi/runtime": { - "version": "2.0.0-alpha.4", - "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-alpha.4.tgz", - "integrity": "sha512-Wy1TQ99obRP3Ah7cf/OOtK1zD9t3pYTWz+G/SpAwTFMhG5hoMdlvfzBpYoHUigS/izu3q+VhYMKhJd7Ii/trpg==", - "dev": true, - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "tslib": "^2.4.0" - } - }, - "node_modules/@emnapi/wasi-threads": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.0.1.tgz", - "integrity": "sha512-9DsSk+o5NBX0CCJT8s0EROGSGxjR/tKu6aBTaVyq+SjAEQH4XcdcRxPBRzsBLizTTJ49MJjF+jgu3qnO9GLQcQ==", - "dev": true, - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "tslib": "^2.4.0" - } - }, - "node_modules/@isaacs/cliui": { - "version": "8.0.2", - "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", - "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", - "dev": true, - "license": "ISC", - "dependencies": { - "string-width": "^5.1.2", - "string-width-cjs": "npm:string-width@^4.2.0", - "strip-ansi": "^7.0.1", - "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", - "wrap-ansi": "^8.1.0", - "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/@napi-rs/wasm-runtime": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.0.tgz", - "integrity": "sha512-kDoONqMa+VnZ4vvvu/ZUurpJ4gkZU57e7g69qpNgWhYcZFPUHZM2CEMKm+cG6ufDVALbjMvfmMjFVqaK7uEMnA==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@tybys/wasm-util": "^0.10.3" - }, - "engines": { - "node": "^20.19.0 || ^22.13.0 || >=23.5.0" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/Brooooooklyn" - }, - "peerDependencies": { - "@emnapi/core": "^2.0.0-alpha.3", - "@emnapi/runtime": "^2.0.0-alpha.3" - } - }, "node_modules/@oxc-project/types": { - "version": "0.140.0", - "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.140.0.tgz", - "integrity": "sha512-h5LUOzGArYemnW1NMz/DuuQhBi96J6JL2Bk8zE4kvqxB5Sg3jxmCiH4uyOWHDkiKSt5vWlG4FIwCR/DbstcNRQ==", + "version": "0.147.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.147.0.tgz", + "integrity": "sha512-IJ3s6ltHLp45S0bh7phkX+gJO7A1Wuz2EaqpAhb8WjqDwbzMiWKHhyyT42tskaWjEYXtHtVCPpnBJVT9+dcRLg==", "dev": true, "license": "MIT", "funding": { @@ -119,9 +42,9 @@ } }, "node_modules/@oxfmt/binding-android-arm-eabi": { - "version": "0.61.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm-eabi/-/binding-android-arm-eabi-0.61.0.tgz", - "integrity": "sha512-BaS+1OVvg9sr+Xav0+KdWedQRcAzrdoEcwMZeqoc2F6ieC1s/t5eM35YQoRPQ7vAqkZ+p3tbQb1r9I9mrV5oGA==", + "version": "0.66.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm-eabi/-/binding-android-arm-eabi-0.66.0.tgz", + "integrity": "sha512-2Me9eoptv6ERdEuI2P8AOlYdHHraXebJaM6SC0kc2Dfb+mLrep2db+fedBPKaYn673h/vBgvP4tkOdAbaudX6w==", "cpu": [ "arm" ], @@ -136,9 +59,9 @@ } }, "node_modules/@oxfmt/binding-android-arm64": { - "version": "0.61.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm64/-/binding-android-arm64-0.61.0.tgz", - "integrity": "sha512-of8atAV0M1egGcVOMbgZCvc10sFOP3ayQBNQV5h5G3fNq8gACdEswfFk9bzGrdbM23rtg0Coxi7np7oPLcueNw==", + "version": "0.66.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm64/-/binding-android-arm64-0.66.0.tgz", + "integrity": "sha512-u7O+bSSF0HGsDKkQQxBqvLGVepu93RA+JKu+ONqvfh4sCnCEbj31wZj4iG5gk3XfRwrmYj0/8catkO2LcblQKQ==", "cpu": [ "arm64" ], @@ -153,9 +76,9 @@ } }, "node_modules/@oxfmt/binding-darwin-arm64": { - "version": "0.61.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-arm64/-/binding-darwin-arm64-0.61.0.tgz", - "integrity": "sha512-7l8+5ov4BGwtAcmpzvEik/TG3bciwyw/S3e6j5GKH7pcQqcgCVxD3AuJeP6upto+SOTBKQ4wrrdbMt0gq8fHSQ==", + "version": "0.66.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-arm64/-/binding-darwin-arm64-0.66.0.tgz", + "integrity": "sha512-/ikyMIVjX/sdo7KtjxoEsSUosfPzveVhT9RWMx9yGqFDKFJ89JAEKuEeLBmurDjrkb4w8tOnAdSO3SBaplY3bw==", "cpu": [ "arm64" ], @@ -170,9 +93,9 @@ } }, "node_modules/@oxfmt/binding-darwin-x64": { - "version": "0.61.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-x64/-/binding-darwin-x64-0.61.0.tgz", - "integrity": "sha512-Fnz4dDDXBb7udk+DmwelNjxbD6yptyxwCqwCH2ebo4RVLxVsRfFsn/AHJC49KIltPrVokamGv4SSOsiV50DTxQ==", + "version": "0.66.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-x64/-/binding-darwin-x64-0.66.0.tgz", + "integrity": "sha512-q5xUsKeFqawa9NXa6ZGXWimFV19m8MogKPdTaSVDAAk2EQKBmBZRDeluwcl1p8ty/OFc9s9888OKEh3xfPVH0g==", "cpu": [ "x64" ], @@ -187,9 +110,9 @@ } }, "node_modules/@oxfmt/binding-freebsd-x64": { - "version": "0.61.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-freebsd-x64/-/binding-freebsd-x64-0.61.0.tgz", - "integrity": "sha512-mddOebKNCP+AucmzfNsk3jgbr681qAUvgMqi865GW5gWLJ/AnzXbvjQRrny0e++NAN8aphav/aRSrfFxNsNjpA==", + "version": "0.66.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-freebsd-x64/-/binding-freebsd-x64-0.66.0.tgz", + "integrity": "sha512-CR+x4VzMY0pRXLK/xFQ/RzsSFkP5t2Z2mef0QY6OP/rTRcMUoMLCOM62/3Fp/t0K+UDoBKxvMyeb6D0zPMjleA==", "cpu": [ "x64" ], @@ -204,9 +127,9 @@ } }, "node_modules/@oxfmt/binding-linux-arm-gnueabihf": { - "version": "0.61.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-0.61.0.tgz", - "integrity": "sha512-svx59iYL+DbaZGZUIoice4W0CjRXGExnbz7Re+awIb60rVxBS2KrU7Hnlx+nZYanLGLpjneUEgo/VFEKkSZAyQ==", + "version": "0.66.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-0.66.0.tgz", + "integrity": "sha512-ZEYmO/LbH9tTQCADILHGZE4GeOXOAj2VzedHkASNwjmwlwtutJCLpCJbIs37wRGTFgWRoEcD72jpMX+IBJUGjQ==", "cpu": [ "arm" ], @@ -221,9 +144,9 @@ } }, "node_modules/@oxfmt/binding-linux-arm-musleabihf": { - "version": "0.61.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-0.61.0.tgz", - "integrity": "sha512-BYK9MPJPCf6d+fLKMTruThmEyCtHzQ1zLcsrTlUVkmnoXIaHAbfpeLYQwX1tkjs7W11dyzoi6HFvKcdnvX1zNg==", + "version": "0.66.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-0.66.0.tgz", + "integrity": "sha512-hNtR9/oU0CeTkq7JnRkmBQwqe17v2ZaAMLC4VcN7IIOWeRyWDk0knSPWS9iiLmtbZ2RRBBtsG01jQgkZmKCJeQ==", "cpu": [ "arm" ], @@ -238,13 +161,16 @@ } }, "node_modules/@oxfmt/binding-linux-arm64-gnu": { - "version": "0.61.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-0.61.0.tgz", - "integrity": "sha512-QUaCNLq2/EC6G5ljOuFanl9Lgw6ZWp4co7rs4+KOMUzbGfA4Lq58FHRjjF9sVIG+93XSbo343MxFATrOU1qctA==", + "version": "0.66.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-0.66.0.tgz", + "integrity": "sha512-uwOVQ8i6I1LT/+eDzfsgrrcZp8Fn6NPVUPn8fF5gdFGekFf0PddF+LEuwsD0/pbNUcKZhDj2rQ5UpITh9gF4iQ==", "cpu": [ "arm64" ], "dev": true, + "libc": [ + "glibc" + ], "license": "MIT", "optional": true, "os": [ @@ -255,13 +181,16 @@ } }, "node_modules/@oxfmt/binding-linux-arm64-musl": { - "version": "0.61.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-musl/-/binding-linux-arm64-musl-0.61.0.tgz", - "integrity": "sha512-S6uvJ6MXnRXl+zTs0CARNDvkE+cymj0EVWEKKsyKnlLlqTyQJBjw5s4D2pSIOZc+S46cy4STefzcr/sm0VzVPA==", + "version": "0.66.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-musl/-/binding-linux-arm64-musl-0.66.0.tgz", + "integrity": "sha512-tTkF2Dmx4nGAjmBlZb+UtTGqR/EK4ZrW9qBfzte07a9XWqzoGGKzpFFlyNDhQe+Uwql94+ReCTeNbhOXscw1Dg==", "cpu": [ "arm64" ], "dev": true, + "libc": [ + "musl" + ], "license": "MIT", "optional": true, "os": [ @@ -272,13 +201,16 @@ } }, "node_modules/@oxfmt/binding-linux-ppc64-gnu": { - "version": "0.61.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-0.61.0.tgz", - "integrity": "sha512-6VDlRcytvZG6UlSIdAFKDLbppo9tvPxrWzle6vHldYFMeuDPQEfMKrkwezp7FaBq1wik9ra554ZZeRPsyIkFpg==", + "version": "0.66.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-0.66.0.tgz", + "integrity": "sha512-F3cKHUav4yXOHn6GFnwpBhSYsJOYKKf9eqO/9jlEuqPxNw9zb98E9ZFct79gcg8pibUGkbveEu9WDlmXJpDzKw==", "cpu": [ "ppc64" ], "dev": true, + "libc": [ + "glibc" + ], "license": "MIT", "optional": true, "os": [ @@ -289,13 +221,16 @@ } }, "node_modules/@oxfmt/binding-linux-riscv64-gnu": { - "version": "0.61.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-0.61.0.tgz", - "integrity": "sha512-KkBTYbzExpbmn15XjKPLu2fRV2PVlq+KWt+brad5rwIa03vdYoaDRWiS7raHII/dCTR6Ro4UpYUCH4t6lif4WQ==", + "version": "0.66.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-0.66.0.tgz", + "integrity": "sha512-K5fDaNZfDyQMYA/3qL21bqyN0X9T15LLwwbFPt2aHc94+ZG7bh0vZEsy2y7NlRnjjHFSwN+Hzg6ldJtbOriH4Q==", "cpu": [ "riscv64" ], "dev": true, + "libc": [ + "glibc" + ], "license": "MIT", "optional": true, "os": [ @@ -306,13 +241,16 @@ } }, "node_modules/@oxfmt/binding-linux-riscv64-musl": { - "version": "0.61.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-0.61.0.tgz", - "integrity": "sha512-69tzIq7sJLVB9dxYYtvMzcSSsnZHSO+U2U19O2RqDqgj6+Q4O7HjSXdaszbcgqzhsUwzSH7z5kWvk8nmf6BHTg==", + "version": "0.66.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-0.66.0.tgz", + "integrity": "sha512-44Yc+I+qOmTElRcEhm5hUKIUJEQIOugymz4ua4tB0Wox7tGAfIbjzmXz/HDAtw1Ij6gmBwZlzh4hc9679RhWeA==", "cpu": [ "riscv64" ], "dev": true, + "libc": [ + "musl" + ], "license": "MIT", "optional": true, "os": [ @@ -323,13 +261,16 @@ } }, "node_modules/@oxfmt/binding-linux-s390x-gnu": { - "version": "0.61.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-0.61.0.tgz", - "integrity": "sha512-Oqi/N0OvtOVXsPKAOOhKgGH3msRYF8BLJaNBbWiupRiKoKVyc8JRKPCfarkQJC+RgP9U8raUKLe+bNwd0HUMiA==", + "version": "0.66.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-0.66.0.tgz", + "integrity": "sha512-1e29Eg9hEj2kRBB19M0seIehPbbXHCk35GvImjDvb79rjjYjXCRmtbUNHJcgoktZAMIzXrTbxDBKmTc1V4bg3A==", "cpu": [ "s390x" ], "dev": true, + "libc": [ + "glibc" + ], "license": "MIT", "optional": true, "os": [ @@ -340,13 +281,16 @@ } }, "node_modules/@oxfmt/binding-linux-x64-gnu": { - "version": "0.61.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-gnu/-/binding-linux-x64-gnu-0.61.0.tgz", - "integrity": "sha512-3TKwv/ed4uwJSemAA8P9XcoqETpjQI4waquF9UilhA9Mn/dhr1PdUEXWlL74mtc6ZNfmKPA9+NEJm01nRF8CVA==", + "version": "0.66.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-gnu/-/binding-linux-x64-gnu-0.66.0.tgz", + "integrity": "sha512-vODY1UQo10gngn0+D4xHKU84F1Twm1LqrzV4SqPXvmQKSd87paehvZ6jqA5wKs6XQrlWul9clYMDVHcoW9CPMA==", "cpu": [ "x64" ], "dev": true, + "libc": [ + "glibc" + ], "license": "MIT", "optional": true, "os": [ @@ -357,13 +301,16 @@ } }, "node_modules/@oxfmt/binding-linux-x64-musl": { - "version": "0.61.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-musl/-/binding-linux-x64-musl-0.61.0.tgz", - "integrity": "sha512-uFso4u4nLkVSlMCpgjyvWV60Gt7GvDQHnk1mmRxHIkZTMB0ljpUKwCD9FYGgN9H97x2wYl0UwEjgRZaPIuhEhw==", + "version": "0.66.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-musl/-/binding-linux-x64-musl-0.66.0.tgz", + "integrity": "sha512-YDzXx2JsT4+HL4MdkVrYjO55NS5lUKNm8rLC4ZPou8+seu0v0jhecSh+ufoO6+xEa8gccEezMlI2WHJi4ApUgw==", "cpu": [ "x64" ], "dev": true, + "libc": [ + "musl" + ], "license": "MIT", "optional": true, "os": [ @@ -374,9 +321,9 @@ } }, "node_modules/@oxfmt/binding-openharmony-arm64": { - "version": "0.61.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-openharmony-arm64/-/binding-openharmony-arm64-0.61.0.tgz", - "integrity": "sha512-keGLkzeOvkMpNmPp4hffXWpfoSsY6e1K8++KXD4mSSfxdvM8q9QUDsYY689TB1k6Co832DZn1MnaaVx6cIBMWQ==", + "version": "0.66.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-openharmony-arm64/-/binding-openharmony-arm64-0.66.0.tgz", + "integrity": "sha512-mJjUYd8lj0+j4JkYyEM+5qKBf1Rnrpgjn/SVYKJhicVDqLz566ooa7Fs8zflPqt+dnZDV7X054rVIQX6ZcQNlQ==", "cpu": [ "arm64" ], @@ -391,9 +338,9 @@ } }, "node_modules/@oxfmt/binding-win32-arm64-msvc": { - "version": "0.61.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-0.61.0.tgz", - "integrity": "sha512-VzsAISkFxmNhJ5LBDEL9VuH6tJsVJMtqYit2LyIUf/HLnsCe4Pg9SMOjjVQzGWt0bnpyfJ94CrqTqcpNZzK+ug==", + "version": "0.66.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-0.66.0.tgz", + "integrity": "sha512-soV+0vESv7e5ntCHWC61x4gg8OSak6IHHnWsZmHrJFlvMj2AK+kmldErCNkVkrvc1Ts2/++rJXn+IuAb2WMXhw==", "cpu": [ "arm64" ], @@ -408,9 +355,9 @@ } }, "node_modules/@oxfmt/binding-win32-ia32-msvc": { - "version": "0.61.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-0.61.0.tgz", - "integrity": "sha512-xv4t7yzwJoYaLB6Zv28B3W+j7brEjsyv50rLTAQgmxJzddce9fAMCxed8dSAkbWES0zz2J29nYK5FaTuD2YBHg==", + "version": "0.66.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-0.66.0.tgz", + "integrity": "sha512-YCPi23uRIEYuIKTZohAkKbPFpujQ5QBuUM5iDv+UqbCmTPAkaFsxjsSuB8xlBpRT0G7eP/4HMF+cPDSqHtOD9A==", "cpu": [ "ia32" ], @@ -425,9 +372,9 @@ } }, "node_modules/@oxfmt/binding-win32-x64-msvc": { - "version": "0.61.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-x64-msvc/-/binding-win32-x64-msvc-0.61.0.tgz", - "integrity": "sha512-6EZXFkqOwxdDYjIn3TSNnPk3ST5E5GiYd4FiM6UF/mCL/LZSfr6D6UygTfW3R1PCQP2quCKpCEGRlij8E3VYbg==", + "version": "0.66.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-x64-msvc/-/binding-win32-x64-msvc-0.66.0.tgz", + "integrity": "sha512-bwTQcv/JVRPkOqQtMF0X7vpvpncDQiBcXHxZ9S2hR12Hlo8bvBdUR5x5XnxzDZ3kM0qoZw1rv7KaD66Ly+pFWA==", "cpu": [ "x64" ], @@ -442,9 +389,9 @@ } }, "node_modules/@oxlint/binding-android-arm-eabi": { - "version": "1.76.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm-eabi/-/binding-android-arm-eabi-1.76.0.tgz", - "integrity": "sha512-ZHIE5Zt9AsPDcY4nOlofXt0YfneEeo+QrKMPcPzLf2Z6Q8VtV2W73d7SFJ920WUwyik783u/doKCs3KXdwG+7w==", + "version": "1.81.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm-eabi/-/binding-android-arm-eabi-1.81.0.tgz", + "integrity": "sha512-IcCRsXiedJoJopY6mpZUBEeVFsUrutmrG7dZ87zMuKJlhg70Ora9bBl1WcCxZQtyI10YpnVdEso5oCg7YcfSHw==", "cpu": [ "arm" ], @@ -459,9 +406,9 @@ } }, "node_modules/@oxlint/binding-android-arm64": { - "version": "1.76.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm64/-/binding-android-arm64-1.76.0.tgz", - "integrity": "sha512-shm/ngQilHK6bs+ElJWa4oHfNj5vL1Gl/iVEJldTQjpr0/67oSgr0KUpbmcnLig5Fo0v/l6j2567A7TOL89ONA==", + "version": "1.81.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm64/-/binding-android-arm64-1.81.0.tgz", + "integrity": "sha512-GRrIPyTGVhx3L3h+0T5xT2A0jFAcdPv4+IfuXpGDLIdl6XeYhgg/zw72A5ILZoUgRqZuM8F1y+V/gfDriXSxzQ==", "cpu": [ "arm64" ], @@ -476,9 +423,9 @@ } }, "node_modules/@oxlint/binding-darwin-arm64": { - "version": "1.76.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-arm64/-/binding-darwin-arm64-1.76.0.tgz", - "integrity": "sha512-rvJmrAPKSQ9aWJ6wIS6CK2tJjwzfW0ApQH9qokq6sfDvmHwoyIHxHFMq7z7i7GiV6fdE6s8qvBqWKPTu8RmT6Q==", + "version": "1.81.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-arm64/-/binding-darwin-arm64-1.81.0.tgz", + "integrity": "sha512-qNQ9tXRgLuKbqSV1S2h9h4KPHjbovO7RRR2/enUOtHzTkFZ7B9X5zqqHJua8dRyc7dBy7Aoyq5pqTSLFVcAzGQ==", "cpu": [ "arm64" ], @@ -493,9 +440,9 @@ } }, "node_modules/@oxlint/binding-darwin-x64": { - "version": "1.76.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-x64/-/binding-darwin-x64-1.76.0.tgz", - "integrity": "sha512-U/zYdb7VYKGY6pA9Vd2rYl9O/HlCylcOlb5PGPvVLtg+oLGsk6H3XGKEMHKyqD3nmmtmlmwb/8SwU2vfSAtvMw==", + "version": "1.81.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-x64/-/binding-darwin-x64-1.81.0.tgz", + "integrity": "sha512-q0QTm32jWga2Gv4j7IaVZN0jYMi9UV73sWVgFtDA4iIfqwMCLLZ3ve+9KwfYtsaKZSgQhmPaogeZWqDZpcY1Pw==", "cpu": [ "x64" ], @@ -510,9 +457,9 @@ } }, "node_modules/@oxlint/binding-freebsd-x64": { - "version": "1.76.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-freebsd-x64/-/binding-freebsd-x64-1.76.0.tgz", - "integrity": "sha512-WvKG9CAriuo0XNiFzpXjDngUZcRGFNpaK2kLyMUsnJlShxkT96u+BpJQ3KqdQwGOrvI14L6V8bAwXwAYNNY6Jg==", + "version": "1.81.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-freebsd-x64/-/binding-freebsd-x64-1.81.0.tgz", + "integrity": "sha512-/+8wVWDXEC7wHVAhOc59Fw/SkMc1arLkFD8iQCaSsmzenK1X4doFqquL9H1wrtGUzaiycVqkf/sSpcILK6W1UA==", "cpu": [ "x64" ], @@ -527,9 +474,9 @@ } }, "node_modules/@oxlint/binding-linux-arm-gnueabihf": { - "version": "1.76.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.76.0.tgz", - "integrity": "sha512-qJ5+RH99TqFRq3UCDxkW0zJJu9c+OAHFY72vGlxZLEpuO+MpKo3POgqb8sYipL9KYm8XY6ofb0HsOuvY6hQNqQ==", + "version": "1.81.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.81.0.tgz", + "integrity": "sha512-4xt422FEgioRq9hAL4Tq7fujGUWnc8z1BJ+Oi8RN8vB8axaP+sdK6a2xdlcQCCYnJg9QMuMFS0AucuIFx/EacA==", "cpu": [ "arm" ], @@ -544,9 +491,9 @@ } }, "node_modules/@oxlint/binding-linux-arm-musleabihf": { - "version": "1.76.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-1.76.0.tgz", - "integrity": "sha512-PvPCVptkgVARsucgIqFQQcSmJ6xc6GtnVB5bRBekRahTc9eObMtjHfMjy5M+C2tHt5UCMttWM9RuSk/H9NqYeg==", + "version": "1.81.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-1.81.0.tgz", + "integrity": "sha512-u3vna8KdGplH4DRCW9K54D68fcMo7IxVrkCJWwXnIhwtBdnDnYrmzOUA/XjmBlPpcLsgw9Z5BNdY4za9+Dj+MQ==", "cpu": [ "arm" ], @@ -561,13 +508,16 @@ } }, "node_modules/@oxlint/binding-linux-arm64-gnu": { - "version": "1.76.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.76.0.tgz", - "integrity": "sha512-3KeFDx8Bu4HPAXbuHZOr/oHvN+QT+JQhMw/NYPz7Z071xLSsG27Jfh9PIQVEY7hk1I+jr43ExqRIeJ6VKk2yLw==", + "version": "1.81.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.81.0.tgz", + "integrity": "sha512-3j9k+gsYsE7nv71GWotXsqsa2l9/aJenD7dVHNt/CBvsb0SgRjSMnHFeP59IXUAl1wvVFhqGl2wJNMwWU3UBlA==", "cpu": [ "arm64" ], "dev": true, + "libc": [ + "glibc" + ], "license": "MIT", "optional": true, "os": [ @@ -578,13 +528,16 @@ } }, "node_modules/@oxlint/binding-linux-arm64-musl": { - "version": "1.76.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.76.0.tgz", - "integrity": "sha512-oPFkkKTgl0K/EIg9fQ8oA3IGcI05/Mq1en04iFa41mmNPT+6KEiByVazTOZZJiHMBBrbsns1YJ2e1Scqwzesjw==", + "version": "1.81.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.81.0.tgz", + "integrity": "sha512-k5iAp3dNxW0/uDCBY+WSm8jKB2szu7SkEQZdgRRpDXvuDd69vvDcqhB3A/pWCfCwXyenjNjFn9Td1fVoyAc+Yg==", "cpu": [ "arm64" ], "dev": true, + "libc": [ + "musl" + ], "license": "MIT", "optional": true, "os": [ @@ -595,13 +548,16 @@ } }, "node_modules/@oxlint/binding-linux-ppc64-gnu": { - "version": "1.76.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.76.0.tgz", - "integrity": "sha512-gN7yZ0eqflA5Fhf1wvHxGUltIV3FsvmB1zhNMDEK9vSHhc7E6qg9CuPeBgPZab66Tjzq6w6kHAtNEvnTHf4cyw==", + "version": "1.81.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.81.0.tgz", + "integrity": "sha512-TFqLja3uYmVSte6nof9GWrex9Z8WgdZrNiLC6Te5rXGDqXB2y4j/26iFhwosXiAFqDhE9JJVuuCkDKLwptTn1g==", "cpu": [ "ppc64" ], "dev": true, + "libc": [ + "glibc" + ], "license": "MIT", "optional": true, "os": [ @@ -612,13 +568,16 @@ } }, "node_modules/@oxlint/binding-linux-riscv64-gnu": { - "version": "1.76.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-1.76.0.tgz", - "integrity": "sha512-S/HqMbn22mQrjtErUxEoS/a55u8kIeXvreIxiJu5G7Le3UecEd6SQZxrDIpuhtgaFnsY/nVra3ytP+pRljDilA==", + "version": "1.81.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-1.81.0.tgz", + "integrity": "sha512-UEcySvGS0NOVo7h7n7CYyJL9+6gFAh7Zc/ToDXVScFvzHSTIxtzkMVU30rmQ6+nQ1LF+UdiRDdJajpDu+OylLg==", "cpu": [ "riscv64" ], "dev": true, + "libc": [ + "glibc" + ], "license": "MIT", "optional": true, "os": [ @@ -629,13 +588,16 @@ } }, "node_modules/@oxlint/binding-linux-riscv64-musl": { - "version": "1.76.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-1.76.0.tgz", - "integrity": "sha512-ZIga3097VJZolGZk6SrIAUokIGfRkxRlhiHDUznZptGBfwrhD7pNfD1rzEzsCwvk/1DX0A1bLz+liuNh5QKIVQ==", + "version": "1.81.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-1.81.0.tgz", + "integrity": "sha512-H+diDbhD00+wI1IRP8Kz88x/lat+DgtoBJzoTthS16xkTJGNaEkfb8gzmd1rzc/2uDQQMl7GNl+JFUacVeWxIA==", "cpu": [ "riscv64" ], "dev": true, + "libc": [ + "musl" + ], "license": "MIT", "optional": true, "os": [ @@ -646,13 +608,16 @@ } }, "node_modules/@oxlint/binding-linux-s390x-gnu": { - "version": "1.76.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.76.0.tgz", - "integrity": "sha512-ZGiiA7pFzMJSyMWYZTVlPgbTsx+Vl8ihLGMIujPwaslUF7kIPPWAbVmAlTc+9lWDV+DCiB8Ikixu+lSHeOIIWQ==", + "version": "1.81.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.81.0.tgz", + "integrity": "sha512-8znJ/5TekjOKg1j1Acho4PJMdiAHLtlcXuWEiipOhAMV6rQcXdmDdXCbheyDczN6TjBwiNfjcP81k4AthrKRzw==", "cpu": [ "s390x" ], "dev": true, + "libc": [ + "glibc" + ], "license": "MIT", "optional": true, "os": [ @@ -663,13 +628,16 @@ } }, "node_modules/@oxlint/binding-linux-x64-gnu": { - "version": "1.76.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.76.0.tgz", - "integrity": "sha512-JLiy5WuvEBFTT6ErIFV35SLzi0R7Iri6MKU6dZbTxfIx8pndbbPs3Mj780nMipBFcPkti+okAPOJ9POKkHFEgg==", + "version": "1.81.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.81.0.tgz", + "integrity": "sha512-Q2Wj70yFsvn5QjlmifFzbj4H+kJy53bwqc41o1fzoM7MpLV1NIbhg/LpWXRfC6KOkSAdUx1Wd8VJsdPmhp/HRA==", "cpu": [ "x64" ], "dev": true, + "libc": [ + "glibc" + ], "license": "MIT", "optional": true, "os": [ @@ -680,13 +648,16 @@ } }, "node_modules/@oxlint/binding-linux-x64-musl": { - "version": "1.76.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-musl/-/binding-linux-x64-musl-1.76.0.tgz", - "integrity": "sha512-z7lgKQtbo/I1NIe8G5NHLesxJDv0tRSUWTpXKb9Pm3E9nKFKfO4IOSDtFroKgXtOYb0jQbcdH+0wzTyMXVes+A==", + "version": "1.81.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-musl/-/binding-linux-x64-musl-1.81.0.tgz", + "integrity": "sha512-cPInHp/ddEe5qkyK2IiyQ8Q3Mp2oLLEhhsGgTK2oZx4L6+llGam1H1yBvJZ7qHfOXj8N3hxBS8sj4tO+gtFlIg==", "cpu": [ "x64" ], "dev": true, + "libc": [ + "musl" + ], "license": "MIT", "optional": true, "os": [ @@ -697,9 +668,9 @@ } }, "node_modules/@oxlint/binding-openharmony-arm64": { - "version": "1.76.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-openharmony-arm64/-/binding-openharmony-arm64-1.76.0.tgz", - "integrity": "sha512-JOjKymIpb9QcYfEhZsN6h4V9Ivd474W38cNIBRv6bg2TbIvogbMTH0Mg6YWW9TiRDqfcX+/Hyfsbo5vcSE5guQ==", + "version": "1.81.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-openharmony-arm64/-/binding-openharmony-arm64-1.81.0.tgz", + "integrity": "sha512-0CQxSX4ajqm07AHBf5U33qQzXKdd7wtq/oTL/7vpY6RNNuxrRi8W4bqUV1Jyu/vj+9KmxQyDhxfeVX1nQL6kfg==", "cpu": [ "arm64" ], @@ -714,9 +685,9 @@ } }, "node_modules/@oxlint/binding-win32-arm64-msvc": { - "version": "1.76.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.76.0.tgz", - "integrity": "sha512-pqDWZiwcmByWUEm1NFUBNiT6aentCcaoMWJv0HbXEmuYermJ4sg8ppVrshubYP2MZ6SHccJJcpr6x469PuDFIw==", + "version": "1.81.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.81.0.tgz", + "integrity": "sha512-l0hbeISm9673hVrrQU8j/p2M7YH9Ouoj7p7E/QM55NTrKVLP+P3PF8hLu+OY+x0VtGRW+ggiQKZqmdYps9H+TA==", "cpu": [ "arm64" ], @@ -731,9 +702,9 @@ } }, "node_modules/@oxlint/binding-win32-ia32-msvc": { - "version": "1.76.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-1.76.0.tgz", - "integrity": "sha512-Ba0O659kgMv6pwO3z9PdO+K3aMxQRaw9HnG+e6AtOfgwcKFvYilciQYBoUBmxfQvOCKZe1SwjMkuB542NkuDMQ==", + "version": "1.81.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-1.81.0.tgz", + "integrity": "sha512-ksqPP5jbFXcYreEQ7zdJh06rJQBymCTyGRCdaXjfcf2aG4f8KxUWY5wcgYHmaTK+FJ4bPG5sUAdOX+6trnH1JA==", "cpu": [ "ia32" ], @@ -748,9 +719,9 @@ } }, "node_modules/@oxlint/binding-win32-x64-msvc": { - "version": "1.76.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.76.0.tgz", - "integrity": "sha512-5qcirPHO8nKfkoowEVWtpAoVTcYDy6g0UT0NGic450Qv8J2NrOqg4uQ8QppRP4MDTC7Xx47lbZnmadTH03CGGA==", + "version": "1.81.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.81.0.tgz", + "integrity": "sha512-IZuUCwGw9emG5JtCp+fYGB+Z4OWEoeEcM8R5BA1pYw63/ieYFVdcU2ylxTpHbVHSenZnsYE+ZZ20uHAJszQ4cA==", "cpu": [ "x64" ], @@ -764,21 +735,27 @@ "node": "^20.19.0 || >=22.12.0" } }, - "node_modules/@pkgjs/parseargs": { - "version": "0.11.0", - "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", - "integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==", + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.6.tgz", + "integrity": "sha512-b+jTcARdTiFLI6jB4a5XjTm0RWd6KcRfQj/I2356fxUZemiho9zQLxo0RtCuMDAyKcLo6cEltkgbQp6d1+sjjQ==", + "cpu": [ + "arm" + ], "dev": true, "license": "MIT", "optional": true, + "os": [ + "android" + ], "engines": { - "node": ">=14" + "node": "^20.19.0 || >=22.12.0" } }, "node_modules/@rolldown/binding-android-arm64": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.0.tgz", - "integrity": "sha512-9yB1l95IrJuNGDFdOYe79vdApdz6WWBCObE+rQ2LUliYUlcyFwSYIb2xb5/Ifw7dAtMy2ZqNyd8QTSOc7duAKw==", + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.6.tgz", + "integrity": "sha512-lkWU8ZJaRk9q3CIEY1Tc7vIFALp3Xw5NfGJo2hQg5oIqNgxWi1zI+IiDEK3r70BF5Dzol1tcXsnzsRc8NLhG+Q==", "cpu": [ "arm64" ], @@ -793,9 +770,9 @@ } }, "node_modules/@rolldown/binding-darwin-arm64": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.0.tgz", - "integrity": "sha512-pexNaW9ACLUOaBITOpU6qVu4VrsOFIjTv6bzgu0YUATo4eUJx0V605PxwZfndpPOn0ilqGqvGQ0M8UW0IE24jg==", + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.6.tgz", + "integrity": "sha512-dgR56NYnvAszm7Ob1B2/Vn0e8bUQYZH2UjVaMMtMVOCKFSfjhfLmuA/9+O+F+ajUdG6B/bSssrKW6JJYASa8jA==", "cpu": [ "arm64" ], @@ -810,9 +787,9 @@ } }, "node_modules/@rolldown/binding-darwin-x64": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.0.tgz", - "integrity": "sha512-NqKYaq0355ZmNMG4QGpxtEDxsc7tGDhjhCm4PpE0cwnBW+5Il95LJyq414niEiaKLVjnVHBEjSo1wngKxJNiFw==", + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.6.tgz", + "integrity": "sha512-vpVxFvUCFioJqug7OTvqptkc4yb8UX0AwfDmJpaR/0sWz+BUmqSVAf7c8JkUgnN8YLspb4a/N6NhTyMAmdyQ7Q==", "cpu": [ "x64" ], @@ -827,9 +804,9 @@ } }, "node_modules/@rolldown/binding-freebsd-x64": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.0.tgz", - "integrity": "sha512-3vPoHzh6eBTz9IbB0/qZdSr0Qeks2echn+I4cHu2joV74VriPDdldswksEDzrl1mBB+oPRi+67+3Ib59paxIPQ==", + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.6.tgz", + "integrity": "sha512-h1wG6Y6K3JlRswxsI64qQJqBAy4vrLuHgRbc8CZMGSWTOFRY6ghMApM1NKzB2I0n5xV1fjkE18SuVl2QpLeNpA==", "cpu": [ "x64" ], @@ -844,9 +821,9 @@ } }, "node_modules/@rolldown/binding-linux-arm-gnueabihf": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.0.tgz", - "integrity": "sha512-E6NNefZ1bUVmKJq2tJkf45J4Zyczj7qm9rUT7NY+Xo2474Y13qWAwc2tvBt0BAVbmtXR1llkxXg0Ou1jbDf2SQ==", + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.6.tgz", + "integrity": "sha512-tbCiqub0q2MVWJKgF5PoAlNWCtQydiOYSLIkd8sByqK/6MMYLJRcSXSYodqYtd0O+Fw7QaVmKKlS4oL94YRZ0w==", "cpu": [ "arm" ], @@ -861,13 +838,16 @@ } }, "node_modules/@rolldown/binding-linux-arm64-gnu": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.0.tgz", - "integrity": "sha512-D+TgkdgM1vu+7/Fpf8+v0ARW+RXEP9Ccazgm8zQ4JFFd9Q7SrYQ2TakU5S5ihazQDgpKyAgZDOcIFsvoHmTZ8w==", + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.6.tgz", + "integrity": "sha512-oxK9+baEBPhZG5HB4URY+uU04zJWeZlH6Tb9rB5DK4DF9XR1uXNLXt5Q5ZsugTKayNCNLhkcwz/ye74hRI98dg==", "cpu": [ "arm64" ], "dev": true, + "libc": [ + "glibc" + ], "license": "MIT", "optional": true, "os": [ @@ -878,13 +858,16 @@ } }, "node_modules/@rolldown/binding-linux-arm64-musl": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.0.tgz", - "integrity": "sha512-wUqdwJBbAv0APN87GecstdMUtLjjNTs0hBALpxETD73mccFxdmt/XeizXDtN5RAlBwNKmI+Tg+blect2G+8IeQ==", + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.6.tgz", + "integrity": "sha512-muWCk27FVBEZtv0MsK8gnfSmgczA8KQ0uRVJbTABKhkRfQc38aUrcb7fhi3BNiyseFmgcRsoMfQsSNJ+DbZdSw==", "cpu": [ "arm64" ], "dev": true, + "libc": [ + "musl" + ], "license": "MIT", "optional": true, "os": [ @@ -895,13 +878,16 @@ } }, "node_modules/@rolldown/binding-linux-ppc64-gnu": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.0.tgz", - "integrity": "sha512-9DtF35qR9/NrfhM4oxLplCzVVjE+KKm8Pjemi0i/sdhAWkUasjmSo8WTTubNJClhSHCfyk2yeyoXDQEDPtDAAw==", + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.6.tgz", + "integrity": "sha512-eWDoSfU7Co2qj3vgB3Dt4lj1mG6CoWbcJQkRMP3XJplyCMtuaq3LHvPFjS9QIPvMGWVadJC04Xiy0IdcVPtnwQ==", "cpu": [ "ppc64" ], "dev": true, + "libc": [ + "glibc" + ], "license": "MIT", "optional": true, "os": [ @@ -912,13 +898,16 @@ } }, "node_modules/@rolldown/binding-linux-s390x-gnu": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.0.tgz", - "integrity": "sha512-RzuHrBh8X8Hntd2N4VR02QGEciq/9JhcZoTpR/Cee6otRrlILGCf3cg2ygHuih+ZebUnWmMrDX6ITI85btO6rQ==", + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.6.tgz", + "integrity": "sha512-2bWNjRSIayvupRKxXUY2tWG9fYdoUlTqWywHRvE8Eq3GvuQ+f2HeIkve697fIt+IQs/PV8yFsdWuhp1aJ1PdnA==", "cpu": [ "s390x" ], "dev": true, + "libc": [ + "glibc" + ], "license": "MIT", "optional": true, "os": [ @@ -929,13 +918,16 @@ } }, "node_modules/@rolldown/binding-linux-x64-gnu": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.0.tgz", - "integrity": "sha512-MK7L0018jjh1jR3mh21G2j1zAVcpscJBlPo2z19pRjv2XOYGRhaV4LyiD8HO6nCDdZln9IFgCMIV5yt4E3klGQ==", + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.6.tgz", + "integrity": "sha512-KekI0gS0wLxe1UBSQSjenBVwou/JkcQPDzBPICGZjxUv9k3RteHDPBQaiOicZUFKRIH2wKEimGwVpnJsbPzu7w==", "cpu": [ "x64" ], "dev": true, + "libc": [ + "glibc" + ], "license": "MIT", "optional": true, "os": [ @@ -946,13 +938,16 @@ } }, "node_modules/@rolldown/binding-linux-x64-musl": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.0.tgz", - "integrity": "sha512-gyrxLQ9NfGb/9LoVnC4kb9miUghw1mghnkfYvNHSnVIXriabnfgGPUP4RLcJm87q3KgYz4FYUG8IDiWUT+CpSw==", + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.6.tgz", + "integrity": "sha512-TvtPnfVr+HtyGiDmPK4VWmlNm7QhNNAcK5Q9A7aOXsI8545yCyaoMaicXrFZ72JzeYjaUVk7yT243zT0jzjFKQ==", "cpu": [ "x64" ], "dev": true, + "libc": [ + "musl" + ], "license": "MIT", "optional": true, "os": [ @@ -963,9 +958,9 @@ } }, "node_modules/@rolldown/binding-openharmony-arm64": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.0.tgz", - "integrity": "sha512-/6VFMQGRmrhP77KXDC+StIxGzcNp5JOIyYtw0CQ8gPlzhpiIRucYfoM5FaFamHd5BJYIdH86yfP46l1p3WdrFA==", + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.6.tgz", + "integrity": "sha512-iOo0VEay2XFhaCcH0sps5XIimkSuOnNaZrf6+ZkoSOQBJPKNU48RkmJv0/lSpipexu5P+ouFgafe5IGr/DiQfg==", "cpu": [ "arm64" ], @@ -979,63 +974,10 @@ "node": "^20.19.0 || >=22.12.0" } }, - "node_modules/@rolldown/binding-wasm32-wasi": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.2.0.tgz", - "integrity": "sha512-rwdbUL465kisF24WEJLvP3JrEG6E5GRuIHt5wpMwHGERtHe4Wm2CIvtf5gTBgr2tGOHKh5NdKEAFS2VkOPE91g==", - "cpu": [ - "wasm32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@emnapi/core": "1.11.2", - "@emnapi/runtime": "1.11.2", - "@napi-rs/wasm-runtime": "^1.1.6" - }, - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-wasm32-wasi/node_modules/@emnapi/core": { - "version": "1.11.2", - "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.2.tgz", - "integrity": "sha512-TC8MkTuZUtcTSiFeuC0ksCh9QIJ5+F21MvZ4Wn4ORfYaFJ/0dsiudv5tVkejgwZlwQ39jL9WWDe2lz8x0WglOA==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@emnapi/wasi-threads": "1.2.2", - "tslib": "^2.4.0" - } - }, - "node_modules/@rolldown/binding-wasm32-wasi/node_modules/@emnapi/runtime": { - "version": "1.11.2", - "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.2.tgz", - "integrity": "sha512-kyOl3X0DuTiT1h2ft8r2fYO8JYtU9a9Xis/zBSiGArNaagCOWx90N1k2wxp18czFDH+OgcWGb5ZP/XMt3dcyPA==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "tslib": "^2.4.0" - } - }, - "node_modules/@rolldown/binding-wasm32-wasi/node_modules/@emnapi/wasi-threads": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.2.tgz", - "integrity": "sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "tslib": "^2.4.0" - } - }, "node_modules/@rolldown/binding-win32-arm64-msvc": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.0.tgz", - "integrity": "sha512-+5suHwRiKGmhwyUaNT8a5QbrBvLFh2DbO910TEmGRH1aSxwrCezodvGQnulv4uiWEIv1Kq4ypRsJ5+O+ry1DiA==", + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.6.tgz", + "integrity": "sha512-y5NTmmasMS455JlOCO4ZM9krIchv3Mvm1crL1iUPGOPgEzSkves9n0SdC5Sjz6+qWDFhd8/JpfWMH8NSWNHe+A==", "cpu": [ "arm64" ], @@ -1050,9 +992,9 @@ } }, "node_modules/@rolldown/binding-win32-x64-msvc": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.0.tgz", - "integrity": "sha512-WfFv6/qGufotqBSBzBYwgpCkJBk8Nj7697LL9vTz/XWc67e0r3oewu8iMRwQj3AUL45GVD7wVsPjCsAAtW66Wg==", + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.6.tgz", + "integrity": "sha512-np8iZSLfXlAD4kWhiyq/u0Yt8oZDtRQ8lGhQaCXo2rl37KNjeU0GjJuwr4P3oeZ++ROfofsKNBqR5LTO8aXyWQ==", "cpu": [ "x64" ], @@ -1073,27 +1015,16 @@ "dev": true, "license": "MIT" }, - "node_modules/@tybys/wasm-util": { - "version": "0.10.3", - "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.3.tgz", - "integrity": "sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "tslib": "^2.4.0" - } - }, "node_modules/@types/emscripten": { - "version": "1.41.5", - "resolved": "https://registry.npmjs.org/@types/emscripten/-/emscripten-1.41.5.tgz", - "integrity": "sha512-cMQm7pxu6BxtHyqJ7mQZ2kXWV5SLmugybFdHCBbJ5eHzOo6VhBckEgAT3//rP5FwPHNPeEiq4SmQ5ucBwsOo4Q==", + "version": "1.41.6", + "resolved": "https://registry.npmjs.org/@types/emscripten/-/emscripten-1.41.6.tgz", + "integrity": "sha512-uN+9i8bFT5CUcZfyIEYDrSueACEyKGbUs5kC/72DGlZZoinh84sJfVV0i8UOJD1asdzkvLPBRrKs41kZ8MdEXg==", "license": "MIT" }, "node_modules/@types/node": { - "version": "26.1.2", - "resolved": "https://registry.npmjs.org/@types/node/-/node-26.1.2.tgz", - "integrity": "sha512-Vu4a5UFA9rIIFJ7rB/Vaafh9lrCQszopTCx6KjFboXTGQbPNasehVR5TEiithSDGyd1DEiUByggTZsg8jukeIg==", + "version": "26.4.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.4.1.tgz", + "integrity": "sha512-k97ENvZWtvA6yqz5/FS6a7duDgOPEeOQOc2iKS/nY6mX6qJUKtLnWzQS+Xj6tXweyj6ZcTAK2Qecetnvi9nCLA==", "dev": true, "license": "MIT", "dependencies": { @@ -1440,35 +1371,6 @@ "node": ">=16.20.0" } }, - "node_modules/ansi-regex": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.1.0.tgz", - "integrity": "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/ansi-regex?sponsor=1" - } - }, - "node_modules/ansi-styles": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "dev": true, - "license": "MIT", - "dependencies": { - "color-convert": "^2.0.1" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, "node_modules/argparse": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", @@ -1477,20 +1379,26 @@ "license": "Python-2.0" }, "node_modules/balanced-match": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", - "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", "dev": true, - "license": "MIT" + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } }, "node_modules/brace-expansion": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.3.tgz", - "integrity": "sha512-DRdx5neNsG/QXbniLFWi2YmC/68oeOOmKz6zOjVk6ZS1ZLXgLIKqVEc6hWsmkjBbgii0SwaBTcJ5XKj5gzY/4A==", + "version": "5.0.9", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.9.tgz", + "integrity": "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==", "dev": true, "license": "MIT", "dependencies": { - "balanced-match": "^1.0.0" + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" } }, "node_modules/browser-stdout": { @@ -1500,19 +1408,6 @@ "dev": true, "license": "ISC" }, - "node_modules/camelcase": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz", - "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/chai": { "version": "6.2.2", "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz", @@ -1536,23 +1431,6 @@ "chai": ">= 2.1.2 < 7" } }, - "node_modules/chalk": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", - "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-styles": "^4.1.0", - "supports-color": "^7.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/chalk?sponsor=1" - } - }, "node_modules/check-error": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.1.tgz", @@ -1564,134 +1442,21 @@ } }, "node_modules/chokidar": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz", - "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-5.0.0.tgz", + "integrity": "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==", "dev": true, "license": "MIT", "dependencies": { - "readdirp": "^4.0.1" + "readdirp": "^5.0.0" }, "engines": { - "node": ">= 14.16.0" + "node": ">= 20.19.0" }, "funding": { "url": "https://paulmillr.com/funding/" } }, - "node_modules/cliui": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", - "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", - "dev": true, - "license": "ISC", - "dependencies": { - "string-width": "^4.2.0", - "strip-ansi": "^6.0.1", - "wrap-ansi": "^7.0.0" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/cliui/node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/cliui/node_modules/emoji-regex": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "dev": true, - "license": "MIT" - }, - "node_modules/cliui/node_modules/string-width": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "dev": true, - "license": "MIT", - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/cliui/node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/cliui/node_modules/wrap-ansi": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", - "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-styles": "^4.0.0", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/wrap-ansi?sponsor=1" - } - }, - "node_modules/color-convert": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "color-name": "~1.1.4" - }, - "engines": { - "node": ">=7.0.0" - } - }, - "node_modules/color-name": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "dev": true, - "license": "MIT" - }, - "node_modules/cross-spawn": { - "version": "7.0.6", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", - "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", - "dev": true, - "license": "MIT", - "dependencies": { - "path-key": "^3.1.0", - "shebang-command": "^2.0.0", - "which": "^2.0.1" - }, - "engines": { - "node": ">= 8" - } - }, "node_modules/debug": { "version": "4.4.0", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz", @@ -1710,66 +1475,16 @@ } } }, - "node_modules/decamelize": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-4.0.0.tgz", - "integrity": "sha512-9iE1PgSik9HeIIw2JO94IidnE3eBoQrFJ3w7sFuzSX4DpmZ3v5sZpUiV5Swcf6mQEF+Y0ru8Neo+p+nyh2J+hQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/diff": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/diff/-/diff-7.0.0.tgz", - "integrity": "sha512-PJWHUb1RFevKCwaFA9RlG5tCd+FO5iRh9A8HEtkmBH2Li03iJriB6m6JIN4rGz3K3JLawI7/veA1xzRKP6ISBw==", + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/diff/-/diff-9.0.0.tgz", + "integrity": "sha512-svtcdpS8CgJyqAjEQIXdb3OjhFVVYjzGAPO8WGCmRbrml64SPw/jJD4GoE98aR7r25A0XcgrK3F02yw9R/vhQw==", "dev": true, "license": "BSD-3-Clause", "engines": { "node": ">=0.3.1" } }, - "node_modules/eastasianwidth": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", - "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", - "dev": true, - "license": "MIT" - }, - "node_modules/emoji-regex": { - "version": "9.2.2", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", - "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", - "dev": true, - "license": "MIT" - }, - "node_modules/escalade": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", - "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/escape-string-regexp": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", - "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/fengari": { "version": "0.1.5", "resolved": "https://registry.npmjs.org/fengari/-/fengari-0.1.5.tgz", @@ -1799,33 +1514,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/flat": { - "version": "5.0.2", - "resolved": "https://registry.npmjs.org/flat/-/flat-5.0.2.tgz", - "integrity": "sha512-b6suED+5/3rTpUBdG1gupIl8MPFCAMA0QXwmljLhvCUKcUvdE4gWky9zpuGCcXHOsz4J9wPGNWq6OKpmIzz3hQ==", - "dev": true, - "license": "BSD-3-Clause", - "bin": { - "flat": "cli.js" - } - }, - "node_modules/foreground-child": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.0.tgz", - "integrity": "sha512-Ld2g8rrAyMYFXBhEqMz8ZAHBi4J4uS1i/CxGMDnjyFWddMXLVcDp051DZfu+t7+ab7Wv6SMqpWmyFIj5UbfFvg==", - "dev": true, - "license": "ISC", - "dependencies": { - "cross-spawn": "^7.0.0", - "signal-exit": "^4.0.1" - }, - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, "node_modules/fsevents": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", @@ -1841,33 +1529,19 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, - "node_modules/get-caller-file": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", - "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", - "dev": true, - "license": "ISC", - "engines": { - "node": "6.* || 8.* || >= 10.*" - } - }, "node_modules/glob": { - "version": "10.5.0", - "resolved": "https://registry.npmjs.org/glob/-/glob-10.5.0.tgz", - "integrity": "sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==", - "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", + "version": "13.0.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", + "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==", "dev": true, - "license": "ISC", + "license": "BlueOak-1.0.0", "dependencies": { - "foreground-child": "^3.1.0", - "jackspeak": "^3.1.2", - "minimatch": "^9.0.4", - "minipass": "^7.1.2", - "package-json-from-dist": "^1.0.0", - "path-scurry": "^1.11.1" + "minimatch": "^10.2.2", + "minipass": "^7.1.3", + "path-scurry": "^2.0.2" }, - "bin": { - "glob": "dist/esm/bin.mjs" + "engines": { + "node": "18 || 20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" @@ -1883,26 +1557,6 @@ "node": ">=8" } }, - "node_modules/he": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz", - "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==", - "dev": true, - "license": "MIT", - "bin": { - "he": "bin/he" - } - }, - "node_modules/is-fullwidth-code-point": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/is-path-inside": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.3.tgz", @@ -1913,16 +1567,6 @@ "node": ">=8" } }, - "node_modules/is-plain-obj": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-2.1.0.tgz", - "integrity": "sha512-YWnfyRwxL/+SsrWYfOpUtz5b3YD+nyfkHvjbcanzk8zgyO4ASD67uVMRt8k5bM4lLMDnXfriRhOpemw+NfT1eA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/is-unicode-supported": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz", @@ -1936,33 +1580,10 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/isexe": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", - "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", - "dev": true, - "license": "ISC" - }, - "node_modules/jackspeak": { - "version": "3.4.3", - "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz", - "integrity": "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "@isaacs/cliui": "^8.0.2" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - }, - "optionalDependencies": { - "@pkgjs/parseargs": "^0.11.0" - } - }, "node_modules/js-yaml": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.0.tgz", - "integrity": "sha512-1td788aAnnZ5qs7V2QIRl1owjtYpbKt749Y3xauqQgwIIGF/xXWz1wMTEBx5O3LK3lXLVuqXPdPxj2BoFHaW9Q==", + "version": "5.4.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-5.4.1.tgz", + "integrity": "sha512-28R/k+NAjeuf7+CKlTxWZVExJGwVVLwY06DgEnOMz2gEpfNkDcD7QvyiVPT0xy0XXhU8vHsd4Ot42OOPdJG7dQ==", "dev": true, "funding": [ { @@ -1979,7 +1600,7 @@ "argparse": "^2.0.1" }, "bin": { - "js-yaml": "bin/js-yaml.js" + "js-yaml": "bin/js-yaml.mjs" } }, "node_modules/locate-path": { @@ -1998,91 +1619,71 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/log-symbols": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-4.1.0.tgz", - "integrity": "sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==", + "node_modules/lru-cache": { + "version": "11.5.2", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.2.tgz", + "integrity": "sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g==", "dev": true, - "license": "MIT", - "dependencies": { - "chalk": "^4.1.0", - "is-unicode-supported": "^0.1.0" - }, + "license": "BlueOak-1.0.0", "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "node": "20 || >=22" } }, - "node_modules/lru-cache": { - "version": "10.4.3", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", - "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", - "dev": true, - "license": "ISC" - }, "node_modules/minimatch": { - "version": "9.0.9", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz", - "integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==", + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", "dev": true, - "license": "ISC", + "license": "BlueOak-1.0.0", "dependencies": { - "brace-expansion": "^2.0.2" + "brace-expansion": "^5.0.8" }, "engines": { - "node": ">=16 || 14 >=14.17" + "node": "18 || 20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" } }, "node_modules/minipass": { - "version": "7.1.2", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", - "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", + "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", "dev": true, - "license": "ISC", + "license": "BlueOak-1.0.0", "engines": { "node": ">=16 || 14 >=14.17" } }, "node_modules/mocha": { - "version": "11.7.6", - "resolved": "https://registry.npmjs.org/mocha/-/mocha-11.7.6.tgz", - "integrity": "sha512-nS9xOGbw2I3cjCpxwZAEJ9xK9lmJ08vEkQvLtz4du9ZrF9UrjRpeJGiIgl2Z+Qs++pmB4ecDe48Fwsh+j+j7xA==", + "version": "12.0.0", + "resolved": "https://registry.npmjs.org/mocha/-/mocha-12.0.0.tgz", + "integrity": "sha512-NYNh5IFt6WYqm9bi4601m7vix8MZdXC0DwS4gY6WhXO2RgJWhivhISVmq1oklCif18OSI9l+vx5Mdm5oh1XGiQ==", "dev": true, "license": "MIT", "dependencies": { "browser-stdout": "^1.3.1", - "chokidar": "^4.0.1", + "chokidar": "^5.0.0", "debug": "^4.3.5", - "diff": "^7.0.0", - "escape-string-regexp": "^4.0.0", + "diff": "^9.0.0", "find-up": "^5.0.0", - "glob": "^10.4.5", - "he": "^1.2.0", + "glob": "^13.0.0", "is-path-inside": "^3.0.3", - "js-yaml": "^4.1.0", - "log-symbols": "^4.1.0", - "minimatch": "^9.0.5", + "is-unicode-supported": "^0.1.0", + "js-yaml": "^5.0.0", + "minimatch": "^10.2.2", "ms": "^2.1.3", "picocolors": "^1.1.1", - "serialize-javascript": "^6.0.2", - "strip-json-comments": "^3.1.1", + "serialize-javascript": "^7.0.2", + "strip-json-comments": "^5.0.3", "supports-color": "^8.1.1", - "workerpool": "^9.2.0", - "yargs": "^17.7.2", - "yargs-parser": "^21.1.1", - "yargs-unparser": "^2.0.0" + "workerpool": "^10.0.0" }, "bin": { - "_mocha": "bin/_mocha", "mocha": "bin/mocha.js" }, "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + "node": "^20.19.0 || >=22.12.0" } }, "node_modules/mocha/node_modules/supports-color": { @@ -2109,9 +1710,9 @@ "license": "MIT" }, "node_modules/oxfmt": { - "version": "0.61.0", - "resolved": "https://registry.npmjs.org/oxfmt/-/oxfmt-0.61.0.tgz", - "integrity": "sha512-DxdHBEMYpcEnHoUHjjOigUqV2TYKsvxLwUPXnVYBjgFdqrcQ/91OtwubtZ2PUodCs3sStI8R5Qw3fKNGK4e8wQ==", + "version": "0.66.0", + "resolved": "https://registry.npmjs.org/oxfmt/-/oxfmt-0.66.0.tgz", + "integrity": "sha512-FfvqR8RFtV6JJpRrpkfqyVCQ7HDvZ/VriWFx7veftCgL1B5ZO9qNr+1rvPieycMQnNfVG0PWyJQiy7p0hq1I5w==", "dev": true, "license": "MIT", "dependencies": { @@ -2124,28 +1725,28 @@ "node": "^20.19.0 || >=22.12.0" }, "funding": { - "url": "https://github.com/sponsors/Boshen" + "url": "https://github.com/sponsors/oxc-project" }, "optionalDependencies": { - "@oxfmt/binding-android-arm-eabi": "0.61.0", - "@oxfmt/binding-android-arm64": "0.61.0", - "@oxfmt/binding-darwin-arm64": "0.61.0", - "@oxfmt/binding-darwin-x64": "0.61.0", - "@oxfmt/binding-freebsd-x64": "0.61.0", - "@oxfmt/binding-linux-arm-gnueabihf": "0.61.0", - "@oxfmt/binding-linux-arm-musleabihf": "0.61.0", - "@oxfmt/binding-linux-arm64-gnu": "0.61.0", - "@oxfmt/binding-linux-arm64-musl": "0.61.0", - "@oxfmt/binding-linux-ppc64-gnu": "0.61.0", - "@oxfmt/binding-linux-riscv64-gnu": "0.61.0", - "@oxfmt/binding-linux-riscv64-musl": "0.61.0", - "@oxfmt/binding-linux-s390x-gnu": "0.61.0", - "@oxfmt/binding-linux-x64-gnu": "0.61.0", - "@oxfmt/binding-linux-x64-musl": "0.61.0", - "@oxfmt/binding-openharmony-arm64": "0.61.0", - "@oxfmt/binding-win32-arm64-msvc": "0.61.0", - "@oxfmt/binding-win32-ia32-msvc": "0.61.0", - "@oxfmt/binding-win32-x64-msvc": "0.61.0" + "@oxfmt/binding-android-arm-eabi": "0.66.0", + "@oxfmt/binding-android-arm64": "0.66.0", + "@oxfmt/binding-darwin-arm64": "0.66.0", + "@oxfmt/binding-darwin-x64": "0.66.0", + "@oxfmt/binding-freebsd-x64": "0.66.0", + "@oxfmt/binding-linux-arm-gnueabihf": "0.66.0", + "@oxfmt/binding-linux-arm-musleabihf": "0.66.0", + "@oxfmt/binding-linux-arm64-gnu": "0.66.0", + "@oxfmt/binding-linux-arm64-musl": "0.66.0", + "@oxfmt/binding-linux-ppc64-gnu": "0.66.0", + "@oxfmt/binding-linux-riscv64-gnu": "0.66.0", + "@oxfmt/binding-linux-riscv64-musl": "0.66.0", + "@oxfmt/binding-linux-s390x-gnu": "0.66.0", + "@oxfmt/binding-linux-x64-gnu": "0.66.0", + "@oxfmt/binding-linux-x64-musl": "0.66.0", + "@oxfmt/binding-openharmony-arm64": "0.66.0", + "@oxfmt/binding-win32-arm64-msvc": "0.66.0", + "@oxfmt/binding-win32-ia32-msvc": "0.66.0", + "@oxfmt/binding-win32-x64-msvc": "0.66.0" }, "peerDependencies": { "svelte": "^5.0.0", @@ -2161,9 +1762,9 @@ } }, "node_modules/oxlint": { - "version": "1.76.0", - "resolved": "https://registry.npmjs.org/oxlint/-/oxlint-1.76.0.tgz", - "integrity": "sha512-6QoFioEU4fNdiUx/2Eo6TRd6NG7H7njnRCz8rhB66cZmMHDTqcm1Rjvl8Wry+ZTQMBAmyb4Mlf62Mk5X+eHSOw==", + "version": "1.81.0", + "resolved": "https://registry.npmjs.org/oxlint/-/oxlint-1.81.0.tgz", + "integrity": "sha512-HyrJYqeoOCL0iqaLEzGewGT48ZX99P3hxYh8udAF9RGGIghSamkXE4ClUyBpEDNqasamThgmlPbuMOe7SAZmHg==", "dev": true, "license": "MIT", "bin": { @@ -2173,28 +1774,28 @@ "node": "^20.19.0 || >=22.12.0" }, "funding": { - "url": "https://github.com/sponsors/Boshen" + "url": "https://github.com/sponsors/oxc-project" }, "optionalDependencies": { - "@oxlint/binding-android-arm-eabi": "1.76.0", - "@oxlint/binding-android-arm64": "1.76.0", - "@oxlint/binding-darwin-arm64": "1.76.0", - "@oxlint/binding-darwin-x64": "1.76.0", - "@oxlint/binding-freebsd-x64": "1.76.0", - "@oxlint/binding-linux-arm-gnueabihf": "1.76.0", - "@oxlint/binding-linux-arm-musleabihf": "1.76.0", - "@oxlint/binding-linux-arm64-gnu": "1.76.0", - "@oxlint/binding-linux-arm64-musl": "1.76.0", - "@oxlint/binding-linux-ppc64-gnu": "1.76.0", - "@oxlint/binding-linux-riscv64-gnu": "1.76.0", - "@oxlint/binding-linux-riscv64-musl": "1.76.0", - "@oxlint/binding-linux-s390x-gnu": "1.76.0", - "@oxlint/binding-linux-x64-gnu": "1.76.0", - "@oxlint/binding-linux-x64-musl": "1.76.0", - "@oxlint/binding-openharmony-arm64": "1.76.0", - "@oxlint/binding-win32-arm64-msvc": "1.76.0", - "@oxlint/binding-win32-ia32-msvc": "1.76.0", - "@oxlint/binding-win32-x64-msvc": "1.76.0" + "@oxlint/binding-android-arm-eabi": "1.81.0", + "@oxlint/binding-android-arm64": "1.81.0", + "@oxlint/binding-darwin-arm64": "1.81.0", + "@oxlint/binding-darwin-x64": "1.81.0", + "@oxlint/binding-freebsd-x64": "1.81.0", + "@oxlint/binding-linux-arm-gnueabihf": "1.81.0", + "@oxlint/binding-linux-arm-musleabihf": "1.81.0", + "@oxlint/binding-linux-arm64-gnu": "1.81.0", + "@oxlint/binding-linux-arm64-musl": "1.81.0", + "@oxlint/binding-linux-ppc64-gnu": "1.81.0", + "@oxlint/binding-linux-riscv64-gnu": "1.81.0", + "@oxlint/binding-linux-riscv64-musl": "1.81.0", + "@oxlint/binding-linux-s390x-gnu": "1.81.0", + "@oxlint/binding-linux-x64-gnu": "1.81.0", + "@oxlint/binding-linux-x64-musl": "1.81.0", + "@oxlint/binding-openharmony-arm64": "1.81.0", + "@oxlint/binding-win32-arm64-msvc": "1.81.0", + "@oxlint/binding-win32-ia32-msvc": "1.81.0", + "@oxlint/binding-win32-x64-msvc": "1.81.0" }, "peerDependencies": { "oxlint-tsgolint": ">=7.0.2001", @@ -2241,13 +1842,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/package-json-from-dist": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz", - "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==", - "dev": true, - "license": "BlueOak-1.0.0" - }, "node_modules/path-exists": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", @@ -2258,28 +1852,18 @@ "node": ">=8" } }, - "node_modules/path-key": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", - "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/path-scurry": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz", - "integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==", + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz", + "integrity": "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==", "dev": true, "license": "BlueOak-1.0.0", "dependencies": { - "lru-cache": "^10.2.0", - "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" + "lru-cache": "^11.0.0", + "minipass": "^7.1.2" }, "engines": { - "node": ">=16 || 14 >=14.18" + "node": "18 || 20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" @@ -2293,13 +1877,13 @@ "license": "ISC" }, "node_modules/playwright": { - "version": "1.62.0", - "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.62.0.tgz", - "integrity": "sha512-Z14dG305dgaLu6foB1TXQagFiW8JfSUIUaUuPaKQ6NtBPKF1P/qXcqfh6c6K/icPqdy37JmjbiBXf6JNg6Sylw==", + "version": "1.62.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.62.1.tgz", + "integrity": "sha512-0M+L3LAD8/nm554LOla9Ayx0j0tmFZ0FBcoQ7F1VuVHpM/XpiC8RcDzBQB8W5+hA8L22THxELzeF+2WcUzvcLg==", "dev": true, "license": "Apache-2.0", "dependencies": { - "playwright-core": "1.62.0" + "playwright-core": "1.62.1" }, "bin": { "playwright": "cli.js" @@ -2312,9 +1896,9 @@ } }, "node_modules/playwright-core": { - "version": "1.62.0", - "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.62.0.tgz", - "integrity": "sha512-nsNRyq0r2zsG8AcRHWknc9QRA5XCueC7gWMrs+Gx2tlZn9hcl8zudfh00lhJPY1DE7NmZ6bDsT9g2yey8mXljA==", + "version": "1.62.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.62.1.tgz", + "integrity": "sha512-wPYSwEBJY9GHraISXqyqtx0na0LpO3XEX7jNDhntbex7tzUS7kLnZsOlFruFJB4Hi/rhDMjXGqHewDZ68nYZVw==", "dev": true, "license": "Apache-2.0", "bin": { @@ -2324,24 +1908,14 @@ "node": ">=20" } }, - "node_modules/randombytes": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", - "integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "safe-buffer": "^5.1.0" - } - }, "node_modules/readdirp": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz", - "integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==", + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-5.1.1.tgz", + "integrity": "sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA==", "dev": true, "license": "MIT", "engines": { - "node": ">= 14.18.0" + "node": ">= 20.19.0" }, "funding": { "type": "individual", @@ -2358,24 +1932,14 @@ "node": ">= 0.8.0" } }, - "node_modules/require-directory": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", - "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/rolldown": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.0.tgz", - "integrity": "sha512-u7tgm5l4Yw1iTqUL4EcYOAt7fFvCgQMLeidrnD4GALlC6aOznCjezYajgxeyKw27u0Q5N7fwgCzjVyPIWzwuBA==", + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.6.tgz", + "integrity": "sha512-vMM4q3aixf46GiF1Kok8jDPFsEpXgFWGjUHXNkNHNm+Y2adXAG2dbX91jkti3i0ZRsOlcmbuzAz1poObSHCmUA==", "dev": true, "license": "MIT", "dependencies": { - "@oxc-project/types": "=0.140.0", + "@oxc-project/types": "=0.147.0", "@rolldown/pluginutils": "^1.0.0" }, "bin": { @@ -2385,88 +1949,31 @@ "node": "^20.19.0 || >=22.12.0" }, "optionalDependencies": { - "@rolldown/binding-android-arm64": "1.2.0", - "@rolldown/binding-darwin-arm64": "1.2.0", - "@rolldown/binding-darwin-x64": "1.2.0", - "@rolldown/binding-freebsd-x64": "1.2.0", - "@rolldown/binding-linux-arm-gnueabihf": "1.2.0", - "@rolldown/binding-linux-arm64-gnu": "1.2.0", - "@rolldown/binding-linux-arm64-musl": "1.2.0", - "@rolldown/binding-linux-ppc64-gnu": "1.2.0", - "@rolldown/binding-linux-s390x-gnu": "1.2.0", - "@rolldown/binding-linux-x64-gnu": "1.2.0", - "@rolldown/binding-linux-x64-musl": "1.2.0", - "@rolldown/binding-openharmony-arm64": "1.2.0", - "@rolldown/binding-wasm32-wasi": "1.2.0", - "@rolldown/binding-win32-arm64-msvc": "1.2.0", - "@rolldown/binding-win32-x64-msvc": "1.2.0" - } - }, - "node_modules/safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" + "@rolldown/binding-android-arm-eabi": "1.2.6", + "@rolldown/binding-android-arm64": "1.2.6", + "@rolldown/binding-darwin-arm64": "1.2.6", + "@rolldown/binding-darwin-x64": "1.2.6", + "@rolldown/binding-freebsd-x64": "1.2.6", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.6", + "@rolldown/binding-linux-arm64-gnu": "1.2.6", + "@rolldown/binding-linux-arm64-musl": "1.2.6", + "@rolldown/binding-linux-ppc64-gnu": "1.2.6", + "@rolldown/binding-linux-s390x-gnu": "1.2.6", + "@rolldown/binding-linux-x64-gnu": "1.2.6", + "@rolldown/binding-linux-x64-musl": "1.2.6", + "@rolldown/binding-openharmony-arm64": "1.2.6", + "@rolldown/binding-win32-arm64-msvc": "1.2.6", + "@rolldown/binding-win32-x64-msvc": "1.2.6" + } }, "node_modules/serialize-javascript": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.2.tgz", - "integrity": "sha512-Saa1xPByTTq2gdeFZYLLo+RFE35NHZkAbqZeWNd3BpzppeVisAqpDjcp8dyf6uIvEqJRd46jemmyA4iFIeVk8g==", + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-7.1.1.tgz", + "integrity": "sha512-k3CMsaIvvdSwm8oLB4MXSl0wH2/cwlH7xGcnRd2DaeRmBkbzYmyT8j0tsX60DwD1eRwHTpNpH8ljKu9oUT1MeQ==", "dev": true, "license": "BSD-3-Clause", - "dependencies": { - "randombytes": "^2.1.0" - } - }, - "node_modules/shebang-command": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", - "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", - "dev": true, - "license": "MIT", - "dependencies": { - "shebang-regex": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/shebang-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", - "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", - "dev": true, - "license": "MIT", "engines": { - "node": ">=8" - } - }, - "node_modules/signal-exit": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", - "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" + "node": ">=20.0.0" } }, "node_modules/sprintf-js": { @@ -2476,136 +1983,19 @@ "dev": true, "license": "BSD-3-Clause" }, - "node_modules/string-width": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", - "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", - "dev": true, - "license": "MIT", - "dependencies": { - "eastasianwidth": "^0.2.0", - "emoji-regex": "^9.2.2", - "strip-ansi": "^7.0.1" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/string-width-cjs": { - "name": "string-width", - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "dev": true, - "license": "MIT", - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/string-width-cjs/node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/string-width-cjs/node_modules/emoji-regex": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "dev": true, - "license": "MIT" - }, - "node_modules/string-width-cjs/node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/strip-ansi": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", - "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-regex": "^6.0.1" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/strip-ansi?sponsor=1" - } - }, - "node_modules/strip-ansi-cjs": { - "name": "strip-ansi", - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/strip-ansi-cjs/node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/strip-json-comments": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", - "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-5.0.3.tgz", + "integrity": "sha512-1tB5mhVo7U+ETBKNf92xT4hrQa3pm0MZ0PQvuDnWgAAGHDsfp4lPSpiS6psrSiet87wyGPh9ft6wmhOMQ0hDiw==", "dev": true, "license": "MIT", "engines": { - "node": ">=8" + "node": ">=14.16" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/supports-color": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", - "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", - "dev": true, - "license": "MIT", - "dependencies": { - "has-flag": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/tinypool": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-2.1.0.tgz", @@ -2675,224 +2065,13 @@ "dev": true, "license": "MIT" }, - "node_modules/which": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", - "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", - "dev": true, - "license": "ISC", - "dependencies": { - "isexe": "^2.0.0" - }, - "bin": { - "node-which": "bin/node-which" - }, - "engines": { - "node": ">= 8" - } - }, "node_modules/workerpool": { - "version": "9.3.4", - "resolved": "https://registry.npmjs.org/workerpool/-/workerpool-9.3.4.tgz", - "integrity": "sha512-TmPRQYYSAnnDiEB0P/Ytip7bFGvqnSU6I2BcuSw7Hx+JSg/DsUi5ebYfc8GYaSdpuvOcEs6dXxPurOYpe9QFwg==", + "version": "10.0.3", + "resolved": "https://registry.npmjs.org/workerpool/-/workerpool-10.0.3.tgz", + "integrity": "sha512-6z2Iis68Wqth93/G/wJP9u+R3O+d2XTlgWChGCwuT1qLbBsOYueGRZuJ++v3mtDP5KjYdy+WzvWC+VWETSVXJA==", "dev": true, "license": "Apache-2.0" }, - "node_modules/wrap-ansi": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", - "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-styles": "^6.1.0", - "string-width": "^5.0.1", - "strip-ansi": "^7.0.1" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/wrap-ansi?sponsor=1" - } - }, - "node_modules/wrap-ansi-cjs": { - "name": "wrap-ansi", - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", - "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-styles": "^4.0.0", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/wrap-ansi?sponsor=1" - } - }, - "node_modules/wrap-ansi-cjs/node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/wrap-ansi-cjs/node_modules/emoji-regex": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "dev": true, - "license": "MIT" - }, - "node_modules/wrap-ansi-cjs/node_modules/string-width": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "dev": true, - "license": "MIT", - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/wrap-ansi-cjs/node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/wrap-ansi/node_modules/ansi-styles": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", - "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "node_modules/y18n": { - "version": "5.0.8", - "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", - "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=10" - } - }, - "node_modules/yargs": { - "version": "17.7.2", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", - "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", - "dev": true, - "license": "MIT", - "dependencies": { - "cliui": "^8.0.1", - "escalade": "^3.1.1", - "get-caller-file": "^2.0.5", - "require-directory": "^2.1.1", - "string-width": "^4.2.3", - "y18n": "^5.0.5", - "yargs-parser": "^21.1.1" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/yargs-parser": { - "version": "21.1.1", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", - "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=12" - } - }, - "node_modules/yargs-unparser": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/yargs-unparser/-/yargs-unparser-2.0.0.tgz", - "integrity": "sha512-7pRTIA9Qc1caZ0bZ6RYRGbHJthJWuakf+WmHK0rVeLkNrrGhfoabBNdue6kdINI6r4if7ocq9aD/n7xwKOdzOA==", - "dev": true, - "license": "MIT", - "dependencies": { - "camelcase": "^6.0.0", - "decamelize": "^4.0.0", - "flat": "^5.0.2", - "is-plain-obj": "^2.1.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/yargs/node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/yargs/node_modules/emoji-regex": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "dev": true, - "license": "MIT" - }, - "node_modules/yargs/node_modules/string-width": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "dev": true, - "license": "MIT", - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/yargs/node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/yocto-queue": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", diff --git a/package.json b/package.json index c997139..c809188 100755 --- a/package.json +++ b/package.json @@ -69,15 +69,15 @@ "chai": "6.2.2", "chai-as-promised": "8.0.2", "fengari": "0.1.5", - "mocha": "11.7.6", - "oxfmt": "0.61.0", - "oxlint": "1.76.0", - "playwright": "1.62.0", - "rolldown": "1.2.0", + "mocha": "12.0.0", + "oxfmt": "0.66.0", + "oxlint": "1.81.0", + "playwright": "1.62.1", + "rolldown": "1.2.6", "tslib": "2.8.1", "typescript": "7.0.2" }, "dependencies": { - "@types/emscripten": "1.41.5" + "@types/emscripten": "1.41.6" } } From c37067024e89a96e9de2dec0a490cf2a7605006e Mon Sep 17 00:00:00 2001 From: ceifa Date: Tue, 1 Sep 2026 21:02:58 -0300 Subject: [PATCH 55/83] add gc --- src/gc.ts | 112 ++++++++++++++++++++++++++++++++++++++++++++ src/index.ts | 4 ++ src/module.ts | 15 +++++- src/state.ts | 6 ++- src/thread.ts | 2 +- src/types.ts | 39 +++++++++++++++ test/state.test.js | 99 +++++++++++++++++++++++++++++++++++++++ utils/build-wasm.sh | 3 +- 8 files changed, 276 insertions(+), 4 deletions(-) create mode 100644 src/gc.ts diff --git a/src/gc.ts b/src/gc.ts new file mode 100644 index 0000000..569e634 --- /dev/null +++ b/src/gc.ts @@ -0,0 +1,112 @@ +import type LuaState from './state' +import { LUA_GC_PARAMS, type LuaGcMode, type LuaGcOptions, type LuaGcParam, LuaGcWhat } from './types' + +/** The state's garbage collector, as `state.gc`: what `collectgarbage` offers, callable from JS. */ +export default class LuaGarbageCollector { + public constructor( + private readonly state: LuaState, + options?: LuaGcOptions, + ) { + if (options?.mode) { + this.setMode(options.mode) + } + for (const name in options?.params) { + this.param(name as LuaGcParam, options.params[name as LuaGcParam]) + } + } + + public collect(): void { + this.call(LuaGcWhat.Collect) + } + + /** + * Runs one incremental step, sized as if `bytes` had just been allocated. Zero forces a single + * basic step. + * @returns true when the step finished a collection cycle. + */ + public step(bytes = 0): boolean { + assertNonNegativeInteger('step size', bytes) + return this.call(LuaGcWhat.Step, bytes) !== 0 + } + + /** Stops automatic collection until {@link restart}. Explicit calls still work. */ + public stop(): void { + this.call(LuaGcWhat.Stop) + } + + public restart(): void { + this.call(LuaGcWhat.Restart) + } + + public isRunning(): boolean { + return this.call(LuaGcWhat.IsRunning) !== 0 + } + + /** + * Bytes in use by the state, what `collectgarbage('count')` reports. Counts the same thing as + * `state.memory.used` without needing the tracing allocator. + */ + public count(): number { + return this.call(LuaGcWhat.Count) * 1024 + this.call(LuaGcWhat.CountB) + } + + /** + * Lua only reports the mode while switching, so this switches to incremental and back when + * that was not what ran. Not free on a generational state, where the switch back runs a minor + * collection. + */ + public getMode(): LuaGcMode { + const previous = this.setMode('incremental') + if (previous === 'generational') { + this.setMode('generational') + } + return previous + } + + /** + * Lua defaults to incremental. Generational trades throughput on programs that keep most of + * what they allocate for lower pause times when most objects die young. + * @returns the mode that was running before. + */ + public setMode(mode: LuaGcMode): LuaGcMode { + if (mode !== 'incremental' && mode !== 'generational') { + throw new TypeError(`unknown garbage collector mode '${mode}', expected incremental or generational`) + } + const previous = this.call(mode === 'generational' ? LuaGcWhat.Gen : LuaGcWhat.Inc) + return previous === LuaGcWhat.Gen ? 'generational' : 'incremental' + } + + /** + * Reads a collector tunable, and sets it when `value` is given. Lua stores these with about two + * significant digits of precision, so a value read back can differ from the one set. + * @returns the value it had before the call. + */ + public param(name: LuaGcParam, value?: number): number { + const index = LUA_GC_PARAMS[name] + if (index === undefined) { + throw new TypeError(`unknown garbage collector parameter '${name}', expected one of: ${Object.keys(LUA_GC_PARAMS).join(', ')}`) + } + if (value !== undefined) { + assertNonNegativeInteger(name, value) + } + // -1 tells lua_gc to leave the parameter alone. + return this.call(LuaGcWhat.Param, index, value ?? -1) + } + + private call(what: LuaGcWhat, a = 0, b = 0): number { + this.state.assertNotClosed() + const result = this.state.module.lua_gc(this.state.address, what, a, b) + // lua_gc refuses every option while a collection is in progress, which from JS can only + // mean this was reached from a __gc or __close handler run by the collector itself. + if (result < 0) { + throw new Error('the garbage collector cannot be controlled from inside a finalizer') + } + return result + } +} + +function assertNonNegativeInteger(name: string, value: number): void { + if (!(Number.isInteger(value) && value >= 0)) { + throw new RangeError(`garbage collector ${name} must be a non-negative integer, got ${value}`) + } +} diff --git a/src/index.ts b/src/index.ts index b3f5360..9f36d98 100755 --- a/src/index.ts +++ b/src/index.ts @@ -1,5 +1,6 @@ export { default as LuaRuntime } from './runtime' export { default as LuaState, type LuaMemory } from './state' +export type { default as LuaGarbageCollector } from './gc' export { default as LuaThread, type OrderedExtension } from './thread' export { default as LuaMultiReturn } from './multireturn' export { default as LuaRawResult } from './raw-result' @@ -43,6 +44,9 @@ export { type CreateStateOptions, type LuaMemoryOptions, type LuaLimitOptions, + type LuaGcOptions, + type LuaGcMode, + type LuaGcParam, type LuaRunOptions, type LuaLoadOptions, type LuaDoOptions, diff --git a/src/module.ts b/src/module.ts index 02a0d23..c4494ca 100755 --- a/src/module.ts +++ b/src/module.ts @@ -548,6 +548,7 @@ export default class LuaModule { public luaopen_debug: (L: LuaAddress) => number public luaopen_package: (L: LuaAddress) => number public luaL_openlibs: (L: LuaAddress) => void + public lua_gc: (L: LuaAddress, what: number, a: number, b: number) => number /** The mounts that are live, so a later one can be checked against them. */ private readonly mounts: ResolvedMount[] @@ -568,6 +569,9 @@ export default class LuaModule { // C writes these immediately before returning and we read them straight after with no // interleaving await, so a single shared slot each stays reentrancy safe. private readonly sizeScratch: number + /** The two 32 bit slots {@link lua_gc} passes its variadic arguments through. */ + private readonly gcArgsScratch: number + private readonly rawLuaGc: (L: LuaAddress, what: number, args: number) => number /** The `nresults` out parameter for {@link lua_resume}, read by `Thread.resume`. */ public readonly resultCountScratch: number /** @@ -743,6 +747,14 @@ export default class LuaModule { this.luaopen_debug = this.cwrap('luaopen_debug', 'number', ['number']) this.luaopen_package = this.cwrap('luaopen_package', 'number', ['number']) this.luaL_openlibs = (L) => this.luaL_openselectedlibs(L, -1, 0) + // lua_gc is variadic: the wasm32 ABI passes `...` as a pointer to the arguments laid out + // in memory, and every argument lua_gc reads is 32 bit. + this.rawLuaGc = this.cwrap('lua_gc', 'number', ['number', 'number', 'number']) + this.lua_gc = (L, what, a, b) => { + this.writePointer(this.gcArgsScratch, a) + this.writePointer(this.gcArgsScratch + PointerSize, b) + return this.rawLuaGc(L, what, this.gcArgsScratch) + } this.rawLuaToLString = this.cwrap('lua_tolstring', 'number', ['number', 'number', 'number']) this.rawLuaLToLString = this.cwrap('luaL_tolstring', 'number', ['number', 'number', 'number']) @@ -751,9 +763,10 @@ export default class LuaModule { this.sizeScratch = module._malloc(PointerSize) this.resultCountScratch = module._malloc(PointerSize) + this.gcArgsScratch = module._malloc(2 * PointerSize) // Never read or written, only compared: it exists so that the address is ours alone. this.interruptToken = module._malloc(1) - if (!this.sizeScratch || !this.resultCountScratch || !this.interruptToken) { + if (!this.sizeScratch || !this.resultCountScratch || !this.gcArgsScratch || !this.interruptToken) { throw new Error('failed to allocate the scratch buffers for C out parameters') } } diff --git a/src/state.ts b/src/state.ts index 8d0b1a8..aaad746 100755 --- a/src/state.ts +++ b/src/state.ts @@ -1,3 +1,4 @@ +import LuaGarbageCollector from './gc' import type LuaModule from './module' import Thread from './thread' import type LuaTypeExtension from './type-extension' @@ -115,13 +116,14 @@ function createAddress(cmodule: LuaModule, memory: LuaMemoryOptions | undefined) export default class LuaState extends Thread { /** Present only when the state was created with `memory.trace` or `memory.max`. */ public readonly memory: LuaMemory | undefined + public readonly gc: LuaGarbageCollector private readonly allocatorFunctionPointer: number | undefined private readonly defaultMaxInstructions: number | undefined private readonly closeListeners: (() => void)[] = [] public constructor(cmodule: LuaModule, options: CreateStateOptions = {}) { - const { libs = true, objects = 'proxy', errors = objects === 'copy', inject = false, memory, limits, onWarn } = options + const { libs = true, objects = 'proxy', errors = objects === 'copy', inject = false, memory, limits, gc, onWarn } = options const created = createAddress(cmodule, memory) super(cmodule, [], created.address) @@ -134,6 +136,8 @@ export default class LuaState extends Thread { throw new Error('Lua state could not be created (probably due to lack of memory)') } + this.gc = new LuaGarbageCollector(this, gc) + // Generic handlers - These may be required to be registered for additional types. this.registerTypeExtension(BUILT_IN_PRIORITY.table, createTableType(this)) this.registerTypeExtension(BUILT_IN_PRIORITY.function, createFunctionType(this, limits?.functionTimeout)) diff --git a/src/thread.ts b/src/thread.ts index 301e3a7..27018e8 100755 --- a/src/thread.ts +++ b/src/thread.ts @@ -490,7 +490,7 @@ export default class Thread { * extension pays nothing for them, and everything that puts them to work is guarded here. A new * method belongs on one side or the other of that line. */ - protected assertNotClosed(): void { + public assertNotClosed(): void { if (this.isClosed()) { throw new Error('the Lua state is closed') } diff --git a/src/types.ts b/src/types.ts index 9278754..d733d9a 100755 --- a/src/types.ts +++ b/src/types.ts @@ -76,6 +76,20 @@ export interface LuaLimitOptions { maxInstructions?: number | undefined } +/** + * The tunables of `collectgarbage('param', ...)`. `pause`, `stepmul` and `stepsize` drive the + * incremental collector, the other three the generational one. + */ +export type LuaGcParam = 'minormul' | 'majorminor' | 'minormajor' | 'pause' | 'stepmul' | 'stepsize' + +export type LuaGcMode = 'incremental' | 'generational' + +/** Applied before the standard libraries open, so even their tables are allocated under it. */ +export interface LuaGcOptions { + mode?: LuaGcMode | undefined + params?: Partial> | undefined +} + export interface CreateStateOptions { /** * Which standard libraries to open. `true` opens all of them, `false` opens none (which @@ -96,6 +110,7 @@ export interface CreateStateOptions { inject?: boolean | undefined memory?: LuaMemoryOptions | undefined limits?: LuaLimitOptions | undefined + gc?: LuaGcOptions | undefined /** Where diagnostics go. Defaults to the runtime's handler, and then to `console.warn`. */ onWarn?: LuaWarnHandler | undefined } @@ -184,6 +199,30 @@ export enum LuaType { Thread = 8, } +/** The `what` argument of `lua_gc`. */ +export enum LuaGcWhat { + Stop = 0, + Restart = 1, + Collect = 2, + Count = 3, + CountB = 4, + Step = 5, + IsRunning = 6, + Gen = 7, + Inc = 8, + Param = 9, +} + +/** The `LUA_GCP*` indices of `lua_gc(L, LUA_GCPARAM, ...)`. */ +export const LUA_GC_PARAMS: Record = { + minormul: 0, + majorminor: 1, + minormajor: 2, + pause: 3, + stepmul: 4, + stepsize: 5, +} + export enum LuaEventCodes { Call = 0, Ret = 1, diff --git a/test/state.test.js b/test/state.test.js index 70e43e2..c0acfd6 100644 --- a/test/state.test.js +++ b/test/state.test.js @@ -445,6 +445,105 @@ describe('State', () => { expect(state.memory).to.be.undefined }) + it('gc.count and gc.collect agree with collectgarbage', async () => { + using state = await getState() + state.gc.stop() + const counts = [] + state.set('record', () => counts.push(state.gc.count())) + const luaCount = await state.doString(` + local t = {} + for i = 1, 10000 do t[i] = { i } end + record() + local count = collectgarbage('count') * 1024 + record() + return count + `) + expect(counts[1]).to.be.equal(luaCount) + + state.gc.collect() + expect(state.gc.count()).to.be.lessThan(luaCount) + }) + + it('gc.stop and gc.restart toggle automatic collection', async () => { + using state = await getState() + expect(state.gc.isRunning()).to.be.true + + state.gc.stop() + expect(state.gc.isRunning()).to.be.false + expect(await state.doString(`return collectgarbage('isrunning')`)).to.be.false + + state.gc.restart() + expect(state.gc.isRunning()).to.be.true + }) + + it('gc.step reports the end of a cycle', async () => { + using state = await getState() + state.gc.stop() + let finished = false + for (let i = 0; i < 100 && !finished; i++) { + finished = state.gc.step(1 << 20) + } + expect(finished).to.be.true + expect(() => state.gc.step(-1)).to.throw(RangeError) + }) + + it('gc mode switches between the collectors', async () => { + using state = await getState() + expect(state.gc.getMode()).to.be.equal('incremental') + + expect(state.gc.setMode('generational')).to.be.equal('incremental') + expect(state.gc.getMode()).to.be.equal('generational') + expect(await state.doString(`return collectgarbage('incremental')`)).to.be.equal('generational') + expect(state.gc.getMode()).to.be.equal('incremental') + + expect(() => state.gc.setMode('nope')).to.throw(TypeError) + }) + + it('gc.param reads and sets every tunable', async () => { + using state = await getState() + for (const name of ['minormul', 'majorminor', 'minormajor', 'pause', 'stepmul', 'stepsize']) { + const initial = state.gc.param(name) + expect(initial, name).to.be.greaterThan(0) + expect(await state.doString(`return collectgarbage('param', '${name}')`), name).to.be.equal(initial) + + expect(state.gc.param(name, 400), name).to.be.equal(initial) + expect(state.gc.param(name), name).to.be.equal(400) + expect(await state.doString(`return collectgarbage('param', '${name}')`), name).to.be.equal(400) + } + + expect(() => state.gc.param('bogus')).to.throw(TypeError) + expect(() => state.gc.param('pause', -1)).to.throw(RangeError) + expect(() => state.gc.param('pause', 1.5)).to.throw(RangeError) + }) + + it('gc options apply at state creation', async () => { + using state = await getState({ gc: { mode: 'generational', params: { pause: 200, stepmul: 400 } } }) + expect(state.gc.getMode()).to.be.equal('generational') + expect(state.gc.param('pause')).to.be.equal(200) + expect(state.gc.param('stepmul')).to.be.equal(400) + }) + + it('gc refuses to run from inside a finalizer', async () => { + using state = await getState() + state.set('collectFromJs', () => state.gc.collect()) + const message = await state.doString(` + local message + setmetatable({}, { __gc = function() + local ok, err = pcall(collectFromJs) + message = tostring(err) + end }) + collectgarbage() + return message + `) + expect(message).to.contain('inside a finalizer') + }) + + it('gc throws on a closed state', async () => { + const state = await getState() + state.close() + expect(() => state.gc.collect()).to.throw('the Lua state is closed') + }) + it('limit memory use causes program loading failure succeeds', async () => { using state = await getState({ memory: { trace: true } }) state.memory.max = state.memory.used diff --git a/utils/build-wasm.sh b/utils/build-wasm.sh index c7d5f98..d0d4011 100755 --- a/utils/build-wasm.sh +++ b/utils/build-wasm.sh @@ -208,7 +208,8 @@ COMMON=( '_luaopen_math', \ '_luaopen_debug', \ '_luaopen_package', \ - '_luaL_openselectedlibs' \ + '_luaL_openselectedlibs', \ + '_lua_gc' \ ]" ) From 5df01194c1fe029a9c3066f4646b688a109f30aa Mon Sep 17 00:00:00 2001 From: ceifa Date: Tue, 1 Sep 2026 21:24:38 -0300 Subject: [PATCH 56/83] save a few bytes LUA_USE_JUMPTABLE=0 makes luaV_execute dispatch through a switch instead of computed gotos. Wasm has no indirect branch, so clang lowers every computed goto back into a switch anyway, only with the dispatch duplicated at each opcode: the plain switch is ~4 KB smaller and measured no slower (heapsort ran ~20% faster) with emsdk 6.0.9. --- utils/build-wasm.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/utils/build-wasm.sh b/utils/build-wasm.sh index d0d4011..255c7cd 100755 --- a/utils/build-wasm.sh +++ b/utils/build-wasm.sh @@ -12,7 +12,7 @@ then else # TEXTDECODER=1 keeps Emscripten's short string decode path, which -Oz would otherwise drop # in favour of always calling TextDecoder. LuaModule.readString relies on it. - extension=(-Oz -fno-inline-functions -s TEXTDECODER=1 -s BINARYEN_EXTRA_PASSES=gufa-optimizing) + extension=(-Oz -fno-inline-functions -DLUA_USE_JUMPTABLE=0 -s TEXTDECODER=1 -s BINARYEN_EXTRA_PASSES=gufa-optimizing,converge) fi # Everything that is not about the filesystem, shared by both glues below so they can share one From ecbe098db1b3a831dc3544bf31da5f699e31a7b3 Mon Sep 17 00:00:00 2001 From: ceifa Date: Tue, 1 Sep 2026 21:55:37 -0300 Subject: [PATCH 57/83] construct classes when calling --- src/type-extensions/proxy.ts | 21 ++++++---- test/state.test.js | 77 ++++++++++++++++++++++++++++++++++++ 2 files changed, 90 insertions(+), 8 deletions(-) diff --git a/src/type-extensions/proxy.ts b/src/type-extensions/proxy.ts index 6b82e53..264dcda 100644 --- a/src/type-extensions/proxy.ts +++ b/src/type-extensions/proxy.ts @@ -6,6 +6,16 @@ import TypeExtension from '../type-extension' import { LuaType } from '../types' import { isPromise } from '../utils' +const isClass = (target: unknown): target is new (...args: any[]) => any => + target === Date || (typeof target === 'function' && target.prototype?.constructor === target && target.toString().startsWith('class ')) + +const isClassLike = (target: unknown): boolean => { + if (typeof target !== 'function' || !target.prototype || target.prototype.constructor !== target) { + return false + } + return isClass(target) || Object.getOwnPropertyNames(target.prototype).length > 1 +} + class ProxyTypeExtension extends TypeExtension { private readonly gcPointer: number @@ -98,7 +108,7 @@ class ProxyTypeExtension extends TypeExtension { if (args[0] === self) { args.shift() } - return self(...args) + return isClass(self) ? new self(...args) : self(...args) }) state.module.lua_setfield(state.address, metatableIndex, '__call') } @@ -125,13 +135,8 @@ class ProxyTypeExtension extends TypeExtension { return false } - if (typeof target !== 'object') { - const isClass = - typeof target === 'function' && target.prototype?.constructor === target && target.toString().startsWith('class ') - - if (!isClass) { - return false - } + if (typeof target !== 'object' && !isClassLike(target)) { + return false } if (isPromise(target)) { diff --git a/test/state.test.js b/test/state.test.js index c0acfd6..9734d87 100644 --- a/test/state.test.js +++ b/test/state.test.js @@ -633,6 +633,83 @@ describe('State', () => { expect(res).to.be.equal('demo name 2') }) + it('calling a class from lua constructs it', async () => { + using state = await getState() + state.set('TestClass', TestClass) + + const res = await state.doString(` + local instance = TestClass("demo name 3") + return instance:getName() .. " " .. TestClass.hello() + `) + expect(res).to.be.equal('demo name 3 world') + }) + + it('calling a class with no methods still constructs it', async () => { + using state = await getState() + class Empty {} + state.set('Empty', Empty) + + expect(await state.doString('return Empty()')).to.be.an.instanceOf(Empty) + }) + + it('a function-style class is indexable but called, not constructed', async () => { + using state = await getState() + function Legacy(name) { + this.name = name + } + Legacy.prototype.getName = function () { + return this.name + } + Legacy.create = (name) => new Legacy(name) + state.set('Legacy', Legacy) + + // Statics are reachable through the proxy. + expect(await state.doString('return Legacy.create("legacy name"):getName()')).to.be.equal('legacy name') + // A plain call stays a plain call: strict-mode `this` is undefined, as it would be in JS. + await expect(state.doString('return Legacy("legacy name")')).to.eventually.be.rejectedWith('Cannot set properties of undefined') + }) + + it('calling Date constructs a date', async () => { + using state = await getState() + state.set('Date', Date) + + expect(await state.doString('return Date()')).to.be.an.instanceOf(Date) + expect(await state.doString('return Date(0):getTime()')).to.be.equal(0) + expect(await state.doString('return Date.UTC(2020, 0, 1)')).to.be.equal(1577836800000) + }) + + it('builtins that must not be constructed are still called', async () => { + using state = await getState() + state.set('String', String) + state.set('BigInt', BigInt) + + expect(await state.doString('return String(5)')).to.be.equal('5') + // A BigInt round-trips through Lua as an integer; the point is that the call did not throw. + expect(await state.doString('return BigInt(5)')).to.be.equal(5) + }) + + it('a builtin function-style class is indexable and constructible', async () => { + using state = await getState() + state.set('Buffer', Buffer) + + expect(await state.doString('return Buffer.from("abc"):toString("hex")')).to.be.equal('616263') + expect(await state.doString('return Buffer.alloc(2).length')).to.be.equal(2) + }) + + it('a plain function is called, not constructed', async () => { + using state = await getState() + function add(a, b) { + return a + b + } + state.set('add', add) + state.set('addArrow', (a, b) => a + b) + state.set('addProxied', decorate(add, { as: 'proxy' })) + + expect(await state.doString('return add(1, 2)')).to.be.equal(3) + expect(await state.doString('return addArrow(1, 2)')).to.be.equal(3) + expect(await state.doString('return addProxied(1, 2)')).to.be.equal(3) + }) + it('wrap a js object using proxy and apply metatable in lua', async () => { using state = await getState() state.set('TestClass', { From d41c9f5db4b1517224e3b9e600ca7e71b069fd7d Mon Sep 17 00:00:00 2001 From: ceifa Date: Fri, 4 Sep 2026 18:24:46 -0300 Subject: [PATCH 58/83] small fixes --- .gitignore | 1 - src/thread.ts | 15 +++++++++------ src/type-extensions/error.ts | 13 +++++++++---- src/type-extensions/function.ts | 6 +----- src/type-extensions/null.ts | 3 +-- test/api.test.js | 26 ++++++++++++++++++++++++++ test/errors.test.js | 23 +++++++++++++++++++++++ test/limits.test.js | 31 +++++++++++++++++++++++++++++++ test/state.test.js | 19 ++++++++++++++++++- 9 files changed, 118 insertions(+), 19 deletions(-) diff --git a/.gitignore b/.gitignore index 3c5c5da..1d88fd9 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,3 @@ .rollup.cache/ tsconfig.tsbuildinfo build/ -.eslintcache \ No newline at end of file diff --git a/src/thread.ts b/src/thread.ts index 27018e8..7a1531d 100755 --- a/src/thread.ts +++ b/src/thread.ts @@ -129,6 +129,7 @@ export default class Thread { // Also covers the resumes `run` makes after an await, where the state can have been closed // by anything else that got to run in the meantime. this.assertNotClosed() + this.rootThread.pendingInterrupt = undefined // The shared slot is safe for the same reason the one behind it is: C writes the count as it // returns and it is read straight after, with nothing interleaved. A nested resume has // finished with the slot by the time this one's lua_resume writes to it. @@ -209,6 +210,7 @@ export default class Thread { public runSync(argCount = 0, options?: LuaRunOptions): MultiReturn { this.assertNotClosed() + this.rootThread.pendingInterrupt = undefined const restore = this.applyRunOptions(options) try { const base = this.getTop() - argCount - 1 // The 1 is for the function to run @@ -225,6 +227,7 @@ export default class Thread { public call(name: string, ...args: any[]): MultiReturn { this.assertNotClosed() + this.rootThread.pendingInterrupt = undefined const type = this.module.lua_getglobal(this.address, name) if (type !== LuaType.Function) { throw new TypeError(`cannot call '${name}': expected a function, got ${LuaType[type]}`) @@ -235,7 +238,7 @@ export default class Thread { } const base = this.getTop() - args.length - 1 // The 1 is for the function to run - this.module.lua_callk(this.address, args.length, LUA_MULTRET, 0, null) + this.assertOk(this.module.lua_pcallk(this.address, args.length, LUA_MULTRET, 0, 0, null)) return this.getStackValues(base) } @@ -264,8 +267,8 @@ export default class Thread { const target = decoration ? decoration.target : rawValue if (target instanceof Thread) { - const isMain = this.module.lua_pushthread(target.address) === 1 - if (!isMain) { + this.module.lua_pushthread(target.address) + if (target.address !== this.address) { this.module.lua_xmove(target.address, this.address, 1) } return @@ -661,14 +664,14 @@ export default class Thread { maxInstructions !== undefined ? Math.max(1, Math.min(INSTRUCTION_HOOK_COUNT, maxInstructions)) : INSTRUCTION_HOOK_COUNT if (!this.hookFunctionPointer) { - this.hookFunctionPointer = this.module.addFunction((): void => { + this.hookFunctionPointer = this.module.addFunction((hookL: LuaAddress): void => { // Reads this.limits rather than closing over them, so a hook allocated for an // earlier configuration still honours the current one. const error = this.checkHookLimits() if (error) { this.rootThread.pendingInterrupt = error - this.module.lua_pushlightuserdata(this.address, this.module.interruptToken) - this.module.lua_error(this.address) + this.module.lua_pushlightuserdata(hookL, this.module.interruptToken) + this.module.lua_error(hookL) } }, 'vii') } diff --git a/src/type-extensions/error.ts b/src/type-extensions/error.ts index ba39174..9d6a706 100644 --- a/src/type-extensions/error.ts +++ b/src/type-extensions/error.ts @@ -22,12 +22,17 @@ class ErrorTypeExtension extends TypeExtension { state.module.lua_pushcclosure(state.address, this.gcPointer, 0) state.module.lua_setfield(state.address, metatableIndex, '__gc') - // Add an __index method that returns the message field state.pushValue((jsRefError: Error, key: unknown) => { - if (key === 'message') { - return jsRefError.message + switch (key) { + case 'message': + return jsRefError.message + case 'name': + return jsRefError.name + case 'stack': + return jsRefError.stack + default: + return undefined } - return null }) state.module.lua_setfield(state.address, metatableIndex, '__index') diff --git a/src/type-extensions/function.ts b/src/type-extensions/function.ts index 350c2f5..a7cebf7 100644 --- a/src/type-extensions/function.ts +++ b/src/type-extensions/function.ts @@ -41,10 +41,6 @@ class FunctionTypeExtension extends TypeExtension { this.callbackContext = state.newAnchoredThread().thread this.pooledCallThread = this.callbackContext.newAnchoredThread().thread - if (!this.functionRegistry) { - state.warn('FunctionTypeExtension: FinalizationRegistry not found. Memory leaks likely.') - } - this.gcPointer = this.createGcFunction() // Creates metatable if it doesn't exist, always pushes it onto the stack. @@ -257,7 +253,7 @@ class FunctionTypeExtension extends TypeExtension { } } - this.functionRegistry?.register(jsFunc, func) + this.functionRegistry.register(jsFunc, func) return jsFunc } diff --git a/src/type-extensions/null.ts b/src/type-extensions/null.ts index 35c2e2e..1ea7f96 100644 --- a/src/type-extensions/null.ts +++ b/src/type-extensions/null.ts @@ -24,8 +24,7 @@ class NullTypeExtension extends TypeExtension { state.module.lua_pushcclosure(state.address, this.gcPointer, 0) state.module.lua_setfield(state.address, metatableIndex, '__gc') - // Add an __index method that returns nothing. - state.pushValue(() => null) + state.pushValue(() => undefined) state.module.lua_setfield(state.address, metatableIndex, '__index') state.pushValue(() => 'null') diff --git a/test/api.test.js b/test/api.test.js index 3b64d6a..1d40fb3 100644 --- a/test/api.test.js +++ b/test/api.test.js @@ -148,6 +148,32 @@ describe('Custom type extensions', () => { }) describe('Thread lifecycle', () => { + it('pushValue of the main thread should land on the pushing stack', async () => { + using state = await getState() + const thread = state.newThread() + const stateTop = state.getTop() + + thread.pushValue(state) + + expect(thread.getTop()).to.be.equal(1) + expect(state.getTop()).to.be.equal(stateTop) + expect(thread.getValue(-1)).to.be.equal(state) + + thread.pop() + }) + + it('pushValue of a thread onto itself should not move anything', async () => { + using state = await getState() + const thread = state.newThread() + + thread.pushValue(thread) + + expect(thread.getTop()).to.be.equal(1) + expect(thread.getValue(-1)).to.be.equal(thread) + + thread.pop() + }) + it('resetThread should let a finished thread be loaded again', async () => { using state = await getState() const thread = state.newThread() diff --git a/test/errors.test.js b/test/errors.test.js index 9a7b19a..c7aaeb0 100644 --- a/test/errors.test.js +++ b/test/errors.test.js @@ -75,6 +75,29 @@ describe('errors option', () => { expect(await state.doString(catchIt('err.message'))).to.be.equal('kaboom') }) + it('should expose name and stack when on', async () => { + using state = await getState({ errors: true }) + setThrow(state) + + expect(await state.doString(catchIt('err.name'))).to.be.equal('Error') + expect(await state.doString(catchIt('type(err.stack)'))).to.be.equal('string') + }) + + it('should read an unknown field as nil when on', async () => { + using state = await getState({ errors: true }) + setThrow(state) + + expect(await state.doString(catchIt('type(err.nope)'))).to.be.equal('nil') + expect(await state.doString(catchIt('err.nope == nil'))).to.be.equal(true) + }) + + it('should be read-only when on', async () => { + using state = await getState({ errors: true }) + setThrow(state) + + await expect(state.doString(catchIt('err.message = "rewritten"'))).to.eventually.be.rejected + }) + it('should be overridable to off when objects is copy', async () => { using state = await getState({ objects: 'copy', errors: false }) setThrow(state) diff --git a/test/limits.test.js b/test/limits.test.js index 16f9c16..a666a36 100644 --- a/test/limits.test.js +++ b/test/limits.test.js @@ -119,4 +119,35 @@ describe('Run limits', () => { expect(error.message).to.contain('raised after the interrupt was caught') }) }) + + it('an interrupt inside a coroutine unwinds the coroutine too', async function () { + this.timeout(20_000) + using state = await getState() + + const outcome = state.doStringSync( + `local co = coroutine.create(function () ${busyLoop} end) + local ok = coroutine.resume(co) + return tostring(ok) .. " " .. coroutine.status(co)`, + { maxInstructions: 5_000 }, + ) + + expect(outcome).to.be.equal('false dead') + }) + + it('an interrupt token the script kept does not turn a later run into a limit error', async function () { + this.timeout(20_000) + using state = await getState({ objects: 'copy', errors: false }) + + state.doStringSync(`local ok, token = pcall(function () ${busyLoop} end) saved = token`, { maxInstructions: 5_000 }) + + let error + try { + state.doStringSync('error(saved)') + } catch (err) { + error = err + } + + expect(error).to.be.an('error') + expect(error).to.not.be.an.instanceOf(LuaInterruptError) + }) }) diff --git a/test/state.test.js b/test/state.test.js index 9734d87..fb27b09 100644 --- a/test/state.test.js +++ b/test/state.test.js @@ -316,6 +316,15 @@ describe('State', () => { expect(returns.at(-1)).to.be.a('function') }) + it('call a global function that raises should throw instead of panicking', async () => { + using state = await getState() + state.doStringSync('function boom() error("kaboom") end') + + expect(() => state.call('boom')).to.throw('kaboom') + expect(state.isClosed()).to.be.equal(false) + expect(state.doStringSync('return 1 + 1')).to.be.equal(2) + }) + it('get a lua thread should succeed', async () => { using state = await getState() @@ -646,7 +655,7 @@ describe('State', () => { it('calling a class with no methods still constructs it', async () => { using state = await getState() - class Empty {} + class Empty { } state.set('Empty', Empty) expect(await state.doString('return Empty()')).to.be.an.instanceOf(Empty) @@ -1223,6 +1232,14 @@ describe('State', () => { expect(state.get('value')).to.be.null }) + it('reading a field off the null sentinel should be nil', async () => { + using state = await getState() + state.set('value', null) + + expect(await state.doString('return type(value.anything)')).to.be.equal('nil') + expect(await state.doString('return value.anything == nil')).to.be.true + }) + it('a pushed null should equal the injected null global', async () => { using state = await getState() state.set('value', null) From f3d9282869cdf42cbe36b0d5c2b8bcabf523d94a Mon Sep 17 00:00:00 2001 From: ceifa Date: Fri, 4 Sep 2026 19:22:19 -0300 Subject: [PATCH 59/83] reuse object instance when pushed twice --- src/type-extension.ts | 19 ++++---- src/type-extensions/function.ts | 80 ++++++++++++++++++++++++++------- src/type-extensions/proxy.ts | 17 ++++++- test/api.test.js | 38 ++++++++++++++++ 4 files changed, 128 insertions(+), 26 deletions(-) diff --git a/src/type-extension.ts b/src/type-extension.ts index 4dcd8fa..25a1b62 100644 --- a/src/type-extension.ts +++ b/src/type-extension.ts @@ -9,14 +9,15 @@ export default abstract class LuaTypeExtension { /** Owns this extension's metatable and function pointers, so its lifetime bounds theirs. */ protected state: LuaState /** - * A weak valued table in the registry mapping a reference index to the userdata pushed for it, - * so pushing the same value again returns that userdata instead of allocating another one -- - * which also gives it a stable identity in Lua. Weak, so the cache never keeps a userdata - * alive: an entry goes as soon as Lua drops the userdata, before its `__gc` releases the - * reference index it is keyed by. Per extension, because the same value pushed through two - * extensions must not share a userdata carrying the wrong metatable. + * A weak valued table in the registry mapping a reference index to the Lua value pushed for it + * (the userdata here, the closure over it in the function extension), so pushing the same value + * again returns that one instead of allocating another -- which also gives it a stable identity + * in Lua. Weak, so the cache never keeps a Lua value alive: an entry goes as soon as Lua drops + * the value, before the userdata's `__gc` releases the reference index it is keyed by. Per + * extension, because the same value pushed through two extensions must not share a userdata + * carrying the wrong metatable. */ - private readonly userdataCacheReference: bigint + protected readonly pushedValueCacheReference: bigint public constructor(state: LuaState, name: string) { this.state = state @@ -28,7 +29,7 @@ export default abstract class LuaTypeExtension { module.lua_pushstring(state.address, 'v') module.lua_setfield(state.address, -2, '__mode') module.lua_setmetatable(state.address, -2) - this.userdataCacheReference = BigInt(module.luaL_ref(state.address, LUA_REGISTRYINDEX)) + this.pushedValueCacheReference = BigInt(module.luaL_ref(state.address, LUA_REGISTRYINDEX)) } public isType(_thread: Thread, _index: number, type: LuaType, name?: string): boolean { @@ -80,7 +81,7 @@ export default abstract class LuaTypeExtension { // The cache table stays at the bottom for the whole push, so the probe and the store // below share the one registry fetch. - module.lua_rawgeti(thread.address, LUA_REGISTRYINDEX, this.userdataCacheReference) + module.lua_rawgeti(thread.address, LUA_REGISTRYINDEX, this.pushedValueCacheReference) const existingIndex = module.getRefIndex(target) if (existingIndex !== undefined) { diff --git a/src/type-extensions/function.ts b/src/type-extensions/function.ts index a7cebf7..b3613d7 100644 --- a/src/type-extensions/function.ts +++ b/src/type-extensions/function.ts @@ -1,4 +1,4 @@ -import { Decoration } from '../decoration' +import { Decoration, type DecorationOptions } from '../decoration' import type LuaState from '../state' import MultiReturn from '../multireturn' import RawResult from '../raw-result' @@ -9,6 +9,13 @@ import { isEmscriptenUnwind } from '../utils' export type FunctionType = (...args: any[]) => Promise | any +const NO_OPTIONS: DecorationOptions = {} + +/** Whether the wrapper would behave any differently for these options than for none. */ +function affectsCall(options: DecorationOptions): boolean { + return options.self !== undefined || options.receiveThread === true || options.receiveArgsQuantity === true +} + class FunctionTypeExtension extends TypeExtension { private readonly functionRegistry = new FinalizationRegistry((func: number) => { if (!this.state.isClosed()) { @@ -61,18 +68,25 @@ class FunctionTypeExtension extends TypeExtension { // The upvalue is always the userdata pushValue closed this wrapper over, so the // metatable check luaL_checkudata does (and the name it marshals) is saved on every - // call. Only a ref that does not resolve to a function decoration -- the upvalue - // replaced through the debug library -- falls back to it, for the error the C API - // would have raised. + // call. Only a ref that resolves to neither a function nor a function decoration -- the + // upvalue replaced through the debug library -- falls back to it, for the error the C + // API would have raised. const upvalueIndex = state.module.lua_upvalueindex(1) const refUserdata = state.module.lua_touserdata(calledL, upvalueIndex) const reference = refUserdata ? state.module.getRef(state.module.readPointer(refUserdata)) : undefined - if (!(reference instanceof Decoration) || typeof reference.target !== 'function') { + let target: FunctionType + let decorationOptions: DecorationOptions + if (typeof reference === 'function') { + target = reference as FunctionType + decorationOptions = NO_OPTIONS + } else if (reference instanceof Decoration && typeof reference.target === 'function') { + target = reference.target + decorationOptions = reference.options + } else { // Raises the error the C API would have; the throw below is unreachable. state.module.luaL_checkudata(calledL, upvalueIndex, this.name) throw new Error('a js_function upvalue does not hold a function reference') } - const { target, options: decorationOptions } = reference const argsQuantity = calledThread.getTop() const args = [] @@ -167,28 +181,62 @@ class FunctionTypeExtension extends TypeExtension { return false } + const module = thread.module + // It's surprisingly inefficient to map JS functions to C functions so this creates a reference to the // function which stays solely in JS. The cfunction called from Lua is created at the top of the class // and it accesses the JS data through an upvalue. + // + // The wrapper only needs the decoration when it carries an option it acts on. Otherwise the + // bare function is referenced instead, so that every push of the same function -- decorated + // or not, since Thread.pushValue synthesises a fresh decoration for a plain one -- shares + // one reference and, through the cache below, one Lua closure. A decoration with options + // is referenced as it is: the same instance pushed twice still yields one closure, while + // the same function under different options stays distinct, as its behaviour is. + const referent: unknown = affectsCall(decoration.options) ? decoration : decoration.target + + // The cache table stays at the bottom for the whole push, so the probe and the store + // below share the one registry fetch. + module.lua_rawgeti(thread.address, LUA_REGISTRYINDEX, this.pushedValueCacheReference) + + const existingIndex = module.getRefIndex(referent) + if (existingIndex !== undefined) { + if (module.lua_rawgeti(thread.address, -1, BigInt(existingIndex)) === LuaType.Function) { + // Drop the cache table, keeping the closure. + module.lua_remove(thread.address, -2) + return true + } + // Pop the miss; the cache table stays for the store. + thread.pop(1) + } - const pointer = thread.module.ref(decoration) + const pointer = module.ref(referent) // 4 = size of pointer in wasm. - const userDataPointer = thread.module.lua_newuserdatauv(thread.address, PointerSize, 0) - thread.module.writePointer(userDataPointer, pointer) - - if (LuaType.Nil === thread.module.luaL_getmetatable(thread.address, this.name)) { - // Pop the pushed userdata. - thread.pop(1) - thread.module.unref(pointer) + const userDataPointer = module.lua_newuserdatauv(thread.address, PointerSize, 0) + module.writePointer(userDataPointer, pointer) + + if (LuaType.Nil === module.luaL_getmetatable(thread.address, this.name)) { + // Pop the pushed nil, the userdata and the cache table. The reference has to be + // released by hand: without a metatable the userdata has no __gc, so nothing else ever + // would. + thread.pop(3) + module.unref(pointer) throw new Error(`metatable not found: ${this.name}`) } // Set as the metatable for the function. // -1 is the metatable, -2 is the userdata - thread.module.lua_setmetatable(thread.address, -2) + module.lua_setmetatable(thread.address, -2) // Pass 1 to associate the closure with the userdata, pops the userdata. - thread.module.lua_pushcclosure(thread.address, this.functionWrapper, 1) + module.lua_pushcclosure(thread.address, this.functionWrapper, 1) + + // Remember the closure for the next push of the same function, then drop the cache table + // from under it. Weak, so this never outlives the closure: once Lua collects it the + // userdata upvalue goes too, and its __gc releases the reference. + module.lua_pushvalue(thread.address, -1) + module.lua_rawseti(thread.address, -3, BigInt(pointer)) + module.lua_remove(thread.address, -2) return true } diff --git a/src/type-extensions/proxy.ts b/src/type-extensions/proxy.ts index 264dcda..d1ffe55 100644 --- a/src/type-extensions/proxy.ts +++ b/src/type-extensions/proxy.ts @@ -18,6 +18,7 @@ const isClassLike = (target: unknown): boolean => { class ProxyTypeExtension extends TypeExtension { private readonly gcPointer: number + private readonly boundMethods = new WeakMap any, Decoration<(...args: any[]) => any>>>() public constructor(state: LuaState) { super(state, 'js_proxy') @@ -51,7 +52,7 @@ class ProxyTypeExtension extends TypeExtension { const value = self[key as string | number] if (typeof value === 'function') { - return decorate(value as (...args: any[]) => any, { self }) + return this.bindMethod(self, value as (...args: any[]) => any) } return value @@ -117,6 +118,20 @@ class ProxyTypeExtension extends TypeExtension { state.module.lua_pop(state.address, 1) } + private bindMethod(self: object, method: (...args: any[]) => any): Decoration<(...args: any[]) => any> { + let methods = this.boundMethods.get(self) + if (!methods) { + methods = new WeakMap() + this.boundMethods.set(self, methods) + } + let bound = methods.get(method) + if (!bound) { + bound = decorate(method, { self }) + methods.set(method, bound) + } + return bound + } + public isType(_thread: Thread, _index: number, type: LuaType, name?: string): boolean { // Capture proxied types and functions returned by lua. return type === LuaType.Userdata && name === this.name diff --git a/test/api.test.js b/test/api.test.js index 1d40fb3..fc4b6f1 100644 --- a/test/api.test.js +++ b/test/api.test.js @@ -82,6 +82,44 @@ describe('Decoration options', () => { expect(await state.doString('return grab("a", "b")')).to.be.equal('number:a,b') }) + it('should push the same function as the same Lua value', async () => { + using state = await getState() + const fn = () => 1 + state.set('a', fn) + state.set('b', fn) + state.set('c', decorate(fn, {})) + + expect(await state.doString('return a == b and b == c')).to.be.equal(true) + }) + + it('should push the same decoration as the same Lua value, and different options as different ones', async () => { + using state = await getState() + const fn = (...args) => args.length + const bound = decorate(fn, { self: {} }) + state.set('plain', fn) + state.set('bound1', bound) + state.set('bound2', bound) + state.set('counting', decorate(fn, { receiveArgsQuantity: true })) + + expect(await state.doString('return bound1 == bound2')).to.be.equal(true) + expect(await state.doString('return plain ~= bound1 and plain ~= counting and bound1 ~= counting')).to.be.equal(true) + expect(await state.doString('return plain(1, 2), bound1(1, 2), counting(1, 2)')).to.be.equal(2) + }) + + it('should hand out the same Lua value for the same proxied method', async () => { + using state = await getState() + state.set('obj', { + n: 0, + bump() { + this.n++ + }, + }) + + expect(await state.doString('return obj.bump == obj.bump')).to.be.equal(true) + await state.doString('for _ = 1, 3 do obj:bump() end') + expect(state.get('obj').n).to.be.equal(3) + }) + it('receiveArgsQuantity should pass the count instead of the arguments', async () => { using state = await getState() state.set( From 40c8c270cbf6213ddb629e896d938b90c40e439c Mon Sep 17 00:00:00 2001 From: ceifa Date: Fri, 4 Sep 2026 19:35:03 -0300 Subject: [PATCH 60/83] proxied arrays act like arrays --- src/type-extensions/proxy.ts | 8 ++++++-- test/state.test.js | 31 ++++++++++++++++++++++++++++++- 2 files changed, 36 insertions(+), 3 deletions(-) diff --git a/src/type-extensions/proxy.ts b/src/type-extensions/proxy.ts index d1ffe55..b0462b9 100644 --- a/src/type-extensions/proxy.ts +++ b/src/type-extensions/proxy.ts @@ -85,12 +85,16 @@ class ProxyTypeExtension extends TypeExtension { state.module.lua_setfield(state.address, metatableIndex, '__len') state.pushValue((self: any) => { - const keys = Object.getOwnPropertyNames(self) + const isArray = Array.isArray(self) + const keys = isArray ? self : Object.keys(self) let i = 0 // Stateful rather than stateless. First call is with nil. return MultiReturn.of( () => { - const ret = MultiReturn.of(keys[i], self[keys[i]]) + if (i >= keys.length) { + return undefined + } + const ret = isArray ? MultiReturn.of(i + 1, self[i]) : MultiReturn.of(keys[i], self[keys[i]]) i++ return ret }, diff --git a/test/state.test.js b/test/state.test.js index fb27b09..68b1170 100644 --- a/test/state.test.js +++ b/test/state.test.js @@ -209,6 +209,35 @@ describe('State', () => { expect(keys).to.be.equal('own') }) + it('pairs over a proxied array should yield 1-based numeric keys', async () => { + using state = await getState() + state.set('arr', ['a', 'b', 'c']) + + const out = await state.doString(` + local out = {} + for key, value in pairs(arr) do out[#out + 1] = type(key) .. ':' .. tostring(key) .. '=' .. value end + return table.concat(out, ',') + `) + + expect(out).to.be.equal('number:1=a,number:2=b,number:3=c') + }) + + it('pairs over a proxied object should yield only own enumerable keys', async () => { + using state = await getState() + const obj = Object.create({ inherited: 'yes' }) + obj.own = 'mine' + Object.defineProperty(obj, 'hidden', { value: 1, enumerable: false }) + state.set('obj', obj) + + const out = await state.doString(` + local out = {} + for key, value in pairs(obj) do out[#out + 1] = key .. '=' .. value end + return table.concat(out, ',') + `) + + expect(out).to.be.equal('own=mine') + }) + it('non enumerable properties should not be copied into the lua table', async () => { using state = await getState({ objects: 'copy' }) const obj = { own: 'mine' } @@ -655,7 +684,7 @@ describe('State', () => { it('calling a class with no methods still constructs it', async () => { using state = await getState() - class Empty { } + class Empty {} state.set('Empty', Empty) expect(await state.doString('return Empty()')).to.be.an.instanceOf(Empty) From feeea6ba11c417c563e1ff3b22557483322144e5 Mon Sep 17 00:00:00 2001 From: ceifa Date: Fri, 4 Sep 2026 20:10:18 -0300 Subject: [PATCH 61/83] perf, size, refact --- .claude/worktrees/js-size | 1 + src/module.ts | 142 +++++++++++++++++++++++++++----- src/thread.ts | 11 +-- src/type-extension.ts | 122 +++++++++++++++++---------- src/type-extensions/error.ts | 42 ++-------- src/type-extensions/function.ts | 80 ++---------------- src/type-extensions/null.ts | 42 ++-------- src/type-extensions/promise.ts | 58 +++++-------- src/type-extensions/proxy.ts | 120 ++++++++------------------- src/type-extensions/table.ts | 10 +-- src/type-extensions/userdata.ts | 37 ++------- test/api.test.js | 55 +++++++++---- utils/build-wasm.sh | 4 +- 13 files changed, 337 insertions(+), 387 deletions(-) create mode 160000 .claude/worktrees/js-size diff --git a/.claude/worktrees/js-size b/.claude/worktrees/js-size new file mode 160000 index 0000000..40c8c27 --- /dev/null +++ b/.claude/worktrees/js-size @@ -0,0 +1 @@ +Subproject commit 40c8c270cbf6213ddb629e896d938b90c40e439c diff --git a/src/module.ts b/src/module.ts index c4494ca..869a99d 100755 --- a/src/module.ts +++ b/src/module.ts @@ -97,10 +97,10 @@ export interface LuaModuleOptions { onWarn?: LuaWarnHandler | undefined } -// One-shot conversions, so a single stateless encoder is shared by every module. Decoding goes -// through Emscripten's UTF8ToString, and streaming output keeps its own decoder in -// createOutputWriter. +// One-shot conversions, so a single stateless codec pair is shared by every module. Streaming +// output keeps its own decoder in createOutputWriter, since a flush can cut a character in half. const textEncoder = new TextEncoder() +const textDecoder = new TextDecoder() // Above this a dedicated allocation is used, so one huge string cannot permanently retain the // scratch buffer. @@ -129,9 +129,12 @@ const enum StringArgument { // passed to one of these would overflow it. const STACK_STRING_LIMIT = 1024 -// Above this, TextEncoder beats copying byte by byte in JS (measured; TEXTDECODER=1 covers the -// other direction upstream). +// Above this, TextEncoder beats copying byte by byte in JS (measured). const INLINE_ENCODE_LIMIT = 40 +// Above this, TextDecoder beats gathering the bytes in JS (measured). Its cost is nearly flat -- +// mostly the subarray view and the call -- while the inline path grows per byte; the two cross +// here. Most reads are well under it: table keys, global names, short values. +const INLINE_DECODE_LIMIT = 32 // The wasm value types Emscripten's function signature letters map to. `p` is a pointer, which is // an i32 in a build without MEMORY64. @@ -479,7 +482,7 @@ export default class LuaModule { public lua_compare: (L: LuaAddress, idx1: number, idx2: number, op: number) => number public lua_pushnil: (L: LuaAddress) => void public lua_pushnumber: (L: LuaAddress, n: number) => void - public lua_pushinteger: (L: LuaAddress, n: bigint) => void + public lua_pushinteger: (L: LuaAddress, n: number | bigint) => void public lua_pushlstring: (L: LuaAddress, s: number, len: number) => void public lua_pushcclosure: (L: LuaAddress, fn: number, n: number) => void public lua_pushboolean: (L: LuaAddress, b: number) => void @@ -488,9 +491,9 @@ export default class LuaModule { public lua_getglobal: (L: LuaAddress, name: string | null) => LuaType public lua_gettable: (L: LuaAddress, idx: number) => LuaType public lua_getfield: (L: LuaAddress, idx: number, k: string | null) => LuaType - public lua_geti: (L: LuaAddress, idx: number, n: bigint) => LuaType + public lua_geti: (L: LuaAddress, idx: number, n: number | bigint) => LuaType public lua_rawget: (L: LuaAddress, idx: number) => LuaType - public lua_rawgeti: (L: LuaAddress, idx: number, n: bigint) => LuaType + public lua_rawgeti: (L: LuaAddress, idx: number, n: number | bigint) => LuaType public lua_rawgetp: (L: LuaAddress, idx: number, p: number | null) => LuaType public lua_createtable: (L: LuaAddress, narr: number, nrec: number) => void public lua_newuserdatauv: (L: LuaAddress, sz: number, nuvalue: number) => LuaAddress @@ -499,9 +502,9 @@ export default class LuaModule { public lua_setglobal: (L: LuaAddress, name: string | null) => void public lua_settable: (L: LuaAddress, idx: number) => void public lua_setfield: (L: LuaAddress, idx: number, k: string | null) => void - public lua_seti: (L: LuaAddress, idx: number, n: bigint) => void + public lua_seti: (L: LuaAddress, idx: number, n: number | bigint) => void public lua_rawset: (L: LuaAddress, idx: number) => void - public lua_rawseti: (L: LuaAddress, idx: number, n: bigint) => void + public lua_rawseti: (L: LuaAddress, idx: number, n: number | bigint) => void public lua_rawsetp: (L: LuaAddress, idx: number, p: number | null) => void public lua_setmetatable: (L: LuaAddress, objindex: number) => number public lua_setiuservalue: (L: LuaAddress, idx: number, n: number) => number @@ -588,6 +591,8 @@ export default class LuaModule { */ public readonly interruptToken: number private stringBuffer = 0 + /** Built on first use by {@link referenceGcFunction}, then kept for the module's lifetime. */ + private referenceGcPointer: number | undefined public constructor( module: LuaEmscriptenModule, @@ -678,7 +683,7 @@ export default class LuaModule { this.lua_compare = this.cwrap('lua_compare', 'number', ['number', 'number', 'number', 'number']) this.lua_pushnil = this.cwrap('lua_pushnil', null, ['number']) this.lua_pushnumber = this.cwrap('lua_pushnumber', null, ['number', 'number']) - this.lua_pushinteger = this.cwrap('lua_pushinteger', null, ['number', 'number']) + this.lua_pushinteger = this.withIntegerArgument('lua_pushinteger', null, ['number', 'number']) this.lua_pushcclosure = this.cwrap('lua_pushcclosure', null, ['number', 'number', 'number']) this.lua_pushboolean = this.cwrap('lua_pushboolean', null, ['number', 'number']) this.lua_pushlightuserdata = this.cwrap('lua_pushlightuserdata', null, ['number', 'number']) @@ -686,9 +691,9 @@ export default class LuaModule { this.lua_getglobal = this.cwrap('lua_getglobal', 'number', ['number', 'string']) this.lua_gettable = this.cwrap('lua_gettable', 'number', ['number', 'number']) this.lua_getfield = this.cwrap('lua_getfield', 'number', ['number', 'number', 'string']) - this.lua_geti = this.cwrap('lua_geti', 'number', ['number', 'number', 'number']) + this.lua_geti = this.withIntegerArgument('lua_geti', 'number', ['number', 'number', 'number']) this.lua_rawget = this.cwrap('lua_rawget', 'number', ['number', 'number']) - this.lua_rawgeti = this.cwrap('lua_rawgeti', 'number', ['number', 'number', 'number']) + this.lua_rawgeti = this.withIntegerArgument('lua_rawgeti', 'number', ['number', 'number', 'number']) this.lua_rawgetp = this.cwrap('lua_rawgetp', 'number', ['number', 'number', 'number']) this.lua_createtable = this.cwrap('lua_createtable', null, ['number', 'number', 'number']) this.lua_newuserdatauv = this.cwrap('lua_newuserdatauv', 'number', ['number', 'number', 'number']) @@ -697,9 +702,9 @@ export default class LuaModule { this.lua_setglobal = this.cwrap('lua_setglobal', null, ['number', 'string']) this.lua_settable = this.cwrap('lua_settable', null, ['number', 'number']) this.lua_setfield = this.cwrap('lua_setfield', null, ['number', 'number', 'string']) - this.lua_seti = this.cwrap('lua_seti', null, ['number', 'number', 'number']) + this.lua_seti = this.withIntegerArgument('lua_seti', null, ['number', 'number', 'number']) this.lua_rawset = this.cwrap('lua_rawset', null, ['number', 'number']) - this.lua_rawseti = this.cwrap('lua_rawseti', null, ['number', 'number', 'number']) + this.lua_rawseti = this.withIntegerArgument('lua_rawseti', null, ['number', 'number', 'number']) this.lua_rawsetp = this.cwrap('lua_rawsetp', null, ['number', 'number', 'number']) this.lua_setmetatable = this.cwrap('lua_setmetatable', 'number', ['number', 'number']) this.lua_setiuservalue = this.cwrap('lua_setiuservalue', 'number', ['number', 'number', 'number']) @@ -851,14 +856,33 @@ export default class LuaModule { } } + /** + * The counterpart to {@link writeString}. A short ASCII string is gathered and built in one + * `fromCharCode`: Emscripten's own decoder concatenates a character at a time below its + * TextDecoder threshold, which cost more than the decode itself for the names and keys that + * make up most reads here. A NUL is an ordinary byte, since the length is already known. + */ public readString(pointer: number, length: number): string { if (!length) { return '' } - // The third argument keeps it from stopping at a NUL, since a Lua string can contain them - // and the length is already known. Built with TEXTDECODER=1 so this skips TextDecoder for - // the short names and keys that most of these are -- see utils/build-wasm.sh. - return this.emscripten.UTF8ToString(pointer, length, true) + const heap = this.heap + if (length <= INLINE_DECODE_LIMIT) { + const codes = new Array(length) + let index = 0 + while (index < length) { + const code = heap[pointer + index] + if (code > 0x7f) { + break + } + codes[index++] = code + } + if (index === length) { + return String.fromCharCode.apply(null, codes) + } + // Anything non-ASCII is decoded from the start, the same as the long strings below. + } + return textDecoder.decode(heap.subarray(pointer, pointer + length)) } /** @@ -949,6 +973,29 @@ export default class LuaModule { this.emscripten.removeFunction(pointer) } + /** + * The `__gc` handler for a userdata holding a reference index, which is what every reference + * holding type extension puts on its metatable and the same code for each of them. One per + * module rather than one per extension per state: each takes a trampoline of its own from + * {@link addFunction}, and those were a fifth of what creating a state cost. Owned by the + * module, so it is never removed. + */ + public referenceGcFunction(): number { + this.referenceGcPointer ??= this.addFunction((L: LuaAddress): number => { + // Only a userdata pushed by LuaTypeExtension holds a reference index, and those are + // exactly one pointer wide. The check stands in for the metatable name one a handler + // built per extension can make: it rules out the io library's stream handles, the one + // other userdata Lua code can reach and put one of these metatables on through + // debug.setmetatable, which would otherwise be read as an index and unreferenced. + const userdata = this.lua_touserdata(L, 1) + if (userdata && this.lua_rawlen(L, 1) === BigInt(PointerSize)) { + this.unref(this.readPointer(userdata)) + } + return LuaReturn.Ok + }, 'ii') + return this.referenceGcPointer + } + private toLString(raw: (L: LuaAddress, idx: number, len: number) => number, L: LuaAddress, idx: number, len: number | null): string { const lengthPointer = len ?? this.sizeScratch const pointer = raw(L, idx, lengthPointer) @@ -1024,6 +1071,33 @@ export default class LuaModule { return this.referenceMap.get(index) } + /** + * Pushes a fresh userdata holding a reference to `target`: the box every reference carrying + * type extension puts a JS value in. The layout, a single pointer sized slot holding the + * reference index, is known here, in {@link getReferenceBox} and in the `__gc` handler + * {@link referenceGcFunction} builds, and nowhere else. + * + * The reference is the caller's to release until the box has a metatable carrying that `__gc`, + * which is what hands ownership to Lua. + * @returns the reference index, which also serves as the box's identity in a push cache. + */ + public pushReferenceBox(L: LuaAddress, target: unknown): number { + const index = this.ref(target) + const userDataPointer = this.lua_newuserdatauv(L, PointerSize, 0) + this.writePointer(userDataPointer, index) + return index + } + + /** + * The JS value boxed in the userdata at `index`, or undefined when nothing is boxed there. With + * a `metatableName` only a userdata carrying that metatable counts; without one the caller has + * already established what it is looking at, so the check and the name it marshals are skipped. + */ + public getReferenceBox(L: LuaAddress, index: number, metatableName?: string): unknown { + const userDataPointer = metatableName === undefined ? this.lua_touserdata(L, index) : this.luaL_testudata(L, index, metatableName) + return userDataPointer ? this.referenceMap.get(this.readPointer(userDataPointer)) : undefined + } + /** The index {@link ref} already holds for `data`, without taking a count, or undefined. */ public getRefIndex(data: unknown): number | undefined { return this.referenceTracker.get(data)?.index @@ -1071,6 +1145,36 @@ export default class LuaModule { } } + /** + * A binding whose last argument is a `lua_Integer`, taking either a BigInt or a number. The + * BigInt goes to the C API as it is; a number, which has to be a safe integer, goes to the + * double taking twin of the same name in src/native/wasmoon.c, saving the BigInt conversion on + * every call. The integer is the last argument of each of these. + */ + private withIntegerArgument( + name: string, + returnType: Emscripten.JSType | null, + argTypes: Emscripten.JSType[], + ): (...args: any[]) => any { + const bigintBinding = this.cwrap(name, returnType, argTypes) + const numberBinding = this.cwrap(name.replace('lua_', 'wasmoon_'), returnType, argTypes) + const integerLast = argTypes.length === 2 + if (!integerLast && argTypes.length !== 3) { + throw new Error(`withIntegerArgument only covers arities 2 and 3, not ${argTypes.length}`) + } + + return (a: any, b: any, c?: any): any => { + const n = integerLast ? b : c + if (typeof n === 'bigint') { + return bigintBinding(a, b, c) + } + if (!Number.isSafeInteger(n)) { + throw new RangeError(`${n} is not a safe integer; pass a BigInt for the full lua_Integer range`) + } + return numberBinding(a, b, c) + } + } + private cwrap( name: string, returnType: Emscripten.JSType | null, diff --git a/src/thread.ts b/src/thread.ts index 7a1531d..5a433bf 100755 --- a/src/thread.ts +++ b/src/thread.ts @@ -1,4 +1,4 @@ -import { Decoration, type LuaMetatable } from './decoration' +import { Decoration, type DecorationOptions, type LuaMetatable } from './decoration' import type LuaModule from './module' import MultiReturn from './multireturn' import type LuaTypeExtension from './type-extension' @@ -37,6 +37,7 @@ const INSTRUCTION_HOOK_COUNT = 1000 const LUA_INTEGER_BITS = 64 const NO_RESTORE = (): void => undefined +const NO_OPTIONS: Readonly = Object.freeze({}) export default class Thread { public readonly address: LuaAddress @@ -283,7 +284,7 @@ export default class Thread { // Only integers JS can represent exactly become Lua integers. Values like 1e300 // are integral but far outside int64, and would wrap silently if pushed as one. if (Number.isSafeInteger(target)) { - this.module.lua_pushinteger(this.address, BigInt(target)) + this.module.lua_pushinteger(this.address, target) } else { this.module.lua_pushnumber(this.address, target) } @@ -305,7 +306,7 @@ export default class Thread { // not guaranteed to leave exactly one value behind. That is worth the two // lua_gettop calls here, and not worth them on every primitive push. const startTop = this.getTop() - if (this.pushWithExtension(decoration ?? new Decoration(target, {}), cache)) { + if (this.pushWithExtension(decoration ?? new Decoration(target, NO_OPTIONS), cache)) { const endTop = this.getTop() if (endTop !== startTop + 1) { throw new Error(`pushValue expected stack size ${startTop + 1}, got ${endTop}`) @@ -365,8 +366,6 @@ export default class Thread { } public getValue(index: number, inputType?: LuaType, cache?: LuaGetCache): any { - index = this.absIndex(index) - const type: LuaType = inputType ?? this.module.lua_type(this.address, index) switch (type) { @@ -390,6 +389,8 @@ export default class Thread { case LuaType.Thread: return this.stateToThread(this.module.lua_tothread(this.address, index)) default: { + index = this.absIndex(index) + let metatableName: string | undefined if (type === LuaType.Table || type === LuaType.Userdata) { metatableName = this.getMetatableName(index) diff --git a/src/type-extension.ts b/src/type-extension.ts index 25a1b62..9b4af45 100644 --- a/src/type-extension.ts +++ b/src/type-extension.ts @@ -1,7 +1,7 @@ import type { Decoration } from './decoration' import type LuaState from './state' import type Thread from './thread' -import { LUA_REGISTRYINDEX, type LuaAddress, type LuaGetCache, type LuaPushCache, LuaReturn, LuaType, PointerSize } from './types' +import { LUA_REGISTRYINDEX, type LuaGetCache, type LuaPushCache, LuaType } from './types' export default abstract class LuaTypeExtension { // Type name, for metatables and lookups. @@ -17,7 +17,7 @@ export default abstract class LuaTypeExtension { * extension, because the same value pushed through two extensions must not share a userdata * carrying the wrong metatable. */ - protected readonly pushedValueCacheReference: bigint + protected readonly pushedValueCacheReference: number public constructor(state: LuaState, name: string) { this.state = state @@ -29,7 +29,7 @@ export default abstract class LuaTypeExtension { module.lua_pushstring(state.address, 'v') module.lua_setfield(state.address, -2, '__mode') module.lua_setmetatable(state.address, -2) - this.pushedValueCacheReference = BigInt(module.luaL_ref(state.address, LUA_REGISTRYINDEX)) + this.pushedValueCacheReference = module.luaL_ref(state.address, LUA_REGISTRYINDEX) } public isType(_thread: Thread, _index: number, type: LuaType, name?: string): boolean { @@ -37,8 +37,9 @@ export default abstract class LuaTypeExtension { } /** - * Releases what the extension owns outside Lua: the function pointers it took from - * `addFunction`, and any JS side bookkeeping. + * Releases what the extension owns outside Lua: function pointers it took from `addFunction`, + * and any JS side bookkeeping. Nothing, for an extension that has no more than + * {@link defineMetatable} gives it; one that owns more overrides this and calls `super.close()`. * * Called only from {@link LuaState.close}, and only after `lua_close` has already run every * `__gc` handler and freed the state along with its registry and every thread anchored there. @@ -46,78 +47,109 @@ export default abstract class LuaTypeExtension { * but nothing may touch the state itself -- unreffing a registry slot or calling into a thread * at this point is a use after free. */ - public abstract close(): void + public close(): void { + // The __gc handler belongs to the module, so there is nothing of the base's to release. + } /** - * The `__gc` handler every reference holding extension needs. The caller owns the returned - * pointer and has to release it with the module's `removeFunction` in {@link close}. + * Creates the metatable named after this extension: protected from `getmetatable` and + * `setmetatable` in Lua, with the `__gc` that releases the reference a box pushed by + * {@link pushReference} holds, and with each of `metamethods` set on it. A metamethod is pushed + * the way any value is, so a function becomes a Lua function and a plain object a table -- by + * way of the extensions registered so far, which is why the built-ins register in dependency + * order. + * + * Only fills a metatable it created. A second extension registered under the same name on the + * same state finds the first one's and leaves it alone. */ - protected createGcFunction(): number { - return this.state.module.addFunction((calledL: LuaAddress) => { - // Throws a lua error which does a jump if it does not match. - const userDataPointer = this.state.module.luaL_checkudata(calledL, 1, this.name) - const referencePointer = this.state.module.readPointer(userDataPointer) - this.state.module.unref(referencePointer) - - return LuaReturn.Ok - }, 'ii') + protected defineMetatable(metamethods: Record = {}): void { + const state = this.state + const module = state.module + const L = state.address + + if (module.luaL_newmetatable(L, this.name)) { + const metatableIndex = module.lua_gettop(L) + + module.lua_pushstring(L, 'protected metatable') + module.lua_setfield(L, metatableIndex, '__metatable') + + module.lua_pushcclosure(L, module.referenceGcFunction(), 0) + module.lua_setfield(L, metatableIndex, '__gc') + + for (const key in metamethods) { + state.pushValue(metamethods[key]) + module.lua_setfield(L, metatableIndex, key) + } + } + // Whether created here or found, the metatable is on the stack. + module.lua_pop(L, 1) } // A base implementation that assumes user data serialisation public getValue(thread: Thread, index: number, _cache?: LuaGetCache): T { - const refUserdata = thread.module.luaL_testudata(thread.address, index, this.name) - if (!refUserdata) { + const value = thread.module.getReferenceBox(thread.address, index, this.name) + if (value === undefined) { throw new Error(`data does not have the expected metatable: ${this.name}`) } - const referencePointer = thread.module.readPointer(refUserdata) - return thread.module.getRef(referencePointer) as T + return value as T } // Return false if type not matched, otherwise true. This base method does not // check the type. That must be done by the class extending this. public pushValue(thread: Thread, decoratedValue: Decoration, _cache?: LuaPushCache): boolean { - const { target } = decoratedValue + this.pushReference(thread, decoratedValue.target) + return true + } + + /** + * Pushes `referent` boxed in a userdata carrying this extension's metatable -- or, if Lua still + * holds the value pushed for it before, that same value, so a JS value pushed twice is one value + * in Lua. With `closure`, a C function pointer, what is pushed and cached is instead a closure + * over the box, which it sees as its first upvalue. + */ + protected pushReference(thread: Thread, referent: unknown, closure?: number): void { const module = thread.module + const L = thread.address + const cachedType = closure === undefined ? LuaType.Userdata : LuaType.Function // The cache table stays at the bottom for the whole push, so the probe and the store // below share the one registry fetch. - module.lua_rawgeti(thread.address, LUA_REGISTRYINDEX, this.pushedValueCacheReference) + module.lua_rawgeti(L, LUA_REGISTRYINDEX, this.pushedValueCacheReference) - const existingIndex = module.getRefIndex(target) + const existingIndex = module.getRefIndex(referent) if (existingIndex !== undefined) { - if (module.lua_rawgeti(thread.address, -1, BigInt(existingIndex)) === LuaType.Userdata) { - // Drop the cache table, keeping the userdata. - module.lua_remove(thread.address, -2) - return true + if (module.lua_rawgeti(L, -1, existingIndex) === cachedType) { + // Drop the cache table, keeping the value. + module.lua_remove(L, -2) + return } // Pop the miss; the cache table stays for the store. thread.pop(1) } - const pointer = module.ref(target) - // 4 = size of pointer in wasm. - const userDataPointer = module.lua_newuserdatauv(thread.address, PointerSize, 0) - module.writePointer(userDataPointer, pointer) + const pointer = module.pushReferenceBox(L, referent) - if (LuaType.Nil === module.luaL_getmetatable(thread.address, this.name)) { - // Pop the pushed nil value, the user data and the cache table. The reference has to be - // released by hand: without a metatable the userdata has no __gc, so nothing else ever - // would. + if (LuaType.Nil === module.luaL_getmetatable(L, this.name)) { + // Pop the pushed nil value, the box and the cache table. The reference has to be + // released by hand: without a metatable the box has no __gc, so nothing else ever would. thread.pop(3) module.unref(pointer) throw new Error(`metatable not found: ${this.name}`) } - // Set as the metatable for the userdata. - // -1 is the metatable, -2 is the user data. - module.lua_setmetatable(thread.address, -2) + // -1 is the metatable, -2 is the box. + module.lua_setmetatable(L, -2) - // Remember the userdata for the next push of the same value, then drop the cache table - // from under it. - module.lua_pushvalue(thread.address, -1) - module.lua_rawseti(thread.address, -3, BigInt(pointer)) - module.lua_remove(thread.address, -2) + if (closure !== undefined) { + // Pops the box and pushes the closure holding it as an upvalue. + module.lua_pushcclosure(L, closure, 1) + } - return true + // Remember the value for the next push of the same referent, then drop the cache table + // from under it. Weak, so this never outlives the value: once Lua collects it the box goes + // too, and its __gc releases the reference. + module.lua_pushvalue(L, -1) + module.lua_rawseti(L, -3, pointer) + module.lua_remove(L, -2) } } diff --git a/src/type-extensions/error.ts b/src/type-extensions/error.ts index 9d6a706..715ad1f 100644 --- a/src/type-extensions/error.ts +++ b/src/type-extensions/error.ts @@ -1,28 +1,14 @@ -import { Decoration } from '../decoration' +import type { Decoration } from '../decoration' import type LuaState from '../state' import type Thread from '../thread' import TypeExtension from '../type-extension' class ErrorTypeExtension extends TypeExtension { - private gcPointer: number - public constructor(state: LuaState, injectObject: boolean) { super(state, 'js_error') - this.gcPointer = this.createGcFunction() - - if (state.module.luaL_newmetatable(state.address, this.name)) { - const metatableIndex = state.module.lua_gettop(state.address) - - // Mark it as uneditable - state.module.lua_pushstring(state.address, 'protected metatable') - state.module.lua_setfield(state.address, metatableIndex, '__metatable') - - // Add the gc function - state.module.lua_pushcclosure(state.address, this.gcPointer, 0) - state.module.lua_setfield(state.address, metatableIndex, '__gc') - - state.pushValue((jsRefError: Error, key: unknown) => { + this.defineMetatable({ + __index: (jsRefError: Error, key: unknown) => { switch (key) { case 'message': return jsRefError.message @@ -33,19 +19,11 @@ class ErrorTypeExtension extends TypeExtension { default: return undefined } - }) - state.module.lua_setfield(state.address, metatableIndex, '__index') - - // Add a tostring method that returns the message. - state.pushValue((jsRefError: Error) => { - // The message rather than toString to avoid the Error: prefix being - // added. This fits better with Lua errors. - return jsRefError.message - }) - state.module.lua_setfield(state.address, metatableIndex, '__tostring') - } - // Pop the metatable from the stack. - state.module.lua_pop(state.address, 1) + }, + // The message rather than toString to avoid the Error: prefix being + // added. This fits better with Lua errors. + __tostring: (jsRefError: Error) => jsRefError.message, + }) if (injectObject) { // Lastly create a static Error constructor. @@ -71,10 +49,6 @@ class ErrorTypeExtension extends TypeExtension { } return super.pushValue(thread, decoration) } - - public close(): void { - this.state.module.removeFunction(this.gcPointer) - } } export default function createTypeExtension(state: LuaState, injectObject: boolean): TypeExtension { diff --git a/src/type-extensions/function.ts b/src/type-extensions/function.ts index b3613d7..e78fe3d 100644 --- a/src/type-extensions/function.ts +++ b/src/type-extensions/function.ts @@ -4,7 +4,7 @@ import MultiReturn from '../multireturn' import RawResult from '../raw-result' import type Thread from '../thread' import TypeExtension from '../type-extension' -import { LUA_REGISTRYINDEX, LuaReturn, type LuaAddress, LuaType, PointerSize } from '../types' +import { LUA_REGISTRYINDEX, LuaReturn, type LuaAddress, LuaType } from '../types' import { isEmscriptenUnwind } from '../utils' export type FunctionType = (...args: any[]) => Promise | any @@ -23,7 +23,6 @@ class FunctionTypeExtension extends TypeExtension { } }) - private gcPointer: number private functionWrapper: number private callbackContext: Thread /** @@ -48,20 +47,9 @@ class FunctionTypeExtension extends TypeExtension { this.callbackContext = state.newAnchoredThread().thread this.pooledCallThread = this.callbackContext.newAnchoredThread().thread - this.gcPointer = this.createGcFunction() - - // Creates metatable if it doesn't exist, always pushes it onto the stack. - if (state.module.luaL_newmetatable(state.address, this.name)) { - state.module.lua_pushstring(state.address, '__gc') - state.module.lua_pushcclosure(state.address, this.gcPointer, 0) - state.module.lua_settable(state.address, -3) - - state.module.lua_pushstring(state.address, '__metatable') - state.module.lua_pushstring(state.address, 'protected metatable') - state.module.lua_settable(state.address, -3) - } - // Pop the metatable from the stack. - state.module.lua_pop(state.address, 1) + // Nothing but the box's own __gc: the metatable goes on the upvalue, not on the closure + // Lua sees, so no metamethod on it could ever be reached. + this.defineMetatable() this.functionWrapper = state.module.addFunction((calledL: LuaAddress) => { const calledThread = state.stateToThread(calledL) @@ -72,8 +60,7 @@ class FunctionTypeExtension extends TypeExtension { // upvalue replaced through the debug library -- falls back to it, for the error the C // API would have raised. const upvalueIndex = state.module.lua_upvalueindex(1) - const refUserdata = state.module.lua_touserdata(calledL, upvalueIndex) - const reference = refUserdata ? state.module.getRef(state.module.readPointer(refUserdata)) : undefined + const reference = state.module.getReferenceBox(calledL, upvalueIndex) let target: FunctionType let decorationOptions: DecorationOptions if (typeof reference === 'function') { @@ -133,7 +120,6 @@ class FunctionTypeExtension extends TypeExtension { } public close(): void { - this.state.module.removeFunction(this.gcPointer) this.state.module.removeFunction(this.functionWrapper) // Doesn't destroy the Lua threads, just function pointers. The threads themselves went // with the state. @@ -181,8 +167,6 @@ class FunctionTypeExtension extends TypeExtension { return false } - const module = thread.module - // It's surprisingly inefficient to map JS functions to C functions so this creates a reference to the // function which stays solely in JS. The cfunction called from Lua is created at the top of the class // and it accesses the JS data through an upvalue. @@ -195,49 +179,7 @@ class FunctionTypeExtension extends TypeExtension { // the same function under different options stays distinct, as its behaviour is. const referent: unknown = affectsCall(decoration.options) ? decoration : decoration.target - // The cache table stays at the bottom for the whole push, so the probe and the store - // below share the one registry fetch. - module.lua_rawgeti(thread.address, LUA_REGISTRYINDEX, this.pushedValueCacheReference) - - const existingIndex = module.getRefIndex(referent) - if (existingIndex !== undefined) { - if (module.lua_rawgeti(thread.address, -1, BigInt(existingIndex)) === LuaType.Function) { - // Drop the cache table, keeping the closure. - module.lua_remove(thread.address, -2) - return true - } - // Pop the miss; the cache table stays for the store. - thread.pop(1) - } - - const pointer = module.ref(referent) - // 4 = size of pointer in wasm. - const userDataPointer = module.lua_newuserdatauv(thread.address, PointerSize, 0) - module.writePointer(userDataPointer, pointer) - - if (LuaType.Nil === module.luaL_getmetatable(thread.address, this.name)) { - // Pop the pushed nil, the userdata and the cache table. The reference has to be - // released by hand: without a metatable the userdata has no __gc, so nothing else ever - // would. - thread.pop(3) - module.unref(pointer) - throw new Error(`metatable not found: ${this.name}`) - } - - // Set as the metatable for the function. - // -1 is the metatable, -2 is the userdata - module.lua_setmetatable(thread.address, -2) - - // Pass 1 to associate the closure with the userdata, pops the userdata. - module.lua_pushcclosure(thread.address, this.functionWrapper, 1) - - // Remember the closure for the next push of the same function, then drop the cache table - // from under it. Weak, so this never outlives the closure: once Lua collects it the - // userdata upvalue goes too, and its __gc releases the reference. - module.lua_pushvalue(thread.address, -1) - module.lua_rawseti(thread.address, -3, BigInt(pointer)) - module.lua_remove(thread.address, -2) - + this.pushReference(thread, referent, this.functionWrapper) return true } @@ -246,8 +188,6 @@ class FunctionTypeExtension extends TypeExtension { thread.module.lua_pushvalue(thread.address, index) // Create a reference to the function which pops it from the stack const func = thread.module.luaL_ref(thread.address, LUA_REGISTRYINDEX) - // The reference never changes, so the bigint the i64 parameter needs is built once. - const funcReference = BigInt(func) const jsFunc = (...args: any[]): any => { // Calling a function would ideally be in the Lua context that's calling it. For example if the JS function @@ -266,7 +206,7 @@ class FunctionTypeExtension extends TypeExtension { const callThread = this.acquireCallThread() let failed = false try { - const internalType = callThread.module.lua_rawgeti(callThread.address, LUA_REGISTRYINDEX, funcReference) + const internalType = callThread.module.lua_rawgeti(callThread.address, LUA_REGISTRYINDEX, func) if (internalType !== LuaType.Function) { const callMetafieldType = callThread.module.luaL_getmetafield(callThread.address, -1, '__call') callThread.pop() @@ -289,10 +229,8 @@ class FunctionTypeExtension extends TypeExtension { } callThread.assertOk(status) - if (callThread.getTop() > 0) { - return callThread.getValue(-1) - } - return undefined + // Asking for one result leaves exactly one, nil included, so the top is where it is. + return callThread.getValue(1) } catch (err) { failed = true throw err diff --git a/src/type-extensions/null.ts b/src/type-extensions/null.ts index 1ea7f96..a35db5c 100644 --- a/src/type-extensions/null.ts +++ b/src/type-extensions/null.ts @@ -1,44 +1,24 @@ -import { Decoration } from '../decoration' +import type { Decoration } from '../decoration' import type LuaState from '../state' import type Thread from '../thread' import TypeExtension from '../type-extension' import { LUA_REGISTRYINDEX } from '../types' class NullTypeExtension extends TypeExtension { - private gcPointer: number private nullReference: number public constructor(state: LuaState) { super(state, 'js_null') - this.gcPointer = this.createGcFunction() + this.defineMetatable({ + __index: () => undefined, + __tostring: () => 'null', + __eq: (self: unknown, other: unknown) => self === other, + }) - if (state.module.luaL_newmetatable(state.address, this.name)) { - const metatableIndex = state.module.lua_gettop(state.address) - - // Mark it as uneditable - state.module.lua_pushstring(state.address, 'protected metatable') - state.module.lua_setfield(state.address, metatableIndex, '__metatable') - - // Add the gc function - state.module.lua_pushcclosure(state.address, this.gcPointer, 0) - state.module.lua_setfield(state.address, metatableIndex, '__gc') - - state.pushValue(() => undefined) - state.module.lua_setfield(state.address, metatableIndex, '__index') - - state.pushValue(() => 'null') - state.module.lua_setfield(state.address, metatableIndex, '__tostring') - - state.pushValue((self: unknown, other: unknown) => self === other) - state.module.lua_setfield(state.address, metatableIndex, '__eq') - } - // Pop the metatable from the stack. - state.module.lua_pop(state.address, 1) - - // Create a new table, this is unique and will be the "null" value by attaching the - // metatable created above. The first argument is the target, the second options. - super.pushValue(state, new Decoration({}, {})) + // A box like any other, around an object nothing else ever holds, is what makes the sentinel + // unique: it carries the metatable above, so it reads back as null. + this.pushReference(state, {}) // Lua code is free to reassign the `null` global, so marshalling anchors the sentinel in // the registry instead of looking it up by name. @@ -63,10 +43,6 @@ class NullTypeExtension extends TypeExtension { thread.module.lua_rawgeti(thread.address, LUA_REGISTRYINDEX, BigInt(this.nullReference)) return true } - - public close(): void { - this.state.module.removeFunction(this.gcPointer) - } } export default function createTypeExtension(state: LuaState): TypeExtension { diff --git a/src/type-extensions/promise.ts b/src/type-extensions/promise.ts index 63e8c4a..5d5e81c 100644 --- a/src/type-extensions/promise.ts +++ b/src/type-extensions/promise.ts @@ -1,4 +1,4 @@ -import { Decoration } from '../decoration' +import { decorate, type Decoration } from '../decoration' import type LuaState from '../state' import MultiReturn from '../multireturn' import RawResult from '../raw-result' @@ -6,15 +6,25 @@ import type Thread from '../thread' import TypeExtension from '../type-extension' import type { LuaAddress } from '../types' import { isPromise } from '../utils' -import { decorate } from '../decoration' /** The half of an in flight `:await()` the continuation needs once the promise has settled. */ interface PendingAwait { result: { status: 'fulfilled' | 'rejected'; value: any } | undefined } +/** + * A bare thenable reaches here too, and only `then` is guaranteed on one. Adopting it into a real + * promise is what makes catch/finally/await work on it, and is a no-op for the native promises + * that make up almost every case. + */ +const asPromise = (self: unknown): Promise => { + if (!isPromise(self)) { + throw new Error('self instance is not a promise') + } + return Promise.resolve(self) +} + class PromiseTypeExtension extends TypeExtension> { - private gcPointer: number /** * Keyed by the address of the thread parked in the await. A thread suspended in `lua_yieldk` * cannot reach another `:await()`, so at most one is ever in flight per thread. @@ -30,7 +40,6 @@ class PromiseTypeExtension extends TypeExtension> { public constructor(state: LuaState, injectObject: boolean) { super(state, 'js_promise') - this.gcPointer = this.createGcFunction() this.continuancePointer = state.module.addFunction((continuanceState: LuaAddress): number => { const pending = this.pendingAwaits.get(continuanceState) if (!pending) { @@ -71,28 +80,10 @@ class PromiseTypeExtension extends TypeExtension> { } }, 'iiii') - if (state.module.luaL_newmetatable(state.address, this.name)) { - const metatableIndex = state.module.lua_gettop(state.address) - - // Mark it as uneditable - state.module.lua_pushstring(state.address, 'protected metatable') - state.module.lua_setfield(state.address, metatableIndex, '__metatable') - - // Add the gc function - state.module.lua_pushcclosure(state.address, this.gcPointer, 0) - state.module.lua_setfield(state.address, metatableIndex, '__gc') - - // A bare thenable reaches here too, and only `then` is guaranteed on one. Adopting it - // into a real promise is what makes catch/finally/await work on it, and is a no-op for - // the native promises that make up almost every case. - const asPromise = (self: unknown): Promise => { - if (!isPromise(self)) { - throw new Error('self instance is not a promise') - } - return Promise.resolve(self) - } - - state.pushValue({ + this.defineMetatable({ + // A plain object, which the table extension (registered before this one) copies into a + // Lua table of methods. + __index: { next: (self: unknown, ...args: Parameters['then']>) => asPromise(self).then(...args), catch: (self: unknown, ...args: Parameters['catch']>) => asPromise(self).catch(...args), finally: (self: unknown, ...args: Parameters['finally']>) => asPromise(self).finally(...args), @@ -125,14 +116,9 @@ class PromiseTypeExtension extends TypeExtension> { }, { receiveThread: true }, ), - }) - state.module.lua_setfield(state.address, metatableIndex, '__index') - - state.pushValue((self: Promise, other: Promise) => self === other) - state.module.lua_setfield(state.address, metatableIndex, '__eq') - } - // Pop the metatable from the stack. - state.module.lua_pop(state.address, 1) + }, + __eq: (self: Promise, other: Promise) => self === other, + }) if (injectObject) { // Lastly create a static Promise constructor. @@ -150,8 +136,8 @@ class PromiseTypeExtension extends TypeExtension> { } } - public close(): void { - this.state.module.removeFunction(this.gcPointer) + public override close(): void { + super.close() this.state.module.removeFunction(this.continuancePointer) // A coroutine abandoned mid await never reaches its continuation, so its record is still // here holding whatever the promise settled with. Nothing tells us when Lua's own GC took diff --git a/src/type-extensions/proxy.ts b/src/type-extensions/proxy.ts index b0462b9..38d2382 100644 --- a/src/type-extensions/proxy.ts +++ b/src/type-extensions/proxy.ts @@ -3,7 +3,6 @@ import type LuaState from '../state' import MultiReturn from '../multireturn' import type Thread from '../thread' import TypeExtension from '../type-extension' -import { LuaType } from '../types' import { isPromise } from '../utils' const isClass = (target: unknown): target is new (...args: any[]) => any => @@ -16,75 +15,42 @@ const isClassLike = (target: unknown): boolean => { return isClass(target) || Object.getOwnPropertyNames(target.prototype).length > 1 } +/** + * Lua indexes js objects with the key as given, except that a number is mapped from Lua's 1 based + * indexing to JS's 0 -- which matters most for ipairs, which calls __index with 1, 2, 3... until + * it gets nil. + */ +const toJsKey = (key: unknown): string | number => { + switch (typeof key) { + case 'number': + return key - 1 + case 'string': + return key + default: + throw new Error('Only strings or numbers can index js objects') + } +} + class ProxyTypeExtension extends TypeExtension { - private readonly gcPointer: number private readonly boundMethods = new WeakMap any, Decoration<(...args: any[]) => any>>>() public constructor(state: LuaState) { super(state, 'js_proxy') - this.gcPointer = this.createGcFunction() - - if (state.module.luaL_newmetatable(state.address, this.name)) { - const metatableIndex = state.module.lua_gettop(state.address) - - // Mark it as uneditable - state.module.lua_pushstring(state.address, 'protected metatable') - state.module.lua_setfield(state.address, metatableIndex, '__metatable') - - // Add the gc function - state.module.lua_pushcclosure(state.address, this.gcPointer, 0) - state.module.lua_setfield(state.address, metatableIndex, '__gc') - - state.pushValue((self: any, key: unknown) => { - switch (typeof key) { - case 'number': - // Map from Lua's 1 based indexing to JS's 0. - // This is especially important here because ipairs just calls - // __index with 1, 2, 3, 4 etc until there's a null. - key = key - 1 - // Fallthrough - case 'string': - break - default: - throw new Error('Only strings or numbers can index js objects') - } - - const value = self[key as string | number] + this.defineMetatable({ + __index: (self: any, key: unknown) => { + const value = self[toJsKey(key)] if (typeof value === 'function') { return this.bindMethod(self, value as (...args: any[]) => any) } - return value - }) - state.module.lua_setfield(state.address, metatableIndex, '__index') - - state.pushValue((self: any, key: unknown, value: any) => { - switch (typeof key) { - case 'number': - // Map from Lua's 1 based indexing to JS's 0. - key = key - 1 - // Fallthrough - case 'string': - break - default: - throw new Error('Only strings or numbers can index js objects') - } - self[key as string | number] = value - }) - state.module.lua_setfield(state.address, metatableIndex, '__newindex') - - state.pushValue((self: any) => { - return self.toString?.() ?? typeof self - }) - state.module.lua_setfield(state.address, metatableIndex, '__tostring') - - state.pushValue((self: any) => { - return self.length || 0 - }) - state.module.lua_setfield(state.address, metatableIndex, '__len') - - state.pushValue((self: any) => { + }, + __newindex: (self: any, key: unknown, value: any) => { + self[toJsKey(key)] = value + }, + __tostring: (self: any) => self.toString?.() ?? typeof self, + __len: (self: any) => self.length || 0, + __pairs: (self: any) => { const isArray = Array.isArray(self) const keys = isArray ? self : Object.keys(self) let i = 0 @@ -101,25 +67,15 @@ class ProxyTypeExtension extends TypeExtension { self, null, ) - }) - state.module.lua_setfield(state.address, metatableIndex, '__pairs') - - state.pushValue((self: any, other: any) => { - return self === other - }) - state.module.lua_setfield(state.address, metatableIndex, '__eq') - - state.pushValue((self: any, ...args: any[]) => { + }, + __eq: (self: any, other: any) => self === other, + __call: (self: any, ...args: any[]) => { if (args[0] === self) { args.shift() } return isClass(self) ? new self(...args) : self(...args) - }) - state.module.lua_setfield(state.address, metatableIndex, '__call') - } - - // Pop the metatable from the stack. - state.module.lua_pop(state.address, 1) + }, + }) } private bindMethod(self: object, method: (...args: any[]) => any): Decoration<(...args: any[]) => any> { @@ -136,15 +92,9 @@ class ProxyTypeExtension extends TypeExtension { return bound } - public isType(_thread: Thread, _index: number, type: LuaType, name?: string): boolean { - // Capture proxied types and functions returned by lua. - return type === LuaType.Userdata && name === this.name - } - public getValue(thread: Thread, index: number): any { - const refUserdata = thread.module.lua_touserdata(thread.address, index) - const referencePointer = thread.module.readPointer(refUserdata) - return thread.module.getRef(referencePointer) + // isType has already matched the metatable, so the check is not paid for again here. + return thread.module.getReferenceBox(thread.address, index) } public pushValue(thread: Thread, decoratedValue: Decoration): boolean { @@ -175,10 +125,6 @@ class ProxyTypeExtension extends TypeExtension { return super.pushValue(thread, decoratedValue) } - - public close(): void { - this.state.module.removeFunction(this.gcPointer) - } } export default function createTypeExtension(state: LuaState): TypeExtension { diff --git a/src/type-extensions/table.ts b/src/type-extensions/table.ts index 611ffe7..1ce2d3a 100644 --- a/src/type-extensions/table.ts +++ b/src/type-extensions/table.ts @@ -11,10 +11,6 @@ class TableTypeExtension extends TypeExtension { super(state, 'js_table') } - public close(): void { - // Nothing to do - } - public isType(_thread: Thread, _index: number, type: LuaType): boolean { return type === LuaType.Table } @@ -46,7 +42,7 @@ class TableTypeExtension extends TypeExtension { const seenMap: LuaPushCache = cache ?? new Map() const existingReference = seenMap.get(target) if (existingReference !== undefined) { - thread.module.lua_rawgeti(thread.address, LUA_REGISTRYINDEX, BigInt(existingReference)) + thread.module.lua_rawgeti(thread.address, LUA_REGISTRYINDEX, existingReference) return true } @@ -57,7 +53,7 @@ class TableTypeExtension extends TypeExtension { thread.module.lua_createtable(thread.address, arrayCount, keyCount) const ref = thread.module.luaL_ref(thread.address, LUA_REGISTRYINDEX) seenMap.set(target, ref) - thread.module.lua_rawgeti(thread.address, LUA_REGISTRYINDEX, BigInt(ref)) + thread.module.lua_rawgeti(thread.address, LUA_REGISTRYINDEX, ref) } if (Array.isArray(target)) { @@ -66,7 +62,7 @@ class TableTypeExtension extends TypeExtension { for (let i = 0; i < target.length; i++) { thread.pushValue(target[i], seenMap) // Raw, so the table being built cannot be observed through metamethods. - thread.module.lua_rawseti(thread.address, tableIndex, BigInt(i + 1)) + thread.module.lua_rawseti(thread.address, tableIndex, i + 1) } } else { // A for..in loop would also walk the prototype chain and copy inherited members. diff --git a/src/type-extensions/userdata.ts b/src/type-extensions/userdata.ts index 4a87082..fd8432d 100644 --- a/src/type-extensions/userdata.ts +++ b/src/type-extensions/userdata.ts @@ -1,41 +1,18 @@ -import { Decoration } from '../decoration' +import type { Decoration } from '../decoration' import type LuaState from '../state' import type Thread from '../thread' import TypeExtension from '../type-extension' -import { LuaType } from '../types' class UserdataTypeExtension extends TypeExtension { - private readonly gcPointer: number - public constructor(state: LuaState) { super(state, 'js_userdata') - - this.gcPointer = this.createGcFunction() - - if (state.module.luaL_newmetatable(state.address, this.name)) { - const metatableIndex = state.module.lua_gettop(state.address) - - // Mark it as uneditable - state.module.lua_pushstring(state.address, 'protected metatable') - state.module.lua_setfield(state.address, metatableIndex, '__metatable') - - // Add the gc function - state.module.lua_pushcclosure(state.address, this.gcPointer, 0) - state.module.lua_setfield(state.address, metatableIndex, '__gc') - } - - // Pop the metatable from the stack. - state.module.lua_pop(state.address, 1) - } - - public isType(_thread: Thread, _index: number, type: LuaType, name?: string): boolean { - return type === LuaType.Userdata && name === this.name + // Opaque: nothing but the box's own __gc. + this.defineMetatable() } public getValue(thread: Thread, index: number): any { - const refUserdata = thread.module.lua_touserdata(thread.address, index) - const referencePointer = thread.module.readPointer(refUserdata) - return thread.module.getRef(referencePointer) + // isType has already matched the metatable, so the check is not paid for again here. + return thread.module.getReferenceBox(thread.address, index) } public pushValue(thread: Thread, decoratedValue: Decoration): boolean { @@ -45,10 +22,6 @@ class UserdataTypeExtension extends TypeExtension { return super.pushValue(thread, decoratedValue) } - - public close(): void { - this.state.module.removeFunction(this.gcPointer) - } } export default function createTypeExtension(state: LuaState): TypeExtension { diff --git a/test/api.test.js b/test/api.test.js index fc4b6f1..a1eea99 100644 --- a/test/api.test.js +++ b/test/api.test.js @@ -1,5 +1,5 @@ import { expect } from 'chai' -import { LuaMultiReturn, LuaRawResult, LuaReturn, LuaTypeExtension, decorate } from '../dist/index.js' +import { LuaMultiReturn, LuaRawResult, LuaReturn, LuaType, LuaTypeExtension, decorate } from '../dist/index.js' import { getLua, getState } from './utils.js' describe('MultiReturn', () => { @@ -144,20 +144,7 @@ describe('Custom type extensions', () => { class PointExtension extends LuaTypeExtension { constructor(state) { super(state, 'js_point') - this.gcPointer = this.createGcFunction() - - if (state.module.luaL_newmetatable(state.address, this.name)) { - const metatableIndex = state.module.lua_gettop(state.address) - state.module.lua_pushcclosure(state.address, this.gcPointer, 0) - state.module.lua_setfield(state.address, metatableIndex, '__gc') - state.pushValue((point) => `Point(${point.x})`) - state.module.lua_setfield(state.address, metatableIndex, '__tostring') - } - state.module.lua_pop(state.address, 1) - } - - close() { - this.state.module.emscripten.removeFunction(this.gcPointer) + this.defineMetatable({ __tostring: (point) => `Point(${point.x})` }) } pushValue(thread, decoration) { @@ -176,6 +163,19 @@ describe('Custom type extensions', () => { expect(state.get('pt')).to.be.equal(point) }) + it('should get a protected metatable and release the reference once collected', async () => { + using state = await getState() + state.registerTypeExtension(6, new PointExtension(state)) + const point = new Point(1) + state.set('pt', point) + + expect(await state.doString('return getmetatable(pt)')).to.be.equal('protected metatable') + expect(state.module.getRefIndex(point)).to.not.be.undefined + + await state.doString('pt = nil collectgarbage() collectgarbage()') + expect(state.module.getRefIndex(point)).to.be.undefined + }) + it('should leave values it refuses to the built in handling', async () => { using state = await getState() state.registerTypeExtension(6, new PointExtension(state)) @@ -314,6 +314,31 @@ describe('Lua integer arguments', () => { expect(await state.doString('return table.concat(letters, ",")')).to.be.equal('a,b,c') }) + it('should take a raw table index as a number', async () => { + using state = await getState() + state.module.lua_createtable(state.address, 3, 0) + + for (const [index, text] of ['a', 'b', 'c'].entries()) { + state.pushValue(text) + state.module.lua_rawseti(state.address, -2, index + 1) + } + state.module.lua_setglobal(state.address, 'letters') + + expect(await state.doString('return table.concat(letters, ",")')).to.be.equal('a,b,c') + expect(state.module.lua_getglobal(state.address, 'letters')).to.be.equal(LuaType.Table) + expect(state.module.lua_rawgeti(state.address, -1, 2)).to.be.equal(LuaType.String) + expect(state.getValue(-1)).to.be.equal('b') + }) + + it('should refuse a number that is not a safe integer where a lua_Integer is expected', async () => { + using state = await getState() + + expect(() => state.module.lua_pushinteger(state.address, 1.5)).to.throw(RangeError) + expect(() => state.module.lua_pushinteger(state.address, 2 ** 53)).to.throw(RangeError) + expect(() => state.module.lua_pushinteger(state.address, Number.NaN)).to.throw(RangeError) + expect(state.getTop()).to.be.equal(0) + }) + it('should reach an index a double cannot hold exactly through a bigint', async () => { using state = await getState() const index = 2n ** 62n diff --git a/utils/build-wasm.sh b/utils/build-wasm.sh index 255c7cd..fbdd773 100755 --- a/utils/build-wasm.sh +++ b/utils/build-wasm.sh @@ -10,9 +10,7 @@ if [ "$1" == "dev" ]; then extension=(-O0 -g3 -s ASSERTIONS=1 -s SAFE_HEAP=1 -s STACK_OVERFLOW_CHECK=2) else - # TEXTDECODER=1 keeps Emscripten's short string decode path, which -Oz would otherwise drop - # in favour of always calling TextDecoder. LuaModule.readString relies on it. - extension=(-Oz -fno-inline-functions -DLUA_USE_JUMPTABLE=0 -s TEXTDECODER=1 -s BINARYEN_EXTRA_PASSES=gufa-optimizing,converge) + extension=(-Oz -fno-inline-functions -DLUA_USE_JUMPTABLE=0 -s BINARYEN_EXTRA_PASSES=gufa-optimizing,converge) fi # Everything that is not about the filesystem, shared by both glues below so they can share one From cd1845fd90346d52d166f446274831594e5254e5 Mon Sep 17 00:00:00 2001 From: ceifa Date: Sat, 5 Sep 2026 16:10:51 -0300 Subject: [PATCH 62/83] fix hook counter surpassing limit --- .claude/worktrees/js-size | 1 - src/thread.ts | 11 ++++++++--- test/limits.test.js | 16 ++++++++++++++++ 3 files changed, 24 insertions(+), 4 deletions(-) delete mode 160000 .claude/worktrees/js-size diff --git a/.claude/worktrees/js-size b/.claude/worktrees/js-size deleted file mode 160000 index 40c8c27..0000000 --- a/.claude/worktrees/js-size +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 40c8c270cbf6213ddb629e896d938b90c40e439c diff --git a/src/thread.ts b/src/thread.ts index 5a433bf..1fdcf58 100755 --- a/src/thread.ts +++ b/src/thread.ts @@ -668,7 +668,7 @@ export default class Thread { this.hookFunctionPointer = this.module.addFunction((hookL: LuaAddress): void => { // Reads this.limits rather than closing over them, so a hook allocated for an // earlier configuration still honours the current one. - const error = this.checkHookLimits() + const error = this.checkHookLimits(hookL) if (error) { this.rootThread.pendingInterrupt = error this.module.lua_pushlightuserdata(hookL, this.module.interruptToken) @@ -680,13 +680,18 @@ export default class Thread { this.module.lua_sethook(this.address, this.hookFunctionPointer, LuaEventMasks.Count, this.hookCount) } - private checkHookLimits(): LuaInterruptError | undefined { + private checkHookLimits(hookL: LuaAddress): LuaInterruptError | undefined { const { maxInstructions } = this.limits if (maxInstructions !== undefined) { this.instructionsUsed += this.hookCount - if (this.instructionsUsed > maxInstructions) { + const remaining = maxInstructions - this.instructionsUsed + if (remaining <= 0) { return new LuaInstructionLimitError(`thread exceeded its budget of ${maxInstructions} instructions`) } + if (remaining < this.hookCount) { + this.hookCount = remaining + this.module.lua_sethook(hookL, this.hookFunctionPointer ?? null, LuaEventMasks.Count, remaining) + } } return this.checkYieldLimits() } diff --git a/test/limits.test.js b/test/limits.test.js index a666a36..dd4416d 100644 --- a/test/limits.test.js +++ b/test/limits.test.js @@ -4,6 +4,8 @@ import { getState } from './utils.js' describe('Run limits', () => { const busyLoop = 'local x = 0 for i = 1, 1e9 do x = x + 1 end return x' + const countingLoop = 'i = 0 while true do i = i + 1 end' + const instructionsPerIteration = 4 it('timeout interrupts a tight loop', async function () { this.timeout(20_000) @@ -19,6 +21,20 @@ describe('Run limits', () => { await expect(state.doString(busyLoop, { maxInstructions: 5_000 })).to.eventually.be.rejectedWith(LuaInstructionLimitError) }) + it('maxInstructions stops inside the budget rather than a hook period past it', async function () { + this.timeout(20_000) + + for (const maxInstructions of [500, 1_000, 1_500, 5_000]) { + using state = await getState() + + await expect(state.doString(countingLoop, { maxInstructions })).to.eventually.be.rejectedWith(LuaInstructionLimitError) + + const executed = state.get('i') * instructionsPerIteration + expect(executed, `budget of ${maxInstructions}`).to.be.at.most(maxInstructions) + expect(executed, `budget of ${maxInstructions}`).to.be.above(maxInstructions - 2 * instructionsPerIteration) + } + }) + it('an already aborted signal stops the run', async function () { this.timeout(20_000) using state = await getState() From 2bd30a8424310d53b910b5355a8535d31a28dc73 Mon Sep 17 00:00:00 2001 From: ceifa Date: Sat, 5 Sep 2026 16:17:27 -0300 Subject: [PATCH 63/83] remove unnecessary bigint conversion --- bench/interop.js | 14 ++++++++++++++ src/type-extensions/null.ts | 2 +- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/bench/interop.js b/bench/interop.js index 251a431..6f539c8 100644 --- a/bench/interop.js +++ b/bench/interop.js @@ -55,6 +55,19 @@ function createCallLuaFromJsBenchmark(lua) { }) } +function createPushNullBenchmark(lua) { + return withState(lua, { inject: true }, (state) => { + for (let i = 0; i < CALL_COUNT; i++) { + state.pushValue(null) + state.pop() + } + state.pushValue(null) + assert.equal(state.getValue(-1), null) + state.pop() + assert.equal(state.getTop(), 0) + }) +} + function createCallJsFromLuaBenchmark(lua) { return withState(lua, {}, (state) => { state.set('add', (a, b) => a + b) @@ -124,6 +137,7 @@ export async function runInteropBench(options = {}) { { name: 'Call JS from Lua', run: createCallJsFromLuaBenchmark(lua) }, { name: 'Read table into JS', run: createReadTableBenchmark(lua) }, { name: 'Push table into Lua', run: createPushTableBenchmark(lua) }, + { name: 'Push null into Lua', run: createPushNullBenchmark(lua) }, { name: 'Proxy field access from Lua', run: createProxyAccessBenchmark(lua) }, { name: 'doStringSync', run: createDoStringBenchmark(lua) }, ], diff --git a/src/type-extensions/null.ts b/src/type-extensions/null.ts index a35db5c..f4c61c9 100644 --- a/src/type-extensions/null.ts +++ b/src/type-extensions/null.ts @@ -40,7 +40,7 @@ class NullTypeExtension extends TypeExtension { if (decoration.target !== null) { return false } - thread.module.lua_rawgeti(thread.address, LUA_REGISTRYINDEX, BigInt(this.nullReference)) + thread.module.lua_rawgeti(thread.address, LUA_REGISTRYINDEX, this.nullReference) return true } } From 8b2a0fc9c71ac83ad8320ef56f1d76d522816d2a Mon Sep 17 00:00:00 2001 From: ceifa Date: Sat, 5 Sep 2026 19:06:26 -0300 Subject: [PATCH 64/83] better async model --- .oxfmtrc.json | 2 +- .oxlintrc.json | 2 +- README.md | 88 ++-- docs/async-redesign/README.md | 449 ++++++++++++++++++ .../experiments/build-wasm-eh.sh | 222 +++++++++ .../experiments/current-behavior.mjs | 34 ++ .../async-redesign/experiments/jspi-modes.mjs | 98 ++++ docs/async-redesign/experiments/jspi-raw.mjs | 52 ++ docs/async-redesign/experiments/jspi-sp.mjs | 23 + .../async-redesign/experiments/jspi-stack.mjs | 61 +++ docs/async-redesign/experiments/perf-dist.mjs | 25 + docs/async-redesign/experiments/perf-raw.mjs | 60 +++ src/async.ts | 147 ++++++ src/module.ts | 173 +++++++ src/native/wasmoon.c | 58 +++ src/state.ts | 10 +- src/thread.ts | 232 +++++++-- src/type-extension.ts | 12 +- src/type-extensions/function.ts | 65 ++- src/type-extensions/promise.ts | 70 ++- src/types.ts | 9 + src/utils.ts | 10 +- test/async.test.js | 130 +++++ test/bundling.test.js | 2 +- test/promises.test.js | 2 +- test/state.test.js | 10 +- test/utils.js | 8 +- utils/build-wasm.sh | 15 +- 28 files changed, 1950 insertions(+), 119 deletions(-) create mode 100644 docs/async-redesign/README.md create mode 100755 docs/async-redesign/experiments/build-wasm-eh.sh create mode 100644 docs/async-redesign/experiments/current-behavior.mjs create mode 100644 docs/async-redesign/experiments/jspi-modes.mjs create mode 100644 docs/async-redesign/experiments/jspi-raw.mjs create mode 100644 docs/async-redesign/experiments/jspi-sp.mjs create mode 100644 docs/async-redesign/experiments/jspi-stack.mjs create mode 100644 docs/async-redesign/experiments/perf-dist.mjs create mode 100644 docs/async-redesign/experiments/perf-raw.mjs create mode 100644 src/async.ts create mode 100644 src/native/wasmoon.c create mode 100644 test/async.test.js diff --git a/.oxfmtrc.json b/.oxfmtrc.json index 600545a..1095bb1 100644 --- a/.oxfmtrc.json +++ b/.oxfmtrc.json @@ -7,5 +7,5 @@ "printWidth": 140, "tabWidth": 4, "sortPackageJson": false, - "ignorePatterns": ["rolldown.config.*.js"] + "ignorePatterns": ["rolldown.config.*.js", "docs/**"] } diff --git a/.oxlintrc.json b/.oxlintrc.json index c9c4b84..0a9cd20 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -11,7 +11,7 @@ "consistent-function-scoping": "off", "promise/always-return": "off" }, - "ignorePatterns": ["dist/**", "build/**", "rolldown.config.ts", "rolldown.config.*.js", "utils/**"], + "ignorePatterns": ["dist/**", "build/**", "docs/**", "rolldown.config.ts", "rolldown.config.*.js", "utils/**"], "env": { "builtin": true } diff --git a/README.md b/README.md index cee9827..b2e4334 100644 --- a/README.md +++ b/README.md @@ -228,7 +228,7 @@ build. ### Promises -Promises can be await'd from Lua with some caveats detailed in the below section. To await a Promise call `:await()` on it which will yield the Lua execution until the promise completes. +Promises can be `await`'d from Lua by calling `:await()` on them, which parks the Lua execution until the promise settles and then returns its value (or raises its rejection as a Lua error). ```js import { LuaRuntime } from 'wasmoon' @@ -246,60 +246,58 @@ try { } ``` -### Async/Await +### Async engine -It's not possible to await in a callback from JS into Lua. This is a limitation of Lua but there are some workarounds. It can also be encountered when yielding at the top-level of a file. An example where you might encounter this is a snippet like this: +Under the hood there are two engines, chosen automatically at load: + +- **JSPI** (the default where the platform supports it: Chrome/Edge 137+, Firefox 153+, Node 25+). + An `:await()` suspends the whole WebAssembly stack, so it works **anywhere** — inside a + `table.sort` comparator, a `string.gsub` callback, a `promise:next` handler, a coroutine nothing + drives from the host, or a Lua function called back from JS. +- **Coroutine yielding** (the fallback, when JSPI is unavailable). An `:await()` parks by yielding + the running coroutine, so it works at the top level of a run and anywhere Lua can yield, but not + across a C-call boundary such as `table.sort` or `gsub`. Attempting that raises a clear error. + +Both engines share the same observable behaviour everywhere they can express it. Force one with the +`async` option, which is useful for testing or to keep behaviour identical across platforms: ```js -local res = sleep(1):next(function () - sleep(10):await() - return 15 -end) -print("res", res:await()) +const lua = await LuaRuntime.load({ async: 'yield' }) // 'auto' (default), 'jspi', or 'yield' ``` -Which will throw an error like this: +A run parked on a promise can be interrupted by a `timeout` or an `AbortSignal`, without waiting for +the promise to settle: -``` -Error: Lua Error(ErrorRun/2): cannot resume dead coroutine - at Thread.assertOk (/home/tstableford/projects/wasmoon/dist/index.js:409:23) - at Thread. (/home/tstableford/projects/wasmoon/dist/index.js:142:22) - at Generator.throw () - at rejected (/home/tstableford/projects/wasmoon/dist/index.js:26:69) +```js +await state.doString('sleep(60000):await()', { timeout: 1000 }) // rejects after ~1s ``` -Or like this: +#### Awaiting in a JS→Lua callback -``` -attempt to yield across a C-call boundary +A Lua function called from JS runs synchronously and returns its value directly. If it `:await()`s, +the call becomes asynchronous and returns a `Promise` instead: + +```js +state.set('handler', null) +await state.doString('handler = function(x) return sleep(10):await() + x end') +const handler = state.get('handler') +console.log(await handler(5)) // a promise, because the callback awaited ``` -You can workaround this by doing something like below: +#### Handling a top-level `coroutine.yield` -```lua -function async(callback) - return function(...) - local co = coroutine.create(callback) - local safe, result = coroutine.resume(co, ...) - - return Promise.create(function(resolve, reject) - local function step() - if coroutine.status(co) == "dead" then - local send = safe and resolve or reject - return send(result) - end - - safe, result = coroutine.resume(co) - - if safe and result == Promise.resolve(result) then - result:finally(step) - else - step() - end - end - - result:finally(step) - end) - end -end +A top level `coroutine.yield` that is not an `:await()` is a *host yield*. Pass `onYield` to receive +its values and decide what the resume hands back; its return may be a promise, a `LuaMultiReturn` of +several values, or a single value: + +```js +const thread = state.newThread() +thread.loadString('local reply = coroutine.yield("ping") return reply') +const [result] = await thread.run(0, { + onYield: (values) => { + console.log(values[0]) // "ping" + return 'pong' + }, +}) +console.log(result) // "pong" ``` diff --git a/docs/async-redesign/README.md b/docs/async-redesign/README.md new file mode 100644 index 0000000..4beda98 --- /dev/null +++ b/docs/async-redesign/README.md @@ -0,0 +1,449 @@ +# Rethinking async in wasmoon + +Design proposal, 2026-09-05. Everything marked *measured* below was run against the current +`dist/` (Node 26.7, V8 14.6) or against a one-off wasm build; the scripts are in `experiments/`. + +## TL;DR + +The current model has one primitive, "yield the Lua coroutine and let a JS loop look at what was +yielded", and everything (awaiting, time slicing, cancellation, callbacks) is squeezed through it. +That is why awaits fail inside `table.sort`, `gsub`, `promise:next(luaFn)` and every JS→Lua +callback, why top-level `coroutine.yield` values are silently dropped, why a parked run cannot be +aborted or timed out, and why a loop of awaits starves the event loop. + +Proposal, in two layers: + +1. **A real scheduler in JS, engine-agnostic.** Every asynchronous entry point becomes a *run*: + one Lua coroutine, one JS promise, one cancellation scope. The scheduler owns parking and + resuming, uses an explicit yield protocol instead of sniffing the last yielded value, resumes + in microtasks with a starvation guard, can cancel a parked run, and lets JS→Lua callbacks + return a promise when the Lua side suspends. This fixes most of the list above with no wasm + change and is required anyway as the fallback engine. +2. **JSPI as the primary engine where available.** With `-sSUPPORT_LONGJMP=wasm` (+47 bytes of + wasm, -746 bytes of glue JS, and *measured* 30-45% faster `pcall`/`error`/yield paths on its + own) the interpreter runs under `WebAssembly.promising`, and an await anywhere, including + across C boundaries and inside coroutines nobody drives, simply suspends the wasm stack. + *Measured*: a suspension costs 0.3-1.6 µs depending on the stack strategy versus 6 µs for + today's coroutine round trip; CPU-bound code is unaffected; 1000 parked runs cost ~4 MB, the + same as today. Two things make it work in this codebase: a C-side trampoline that calls a plain + import first and a `Suspending` import only when suspension is allowed, and saving each run's + slice of the linear-memory C stack across a suspension (without that, interleaved runs corrupt + each other; both *measured*). See §6 for the full numbers. + +JSPI is in Chrome/Edge 137+, Firefox 153+, Node 25+ (Node 24 only behind a flag) and not in +Safari, so the scheduler layer stays the contract and JSPI is a feature-detected accelerator with +identical observable semantics wherever both can express them. + +--- + +## 1. How it works today + +``` +doString(code) Lua JS function `sleep` + │ newAnchoredThread + load │ │ + │ thread.run() ── lua_resume ────────► │ sleep(10):await() │ + │ │ └► promise ext `await`: │ + │ │ pendingAwaits[L] = {…} │ + │ │ push(promise) │ + │ │ lua_yieldk(L, 1, 0, k) ─────┼──► longjmp → JS exception + │ ◄── LUA_YIELD, 1 value ──────────────┘ │ (EmscriptenEH, rethrown) + │ getValue(-1); isPromise? await it │ + │ else: setImmediate / setTimeout(0) │ + │ lua_resume(L, 0) ──────────────────► │ continuation k: │ + │ │ result ready? push, return 1 │ + │ │ not ready? lua_yieldk again │ + │ ◄── LUA_OK ── getStackValues() │ │ +``` + +Relevant code: `Thread.run` (`src/thread.ts:158`), the promise extension +(`src/type-extensions/promise.ts`), `FunctionTypeExtension.getValue` which calls Lua from JS +with a synchronous `lua_pcallk` (`src/type-extensions/function.ts:191`), and the limit hook +(`src/thread.ts` `applyHook`/`checkYieldLimits`). + +Properties of this model: + +- The *only* way to park is `lua_yieldk` on the coroutine `run()` is driving. Anything that is + not that coroutine, or has a C frame between it and the await, cannot park. +- The host decides what a yield *means* by looking at the last yielded value. Await and + "cooperative time slice" share one channel; user yields have no channel at all. +- JS→Lua calls are always synchronous. The callback runs on a pooled thread under `lua_pcallk` + and a yield is an error. +- Awaits inside a coroutine that Lua code resumes (not the host) work by *polling*: the + continuation re-yields with zero values until the promise has settled, and the resumer has to + `coroutine.yield()` to the host between attempts (see the README workaround). +- Limits are checked by the debug hook while Lua runs and by `run()` around yields only. + +## 2. What is wrong (all *measured*, `experiments/current-behavior.mjs`) + +| # | Behaviour | Result today | +|---|---|---| +| 1 | `coroutine.yield(io.stdout)` at top level of `doString` | throws `TypeError: the Lua type 'userdata' with metatable 'FILE*' has no JS representation`. `run()` calls `getValue(-1)` on whatever the script yielded. | +| 2 | `local a, b = coroutine.yield(1, 2)` at top level | `a`, `b` are nil. Values are popped and discarded, resume passes nothing back. | +| 3 | `:await()` inside a `table.sort` comparator or a `gsub` callback | `cannot await in a thread that cannot yield, use doString instead of doStringSync`. Wrong diagnosis: we *are* in `doString`, this is a C-call boundary. | +| 4 | `:await()` inside `promise:next(function() ... end)` | same error. The callback is entered from JS via `lua_pcallk`. | +| 5 | JS calls a Lua function that awaits (`state.get('f')(2)`) | same error. No way to get a promise back. | +| 6 | `while not flag() do Promise.resolve(1):await() end` with a 5 ms timer setting `flag` | 20 000 iterations, timer never fires. Resumes are microtasks with no macrotask boundary. | +| 7 | `sleep(300):await()` with `{ signal }` aborted at 10 ms, or `{ timeout: 10 }` | rejects after **301 ms**. Limits are only observed after the promise settles. | +| 8 | 200 bare `coroutine.yield()` round trips | 6 ms in Node. In browsers `setTimeout(0)` is clamped to 4 ms when nested, so the same script takes ~800 ms. | +| 9 | Cost of one await round trip on an already settled promise | ~6 µs (10k in 59 ms): two `lua_resume` calls, a longjmp through a JS exception, a Map lookup, a promise `then`. | +| 10 | Nested `coroutine.resume(co)` where `co` awaits | returns `true` immediately with the promise as its value; the caller must poll. Also `pendingAwaits` keeps the record until the state closes if `co` is never resumed again (documented leak, `promise.ts:141`). | + +Things that do work and should keep working: awaits inside `pcall`, inside Lua metamethods +called from Lua (`__index` from Lua code is yieldable in 5.4+), inside Lua iterators, several +host-driven runs interleaving on one state, `Promise.all`, rejection → Lua error and back. + +Smaller structural issues worth fixing while there: + +- `pendingInterrupt` lives on the root thread and every `resume()` clears it, so two interleaved + runs can clobber each other's interrupt (safe today only because hook → `lua_error` → + `assertOk` never crosses an await). +- `stateToThread` allocates a fresh `Thread` for every callback made from a coroutine the JS side + has not seen before. +- Every `lua_yieldk` from a C function longjmps, which under `SUPPORT_LONGJMP=emscripten` is a JS + exception plus the `isEmscriptenUnwind` brand hack in `rolldown.config.ts`. + +## 3. Constraints + +- **Size and speed budget.** `glue.wasm` is 192,923 bytes after a long flag sweep; the JS bundle + was cut to ~98 KB. Asyncify would roughly double the wasm and slow the interpreter by tens of + percent, so it is out. +- **Targets.** `browserslist`: Chrome ≥134, Firefox ≥138, Safari ≥26; `engines`: Node ≥24. JSPI + coverage today: Chrome/Edge 137+, Firefox 153+, Node 25+ by default (`--experimental-wasm-jspi` + on Node 24), Safari none. Any design needs a non-JSPI path with the same API. +- **One wasm instance, many states, one linear-memory C stack.** Everything that suspends shares + the 1 MB Emscripten stack. This is the one place JSPI needs help (section 5.4). +- **Lua's own rules stay.** A `lua_State` cannot be entered twice concurrently (*measured*: two + promising `lua_pcallk` on the same thread → `memory access out of bounds`), so every run still + needs its own coroutine, as `callByteCode` already does. + +## 4. Options considered + +**A. Asyncify.** Solves the C-boundary problem by rewriting the wasm. Rejected on size and speed, +and it still allows only one in-flight suspension per instance. + +**B. Keep `lua_yieldk`, fix the scheduler.** No wasm change. Fixes 1, 2, 4, 5, 6, 7, 8, 10 and the +misleading message in 3. Does *not* fix 3 itself (C-call boundary) and cannot make an await inside +a Lua-resumed coroutine transparent. Needed regardless as the fallback. + +**C. JSPI.** Fixes everything in the table including 3, and awaits inside Lua-resumed coroutines +become transparent (the resumer simply waits). *Measured* on a `-sSUPPORT_LONGJMP=wasm` build, +raw glue, Node 26 (`experiments/jspi-raw.mjs`): + +| Measurement | Result | +|---|---| +| await inside `table.sort` comparator, `gsub` callback, `coroutine.wrap` body | all work | +| Lua `error()` after a suspension, `lua_error` from a suspended import | caught by `pcall` correctly | +| `coroutine.yield` alongside JSPI | works | +| Suspending import called while **not** under `promising` | traps `trying to suspend without WebAssembly.promising` **even when it does not return a promise** | +| Suspending import called with a JS `invoke_*` longjmp trampoline on the stack (today's build) | traps `trying to suspend JS frames` | +| 10k `lua_pcallk` round trips, sync vs `promising` | 17.2 ms vs 39.3 ms (+2.2 µs per entry) | +| 100k imports that never suspend, plain vs `Suspending` | 4.1 ms vs 13.1 ms (+0.09 µs per call) | +| 10k suspensions on an already settled promise | 2.6 ms (0.26 µs each; today 6 µs) | +| 200k-element `table.sort`, sync vs `promising` | 100 ms vs 91 ms (noise) | +| wasm size, `SUPPORT_LONGJMP=emscripten` → `wasm` | 192,923 → 192,970 bytes; glue JS 87,012 → 86,266 | +| 100k `pcall(f)` without error, same switch | 12.2 ms → 6.8 ms | +| 100k `pcall(error, "x")`, same switch | 136 ms → 87 ms | +| 100k Lua-only `coroutine.yield`/resume, same switch | 97 ms → 65 ms | +| 100k `lua_yieldk` / `lua_error` from a JS function, same switch | 115 → 83 ms / 145 → 103 ms | +| heapsort.lua, same switch | 13.4 ms → 13.5 ms | + +Two concurrent runs on different states interleaving deep C recursion (`pcall` + `gsub` buffers) +across suspensions **corrupt each other** unless the linear-memory stack is managed: a Lua longjmp +escapes as a raw `WebAssembly.Exception`, then `C stack overflow`, then `memory access out of +bounds` (`experiments/jspi-stack.mjs`, unmanaged). With the management described in 5.4 the same +test passes every round. Pyodide documents the same problem and fix for CPython +(blog.pyodide.org, "Integrating JSPI with the WebAssembly C Runtime"). + +**Recommendation: B as the contract, C as the engine when present.** The visible API is defined +by B; C removes B's remaining limitations where the platform allows and is detected at load. + +## 5. Proposed architecture + +### 5.1 The run + +```ts +/** One asynchronous entry into Lua. Owned by the scheduler, never exposed as is. */ +interface Run { + thread: Thread // its own coroutine (lua_newthread), anchored in the registry + limits: LuaThreadLimits // deadline, budget, signal; replaces the root pendingInterrupt slot + settle: Deferred + parked?: Parked // what it is waiting on, if anything + onYield?: (values: MultiReturn) => unknown | Promise +} +``` + +`doString`, `doFile`, `Thread.run` and (new) asynchronous Lua function calls all create a run. +Sync entry points (`doStringSync`, `call`, `runSync`) do not; they increment a module-wide +`syncDepth` counter for the duration of the call (see 5.3). + +### 5.2 One suspender interface, two engines + +```ts +interface Suspender { + /** Called by the promise extension from inside a Lua→JS call. Must not return normally + * unless it has a value to hand back. */ + park(thread: Thread, promise: PromiseLike): number // returns a Lua result count + /** Drives a run to completion. */ + drive(run: Run, argCount: number): Promise +} +``` + +**YieldSuspender (fallback, today's mechanism cleaned up).** + +- `park`: refuses unless `lua_isyieldable`; records `{ promise }` on the run (or, for a coroutine + Lua code is resuming, in an ephemeron-keyed registry table, see 5.6); yields **two** values: + the module's await token (a lightuserdata the module owns, like `interruptToken`) and the + promise. Continuation `k` is one shared function pointer as now. +- `drive`: `lua_resume` loop. On `LUA_YIELD`: if slot `-2` is the await token (pointer compare, no + `getValue` on user values) → await the promise, resume; otherwise it is a **host yield** → + hand `getStackValues` to `run.onYield`, resume with whatever it returns (awaited if a promise). + Default `onYield` is "give the event loop a turn and resume with nothing", which is today's + behaviour minus the discarded values bug. +- Resume happens in the promise's own microtask. A per-run counter forces a macrotask boundary + after N consecutive microtask resumes (or after T ms of continuous running), which fixes #6 + without paying a macrotask per await. +- Macrotask = `scheduler.yield()` if present, else `MessageChannel` (no 4 ms clamp), else + `setImmediate`/`setTimeout`. Fixes #8. + +**JspiSuspender.** + +- Enabled when `typeof WebAssembly.Suspending === 'function'` *and* the glue was built with + `SUPPORT_LONGJMP=wasm`. `drive` calls `promising(lua_resume)`; host yields work exactly as + above, so the run loop is shared. +- `park` never yields; it returns a marker that tells the C trampoline (5.3) to call the + `Suspending` import, which returns the promise and lets the VM switch stacks. +- Nothing is recorded anywhere: the pending state *is* the suspended wasm stack. #10's leak and + the polling protocol disappear, and an await inside a coroutine that Lua resumes just makes the + resumer wait, which is what users expect. The README polling pattern keeps working unchanged + (the loop observes the coroutine finishing). + +### 5.3 The C trampoline, and when suspension is allowed + +Today each JS function is a C closure whose C function is an `addFunction` trampoline +(`functionWrapper`). Two facts from the measurements shape the replacement: a `Suspending` import +traps whenever it is reached outside a `promising` call, and it traps if a JS frame sits between +it and the `promising` boundary. So the decision to suspend has to be taken *before* touching the +`Suspending` import, and from a wasm frame. + +```c +/* src/native/wasmoon.c */ +extern int wasmoon_call(lua_State *L); /* plain import: runs the JS function */ +extern int wasmoon_await(lua_State *L); /* Suspending import: returns the stashed promise */ + +static int wasmoon_jsfunction(lua_State *L) { + int n = wasmoon_call(L); /* >= 0: results pushed; -1: a promise is pending */ + if (n == -1) n = wasmoon_await(L); /* wasm frame → import, no JS in between */ + return n; +} +``` + +`wasmoon_call` is today's `functionWrapper` body plus the promise extension's `await`, and ends +with one decision: + +| Situation | `wasmoon_call` does | +|---|---| +| result is not an await request | push results, return count (unchanged) | +| `:await()` and `syncDepth === 0` and JSPI engine | stash the promise, return -1 → VM suspends | +| `:await()` and `syncDepth > 0` (a sync entry point is on the JS stack) or no JSPI | `YieldSuspender.park` if `lua_isyieldable`, else the error, now worded "cannot await here: a synchronous call is on the stack" / "…across a C-call boundary" | + +`syncDepth` is exact because resumptions only ever happen from an empty JS stack (promise +reactions are microtasks), and a sync entry point cannot yield to the event loop. The one edge, a +run *started* from inside a sync callback, degrades to the yield path, which is correct. + +Both imports are provided through Emscripten's `instantiateWasm` hook so `wasmoon_await` can be +wrapped in `WebAssembly.Suspending` when available and be a plain never-called stub otherwise; no +`-sJSPI` flag, no Asyncify glue. `addFunction` stays for user-registered raw C functions and the +hook; the per-state trampoline pool becomes one C function with the JS reference in an upvalue, +as today. + +### 5.4 Linear-memory stack management (JSPI only) + +JSPI switches the wasm stack, not the `__stack_pointer` global or the memory it points at. When a +resumed run returns through a frame (which restores `__stack_pointer` to that frame's entry) and +then pushes new frames, it writes over any other suspended run's frames below. *Measured*: a Lua +longjmp escapes as a raw `WebAssembly.Exception`, then `C stack overflow`, then `memory access out +of bounds`; the pointer also drifts down 224 bytes per interleaving. Pyodide hit and documented the +same thing for CPython. + +Two strategies were measured (`experiments/jspi-modes.mjs`); both pass the interleaving stress and +the nested-start case (a run started from inside another run's JS callback): + +| | **copy** (recommended) | **region** | +|---|---|---| +| Mechanism | on suspension copy `[sp, mainSP)` to a JS buffer and set SP back; before resuming copy it back and restore `sp`. The promising wrapper restores its own entry SP after the call returns. | `malloc` a 256 KB region per promising run, set SP to its top; the suspension saves/restores SP. | +| Suspension on a settled promise | 1.6 µs | 0.5 µs | +| Suspension 30 `pcall` levels deep (~30 KB of C frames) | 3.9 µs | 0.5 µs | +| 1000 parked runs | rss +4.4 MB, wasm memory +0 | rss +224 MB, wasm memory +247 MB | +| Bytes copied per suspension in the stress test | 23 KB avg | 0 | + +Copy is Pyodide's "simplest fix" and is what the numbers favour: parked runs are the common +steady state for anything event driven, and a suspension is still 4x cheaper than today's round +trip in the worst case measured. Worst-case slice size is bounded by Lua's own C-call limit: +*measured* 108 KB (nested `gsub` to the limit), 45 KB (nested `pcall`), 22 KB (`table.sort` +comparators). Follow-ups if the copy ever shows up in a profile: copy `[sp, entrySP)` instead of +up to the main top (needs the run's entry SP, i.e. run tracking), and pool the buffers by size +class instead of `slice`. + +Why copying back stale bytes over another run's range is safe: a resume only ever happens from an +empty JS stack, at which point every other run is either finished or suspended and therefore +holding its own copy, which it restores on its own resume. Sync entry points push below whatever +the current SP is and finish before anything can resume. + +### 5.5 JS→Lua calls become sync-or-promise + +`getValue` for a function returns a callable that: + +1. acquires a coroutine (pool as today) and runs the function with `lua_resume`, not `lua_pcallk`; +2. if it finishes, returns the value synchronously (unchanged fast path, no promise allocated); +3. if it yields with the await protocol, hands the coroutine to the scheduler as a run and + **returns a Promise**; a host yield inside a callback is an error, as now. + +Under JSPI the same callable still uses `lua_resume` synchronously (a `promising` entry would +cost +2.2 µs on the hot interop path and would *always* return a promise). An await inside it +takes the yield path because `syncDepth > 0`, so `promise:next(function() sleep():await() end)`, +`array:map(luaFn)` with an awaiting `luaFn`, and `await state.get('handler')(req)` all work in +both engines. The footgun ("sometimes a promise") is real but is the only shape that composes with +JS APIs that accept callbacks; `decorate(fn, { call: 'sync' })` can opt a function out (throw on +suspension) and `{ call: 'async' }` can force a promise. + +### 5.6 Cancellation and limits while parked + +- A run's `signal`/`timeout` is raced against every park. On abort the run is resumed with the + interrupt token pushed and `lua_error` (the hook's existing mechanism), so `__close`/to-be-closed + variables run, `pcall` in the script cannot swallow it (token check in `assertOk` as today), and + the coroutine ends in a defined state. Same code path in both engines; in JSPI the resume is + "return from the `Suspending` import, then `lua_error`", never a foreign JS exception thrown + into wasm. The eventual settlement of the abandoned promise is ignored. Fixes #7. +- `pendingInterrupt` moves onto the run. Nested coroutines inherit the hook and report to the + run that owns them (they already inherit the hook function pointer). +- Fallback engine, coroutine resumed by Lua code (not a run): the pending record is keyed in a + registry ephemeron table `{ [thread] = box }` whose box `__gc` drops the JS record, so an + abandoned awaiting coroutine is collected with the thread instead of at `state.close()`. + +### 5.7 Lua-side surface + +- `promise:await()` unchanged. +- `Promise.async(fn, ...)` (inject mode) starts `fn` as its own run and returns a promise. This is + the README workaround implemented in JS with no polling, and the recommended way to fan out. + Works identically in both engines. +- Under the fallback engine, `coroutine.resume(co)` where `co` awaits keeps today's semantics + (yields the promise up; resumer polls). Under JSPI the resumer waits. Documented as "the + fallback is a subset". + +## 6. Performance and memory + +Everything here is *measured* (Node 26.7, `experiments/perf-dist.mjs`, `perf-raw.mjs`, +`jspi-modes.mjs`), best of 5. + +**Hot paths that must not regress** + +| Path | Today | Proposed | Why | +|---|---|---|---| +| Lua→JS function call that does not await | 0.04 µs import | same + one C call | the plain import runs first; the `Suspending` import is only reached when suspension was decided | +| JS→Lua callback (100k calls, pooled thread) | `lua_pcallk` 14.6 ms; through `getValue` wrapper 16.4 ms | `lua_resume` 14.8 ms | same cost; a promise is only allocated when the callback actually suspends | +| CPU-bound Lua (heapsort.lua) | 13.4 ms | 13.5 ms under wasm EH; 91 vs 100 ms for a 200k `table.sort` under `promising` | no Asyncify instrumentation, JSPI is free while not suspending | +| `pcall`, `error`, coroutine yield/resume | see §4 | 30-45% faster | wasm EH replaces the `invoke_*` JS trampolines and JS exceptions | + +**Per-run and per-await costs** + +| | Today | Fallback engine | JSPI engine | +|---|---|---|---| +| Starting a run (`doString('return 1')`) | 4.1 µs | ~same (a `Run` object and a deferred on top) | +2.2 µs for the `promising` entry (39.3 vs 17.2 ms per 10k) | +| Await of a settled promise | 6 µs (two resumes, a JS-exception longjmp, Map lookup) | ~4 µs (wasm-EH longjmp, no Map, starvation counter) | 1.6 µs copy / 0.5 µs region | +| Await 30 C levels deep | error today | error | 3.9 µs copy / 0.5 µs region | +| Bare `coroutine.yield()` round trip | 30 µs Node, ~4 ms browsers | ~µs (`MessageChannel`), no clamp | same loop | +| Resume 1000 parked runs | 2.5 ms | ~same | 0.9 ms | + +**Memory** + +| | Today | Fallback engine | JSPI engine (copy) | JSPI engine (region) | +|---|---|---|---|---| +| 1000 concurrently parked runs | rss +3.8 MB (1.9 MB JS heap; a Lua thread and a pending record each) | ~same, minus the leaked records | rss +4.4 MB (V8 suspended stack ~4-5 KB each, saved slice a few KB) | rss +224 MB | +| Per parked await, steady state | pending record until resume or `state.close()` | pending record until resume, cancel, or the thread's `__gc` | the saved stack slice, freed on resume | the region, freed on completion | +| Abandoned awaiting coroutine | leaks until `state.close()` | collected with the thread (ephemeron) | nothing to leak | nothing to leak | +| Extra bundle | | ~1-2 KB (scheduler) | + a few hundred bytes (wrapper, copy) | | + +Take-aways: the redesign does not touch the interop or interpreter hot paths; awaits get 1.5-10x +cheaper depending on engine; wasm EH is a straight speed win for error handling; and the copy +strategy keeps memory flat in the number of parked runs, which the region strategy does not. + +## 7. API changes (JS) + +| Today | Proposed | Notes | +|---|---|---| +| `doString/doFile` → Promise | unchanged | now a run; abortable while parked | +| `doStringSync/doFileSync` | unchanged | `syncDepth++` around the call | +| `thread.run(argCount, options)` | `+ options.onYield(values) → resume values \| Promise` | top-level `coroutine.yield` becomes a usable host channel; default keeps time-slicing behaviour | +| `thread.runSync`, `thread.call` | unchanged | | +| Lua function from `getValue`: sync, throws on yield | sync result **or** Promise when it suspends | `decorate(fn, { call: 'sync' \| 'async' })` to pin | +| `LuaRunOptions.signal` "observed after the promise settles" | interrupts a parked run immediately | doc change + behaviour | +| `Promise.create/all/resolve` (inject) | `+ Promise.async` | | +| `LuaRuntime.load()` | `+ options.async?: 'auto' \| 'jspi' \| 'yield'` and `runtime.engine` | `'auto'` default; `'yield'` for tests and for diffing behaviour | +| error `cannot await in a thread that cannot yield, use doString instead of doStringSync` | split into "synchronous call on the stack" and "C-call boundary (use the JSPI engine or Promise.async)" | | + +Breaking: (a) callbacks can now return promises; (b) top-level yield values are no longer +discarded; (c) `signal`/`timeout` fire while parked. All three are today's bugs rather than +features, but (a) deserves a major version note. + +## 8. Build changes + +- `-sSUPPORT_LONGJMP=wasm` in `utils/build-wasm.sh`. Required for JSPI (no `invoke_*` JS frames), + +47 bytes wasm, smaller glue, and a native longjmp instead of a JS exception on every + `lua_yieldk`/`lua_error` from a C function. `isEmscriptenUnwind` becomes + `err instanceof WebAssembly.Exception` and the `EmscriptenEH` brand plugin in + `rolldown.config.ts` goes away. All target browsers support wasm EH. +- `src/native/wasmoon.c` gains `wasmoon_jsfunction` and the two imports; the imports are + resolved in `Module.instantiateWasm`. +- No `-sJSPI`, no `-sASYNCIFY`. Feature detection at load, both engines in the bundle (the JSPI + part is a few hundred bytes). + +## 9. Phasing + +1. **Scheduler rewrite (fallback engine only).** `Run`, await token protocol, `onYield`, macrotask + policy, starvation guard, cancellation while parked, per-run interrupt slot, ephemeron for + nested awaits, sync-or-promise callbacks. Ship behind no flag; this is a bugfix release with + one semver-major note. Tests: everything in §2 becomes a test. +2. **`SUPPORT_LONGJMP=wasm` + `wasmoon_jsfunction` in C.** Behaviour-neutral on its own; measure + heapsort and interop benches (memory says the current `-Oz` set wins on heapsort, this flag + was size-neutral in that sweep and was not speed-tested). +3. **JspiSuspender.** `promising(lua_resume)`, stack slice copy (§5.4), `syncDepth` gate, + `Suspending` import via `instantiateWasm`. Gate on the §6 numbers: interop bench unchanged, + heapsort unchanged, 1000 parked runs under 10 MB. Run the whole test suite under `async: 'jspi'` and + `async: 'yield'` on Node ≥25 and browsers; add the interleaving stress from + `experiments/jspi-stack.mjs` as a test. +4. **Docs.** Replace the README "Async/Await" workaround with `Promise.async`, describe the two + engines and the one semantic difference (§5.7). + +## 10. Risks and open questions + +- **Copy cost on deep stacks.** 4 µs at 30 C levels; a pathological script awaiting inside deeply + nested `gsub` callbacks pays ~10 µs per await. Acceptable, and the `[sp, entrySP)` follow-up + halves it. +- **`stackRestore` interaction with Emscripten internals.** `stringToUTF8OnStack`/`withCString` + use the C stack; they must not straddle a park. Today `pushValue` never does, keep it that way. +- **JSPI and the debug hook.** Untested: a hook that fires and `lua_error`s while another run is + suspended. Should be fine (same thread only), needs a test. +- **Firefox/Safari fallback fidelity.** The C-call-boundary case stays an error on Safari and + Firefox <153. Message must point at `Promise.async` or restructuring. +- **Same-function two trampolines?** Not needed: one C function, decision at call time. Verify + `lua_pushcclosure` with a real C function (not `addFunction`) does not change `getReferenceBox` + upvalue handling. +- **Name of `Promise.async` / `decorate` options.** Bikeshed. + +## Appendix: experiments + +All in `experiments/`, run from the repo root. + +- `current-behavior.mjs`: the table in §2 against `dist/`. +- `build-wasm-eh.sh`: the build script with `-sSUPPORT_LONGJMP=wasm`, output to `/out`; run via + `podman run --rm -v "$PWD:/wasmoon" -v "$OUT:/out" docker.io/emscripten/emsdk /out/build-wasm-eh.sh`. +- `jspi-raw.mjs `: JSPI feature and timing matrix (§4 C) against the raw glue. +- `jspi-sp.mjs `: prints `__stack_pointer` around suspensions (shows the drift). +- `jspi-stack.mjs [mitigate]`: the interleaving stress; fails without `mitigate`, passes + with it. +- `jspi-modes.mjs `: the two stack strategies of §5.4 against the + stress, the nested start, suspension timings and memory for 1000 parked runs. Run with + `--expose-gc`. +- `perf-raw.mjs [jspi]`: heapsort, `pcall`/`error`/yield throughput, worst-case C stack + depth; with `jspi`, memory and entry costs. Run on both glues to get the wasm EH comparison. +- `perf-dist.mjs`: today's callback call cost and parked-run memory against `dist/`. diff --git a/docs/async-redesign/experiments/build-wasm-eh.sh b/docs/async-redesign/experiments/build-wasm-eh.sh new file mode 100755 index 0000000..3a2ffef --- /dev/null +++ b/docs/async-redesign/experiments/build-wasm-eh.sh @@ -0,0 +1,222 @@ +#!/bin/bash -e +cd /wasmoon/utils +true + +LUA_SRC=$(ls ../lua/*.c | grep -v "luac.c" | grep -v "lua.c" | tr "\n" " ") + +# Do not add --closure here: it renames properties, which would strip the brand the JS build puts on +# the glue's longjmp unwind classes (see rolldown.config.ts) and turn every unwind into a Lua error. +if [ "$1" == "dev" ]; +then + extension=(-O0 -g3 -s ASSERTIONS=1 -s SAFE_HEAP=1 -s STACK_OVERFLOW_CHECK=2) +else + extension=(-Oz -fno-inline-functions -DLUA_USE_JUMPTABLE=0 -s BINARYEN_EXTRA_PASSES=gufa-optimizing,converge) +fi + +# Everything that is not about the filesystem, shared by both glues below so they can share one +# `glue.wasm`. +COMMON=( + -s WASM=1 + -s SUPPORT_LONGJMP=wasm + "${extension[@]}" + -s EXPORTED_RUNTIME_METHODS="[ + 'addFunction', \ + 'removeFunction', \ + 'FS', \ + 'PATH', \ + 'ENV', \ + 'getValue', \ + 'setValue', \ + 'lengthBytesUTF8', \ + 'stringToUTF8', \ + 'stringToNewUTF8', \ + 'stringToUTF8OnStack', \ + 'stackSave', \ + 'stackRestore', \ + 'UTF8ToString', \ + 'HEAPU8', \ + 'HEAPU32' + ]" + -s DEFAULT_LIBRARY_FUNCS_TO_INCLUDE="[ + '\$FS_mkdirTree', \ + '\$PATH', \ + '\$PATH_FS' + ]" + -s INCOMING_MODULE_JS_API="[ + 'locateFile', \ + 'preRun', \ + 'print', \ + 'printErr' \ + ]" + -s MODULARIZE=1 + -s ALLOW_TABLE_GROWTH=1 + -s EXPORT_NAME="initWasmModule" + -s ALLOW_MEMORY_GROWTH=1 + -s STRICT=1 + -s EXPORT_ES6=1 + -s MALLOC=emmalloc + -s STACK_SIZE=1MB + -s WASM_BIGINT + -s EXPORTED_FUNCTIONS="[ + '_malloc', \ + '_free', \ + '_realloc', \ + '_luaL_checkversion_', \ + '_luaL_getmetafield', \ + '_luaL_callmeta', \ + '_luaL_tolstring', \ + '_luaL_argerror', \ + '_luaL_typeerror', \ + '_luaL_checklstring', \ + '_luaL_optlstring', \ + '_luaL_checknumber', \ + '_luaL_optnumber', \ + '_luaL_checkinteger', \ + '_luaL_optinteger', \ + '_luaL_checkstack', \ + '_luaL_checktype', \ + '_luaL_checkany', \ + '_luaL_newmetatable', \ + '_luaL_setmetatable', \ + '_luaL_testudata', \ + '_luaL_checkudata', \ + '_luaL_where', \ + '_luaL_fileresult', \ + '_luaL_execresult', \ + '_luaL_ref', \ + '_luaL_unref', \ + '_luaL_loadfilex', \ + '_luaL_loadbufferx', \ + '_luaL_loadstring', \ + '_luaL_newstate', \ + '_luaL_len', \ + '_luaL_addgsub', \ + '_luaL_gsub', \ + '_luaL_setfuncs', \ + '_luaL_getsubtable', \ + '_luaL_traceback', \ + '_luaL_requiref', \ + '_luaL_buffinit', \ + '_luaL_prepbuffsize', \ + '_luaL_addlstring', \ + '_luaL_addstring', \ + '_luaL_addvalue', \ + '_luaL_pushresult', \ + '_luaL_pushresultsize', \ + '_luaL_buffinitsize', \ + '_lua_newstate', \ + '_lua_close', \ + '_lua_newthread', \ + '_lua_closethread', \ + '_lua_atpanic', \ + '_lua_version', \ + '_lua_absindex', \ + '_lua_gettop', \ + '_lua_settop', \ + '_lua_pushvalue', \ + '_lua_rotate', \ + '_lua_copy', \ + '_lua_checkstack', \ + '_lua_xmove', \ + '_lua_isnumber', \ + '_lua_isstring', \ + '_lua_iscfunction', \ + '_lua_isinteger', \ + '_lua_isuserdata', \ + '_lua_type', \ + '_lua_typename', \ + '_lua_tonumberx', \ + '_lua_tointegerx', \ + '_lua_toboolean', \ + '_lua_tolstring', \ + '_lua_rawlen', \ + '_lua_tocfunction', \ + '_lua_touserdata', \ + '_lua_tothread', \ + '_lua_topointer', \ + '_lua_arith', \ + '_lua_rawequal', \ + '_lua_compare', \ + '_lua_pushnil', \ + '_lua_pushnumber', \ + '_lua_pushinteger', \ + '_lua_pushlstring', \ + '_lua_pushstring', \ + '_lua_pushcclosure', \ + '_lua_pushboolean', \ + '_lua_pushlightuserdata', \ + '_lua_pushthread', \ + '_lua_getglobal', \ + '_lua_gettable', \ + '_lua_getfield', \ + '_lua_geti', \ + '_lua_rawget', \ + '_lua_rawgeti', \ + '_lua_rawgetp', \ + '_lua_createtable', \ + '_lua_newuserdatauv', \ + '_lua_getmetatable', \ + '_lua_getiuservalue', \ + '_lua_setglobal', \ + '_lua_settable', \ + '_lua_setfield', \ + '_lua_seti', \ + '_lua_rawset', \ + '_lua_rawseti', \ + '_lua_rawsetp', \ + '_lua_setmetatable', \ + '_lua_setiuservalue', \ + '_lua_callk', \ + '_lua_pcallk', \ + '_lua_load', \ + '_lua_dump', \ + '_lua_yieldk', \ + '_lua_resume', \ + '_lua_status', \ + '_lua_isyieldable', \ + '_lua_setwarnf', \ + '_lua_warning', \ + '_lua_error', \ + '_lua_next', \ + '_lua_concat', \ + '_lua_len', \ + '_lua_stringtonumber', \ + '_lua_getallocf', \ + '_lua_setallocf', \ + '_lua_toclose', \ + '_lua_closeslot', \ + '_lua_getstack', \ + '_lua_getinfo', \ + '_lua_getlocal', \ + '_lua_setlocal', \ + '_lua_getupvalue', \ + '_lua_setupvalue', \ + '_lua_upvalueid', \ + '_lua_upvaluejoin', \ + '_lua_sethook', \ + '_lua_gethook', \ + '_lua_gethookmask', \ + '_lua_gethookcount', \ + '_luaopen_base', \ + '_luaopen_coroutine', \ + '_luaopen_table', \ + '_luaopen_io', \ + '_luaopen_os', \ + '_luaopen_string', \ + '_luaopen_utf8', \ + '_luaopen_math', \ + '_luaopen_debug', \ + '_luaopen_package', \ + '_luaL_openselectedlibs', \ + '_lua_gc' \ + ]" +) + +# The default glue, for every environment. Its filesystem is Emscripten's in-memory one, and +# -lnodefs.js adds the NODEFS backend so a host directory can be mounted into it (LuaModuleOptions +# `mounts`). Nothing here reaches the host on its own. +emcc "${COMMON[@]}" \ + -lnodefs.js \ + -s ENVIRONMENT="web,worker,node" \ + -o /out/glue.js \ + ${LUA_SRC} diff --git a/docs/async-redesign/experiments/current-behavior.mjs b/docs/async-redesign/experiments/current-behavior.mjs new file mode 100644 index 0000000..4b256c2 --- /dev/null +++ b/docs/async-redesign/experiments/current-behavior.mjs @@ -0,0 +1,34 @@ +import { LuaRuntime } from '../../../dist/index.js' +const lua = await LuaRuntime.load() +const state = lua.createState({ inject: true }) +state.set('sleep', (ms) => new Promise((r) => setTimeout(r, ms))) +const probe = async (name, code, opts) => { + const t = Date.now() + try { const r = await state.doString(code, opts); console.log(`[${name}] ok ->`, r, `${Date.now()-t}ms`) } + catch (e) { console.log(`[${name}] ERR ->`, String(e.message).split('\n')[0], `${Date.now()-t}ms`) } +} +await probe('top-level yield of unrepresentable value', `coroutine.yield(io.stdout) return 1`) +await probe('top-level yield values discarded', `local a, b = coroutine.yield(1, 2) return a, b`) +await probe('await inside table.sort comparator', `local t = {3,2,1} table.sort(t, function(a,b) sleep(1):await() return a', await state.get('callback')(2)) } catch (e) { console.log('[JS calls Lua fn that awaits] ERR ->', e.message.split('\n')[0]) } +let fired = false; setTimeout(() => { fired = true }, 5) +state.set('fired', () => fired) +await probe('resolved await loop starves timers? (cap 20000 iterations)', `local n=0 while not fired() and n < 20000 do Promise.resolve(1):await() n=n+1 end return n, fired()`) +await probe('200 bare coroutine.yield() round trips', `for i=1,200 do coroutine.yield() end return 1`) +const ac = new AbortController(); setTimeout(() => ac.abort(), 10) +await probe('abort while parked on 300ms sleep', `sleep(300):await() return 1`, { signal: ac.signal }) +await probe('timeout 10ms while parked on 300ms sleep', `sleep(300):await() return 1`, { timeout: 10 }) +const t0 = Date.now() +const rs = await Promise.all([1,2,3].map(i => state.doString(`sleep(30):await() return ${i}`))) +console.log('[3 concurrent doString on one state] ->', rs, `${Date.now()-t0}ms`) +await probe('nested coroutine.resume of awaiting coroutine, no polling', `local co = coroutine.create(function() sleep(1):await() return 3 end) local ok, v = coroutine.resume(co) return ok, tostring(v), coroutine.status(co)`) +// cost of one await round trip on an already-resolved promise +await probe('10000 awaits of resolved promise (timing)', `local p = Promise.resolve(1) for i=1,10000 do p:await() end return 1`) +state.close() diff --git a/docs/async-redesign/experiments/jspi-modes.mjs b/docs/async-redesign/experiments/jspi-modes.mjs new file mode 100644 index 0000000..f0e46bb --- /dev/null +++ b/docs/async-redesign/experiments/jspi-modes.mjs @@ -0,0 +1,98 @@ +// Compares three ways of handling the linear-memory C stack under JSPI: +// none : nothing (known to corrupt) +// region : a malloc'd stack region per promising run, SP saved/restored around each suspension +// copy : shared stack; on suspension copy out [sp, mainSP) and restore it before resuming +// Usage: node jspi-modes.mjs +const mode = process.argv[3] +const { default: init } = await import(process.argv[2]) +const M = await init({}) +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)) +const cstr = (s) => M.stringToNewUTF8(s) +const tostr = (L, i) => M.UTF8ToString(M._lua_tolstring(L, i, 0)) +const newState = () => { const L = M._luaL_newstate(); M._luaL_openselectedlibs(L, 0xffff, 0); return L } +const load = (L, code) => { const p = cstr(code); const st = M._luaL_loadbufferx(L, p, M.lengthBytesUTF8(code), p, 0); M._free(p); if (st) throw new Error('load: ' + tostr(L, -1)) } +const pcallRaw = WebAssembly.promising(M._lua_pcallk) +const REGION = 256 * 1024 +const mainSP = M.stackSave() +let copiedBytes = 0, suspensions = 0 +const pcallAsync = async (L, ...args) => { + if (mode === 'copy') { + // Restore whatever SP the caller had, so a run started from inside an active run's callback + // hands the stack back to that run when it completes or first suspends. + const entry = M.stackSave() + const p = pcallRaw(L, ...args); M.stackRestore(entry); return p + } + if (mode !== 'region') return pcallRaw(L, ...args) + const region = M._malloc(REGION) + M.stackRestore(region + REGION) + try { const p = pcallRaw(L, ...args); M.stackRestore(mainSP); return await p } + finally { M.stackRestore(mainSP); M._free(region) } +} +const suspending = (fn) => new WebAssembly.Suspending( + mode === 'region' ? async (...args) => { const sp = M.stackSave(); try { return await fn(...args) } finally { M.stackRestore(sp) } } + : mode === 'copy' ? async (...args) => { + const sp = M.stackSave() + const saved = M.HEAPU8.slice(sp, mainSP) // the frames this run needs back + copiedBytes += saved.length; suspensions++ + try { return await fn(...args) } finally { M.HEAPU8.set(saved, sp); M.stackRestore(sp) } + } + : fn) +const run = async (L, code) => { const top = M._lua_gettop(L); load(L, code); const st = await pcallAsync(L, 0, 1, 0, 0, 0); const v = tostr(L, -1); M._lua_settop(L, top); if (st) throw new Error(`status ${st}: ${v}`); return v } +const def = (L, name, ptr) => { M._lua_pushcclosure(L, ptr, 0); const p = cstr(name); M._lua_setglobal(L, p); M._free(p) } +const sleepPtr = M.addFunction(suspending(async (L) => { await sleep(M._lua_tonumberx(L, 1, 0)); M._lua_pushinteger(L, 42n); return 1 }), 'ii') +const microPtr = M.addFunction(suspending(async (L) => { await Promise.resolve(); M._lua_pushinteger(L, 1n); return 1 }), 'ii') +const mk = () => { const L = newState(); def(L, 'jspiSleep', sleepPtr); def(L, 'jspiMicro', microPtr); return L } +const deep = (ms, depth, tag) => ` + local function f(n) + if n == 0 then jspiSleep(${ms}) return "" end + local mine = ("${tag}"):rep(200) .. ("%03d"):format(n) + local inner + local r = (mine):gsub("%d%d%d", function(d) + local ok, v = pcall(function() return f(n - 1) end) + if not ok then error(v, 0) end + inner = v + return d + end, 1) + assert(r == mine, "gsub buffer clobbered at level " .. n) + return inner .. mine + end + local out = f(${depth}) + assert(#out == ${depth} * 203, "result length clobbered") + return "ok"` +const A = mk(), B = mk(), C = mk() +const fmt = (e) => `${e?.constructor?.name}: ${String(e?.message ?? e)}`.slice(0, 120) +console.log(`mode: ${mode}`) +for (let round = 1; round <= 3; round++) { + try { + const r = await Promise.all([ + run(A, `pcall(function() jspiSleep(2) end) ${deep(0, 40, "A")}`), + run(B, deep(30, 40, "B")), + run(C, `for i = 1, 5 do pcall(function() jspiSleep(3) end) ${deep(1, 20, "C")} end return "ok"`), + ]) + console.log(` interleaving round ${round}:`, r.join(',')) + } catch (e) { console.log(` interleaving round ${round}: FAILED:`, fmt(e)) } +} +// Nested start: a run started from inside another run's JS callback while that run is active. +try { + let inner + const startInner = M.addFunction((L) => { inner = run(C, deep(5, 30, "N")); return 0 }, 'ii'); def(A, 'startInner', startInner) + const outer = run(A, `startInner() ${deep(2, 30, "O")}`) + console.log(' nested start:', await outer, await inner) +} catch (e) { console.log(' nested start: FAILED:', fmt(e)) } +console.log(` stack bytes copied per suspension (avg): ${suspensions ? Math.round(copiedBytes / suspensions).toLocaleString() : 'n/a'}`) + +let s = performance.now(); await run(A, `for i=1,10000 do jspiMicro() end`) +console.log(` 10k suspensions on a settled promise: ${(performance.now() - s).toFixed(1)} ms`) +s = performance.now(); await run(A, `local function f(n) if n == 0 then for i=1,2000 do jspiMicro() end return end pcall(f, n-1) end f(30)`) +console.log(` 2k suspensions 30 pcall levels deep: ${(performance.now() - s).toFixed(1)} ms`) + +// Memory for 1000 concurrently parked runs. +let release; const gate = new Promise((r) => { release = r }) +const waitPtr = M.addFunction(suspending(async () => { await gate; return 0 }), 'ii') +const L0 = newState(); M._lua_checkstack(L0, 1100); const threads = [] +for (let i = 0; i < 1000; i++) { const T = M._lua_newthread(L0); def(T, 'wait', waitPtr); threads.push(T) } +global.gc?.(); const before = process.memoryUsage(); const heapBefore = M.HEAPU8.length +const runs = threads.map((T) => { load(T, `wait() return 1`); return pcallAsync(T, 0, 1, 0, 0, 0) }) +global.gc?.(); const during = process.memoryUsage() +console.log(` 1000 parked runs: rss +${((during.rss - before.rss) / 1048576).toFixed(1)} MB, js heap +${((during.heapUsed - before.heapUsed) / 1048576).toFixed(1)} MB, wasm memory +${((M.HEAPU8.length - heapBefore) / 1048576).toFixed(1)} MB`) +s = performance.now(); release(); await Promise.all(runs); console.log(` resume all 1000: ${(performance.now() - s).toFixed(1)} ms`) diff --git a/docs/async-redesign/experiments/jspi-raw.mjs b/docs/async-redesign/experiments/jspi-raw.mjs new file mode 100644 index 0000000..320a56a --- /dev/null +++ b/docs/async-redesign/experiments/jspi-raw.mjs @@ -0,0 +1,52 @@ +// Drives the raw Emscripten glue (no wasmoon TS layer) so it can point at an experimental build. +const glue = process.argv[2] +const { default: init } = await import(glue) +const M = await init({}) +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)) +const cstr = (s) => M.stringToNewUTF8(s) +const tostr = (L, i) => M.UTF8ToString(M._lua_tolstring(L, i, 0)) +const newState = () => { const L = M._luaL_newstate(); M._luaL_openselectedlibs(L, 0xffff, 0); return L } +const load = (L, code) => { const p = cstr(code); const n = M.lengthBytesUTF8(code); const st = M._luaL_loadbufferx(L, p, n, p, 0); M._free(p); if (st) throw new Error('load: ' + tostr(L, -1)) } +const pcallAsync = WebAssembly.promising(M._lua_pcallk) +const run = async (L, code) => { const top = M._lua_gettop(L); load(L, code); const st = await pcallAsync(L, 0, 1, 0, 0, 0); const v = tostr(L, -1); M._lua_settop(L, top); if (st) throw new Error(`status ${st}: ${v}`); return v } +const runSync = (L, code) => { const top = M._lua_gettop(L); load(L, code); const st = M._lua_pcallk(L, 0, 1, 0, 0, 0); const v = tostr(L, -1); M._lua_settop(L, top); if (st) throw new Error(`status ${st}: ${v}`); return v } +const def = (L, name, ptr) => { M._lua_pushcclosure(L, ptr, 0); const p = cstr(name); M._lua_setglobal(L, p); M._free(p) } + +const fns = { + jspiSleep: M.addFunction(new WebAssembly.Suspending(async (L) => { const ms = M._lua_tonumberx(L, 1, 0); await sleep(ms); M._lua_pushinteger(L, 42n); return 1 }), 'ii'), + jspiSync: M.addFunction(new WebAssembly.Suspending((L) => { M._lua_pushinteger(L, 1n); return 1 }), 'ii'), + jspiMicro: M.addFunction(new WebAssembly.Suspending(async (L) => { await Promise.resolve(); M._lua_pushinteger(L, 1n); return 1 }), 'ii'), + jspiThrow: M.addFunction(new WebAssembly.Suspending(async (L) => { await sleep(1); const p = cstr('boom after suspend'); M._lua_pushstring(L, p); M._free(p); return M._lua_error(L) }), 'ii'), + plainFn: M.addFunction((L) => { M._lua_pushinteger(L, 1n); return 1 }, 'ii'), +} +const mk = () => { const L = newState(); for (const [n, p] of Object.entries(fns)) def(L, n, p); return L } +const L1 = mk(), L2 = mk() +const t = async (name, f) => { try { console.log(`[${name}]`, await f()) } catch (e) { console.log(`[${name}] FAILED:`, e.message.split('\n')[0]) } } + +await t('await in C function', () => run(L1, `return jspiSleep(5) * 2`)) +await t('inside table.sort comparator', () => run(L1, `local t={3,2,1} table.sort(t, function(a,b) jspiSleep(1) return a run(L1, `return (("abc"):gsub(".", function(c) jspiSleep(1) return c:upper() end))`)) +await t('inside coroutine, no host yield', () => run(L1, `local co=coroutine.wrap(function() return jspiSleep(1) end) return co()`)) +await t('lua error after suspend is pcall-able', () => run(L1, `local ok, e = pcall(jspiThrow) return tostring(ok) .. " " .. tostring(e)`)) +await t('lua error() after suspend in Lua', () => run(L1, `local ok, e = pcall(function() jspiSleep(1) error("boom") end) return tostring(e)`)) +await t('coroutine.yield still works alongside', () => run(L1, `local co = coroutine.create(function() jspiSleep(1) coroutine.yield(7) return 8 end) local _, a = coroutine.resume(co) local _, b = coroutine.resume(co) return a .. b`)) +await t('sync pcall with a suspending import (expected to fail)', () => runSync(L1, `return jspiSleep(1)`)) +await t('sync pcall with non-suspending Suspending import', () => runSync(L1, `return jspiSync()`)) + +const stress = (L, ms) => run(L, `for i=1,40 do local r = ("x"):rep(64):gsub(".", function() jspiSleep(${ms}) return "y" end) assert(r == ("y"):rep(64), "clobbered") end return "ok"`) +await t('two states interleaving suspended runs (shadow stack)', () => Promise.all([stress(L1, 1), stress(L2, 2)])) +await t('same state, two concurrent promising pcalls', () => Promise.all([stress(L1, 1), stress(L1, 2)])) +// Deep C recursion live across suspensions on both sides. +const deep = (L, ms) => run(L, `local function f(n) if n == 0 then jspiSleep(${ms}) return 0 end return 1 + tonumber(("%d"):format(f(n-1))) end for i=1,20 do assert(f(150) == 150) end return "ok"`) +await t('deep interleaved recursion across suspensions', () => Promise.all([deep(L1, 1), deep(L2, 2)])) + +const time = async (name, f) => { const s = performance.now(); await f(); console.log(` ${name}: ${(performance.now() - s).toFixed(1)} ms`) } +await time('100k Suspending imports that never suspend (promising pcall)', () => run(L1, `for i=1,100000 do jspiSync() end`)) +await time('100k plain imports (promising pcall)', () => run(L1, `for i=1,100000 do plainFn() end`)) +await time('100k plain imports (sync pcall)', async () => runSync(L1, `for i=1,100000 do plainFn() end`)) +await time('10k promising pcall round trips', async () => { for (let i = 0; i < 10000; i++) await run(L1, `return 1`) }) +await time('10k sync pcall round trips', async () => { for (let i = 0; i < 10000; i++) runSync(L1, `return 1`) }) +await time('10k suspensions on resolved promise', () => run(L1, `for i=1,10000 do jspiMicro() end`)) +await time('1k suspensions on setTimeout(0)', () => run(L1, `for i=1,1000 do jspiSleep(0) end`)) +await time('heapsort-ish CPU loop, sync pcall', async () => runSync(L1, `local t={} for i=1,200000 do t[i]=(i*7919)%1000 end table.sort(t)`)) +await time('heapsort-ish CPU loop, promising pcall', () => run(L1, `local t={} for i=1,200000 do t[i]=(i*7919)%1000 end table.sort(t)`)) diff --git a/docs/async-redesign/experiments/jspi-sp.mjs b/docs/async-redesign/experiments/jspi-sp.mjs new file mode 100644 index 0000000..8c21ef0 --- /dev/null +++ b/docs/async-redesign/experiments/jspi-sp.mjs @@ -0,0 +1,23 @@ +const { default: init } = await import(process.argv[2]) +const M = await init({}) +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)) +const cstr = (s) => M.stringToNewUTF8(s) +const newState = () => { const L = M._luaL_newstate(); M._luaL_openselectedlibs(L, 0xffff, 0); return L } +const load = (L, code) => { const p = cstr(code); M._luaL_loadbufferx(L, p, M.lengthBytesUTF8(code), p, 0); M._free(p) } +const pcallRaw = WebAssembly.promising(M._lua_pcallk) +const log = (tag) => console.log(tag.padEnd(46), 'SP =', M.stackSave()) +log('main, before anything') +const ptr = M.addFunction(new WebAssembly.Suspending(async (L) => { + const name = M.UTF8ToString(M._lua_tolstring(L, 1, 0)); const ms = M._lua_tonumberx(L, 2, 0) + log(`import entry (${name})`) + await sleep(ms) + log(`import after await, before resume (${name})`) + M._lua_pushinteger(L, 1n); return 1 +}), 'ii') +const def = (L) => { M._lua_pushcclosure(L, ptr, 0); const p = cstr('susp'); M._lua_setglobal(L, p); M._free(p) } +const A = newState(), B = newState(); def(A); def(B) +load(A, `susp("A shallow", 5) local function f(n) if n == 0 then susp("A deep", 5) return end f(n-1) end f(60)`) +load(B, `local function f(n) if n == 0 then susp("B deep", 20) return end f(n-1) end f(60)`) +const pa = pcallRaw(A, 0, 0, 0, 0, 0); log('main, after A suspended') +const pb = pcallRaw(B, 0, 0, 0, 0, 0); log('main, after B suspended') +await Promise.all([pa, pb]); log('main, both done') diff --git a/docs/async-redesign/experiments/jspi-stack.mjs b/docs/async-redesign/experiments/jspi-stack.mjs new file mode 100644 index 0000000..3ef1e1f --- /dev/null +++ b/docs/async-redesign/experiments/jspi-stack.mjs @@ -0,0 +1,61 @@ +// Adversarial for the linear-memory C stack. Lua->Lua calls do not recurse in C, so recursion goes +// through pcall (a lua_longjmp with a setjmp buffer per level on the C stack) and gsub (a +// luaL_Buffer per level), each level verifying its own C-stack data after the inner levels ran. +const mitigate = process.argv[3] === 'mitigate' +const { default: init } = await import(process.argv[2]) +const M = await init({}) +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)) +const cstr = (s) => M.stringToNewUTF8(s) +const tostr = (L, i) => M.UTF8ToString(M._lua_tolstring(L, i, 0)) +const newState = () => { const L = M._luaL_newstate(); M._luaL_openselectedlibs(L, 0xffff, 0); return L } +const load = (L, code) => { const p = cstr(code); const st = M._luaL_loadbufferx(L, p, M.lengthBytesUTF8(code), p, 0); M._free(p); if (st) throw new Error('load: ' + tostr(L, -1)) } +const pcallRaw = WebAssembly.promising(M._lua_pcallk) +const REGION = 256 * 1024 +const mainSP = M.stackSave() +const pcallAsync = async (L, ...args) => { + if (!mitigate) return pcallRaw(L, ...args) + const region = M._malloc(REGION) + M.stackRestore(region + REGION) + try { const p = pcallRaw(L, ...args); M.stackRestore(mainSP); return await p } + finally { M.stackRestore(mainSP); M._free(region) } +} +const suspending = (fn) => new WebAssembly.Suspending(mitigate + ? async (...args) => { const sp = M.stackSave(); try { return await fn(...args) } finally { M.stackRestore(sp) } } + : fn) +const run = async (L, code) => { const top = M._lua_gettop(L); load(L, code); const st = await pcallAsync(L, 0, 1, 0, 0, 0); const v = tostr(L, -1); M._lua_settop(L, top); if (st) throw new Error(`status ${st}: ${v}`); return v } +const def = (L, name, ptr) => { M._lua_pushcclosure(L, ptr, 0); const p = cstr(name); M._lua_setglobal(L, p); M._free(p) } +const sleepPtr = M.addFunction(suspending(async (L) => { const ms = M._lua_tonumberx(L, 1, 0); await sleep(ms); M._lua_pushinteger(L, 42n); return 1 }), 'ii') +const mk = () => { const L = newState(); def(L, 'jspiSleep', sleepPtr); return L } +const deep = (ms, depth, tag) => ` + local function f(n) + if n == 0 then jspiSleep(${ms}) return "" end + local mine = ("${tag}"):rep(200) .. ("%03d"):format(n) + local inner + local r = (mine):gsub("%d%d%d", function(d) + local ok, v = pcall(function() return f(n - 1) end) + if not ok then error(v, 0) end + inner = v + return d + end, 1) + assert(r == mine, "gsub buffer clobbered at level " .. n) + return inner .. mine + end + local out = f(${depth}) + assert(#out == ${depth} * 203, "result length clobbered") + return "ok"` +const A = mk(), B = mk() +for (let round = 1; round <= 3; round++) { + try { + const r = await Promise.all([ + run(A, `pcall(function() jspiSleep(2) end) ${deep(0, 40, "A")}`), // shallow park, then deep C recursion while B is parked + run(B, deep(30, 40, "B")), // deep C recursion, then park for 30ms + ]) + console.log(`round ${round}:`, r) + } catch (e) { console.log(`round ${round}: FAILED:`, `${e?.constructor?.name}: ${String(e?.message ?? e)}`.slice(0, 160)) } +} +try { + // Single run: park deep, and while parked let the main JS thread make deep sync calls. + const parked = run(A, deep(20, 40, "A")) + load(B, deep(0, 40, "B").replace('jspiSleep(0)', '')); const st = M._lua_pcallk(B, 0, 1, 0, 0, 0); const v = tostr(B, -1); M._lua_settop(B, 0) + console.log('deep sync call while A parked deep:', st, v, '| A ->', await parked) +} catch (e) { console.log('sync-while-parked FAILED:', `${e?.constructor?.name}: ${String(e?.message ?? e)}`.slice(0, 160)) } diff --git a/docs/async-redesign/experiments/perf-dist.mjs b/docs/async-redesign/experiments/perf-dist.mjs new file mode 100644 index 0000000..5f089c3 --- /dev/null +++ b/docs/async-redesign/experiments/perf-dist.mjs @@ -0,0 +1,25 @@ +import { LuaRuntime } from '../../../dist/index.js' +const lua = await LuaRuntime.load() +const M = lua.module +const state = lua.createState({ inject: true }) +const time = (name, f, n = 5) => { let best = Infinity; for (let i = 0; i < n; i++) { const s = performance.now(); f(); best = Math.min(best, performance.now() - s) } console.log(` ${name}: ${best.toFixed(1)} ms (best of ${n})`) } + +console.log('== callbacks: lua_pcallk vs lua_resume on a pooled thread ==') +state.doStringSync('function f(x) return x + 1 end') +const T = state.newThread() +const N = 100000 +time(`${N} lua_pcallk calls`, () => { for (let i = 0; i < N; i++) { M.lua_getglobal(T.address, 'f'); M.lua_pushinteger(T.address, i); M.lua_pcallk(T.address, 1, 1, 0, 0, null); M.lua_settop(T.address, 0) } }) +time(`${N} lua_resume calls`, () => { for (let i = 0; i < N; i++) { M.lua_getglobal(T.address, 'f'); M.lua_pushinteger(T.address, i); M.lua_resume(T.address, null, 1, M.resultCountScratch); M.lua_settop(T.address, 0) } }) +const jsF = state.get('f') +time(`${N} calls through today's getValue wrapper`, () => { for (let i = 0; i < N; i++) jsF(i) }) + +console.log('== today: memory for 1000 concurrently parked doString awaits ==') +let release; const gate = new Promise((r) => { release = r }) +state.set('wait', () => gate) +global.gc?.(); const before = process.memoryUsage(); const heapBefore = M.emscripten.HEAPU8.length +const runs = []; for (let i = 0; i < 1000; i++) runs.push(state.doString('wait():await() return 1')) +await new Promise((r) => setTimeout(r, 20)); global.gc?.(); const during = process.memoryUsage() +console.log(` 1000 parked runs: rss +${((during.rss - before.rss) / 1048576).toFixed(1)} MB, js heap +${((during.heapUsed - before.heapUsed) / 1048576).toFixed(1)} MB, wasm memory grew ${(M.emscripten.HEAPU8.length - heapBefore) / 1048576} MB`) +const s = performance.now(); release(); await Promise.all(runs); console.log(` resuming all 1000: ${(performance.now() - s).toFixed(1)} ms`) +time('1000 doString of "return 1" (run setup cost today)', () => { const ps = []; for (let i = 0; i < 1000; i++) ps.push(state.doString('return 1')) }, 3) +state.close() diff --git a/docs/async-redesign/experiments/perf-raw.mjs b/docs/async-redesign/experiments/perf-raw.mjs new file mode 100644 index 0000000..bccbb3f --- /dev/null +++ b/docs/async-redesign/experiments/perf-raw.mjs @@ -0,0 +1,60 @@ +// Raw-glue measurements. Usage: node perf-raw.mjs [jspi] +const { default: init } = await import(process.argv[2]) +const jspi = process.argv[3] === 'jspi' +const M = await init({}) +const cstr = (s) => M.stringToNewUTF8(s) +const tostr = (L, i) => M.UTF8ToString(M._lua_tolstring(L, i, 0)) +const L = M._luaL_newstate(); M._luaL_openselectedlibs(L, 0xffff, 0) +const load = (T, code) => { const p = cstr(code); const st = M._luaL_loadbufferx(T, p, M.lengthBytesUTF8(code), p, 0); M._free(p); if (st) throw new Error('load: ' + tostr(T, -1)) } +const runSync = (T, code) => { const top = M._lua_gettop(T); load(T, code); const st = M._lua_pcallk(T, 0, 1, 0, 0, 0); const v = tostr(T, -1); M._lua_settop(T, top); if (st) throw new Error(`status ${st}: ${v}`); return v } +const time = (name, f, n = 5) => { let best = Infinity; for (let i = 0; i < n; i++) { const s = performance.now(); f(); best = Math.min(best, performance.now() - s) } console.log(` ${name}: ${best.toFixed(1)} ms (best of ${n})`) } +const heapsort = (await import('node:fs')).readFileSync(new URL('../../../bench/heapsort.lua', import.meta.url), 'utf8') + +console.log('== CPU / error paths ==') +runSync(L, 'hs = (function() ' + heapsort + ' end)()'); time('heapsort.lua', () => runSync(L, 'return hs()')) +time('100k pcall(error) round trips', () => runSync(L, `for i=1,100000 do pcall(error, "x") end`)) +time('100k pcall(f) no error', () => runSync(L, `local f = function() end for i=1,100000 do pcall(f) end`)) +time('100k coroutine.yield/resume (Lua only)', () => runSync(L, `local co = coroutine.wrap(function() while true do coroutine.yield() end end) for i=1,100000 do co() end`)) +// A C function that yields: lua_yieldk from C is a longjmp. Use a JS import that yields. +const yieldPtr = M.addFunction((T) => M._lua_yieldk(T, 0, 0, 0), 'ii') +M._lua_pushcclosure(L, yieldPtr, 0); { const p = cstr('cyield'); M._lua_setglobal(L, p); M._free(p) } +time('100k yields from a C (JS) function via longjmp', () => runSync(L, `local co = coroutine.wrap(function() while true do cyield() end end) for i=1,100000 do co() end`)) +const errPtr = M.addFunction((T) => { const p = cstr('e'); M._lua_pushstring(T, p); M._free(p); return M._lua_error(T) }, 'ii') +M._lua_pushcclosure(L, errPtr, 0); { const p = cstr('cerror'); M._lua_setglobal(L, p); M._free(p) } +time('100k lua_error from a C (JS) function', () => runSync(L, `for i=1,100000 do pcall(cerror) end`)) + +console.log('== C stack depth ==') +const minSP = { v: Infinity } +const probePtr = M.addFunction((T) => { minSP.v = Math.min(minSP.v, M.stackSave()); return 0 }, 'ii') +M._lua_pushcclosure(L, probePtr, 0); { const p = cstr('probe'); M._lua_setglobal(L, p); M._free(p) } +const top = M.stackSave() +for (const [name, code] of [ + ['pcall recursion to the C limit', `local n = 0 local function f() n = n + 1 probe() local ok, e = pcall(f) if not ok and n == 1 then return e end end f() return n`], + ['gsub recursion to the C limit', `local n = 0 local function f() n = n + 1 probe() local ok, e = pcall(function() ("a"):gsub("a", f) end) end f() return n`], + ['string.format/ tostring / sort nesting', `local n = 0 local function f() n = n + 1 probe() pcall(table.sort, {2,1}, function(a,b) f() return a { release = r }) + const waitPtr = M.addFunction(new WebAssembly.Suspending(async (T) => { await gate; return 0 }), 'ii') + const N = 1000 + M._lua_checkstack(L, N + 10); const threads = [] + for (let i = 0; i < N; i++) { const T = M._lua_newthread(L); M._lua_pushcclosure(T, waitPtr, 0); const p = cstr('wait'); M._lua_setglobal(T, p); M._free(p); threads.push(T) } + // threads stay anchored on the main stack + global.gc?.(); const before = process.memoryUsage() + const heapBefore = M.HEAPU8.length + const runs = threads.map((T) => { load(T, `wait() return 1`); return pcallAsync(T, 0, 1, 0, 0, 0) }) + global.gc?.(); const during = process.memoryUsage() + console.log(` ${N} suspended runs: rss +${((during.rss - before.rss) / 1048576).toFixed(1)} MB, js heap +${((during.heapUsed - before.heapUsed) / 1048576).toFixed(1)} MB, external +${((during.external - before.external) / 1048576).toFixed(1)} MB, wasm memory grew ${(M.HEAPU8.length - heapBefore) / 1048576} MB`) + const s = performance.now(); release(); await Promise.all(runs) + console.log(` resuming all ${N}: ${(performance.now() - s).toFixed(1)} ms`) + // Cost of starting a promising run that completes synchronously, vs sync, on a fresh thread each time. + const T = M._lua_newthread(L) + time('10k promising pcall (sync completion) on one thread', () => { for (let i = 0; i < 10000; i++) { load(T, 'return 1'); pcallAsync(T, 0, 1, 0, 0, 0); M._lua_settop(T, 0) } }) + time('10k sync pcall on one thread', () => { for (let i = 0; i < 10000; i++) { load(T, 'return 1'); M._lua_pcallk(T, 0, 1, 0, 0, 0); M._lua_settop(T, 0) } }) + time('10k malloc/free of a 256 KB region', () => { for (let i = 0; i < 10000; i++) M._free(M._malloc(262144)) }) + time('10k malloc/free of a 64 KB region', () => { for (let i = 0; i < 10000; i++) M._free(M._malloc(65536)) }) +} diff --git a/src/async.ts b/src/async.ts new file mode 100644 index 0000000..7ebbdbd --- /dev/null +++ b/src/async.ts @@ -0,0 +1,147 @@ +/** + * A macrotask, so pending promise reactions *and* timers get a turn before Lua is resumed. A + * microtask would starve timer driven code such as setTimeout based sleeps. + * + * MessageChannel where it exists, because a browser clamps a nested setTimeout to 4ms while a + * message post is not clamped; setImmediate under Node; setTimeout as the last resort. + */ +type Macrotask = (task: () => void) => void + +const macrotask: Macrotask = (() => { + if (typeof MessageChannel === 'function') { + const channel = new MessageChannel() + const queue: Array<() => void> = [] + channel.port1.onmessage = () => queue.shift()?.() + // Node keeps the event loop alive for an open port, which would stop a process exiting once + // its Lua work is done; unref lets it exit. A no-op in the browser, which has neither. + ;(channel.port1 as { unref?: () => void }).unref?.() + ;(channel.port2 as { unref?: () => void }).unref?.() + return (task: () => void) => { + queue.push(task) + channel.port2.postMessage(null) + } + } + if (typeof setImmediate === 'function') { + return (task: () => void) => void setImmediate(task) + } + return (task: () => void) => void setTimeout(task, 0) +})() + +export const yieldToEventLoop = (): Promise => { + return new Promise((resolve) => macrotask(resolve)) +} + +/** + * Awaits `promise` but resolves early if `signal` aborts or `deadline` passes, so a run parked on a + * long promise can still be interrupted rather than waiting for it to settle. The abandoned promise + * is left to settle on its own and its result ignored. + */ +export function awaitInterruptible( + promise: PromiseLike, + signal: AbortSignal | undefined, + deadline: number | undefined, +): Promise { + if (signal === undefined && deadline === undefined) { + return Promise.resolve(promise).then(NOOP, NOOP) + } + + return new Promise((resolve) => { + let settled = false + const finish = (): void => { + if (settled) { + return + } + settled = true + if (timer !== undefined) { + clearTimeout(timer) + } + if (onAbort !== undefined) { + signal?.removeEventListener('abort', onAbort) + } + resolve() + } + + let timer: ReturnType | undefined + if (deadline !== undefined) { + timer = setTimeout(finish, Math.max(0, deadline - Date.now())) + } + + let onAbort: (() => void) | undefined + if (signal !== undefined) { + if (signal.aborted) { + finish() + return + } + onAbort = finish + signal.addEventListener('abort', onAbort, { once: true }) + } + + Promise.resolve(promise).then(finish, finish) + }) +} + +const NOOP = (): void => undefined + +export type SettleOutcome = + | { interrupted: false; resolved: true; value: unknown } + | { interrupted: false; resolved: false; error: unknown } + | { interrupted: true } + +/** + * Awaits `promise`, but reports an interruption instead if `signal` aborts or `deadline` passes + * first. Used by the JSPI await hook, which unwinds the suspended run with a Lua error when it is + * interrupted rather than waiting for the promise it was parked on. + */ +export function settleOrInterrupt( + promise: PromiseLike, + signal: AbortSignal | undefined, + deadline: number | undefined, +): Promise { + const settled: Promise = Promise.resolve(promise).then( + (value) => ({ interrupted: false, resolved: true, value }), + (error) => ({ interrupted: false, resolved: false, error }), + ) + if (signal === undefined && deadline === undefined) { + return settled + } + + return new Promise((resolve) => { + let done = false + const finish = (outcome: SettleOutcome): void => { + if (done) { + return + } + done = true + if (timer !== undefined) { + clearTimeout(timer) + } + if (onAbort !== undefined) { + signal?.removeEventListener('abort', onAbort) + } + resolve(outcome) + } + + let timer: ReturnType | undefined + if (deadline !== undefined) { + timer = setTimeout(() => finish({ interrupted: true }), Math.max(0, deadline - Date.now())) + } + + let onAbort: (() => void) | undefined + if (signal !== undefined) { + if (signal.aborted) { + finish({ interrupted: true }) + return + } + onAbort = () => finish({ interrupted: true }) + signal.addEventListener('abort', onAbort, { once: true }) + } + + settled.then(finish) + }) +} + +/** + * Returned by a JS function through the C trampoline to ask it to suspend the JSPI stack. The + * function extension turns it into the -1 the trampoline reads; nothing else produces it. + */ +export const SUSPEND: unique symbol = Symbol('wasmoon.suspend') diff --git a/src/module.ts b/src/module.ts index 869a99d..a0ba19e 100755 --- a/src/module.ts +++ b/src/module.ts @@ -3,6 +3,7 @@ // `/// ` at the top of the emitted declarations to cover everyone // else. tsc drops the directive when it is written here, hence the build step. import initWasmModule from '../build/glue.js' +import { settleOrInterrupt } from './async' import { defaultWarnHandler, LUA_REGISTRYINDEX, type LuaAddress, LuaReturn, LuaType, type LuaWarnHandler, PointerSize } from './types' // A rolldown plugin will resolve this to the current version on package.json import version from 'package-version' @@ -95,6 +96,13 @@ export interface LuaModuleOptions { * that state overrides it. Defaults to `console.warn`. */ onWarn?: LuaWarnHandler | undefined + /** + * Which async engine to run under. `'auto'` (the default) uses JSPI where the platform has it, + * so an `:await()` can suspend the wasm stack anywhere, and falls back to the coroutine + * yielding engine otherwise. `'jspi'` requires JSPI and throws if it is missing; `'yield'` + * forces the fallback, which is useful for tests and for matching the fallback's semantics. + */ + async?: 'auto' | 'jspi' | 'yield' | undefined } // One-shot conversions, so a single stateless codec pair is shared by every module. Streaming @@ -340,12 +348,14 @@ export default class LuaModule { throw new Error(`fs: 'host' needs glue-host.js, which the bundle replaced with a stub because it targets the browser`) } + const asyncEngine = opts.async ?? 'auto' const load = async (wasmFile?: string): Promise => { return new LuaModule( await init({ ...(wasmFile === undefined ? {} : { locateFile: () => wasmFile }), preRun, printErr }), opts.onWarn, fs, mounts, + asyncEngine, ) } @@ -396,6 +406,8 @@ export default class LuaModule { public readonly onWarn: LuaWarnHandler | undefined /** Which filesystem this module was loaded with, as {@link LuaModuleOptions.fs}. */ public readonly fs: LuaFileSystem + /** The async engine requested at load, as {@link LuaModuleOptions.async}. */ + public readonly asyncEngine: 'auto' | 'jspi' | 'yield' public luaL_checkversion_: (L: LuaAddress, ver: number, sz: number) => void public luaL_getmetafield: (L: LuaAddress, obj: number, e: string | null) => LuaType @@ -536,6 +548,10 @@ export default class LuaModule { public lua_upvalueid: (L: LuaAddress, fidx: number, n: number) => LuaAddress public lua_upvaluejoin: (L: LuaAddress, fidx1: number, n1: number, fidx2: number, n2: number) => void public lua_sethook: (L: LuaAddress, func: number | null, mask: number, count: number) => void + /** Installs the await hook the {@link wasmoon_push_jsfunction} closures suspend through. */ + public wasmoon_set_await_hook: (hook: number) => void + /** Pops the reference box on the stack and pushes a JS function closure over it and `callHook`. */ + public wasmoon_push_jsfunction: (L: LuaAddress, callHook: number) => void public lua_gethook: (L: LuaAddress) => number public lua_gethookmask: (L: LuaAddress) => number public lua_gethookcount: (L: LuaAddress) => number @@ -590,6 +606,57 @@ export default class LuaModule { * of the limit that was actually hit. */ public readonly interruptToken: number + /** + * The wasm stack pointer while control is in JS with none of our wasm frames below, captured + * once. A JSPI suspension frees the C stack from the run's frontier up to here, and restores it + * before resuming. See {@link installAwaitHook}. + */ + public readonly mainStackPointer: number + /** + * Set true only while a JSPI promising resume is the innermost driver on the stack, so an + * `:await()` knows a suspend would reach a promising boundary. A synchronous entry point + * (doStringSync, a JS→Lua callback) sets it false around its own resume, so an await there + * takes the yield path instead of trapping. + */ + public stackCanSuspend = false + /** + * Depth of synchronous entry points on the JS stack. While above zero an `:await()` cannot + * suspend or yield to the event loop, because the outermost caller is blocking. + */ + public syncDepth = 0 + /** + * The promise a JSPI `:await()` stashed for the C trampoline's await hook to suspend on, along + * with how to marshal its settled value back onto the Lua stack. Read synchronously by the + * await hook right after the await closure returns, so a single slot is reentrancy safe. + */ + public pendingSuspend: + | { + promise: PromiseLike + signal: AbortSignal | undefined + deadline: number | undefined + isClosed: () => boolean + onResolve: (value: unknown) => number + onReject: (error: unknown) => number + onInterrupt: () => number + } + | undefined + private awaitHookPointer: number | undefined + /** + * The deadline and abort signal of the JSPI run currently resuming, so an `:await()` it reaches + * can be interrupted while parked. Set around each promising resume rather than read from the + * awaiting thread, whose JS wrapper is often a fresh object without the run's limits on it. + */ + public activeRunDeadline: number | undefined + public activeRunSignal: AbortSignal | undefined + /** + * Whether runs on this module go through JSPI. On unless the platform lacks it or `async` asked + * for the yielding engine, in which case an `:await()` can only park at a coroutine boundary. + */ + public readonly useJspi: boolean + /** `promising(lua_resume)`, built once. */ + private promisingResumeFunction: + | ((L: LuaAddress, from: LuaAddress | null, narg: number, nres: number) => Promise) + | undefined private stringBuffer = 0 /** Built on first use by {@link referenceGcFunction}, then kept for the module's lifetime. */ private referenceGcPointer: number | undefined @@ -599,11 +666,19 @@ export default class LuaModule { onWarn?: LuaWarnHandler, fs: LuaFileSystem = 'memory', mounts: readonly ResolvedMount[] = [], + asyncEngine: 'auto' | 'jspi' | 'yield' = 'auto', ) { this.emscripten = module this.onWarn = onWarn this.fs = fs this.mounts = [...mounts] + this.asyncEngine = asyncEngine + + if (asyncEngine === 'jspi' && !this.jspiSupported) { + throw new Error( + "async: 'jspi' needs a platform with the JavaScript Promise Integration API and a glue built with SUPPORT_LONGJMP=wasm", + ) + } this.luaL_checkversion_ = this.cwrap('luaL_checkversion_', null, ['number', 'number', 'number']) this.luaL_getmetafield = this.cwrap('luaL_getmetafield', 'number', ['number', 'number', 'string']) @@ -736,6 +811,8 @@ export default class LuaModule { this.lua_upvalueid = this.cwrap('lua_upvalueid', 'number', ['number', 'number', 'number']) this.lua_upvaluejoin = this.cwrap('lua_upvaluejoin', null, ['number', 'number', 'number', 'number', 'number']) this.lua_sethook = this.cwrap('lua_sethook', null, ['number', 'number', 'number', 'number']) + this.wasmoon_set_await_hook = this.cwrap('wasmoon_set_await_hook', null, ['number']) + this.wasmoon_push_jsfunction = this.cwrap('wasmoon_push_jsfunction', null, ['number', 'number']) this.lua_gethook = this.cwrap('lua_gethook', 'number', ['number']) this.lua_gethookmask = this.cwrap('lua_gethookmask', 'number', ['number']) this.lua_gethookcount = this.cwrap('lua_gethookcount', 'number', ['number']) @@ -774,6 +851,64 @@ export default class LuaModule { if (!this.sizeScratch || !this.resultCountScratch || !this.gcArgsScratch || !this.interruptToken) { throw new Error('failed to allocate the scratch buffers for C out parameters') } + + // Captured while no Lua is running, so it is the top of the C stack in JS land. + this.mainStackPointer = this.stackSave() + this.useJspi = this.jspiSupported && this.asyncEngine !== 'yield' + if (this.useJspi) { + this.installAwaitHook() + } + } + + /** {@link promising}-wrapped `lua_resume`, built on first use and kept. */ + public promisingResume(): (L: LuaAddress, from: LuaAddress | null, narg: number, nres: number) => Promise { + this.promisingResumeFunction ??= this.promising(this.lua_resume as (...args: any[]) => LuaReturn) + return this.promisingResumeFunction + } + + /** + * Installs the single C await hook every JS function closure suspends through under JSPI. It + * awaits the promise the {@link pendingSuspend} slot was left holding, having first freed this + * run's slice of the shared linear-memory C stack so other runs can use it while parked, then + * restores that slice and marshals the settled value back before returning into Lua. + */ + private installAwaitHook(): void { + this.awaitHookPointer = this.emscripten.addFunction( + this.suspending(async (L: LuaAddress): Promise => { + const suspend = this.pendingSuspend + this.pendingSuspend = undefined + if (suspend === undefined) { + throw new Error('the JSPI await hook ran with no pending suspend') + } + + const stackPointer = this.stackSave() + const savedStack = this.readHeapSlice(stackPointer, this.mainStackPointer) + this.stackRestore(this.mainStackPointer) + + const outcome = await settleOrInterrupt(suspend.promise, suspend.signal, suspend.deadline) + + // The state was closed while parked: lua_close has freed the stack this would + // resume into, so stay suspended forever rather than resume into freed memory. The + // run itself was already rejected by runJspi's close race. + if (suspend.isClosed()) { + await new Promise(() => undefined) + } + + // Back on this run's stack: put its frames back before touching Lua, and mark the + // stack promising again for any further await this resume reaches. + this.writeHeapSlice(stackPointer, savedStack) + this.stackRestore(stackPointer) + this.stackCanSuspend = true + + void L + if (outcome.interrupted) { + return suspend.onInterrupt() + } + return outcome.resolved ? suspend.onResolve(outcome.value) : suspend.onReject(outcome.error) + }), + 'ii', + ) + this.wasmoon_set_await_hook(this.awaitHookPointer) } /** @@ -943,6 +1078,44 @@ export default class LuaModule { this.emscripten.HEAPU32[pointer >>> 2] = value } + /** + * Whether this runtime can run Lua under JSPI, so an `:await()` can suspend the wasm stack + * anywhere instead of only at a coroutine boundary. Needs the VM support and a glue built with + * `SUPPORT_LONGJMP=wasm`, without which a suspend trap fires on the `invoke_*` JS trampolines. + */ + public readonly jspiSupported: boolean = + typeof (WebAssembly as { Suspending?: unknown }).Suspending === 'function' && + typeof (WebAssembly as { promising?: unknown }).promising === 'function' + + /** The current wasm stack pointer, saved so a suspended run's C frames can be restored. */ + public stackSave(): number { + return this.emscripten.stackSave() + } + + public stackRestore(pointer: number): void { + this.emscripten.stackRestore(pointer) + } + + /** A copy of `[start, end)` of the wasm heap. Used to preserve a suspended run's C stack. */ + public readHeapSlice(start: number, end: number): Uint8Array { + return this.heap.slice(start, end) + } + + /** Writes `bytes` back into the wasm heap at `pointer`. */ + public writeHeapSlice(pointer: number, bytes: Uint8Array): void { + this.heap.set(bytes, pointer) + } + + /** Wraps a wasm export so calling it runs Lua on a JSPI stack that can suspend. */ + public promising any>(fn: T): (...args: Parameters) => Promise> { + return (WebAssembly as unknown as { promising: (fn: T) => (...args: Parameters) => Promise> }).promising(fn) + } + + /** Wraps a JS callback so a Lua import can suspend the JSPI stack while it awaits. */ + public suspending(fn: (...args: any[]) => any): any { + return new (WebAssembly as unknown as { Suspending: new (fn: (...args: any[]) => any) => unknown }).Suspending(fn) + } + /** * Puts a JS callback in the indirect function table and returns the pointer Lua calls it * through. Release it with {@link removeFunction}. diff --git a/src/native/wasmoon.c b/src/native/wasmoon.c new file mode 100644 index 0000000..3261468 --- /dev/null +++ b/src/native/wasmoon.c @@ -0,0 +1,58 @@ +#include "lua.h" + +/* + * Twins of the lua_Integer entry points that take a double where the originals take a 64 bit + * integer. lua_Integer crosses the wasm boundary as a BigInt, so pushing a plain JS number would + * otherwise convert to BigInt on every call; these let a number that is a safe integer skip that. + */ + +void wasmoon_pushinteger(lua_State *L, double n) { + lua_pushinteger(L, (lua_Integer)n); +} + +int wasmoon_geti(lua_State *L, int idx, double n) { + return lua_geti(L, idx, (lua_Integer)n); +} + +int wasmoon_rawgeti(lua_State *L, int idx, double n) { + return lua_rawgeti(L, idx, (lua_Integer)n); +} + +void wasmoon_seti(lua_State *L, int idx, double n) { + lua_seti(L, idx, (lua_Integer)n); +} + +void wasmoon_rawseti(lua_State *L, int idx, double n) { + lua_rawseti(L, idx, (lua_Integer)n); +} + +/* + * The closure every JS function is pushed as. Its first upvalue is the reference box the function + * extension reads; its second is the call hook, a lua_CFunction stored as light userdata. + * + * The call hook runs the JS function. When it returns -1 the JS side has stashed a promise and + * asked to suspend, and the await hook is reached from this wasm frame with no JS frame in between, + * which is what the JSPI engine needs to switch the stack. The await hook is a plain never + * suspending stub under the fallback engine, where the call hook never returns -1. + */ + +static lua_CFunction await_hook; + +static int wasmoon_jsfunction(lua_State *L) { + lua_CFunction call_hook = (lua_CFunction)lua_touserdata(L, lua_upvalueindex(2)); + int n = call_hook(L); + if (n == -1) { + n = await_hook(L); + } + return n; +} + +void wasmoon_set_await_hook(lua_CFunction hook) { + await_hook = hook; +} + +/* Pops the reference box already on the stack and pushes the closure over it and call_hook. */ +void wasmoon_push_jsfunction(lua_State *L, lua_CFunction call_hook) { + lua_pushlightuserdata(L, (void *)call_hook); + lua_pushcclosure(L, wasmoon_jsfunction, 2); +} diff --git a/src/state.ts b/src/state.ts index aaad746..dd7fccc 100755 --- a/src/state.ts +++ b/src/state.ts @@ -259,9 +259,15 @@ export default class LuaState extends Thread { } } - /** Notified once when this state closes, so an owner can drop its reference. */ - public onClose(listener: () => void): void { + /** Notified once when this state closes, so an owner can drop its reference. Returns a function that removes the listener. */ + public onClose(listener: () => void): () => void { this.closeListeners.push(listener) + return () => { + const index = this.closeListeners.indexOf(listener) + if (index >= 0) { + this.closeListeners.splice(index, 1) + } + } } /** Closes the state and frees everything it owns. Safe to call more than once. */ diff --git a/src/thread.ts b/src/thread.ts index 1fdcf58..6ccdaf6 100755 --- a/src/thread.ts +++ b/src/thread.ts @@ -22,8 +22,10 @@ import { LuaTimeoutError, LuaType, type LuaWarnHandler, + PointerSize, } from './types' -import { isEmscriptenUnwind, isPromise, yieldToEventLoop } from './utils' +import { isEmscriptenUnwind, isPromise } from './utils' +import { awaitInterruptible, yieldToEventLoop } from './async' export interface OrderedExtension { // Bigger is more important @@ -126,6 +128,18 @@ export default class Thread { this.assertOk(this.module.luaL_loadfilex(this.address, filename, options?.mode ?? 't')) } + /** + * Unwinds the currently running coroutine at `L` with a limit error, the same way the debug + * hook does: the token identifies it in {@link assertOk}, so a `pcall` in the script cannot + * swallow it. Used by the JSPI await hook to abandon a run parked past its deadline or on an + * aborted signal. Returns what `lua_error` returns, which never actually returns. + */ + public interruptWith(L: LuaAddress, error: LuaInterruptError): number { + this.rootThread.pendingInterrupt = error + this.module.lua_pushlightuserdata(L, this.module.interruptToken) + return this.module.lua_error(L) + } + public resume(argCount = 0): LuaResumeResult { // Also covers the resumes `run` makes after an await, where the state can have been closed // by anything else that got to run in the meantime. @@ -165,10 +179,122 @@ export default class Thread { this.assertNotClosed() const restore = this.applyRunOptions(options) try { - let resumeResult: LuaResumeResult = this.resume(argCount) + if (this.module.useJspi) { + return await this.runJspi(argCount, options) + } + return await this.runYielding(argCount, options) + } finally { + restore() + } + } + + /** + * The engine-agnostic run loop. An `:await()` parks by yielding the promise, which is awaited + * here and can be interrupted by the deadline or abort signal. Any other yield is a host yield: + * its values go to `options.onYield`, and its return decides what the resume hands back. + */ + private async runYielding(argCount: number, options?: LuaRunOptions): Promise { + return this.continueYielding(this.resumeYielding(argCount), options) + } + + /** + * A resume of the yielding loop: an `:await()` it reaches must park by yielding the coroutine + * rather than suspending the wasm stack, since this resume is not a promising one. Forced off + * for the resume so a JSPI run parked elsewhere, which leaves the flag on, does not mislead it. + */ + public resumeYielding(argCount = 0): LuaResumeResult { + const previousCanSuspend = this.module.stackCanSuspend + this.module.stackCanSuspend = false + try { + return this.resume(argCount) + } finally { + this.module.stackCanSuspend = previousCanSuspend + } + } + + /** The yielding run loop, continued from an already obtained resume result. */ + public async continueYielding(first: LuaResumeResult, options?: LuaRunOptions): Promise { + let resumeResult: LuaResumeResult = first + while (resumeResult.result === LuaReturn.Yield) { + // The hook only fires while Lua runs, so a parked thread is checked here instead. + const limitError = this.checkYieldLimits() + if (limitError) { + if (resumeResult.resultCount > 0) { + this.pop(resumeResult.resultCount) + } + throw limitError + } + + // An unrepresentable yielded value is not necessarily an error: only an await needs to + // read it, and a host yield of one is handed to onYield as it lies on the stack. + let awaited: PromiseLike | undefined + if (resumeResult.resultCount > 0) { + let lastValue: unknown + try { + lastValue = this.getValue(-1) + } catch { + lastValue = undefined + } + if (isPromise(lastValue)) { + awaited = lastValue + } + } + + let nextArgCount = 0 + if (awaited) { + this.pop(resumeResult.resultCount) + const { deadline, signal } = this.getLimits() + await awaitInterruptible(awaited, signal, deadline) + } else if (options?.onYield) { + const values = this.getStackValues(this.getTop() - resumeResult.resultCount) + this.assertNotClosed() + const resumeWith = await options.onYield(values) + nextArgCount = this.pushResumeValues(resumeWith) + } else { + if (resumeResult.resultCount > 0) { + this.pop(resumeResult.resultCount) + } + // Skip a tick so promises, timers and the like get a turn before Lua resumes. + await yieldToEventLoop() + } + + // The wait itself can outlast the deadline, and resuming would hand Lua another full + // slice before the hook noticed. + const waitError = this.checkYieldLimits() + if (waitError) { + throw waitError + } + + resumeResult = this.resumeYielding(nextArgCount) + } + + this.assertOk(resumeResult.result) + return this.getStackValues() + } + + /** + * Runs under JSPI, so an `:await()` suspends the wasm stack instead of yielding a promise. Only + * a host `coroutine.yield` returns control here, and it is handled the same as in the yielding + * engine; the awaits resolve inside the promising resume without the loop seeing them. + */ + private async runJspi(argCount: number, options?: LuaRunOptions): Promise { + const module = this.module + const nresPointer = module.emscripten._malloc(PointerSize) + if (!nresPointer) { + throw new Error('failed to allocate the JSPI result count slot') + } + // A promising resume parked on an await cannot be interrupted from outside, and closing the + // state frees the stack it would resume into. This rejects the run instead; the await hook, + // seeing the state closed, stays suspended rather than resuming into freed memory. + const rootState = this.rootThread as unknown as { onClose(listener: () => void): () => void } + let onClosed: () => void = NO_RESTORE + const closed = new Promise((_resolve, reject) => { + onClosed = rootState.onClose(() => reject(new Error('the Lua state is closed'))) + }) + closed.catch(NO_RESTORE) + try { + let resumeResult = await Promise.race([this.resumeJspi(argCount, nresPointer), closed]) while (resumeResult.result === LuaReturn.Yield) { - // If it's completed there's no need to needlessly discard the output. The hook - // only fires while Lua runs, so a parked thread is checked here instead. const limitError = this.checkYieldLimits() if (limitError) { if (resumeResult.resultCount > 0) { @@ -176,48 +302,93 @@ export default class Thread { } throw limitError } - if (resumeResult.resultCount > 0) { - const lastValue = this.getValue(-1) - this.pop(resumeResult.resultCount) - // If there's a result and it's a promise, then wait for it. - if (isPromise(lastValue)) { - await lastValue - } else { - // If it's a non-promise, then skip a tick to yield for promises, timers, etc. - await yieldToEventLoop() - } - } else { - // If there's nothing to yield, then skip a tick to yield for promises, timers, etc. - await yieldToEventLoop() - } - - // The wait itself can outlast the deadline, and resuming would hand Lua another - // full slice before the hook noticed. - const waitError = this.checkYieldLimits() - if (waitError) { - throw waitError + let nextArgCount = 0 + if (options?.onYield) { + const values = this.getStackValues(this.getTop() - resumeResult.resultCount) + this.assertNotClosed() + const resumeWith = await options.onYield(values) + nextArgCount = this.pushResumeValues(resumeWith) + } else if (resumeResult.resultCount > 0) { + this.pop(resumeResult.resultCount) } - resumeResult = this.resume(0) + resumeResult = await Promise.race([this.resumeJspi(nextArgCount, nresPointer), closed]) } - this.assertOk(resumeResult.result) + // A parked run interrupted by its deadline or signal raises the interrupt into Lua, so a + // pcall in the script could swallow it and let the run finish. As with the debug hook, + // the interrupt still ends the run rather than being catchable from Lua. + const interrupt = this.rootThread.pendingInterrupt + if (interrupt) { + this.rootThread.pendingInterrupt = undefined + throw interrupt + } return this.getStackValues() } finally { - restore() + onClosed() + module.emscripten._free(nresPointer) + } + } + + /** + * One promising `lua_resume`. The promise it returns resolves only once the resume runs to a + * host yield, a return or an error -- an `:await()` in between suspends and resumes the wasm + * stack invisibly. The stack pointer is put back after the synchronous portion so a sync call + * made while this run is parked reuses the C stack rather than growing past it. + */ + private async resumeJspi(argCount: number, nresPointer: number): Promise { + this.assertNotClosed() + this.rootThread.pendingInterrupt = undefined + const module = this.module + const previousCanSuspend = module.stackCanSuspend + const previousDeadline = module.activeRunDeadline + const previousSignal = module.activeRunSignal + module.stackCanSuspend = true + const { deadline, signal } = this.getLimits() + module.activeRunDeadline = deadline + module.activeRunSignal = signal + const entryStackPointer = module.stackSave() + module.writePointer(nresPointer, 0) + try { + const pending = module.promisingResume()(this.address, null, argCount, nresPointer) + module.stackRestore(entryStackPointer) + const result: LuaReturn = await pending + return { result, resultCount: module.readPointer(nresPointer) } + } finally { + module.stackCanSuspend = previousCanSuspend + module.activeRunDeadline = previousDeadline + module.activeRunSignal = previousSignal + module.stackRestore(entryStackPointer) } } + /** Pushes the values a host yield resumes with, and returns how many. */ + private pushResumeValues(values: unknown): number { + if (values === undefined) { + return 0 + } + if (values instanceof MultiReturn) { + for (const value of values) { + this.pushValue(value) + } + return values.length + } + this.pushValue(values) + return 1 + } + public runSync(argCount = 0, options?: LuaRunOptions): MultiReturn { this.assertNotClosed() this.rootThread.pendingInterrupt = undefined const restore = this.applyRunOptions(options) + this.module.syncDepth++ try { const base = this.getTop() - argCount - 1 // The 1 is for the function to run this.assertOk(this.module.lua_pcallk(this.address, argCount, LUA_MULTRET, 0, 0, null)) return this.getStackValues(base) } finally { + this.module.syncDepth-- restore() } } @@ -239,7 +410,12 @@ export default class Thread { } const base = this.getTop() - args.length - 1 // The 1 is for the function to run - this.assertOk(this.module.lua_pcallk(this.address, args.length, LUA_MULTRET, 0, 0, null)) + this.module.syncDepth++ + try { + this.assertOk(this.module.lua_pcallk(this.address, args.length, LUA_MULTRET, 0, 0, null)) + } finally { + this.module.syncDepth-- + } return this.getStackValues(base) } diff --git a/src/type-extension.ts b/src/type-extension.ts index 9b4af45..c8a1c6d 100644 --- a/src/type-extension.ts +++ b/src/type-extension.ts @@ -1,7 +1,7 @@ import type { Decoration } from './decoration' import type LuaState from './state' import type Thread from './thread' -import { LUA_REGISTRYINDEX, type LuaGetCache, type LuaPushCache, LuaType } from './types' +import { type LuaAddress, LUA_REGISTRYINDEX, type LuaGetCache, type LuaPushCache, LuaType } from './types' export default abstract class LuaTypeExtension { // Type name, for metatables and lookups. @@ -107,10 +107,10 @@ export default abstract class LuaTypeExtension { * in Lua. With `closure`, a C function pointer, what is pushed and cached is instead a closure * over the box, which it sees as its first upvalue. */ - protected pushReference(thread: Thread, referent: unknown, closure?: number): void { + protected pushReference(thread: Thread, referent: unknown, wrapClosure?: (L: LuaAddress) => void): void { const module = thread.module const L = thread.address - const cachedType = closure === undefined ? LuaType.Userdata : LuaType.Function + const cachedType = wrapClosure === undefined ? LuaType.Userdata : LuaType.Function // The cache table stays at the bottom for the whole push, so the probe and the store // below share the one registry fetch. @@ -140,9 +140,9 @@ export default abstract class LuaTypeExtension { // -1 is the metatable, -2 is the box. module.lua_setmetatable(L, -2) - if (closure !== undefined) { - // Pops the box and pushes the closure holding it as an upvalue. - module.lua_pushcclosure(L, closure, 1) + if (wrapClosure !== undefined) { + // Pops the box and pushes a closure holding it as an upvalue. + wrapClosure(L) } // Remember the value for the next push of the same referent, then drop the cache table diff --git a/src/type-extensions/function.ts b/src/type-extensions/function.ts index e78fe3d..62157b0 100644 --- a/src/type-extensions/function.ts +++ b/src/type-extensions/function.ts @@ -4,8 +4,9 @@ import MultiReturn from '../multireturn' import RawResult from '../raw-result' import type Thread from '../thread' import TypeExtension from '../type-extension' -import { LUA_REGISTRYINDEX, LuaReturn, type LuaAddress, LuaType } from '../types' +import { LUA_REGISTRYINDEX, LuaReturn, type LuaAddress, type LuaResumeResult, LuaType } from '../types' import { isEmscriptenUnwind } from '../utils' +import { SUSPEND } from '../async' export type FunctionType = (...args: any[]) => Promise | any @@ -33,6 +34,9 @@ class FunctionTypeExtension extends TypeExtension { */ private readonly pooledCallThread: Thread private pooledCallThreadInUse = false + /** Registry reference anchoring each in-flight non-pooled call thread, so async calls that + * overlap can be released in any order rather than only as a stack. */ + private readonly callThreadReferences = new Map() /** Milliseconds a Lua function called from JS may run before being interrupted. */ private readonly functionTimeout: number | undefined @@ -96,7 +100,11 @@ class FunctionTypeExtension extends TypeExtension { try { const result = target.apply(decorationOptions?.self, args) - if (result === undefined) { + if (result === SUSPEND) { + // The JS function stashed a promise and asked to suspend: -1 tells the C + // trampoline to reach the await hook, which is the only value it treats specially. + return -1 + } else if (result === undefined) { return 0 } else if (result instanceof RawResult) { return result.count @@ -129,7 +137,11 @@ class FunctionTypeExtension extends TypeExtension { private acquireCallThread(): Thread { if (this.pooledCallThreadInUse) { - return this.callbackContext.newThread() + // Anchored rather than left on the callback context's stack: an async call keeps its + // thread past the return, so overlapping ones must release independently, not as a stack. + const { thread, reference } = this.callbackContext.newAnchoredThread() + this.callThreadReferences.set(thread, reference) + return thread } this.pooledCallThreadInUse = true @@ -139,8 +151,11 @@ class FunctionTypeExtension extends TypeExtension { private releaseCallThread(callThread: Thread, failed: boolean): void { if (callThread !== this.pooledCallThread) { callThread.close() - // Pop thread used for function call. - this.callbackContext.pop() + const reference = this.callThreadReferences.get(callThread) + if (reference !== undefined) { + this.callThreadReferences.delete(callThread) + this.state.module.luaL_unref(this.callbackContext.address, LUA_REGISTRYINDEX, reference) + } return } @@ -179,7 +194,10 @@ class FunctionTypeExtension extends TypeExtension { // the same function under different options stays distinct, as its behaviour is. const referent: unknown = affectsCall(decoration.options) ? decoration : decoration.target - this.pushReference(thread, referent, this.functionWrapper) + // Pushed through the C trampoline rather than a bare closure, so an `:await()` inside the + // function can suspend the wasm stack under JSPI. The trampoline holds the reference box as + // its first upvalue and the wrapper as its second. + this.pushReference(thread, referent, (L) => this.state.module.wasmoon_push_jsfunction(L, this.functionWrapper)) return true } @@ -204,6 +222,7 @@ class FunctionTypeExtension extends TypeExtension { // A call can leave its thread in an inconsistent state, so each one gets a thread that // is either fresh or has been reset since the last call. const callThread = this.acquireCallThread() + let handedOff = false let failed = false try { const internalType = callThread.module.lua_rawgeti(callThread.address, LUA_REGISTRYINDEX, func) @@ -223,19 +242,23 @@ class FunctionTypeExtension extends TypeExtension { callThread.setDeadline(Date.now() + this.functionTimeout) } - const status = callThread.module.lua_pcallk(callThread.address, args.length, 1, 0, 0, null) - if (status === LuaReturn.Yield) { - throw new Error('cannot yield in callbacks from javascript') + // Run on the coroutine rather than through lua_pcallk, so an `:await()` reached + // inside can park by yielding. If it does, the call has become asynchronous and a + // promise is returned; the common case runs to completion in this one resume. + const first = callThread.resumeYielding(args.length) + if (first.result === LuaReturn.Yield) { + handedOff = true + return this.finishAsyncCall(callThread, first) } - callThread.assertOk(status) - - // Asking for one result leaves exactly one, nil included, so the top is where it is. - return callThread.getValue(1) + callThread.assertOk(first.result) + return callThread.getTop() >= 1 ? callThread.getValue(1) : null } catch (err) { failed = true throw err } finally { - this.releaseCallThread(callThread, failed) + if (!handedOff) { + this.releaseCallThread(callThread, failed) + } } } @@ -243,6 +266,20 @@ class FunctionTypeExtension extends TypeExtension { return jsFunc } + + /** Drives a callback that parked on an await to completion, resolving to its first result. */ + private async finishAsyncCall(callThread: Thread, first: LuaResumeResult): Promise { + let failed = false + try { + const values = await callThread.continueYielding(first) + return values.length >= 1 ? values[0] : null + } catch (err) { + failed = true + throw err + } finally { + this.releaseCallThread(callThread, failed) + } + } } export default function createTypeExtension(state: LuaState, functionTimeout?: number): TypeExtension { diff --git a/src/type-extensions/promise.ts b/src/type-extensions/promise.ts index 5d5e81c..60a4db8 100644 --- a/src/type-extensions/promise.ts +++ b/src/type-extensions/promise.ts @@ -4,8 +4,9 @@ import MultiReturn from '../multireturn' import RawResult from '../raw-result' import type Thread from '../thread' import TypeExtension from '../type-extension' -import type { LuaAddress } from '../types' +import { type LuaAddress, LuaAbortError, LuaTimeoutError } from '../types' import { isPromise } from '../utils' +import { SUSPEND } from '../async' /** The half of an in flight `:await()` the continuation needs once the promise has settled. */ interface PendingAwait { @@ -90,11 +91,23 @@ class PromiseTypeExtension extends TypeExtension> { await: decorate( (functionThread: Thread, rawSelf: unknown) => { const self = asPromise(rawSelf) + const module = state.module - // Asking Lua covers every non-resumable context, not just the main - // thread: anything entered through lua_pcall cannot yield either. - if (!state.module.lua_isyieldable(functionThread.address)) { - throw new Error('cannot await in a thread that cannot yield, use doString instead of doStringSync') + // Under JSPI an await can suspend the wasm stack from anywhere, including a + // C-call boundary a yield could not cross, so long as the run reached here + // through a promising resume rather than a synchronous entry point. + if (module.useJspi && module.stackCanSuspend && module.syncDepth === 0) { + return this.suspend(functionThread, self) + } + + // Otherwise it can only park by yielding the coroutine, which a thread + // entered through lua_pcall (doStringSync, a JS→Lua callback) cannot do. + if (!module.lua_isyieldable(functionThread.address)) { + throw new Error( + module.useJspi + ? 'cannot await here: a synchronous call is on the stack, use doString instead of doStringSync' + : 'cannot await across a C-call boundary without JSPI; run this through doString', + ) } const pending: PendingAwait = { result: undefined } @@ -112,7 +125,7 @@ class PromiseTypeExtension extends TypeExtension> { // 1 result, because the yield hands the promise reference back so the // resume that follows can wait on it. functionThread.pushValue(awaitPromise) - return new RawResult(state.module.lua_yieldk(functionThread.address, 1, 0, this.continuancePointer)) + return new RawResult(module.lua_yieldk(functionThread.address, 1, 0, this.continuancePointer)) }, { receiveThread: true }, ), @@ -151,6 +164,51 @@ class PromiseTypeExtension extends TypeExtension> { } return super.pushValue(thread, decoration) } + + /** + * The JSPI await. It hands the promise and how to marshal its result to the module's await + * hook, then returns the sentinel that makes the C trampoline reach that hook and suspend the + * wasm stack. The stack unwinds to the promising resume driving the run and resumes there once + * the promise settles, so nothing here yields the Lua coroutine. + */ + private suspend(thread: Thread, promise: Promise): typeof SUSPEND { + const marshal = (value: unknown): number => { + if (value instanceof RawResult) { + return value.count + } + if (value instanceof MultiReturn) { + for (const item of value) { + thread.pushValue(item) + } + return value.length + } + thread.pushValue(value) + return 1 + } + + // Captured now so a deadline or abort observed while parked interrupts the run rather than + // waiting for the promise. Read from the resuming run, not this thread, whose JS wrapper is + // often a fresh object without the run's limits on it. + const deadline = this.state.module.activeRunDeadline + const signal = this.state.module.activeRunSignal + this.state.module.pendingSuspend = { + promise, + signal, + deadline, + isClosed: () => thread.isClosed(), + onResolve: marshal, + onReject: (error: unknown): number => { + thread.pushValue(error || new Error('promise rejected with no error')) + return this.state.module.lua_error(thread.address) + }, + onInterrupt: (): number => { + const error = + signal?.aborted === true ? new LuaAbortError('thread aborted') : new LuaTimeoutError('thread timeout exceeded') + return thread.interruptWith(thread.address, error) + }, + } + return SUSPEND + } } export default function createTypeExtension(state: LuaState, injectObject: boolean): TypeExtension> { diff --git a/src/types.ts b/src/types.ts index d733d9a..ffec947 100755 --- a/src/types.ts +++ b/src/types.ts @@ -1,3 +1,5 @@ +import type MultiReturn from './multireturn' + /** * An address in the wasm heap: a `lua_State`, or the storage behind a Lua value. Emscripten * function pointers are table indices rather than addresses, so those stay plain numbers. @@ -130,6 +132,13 @@ export interface LuaRunOptions { * promise before the abort is seen, rather than abandoning it mid-flight. */ signal?: AbortSignal | undefined + /** + * Called with the values of a top level `coroutine.yield` that is not an `:await()`. Its return + * becomes the result of that yield when the run resumes; a returned promise is awaited first, a + * `LuaMultiReturn` becomes several values, and `undefined` resumes with none. Without a handler + * such a yield simply hands control back to the event loop and resumes with nothing, as before. + */ + onYield?: ((values: MultiReturn) => unknown | Promise) | undefined } export interface LuaLoadOptions { diff --git a/src/utils.ts b/src/utils.ts index 1e97d47..c9b78f5 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -13,11 +13,15 @@ export const isPromise = (target: unknown): target is PromiseLike => { export const UNWIND_BRAND = '__emscriptenUnwind' /** - * Emscripten unwinds a Lua longjmp by throwing from its internal EmscriptenEH hierarchy. The wasm - * caller gates on `instanceof EmscriptenEH` to resume unwinding, so these have to be rethrown - * rather than raised as Lua errors. The class is module local, hence the brand. + * A Lua longjmp out of a C function that a JS callback is on the stack of, which has to be rethrown + * rather than turned into a Lua error. With `SUPPORT_LONGJMP=wasm` it is a `WebAssembly.Exception` + * the wasm caller resumes unwinding from; the branded `EmscriptenEH` covers the other unwinds + * Emscripten still throws from JS (its class is module local, hence the brand). */ export const isEmscriptenUnwind = (value: unknown): boolean => { + if (typeof WebAssembly.Exception === 'function' && value instanceof WebAssembly.Exception) { + return true + } return (value as Record | null | undefined)?.[UNWIND_BRAND] === true } diff --git a/test/async.test.js b/test/async.test.js new file mode 100644 index 0000000..f824f42 --- /dev/null +++ b/test/async.test.js @@ -0,0 +1,130 @@ +import { use } from 'chai' +import chaiAsPromised from 'chai-as-promised' + +use(chaiAsPromised) +import { expect } from 'chai' +import { LuaTimeoutError, LuaAbortError, LuaMultiReturn } from '../dist/index.js' +import { getState } from './utils.js' + +describe('Async engine', () => { + it('a top level coroutine.yield hands its values to onYield and resumes with its return', async () => { + using state = await getState() + const thread = state.newThread() + thread.loadString('local echoed = coroutine.yield(1, 2) return echoed') + + const seen = [] + const result = await thread.run(0, { + onYield: (values) => { + seen.push([...values]) + return values[0] + values[1] + }, + }) + + expect(seen).to.be.eql([[1, 2]]) + expect(result).to.be.eql([3]) + }) + + it('onYield can resume with several values', async () => { + using state = await getState() + const thread = state.newThread() + thread.loadString('local a, b = coroutine.yield() return a + b') + + const result = await thread.run(0, { onYield: () => LuaMultiReturn.of(4, 5) }) + expect(result).to.be.eql([9]) + }) + + it('an unrepresentable top level yield no longer crashes the run', async () => { + using state = await getState() + const result = await state.doString('coroutine.yield(io.stdout) return 7') + expect(result).to.be.equal(7) + }) + + it('a timeout interrupts a run parked on a promise promptly', async () => { + using state = await getState() + state.set('sleep', (ms) => new Promise((resolve) => setTimeout(resolve, ms))) + + const started = Date.now() + await expect(state.doString('sleep(1000):await() return 1', { timeout: 10 })).to.eventually.be.rejectedWith(LuaTimeoutError) + expect(Date.now() - started, 'interrupted well before the promise settles').to.be.below(500) + }) + + it('an abort signal interrupts a parked run promptly', async () => { + using state = await getState() + state.set('sleep', (ms) => new Promise((resolve) => setTimeout(resolve, ms))) + const controller = new AbortController() + setTimeout(() => controller.abort(), 10) + + const started = Date.now() + await expect(state.doString('sleep(1000):await() return 1', { signal: controller.signal })).to.eventually.be.rejectedWith( + LuaAbortError, + ) + expect(Date.now() - started).to.be.below(500) + }) + + it('interrupting a parked await is catchable by pcall on a fresh run', async () => { + using state = await getState() + state.set('sleep', (ms) => new Promise((resolve) => setTimeout(resolve, ms))) + + // The interrupt unwinds like a limit error: a pcall inside the script cannot swallow it. + await expect( + state.doString('local ok = pcall(function() sleep(1000):await() end) return ok', { timeout: 10 }), + ).to.eventually.be.rejectedWith(LuaTimeoutError) + }) + + describe('across a C-call boundary', () => { + const itJspi = (name, fn) => { + it(name, async function () { + using state = await getState() + if (!state.module.useJspi) { + this.skip() + } + await fn(state) + }) + } + + itJspi('awaits inside a table.sort comparator', async (state) => { + state.set('sleep', (ms) => new Promise((resolve) => setTimeout(() => resolve(ms), ms))) + const result = await state.doString(` + local t = {3, 1, 2} + table.sort(t, function(a, b) sleep(1):await() return a < b end) + return table.concat(t, ",") + `) + expect(result).to.be.equal('1,2,3') + }) + + itJspi('awaits inside a gsub callback', async (state) => { + state.set('sleep', (ms) => new Promise((resolve) => setTimeout(() => resolve(ms), ms))) + const result = await state.doString(`return (("abc"):gsub(".", function(c) sleep(1):await() return c:upper() end))`) + expect(result).to.be.equal('ABC') + }) + + itJspi('awaits inside a promise:next callback', async (state) => { + state.set('sleep', (ms) => new Promise((resolve) => setTimeout(() => resolve(ms), ms))) + const result = await state.doString(` + return sleep(1):next(function() sleep(1):await() return 15 end):await() + `) + expect(result).to.be.equal(15) + }) + + itJspi('awaits inside a coroutine nothing drives from the host', async (state) => { + state.set('sleep', (ms) => new Promise((resolve) => setTimeout(() => resolve(ms), ms))) + const result = await state.doString(` + local co = coroutine.wrap(function() return sleep(1):await() + 1 end) + return co() + `) + expect(result).to.be.equal(2) + }) + }) + + it('a state closed while a JSPI run is parked rejects rather than resuming into freed memory', async () => { + using state = await getState() + if (!state.module.useJspi) { + return + } + state.set('sleep', (ms) => new Promise((resolve) => setTimeout(resolve, ms))) + + const running = state.doString('sleep(20):await() return 1') + state.close() + await expect(running).to.eventually.be.rejectedWith('the Lua state is closed') + }) +}) diff --git a/test/bundling.test.js b/test/bundling.test.js index 05010f6..4ed5462 100644 --- a/test/bundling.test.js +++ b/test/bundling.test.js @@ -76,7 +76,7 @@ describe('Bundling', () => { state.set('yield', () => new Promise((resolve) => emitter.once('resolve', resolve))) const resPromise = state.doString(` local res = yield():next(function () - coroutine.yield() + ("x"):gsub(".", function() coroutine.yield() end) return 15 end) print("res", res:await()) diff --git a/test/promises.test.js b/test/promises.test.js index c839f88..73e8244 100644 --- a/test/promises.test.js +++ b/test/promises.test.js @@ -294,7 +294,7 @@ describe('Promises', () => { expect(() => { state.doStringSync(`sleep(5):await()`) - }).to.throw('cannot await in a thread that cannot yield') + }).to.throw('cannot await') }) it('an await abandoned mid flight should not leak a function table slot', async function () { diff --git a/test/state.test.js b/test/state.test.js index 68b1170..1e9d6db 100644 --- a/test/state.test.js +++ b/test/state.test.js @@ -1177,16 +1177,16 @@ describe('State', () => { expect(await state.doString('return value')).to.be.equal(1e300) }) - it('yielding in a JS callback into Lua does not break lua state', async () => { - // When yielding within a callback the error 'attempt to yield across a C-call boundary'. - // This test just checks that throwing that error still allows the lua global to be - // re-used and doesn't cause JS to abort or some nonsense. + it('yielding across a C-call boundary in a JS callback into Lua does not break lua state', async () => { + // A callback may await, but a coroutine.yield across a C-call boundary (here gsub's) still + // raises 'attempt to yield across a C-call boundary'. This checks that surfacing that error + // still leaves the lua global re-usable and doesn't cause JS to abort or some nonsense. using state = await getState() const testEmitter = new EventEmitter() state.set('yield', () => new Promise((resolve) => testEmitter.once('resolve', resolve))) const resPromise = state.doString(` local res = yield():next(function () - coroutine.yield() + ("x"):gsub(".", function() coroutine.yield() end) return 15 end) print("res", res:await()) diff --git a/test/utils.js b/test/utils.js index 7650f16..ea1a149 100644 --- a/test/utils.js +++ b/test/utils.js @@ -3,12 +3,16 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { LuaRuntime } from '../dist/index.js' +// Lets the whole suite run under either async engine: WASMOON_ASYNC=yield forces the fallback, +// 'jspi' requires JSPI, and the default lets the platform choose. +const asyncEngine = process.env.WASMOON_ASYNC + export const getLua = (options) => { - return LuaRuntime.load(options) + return LuaRuntime.load(asyncEngine ? { async: asyncEngine, ...options } : options) } export const getState = async (config = {}) => { - const lua = await LuaRuntime.load() + const lua = await getLua() return lua.createState({ inject: true, ...config, diff --git a/utils/build-wasm.sh b/utils/build-wasm.sh index fbdd773..19255ea 100755 --- a/utils/build-wasm.sh +++ b/utils/build-wasm.sh @@ -2,10 +2,8 @@ cd $(dirname $0) mkdir -p ../build/host -LUA_SRC=$(ls ../lua/*.c | grep -v "luac.c" | grep -v "lua.c" | tr "\n" " ") +LUA_SRC="$(ls ../lua/*.c | grep -v "luac.c" | grep -v "lua.c" | tr "\n" " ") ../src/native/wasmoon.c" -# Do not add --closure here: it renames properties, which would strip the brand the JS build puts on -# the glue's longjmp unwind classes (see rolldown.config.ts) and turn every unwind into a Lua error. if [ "$1" == "dev" ]; then extension=(-O0 -g3 -s ASSERTIONS=1 -s SAFE_HEAP=1 -s STACK_OVERFLOW_CHECK=2) @@ -17,6 +15,8 @@ fi # `glue.wasm`. COMMON=( -s WASM=1 + -s SUPPORT_LONGJMP=wasm + -I../lua "${extension[@]}" -s EXPORTED_RUNTIME_METHODS="[ 'addFunction', \ @@ -207,7 +207,14 @@ COMMON=( '_luaopen_debug', \ '_luaopen_package', \ '_luaL_openselectedlibs', \ - '_lua_gc' \ + '_lua_gc', \ + '_wasmoon_pushinteger', \ + '_wasmoon_geti', \ + '_wasmoon_rawgeti', \ + '_wasmoon_seti', \ + '_wasmoon_rawseti', \ + '_wasmoon_set_await_hook', \ + '_wasmoon_push_jsfunction' \ ]" ) From bf9fe9bdae6ffc35e569f7962ae22e6c2601de21 Mon Sep 17 00:00:00 2001 From: ceifa Date: Sun, 6 Sep 2026 18:17:36 -0300 Subject: [PATCH 65/83] simplify async model Quality cleanups from review, no behavior change: - collapse awaitInterruptible into settleOrInterrupt - share one settled-value marshaller (Thread.pushReturnValues; marshalResolved/marshalRejected) - centralize the abort/timeout classification in async.limitError - remove the syncDepth field, derivable from stackCanSuspend via one withSuspensionDisabled helper - extract the shared per-yield handling (throwIfLimitReached, handleHostYield) from the two run loops - drop the dead await-hook L parameter and inline the single-use heap-slice wrappers Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_012hBeqdFnHzBUQ7zLRVYQxx --- README.md | 2 +- src/async.ts | 55 ++++-------- src/module.ts | 24 ++---- src/thread.ts | 146 ++++++++++++++++---------------- src/type-extensions/function.ts | 15 +--- src/type-extensions/promise.ts | 74 ++++++++-------- 6 files changed, 134 insertions(+), 182 deletions(-) diff --git a/README.md b/README.md index b2e4334..d7648db 100644 --- a/README.md +++ b/README.md @@ -286,7 +286,7 @@ console.log(await handler(5)) // a promise, because the callback awaited #### Handling a top-level `coroutine.yield` -A top level `coroutine.yield` that is not an `:await()` is a *host yield*. Pass `onYield` to receive +A top level `coroutine.yield` that is not an `:await()` is a _host yield_. Pass `onYield` to receive its values and decide what the resume hands back; its return may be a promise, a `LuaMultiReturn` of several values, or a single value: diff --git a/src/async.ts b/src/async.ts index 7ebbdbd..488d3a8 100644 --- a/src/async.ts +++ b/src/async.ts @@ -5,6 +5,8 @@ * MessageChannel where it exists, because a browser clamps a nested setTimeout to 4ms while a * message post is not clamped; setImmediate under Node; setTimeout as the last resort. */ +import { LuaAbortError, type LuaInterruptError, LuaTimeoutError } from './types' + type Macrotask = (task: () => void) => void const macrotask: Macrotask = (() => { @@ -31,6 +33,21 @@ export const yieldToEventLoop = (): Promise => { return new Promise((resolve) => macrotask(resolve)) } +/** + * The interrupt a deadline or aborted signal calls for, or undefined when neither has fired. The + * single source of both the abort-vs-timeout classification and its message, shared by the debug + * hook's limit check and the JSPI await hook. + */ +export function limitError(signal: AbortSignal | undefined, deadline: number | undefined): LuaInterruptError | undefined { + if (signal?.aborted) { + return new LuaAbortError('thread aborted') + } + if (deadline !== undefined && Date.now() > deadline) { + return new LuaTimeoutError('thread timeout exceeded') + } + return undefined +} + /** * Awaits `promise` but resolves early if `signal` aborts or `deadline` passes, so a run parked on a * long promise can still be interrupted rather than waiting for it to settle. The abandoned promise @@ -41,43 +58,7 @@ export function awaitInterruptible( signal: AbortSignal | undefined, deadline: number | undefined, ): Promise { - if (signal === undefined && deadline === undefined) { - return Promise.resolve(promise).then(NOOP, NOOP) - } - - return new Promise((resolve) => { - let settled = false - const finish = (): void => { - if (settled) { - return - } - settled = true - if (timer !== undefined) { - clearTimeout(timer) - } - if (onAbort !== undefined) { - signal?.removeEventListener('abort', onAbort) - } - resolve() - } - - let timer: ReturnType | undefined - if (deadline !== undefined) { - timer = setTimeout(finish, Math.max(0, deadline - Date.now())) - } - - let onAbort: (() => void) | undefined - if (signal !== undefined) { - if (signal.aborted) { - finish() - return - } - onAbort = finish - signal.addEventListener('abort', onAbort, { once: true }) - } - - Promise.resolve(promise).then(finish, finish) - }) + return settleOrInterrupt(promise, signal, deadline).then(NOOP) } const NOOP = (): void => undefined diff --git a/src/module.ts b/src/module.ts index a0ba19e..efec15c 100755 --- a/src/module.ts +++ b/src/module.ts @@ -619,11 +619,6 @@ export default class LuaModule { * takes the yield path instead of trapping. */ public stackCanSuspend = false - /** - * Depth of synchronous entry points on the JS stack. While above zero an `:await()` cannot - * suspend or yield to the event loop, because the outermost caller is blocking. - */ - public syncDepth = 0 /** * The promise a JSPI `:await()` stashed for the C trampoline's await hook to suspend on, along * with how to marshal its settled value back onto the Lua stack. Read synchronously by the @@ -874,7 +869,9 @@ export default class LuaModule { */ private installAwaitHook(): void { this.awaitHookPointer = this.emscripten.addFunction( - this.suspending(async (L: LuaAddress): Promise => { + // The C signature passes the running coroutine, but it is always the one the await + // parked on, which the pendingSuspend marshallers already hold; nothing here needs it. + this.suspending(async (): Promise => { const suspend = this.pendingSuspend this.pendingSuspend = undefined if (suspend === undefined) { @@ -882,7 +879,7 @@ export default class LuaModule { } const stackPointer = this.stackSave() - const savedStack = this.readHeapSlice(stackPointer, this.mainStackPointer) + const savedStack = this.heap.slice(stackPointer, this.mainStackPointer) this.stackRestore(this.mainStackPointer) const outcome = await settleOrInterrupt(suspend.promise, suspend.signal, suspend.deadline) @@ -896,11 +893,10 @@ export default class LuaModule { // Back on this run's stack: put its frames back before touching Lua, and mark the // stack promising again for any further await this resume reaches. - this.writeHeapSlice(stackPointer, savedStack) + this.heap.set(savedStack, stackPointer) this.stackRestore(stackPointer) this.stackCanSuspend = true - void L if (outcome.interrupted) { return suspend.onInterrupt() } @@ -1096,16 +1092,6 @@ export default class LuaModule { this.emscripten.stackRestore(pointer) } - /** A copy of `[start, end)` of the wasm heap. Used to preserve a suspended run's C stack. */ - public readHeapSlice(start: number, end: number): Uint8Array { - return this.heap.slice(start, end) - } - - /** Writes `bytes` back into the wasm heap at `pointer`. */ - public writeHeapSlice(pointer: number, bytes: Uint8Array): void { - this.heap.set(bytes, pointer) - } - /** Wraps a wasm export so calling it runs Lua on a JSPI stack that can suspend. */ public promising any>(fn: T): (...args: Parameters) => Promise> { return (WebAssembly as unknown as { promising: (fn: T) => (...args: Parameters) => Promise> }).promising(fn) diff --git a/src/thread.ts b/src/thread.ts index 6ccdaf6..6dd0aea 100755 --- a/src/thread.ts +++ b/src/thread.ts @@ -6,7 +6,6 @@ import { defaultWarnHandler, LUA_MULTRET, LUA_REGISTRYINDEX, - LuaAbortError, type LuaAddress, LuaError, LuaEventMasks, @@ -19,13 +18,13 @@ import { LuaReturn, type LuaRunOptions, type LuaThreadLimits, - LuaTimeoutError, LuaType, type LuaWarnHandler, PointerSize, } from './types' import { isEmscriptenUnwind, isPromise } from './utils' -import { awaitInterruptible, yieldToEventLoop } from './async' +import { awaitInterruptible, limitError, yieldToEventLoop } from './async' +import RawResult from './raw-result' export interface OrderedExtension { // Bigger is more important @@ -134,10 +133,10 @@ export default class Thread { * swallow it. Used by the JSPI await hook to abandon a run parked past its deadline or on an * aborted signal. Returns what `lua_error` returns, which never actually returns. */ - public interruptWith(L: LuaAddress, error: LuaInterruptError): number { + public interruptWith(error: LuaInterruptError): number { this.rootThread.pendingInterrupt = error - this.module.lua_pushlightuserdata(L, this.module.interruptToken) - return this.module.lua_error(L) + this.module.lua_pushlightuserdata(this.address, this.module.interruptToken) + return this.module.lua_error(this.address) } public resume(argCount = 0): LuaResumeResult { @@ -198,32 +197,63 @@ export default class Thread { } /** - * A resume of the yielding loop: an `:await()` it reaches must park by yielding the coroutine - * rather than suspending the wasm stack, since this resume is not a promising one. Forced off - * for the resume so a JSPI run parked elsewhere, which leaves the flag on, does not mislead it. + * Runs `fn` with suspension forced off, so an `:await()` it reaches parks by yielding the + * coroutine rather than suspending the wasm stack. Every non-promising driver goes through here + * -- the yielding resume, and the synchronous `lua_pcallk` entry points -- so `stackCanSuspend` + * means exactly "the innermost driver is a promising resume", which is what the await guard reads. */ - public resumeYielding(argCount = 0): LuaResumeResult { + private withSuspensionDisabled(fn: () => T): T { const previousCanSuspend = this.module.stackCanSuspend this.module.stackCanSuspend = false try { - return this.resume(argCount) + return fn() } finally { this.module.stackCanSuspend = previousCanSuspend } } + /** A resume of the yielding loop, forced onto the yield path rather than a wasm suspension. */ + public resumeYielding(argCount = 0): LuaResumeResult { + return this.withSuspensionDisabled(() => this.resume(argCount)) + } + + /** + * Throws the pending limit error if this parked thread has exceeded its deadline or been + * aborted, dropping the yielded values first. The hook only fires while Lua runs, so a parked + * thread is checked here instead. + */ + private throwIfLimitReached(resumeResult: LuaResumeResult): void { + const error = this.checkYieldLimits() + if (error) { + if (resumeResult.resultCount > 0) { + this.pop(resumeResult.resultCount) + } + throw error + } + } + + /** + * Handles a host yield -- a top level `coroutine.yield` that is not an await -- by handing its + * values to `onYield` and returning how many values the resume passes back, or dropping them + * when there is no handler. + */ + private async handleHostYield(resumeResult: LuaResumeResult, options?: LuaRunOptions): Promise { + if (options?.onYield) { + const values = this.getStackValues(this.getTop() - resumeResult.resultCount) + this.assertNotClosed() + return this.pushReturnValues(await options.onYield(values)) + } + if (resumeResult.resultCount > 0) { + this.pop(resumeResult.resultCount) + } + return 0 + } + /** The yielding run loop, continued from an already obtained resume result. */ public async continueYielding(first: LuaResumeResult, options?: LuaRunOptions): Promise { let resumeResult: LuaResumeResult = first while (resumeResult.result === LuaReturn.Yield) { - // The hook only fires while Lua runs, so a parked thread is checked here instead. - const limitError = this.checkYieldLimits() - if (limitError) { - if (resumeResult.resultCount > 0) { - this.pop(resumeResult.resultCount) - } - throw limitError - } + this.throwIfLimitReached(resumeResult) // An unrepresentable yielded value is not necessarily an error: only an await needs to // read it, and a host yield of one is handed to onYield as it lies on the stack. @@ -245,17 +275,12 @@ export default class Thread { this.pop(resumeResult.resultCount) const { deadline, signal } = this.getLimits() await awaitInterruptible(awaited, signal, deadline) - } else if (options?.onYield) { - const values = this.getStackValues(this.getTop() - resumeResult.resultCount) - this.assertNotClosed() - const resumeWith = await options.onYield(values) - nextArgCount = this.pushResumeValues(resumeWith) } else { - if (resumeResult.resultCount > 0) { - this.pop(resumeResult.resultCount) + nextArgCount = await this.handleHostYield(resumeResult, options) + if (!options?.onYield) { + // Skip a tick so promises, timers and the like get a turn before Lua resumes. + await yieldToEventLoop() } - // Skip a tick so promises, timers and the like get a turn before Lua resumes. - await yieldToEventLoop() } // The wait itself can outlast the deadline, and resuming would hand Lua another full @@ -295,24 +320,8 @@ export default class Thread { try { let resumeResult = await Promise.race([this.resumeJspi(argCount, nresPointer), closed]) while (resumeResult.result === LuaReturn.Yield) { - const limitError = this.checkYieldLimits() - if (limitError) { - if (resumeResult.resultCount > 0) { - this.pop(resumeResult.resultCount) - } - throw limitError - } - - let nextArgCount = 0 - if (options?.onYield) { - const values = this.getStackValues(this.getTop() - resumeResult.resultCount) - this.assertNotClosed() - const resumeWith = await options.onYield(values) - nextArgCount = this.pushResumeValues(resumeWith) - } else if (resumeResult.resultCount > 0) { - this.pop(resumeResult.resultCount) - } - + this.throwIfLimitReached(resumeResult) + const nextArgCount = await this.handleHostYield(resumeResult, options) resumeResult = await Promise.race([this.resumeJspi(nextArgCount, nresPointer), closed]) } this.assertOk(resumeResult.result) @@ -363,18 +372,25 @@ export default class Thread { } } - /** Pushes the values a host yield resumes with, and returns how many. */ - private pushResumeValues(values: unknown): number { - if (values === undefined) { + /** + * Pushes a JS value onto the stack as Lua results and returns how many: nothing for `undefined`, + * `count` for a {@link RawResult}, one per element for a {@link MultiReturn}, else the single + * value. Shared by the run loops and the JS function wrapper. + */ + public pushReturnValues(value: unknown): number { + if (value === undefined) { return 0 } - if (values instanceof MultiReturn) { - for (const value of values) { - this.pushValue(value) + if (value instanceof RawResult) { + return value.count + } + if (value instanceof MultiReturn) { + for (const item of value) { + this.pushValue(item) } - return values.length + return value.length } - this.pushValue(values) + this.pushValue(value) return 1 } @@ -382,13 +398,13 @@ export default class Thread { this.assertNotClosed() this.rootThread.pendingInterrupt = undefined const restore = this.applyRunOptions(options) - this.module.syncDepth++ try { const base = this.getTop() - argCount - 1 // The 1 is for the function to run - this.assertOk(this.module.lua_pcallk(this.address, argCount, LUA_MULTRET, 0, 0, null)) + // A synchronous call: an `:await()` reached through it must yield rather than suspend, + // and then fail because a pcalled thread cannot yield. + this.withSuspensionDisabled(() => this.assertOk(this.module.lua_pcallk(this.address, argCount, LUA_MULTRET, 0, 0, null))) return this.getStackValues(base) } finally { - this.module.syncDepth-- restore() } } @@ -410,12 +426,7 @@ export default class Thread { } const base = this.getTop() - args.length - 1 // The 1 is for the function to run - this.module.syncDepth++ - try { - this.assertOk(this.module.lua_pcallk(this.address, args.length, LUA_MULTRET, 0, 0, null)) - } finally { - this.module.syncDepth-- - } + this.withSuspensionDisabled(() => this.assertOk(this.module.lua_pcallk(this.address, args.length, LUA_MULTRET, 0, 0, null))) return this.getStackValues(base) } @@ -873,14 +884,7 @@ export default class Thread { } private checkYieldLimits(): LuaInterruptError | undefined { - const { deadline, signal } = this.limits - if (signal?.aborted) { - return new LuaAbortError('thread aborted') - } - if (deadline !== undefined && Date.now() > deadline) { - return new LuaTimeoutError('thread timeout exceeded') - } - return undefined + return limitError(this.limits.signal, this.limits.deadline) } /** diff --git a/src/type-extensions/function.ts b/src/type-extensions/function.ts index 62157b0..d3c2906 100644 --- a/src/type-extensions/function.ts +++ b/src/type-extensions/function.ts @@ -1,7 +1,5 @@ import { Decoration, type DecorationOptions } from '../decoration' import type LuaState from '../state' -import MultiReturn from '../multireturn' -import RawResult from '../raw-result' import type Thread from '../thread' import TypeExtension from '../type-extension' import { LUA_REGISTRYINDEX, LuaReturn, type LuaAddress, type LuaResumeResult, LuaType } from '../types' @@ -104,19 +102,8 @@ class FunctionTypeExtension extends TypeExtension { // The JS function stashed a promise and asked to suspend: -1 tells the C // trampoline to reach the await hook, which is the only value it treats specially. return -1 - } else if (result === undefined) { - return 0 - } else if (result instanceof RawResult) { - return result.count - } else if (result instanceof MultiReturn) { - for (const item of result) { - calledThread.pushValue(item) - } - return result.length - } else { - calledThread.pushValue(result) - return 1 } + return calledThread.pushReturnValues(result) } catch (err) { if (isEmscriptenUnwind(err)) { throw err diff --git a/src/type-extensions/promise.ts b/src/type-extensions/promise.ts index 60a4db8..dc75dc6 100644 --- a/src/type-extensions/promise.ts +++ b/src/type-extensions/promise.ts @@ -64,21 +64,9 @@ class PromiseTypeExtension extends TypeExtension> { const continuanceThread = state.stateToThread(continuanceState) if (status === 'rejected') { - continuanceThread.pushValue(value || new Error('promise rejected with no error')) - return state.module.lua_error(continuanceState) - } - - if (value instanceof RawResult) { - return value.count - } else if (value instanceof MultiReturn) { - for (const arg of value) { - continuanceThread.pushValue(arg) - } - return value.length - } else { - continuanceThread.pushValue(value) - return 1 + return this.marshalRejected(continuanceThread, value) } + return this.marshalResolved(continuanceThread, value) }, 'iiii') this.defineMetatable({ @@ -95,8 +83,9 @@ class PromiseTypeExtension extends TypeExtension> { // Under JSPI an await can suspend the wasm stack from anywhere, including a // C-call boundary a yield could not cross, so long as the run reached here - // through a promising resume rather than a synchronous entry point. - if (module.useJspi && module.stackCanSuspend && module.syncDepth === 0) { + // through a promising resume rather than a synchronous entry point (which + // `stackCanSuspend` is exactly true for). + if (module.useJspi && module.stackCanSuspend) { return this.suspend(functionThread, self) } @@ -172,20 +161,6 @@ class PromiseTypeExtension extends TypeExtension> { * the promise settles, so nothing here yields the Lua coroutine. */ private suspend(thread: Thread, promise: Promise): typeof SUSPEND { - const marshal = (value: unknown): number => { - if (value instanceof RawResult) { - return value.count - } - if (value instanceof MultiReturn) { - for (const item of value) { - thread.pushValue(item) - } - return value.length - } - thread.pushValue(value) - return 1 - } - // Captured now so a deadline or abort observed while parked interrupts the run rather than // waiting for the promise. Read from the resuming run, not this thread, whose JS wrapper is // often a fresh object without the run's limits on it. @@ -196,19 +171,38 @@ class PromiseTypeExtension extends TypeExtension> { signal, deadline, isClosed: () => thread.isClosed(), - onResolve: marshal, - onReject: (error: unknown): number => { - thread.pushValue(error || new Error('promise rejected with no error')) - return this.state.module.lua_error(thread.address) - }, - onInterrupt: (): number => { - const error = - signal?.aborted === true ? new LuaAbortError('thread aborted') : new LuaTimeoutError('thread timeout exceeded') - return thread.interruptWith(thread.address, error) - }, + onResolve: (value: unknown) => this.marshalResolved(thread, value), + onReject: (error: unknown) => this.marshalRejected(thread, error), + // Reached only once interrupted, so the deadline has passed unless the signal aborted -- + // the recheck in checkYieldLimits does not apply here. + onInterrupt: () => + thread.interruptWith( + signal?.aborted ? new LuaAbortError('thread aborted') : new LuaTimeoutError('thread timeout exceeded'), + ), } return SUSPEND } + + /** Pushes a settled promise value as Lua results and returns how many; `undefined` becomes nil. */ + private marshalResolved(thread: Thread, value: unknown): number { + if (value instanceof RawResult) { + return value.count + } + if (value instanceof MultiReturn) { + for (const item of value) { + thread.pushValue(item) + } + return value.length + } + thread.pushValue(value) + return 1 + } + + /** Raises a rejected promise as a Lua error on `thread`. */ + private marshalRejected(thread: Thread, error: unknown): number { + thread.pushValue(error || new Error('promise rejected with no error')) + return this.state.module.lua_error(thread.address) + } } export default function createTypeExtension(state: LuaState, injectObject: boolean): TypeExtension> { From 55c7d963f0f800e69c150b7a8cd54ea9101be8ec Mon Sep 17 00:00:00 2001 From: ceifa Date: Mon, 7 Sep 2026 14:37:18 -0300 Subject: [PATCH 66/83] refact --- .github/workflows/test.yml | 5 + README.md | 36 +++-- bench/async.js | 73 +++++++++ src/async.ts | 64 ++++---- src/module.ts | 64 ++++++-- src/state.ts | 6 +- src/thread.ts | 278 +++++++++++++++++++++----------- src/type-extensions/function.ts | 6 + src/type-extensions/promise.ts | 75 ++++----- src/types.ts | 11 +- src/utils.ts | 11 -- test/async.test.js | 240 ++++++++++++++++++++++++++- test/browser.test.js | 30 ++++ test/bundling.test.js | 2 +- 14 files changed, 679 insertions(+), 222 deletions(-) create mode 100644 bench/async.js diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index f0519f5..9b41299 100755 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -11,6 +11,11 @@ jobs: strategy: matrix: node-version: [24] + async-engine: [yield, jspi] + + env: + WASMOON_ASYNC: ${{ matrix.async-engine }} + NODE_OPTIONS: ${{ matrix.async-engine == 'jspi' && '--experimental-wasm-jspi' || '' }} steps: - uses: actions/checkout@v7 diff --git a/README.md b/README.md index d7648db..aa9f537 100644 --- a/README.md +++ b/README.md @@ -248,25 +248,28 @@ try { ### Async engine -Under the hood there are two engines, chosen automatically at load: +There are two engines: -- **JSPI** (the default where the platform supports it: Chrome/Edge 137+, Firefox 153+, Node 25+). - An `:await()` suspends the whole WebAssembly stack, so it works **anywhere** — inside a - `table.sort` comparator, a `string.gsub` callback, a `promise:next` handler, a coroutine nothing - drives from the host, or a Lua function called back from JS. -- **Coroutine yielding** (the fallback, when JSPI is unavailable). An `:await()` parks by yielding - the running coroutine, so it works at the top level of a run and anywhere Lua can yield, but not - across a C-call boundary such as `table.sort` or `gsub`. Attempting that raises a clear error. - -Both engines share the same observable behaviour everywhere they can express it. Force one with the -`async` option, which is useful for testing or to keep behaviour identical across platforms: +- **Coroutine yielding** is the fallback when JSPI is unavailable. An `:await()` parks by yielding + the running coroutine, so it works at the top level of a run and anywhere Lua can yield. +- **JSPI** is selected automatically where available. It suspends the WebAssembly stack, allowing awaits across C-call + boundaries such as `table.sort` comparators and `string.gsub` callbacks, and inside + Lua-resumed coroutines. It requires a platform with JSPI support. ```js -const lua = await LuaRuntime.load({ async: 'yield' }) // 'auto' (default), 'jspi', or 'yield' +const lua = await LuaRuntime.load() // JSPI when available, yielding otherwise +const accelerated = await LuaRuntime.load({ async: 'jspi' }) // requires JSPI +const portable = await LuaRuntime.load({ async: 'yield' }) // coroutine yielding on every platform ``` +Both engines use the same run isolation, cancellation, and host-yield contract. Each run owns +its limits and interrupt state, even when several runs or states share a runtime. Repeated awaits +and host yields give the event loop a turn every 256 async steps, so timers can run without paying +for a macrotask on every await. + A run parked on a promise can be interrupted by a `timeout` or an `AbortSignal`, without waiting for -the promise to settle: +the promise to settle. This also applies while an `onYield` handler is pending; closing the state +rejects its parked runs and callbacks: ```js await state.doString('sleep(60000):await()', { timeout: 1000 }) // rejects after ~1s @@ -275,7 +278,8 @@ await state.doString('sleep(60000):await()', { timeout: 1000 }) // rejects after #### Awaiting in a JS→Lua callback A Lua function called from JS runs synchronously and returns its value directly. If it `:await()`s, -the call becomes asynchronous and returns a `Promise` instead: +the call becomes asynchronous and returns a `Promise` instead. These callbacks use coroutine +yielding even when JSPI is enabled, so they cannot await across C-call boundaries: ```js state.set('handler', null) @@ -301,3 +305,7 @@ const [result] = await thread.run(0, { }) console.log(result) // "pong" ``` + +A promise passed to `coroutine.yield` is a host value, not an internal await. The handler receives +it unchanged. Without a handler, yielded values are discarded and the coroutine resumes without +arguments. diff --git a/bench/async.js b/bench/async.js new file mode 100644 index 0000000..4cc9ab9 --- /dev/null +++ b/bench/async.js @@ -0,0 +1,73 @@ +// node --expose-gc bench/async.js [path/to/index.js] +// An alternate bundle makes before/after comparisons use exactly the same workloads. +import assert from 'node:assert/strict' +import { resolve } from 'node:path' +import { pathToFileURL } from 'node:url' + +const { LuaRuntime } = await import(pathToFileURL(resolve(process.argv[2] ?? 'dist/index.js')).href) +const median = (values) => values.sort((a, b) => a - b)[Math.floor(values.length / 2)] + +for (const engine of ['yield', 'jspi']) { + const runtime = await LuaRuntime.load({ async: engine }) + const state = runtime.createState({ inject: true, memory: { trace: true } }) + state.set('ready', Promise.resolve(1)) + state.set('add', (a, b) => a + b) + state.doStringSync('function addLua(a, b) return a + b end') + const addLua = state.get('addLua') + const workloads = { + '20k settled awaits': () => state.doString('local n = 0 for i=1,20000 do n = n + ready:await() end return n'), + '20k JS to Lua calls': () => { + for (let i = 0; i < 20000; i++) assert.equal(addLua(i, 1), i + 1) + }, + '20k Lua to JS calls': () => state.doStringSync('local n = 0 for i=1,20000 do n = add(n, 1) end return n'), + '1k async entries': async () => { + for (let i = 0; i < 1000; i++) assert.equal(await state.doString('return 1'), 1) + }, + 'CPU loop': () => state.doStringSync('local n = 0 for i=1,1000000 do n = n + i end return n'), + } + const timings = {} + for (const [name, run] of Object.entries(workloads)) { + for (let i = 0; i < 3; i++) await run() + const samples = [] + for (let i = 0; i < 7; i++) { + const start = performance.now() + await run() + samples.push(performance.now() - start) + } + timings[name] = Number(median(samples).toFixed(2)) + } + + const heapSamples = [] + const bufferSamples = [] + const luaSamples = [] + for (let sample = 0; sample < 5; sample++) { + let release + state.set( + 'gate', + new Promise((resolve) => { + release = resolve + }), + ) + state.gc.collect() + global.gc?.() + const before = process.memoryUsage() + const luaBefore = state.memory.used + const runs = Array.from({ length: 1000 }, () => state.doString('gate:await() return 1')) + await new Promise((resolve) => setTimeout(resolve, 20)) + global.gc?.() + const during = process.memoryUsage() + heapSamples.push(during.heapUsed - before.heapUsed) + bufferSamples.push(during.arrayBuffers - before.arrayBuffers) + luaSamples.push(state.memory.used - luaBefore) + release() + assert.ok((await Promise.all(runs)).every((value) => value === 1)) + } + console.log( + JSON.stringify({ + engine, + medianMs: timings, + parked1000: { jsHeapBytes: median(heapSamples), arrayBufferBytes: median(bufferSamples), luaBytes: median(luaSamples) }, + }), + ) + state.close() +} diff --git a/src/async.ts b/src/async.ts index 488d3a8..4a85f49 100644 --- a/src/async.ts +++ b/src/async.ts @@ -10,22 +10,18 @@ import { LuaAbortError, type LuaInterruptError, LuaTimeoutError } from './types' type Macrotask = (task: () => void) => void const macrotask: Macrotask = (() => { + if (typeof setImmediate === 'function') { + return (task: () => void) => void setImmediate(task) + } if (typeof MessageChannel === 'function') { const channel = new MessageChannel() const queue: Array<() => void> = [] channel.port1.onmessage = () => queue.shift()?.() - // Node keeps the event loop alive for an open port, which would stop a process exiting once - // its Lua work is done; unref lets it exit. A no-op in the browser, which has neither. - ;(channel.port1 as { unref?: () => void }).unref?.() - ;(channel.port2 as { unref?: () => void }).unref?.() return (task: () => void) => { queue.push(task) channel.port2.postMessage(null) } } - if (typeof setImmediate === 'function') { - return (task: () => void) => void setImmediate(task) - } return (task: () => void) => void setTimeout(task, 0) })() @@ -42,42 +38,23 @@ export function limitError(signal: AbortSignal | undefined, deadline: number | u if (signal?.aborted) { return new LuaAbortError('thread aborted') } - if (deadline !== undefined && Date.now() > deadline) { + if (deadline !== undefined && Date.now() >= deadline) { return new LuaTimeoutError('thread timeout exceeded') } return undefined } -/** - * Awaits `promise` but resolves early if `signal` aborts or `deadline` passes, so a run parked on a - * long promise can still be interrupted rather than waiting for it to settle. The abandoned promise - * is left to settle on its own and its result ignored. - */ -export function awaitInterruptible( - promise: PromiseLike, - signal: AbortSignal | undefined, - deadline: number | undefined, -): Promise { - return settleOrInterrupt(promise, signal, deadline).then(NOOP) -} - -const NOOP = (): void => undefined - export type SettleOutcome = | { interrupted: false; resolved: true; value: unknown } | { interrupted: false; resolved: false; error: unknown } - | { interrupted: true } + | { interrupted: true; error: LuaInterruptError } /** * Awaits `promise`, but reports an interruption instead if `signal` aborts or `deadline` passes * first. Used by the JSPI await hook, which unwinds the suspended run with a Lua error when it is * interrupted rather than waiting for the promise it was parked on. */ -export function settleOrInterrupt( - promise: PromiseLike, - signal: AbortSignal | undefined, - deadline: number | undefined, -): Promise { +export function settleOrInterrupt(promise: unknown, signal: AbortSignal | undefined, deadline: number | undefined): Promise { const settled: Promise = Promise.resolve(promise).then( (value) => ({ interrupted: false, resolved: true, value }), (error) => ({ interrupted: false, resolved: false, error }), @@ -103,17 +80,32 @@ export function settleOrInterrupt( } let timer: ReturnType | undefined - if (deadline !== undefined) { - timer = setTimeout(() => finish({ interrupted: true }), Math.max(0, deadline - Date.now())) + const scheduleDeadline = (): void => { + if (deadline === undefined) { + return + } + // Timers can fire early and delays above 2^31-1 overflow to 1ms in Node. + timer = setTimeout( + () => { + const error = limitError(signal, deadline) + if (error) { + finish({ interrupted: true, error }) + } else { + scheduleDeadline() + } + }, + Math.min(0x7fffffff, Math.max(0, deadline - Date.now())), + ) } + scheduleDeadline() let onAbort: (() => void) | undefined if (signal !== undefined) { if (signal.aborted) { - finish({ interrupted: true }) + finish({ interrupted: true, error: new LuaAbortError('thread aborted') }) return } - onAbort = () => finish({ interrupted: true }) + onAbort = () => finish({ interrupted: true, error: new LuaAbortError('thread aborted') }) signal.addEventListener('abort', onAbort, { once: true }) } @@ -126,3 +118,9 @@ export function settleOrInterrupt( * function extension turns it into the -1 the trampoline reads; nothing else produces it. */ export const SUSPEND: unique symbol = Symbol('wasmoon.suspend') + +/** One record per coroutine await, shared by the continuation and its host driver. */ +export interface PendingAwait { + promise: Promise + result: { status: 'fulfilled' | 'rejected'; value: unknown } | undefined +} diff --git a/src/module.ts b/src/module.ts index efec15c..159ea31 100755 --- a/src/module.ts +++ b/src/module.ts @@ -3,8 +3,18 @@ // `/// ` at the top of the emitted declarations to cover everyone // else. tsc drops the directive when it is written here, hence the build step. import initWasmModule from '../build/glue.js' -import { settleOrInterrupt } from './async' -import { defaultWarnHandler, LUA_REGISTRYINDEX, type LuaAddress, LuaReturn, LuaType, type LuaWarnHandler, PointerSize } from './types' +import { limitError, settleOrInterrupt, yieldToEventLoop } from './async' +import type Thread from './thread' +import { + defaultWarnHandler, + LUA_REGISTRYINDEX, + type LuaAddress, + type LuaInterruptError, + LuaReturn, + LuaType, + type LuaWarnHandler, + PointerSize, +} from './types' // A rolldown plugin will resolve this to the current version on package.json import version from 'package-version' @@ -97,10 +107,9 @@ export interface LuaModuleOptions { */ onWarn?: LuaWarnHandler | undefined /** - * Which async engine to run under. `'auto'` (the default) uses JSPI where the platform has it, - * so an `:await()` can suspend the wasm stack anywhere, and falls back to the coroutine - * yielding engine otherwise. `'jspi'` requires JSPI and throws if it is missing; `'yield'` - * forces the fallback, which is useful for tests and for matching the fallback's semantics. + * Which async engine to run under. `'auto'` (the default) uses JSPI where supported, with + * coroutine yielding as its fallback. `'jspi'` requires JSPI and throws if it is unavailable. + * `'yield'` uses coroutine yielding on every platform. */ async?: 'auto' | 'jspi' | 'yield' | undefined } @@ -626,23 +635,30 @@ export default class LuaModule { */ public pendingSuspend: | { + run: Thread promise: PromiseLike signal: AbortSignal | undefined deadline: number | undefined isClosed: () => boolean onResolve: (value: unknown) => number onReject: (error: unknown) => number - onInterrupt: () => number + onInterrupt: (error: LuaInterruptError) => number } | undefined private awaitHookPointer: number | undefined - /** - * The deadline and abort signal of the JSPI run currently resuming, so an `:await()` it reaches - * can be interrupted while parked. Set around each promising resume rather than read from the - * awaiting thread, whose JS wrapper is often a fresh object without the run's limits on it. - */ - public activeRunDeadline: number | undefined - public activeRunSignal: AbortSignal | undefined + /** The innermost Lua driver. Installed only while entering or continuing Lua. */ + public activeRun: Thread | undefined + private asyncSteps = 0 + + /** Amortized fairness across all runs; the common step allocates nothing. */ + public scheduleAsync(): Promise | undefined { + if (++this.asyncSteps < 256) { + return undefined + } + this.asyncSteps = 0 + return yieldToEventLoop() + } + /** * Whether runs on this module go through JSPI. On unless the platform lacks it or `async` asked * for the yielding engine, in which case an `:await()` can only park at a coroutine boundary. @@ -882,11 +898,19 @@ export default class LuaModule { const savedStack = this.heap.slice(stackPointer, this.mainStackPointer) this.stackRestore(this.mainStackPointer) - const outcome = await settleOrInterrupt(suspend.promise, suspend.signal, suspend.deadline) + this.activeRun = undefined + this.stackCanSuspend = false + const pause = this.scheduleAsync() + // Attach a rejection handler before yielding to the event loop. + const settling = settleOrInterrupt(suspend.promise, suspend.signal, suspend.deadline) + if (pause) { + await pause + } + const outcome = await settling // The state was closed while parked: lua_close has freed the stack this would // resume into, so stay suspended forever rather than resume into freed memory. The - // run itself was already rejected by runJspi's close race. + // run itself was already rejected by its close listener. if (suspend.isClosed()) { await new Promise(() => undefined) } @@ -896,9 +920,15 @@ export default class LuaModule { this.heap.set(savedStack, stackPointer) this.stackRestore(stackPointer) this.stackCanSuspend = true + this.activeRun = suspend.run if (outcome.interrupted) { - return suspend.onInterrupt() + return suspend.onInterrupt(outcome.error) + } + // A fairness pause can outlast the deadline even when the promise settled first. + const interrupt = limitError(suspend.signal, suspend.deadline) + if (interrupt) { + return suspend.onInterrupt(interrupt) } return outcome.resolved ? suspend.onResolve(outcome.value) : suspend.onReject(outcome.error) }), diff --git a/src/state.ts b/src/state.ts index dd7fccc..efd3d6f 100755 --- a/src/state.ts +++ b/src/state.ts @@ -292,10 +292,10 @@ export default class LuaState extends Thread { wrapper.extension.close() } - for (const listener of this.closeListeners) { - listener() + // Listeners may unsubscribe themselves while rejecting a parked run. + while (this.closeListeners.length > 0) { + this.closeListeners.pop()!() } - this.closeListeners.length = 0 } /** Folds the state wide budget in, so run() does the save and restore in one place. */ diff --git a/src/thread.ts b/src/thread.ts index 6dd0aea..85d13ce 100755 --- a/src/thread.ts +++ b/src/thread.ts @@ -22,8 +22,8 @@ import { type LuaWarnHandler, PointerSize, } from './types' -import { isEmscriptenUnwind, isPromise } from './utils' -import { awaitInterruptible, limitError, yieldToEventLoop } from './async' +import { isEmscriptenUnwind } from './utils' +import { limitError, type PendingAwait, settleOrInterrupt } from './async' import RawResult from './raw-result' export interface OrderedExtension { @@ -62,17 +62,43 @@ export default class Thread { */ protected readonly metatableNames: Map private closed = false + private running = false + private rejectRun: (() => void) | undefined + private removeCloseListener: (() => void) | undefined private hookFunctionPointer: number | undefined private hookCount = INSTRUCTION_HOOK_COUNT private limits: LuaThreadLimits = {} private instructionsUsed = 0 /** * The error the debug hook unwound the current run with. See {@link LuaModule.interruptToken} - * for why it is held here rather than pushed into Lua. Kept on the root thread, because the - * hook fires with whichever thread Lua is running -- a coroutine inherits it -- while the - * {@link assertOk} that reports it is the one the run was started on. + * for why it is held here rather than pushed into Lua. The hook can fire on a Lua-created + * coroutine, so it writes to the active driver, which also owns its limits and lifecycle. */ private pendingInterrupt: LuaInterruptError | undefined + // Only the root owns a map. Callback wrappers and run threads share its records. + private awaits: Map | undefined + + public getPendingAwait(address = this.address): PendingAwait | undefined { + return this.rootThread.awaits?.get(address) + } + + public setPendingAwait(address: LuaAddress, pending: PendingAwait): void { + ;(this.rootThread.awaits ??= new Map()).set(address, pending) + } + + public clearPendingAwait(address = this.address): void { + this.rootThread.awaits?.delete(address) + } + + /** Whether the host run loop owns this coroutine's yielded values. */ + public get isRunning(): boolean { + return this.running + } + + /** The driver itself is the run context; no separate context allocation is needed. */ + public get runLimits(): Readonly { + return this.limits + } public constructor(cmodule: LuaModule, typeExtensions: OrderedExtension[], address: number, parent?: Thread) { this.module = cmodule @@ -106,6 +132,7 @@ export default class Thread { public resetThread(): void { this.assertNotClosed() + this.clearPendingAwait() this.assertOk(this.module.lua_resetthread(this.address)) } @@ -134,7 +161,7 @@ export default class Thread { * aborted signal. Returns what `lua_error` returns, which never actually returns. */ public interruptWith(error: LuaInterruptError): number { - this.rootThread.pendingInterrupt = error + ;(this.module.activeRun ?? this).pendingInterrupt = error this.module.lua_pushlightuserdata(this.address, this.module.interruptToken) return this.module.lua_error(this.address) } @@ -143,13 +170,23 @@ export default class Thread { // Also covers the resumes `run` makes after an await, where the state can have been closed // by anything else that got to run in the meantime. this.assertNotClosed() - this.rootThread.pendingInterrupt = undefined + this.pendingInterrupt = undefined // The shared slot is safe for the same reason the one behind it is: C writes the count as it // returns and it is read straight after, with nothing interleaved. A nested resume has // finished with the slot by the time this one's lua_resume writes to it. const dataPointer = this.module.resultCountScratch this.module.writePointer(dataPointer, 0) - const luaResult = this.module.lua_resume(this.address, null, argCount, dataPointer) + const previousRun = this.module.activeRun + const previousCanSuspend = this.module.stackCanSuspend + this.module.activeRun = this + this.module.stackCanSuspend = false + let luaResult: LuaReturn + try { + luaResult = this.module.lua_resume(this.address, null, argCount, dataPointer) + } finally { + this.module.activeRun = previousRun + this.module.stackCanSuspend = previousCanSuspend + } return { result: luaResult, resultCount: this.module.readPointer(dataPointer), @@ -176,45 +213,77 @@ export default class Thread { public async run(argCount = 0, options?: LuaRunOptions): Promise { this.assertNotClosed() + if (this.running) { + throw new Error('the Lua thread is already running') + } const restore = this.applyRunOptions(options) + this.running = true try { - if (this.module.useJspi) { - return await this.runJspi(argCount, options) + if (!this.module.useJspi) { + const first = this.resumeYielding(argCount) + if (first.result !== LuaReturn.Yield) { + this.assertOk(first.result) + return this.getStackValues() + } + return await this.watchRun(this.driveYielding(first, options)) + } + const nresPointer = this.module.emscripten._malloc(PointerSize) + if (!nresPointer) { + throw new Error('failed to allocate the JSPI result count slot') + } + try { + return await this.watchRun(this.runJspi(argCount, nresPointer, options)) + } finally { + this.module.emscripten._free(nresPointer) } - return await this.runYielding(argCount, options) } finally { + this.finishRun() restore() } } - /** - * The engine-agnostic run loop. An `:await()` parks by yielding the promise, which is awaited - * here and can be interrupted by the deadline or abort signal. Any other yield is a host yield: - * its values go to `options.onYield`, and its return decides what the resume hands back. - */ - private async runYielding(argCount: number, options?: LuaRunOptions): Promise { - return this.continueYielding(this.resumeYielding(argCount), options) + /** One close listener and promise per asynchronous entry, rather than one race per resume. */ + private watchRun(pending: Promise): Promise { + return new Promise((resolve, reject) => { + const root = this.rootThread as unknown as { onClose(listener: () => void): () => void } + this.rejectRun = () => reject(new Error('the Lua state is closed')) + this.removeCloseListener = root.onClose(this.rejectRun) + pending.then(resolve, reject) + if (this.isClosed()) { + this.rejectRun() + } + }) + } + + private finishRun(): void { + this.removeCloseListener?.() + this.removeCloseListener = undefined + this.rejectRun = undefined + this.running = false + this.clearPendingAwait() } /** * Runs `fn` with suspension forced off, so an `:await()` it reaches parks by yielding the - * coroutine rather than suspending the wasm stack. Every non-promising driver goes through here - * -- the yielding resume, and the synchronous `lua_pcallk` entry points -- so `stackCanSuspend` - * means exactly "the innermost driver is a promising resume", which is what the await guard reads. + * coroutine rather than suspending the wasm stack. The synchronous `lua_pcallk` entry points + * use this scope; resume inlines it to avoid allocating a closure on the callback hot path. */ private withSuspensionDisabled(fn: () => T): T { const previousCanSuspend = this.module.stackCanSuspend + const previousRun = this.module.activeRun this.module.stackCanSuspend = false + this.module.activeRun = this try { return fn() } finally { this.module.stackCanSuspend = previousCanSuspend + this.module.activeRun = previousRun } } /** A resume of the yielding loop, forced onto the yield path rather than a wasm suspension. */ public resumeYielding(argCount = 0): LuaResumeResult { - return this.withSuspensionDisabled(() => this.resume(argCount)) + return this.resume(argCount) } /** @@ -240,8 +309,20 @@ export default class Thread { private async handleHostYield(resumeResult: LuaResumeResult, options?: LuaRunOptions): Promise { if (options?.onYield) { const values = this.getStackValues(this.getTop() - resumeResult.resultCount) + this.pop(resumeResult.resultCount) + const outcome = await settleOrInterrupt(options.onYield(values), this.limits.signal, this.limits.deadline) this.assertNotClosed() - return this.pushReturnValues(await options.onYield(values)) + const interrupt = this.checkYieldLimits() + if (interrupt) { + throw interrupt + } + if (outcome.interrupted) { + throw outcome.error + } + if (!outcome.resolved) { + throw outcome.error + } + return this.pushReturnValues(outcome.value) } if (resumeResult.resultCount > 0) { this.pop(resumeResult.resultCount) @@ -251,36 +332,43 @@ export default class Thread { /** The yielding run loop, continued from an already obtained resume result. */ public async continueYielding(first: LuaResumeResult, options?: LuaRunOptions): Promise { + this.assertNotClosed() + if (this.running) { + throw new Error('the Lua thread is already running') + } + this.running = true + try { + return await this.watchRun(this.driveYielding(first, options)) + } finally { + this.finishRun() + } + } + + private async driveYielding(first: LuaResumeResult, options?: LuaRunOptions): Promise { let resumeResult: LuaResumeResult = first while (resumeResult.result === LuaReturn.Yield) { this.throwIfLimitReached(resumeResult) - // An unrepresentable yielded value is not necessarily an error: only an await needs to - // read it, and a host yield of one is handed to onYield as it lies on the stack. - let awaited: PromiseLike | undefined - if (resumeResult.resultCount > 0) { - let lastValue: unknown - try { - lastValue = this.getValue(-1) - } catch { - lastValue = undefined - } - if (isPromise(lastValue)) { - awaited = lastValue - } - } - + const awaited = this.getPendingAwait() let nextArgCount = 0 if (awaited) { this.pop(resumeResult.resultCount) - const { deadline, signal } = this.getLimits() - await awaitInterruptible(awaited, signal, deadline) + if (this.limits.signal === undefined && this.limits.deadline === undefined) { + // The continuation's promise already records rejection, so the usual await + // needs no extra promise, reaction, or outcome object. + await awaited.promise + } else { + const outcome = await settleOrInterrupt(awaited.promise, this.limits.signal, this.limits.deadline) + if (outcome.interrupted) { + throw outcome.error + } + } } else { nextArgCount = await this.handleHostYield(resumeResult, options) - if (!options?.onYield) { - // Skip a tick so promises, timers and the like get a turn before Lua resumes. - await yieldToEventLoop() - } + } + const pause = this.module.scheduleAsync() + if (pause) { + await pause } // The wait itself can outlast the deadline, and resuming would hand Lua another full @@ -302,42 +390,32 @@ export default class Thread { * a host `coroutine.yield` returns control here, and it is handled the same as in the yielding * engine; the awaits resolve inside the promising resume without the loop seeing them. */ - private async runJspi(argCount: number, options?: LuaRunOptions): Promise { + private async runJspi(argCount: number, nresPointer: number, options?: LuaRunOptions): Promise { const module = this.module - const nresPointer = module.emscripten._malloc(PointerSize) - if (!nresPointer) { - throw new Error('failed to allocate the JSPI result count slot') - } - // A promising resume parked on an await cannot be interrupted from outside, and closing the - // state frees the stack it would resume into. This rejects the run instead; the await hook, - // seeing the state closed, stays suspended rather than resuming into freed memory. - const rootState = this.rootThread as unknown as { onClose(listener: () => void): () => void } - let onClosed: () => void = NO_RESTORE - const closed = new Promise((_resolve, reject) => { - onClosed = rootState.onClose(() => reject(new Error('the Lua state is closed'))) - }) - closed.catch(NO_RESTORE) - try { - let resumeResult = await Promise.race([this.resumeJspi(argCount, nresPointer), closed]) - while (resumeResult.result === LuaReturn.Yield) { - this.throwIfLimitReached(resumeResult) - const nextArgCount = await this.handleHostYield(resumeResult, options) - resumeResult = await Promise.race([this.resumeJspi(nextArgCount, nresPointer), closed]) + let resumeResult = await this.resumeJspi(argCount, nresPointer) + while (resumeResult.result === LuaReturn.Yield) { + this.throwIfLimitReached(resumeResult) + const nextArgCount = await this.handleHostYield(resumeResult, options) + const pause = module.scheduleAsync() + if (pause) { + await pause } - this.assertOk(resumeResult.result) - // A parked run interrupted by its deadline or signal raises the interrupt into Lua, so a - // pcall in the script could swallow it and let the run finish. As with the debug hook, - // the interrupt still ends the run rather than being catchable from Lua. - const interrupt = this.rootThread.pendingInterrupt + const interrupt = this.checkYieldLimits() if (interrupt) { - this.rootThread.pendingInterrupt = undefined throw interrupt } - return this.getStackValues() - } finally { - onClosed() - module.emscripten._free(nresPointer) + resumeResult = await this.resumeJspi(nextArgCount, nresPointer) + } + this.assertOk(resumeResult.result) + // A parked run interrupted by its deadline or signal raises the interrupt into Lua, so a + // pcall in the script could swallow it and let the run finish. As with the debug hook, + // the interrupt still ends the run rather than being catchable from Lua. + const interrupt = this.pendingInterrupt + if (interrupt) { + this.pendingInterrupt = undefined + throw interrupt } + return this.getStackValues() } /** @@ -348,26 +426,32 @@ export default class Thread { */ private async resumeJspi(argCount: number, nresPointer: number): Promise { this.assertNotClosed() - this.rootThread.pendingInterrupt = undefined + this.pendingInterrupt = undefined const module = this.module const previousCanSuspend = module.stackCanSuspend - const previousDeadline = module.activeRunDeadline - const previousSignal = module.activeRunSignal + const previousRun = module.activeRun module.stackCanSuspend = true - const { deadline, signal } = this.getLimits() - module.activeRunDeadline = deadline - module.activeRunSignal = signal + module.activeRun = this const entryStackPointer = module.stackSave() module.writePointer(nresPointer, 0) try { - const pending = module.promisingResume()(this.address, null, argCount, nresPointer) - module.stackRestore(entryStackPointer) + let pending: Promise + try { + pending = module.promisingResume()(this.address, null, argCount, nresPointer) + } finally { + // Restore the caller immediately, not when this suspended run eventually settles. + module.activeRun = previousRun + module.stackCanSuspend = previousCanSuspend + module.stackRestore(entryStackPointer) + } const result: LuaReturn = await pending + this.assertNotClosed() return { result, resultCount: module.readPointer(nresPointer) } } finally { - module.stackCanSuspend = previousCanSuspend - module.activeRunDeadline = previousDeadline - module.activeRunSignal = previousSignal + if (module.activeRun === this) { + module.activeRun = undefined + module.stackCanSuspend = false + } module.stackRestore(entryStackPointer) } } @@ -396,7 +480,7 @@ export default class Thread { public runSync(argCount = 0, options?: LuaRunOptions): MultiReturn { this.assertNotClosed() - this.rootThread.pendingInterrupt = undefined + this.pendingInterrupt = undefined const restore = this.applyRunOptions(options) try { const base = this.getTop() - argCount - 1 // The 1 is for the function to run @@ -415,7 +499,7 @@ export default class Thread { public call(name: string, ...args: any[]): MultiReturn { this.assertNotClosed() - this.rootThread.pendingInterrupt = undefined + this.pendingInterrupt = undefined const type = this.module.lua_getglobal(this.address, name) if (type !== LuaType.Function) { throw new TypeError(`cannot call '${name}': expected a function, got ${LuaType[type]}`) @@ -442,6 +526,10 @@ export default class Thread { } public stateToThread(L: LuaAddress): Thread { + const active = this.module.activeRun + if (active?.address === L) { + return active + } if (L === this.address) { return this } @@ -608,12 +696,17 @@ export default class Thread { return } + this.clearPendingAwait() + if (this === this.rootThread) { + this.awaits?.clear() + } if (this.hookFunctionPointer) { this.module.removeFunction(this.hookFunctionPointer) this.hookFunctionPointer = undefined } this.closed = true + this.rejectRun?.() } public [Symbol.dispose](): void { @@ -794,8 +887,7 @@ export default class Thread { * token nowhere on the stack, so whatever error did surface is still reported as itself. */ private takePendingInterrupt(stackTop: number): LuaInterruptError | undefined { - const root = this.rootThread - if (root.pendingInterrupt === undefined || stackTop === 0) { + if (this.pendingInterrupt === undefined || stackTop === 0) { return undefined } // The token is a heap address the module never hands to Lua, so nothing else can be at it. @@ -803,8 +895,8 @@ export default class Thread { return undefined } - const interrupt = root.pendingInterrupt - root.pendingInterrupt = undefined + const interrupt = this.pendingInterrupt + this.pendingInterrupt = undefined return interrupt } @@ -855,9 +947,9 @@ export default class Thread { this.hookFunctionPointer = this.module.addFunction((hookL: LuaAddress): void => { // Reads this.limits rather than closing over them, so a hook allocated for an // earlier configuration still honours the current one. - const error = this.checkHookLimits(hookL) + const error = (this.module.activeRun ?? this).checkHookLimits(hookL) if (error) { - this.rootThread.pendingInterrupt = error + ;(this.module.activeRun ?? this).pendingInterrupt = error this.module.lua_pushlightuserdata(hookL, this.module.interruptToken) this.module.lua_error(hookL) } diff --git a/src/type-extensions/function.ts b/src/type-extensions/function.ts index d3c2906..1b82b3c 100644 --- a/src/type-extensions/function.ts +++ b/src/type-extensions/function.ts @@ -136,6 +136,12 @@ class FunctionTypeExtension extends TypeExtension { } private releaseCallThread(callThread: Thread, failed: boolean): void { + callThread.clearPendingAwait() + if (this.state.isClosed()) { + this.callThreadReferences.delete(callThread) + this.pooledCallThreadInUse = false + return + } if (callThread !== this.pooledCallThread) { callThread.close() const reference = this.callThreadReferences.get(callThread) diff --git a/src/type-extensions/promise.ts b/src/type-extensions/promise.ts index dc75dc6..d2f5e53 100644 --- a/src/type-extensions/promise.ts +++ b/src/type-extensions/promise.ts @@ -4,14 +4,9 @@ import MultiReturn from '../multireturn' import RawResult from '../raw-result' import type Thread from '../thread' import TypeExtension from '../type-extension' -import { type LuaAddress, LuaAbortError, LuaTimeoutError } from '../types' +import type { LuaAddress } from '../types' import { isPromise } from '../utils' -import { SUSPEND } from '../async' - -/** The half of an in flight `:await()` the continuation needs once the promise has settled. */ -interface PendingAwait { - result: { status: 'fulfilled' | 'rejected'; value: any } | undefined -} +import { SUSPEND, type PendingAwait } from '../async' /** * A bare thenable reaches here too, and only `then` is guaranteed on one. Adopting it into a real @@ -26,11 +21,6 @@ const asPromise = (self: unknown): Promise => { } class PromiseTypeExtension extends TypeExtension> { - /** - * Keyed by the address of the thread parked in the await. A thread suspended in `lua_yieldk` - * cannot reach another `:await()`, so at most one is ever in flight per thread. - */ - private readonly pendingAwaits = new Map() /** * One continuation for every await on this state. Building one per await meant compiling and * instantiating a wasm trampoline each time, and leaked the table slot whenever the coroutine @@ -42,7 +32,7 @@ class PromiseTypeExtension extends TypeExtension> { super(state, 'js_promise') this.continuancePointer = state.module.addFunction((continuanceState: LuaAddress): number => { - const pending = this.pendingAwaits.get(continuanceState) + const pending = state.getPendingAwait(continuanceState) if (!pending) { // Nothing sensible is left to resume with, and returning would hand Lua a stack it // does not expect. @@ -60,7 +50,7 @@ class PromiseTypeExtension extends TypeExtension> { } const { status, value } = pending.result - this.pendingAwaits.delete(continuanceState) + state.clearPendingAwait(continuanceState) const continuanceThread = state.stateToThread(continuanceState) if (status === 'rejected') { @@ -99,22 +89,29 @@ class PromiseTypeExtension extends TypeExtension> { ) } - const pending: PendingAwait = { result: undefined } - this.pendingAwaits.set(functionThread.address, pending) - - const awaitPromise = self - .then((res) => { - pending.result = { status: 'fulfilled', value: res } - return res - }) - .catch((err) => { - pending.result = { status: 'rejected', value: err } - }) - - // 1 result, because the yield hands the promise reference back so the - // resume that follows can wait on it. - functionThread.pushValue(awaitPromise) - return new RawResult(module.lua_yieldk(functionThread.address, 1, 0, this.continuancePointer)) + const pending: PendingAwait = { + result: undefined, + promise: self.then( + (value) => { + pending.result = { status: 'fulfilled', value } + return value + }, + (value) => { + pending.result = { status: 'rejected', value } + }, + ), + } + state.setPendingAwait(functionThread.address, pending) + + // Host-driven awaits are registered out of band: no promise userdata or + // Lua stack value is needed. A manually resumed coroutine still receives + // its promise, preserving the low-level coroutine.resume contract. + let resultCount = 0 + if (!functionThread.isRunning) { + functionThread.pushValue(pending.promise) + resultCount = 1 + } + return new RawResult(module.lua_yieldk(functionThread.address, resultCount, 0, this.continuancePointer)) }, { receiveThread: true }, ), @@ -141,10 +138,6 @@ class PromiseTypeExtension extends TypeExtension> { public override close(): void { super.close() this.state.module.removeFunction(this.continuancePointer) - // A coroutine abandoned mid await never reaches its continuation, so its record is still - // here holding whatever the promise settled with. Nothing tells us when Lua's own GC took - // that coroutine, so these are bounded by the state's lifetime rather than the await's. - this.pendingAwaits.clear() } public pushValue(thread: Thread, decoration: Decoration): boolean { @@ -164,21 +157,17 @@ class PromiseTypeExtension extends TypeExtension> { // Captured now so a deadline or abort observed while parked interrupts the run rather than // waiting for the promise. Read from the resuming run, not this thread, whose JS wrapper is // often a fresh object without the run's limits on it. - const deadline = this.state.module.activeRunDeadline - const signal = this.state.module.activeRunSignal + const run = this.state.module.activeRun! + const { deadline, signal } = run.runLimits this.state.module.pendingSuspend = { + run, promise, signal, deadline, - isClosed: () => thread.isClosed(), + isClosed: () => run.isClosed(), onResolve: (value: unknown) => this.marshalResolved(thread, value), onReject: (error: unknown) => this.marshalRejected(thread, error), - // Reached only once interrupted, so the deadline has passed unless the signal aborted -- - // the recheck in checkYieldLimits does not apply here. - onInterrupt: () => - thread.interruptWith( - signal?.aborted ? new LuaAbortError('thread aborted') : new LuaTimeoutError('thread timeout exceeded'), - ), + onInterrupt: (error) => thread.interruptWith(error), } return SUSPEND } diff --git a/src/types.ts b/src/types.ts index ffec947..f1222ba 100755 --- a/src/types.ts +++ b/src/types.ts @@ -125,18 +125,17 @@ export interface LuaRunOptions { /** * Interrupts the run when the signal aborts. * - * The abort is observed at the debug hook and around every yield, which has two consequences. - * It cannot fire while the event loop is blocked, so a signal aborted from a timer will not - * interrupt a tight synchronous Lua loop; use `timeout` or `maxInstructions` for those, since - * the hook evaluates them on its own. And a run parked on a promise finishes awaiting that - * promise before the abort is seen, rather than abandoning it mid-flight. + * Interrupts parked awaits and onYield handlers without waiting for their promises to settle. + * A signal cannot fire while the event loop is blocked, so a timer cannot abort a tight Lua + * loop without async steps; use `timeout` or `maxInstructions` for those. Repeated awaits and + * host yields periodically give timers a turn. */ signal?: AbortSignal | undefined /** * Called with the values of a top level `coroutine.yield` that is not an `:await()`. Its return * becomes the result of that yield when the run resumes; a returned promise is awaited first, a * `LuaMultiReturn` becomes several values, and `undefined` resumes with none. Without a handler - * such a yield simply hands control back to the event loop and resumes with nothing, as before. + * such a yield resumes with nothing. Both engines periodically yield to the event loop. */ onYield?: ((values: MultiReturn) => unknown | Promise) | undefined } diff --git a/src/utils.ts b/src/utils.ts index c9b78f5..9cb46f8 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -24,14 +24,3 @@ export const isEmscriptenUnwind = (value: unknown): boolean => { } return (value as Record | null | undefined)?.[UNWIND_BRAND] === true } - -// Browsers have no setImmediate. The 4ms clamp on nested timers is acceptable here. -const scheduleMacrotask = typeof setImmediate === 'function' ? setImmediate : (task: () => void) => setTimeout(task, 0) - -/** - * A macrotask, so pending promise callbacks *and* timers get a chance to run before Lua is - * resumed. A microtask would starve timer driven code such as setTimeout based sleeps. - */ -export const yieldToEventLoop = (): Promise => { - return new Promise((resolve) => scheduleMacrotask(() => resolve())) -} diff --git a/test/async.test.js b/test/async.test.js index f824f42..d9b6317 100644 --- a/test/async.test.js +++ b/test/async.test.js @@ -1,9 +1,10 @@ +import { execFileSync } from 'node:child_process' import { use } from 'chai' import chaiAsPromised from 'chai-as-promised' use(chaiAsPromised) import { expect } from 'chai' -import { LuaTimeoutError, LuaAbortError, LuaMultiReturn } from '../dist/index.js' +import { LuaRuntime, LuaTimeoutError, LuaAbortError, LuaMultiReturn } from '../dist/index.js' import { getState } from './utils.js' describe('Async engine', () => { @@ -128,3 +129,240 @@ describe('Async engine', () => { await expect(running).to.eventually.be.rejectedWith('the Lua state is closed') }) }) + +// Run with WASMOON_ASYNC=yield and WASMOON_ASYNC=jspi; the same contract must hold under both. +describe('Async run isolation', () => { + it('preserves automatic engine selection', async () => { + await using runtime = await LuaRuntime.load() + expect(runtime.module.useJspi).to.equal(runtime.module.jspiSupported) + }) + + it('keeps Node alive until queued continuations finish, then exits', () => { + const entry = new URL('../dist/index.js', import.meta.url).href + const stdout = execFileSync( + process.execPath, + [ + '--input-type=module', + '-e', + ` + import { LuaRuntime } from ${JSON.stringify(entry)} + const runtime = await LuaRuntime.load({ async: 'yield' }) + const state = runtime.createState() + console.log(await state.doString('for i=1,1000 do coroutine.yield() end return 42')) + state.close() + `, + ], + { encoding: 'utf8', timeout: 5000 }, + ) + expect(stdout.trim()).to.equal('42') + }) + + it('a yielded promise is a host value, not an internal await', async () => { + using state = await getState() + const promise = new Promise(() => {}) + state.set('value', promise) + let seen + expect( + await state.doString('return coroutine.yield(1, value)', { + onYield: (values) => { + seen = values + return 42 + }, + }), + ).to.equal(42) + expect([...seen]).to.eql([1, promise]) + }) + + it('keeps host yield results off the stack between resumes', async () => { + using state = await getState() + expect( + await state.doString( + ` + for i = 1, 1000 do + local a, b = coroutine.yield(i, i + 1) + assert(a == i * 2 and b == i * 3) + end + return 42 + `, + { onYield: ([i]) => LuaMultiReturn.of(i * 2, i * 3) }, + ), + ).to.equal(42) + }) + + for (const expression of ['ready:await()', 'coroutine.yield()']) { + it(`lets timers run during repeated ${expression}`, async () => { + using state = await getState() + state.set('ready', Promise.resolve()) + let fired = false + state.set('fired', () => fired) + const timer = setTimeout(() => { + fired = true + }, 0) + try { + expect( + await state.doString(` + for i = 1, 10000 do + ${expression} + if fired() then return true end + end + return false + `), + ).to.equal(true) + } finally { + clearTimeout(timer) + } + }) + } + + it('keeps a deadline through a second await while another run is parked', async () => { + using state = await getState() + let releaseFirst, releaseOther + state.set( + 'first', + new Promise((resolve) => { + releaseFirst = resolve + }), + ) + state.set( + 'other', + new Promise((resolve) => { + releaseOther = resolve + }), + ) + state.set('never', new Promise(() => {})) + const timed = state.doString('first:await() never:await()', { timeout: 30 }) + const checked = expect(timed).to.eventually.be.rejectedWith(LuaTimeoutError) + const other = state.doString('other:await() return 42') + releaseFirst() + await checked + releaseOther() + expect(await other).to.equal(42) + }) + + it('keeps abort signals isolated across states sharing a module', async () => { + using state = await getState() + using other = new state.constructor(state.module) + let releaseFirst, reachedSecond + state.set( + 'first', + new Promise((resolve) => { + releaseFirst = resolve + }), + ) + state.set('never', new Promise(() => {})) + const second = new Promise((resolve) => { + reachedSecond = resolve + }) + state.set('second', reachedSecond) + const controller = new AbortController() + const checked = expect( + state.doString('first:await() second() never:await()', { + signal: controller.signal, + }), + ).to.eventually.be.rejectedWith(LuaAbortError) + const otherRun = other.doString('coroutine.yield() return 7') + releaseFirst() + await second + controller.abort() + await checked + expect(await otherRun).to.equal(7) + }) + + it('does not lose a caught interrupt when Lua starts another run', async () => { + using state = await getState() + if (!state.module.useJspi) return + state.set('never', new Promise(() => {})) + let nested + state.set('start', () => { + nested = state.doString('return 7') + }) + await expect( + state.doString( + ` + pcall(function() never:await() end) + start() + return 42 + `, + { timeout: 10 }, + ), + ).to.eventually.be.rejectedWith(LuaTimeoutError) + expect(await nested).to.equal(7) + }) + + it('interrupts a parked onYield handler', async () => { + using state = await getState() + await expect( + state.doString('coroutine.yield() return 42', { + timeout: 10, + onYield: () => new Promise(() => {}), + }), + ).to.eventually.be.rejectedWith(LuaTimeoutError) + }) + + it('does not overflow a long deadline while parked', async () => { + using state = await getState() + state.set('delayed', new Promise((resolve) => setTimeout(() => resolve(42), 10))) + expect(await state.doString('return delayed:await()', { timeout: 0x80000000 })).to.equal(42) + }) + + it('can abort a loop of immediately settled awaits', async () => { + using state = await getState() + state.set('ready', Promise.resolve()) + const controller = new AbortController() + const timer = setTimeout(() => controller.abort(), 0) + try { + await expect( + state.doString('while true do ready:await() end', { + signal: controller.signal, + timeout: 1000, + }), + ).to.eventually.be.rejectedWith(LuaAbortError) + } finally { + clearTimeout(timer) + } + }) + + it('rejects all parked runs and callbacks when the state closes', async () => { + using state = await getState() + state.set('never', new Promise(() => {})) + state.doStringSync('function callback() never:await() end') + const runs = [ + state.doString('never:await()'), + state.doString('never:await()'), + state.get('callback')(), + state.get('callback')(), + state.doString('coroutine.yield()', { onYield: () => new Promise(() => {}) }), + ] + const checked = runs.map((run) => expect(run).to.eventually.be.rejectedWith('the Lua state is closed')) + state.close() + await Promise.all(checked) + }) + + it('rejects a second run on an already running thread', async () => { + using state = await getState() + state.set('never', new Promise(() => {})) + const thread = state.newThread() + thread.loadString('never:await()') + const first = thread.run() + const checked = expect(first).to.eventually.be.rejectedWith('the Lua state is closed') + await expect(thread.run()).to.eventually.be.rejectedWith('already running') + thread.close() + await checked + }) + + it('can interleave many runs with different suspension depths and settlement orders', async () => { + using state = await getState() + state.set('pause', () => Promise.resolve()) + const runs = Array.from({ length: 32 }, (_, i) => + state.doString(` + local function recurse(n) + if n > 0 then return n + recurse(n - 1) end + for j = 1, 50 do pause():await() end + return ${i} + end + return recurse(${i}) + `), + ) + expect(await Promise.all(runs)).to.eql(Array.from({ length: 32 }, (_, i) => i + (i * (i + 1)) / 2)) + }) +}) diff --git a/test/browser.test.js b/test/browser.test.js index df3a134..74e9766 100644 --- a/test/browser.test.js +++ b/test/browser.test.js @@ -134,6 +134,36 @@ describe('Browser environment', () => { } } + for (const engine of ['yield', 'jspi']) { + it(`isolates async runs and lets timers run under ${engine}`, async function () { + this.timeout(30_000) + const result = await runInBrowser(` + const runtime = await LuaRuntime.load({ wasmFile, async: '${engine}' }) + const state = runtime.createState() + try { + let fired = false + state.set('ready', Promise.resolve()) + state.set('fired', () => fired) + setTimeout(() => { fired = true }, 0) + const fair = await state.doString('for i=1,10000 do ready:await() if fired() then return true end end return false') + let releaseFirst, releaseOther + state.set('first', new Promise((resolve) => { releaseFirst = resolve })) + state.set('other', new Promise((resolve) => { releaseOther = resolve })) + state.set('never', new Promise(() => {})) + const timed = state.doString('first:await() never:await()', { timeout: 30 }).catch((error) => error.name) + const other = state.doString('other:await() return 42') + releaseFirst() + const error = await timed + releaseOther() + return { fair, error, other: await other } + } finally { + state.close() + } + `) + expect(result).to.eql({ fair: true, error: 'LuaTimeoutError', other: 42 }) + }) + } + it('load Lua engine in browser should succeed', async function () { this.timeout(30_000) const result = await runInBrowser(` diff --git a/test/bundling.test.js b/test/bundling.test.js index 4ed5462..f8cf7a9 100644 --- a/test/bundling.test.js +++ b/test/bundling.test.js @@ -47,7 +47,7 @@ describe('Bundling', () => { }) const getMinifiedState = async (config = {}) => { - const lua = await minified.LuaRuntime.load({ wasmFile: WASM_FILE }) + const lua = await minified.LuaRuntime.load({ wasmFile: WASM_FILE, async: process.env.WASMOON_ASYNC }) return lua.createState({ inject: true, ...config }) } From d3e3f448fb096825138117e2bc5f03fd60847b98 Mon Sep 17 00:00:00 2001 From: ceifa Date: Sun, 15 Nov 2026 18:30:16 -0300 Subject: [PATCH 67/83] wip: uncommitted local work on better-async-model (2026-09-07) Snapshot of the working tree at /home/ceifa/Projects/wasmoon, on top of 55c7d96, pushed as-is for review. Not built or tested as part of this commit. --- docs/async-redesign/README.md | 2 +- docs/performance/README.md | 778 ++++++++++++++ docs/performance/async-entries.mjs | 18 + docs/performance/bindings.mjs | 21 + docs/performance/cache-memory.mjs | 26 + docs/performance/call-lua.mjs | 23 + docs/performance/callbacks.mjs | 29 + docs/performance/create-state.mjs | 22 + docs/performance/multiple-returns.mjs | 27 + docs/performance/read-table.mjs | 38 + docs/performance/ready-await-memory.mjs | 33 + docs/performance/reference-memory.mjs | 26 + docs/performance/references.mjs | 29 + docs/performance/retained-memory.mjs | 36 + docs/performance/runtime.mjs | 21 + docs/performance/settled-awaits.mjs | 17 + docs/performance/string-cache-memory.mjs | 16 + docs/performance/string-cache-variants.mjs | 142 +++ docs/performance/string-cache.mjs | 39 + docs/performance/string-decode.mjs | 57 ++ docs/performance/table-copy.mjs | 31 + docs/performance/vm.mjs | 42 + package.json | 3 +- rolldown.config.ts | 17 +- src/async.ts | 29 +- bin/wasmoon => src/cli.js | 4 +- src/declarations.d.ts | 5 + src/module.ts | 1072 +++++++++++--------- src/native/wasmoon.c | 28 +- src/state.ts | 22 +- src/thread.ts | 314 +++--- src/type-extension.ts | 24 +- src/type-extensions/function.ts | 28 +- src/type-extensions/promise.ts | 30 +- src/type-extensions/table.ts | 62 +- test/api.test.js | 84 ++ test/async.test.js | 37 + test/browser.test.js | 20 +- test/cli.test.js | 2 +- test/limits.test.js | 17 + test/promises.test.js | 17 + test/state.test.js | 17 + utils/build-wasm.sh | 16 +- 43 files changed, 2551 insertions(+), 770 deletions(-) create mode 100644 docs/performance/README.md create mode 100644 docs/performance/async-entries.mjs create mode 100644 docs/performance/bindings.mjs create mode 100644 docs/performance/cache-memory.mjs create mode 100644 docs/performance/call-lua.mjs create mode 100644 docs/performance/callbacks.mjs create mode 100644 docs/performance/create-state.mjs create mode 100644 docs/performance/multiple-returns.mjs create mode 100644 docs/performance/read-table.mjs create mode 100644 docs/performance/ready-await-memory.mjs create mode 100644 docs/performance/reference-memory.mjs create mode 100644 docs/performance/references.mjs create mode 100644 docs/performance/retained-memory.mjs create mode 100644 docs/performance/runtime.mjs create mode 100644 docs/performance/settled-awaits.mjs create mode 100644 docs/performance/string-cache-memory.mjs create mode 100644 docs/performance/string-cache-variants.mjs create mode 100644 docs/performance/string-cache.mjs create mode 100644 docs/performance/string-decode.mjs create mode 100644 docs/performance/table-copy.mjs create mode 100644 docs/performance/vm.mjs rename bin/wasmoon => src/cli.js (98%) diff --git a/docs/async-redesign/README.md b/docs/async-redesign/README.md index 4beda98..72043e0 100644 --- a/docs/async-redesign/README.md +++ b/docs/async-redesign/README.md @@ -58,7 +58,7 @@ doString(code) Lua JS func Relevant code: `Thread.run` (`src/thread.ts:158`), the promise extension (`src/type-extensions/promise.ts`), `FunctionTypeExtension.getValue` which calls Lua from JS with a synchronous `lua_pcallk` (`src/type-extensions/function.ts:191`), and the limit hook -(`src/thread.ts` `applyHook`/`checkYieldLimits`). +(`src/thread.ts` `applyHook`/`limitReached`). Properties of this model: diff --git a/docs/performance/README.md b/docs/performance/README.md new file mode 100644 index 0000000..ef22bc4 --- /dev/null +++ b/docs/performance/README.md @@ -0,0 +1,778 @@ +# Performance measurements + +2026-09-07, Node 26.7.0, baseline commit `55c7d96`. + +The table push path now creates its registry anchor without retrieving the table +again, initializes tables without a helper closure, and pushes known string keys +directly. Cycles and shared references still use the same registry anchors. + +Build the baseline and preserve its dist directory, then build the candidate. Run: + +```sh +node docs/performance/table-copy.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js +``` + +The harness alternates baseline/candidate order, discards six warmup rounds and +compares medians from eighteen measured rounds. Two runs of the final change: + +| Input | Median time reduction | +| ---------------------------------------------- | --------------------- | +| Empty object, 20,000 pushes | 3.1–3.9% | +| Three-field object, 20,000 pushes | 4.9–5.8% | +| Array of 2,000 three-field objects, 100 pushes | 4.8–4.9% | + +These are local microbenchmarks, not a whole-library speedup claim. + +The emitted index.js shrank from 114,958 to 114,949 bytes; the sum of individually +gzipped published dist files decreased by 5 bytes. Other emitted files were unchanged. + +With `memory: { trace: true }`, GC stopped, and ten pushes of the nested array, +both versions reported 19,265 bytes before, 2,762,186 after, and 44,499 after a full +collection. Both Wasm heaps were 17,891,328 bytes. The change adds no retained JS +data structures and removes a per-table closure; JS heap allocation was not profiled. + +Validation: 391 tests passed, formatting/lint passed, and `git diff --check` passed. +The full tests require browser server and child-process access outside the sandbox. + +## Array reads and Lua calls + +Sequence classification now runs in C, using the same ordered integer-key walk and +empty-table rule. This eliminates per-key Wasm crossings without allocating a +cache or temporary table. The helper uses public Lua APIs and leaves the stack +unchanged. Its raw export is used directly, avoiding a second binding on LuaModule. + +The Lua function wrapper now uses the result count returned by `lua_resume` +instead of calling `lua_gettop` again. No-result calls still return null, and +multiple-result calls still return only the first value. + +```sh +node docs/performance/read-table.mjs /absolute/baseline/dist /absolute/candidate/dist +node docs/performance/call-lua.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js +node --expose-gc docs/performance/retained-memory.mjs /absolute/candidate/dist/index.js +``` + +The isolated classification comparison uses a baseline already containing the +table-push and result-count changes. Two final runs measured 18.6% and 20.4% less +time reading flat 2,000-element arrays. Nested-table reads changed by 0.4–2.1%; +object-table reads ranged from effectively unchanged to 1.1% slower, within the +observed timing variation. The result-count change measured about 2–3% less time +for 100,000 Lua calls with zero, one, or multiple results. + +For all changes together, actual `npm pack` archives compared against `55c7d96`: + +| Measurement | Baseline | Candidate | +| ---------------- | ------------: | ------------: | +| Package archive | 178,091 bytes | 178,086 bytes | +| Unpacked package | 459,197 bytes | 459,181 bytes | + +The native binary grows by 104 bytes, offset by the smaller JavaScript and other +published changes. Summing individually gzipped files is not the same measurement +as the npm archive; the archive above is the package-size check. + +Lua allocation totals matched for flat arrays, nested tables, object tables, and +function calls. Each Wasm heap remained 17,891,328 bytes. Three separate-process +retained-memory runs with 20 live runtimes/states measured about 10.83 MB of JS +heap for the baseline and 9.96 MB for the candidate after forced GC. This is +evidence for the measured workloads, not a guarantee for every application. + +Validation on the final native build: 391 default-engine tests passed; 387 +fallback-engine tests passed with 4 JSPI-only tests skipped; the upstream Lua +suite finished with `final OK !!!`. A deterministic comparison of 2,000 mixed +table shapes matched the baseline and left both stacks empty. Regression coverage +now also includes numeric string, fractional, zero, and negative keys alongside +array entries. Formatting/lint and `git diff --check` passed. + +## Numeric binding setup + +Numeric exports now omit their redundant conversion signatures. The constructor +previously allocated 108 signature arrays and checked each entry before returning +the unchanged Wasm export. Missing-export validation remains, as do string +conversion and integer-range checks. The integer binding helper takes its argument +position directly instead of inferring it from another temporary signature array. + +```sh +node docs/performance/bindings.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js +node --expose-gc docs/performance/runtime.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js +``` + +The isolated baseline includes the earlier table and call optimizations. The first +constructor comparison measured 22.188 ms versus 19.815 ms for 1,000 wrappers, +10.7% less time; an isolated repeat measured 23.043 ms versus 20.057 ms, 13.0% +less time. The harness releases each wrapper's scratch allocations and uses +the yielding engine to avoid installing an await hook per wrapper. Full runtime +load, state creation, script execution, and close measured 24.625 ms versus +24.297 ms per ten runs, only 1.3% less time; Wasm instantiation dominates that +larger operation. These are warm-process measurements, not cold-start claims. + +The combined package now measures 177,862 bytes compressed and 455,691 bytes +unpacked, compared with 178,091 and 459,197 at the original baseline. The binding +change alone removes 3,490 unpacked bytes. Lua allocation totals and Wasm heap +capacity remain equal. A retained-memory comparison with twenty live runtimes +measured 10.57 MB of JS heap before this change and 9.72 MB after; this diagnostic +is sensitive to compilation and GC and is not a universal memory-saving claim. + +All 391 tests, formatting/lint, and `git diff --check` pass after the binding +change. A broader interop sweep reproduced the table-push and Lua-call gains; +number and short-string round trips and `doStringSync` were effectively unchanged. +Callback and proxy timings varied with process order. Paired callback measurements +against the original baseline were 1.5–2.6% slower, despite a separate-process +repeat being effectively unchanged. Against the build immediately before the +binding simplification, callbacks were 1.1% slower and proxy access 0.2% slower. +The paired harness is `docs/performance/callbacks.mjs` and +takes the same two index.js paths as the constructor benchmark. + +A subsequent control compared two byte-identical copies of the pre-callback +experiment build. The second copy measured 2.3% slower for callbacks and 0.9% +slower for proxy access. Thus the small callback difference above does not +establish a code regression; it is comparable to the harness's control variation. +Removing redundant optional chaining did not improve timings and was reverted. + +## Lazy extension identity caches + +Extensions now create their weak Lua identity cache on first access. Table copies +never use it, and other extensions do not need it until a value of their type is +pushed. The protected cache reference remains available through a getter, so +custom extensions reading it still receive an initialized registry reference. + +```sh +node docs/performance/create-state.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js +node docs/performance/cache-memory.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js +``` + +Against the preceding build, two runs measured these reductions in time for +200 state creations and closes: + +| Options | Time reduction | Lua bytes saved per fresh state | +| ---------------- | -------------: | ------------------------------: | +| Defaults | 5.8–9.3% | 392 | +| Object copying | 5.4–6.1% | 392 | +| Injected helpers | 2.4–4.8% | 392 | + +After first pushes of proxies, opaque userdata, promises, and errors, the candidate +still used 152 fewer Lua bytes. Repeated pushes retained Lua identity, and both +stacks were empty. After collection it also retained 152 fewer Lua bytes. Wasm +heap capacity stayed at 17,891,328 bytes. Repeated twenty-runtime JS retained-heap +measurements overlapped at roughly 9.71–9.74 MB; they do not demonstrate a JS heap +reduction. A callback/proxy comparison remained within the identical-build +control variation described above. + +The combined npm archive is now 177,960 bytes, with 455,889 bytes unpacked, both +below the original 178,091/459,197-byte baseline. Lazy initialization itself adds +98 compressed bytes and 198 unpacked bytes compared with the preceding build. +The default-engine suite passes all 391 tests after this change; the fallback +suite passes 387 with 4 JSPI-only tests skipped. Formatting/lint and diff checks pass. + +## Rejected numeric and compiler experiments + +Calling the existing native integer helper directly after `pushValue` validates a +safe integer did not improve the global or callback workloads and made the +isolated push loop roughly 10% slower. The duplicate-check bypass was reverted. +Inserting extensions in priority order instead of re-sorting the small list also +produced no convincing setup improvement and was reverted. + +The VM harness now covers arithmetic, table allocation/traversal, Lua calls, +string formatting/concatenation, and the existing heapsort fixture. It seeds Lua's +random generator equally for reproducible heapsort inputs: + +```sh +node docs/performance/vm.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js +``` + +Compiler experiments retained `-Oz` and the existing Binaryen passes: + +| Change | Wasm size | Outcome | +| ---------------------------- | ------------: | --------------------------------------------------------------- | +| Existing no-inline build | 193,278 bytes | Baseline before the JSPI fix | +| Add LTO, retain no-inline | 193,565 bytes | No overall VM gain; rejected | +| Remove no-inline | 194,056 bytes | Faster arithmetic/calls/heapsort, but async correctness failure | +| Remove no-inline and add LTO | 198,945 bytes | Exceeds the size budget; rejected | + +Default inlining initially looked useful: about 11% faster arithmetic, 6% faster +Lua calls and heapsort, and 1% faster table work, with string formatting about 4% +slower. Its full package still fit below the original size limit. However, the +full suite failed `can interleave many runs with different suspension depths and +settlement orders` with a WebAssembly exception. Running that test alone +reproduced the failure; restoring the previous no-inline artifacts made it pass. +That initial faster but incorrect build was discarded. The investigation and fix +below subsequently made inlining usable; the compiler change had exposed a race +in the library's JSPI stack restoration. + +Reproduction against either build: + +```sh +node_modules/.bin/mocha --exit --require ./test/boot.js test/async.test.js --grep 'different suspension depths' +``` + +## Synchronous JSPI restoration + +The async await hook used to restore a run's linear-memory C stack before resolving +its promise. There is a microtask gap between that resolution and Wasm resumption, +during which another ready run can restore its own frames over the first run's. +Disabling inlining hid the failure in the existing concurrent-depth test, but a +close-during-settlement stress check also made the old no-inline build trap. + +The await hook now returns an integer identifying a ready continuation. A second, +synchronous C hook consumes that continuation and restores the stack immediately +before Lua executes again. A local map holds only ready continuations; entries +are deleted before invocation, including when invocation throws. The synchronous +hook also checks that the state is still open, covering closure during the +promise-resolution gap. Per-await marshalling now uses one outcome callback +instead of four callbacks to offset the new bookkeeping. + +The final compiler configuration uses default `-Oz` inlining, without LTO. The +previously failing concurrent-depth test passes, along with the new close-timing +regression, all 392 default-engine tests, 388 fallback tests (4 JSPI-only skips), +and the upstream Lua suite. Formatting/lint and diff checks pass. + +Against the immediately preceding no-inline build, the VM harness measured: + +| Workload | Change in median time | +| ------------------------------- | --------------------: | +| Arithmetic | 10.6% lower | +| Table allocation/traversal | 1.5% lower | +| Lua calls | 5.6% lower | +| Heapsort | 5.8% lower | +| String formatting/concatenation | 4.2% higher | + +The correctness fix costs time on settled JSPI awaits: two runs of +`bench/async.js` measured 32.8–35.0 ms per 20,000 awaits versus 29.6–30.3 ms before +the fix. This regression is explicit; an unsynchronized restore is not an +acceptable optimization. Further reduction of continuation overhead remains open. + +For 1,000 parked JSPI runs, measured JS heap growth fell from 4,682,456 to +4,520,328 bytes. Saved-stack ArrayBuffer measurements varied between runs (roughly +28–35 KB before and 30–62 KB after), while Lua allocation growth stayed at +1,177,950 bytes. Total sampled memory was lower. The ready-await diagnostic +samples successive microtask boundaries; its largest observed heap-plus-buffer +delta fell from 5,367,528 to 5,204,872 bytes. Individual phases are not equivalent +work-completion points, so they must not be compared as if they were. + +```sh +node --expose-gc bench/async.js /absolute/candidate/dist/index.js +node --expose-gc docs/performance/ready-await-memory.mjs /absolute/candidate/dist/index.js +``` + +Adding `--close-before-resume` to the latter command exercises the closure stress +case that trapped in the previous no-inline build. The fixed build completes it. + +The combined package measures 178,043 bytes compressed and 456,582 unpacked, +still below the original 178,091/459,197-byte baseline. These are measured workload +results, not a claim that every program is faster or uses less memory. + +## Direct awaits and compact outcomes + +The no-limit JSPI path now awaits the user's promise directly and records its +result in a try/catch. This avoids the extra promise and reactions previously +created by `settleOrInterrupt`. Limited runs still use that helper. Both paths +observe settlement before waiting for the already-scheduled fairness pause, so +rejections cannot go unhandled during the pause. Stack restoration and the final +close/deadline check remain in the synchronous resume hook. + +Outcomes now have one `status` discriminator (`fulfilled`, `rejected`, or +`interrupted`) instead of two boolean flags. This reduces outcome size and lets +host-yield error handling combine its two equivalent throw branches. + +```sh +node docs/performance/settled-awaits.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js +``` + +Compared with the preceding synchronized implementation, two isolated alternating +comparisons measured 29.363/28.635 ms and 29.578/28.835 ms for 20,000 settled awaits, +about 2.5% less time. This recovers part of the synchronization overhead; it is +not a claim that all of that overhead has been removed. + +The 1,000-parked-run benchmark's JS heap delta fell from 4,520,328 to 4,304,520 +bytes, with unchanged Lua allocation growth of 1,177,950 bytes. The ready-await +diagnostic's largest sampled heap-plus-buffer delta fell from 5,204,896 to +5,041,160 bytes. As above, ArrayBuffer measurements and individual microtask +phases vary; these figures describe the sampled workloads. + +The combined package is 178,052 bytes compressed and 456,727 unpacked, below the +original 178,091/459,197-byte baseline. All 392 default-engine tests and 388 +fallback tests pass (4 JSPI-only skips), including the close-timing regression. +The close-before-resume stress diagnostic and formatting/lint/diff checks pass. + +## One limits snapshot per async entry + +An async entry previously called the state's public `getLimits()` (which copies +the configuration), then the child's `setLimits()` (which copies it again). +`LuaState` now forwards the protected configuration directly to `setLimits`, +retaining the child's independent snapshot and the public getter's copy semantics +while eliminating one temporary object per entry. + +```sh +node docs/performance/async-entries.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js +``` + +Two alternating comparisons of 1,000 short async entries measured: + +| Engine | First baseline/candidate median | Repeat baseline/candidate median | +| ------ | ------------------------------: | -------------------------------: | +| Yield | 2.312 / 2.150 ms | 2.334 / 2.214 ms | +| JSPI | 4.767 / 4.412 ms | 4.913 / 4.569 ms | + +That is 5–7% less time for this workload. Retained-memory samples were essentially +unchanged, as expected for removing a temporary copy rather than a retained +structure. The new deadline-isolation regression verifies that changing the +state's deadline leaves a parked run's snapshot intact and affects subsequent +runs. All 393 default-engine tests and 389 fallback tests pass (4 JSPI-only skips), +as do formatting/lint/diff checks. + +The combined archive remains 178,052 bytes. Its unpacked contents are 456,741 +bytes, 14 bytes above the preceding build because the protected field retains its +type in the declaration file. Both remain below the original +178,091/459,197-byte package baseline. + +## Shared return marshalling + +Promise resolution and callback returns now share `Thread.pushReturnValues`. +Its optional `nilOnUndefined` flag preserves the one intentional difference: +an awaited undefined produces one Lua nil, while a normal callback returning +undefined produces no values. The duplicate RawResult/MultiReturn dispatch and +element loop were removed from the promise extension. No cache or per-call +container was added. + +```sh +node docs/performance/multiple-returns.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js +``` + +The harness reuses a three-element MultiReturn to isolate marshalling from array +construction. Two comparisons of 20,000 multi-value JSPI awaits measured +32.344/31.167 ms and 33.808/32.708 ms, a 3.3–3.6% reduction. Callback and fallback +await differences stayed below 1%; scalar settled JSPI awaits varied by about +1.3%, so no gain is claimed for those paths. + +The ready-await diagnostic reported identical largest JS heap and ArrayBuffer +deltas before and after (4,815,616 and 224,000 bytes). The combined archive is +178,067 bytes and its unpacked contents are 456,701 bytes, below the original +178,091/459,197 baseline. Relative to the preceding build, unpacked size drops +40 bytes while archive size rises 15 bytes due to compression and declarations. + +The nil-versus-empty-return distinction now has explicit regression coverage. +All 394 default-engine tests and 390 fallback tests pass (4 JSPI-only skips), +along with formatting/lint/diff checks. + +## Reference registration failure handling + +`LuaModule.ref` used to consume a free slot and retain the value in its strong +map before WeakMap registration could reject an unsupported key. Failed calls +could therefore retain rejected values and lose reusable slots. The regression +check reproduced a jump from reusable slot 1 to slot 7 after six rejected values. + +Registration now lets WeakMap validate the key first, then consumes and assigns +the reference index and commits the strong entry. The metadata record is the +same allocation as before. Every committed strong entry consequently has +metadata, allowing the old orphan-entry cleanup branch in `unref` to be removed. +Tests verify failed calls leave existing references and reusable slots intact, +and that repeated references release a slot only after the final unref. + +```sh +node docs/performance/references.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js +``` + +The final 100,000-registration/release comparisons measured 19.331/19.374 ms +with immediate slot reuse and 21.199/21.284 ms with batch release, both within +0.5% of baseline. No speed gain is claimed; the result is unchanged measured +throughput with corrected failure handling and less cleanup code. An initial +peek-before-commit variant was discarded because it slowed immediate reuse. + +All 396 default-engine tests and 392 fallback tests pass (4 JSPI-only skips), +as do formatting/lint/diff checks. The combined package measures 178,061 bytes +compressed and 456,636 unpacked, below the original 178,091/459,197 baseline. + +## Short-string decoder experiments + +The current decoder gathers short ASCII bytes in a temporary array and calls +`String.fromCharCode.apply`. Two alternatives were rejected: scanning ASCII and +passing a typed-array view to `apply`, and scanning before allocating the array. +The first reduced the temporary array's element storage but made 1–32-byte ASCII +decodes 1.9–3.3 times slower. The second added a second traversal and slowed the +same cases by about 3–15%. Neither offered a consistent Unicode improvement. + +```sh +node docs/performance/string-decode.mjs +node docs/performance/string-decode.mjs --cutoff +``` + +This isolated JavaScript probe alternates variant order, discards five warmup +rounds, and measures twenty rounds of 200,000 decodes. It checks decoded values, +including embedded NUL, malformed UTF-8, and multibyte characters. Default output +orders variants as current array gathering, typed-array view, and scan-first +array gathering; cutoff mode replaces the third variant with direct TextDecoder. +It does not establish whole-library or browser performance. + +The cutoff probe measured array gathering/direct TextDecoder at 24.454/31.565 ms +for 32 bytes, 29.233/31.812 ms for 40 bytes, and 37.289/32.035 ms for 48 bytes. +The existing 32-byte limit is retained: extending it would only help a narrow +ASCII range while allocating larger temporary arrays, including for Unicode +inputs that ultimately use TextDecoder. No production change or speedup is +claimed from these experiments; memory usage and package size are unchanged. + +The broader performance goal remains open. These measurements cover startup, +table conversion, and interop, not every workload supported by the library. + +## Cached decoding of short strings + +Profiling the proxy and table-read workloads showed no dominant JavaScript hotspot: a +bare JS-to-wasm call costs about 4 ns, so the marshalling is spread thinly across the +extension dispatch, argument arrays, and string decoding, which took 7–9% of samples. +The names read out of Lua repeat: table keys, globals, metamethod keys. `readString` +now keeps the string it built for a run of up to 32 ASCII bytes in a 256-slot +direct-mapped cache keyed by a 32-bit hash of the bytes, and returns it when the same +bytes come round again. The bytes are compared only when the stored hash matches, so a +miss costs the hashing pass; a string is stored only on its second sighting, so a stream +of values read once (the elements of a table being copied) is never stored and cannot +push out the names read between them. Hits also hand `self[key]` lookups the same, +already internalized string. Non-ASCII and longer strings take the TextDecoder path as before. + +```sh +node docs/performance/string-cache-variants.mjs +node docs/performance/string-cache.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js +node --expose-gc docs/performance/string-cache-memory.mjs /absolute/candidate/dist/index.js +``` + +The isolated probe compares the decoder alone. Verifying bytes on every equal-length +slot, or storing on every miss, made streams of distinct strings 25–90% slower in +isolation; the hash guard and second-touch rule cut that to the hashing pass, about +6 ns per string, while keeping the repeated-name gains. Paired runs of the final +build against the `55c7d96`-based baseline: + +| Workload | Baseline / candidate median | Change | +| ---------------------------------------------------------- | --------------------------: | --------- | +| 100,000 `data.nested.value` proxy reads from Lua | 91.1 / 78.0 ms | 14% less | +| 100 reads of 2,000 `{id, name, active}` tables | 147.1 / 118.4 ms | 20% less | +| 100 reads of 2,000 integers under distinct string keys | 51.0 / 54.9 ms | 8% more | +| 20,000 global round trips, 8 and 24 character strings | 5.24 / 5.00 and 9.01 / 8.60 ms | 5% less | +| 50 reads of 2,000 distinct string keys and values | 36.3 / 38.3 ms | 6% more | + +Flat array reads, table pushes, Lua calls from JS, callbacks into JS, and the VM +workloads were unchanged within 1–3%. The regression is confined to short ASCII +strings that are each read once; it is the hashing pass, and is accepted for the gains +on the repeated names that make up most reads. + +Memory: the cache is per runtime, not per state. Twenty runtimes retained 9.70 MB of +JS heap before and 9.75 MB after, about 2.3 KB each for the two 256-entry hash arrays +and the slot array. Filling every slot with a 32-byte string retained 16 KB more than +the baseline in the worst case probe. Nothing is retained per state, and repeated +reads allocate fewer strings. The Wasm heap is unchanged at 17,891,328 bytes. + +## Package size and build targets + +The bundle now mangles module level names as well, keeping class names (`keepNames`) +so `LuaState.name` and console output are unchanged; helpers between the classes are +renamed, as they already are inside every method. The browser suite's inlined-page test +referred to the runtime by its bundle-internal name, so it now resolves it through the +export clause. The glue is built for the engines package.json declares (Node 24 and +the browserslist minimums), which drops a `node:crypto` fallback from both glues; the +Wasm is byte-identical. + +| Measurement | Original baseline | Before this change | Now | +| ---------------- | ----------------: | -----------------: | ------------: | +| Package archive | 178,091 bytes | 178,061 bytes | 177,822 bytes | +| Unpacked package | 459,197 bytes | 456,636 bytes | 455,025 bytes | + +## Rejected: native helpers for stack traffic + +Four C helpers were tried and reverted: the metatable address in one call, `lua_next` +returning both entry types, and a get/set pair for the pushed-value identity cache. +They removed two to three wasm calls per proxy read, table entry, or cached push. The +paired harnesses measured 0.4–1.7% on an idle machine (a first run under a concurrent +test suite showed a 20% swing in both directions, which did not reproduce), for 175 +more archive bytes from the export names in the Wasm and both glues. With a call +costing about 4 ns, a helper pays off only when it replaces a loop of calls, as +`wasmoon_isarray` does. + +Validation of the final build: 396 default-engine tests and 392 fallback-engine tests +pass (4 JSPI-only skips), the upstream Lua suite finishes with `final OK !!!`, and +formatting/lint and `git diff --check` pass. The Wasm binary is byte-identical to the +preceding build, so the VM measurements above are a control rather than a claim. + +## Derived bindings and a built CLI + +`LuaModule` used to name each of its 145 bindings in the constructor, one `cwrap` call per +export, which was 8.3 KB of the minified bundle. The bindings that cross only numbers are the wasm +exports themselves, so the constructor now fills every declared binding field still empty with the +export of its name, and only the 37 bindings that marshal a string are listed, in one string of +`name:signature` entries that the wrapper reads directly. The field declarations stay, since they +are what keeps the module out of V8 dictionary mode (`%HasFastProperties` still holds), and a +declared binding with no export still fails at construction rather than at first call. The four +helpers that never were exports (`lua_gc`, `lua_resetthread`, `lua_setcstacklimit`, +`luaL_openlibs`) are methods now, like `lua_pop` and `lua_remove`, so the fill pass has no +exceptions to know about and each module carries four fewer own fields and closures. + +The CLI is built by rolldown as a second entry, `dist/cli.js`, and `bin` points there. It imports +the library by the package's own name at run time rather than bundling a copy, and the source +moved to `src/cli.js`. Minified it is 4,687 bytes where `bin/wasmoon` shipped 15,547 bytes of +source. + +```sh +node docs/performance/bindings.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js +node --expose-gc docs/performance/runtime.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js +node --expose-gc docs/performance/retained-memory.mjs /absolute/candidate/dist/index.js +``` + +| Measurement | Before this change | Now | +| -------------------------- | -----------------: | ------------: | +| `dist/index.js` | 109,564 bytes | 102,407 bytes | +| CLI | 15,547 bytes | 4,687 bytes | +| Package archive | 177,822 bytes | 174,001 bytes | +| Unpacked package | 455,025 bytes | 437,691 bytes | + +Filling the fields by name costs the constructor: three paired runs measured 22.1/35.0, 21.3/33.6 +and 21.5/33.6 ms for 1,000 constructions, about 12 µs more each. The stores are keyed rather than +named, the fill pass reads each field once, and the signature string is split; a first version +that walked the module's exports (a dictionary of 177 entries) or tested a regex per field was +slower still, and was replaced. The construction happens once per `LuaRuntime.load`, which +instantiating the wasm dominates: two paired runs of ten load, create, run and close cycles +measured 23.31/23.17 and 23.23/23.46 ms, unchanged within the harness's variation. Twenty live +runtimes retained 9,688,440 bytes of JS heap against 9,751,312 before, and the Wasm heap stayed at +17,891,328 bytes. The wasm binary is unchanged. + +All 396 tests pass, including the CLI suite against the built entry, as do formatting/lint and +`git diff --check`. + +## A small initial heap and lighter reference bookkeeping + +Every heap snapshot so far reported the Wasm heap at 17,891,328 bytes, of which a fresh state used +about 20 KB: Emscripten's default `INITIAL_HEAP` is 16 MB, on top of the 1 MB stack and the static +data. The build now passes `-s INITIAL_HEAP=1MB` and relies on the `ALLOW_MEMORY_GROWTH` it already +had. A fresh runtime's memory is 2,162,688 bytes and the binary is one byte smaller. In Node the +untouched pages never cost RSS either way (a 17.9 MB memory that is never written adds nothing, +touching all of it adds 24 MB), so what this cuts is the address space reserved per runtime, what +`HEAPU8.length`, heap snapshots and browser memory panels count, and the footprint on platforms that +commit the initial memory. Twenty runtimes reserve 43 MB instead of 358 MB. + +Growing is cheap: from 2 MB to 18 MB in Emscripten's 20% steps is twelve `memory.grow` calls, which +measure 0.038 ms in total, and the module never caches a heap view across a call that can grow +(`heap` is a getter). A 200,000-table workload that holds 17.9 MB of Lua data ends at a 29,097,984 +byte heap against 30,998,528 before, since growth now follows the allocations rather than starting +from 16 MB. + +The JS side of a reference has changed too. `LuaModule.ref` used to allocate a metadata record per +JS value Lua holds and keep it in a `WeakMap`, alongside a `Map` from index to value and a list of +free indices. Values and counts are now two dense arrays indexed by the reference index, with the +free slots threaded through the counts array as negated links (a released slot's count is zero or +less), and the `WeakMap` maps a value to its index alone. The slot is taken only after the `WeakMap` +has accepted the value, so a primitive is still rejected without consuming one. `printRefs` walks +the arrays. Threads also start from one shared, frozen empty limits object instead of allocating +`{}` each, which a JS callback made from a Lua coroutine used to do on every call; `setDeadline` is +the one in-place writer and takes an object of its own first. + +```sh +node docs/performance/vm.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js +node docs/performance/callbacks.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js +node docs/performance/references.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js +node docs/performance/create-state.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js +node docs/performance/call-lua.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js +node --expose-gc docs/performance/retained-memory.mjs /absolute/candidate/dist/index.js +``` + +Memory, against the preceding build: + +| Measurement | Before | Now | +| ---------------------------------------------------- | -------------: | -----------: | +| Wasm heap of a fresh runtime | 17,891,328 | 2,162,688 | +| Heap snapshot self size per runtime plus state | 18,286,275 | 2,554,344 | +| JS heap per live reference (100,000 proxied objects) | 120 B | 62 B | +| JS heap retained after releasing those 100,000 | 1,258,496 | 1,987,336 | +| Lua bytes of a fresh state (default options) | 19,052 | 19,052 | + +The one number that grows is the last memory row: the arrays keep the capacity of the most +references ever live at once, where the maps shrank as entries left. That is 16 bytes per slot of +high-water mark, against half the cost while the references are live, and the third list this +design would have needed was folded into the counts array to keep it there. The 390 KB of JS objects +a runtime retains is otherwise unchanged; the largest single piece of it is Emscripten's 4,096-slot +filesystem name table (32 KB), which is generated code and was left alone. + +Time, medians of the paired harnesses on an idle machine. The Wasm change alone was measured before +the JS change was built: arithmetic 0.9% less, table 0.1% more, calls 0.3% less, strings 1.4% less, +heapsort 0.3% more, callbacks 0.2% less, proxy reads 0.2% more, all inside the control variation +recorded above. With both changes: 100,000 ref/unref pairs 19.28 / 9.70 ms with immediate reuse and +22.45 / 14.20 ms in batches (50% and 37% less); callbacks 17.18 / 16.67 ms and proxy reads +75.63 / 72.82 ms (3% and 4% less); state creation 7.2%, 3.6% and 0.4% less for the default, copying +and injected configurations; Lua calls from JS 1% to 3.5% less. + +One paired result was misleading and is recorded so it is not chased again: `async-entries.mjs` +showed the Wasm change alone 8.5% slower under both engines, but that harness loads two runtimes +into one process, and two *different* wasm binaries no longer share V8's compiled module the way two +copies of one binary do. The heap does not grow at all during that workload (2,162,688 bytes before +and after), and one build per process, alternated three times, spreads over ±15% with no direction +(yield 2.26–2.84 vs 2.25–2.48 ms, JSPI 4.86–5.13 vs 4.58–5.39 ms). The JS change alone in the same +paired harness measured 1.4% (yield) and 7.5% (JSPI) less time. + +The package is 174,011 bytes compressed and 437,914 unpacked, against 174,001 and 437,691: the +private fields carry line comments rather than doc comments, since tsc copies the latter into the +published declarations. All 396 default-engine tests pass, 392 fallback tests with 4 JSPI-only skips, +the upstream Lua suite finishes with `final OK !!!` (its peak memory growing the heap to 64 MB along +the way), and formatting/lint and `git diff --check` pass. + +Considered and not done: `dlmalloc` in place of `emmalloc` costs about 20 KB of wasm and has the same +8-byte rounding on the small blocks Lua allocates, so it would not shrink the heap; a smaller +`MEMORY_GROWTH_GEOMETRIC_STEP` only trims slack that is never touched; a smaller stack than 1 MB +trades untouched pages for silent corruption on deep C recursion; and moving the per-state function +and continuation trampolines to the module would save two `WebAssembly.Instance` objects per state +at the cost of finding the state from the `lua_State` on every callback. + +## Run loop and lifecycle simplification + +2026-09-07, Node 26.7.0, against the preceding build (same wasm). A structural pass over `Thread` +with no change in what runs per call: `run` and `continueYielding` share `startRun`, `watchRun` +and `finishRun`; the JSPI result slot is allocated inside `runJspi`; `runSync` and `call` go +through one `pcall` that saves and restores the active run inline, replacing the closure taking +`withSuspensionDisabled`; `resumeYielding`, an alias of `resume`, is gone; the deadline and abort +checks are `limitReached` and `assertLimits`, and the hook unwinds through `interruptWith`. Close +listeners live on the root thread, so `watchRun` no longer casts to reach `LuaState.onClose`. The +function extension releases its call thread on the two exits instead of tracking `handedOff` and +`failed` flags. The `promising`/`suspending` wrappers on `LuaModule` are replaced by typed +`WebAssembly.promising`/`Suspending` declarations, and `PendingSuspend` is a named type in +`async.ts`. + +The resume hook keeps its reference map: two parked runs whose promises settle in the same tick +have both hook continuations run before either wasm stack resumes, so a single slot would hand the +first run the second run's restore. + +`dist/index.js` 102,579 → 101,894 bytes. One build per process, alternated, medians of 15 rounds +(new vs before): JSPI settled awaits 27.4–28.2 vs 27.8–28.9 ms, Lua→JS calls 3.55–3.67 vs +3.50–3.66 ms, JS→Lua calls 2.97–3.28 vs 3.01–3.05 ms, async entries 5.18–6.06 vs 5.18–6.01 ms; +yield settled awaits 64.3–64.6 vs 63.8–70.3 ms. Every interop row moved less than 3%, inside its +run-to-run variation. 396 tests pass on the default and JSPI engines, 392 with 4 JSPI-only skips +on the fallback, and the upstream Lua suite finishes with `final OK !!!`. + +## Reference capacity reclamation and direct binding setup + +The reference arrays now discard released tails when at least half their slots can be dropped. +A highest-live-index counter makes the tail walk incremental; rebuilding the free list only +after halving capacity amortizes that work. Tables of at most 256 slots retain their capacity +for reuse. Live indices never move, including indices held by other states. This addresses the +post-release memory regression recorded above without returning to a map and metadata record +per reference. A live reference near the high end still prevents reclamation of earlier holes; +this does not establish a universal bound in terms of the number of live references. + +```sh +node --expose-gc docs/performance/reference-memory.mjs /absolute/baseline/dist/index.js +node --expose-gc docs/performance/reference-memory.mjs /absolute/candidate/dist/index.js +node docs/performance/references.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js +``` + +The memory probe warms registration first, keeps one low-index reference alive, then registers +and releases 100,000 objects. In the final comparison, JS heap growth while live was +11,690,296 / 11,690,608 bytes; after release it was 1,897,864 / 1,208 bytes. Repeats of the +candidate's released measurement ranged up to about 4 KB. Wasm heap capacity stayed at +2,162,688 bytes. The older map-based implementation measured 17,469,432 live and 923,032 +released bytes with this same probe. + +Trimming adds work: paired comparisons against the untrimmed arrays cost roughly 3–9% on +100,000 registration/release loops. Compared with the older map-based implementation, the +candidate still measured about 45% less time with immediate reuse and 34–37% less with batch +release. Callback and proxy comparisons varied in direction between runs; no interop speedup +is claimed from this change. + +Binding construction now uses explicit assignments again, keeping the numeric exports direct +and the compact string conversion signatures. This removes enumeration, computed binding +stores, signature splitting and substring allocations from each constructor. Binding fields +are type-only declarations; explicit stores keep V8 fast properties without first initializing +all 146 fields to undefined. Both variants were checked with `%HasFastProperties`. + +Against the reflective constructor, final paired runs took 20.5–20.8 ms rather than +33.8–34.5 ms per 1,000 wrappers, about 38–41% less time. Full load/create/run/close comparisons +were unchanged to 2% faster; Wasm instantiation dominates those operations. Twenty-runtime +retained-JS-heap probes measured about 10.48 MB before and 10.51 MB after this binding change, +so the larger generated code has a small retained cost despite eliminating transient arrays. +The overall memory constraint still needs broader auditing, particularly sparse reference +tables and the decoded-string cache; these results do not prove it for all workloads. + +The final npm archive is 174,453 bytes and unpacks to 442,767 bytes, below the original +178,091 / 459,197-byte baseline. The native binary is byte-identical to the preceding build. +Validation: 397 default-engine tests, 393 fallback tests with 4 JSPI-only skips, upstream Lua's +`final OK !!!`, formatting/lint and diff checks pass. The regression test covers partial and +descending releases, duplicate holders, live-index preservation and slot reuse. A separate +102,400-registration randomized comparison against a JS Map preserved all live values and +indices. All 146 binding fields match the previous build; missing numeric, string and native +exports still fail during construction. + +## Sparse references and a smaller decoder cache + +The sparse-reference audit kept one high-index reference alive after releasing 100,000 lower +ones. Tail trimming cannot help that case: the two arrays retained about 1.90 MB, versus +0.92 MB for the original map and free-list implementation. Replacing the value array with a +Map reduced retention but made registration/release 42–69% slower than the two arrays, so +that experiment was discarded. + +References now use one array. A live slot contains `{ value, count }`; a released slot contains +the negated next free index. Records disappear on release, leaving one backing slot per hole, +as in the original free list. External indices remain one-based, and the array itself is +zero-based. This also avoids paying for a second array while a high live index prevents trimming. + +```sh +node --expose-gc --no-flush-bytecode docs/performance/reference-memory.mjs /absolute/baseline/dist/index.js high +node --expose-gc --no-flush-bytecode docs/performance/reference-memory.mjs /absolute/candidate/dist/index.js high +``` + +The final comparison against the original baseline measured 17.46 / 14.71 MB of incremental +live JS heap, and 0.920 / 0.922 MB after release. Including the runtime and compiled code, +post-release JS heap was 6,055,616 / 6,038,448 bytes, so total retention was lower despite the +roughly 2 KB difference in the incremental measurement. Keeping a low-index anchor instead +allowed trimming to reduce the candidate's incremental retained heap to about 1 KB. Registration +and release still measured 41% less time with immediate reuse and 35% less with batch release +than the original map implementation. The live-record allocation costs about 10–14% on immediate +reuse compared with the two arrays; the batch comparison was approximately unchanged. + +The decoded-string cache is now allocated on the first short ASCII read and has 32 slots, +rather than 256. A saturated 256-slot cache failed the retained-memory constraint even after +the other savings. The smaller cache retains the repeated-name gains in the measured proxy and +nested-table workloads while fitting the full-cache memory check. Applications with larger +working sets of names can have more misses than with the 256-slot experiment. + +On a miss, decoding 1–8 ASCII bytes now calls `String.fromCharCode` with fixed arguments, avoiding +the temporary numeric array. Longer ASCII strings keep the existing gathering path; Unicode +still uses TextDecoder. Two isolated comparisons of this change measured 8–9% less time for +distinct short keys and values, 7–8% less for distinct short keys with numeric values, and 4–6% +less for nested records. These comparisons used the same cache capacity on both sides. With the +final 32-slot cache, comparison against the original baseline measured 19% less time reading +flat arrays, 23% less for nested records, and approximately unchanged time for distinct-key +objects. The earlier distinct-key regression is no longer established by these measurements. + +### Controlling retained-code variation + +An initial twenty-runtime comparison appeared to increase JS heap by about 0.75 MB. Heap +snapshots attributed most of that difference to bytecode and associated metadata, including +Node internals. Repeating the diagnostic changed which build retained that bytecode. The +retained-memory harness now reports V8 code statistics; disabling bytecode flushing during +this diagnostic keeps that variable comparable. This is a measurement flag, not a runtime +requirement or a performance recommendation. + +```sh +node --expose-gc --no-flush-bytecode docs/performance/retained-memory.mjs /absolute/baseline/dist/index.js +node --expose-gc --no-flush-bytecode docs/performance/retained-memory.mjs /absolute/candidate/dist/index.js +node --expose-gc --no-flush-bytecode docs/performance/retained-memory.mjs /absolute/baseline/dist/index.js --fill-cache +node --expose-gc --no-flush-bytecode docs/performance/retained-memory.mjs /absolute/candidate/dist/index.js --fill-cache +``` + +`--fill-cache` uses adjacent duplicates whose byte hashes cover every slot, reports the observed +slot count, then removes the Lua source table and collects it. Separate streaming passes of +distinct strings do not fill a cache that admits only repeated hashes; the earlier 4,096-string +probe did not guarantee full bucket coverage either. + +| Twenty live runtimes | Original baseline | Final candidate | +| ------------------------------------ | ----------------: | --------------: | +| Numeric workload: JS heap | 10,843,304 | 10,732,480 | +| Numeric workload: external memory | 1,871,809 | 1,871,809 | +| Filled-cache workload: JS heap | 10,926,704 | 10,872,512 | +| Filled-cache workload: external | 1,871,809 | 1,876,929 | +| Wasm heap capacity per runtime | 17,891,328 | 2,162,688 | + +The external-memory increase is the cache's two typed arrays: 256 bytes per runtime. JS heap +plus external memory is lower in both workloads. The 256-slot build instead measured 11,128,936 +bytes of JS heap and 1,912,769 external with the same filled-cache probe. These results cover +the measured Node workloads and do not claim every platform has identical object sizes. + +The final package is 174,571 bytes compressed and 443,303 unpacked, versus the original +178,091 / 459,197 bytes. The Wasm binary is unchanged in this pass. All 399 default-engine tests, +395 fallback tests (4 JSPI-only skips), upstream Lua tests, formatting/lint and diff checks pass. +New regressions cover holes below a high live index, symbolic values, invalid indices and +ASCII lengths 0–40 on first and repeated reads, including embedded NULs. + +The broader sweep still reproduces the compiler tradeoff: arithmetic, calls and heapsort are +about 5–9% faster, while string formatting is about 4% slower. Callback and proxy access measured +about 6% and 16% less time than the original baseline, and JS-to-Lua calls about 4–5% less. +Further VM profiling and browser performance measurements remain open. diff --git a/docs/performance/async-entries.mjs b/docs/performance/async-entries.mjs new file mode 100644 index 0000000..4e19451 --- /dev/null +++ b/docs/performance/async-entries.mjs @@ -0,0 +1,18 @@ +import assert from 'node:assert/strict' +import { performance } from 'node:perf_hooks' +const paths = process.argv.slice(2) +if (paths.length !== 2) throw new Error('Pass absolute paths to baseline and candidate index.js files') +for (const engine of ['yield', 'jspi']) { + const runtimes = await Promise.all(paths.map(async (path) => (await import(path)).LuaRuntime.load({ async: engine }))) + const states = runtimes.map((lua) => lua.createState()) + const samples = [[], []] + for (let round = 0; round < 30; round++) + for (const variant of round % 2 ? [1, 0] : [0, 1]) { + const start = performance.now() + for (let i = 0; i < 1000; i++) assert.equal(await states[variant].doString('return 1'), 1) + if (round >= 10) samples[variant].push(performance.now() - start) + } + const medians = samples.map((s) => s.sort((a, b) => a - b)[s.length >> 1]) + console.log({ engine, medians, improvement: 1 - medians[1] / medians[0] }) + states.forEach((state) => state.close()) +} diff --git a/docs/performance/bindings.mjs b/docs/performance/bindings.mjs new file mode 100644 index 0000000..44c6ada --- /dev/null +++ b/docs/performance/bindings.mjs @@ -0,0 +1,21 @@ +import assert from 'node:assert/strict' +import { performance } from 'node:perf_hooks' +const paths = process.argv.slice(2) +if (paths.length !== 2) throw new Error('Pass absolute paths to baseline and candidate index.js files') +const libraries = await Promise.all(paths.map((path) => import(path))) +const runtimes = await Promise.all(libraries.map(({ LuaRuntime }) => LuaRuntime.load({ async: 'yield' }))) +const samples = [[], []] +for (let round = 0; round < 30; round++) { + for (const variant of round % 2 ? [1, 0] : [0, 1]) { + const raw = runtimes[variant].module.emscripten + const start = performance.now() + for (let i = 0; i < 1000; i++) { + const module = new libraries[variant].LuaModule(raw, undefined, 'memory', [], 'yield') + assert.equal(module.lua_gettop, raw._lua_gettop) + for (const name of ['sizeScratch', 'resultCountScratch', 'gcArgsScratch', 'interruptToken']) raw._free(module[name]) + } + if (round >= 10) samples[variant].push(performance.now() - start) + } +} +const medians = samples.map((s) => s.sort((a, b) => a - b)[s.length >> 1]) +console.log({ medians, improvement: 1 - medians[1] / medians[0] }) diff --git a/docs/performance/cache-memory.mjs b/docs/performance/cache-memory.mjs new file mode 100644 index 0000000..a0070b2 --- /dev/null +++ b/docs/performance/cache-memory.mjs @@ -0,0 +1,26 @@ +import assert from 'node:assert/strict' +for (const path of process.argv.slice(2)) { + const { LuaRuntime, decorate } = await import(path) + const lua = await LuaRuntime.load() + const state = lua.createState({ inject: true, memory: { trace: true } }) + state.gc.stop() + const memory = [state.memory.used] + const object = { value: 1 } + for (const [name, value] of [ + ['proxy', object], + ['opaque', decorate(object, { as: 'userdata' })], + ['promise', Promise.resolve(1)], + ['error', new Error('example')], + ]) { + state.set(name, value) + state.set(name + '2', value) + assert.equal(state.doStringSync(`return rawequal(${name},${name}2)`), true) + } + memory.push(state.memory.used) + state.doStringSync('proxy=nil; proxy2=nil; opaque=nil; opaque2=nil; promise=nil; promise2=nil; error=nil; error2=nil') + state.gc.collect() + memory.push(state.memory.used) + assert.equal(state.getTop(), 0) + console.log({ path, memory, wasmHeap: lua.module.emscripten.HEAPU8.length }) + state.close() +} diff --git a/docs/performance/call-lua.mjs b/docs/performance/call-lua.mjs new file mode 100644 index 0000000..a8555f8 --- /dev/null +++ b/docs/performance/call-lua.mjs @@ -0,0 +1,23 @@ +import assert from 'node:assert/strict' +import { performance } from 'node:perf_hooks' +const paths = process.argv.slice(2) +if (paths.length !== 2) throw new Error('Pass absolute paths to baseline and candidate index.js files') +const runtimes = await Promise.all(paths.map(async (path) => (await import(path)).LuaRuntime.load())) +for (const code of ['return function() end', 'return function(a,b) return a+b end', 'return function(a,b) return a,b end']) { + const states = runtimes.map((lua) => lua.createState({ memory: { trace: true } })) + const funcs = states.map((state) => state.doStringSync(code)) + const samples = [[], []] + for (let round = 0; round < 30; round++) { + for (const variant of round % 2 ? [1, 0] : [0, 1]) { + let result + const start = performance.now() + for (let i = 0; i < 100000; i++) result = funcs[variant](1, 2) + const elapsed = performance.now() - start + assert.equal(result, code.includes('a+b') ? 3 : code.includes('a,b end') ? 1 : null) + if (round >= 10) samples[variant].push(elapsed) + } + } + const medians = samples.map((s) => s.sort((a, b) => a - b)[s.length >> 1]) + console.log({ code, medians, improvement: 1 - medians[1] / medians[0], memory: states.map((s) => s.memory.used) }) + states.forEach((s) => s.close()) +} diff --git a/docs/performance/callbacks.mjs b/docs/performance/callbacks.mjs new file mode 100644 index 0000000..0f4984d --- /dev/null +++ b/docs/performance/callbacks.mjs @@ -0,0 +1,29 @@ +import assert from 'node:assert/strict' +import { performance } from 'node:perf_hooks' +const paths = process.argv.slice(2) +if (paths.length !== 2) throw new Error('Pass absolute paths to baseline and candidate index.js files') +const runtimes = await Promise.all(paths.map(async (path) => (await import(path)).LuaRuntime.load())) +for (const kind of ['callback', 'proxy']) { + const states = runtimes.map((lua) => lua.createState()) + for (const state of states) { + state.set('add', (a, b) => a + b) + state.set('data', { nested: { value: 1 } }) + state.doStringSync( + `function run() local sum=0; for i=1,100000 do sum=sum+${kind === 'callback' ? 'add(i,1)' : 'data.nested.value'} end return sum end`, + ) + } + const fns = states.map((state) => state.get('run')) + const samples = [[], []] + for (let round = 0; round < 40; round++) { + for (const variant of round % 2 ? [1, 0] : [0, 1]) { + const start = performance.now() + const result = fns[variant]() + const elapsed = performance.now() - start + assert.equal(result, kind === 'callback' ? 5000150000 : 100000) + if (round >= 10) samples[variant].push(elapsed) + } + } + const medians = samples.map((s) => s.sort((a, b) => a - b)[s.length >> 1]) + console.log({ kind, medians, improvement: 1 - medians[1] / medians[0] }) + states.forEach((state) => state.close()) +} diff --git a/docs/performance/create-state.mjs b/docs/performance/create-state.mjs new file mode 100644 index 0000000..288e0c6 --- /dev/null +++ b/docs/performance/create-state.mjs @@ -0,0 +1,22 @@ +import { performance } from 'node:perf_hooks' +const paths = process.argv.slice(2) +if (paths.length !== 2) throw new Error('Pass absolute paths to baseline and candidate index.js files') +const runtimes = await Promise.all(paths.map(async (path) => (await import(path)).LuaRuntime.load())) +for (const options of [{}, { objects: 'copy' }, { inject: true }]) { + const samples = [[], []] + for (let round = 0; round < 30; round++) { + for (const variant of round % 2 ? [1, 0] : [0, 1]) { + const start = performance.now() + for (let i = 0; i < 200; i++) runtimes[variant].createState(options).close() + if (round >= 10) samples[variant].push(performance.now() - start) + } + } + const medians = samples.map((s) => s.sort((a, b) => a - b)[s.length >> 1]) + const memory = runtimes.map((lua) => { + const state = lua.createState({ ...options, memory: { trace: true } }) + const used = state.memory.used + state.close() + return used + }) + console.log({ options, medians, improvement: 1 - medians[1] / medians[0], memory }) +} diff --git a/docs/performance/multiple-returns.mjs b/docs/performance/multiple-returns.mjs new file mode 100644 index 0000000..3cdc084 --- /dev/null +++ b/docs/performance/multiple-returns.mjs @@ -0,0 +1,27 @@ +import assert from 'node:assert/strict' +import { performance } from 'node:perf_hooks' +const paths = process.argv.slice(2) +if (paths.length !== 2) throw new Error('Pass absolute paths to baseline and candidate index.js files') +const libs = await Promise.all(paths.map((path) => import(path))) +for (const engine of ['yield', 'jspi']) { + const runtimes = await Promise.all(libs.map((lib) => lib.LuaRuntime.load({ async: engine }))) + const states = runtimes.map((lua) => lua.createState({ inject: true })) + for (let i = 0; i < 2; i++) { + const values = libs[i].LuaMultiReturn.of(1, 2, 3) + states[i].set('values', Promise.resolve(values)) + states[i].set('callback', () => values) + } + for (const kind of ['callback', 'await']) { + const code = `local n=0; for i=1,20000 do local a,b,c=${kind === 'callback' ? 'callback()' : 'values:await()'}; n=n+a+b+c end return n` + const samples = [[], []] + for (let round = 0; round < 30; round++) + for (const variant of round % 2 ? [1, 0] : [0, 1]) { + const start = performance.now() + assert.equal(await states[variant].doString(code), 120000) + if (round >= 10) samples[variant].push(performance.now() - start) + } + const medians = samples.map((s) => s.sort((a, b) => a - b)[s.length >> 1]) + console.log({ engine, kind, medians, improvement: 1 - medians[1] / medians[0] }) + } + states.forEach((state) => state.close()) +} diff --git a/docs/performance/read-table.mjs b/docs/performance/read-table.mjs new file mode 100644 index 0000000..a070c60 --- /dev/null +++ b/docs/performance/read-table.mjs @@ -0,0 +1,38 @@ +import assert from 'node:assert/strict' +import { performance } from 'node:perf_hooks' +import { readFileSync, readdirSync } from 'node:fs' +import { gzipSync } from 'node:zlib' +const paths = process.argv.slice(2) +if (paths.length !== 2) throw new Error('Pass absolute paths to baseline and candidate dist directories') +const runtimes = await Promise.all(paths.map(async (path) => (await import(`${path}/index.js`)).LuaRuntime.load())) +for (const source of [ + 'data = {}; for i=1,2000 do data[i]=i end', + 'data = {}; for i=1,2000 do data[i]={id=i,name="item"..i,active=true} end', + 'data = {}; for i=1,2000 do data["item"..i]=i end', +]) { + const states = runtimes.map((lua) => lua.createState({ objects: 'copy', memory: { trace: true } })) + for (const state of states) state.doStringSync(source) + assert.deepEqual(states[0].get('data'), states[1].get('data')) + const samples = [[], []] + for (let round = 0; round < 24; round++) { + for (const variant of round % 2 ? [1, 0] : [0, 1]) { + const start = performance.now() + for (let i = 0; i < 100; i++) states[variant].get('data') + if (round >= 6) samples[variant].push(performance.now() - start) + } + } + const medians = samples.map((s) => s.sort((a, b) => a - b)[s.length >> 1]) + console.log({ source, medians, improvement: 1 - medians[1] / medians[0], memory: states.map((s) => s.memory.used) }) + states.forEach((s) => s.close()) +} +for (const path of paths) { + let bytes = 0, + gzip = 0 + for (const name of readdirSync(path, { recursive: true })) { + if (!/\.(js|ts|wasm)$/.test(name)) continue + const data = readFileSync(`${path}/${name}`) + bytes += data.length + gzip += gzipSync(data).length + } + console.log({ path, bytes, gzip }) +} diff --git a/docs/performance/ready-await-memory.mjs b/docs/performance/ready-await-memory.mjs new file mode 100644 index 0000000..3246125 --- /dev/null +++ b/docs/performance/ready-await-memory.mjs @@ -0,0 +1,33 @@ +if (!global.gc || !process.argv[2]) throw new Error('Use --expose-gc and pass an absolute path to index.js') +const { LuaRuntime } = await import(process.argv[2]) +const lua = await LuaRuntime.load({ async: 'jspi' }) +const results = [] +for (let depth = 0; depth < 7; depth++) { + const state = lua.createState() + let release + state.set( + 'gate', + new Promise((resolve) => { + release = resolve + }), + ) + state.gc.collect() + global.gc() + const before = process.memoryUsage() + const runs = Array.from({ length: 1000 }, () => + state.doString('gate:await() return 1').then( + () => {}, + () => {}, + ), + ) + await new Promise((resolve) => setTimeout(resolve, 10)) + release() + for (let i = 0; i < depth; i++) await Promise.resolve() + global.gc() + const during = process.memoryUsage() + results.push({ depth, heap: during.heapUsed - before.heapUsed, buffers: during.arrayBuffers - before.arrayBuffers }) + if (process.argv.includes('--close-before-resume')) state.close() + await Promise.all(runs) + state.close() +} +console.log(JSON.stringify({ path: process.argv[2], results })) diff --git a/docs/performance/reference-memory.mjs b/docs/performance/reference-memory.mjs new file mode 100644 index 0000000..823dbd4 --- /dev/null +++ b/docs/performance/reference-memory.mjs @@ -0,0 +1,26 @@ +import assert from 'node:assert/strict' + +if (!global.gc || !process.argv[2]) throw new Error('Use --expose-gc and pass an absolute path to index.js') +const { LuaRuntime } = await import(process.argv[2]) +const { module } = await LuaRuntime.load() +const count = 100_000 +const refs = new Uint32Array(count) +const anchor = {} +const high = process.argv[3] === 'high' +let anchorRef = high ? undefined : module.ref(anchor) +const sample = () => { + for (let i = 0; i < 5; i++) global.gc() + return process.memoryUsage().heapUsed +} +// Warm the registration and release paths before measuring retained heap. +for (let i = 0; i < 10_000; i++) module.unref(module.ref({})) +const before = sample() +for (let i = 0; i < count; i++) refs[i] = module.ref({}) +if (high) anchorRef = module.ref(anchor) +const live = sample() +for (const ref of refs) module.unref(ref) +const released = sample() +assert.equal(module.getRef(anchorRef), anchor) +assert.equal(module.getRefIndex(anchor), anchorRef) +console.log({ path: process.argv[2], anchor: high ? 'high' : 'low', live: live - before, released: released - before, heapUsed: released, wasmHeap: module.emscripten.HEAPU8.length }) +module.unref(anchorRef) diff --git a/docs/performance/references.mjs b/docs/performance/references.mjs new file mode 100644 index 0000000..3b67d03 --- /dev/null +++ b/docs/performance/references.mjs @@ -0,0 +1,29 @@ +import assert from 'node:assert/strict' +import { performance } from 'node:perf_hooks' +const paths = process.argv.slice(2) +if (paths.length !== 2) throw new Error('Pass absolute paths to baseline and candidate index.js files') +const modules = await Promise.all(paths.map(async (path) => (await (await import(path)).LuaRuntime.load()).module)) +const values = Array.from({ length: 1000 }, () => ({})) +for (const mode of ['reuse', 'batch']) { + const samples = [[], []] + for (let round = 0; round < 30; round++) + for (const variant of round % 2 ? [1, 0] : [0, 1]) { + const module = modules[variant] + const start = performance.now() + for (let i = 0; i < 100; i++) { + if (mode === 'reuse') + for (const value of values) { + const ref = module.ref(value) + module.unref(ref) + } + else { + const refs = values.map((value) => module.ref(value)) + for (const ref of refs) module.unref(ref) + } + } + if (round >= 10) samples[variant].push(performance.now() - start) + } + const medians = samples.map((s) => s.sort((a, b) => a - b)[s.length >> 1]) + console.log({ mode, medians, improvement: 1 - medians[1] / medians[0] }) + for (const module of modules) for (const value of values) assert.equal(module.getRefIndex(value), undefined) +} diff --git a/docs/performance/retained-memory.mjs b/docs/performance/retained-memory.mjs new file mode 100644 index 0000000..3b4e103 --- /dev/null +++ b/docs/performance/retained-memory.mjs @@ -0,0 +1,36 @@ +import { getHeapCodeStatistics } from 'node:v8' + +if (!global.gc || !process.argv[2]) throw new Error('Use --expose-gc and pass an absolute path to index.js') +const { LuaRuntime } = await import(process.argv[2]) +const runtimes = [] +for (let i = 0; i < 20; i++) { + const lua = await LuaRuntime.load() + const state = lua.createState({ objects: 'copy' }) + state.doStringSync('data={}; for i=1,2000 do data[i]=i end') + for (let j = 0; j < 20; j++) state.get('data') + if (process.argv.includes('--fill-cache')) { + // For a 31-based hash, the final two bytes add every integer from 0 through 255. + // This covers every bucket in caches of up to 256 slots. Adjacent duplicates exercise + // second-touch admission; two separate streaming passes would not fill the cache. + state.doStringSync(` + cacheStrings = {} + for i = 0, 255 do + local s = string.rep('a', 30) .. string.char(i // 31, i % 31) + cacheStrings[2*i+1] = s + cacheStrings[2*i+2] = s + end + `) + state.get('cacheStrings') + state.doStringSync('cacheStrings=nil; collectgarbage("collect")') + } + runtimes.push({ lua, state }) +} +for (let i = 0; i < 5; i++) global.gc() +console.log({ + path: process.argv[2], + heapUsed: process.memoryUsage().heapUsed, + external: process.memoryUsage().external, + wasmHeap: runtimes[0].lua.module.emscripten.HEAPU8.length, + cacheSlots: runtimes[0].lua.module.decodedStrings?.filter(Boolean).length, + code: getHeapCodeStatistics(), +}) diff --git a/docs/performance/runtime.mjs b/docs/performance/runtime.mjs new file mode 100644 index 0000000..f929eab --- /dev/null +++ b/docs/performance/runtime.mjs @@ -0,0 +1,21 @@ +if (!global.gc) throw new Error('Run with --expose-gc') +import { performance } from 'node:perf_hooks' +const paths = process.argv.slice(2) +if (paths.length !== 2) throw new Error('Pass absolute paths to baseline and candidate index.js files') +const libraries = await Promise.all(paths.map((path) => import(path))) +const samples = [[], []] +for (let round = 0; round < 30; round++) { + for (const variant of round % 2 ? [1, 0] : [0, 1]) { + global.gc() + const start = performance.now() + for (let i = 0; i < 10; i++) { + const lua = await libraries[variant].LuaRuntime.load({ async: 'yield' }) + const state = lua.createState() + state.doStringSync('return 1+1') + state.close() + } + if (round >= 10) samples[variant].push(performance.now() - start) + } +} +const medians = samples.map((s) => s.sort((a, b) => a - b)[s.length >> 1]) +console.log({ medians, improvement: 1 - medians[1] / medians[0] }) diff --git a/docs/performance/settled-awaits.mjs b/docs/performance/settled-awaits.mjs new file mode 100644 index 0000000..28568c0 --- /dev/null +++ b/docs/performance/settled-awaits.mjs @@ -0,0 +1,17 @@ +import assert from 'node:assert/strict' +import { performance } from 'node:perf_hooks' +const paths = process.argv.slice(2) +if (paths.length !== 2) throw new Error('Pass absolute paths to baseline and candidate index.js files') +const runtimes = await Promise.all(paths.map(async (path) => (await import(path)).LuaRuntime.load({ async: 'jspi' }))) +const states = runtimes.map((lua) => lua.createState()) +for (const state of states) state.set('ready', Promise.resolve(1)) +const samples = [[], []] +for (let round = 0; round < 30; round++) + for (const variant of round % 2 ? [1, 0] : [0, 1]) { + const start = performance.now() + assert.equal(await states[variant].doString('local n=0; for i=1,20000 do n=n+ready:await() end return n'), 20000) + if (round >= 10) samples[variant].push(performance.now() - start) + } +const medians = samples.map((s) => s.sort((a, b) => a - b)[s.length >> 1]) +console.log({ medians, improvement: 1 - medians[1] / medians[0] }) +states.forEach((state) => state.close()) diff --git a/docs/performance/string-cache-memory.mjs b/docs/performance/string-cache-memory.mjs new file mode 100644 index 0000000..1619bd5 --- /dev/null +++ b/docs/performance/string-cache-memory.mjs @@ -0,0 +1,16 @@ +// Worst case for the decoded string cache: every slot filled with a 32 byte string, read twice so +// it is kept. Reports the JS heap the cache retains per runtime after a full GC. +if (!global.gc) throw new Error('use --expose-gc') +const { LuaRuntime } = await import(process.argv[2]) +const lua = await LuaRuntime.load() +const state = lua.createState() +// 4096 distinct 32-char ASCII strings, each read twice: far more than 256 slots, so every slot ends up holding one. +state.doStringSync('t = {}; for i = 1, 4096 do t[i] = string.format("%032d", i) end') +const read = () => { for (let i = 0; i < 2; i++) state.doStringSync('return t[' + (i + 1) + ']') } +for (let g = 0; g < 5; g++) global.gc() +const before = process.memoryUsage().heapUsed +for (let i = 1; i <= 4096; i++) { state.doStringSync(`return t[${i}]`); state.doStringSync(`return t[${i}]`) } +for (let g = 0; g < 5; g++) global.gc() +const after = process.memoryUsage().heapUsed +console.log({ path: process.argv[2].split('/').slice(-2).join('/'), heapDelta: after - before }) +state.close() diff --git a/docs/performance/string-cache-variants.mjs b/docs/performance/string-cache-variants.mjs new file mode 100644 index 0000000..f97946d --- /dev/null +++ b/docs/performance/string-cache-variants.mjs @@ -0,0 +1,142 @@ +import assert from 'node:assert/strict' +import { performance } from 'node:perf_hooks' +const decoder = new TextDecoder() +const heap = new Uint8Array(1 << 16) +const SIZE = 256 +function original(pointer, length) { + const codes = new Array(length) + let index = 0 + while (index < length) { + const code = heap[pointer + index] + if (code > 127) break + codes[index++] = code + } + if (index === length) return String.fromCharCode.apply(null, codes) + return decoder.decode(heap.subarray(pointer, pointer + length)) +} +function same(text, pointer) { + for (let i = 0; i < text.length; i++) if (text.charCodeAt(i) !== heap[pointer + i]) return false + return true +} +// A: current (verify on equal length, two passes) +const aStrings = new Array(SIZE).fill(''), aHits = new Uint8Array(SIZE) +function current(pointer, length) { + let hash = length, index = 0 + while (index < length) { const code = heap[pointer + index]; if (code > 127) break; hash = (hash * 31 + code) | 0; index++ } + if (index === length) { + const slot = hash & (SIZE - 1), cached = aStrings[slot] + if (cached.length === length && same(cached, pointer)) { aHits[slot] = 1; return cached } + const codes = new Array(length) + for (index = 0; index < length; index++) codes[index] = heap[pointer + index] + const text = String.fromCharCode.apply(null, codes) + if (aHits[slot]) aHits[slot] = 0; else aStrings[slot] = text + return text + } + return decoder.decode(heap.subarray(pointer, pointer + length)) +} +// B: two passes, verify only when the stored hash matches +const bStrings = new Array(SIZE).fill(''), bHashes = new Int32Array(SIZE), bHits = new Uint8Array(SIZE) +function hashGuarded(pointer, length) { + let hash = length, index = 0 + while (index < length) { const code = heap[pointer + index]; if (code > 127) break; hash = (Math.imul(hash, 31) + code) | 0; index++ } + if (index === length) { + const slot = hash & (SIZE - 1) + if (bHashes[slot] === hash) { const cached = bStrings[slot]; if (cached.length === length && same(cached, pointer)) { bHits[slot] = 1; return cached } } + const codes = new Array(length) + for (index = 0; index < length; index++) codes[index] = heap[pointer + index] + const text = String.fromCharCode.apply(null, codes) + if (bHits[slot]) bHits[slot] = 0; else { bStrings[slot] = text; bHashes[slot] = hash } + return text + } + return decoder.decode(heap.subarray(pointer, pointer + length)) +} +// C: one pass gathering and hashing, verify only when the stored hash matches +const cStrings = new Array(SIZE).fill(''), cHashes = new Int32Array(SIZE), cHits = new Uint8Array(SIZE) +function singlePass(pointer, length) { + const codes = new Array(length) + let hash = length, index = 0 + while (index < length) { const code = heap[pointer + index]; if (code > 127) break; hash = (Math.imul(hash, 31) + code) | 0; codes[index++] = code } + if (index === length) { + const slot = hash & (SIZE - 1) + if (cHashes[slot] === hash) { const cached = cStrings[slot]; if (cached.length === length && same(cached, pointer)) { cHits[slot] = 1; return cached } } + const text = String.fromCharCode.apply(null, codes) + if (cHits[slot]) cHits[slot] = 0; else { cStrings[slot] = text; cHashes[slot] = hash } + return text + } + return decoder.decode(heap.subarray(pointer, pointer + length)) +} +// D: B without the second-chance bit +const dStrings = new Array(SIZE).fill(''), dHashes = new Int32Array(SIZE) +function plain(pointer, length) { + let hash = length, index = 0 + while (index < length) { const code = heap[pointer + index]; if (code > 127) break; hash = (Math.imul(hash, 31) + code) | 0; index++ } + if (index === length) { + const slot = hash & (SIZE - 1) + if (dHashes[slot] === hash) { const cached = dStrings[slot]; if (cached.length === length && same(cached, pointer)) return cached } + const codes = new Array(length) + for (index = 0; index < length; index++) codes[index] = heap[pointer + index] + const text = String.fromCharCode.apply(null, codes) + dStrings[slot] = text; dHashes[slot] = hash + return text + } + return decoder.decode(heap.subarray(pointer, pointer + length)) +} +// E: hash pass only, never stores (isolates the hashing cost) +const eHashes = new Int32Array(SIZE) +function hashOnly(pointer, length) { + let hash = length, index = 0 + while (index < length) { const code = heap[pointer + index]; if (code > 127) break; hash = (Math.imul(hash, 31) + code) | 0; index++ } + if (index === length) { + const slot = hash & (SIZE - 1) + if (eHashes[slot] === hash) return 'x' + const codes = new Array(length) + for (index = 0; index < length; index++) codes[index] = heap[pointer + index] + return String.fromCharCode.apply(null, codes) + } + return decoder.decode(heap.subarray(pointer, pointer + length)) +} +// F: store only on the second sighting of the same hash +const fStrings = new Array(SIZE).fill(''), fHashes = new Int32Array(SIZE), fSeen = new Int32Array(SIZE) +function secondTouch(pointer, length) { + let hash = length, index = 0 + while (index < length) { const code = heap[pointer + index]; if (code > 127) break; hash = (Math.imul(hash, 31) + code) | 0; index++ } + if (index === length) { + const slot = hash & (SIZE - 1) + if (fHashes[slot] === hash) { const cached = fStrings[slot]; if (cached.length === length && same(cached, pointer)) return cached } + const codes = new Array(length) + for (index = 0; index < length; index++) codes[index] = heap[pointer + index] + const text = String.fromCharCode.apply(null, codes) + if (fSeen[slot] === hash) { fStrings[slot] = text; fHashes[slot] = hash } else fSeen[slot] = hash + return text + } + return decoder.decode(heap.subarray(pointer, pointer + length)) +} +const variants = [original, plain, hashOnly, secondTouch] +const enc = new TextEncoder() +// Workloads: list of strings laid out in the heap, read cyclically. +function layout(strings) { let p = 8; const spans = []; for (const s of strings) { const b = enc.encode(s); heap.set(b, p); spans.push([p, b.length]); p += b.length + 1 } return spans } +const workloads = { + 'hot keys (id,name,active)': layout(['id', 'name', 'active']), + 'hot keys (nested,value)': layout(['nested', 'value']), + 'distinct keys item1..2000': layout(Array.from({ length: 2000 }, (_, i) => `item${i + 1}`)), + 'mixed: 3 keys + 1 distinct value per entry': (() => { const out = []; const keys = layout(['id', 'name', 'active']); const vals = layout(Array.from({ length: 2000 }, (_, i) => `item${i + 1}`)); for (let i = 0; i < 2000; i++) { out.push(keys[0], keys[1], vals[i], keys[2]) } return out })(), + '24-char repeated': layout(['abcdefghijabcdefghijabcd']), +} +for (const [name, spans] of Object.entries(workloads)) { + for (const v of variants) if (v !== hashOnly) for (const [p, l] of spans) assert.equal(v(p, l), original(p, l)) + const samples = variants.map(() => []) + const n = 200000 + for (let round = 0; round < 24; round++) { + const order = round % 2 ? [3, 2, 1, 0] : [0, 1, 2, 3] + for (const v of order) { + const f = variants[v] + let sink = 0 + const start = performance.now() + for (let i = 0; i < n; i++) { const [p, l] = spans[i % spans.length]; sink += f(p, l).length } + if (round >= 4) samples[v].push(performance.now() - start) + if (sink < 0) throw new Error() + } + } + const med = samples.map((s) => s.sort((a, b) => a - b)[s.length >> 1]) + console.log(name.padEnd(46), variants.map((v, i) => `${v.name}=${med[i].toFixed(2)}`).join(' ')) +} diff --git a/docs/performance/string-cache.mjs b/docs/performance/string-cache.mjs new file mode 100644 index 0000000..4419c7f --- /dev/null +++ b/docs/performance/string-cache.mjs @@ -0,0 +1,39 @@ +import assert from 'node:assert/strict' +import { performance } from 'node:perf_hooks' +const paths = process.argv.slice(2) +const runtimes = await Promise.all(paths.map(async (path) => (await import(path)).LuaRuntime.load())) +for (const length of [8, 24, 200]) { + const value = 'abcdefghij'.repeat(Math.ceil(length / 10)).slice(0, length) + const states = runtimes.map((lua) => lua.createState()) + const samples = [[], []] + for (let round = 0; round < 30; round++) { + for (const variant of round % 2 ? [1, 0] : [0, 1]) { + const state = states[variant] + const start = performance.now() + for (let i = 0; i < 20000; i++) { + state.set('value', value) + if (state.get('value') !== value) throw new Error('mismatch') + } + if (round >= 6) samples[variant].push(performance.now() - start) + } + } + const medians = samples.map((s) => s.sort((a, b) => a - b)[s.length >> 1]) + console.log(JSON.stringify({ length, medians, improvement: 1 - medians[1] / medians[0] })) + states.forEach((s) => s.close()) +} +// Distinct keys streaming through: the cache's worst case. +{ + const states = runtimes.map((lua) => lua.createState({ objects: 'copy' })) + for (const state of states) state.doStringSync('data = {}; for i=1,2000 do data["k"..i] = "v"..i end') + const samples = [[], []] + for (let round = 0; round < 30; round++) { + for (const variant of round % 2 ? [1, 0] : [0, 1]) { + const start = performance.now() + for (let i = 0; i < 50; i++) assert.equal(Object.keys(states[variant].get('data')).length, 2000) + if (round >= 6) samples[variant].push(performance.now() - start) + } + } + const medians = samples.map((s) => s.sort((a, b) => a - b)[s.length >> 1]) + console.log(JSON.stringify({ workload: 'distinct string keys and values', medians, improvement: 1 - medians[1] / medians[0] })) + states.forEach((s) => s.close()) +} diff --git a/docs/performance/string-decode.mjs b/docs/performance/string-decode.mjs new file mode 100644 index 0000000..672aee4 --- /dev/null +++ b/docs/performance/string-decode.mjs @@ -0,0 +1,57 @@ +import assert from 'node:assert/strict' +import { performance } from 'node:perf_hooks' +const decoder = new TextDecoder() +const heap = new Uint8Array(1024) +function original(pointer, length) { + const codes = new Array(length) + let index = 0 + while (index < length) { + const code = heap[pointer + index] + if (code > 127) break + codes[index++] = code + } + if (index === length) return String.fromCharCode.apply(null, codes) + return decoder.decode(heap.subarray(pointer, pointer + length)) +} +function view(pointer, length) { + let index = 0 + while (index < length && heap[pointer + index] <= 127) index++ + const bytes = heap.subarray(pointer, pointer + length) + return index === length ? String.fromCharCode.apply(null, bytes) : decoder.decode(bytes) +} +function scanFirst(pointer, length) { + let index = 0 + while (index < length && heap[pointer + index] <= 127) index++ + if (index !== length) return decoder.decode(heap.subarray(pointer, pointer + length)) + const codes = new Array(length) + for (index = 0; index < length; index++) codes[index] = heap[pointer + index] + return String.fromCharCode.apply(null, codes) +} +// Isolates the short-string decoder; it does not measure Lua/Wasm crossings. +const cutoff = process.argv.includes('--cutoff') +const variants = cutoff + ? [original, view, (pointer, length) => decoder.decode(heap.subarray(pointer, pointer + length))] + : [original, view, scanFirst] +const values = cutoff + ? [32, 40, 48, 64, 80, 96, 128].map((n) => 'a'.repeat(n)) + : ['a', 'hello', 'abcdefghijklmno', 'a'.repeat(32), 'ação', 'こんにちは', 'a'.repeat(25) + 'é'] +for (const bytes of [new Uint8Array([0, 65, 0]), new Uint8Array([255, 128, 65]), new TextEncoder().encode('é😀')]) { + heap.set(bytes, 8) + for (const variant of variants) assert.equal(variant(8, bytes.length), decoder.decode(bytes)) +} +let sink = 0 +for (const value of values) { + const bytes = new TextEncoder().encode(value) + heap.set(bytes, 8) + for (const variant of variants) assert.equal(variant(8, bytes.length), value) + const samples = [[], [], []] + for (let round = 0; round < 25; round++) + for (const v of round % 2 ? [2, 1, 0] : [0, 1, 2]) { + const f = variants[v] + const start = performance.now() + for (let i = 0; i < 200000; i++) sink += f(8, bytes.length).length + if (round >= 5) samples[v].push(performance.now() - start) + } + console.log(JSON.stringify({ value, ms: samples.map((s) => s.sort((a, b) => a - b)[10]) })) +} +console.log(sink) diff --git a/docs/performance/table-copy.mjs b/docs/performance/table-copy.mjs new file mode 100644 index 0000000..8e53bcb --- /dev/null +++ b/docs/performance/table-copy.mjs @@ -0,0 +1,31 @@ +import { performance } from 'node:perf_hooks' +import { statSync } from 'node:fs' +const paths = process.argv.slice(2) +if (paths.length !== 2) throw new Error('Pass absolute paths to baseline and candidate index.js files') +const runtimes = await Promise.all(paths.map(async (path) => (await import(path)).LuaRuntime.load())) +const values = [ + {}, + { id: 1, name: 'item', active: true }, + Array.from({ length: 2000 }, (_, id) => ({ id, name: `item${id}`, active: true })), +] +for (const [index, value] of values.entries()) { + const states = runtimes.map((runtime) => runtime.createState({ objects: 'copy' })) + const samples = [[], []] + const count = index === 2 ? 100 : 20000 + for (let round = 0; round < 24; round++) { + for (const variant of round % 2 ? [1, 0] : [0, 1]) { + const state = states[variant] + const start = performance.now() + for (let i = 0; i < count; i++) { + state.pushValue(value) + state.pop() + } + const elapsed = performance.now() - start + if (round >= 6) samples[variant].push(elapsed) + } + } + const medians = samples.map((sample) => sample.sort((a, b) => a - b)[sample.length >> 1]) + console.log(JSON.stringify({ index, count, medians, improvement: 1 - medians[1] / medians[0] })) + states.forEach((state) => state.close()) +} +console.log(paths.map((path) => ({ path, bytes: statSync(path).size }))) diff --git a/docs/performance/vm.mjs b/docs/performance/vm.mjs new file mode 100644 index 0000000..3002ab8 --- /dev/null +++ b/docs/performance/vm.mjs @@ -0,0 +1,42 @@ +import assert from 'node:assert/strict' +import { performance } from 'node:perf_hooks' +import { readFileSync } from 'node:fs' +const paths = process.argv.slice(2) +if (paths.length !== 2) throw new Error('Pass absolute paths to baseline and candidate index.js files') +const runtimes = await Promise.all(paths.map(async (path) => (await import(path)).LuaRuntime.load())) +const workloads = [ + ['arithmetic', 'return function() local sum=0; for i=1,1000000 do sum=sum+i end return sum end', 500000500000], + [ + 'table', + 'return function() local t={}; for i=1,100000 do t[i]=i end local sum=0; for i=1,#t do sum=sum+t[i] end return sum end', + 5000050000, + ], + [ + 'calls', + 'local function add(a,b) return a+b end; return function() local sum=0; for i=1,200000 do sum=add(sum,i) end return sum end', + 20000100000, + ], + [ + 'strings', + 'return function() local t={}; for i=1,10000 do t[i]=string.format("item:%d",i) end return #table.concat(t,",") end', + 98893, + ], + ['heapsort', readFileSync(new URL('../../bench/heapsort.lua', import.meta.url), 'utf8'), 10], +] +for (const [name, source, expected] of workloads) { + const states = runtimes.map((lua) => lua.createState()) + for (const state of states) state.doStringSync('math.randomseed(1)') + const fns = states.map((state) => state.doStringSync(source)) + const samples = [[], []] + for (let round = 0; round < 30; round++) + for (const variant of round % 2 ? [1, 0] : [0, 1]) { + const start = performance.now() + const result = fns[variant]() + const elapsed = performance.now() - start + assert.equal(result, expected) + if (round >= 10) samples[variant].push(elapsed) + } + const medians = samples.map((s) => s.sort((a, b) => a - b)[s.length >> 1]) + console.log({ name, medians, improvement: 1 - medians[1] / medians[0] }) + states.forEach((state) => state.close()) +} diff --git a/package.json b/package.json index c809188..3750d9b 100755 --- a/package.json +++ b/package.json @@ -33,7 +33,6 @@ "lint:nofix": "oxfmt --check . && oxlint ." }, "files": [ - "bin/*", "dist/*", "!dist/*.map" ], @@ -46,7 +45,7 @@ "safari >= 26" ], "bin": { - "wasmoon": "bin/wasmoon" + "wasmoon": "dist/cli.js" }, "repository": { "type": "git", diff --git a/rolldown.config.ts b/rolldown.config.ts index 6a8ca3a..8f8965f 100644 --- a/rolldown.config.ts +++ b/rolldown.config.ts @@ -4,13 +4,15 @@ import pkg from './package.json' with { type: 'json' } import { UNWIND_BRAND } from './src/utils' export default defineConfig({ - input: './src/index.ts', + // The CLI is an entry of its own: it imports the library by package name at run time rather + // than bundling a second copy of it, and is minified the same way. + input: { index: './src/index.ts', cli: './src/cli.js' }, output: { // A directory rather than a single file, because the host filesystem glue that module.ts // imports on demand has to stay a chunk of its own: a browser bundle then leaves it alone, // and Node loads it only when someone asks for `fs: 'host'`. dir: 'dist', - entryFileNames: 'index.js', + entryFileNames: '[name].js', // Named rather than hashed, so the `browser` field in package.json can point at it. chunkFileNames: 'glue-host.js', format: 'esm', @@ -18,12 +20,15 @@ export default defineConfig({ // The glue arrives from emcc already minified and rolldown would otherwise re-print it // several kilobytes larger than it started. Consumers minify us anyway -- which the // Bundling suite covers -- so doing it here only decides what the package and a CDN - // consumer download. The sourcemap keeps our own frames readable. - minify: { mangle: { toplevel: false } }, + // consumer download. The sourcemap keeps our own frames readable. Module level names are + // mangled too, except that classes keep theirs: those are what a consumer sees, in a + // constructor's `name` and in the console, while the helpers between them are not. + minify: { mangle: { toplevel: true, keepNames: { function: false, class: true } } }, }, // Only the glue imports a node builtin now; the mounts reach node:fs through - // process.getBuiltinModule, which a bundler never has to resolve. - external: ['node:module'], + // process.getBuiltinModule, which a bundler never has to resolve. The rest is the CLI's: the + // builtins it uses, the library it runs, and the package.json it reads its version from. + external: ['node:module', 'node:fs', 'node:readline', 'wasmoon', '../package.json'], plugins: [ { name: 'package-version', diff --git a/src/async.ts b/src/async.ts index 4a85f49..4248d49 100644 --- a/src/async.ts +++ b/src/async.ts @@ -5,6 +5,7 @@ * MessageChannel where it exists, because a browser clamps a nested setTimeout to 4ms while a * message post is not clamped; setImmediate under Node; setTimeout as the last resort. */ +import type Thread from './thread' import { LuaAbortError, type LuaInterruptError, LuaTimeoutError } from './types' type Macrotask = (task: () => void) => void @@ -45,9 +46,21 @@ export function limitError(signal: AbortSignal | undefined, deadline: number | u } export type SettleOutcome = - | { interrupted: false; resolved: true; value: unknown } - | { interrupted: false; resolved: false; error: unknown } - | { interrupted: true; error: LuaInterruptError } + | { status: 'fulfilled'; value: unknown } + | { status: 'rejected'; error: unknown } + | { status: 'interrupted'; error: LuaInterruptError } + +/** + * The promise a JSPI `:await()` stashed for the C trampoline's await hook to suspend on, along + * with how to marshal its settled value back onto the Lua stack. + */ +export interface PendingSuspend { + run: Thread + promise: PromiseLike + signal: AbortSignal | undefined + deadline: number | undefined + resume: (outcome: SettleOutcome) => number +} /** * Awaits `promise`, but reports an interruption instead if `signal` aborts or `deadline` passes @@ -56,8 +69,8 @@ export type SettleOutcome = */ export function settleOrInterrupt(promise: unknown, signal: AbortSignal | undefined, deadline: number | undefined): Promise { const settled: Promise = Promise.resolve(promise).then( - (value) => ({ interrupted: false, resolved: true, value }), - (error) => ({ interrupted: false, resolved: false, error }), + (value) => ({ status: 'fulfilled', value }), + (error) => ({ status: 'rejected', error }), ) if (signal === undefined && deadline === undefined) { return settled @@ -89,7 +102,7 @@ export function settleOrInterrupt(promise: unknown, signal: AbortSignal | undefi () => { const error = limitError(signal, deadline) if (error) { - finish({ interrupted: true, error }) + finish({ status: 'interrupted', error }) } else { scheduleDeadline() } @@ -102,10 +115,10 @@ export function settleOrInterrupt(promise: unknown, signal: AbortSignal | undefi let onAbort: (() => void) | undefined if (signal !== undefined) { if (signal.aborted) { - finish({ interrupted: true, error: new LuaAbortError('thread aborted') }) + finish({ status: 'interrupted', error: new LuaAbortError('thread aborted') }) return } - onAbort = () => finish({ interrupted: true, error: new LuaAbortError('thread aborted') }) + onAbort = () => finish({ status: 'interrupted', error: new LuaAbortError('thread aborted') }) signal.addEventListener('abort', onAbort, { once: true }) } diff --git a/bin/wasmoon b/src/cli.js similarity index 98% rename from bin/wasmoon rename to src/cli.js index 47611a9..2d070a1 100755 --- a/bin/wasmoon +++ b/src/cli.js @@ -1,5 +1,7 @@ #!/usr/bin/env node -import { LuaRuntime, LuaReturn, LuaType, LUA_MULTRET, LuaError } from '../dist/index.js' +// Built into dist/ next to the library, which it reaches by the package's own name so the entry +// point is whatever package.json exports rather than a path fixed here. +import { LuaRuntime, LuaReturn, LuaType, LUA_MULTRET, LuaError } from 'wasmoon' import pkg from '../package.json' with { type: 'json' } import fs from 'node:fs' import readline from 'node:readline' diff --git a/src/declarations.d.ts b/src/declarations.d.ts index d1df7e0..012517d 100644 --- a/src/declarations.d.ts +++ b/src/declarations.d.ts @@ -19,3 +19,8 @@ declare module 'package-version' { const value: string export default value } + +declare namespace WebAssembly { + function promising any>(fn: T): (...args: Parameters) => Promise> + const Suspending: new (fn: (...args: any[]) => any) => (...args: any[]) => any +} diff --git a/src/module.ts b/src/module.ts index 159ea31..a39d1eb 100755 --- a/src/module.ts +++ b/src/module.ts @@ -3,18 +3,9 @@ // `/// ` at the top of the emitted declarations to cover everyone // else. tsc drops the directive when it is written here, hence the build step. import initWasmModule from '../build/glue.js' -import { limitError, settleOrInterrupt, yieldToEventLoop } from './async' +import { limitError, type PendingSuspend, settleOrInterrupt, type SettleOutcome, yieldToEventLoop } from './async' import type Thread from './thread' -import { - defaultWarnHandler, - LUA_REGISTRYINDEX, - type LuaAddress, - type LuaInterruptError, - LuaReturn, - LuaType, - type LuaWarnHandler, - PointerSize, -} from './types' +import { defaultWarnHandler, LUA_REGISTRYINDEX, type LuaAddress, LuaReturn, LuaType, type LuaWarnHandler, PointerSize } from './types' // A rolldown plugin will resolve this to the current version on package.json import version from 'package-version' @@ -66,6 +57,7 @@ export interface LuaEmscriptenModule extends EmscriptenModule { stackSave: () => number stackRestore: (pointer: number) => void ENV: EnvironmentVariables + _wasmoon_isarray: (L: LuaAddress, index: number) => number _realloc: (pointer: number, size: number) => number } @@ -152,6 +144,12 @@ const INLINE_ENCODE_LIMIT = 40 // mostly the subarray view and the call -- while the inline path grows per byte; the two cross // here. Most reads are well under it: table keys, global names, short values. const INLINE_DECODE_LIMIT = 32 +// The short strings read out of Lua are mostly the same few names over and over -- table keys, +// globals, metamethod names -- so the string built for a run of bytes is kept and handed back the +// next time those bytes are read, which also gives the property lookups it usually feeds the +// same, already internalized string. Direct mapped on a hash of the bytes; a power of two. Sized +// for a small working set of repeated names; a full cache must also fit the retained-memory budget. +const DECODED_STRING_CACHE_SIZE = 32 // The wasm value types Emscripten's function signature letters map to. `p` is a pointer, which is // an i32 in a build without MEMORY64. @@ -187,11 +185,6 @@ function buildTrampolineModule(signature: string): WebAssembly.Module { return new WebAssembly.Module(Uint8Array.from([0, 0x61, 0x73, 0x6d, 1, 0, 0, 0, ...typeSection, ...importSection, ...exportSection])) } -interface ReferenceMetadata { - index: number - refCount: number -} - /** A {@link LuaModuleOptions.mounts} entry with both sides checked, ready for `FS.mount`. */ interface ResolvedMount { /** Absolute, with no trailing slash and no `.` or `..` in it. */ @@ -275,6 +268,11 @@ function assertMountFits(live: readonly ResolvedMount[], candidate: ResolvedMoun } } +function mountHostDirectory(fs: EmscriptenFS, { virtualPath, hostPath }: ResolvedMount): void { + fs.mkdirTree(virtualPath) + fs.mount(fs.filesystems.NODEFS, { root: hostPath }, virtualPath) +} + /** Everything the wasm module needs before it starts, and nothing that outlives that. */ interface PreRunConfig { env: EnvironmentVariables | undefined @@ -284,6 +282,11 @@ interface PreRunConfig { stderr: LuaModuleOptions['stderr'] } +interface ReferenceEntry { + value: unknown + count: number +} + /** * Built from a record rather than closed over `initialize`'s scope, because Emscripten keeps * `Module.preRun` for the module's lifetime and a closure would pin everything around it with it. @@ -296,10 +299,8 @@ function createPreRun(config: PreRunConfig): (initializedModule: LuaEmscriptenMo // Nothing to do for `fs: 'host'`: that glue is NODERAWFS, so the filesystem already is the // host's, working directory included. - for (const { virtualPath, hostPath } of config.mounts) { - const fs = initializedModule.FS - fs.mkdirTree(virtualPath) - fs.mount(fs.filesystems.NODEFS, { root: hostPath }, virtualPath) + for (const mount of config.mounts) { + mountHostDirectory(initializedModule.FS, mount) } if (config.stdin || config.stdout || config.stderr) { @@ -418,174 +419,182 @@ export default class LuaModule { /** The async engine requested at load, as {@link LuaModuleOptions.async}. */ public readonly asyncEngine: 'auto' | 'jspi' | 'yield' - public luaL_checkversion_: (L: LuaAddress, ver: number, sz: number) => void - public luaL_getmetafield: (L: LuaAddress, obj: number, e: string | null) => LuaType - public luaL_callmeta: (L: LuaAddress, obj: number, e: string | null) => number - public luaL_argerror: (L: LuaAddress, arg: number, extramsg: string | null) => number - public luaL_typeerror: (L: LuaAddress, arg: number, tname: string | null) => number - public luaL_checklstring: (L: LuaAddress, arg: number, l: number | null) => string - public luaL_optlstring: (L: LuaAddress, arg: number, def: string | null, l: number | null) => string - public luaL_checknumber: (L: LuaAddress, arg: number) => number - public luaL_optnumber: (L: LuaAddress, arg: number, def: number) => number + declare public luaL_checkversion_: (L: LuaAddress, ver: number, sz: number) => void + declare public luaL_getmetafield: (L: LuaAddress, obj: number, e: string | null) => LuaType + declare public luaL_callmeta: (L: LuaAddress, obj: number, e: string | null) => number + declare public luaL_argerror: (L: LuaAddress, arg: number, extramsg: string | null) => number + declare public luaL_typeerror: (L: LuaAddress, arg: number, tname: string | null) => number + declare public luaL_checklstring: (L: LuaAddress, arg: number, l: number | null) => string + declare public luaL_optlstring: (L: LuaAddress, arg: number, def: string | null, l: number | null) => string + declare public luaL_checknumber: (L: LuaAddress, arg: number) => number + declare public luaL_optnumber: (L: LuaAddress, arg: number, def: number) => number // lua_Integer is 64 bit, and the module is built with WASM_BIGINT, so these cross as BigInt. - public luaL_checkinteger: (L: LuaAddress, arg: number) => bigint - public luaL_optinteger: (L: LuaAddress, arg: number, def: bigint) => bigint - public luaL_checkstack: (L: LuaAddress, sz: number, msg: string | null) => void - public luaL_checktype: (L: LuaAddress, arg: number, t: number) => void - public luaL_checkany: (L: LuaAddress, arg: number) => void - public luaL_newmetatable: (L: LuaAddress, tname: string | null) => number - public luaL_setmetatable: (L: LuaAddress, tname: string | null) => void - public luaL_testudata: (L: LuaAddress, ud: number, tname: string | null) => LuaAddress - public luaL_checkudata: (L: LuaAddress, ud: number, tname: string | null) => LuaAddress - public luaL_where: (L: LuaAddress, lvl: number) => void - public luaL_fileresult: (L: LuaAddress, stat: number, fname: string | null) => number - public luaL_execresult: (L: LuaAddress, stat: number) => number - public luaL_ref: (L: LuaAddress, t: number) => number - public luaL_unref: (L: LuaAddress, t: number, ref: number) => void - public luaL_loadfilex: (L: LuaAddress, filename: string | null, mode: string | null) => LuaReturn - public luaL_loadbufferx: ( + declare public luaL_checkinteger: (L: LuaAddress, arg: number) => bigint + declare public luaL_optinteger: (L: LuaAddress, arg: number, def: bigint) => bigint + declare public luaL_checkstack: (L: LuaAddress, sz: number, msg: string | null) => void + declare public luaL_checktype: (L: LuaAddress, arg: number, t: number) => void + declare public luaL_checkany: (L: LuaAddress, arg: number) => void + declare public luaL_newmetatable: (L: LuaAddress, tname: string | null) => number + declare public luaL_setmetatable: (L: LuaAddress, tname: string | null) => void + declare public luaL_testudata: (L: LuaAddress, ud: number, tname: string | null) => LuaAddress + declare public luaL_checkudata: (L: LuaAddress, ud: number, tname: string | null) => LuaAddress + declare public luaL_where: (L: LuaAddress, lvl: number) => void + declare public luaL_fileresult: (L: LuaAddress, stat: number, fname: string | null) => number + declare public luaL_execresult: (L: LuaAddress, stat: number) => number + declare public luaL_ref: (L: LuaAddress, t: number) => number + declare public luaL_unref: (L: LuaAddress, t: number, ref: number) => void + declare public luaL_loadfilex: (L: LuaAddress, filename: string | null, mode: string | null) => LuaReturn + declare public luaL_loadbufferx: ( L: LuaAddress, buff: string | number | null, sz: number, name: string | number | null, mode: string | null, ) => LuaReturn - public luaL_loadstring: (L: LuaAddress, s: string | null) => LuaReturn - public luaL_newstate: () => LuaAddress - public luaL_len: (L: LuaAddress, idx: number) => bigint - public luaL_addgsub: (b: number | null, s: string | null, p: string | null, r: string | null) => void - public luaL_gsub: (L: LuaAddress, s: string | null, p: string | null, r: string | null) => string - public luaL_setfuncs: (L: LuaAddress, l: number | null, nup: number) => void - public luaL_getsubtable: (L: LuaAddress, idx: number, fname: string | null) => number - public luaL_traceback: (L: LuaAddress, L1: LuaAddress, msg: string | null, level: number) => void - public luaL_requiref: (L: LuaAddress, modname: string | null, openf: number, glb: number) => void - public luaL_openselectedlibs: (L: LuaAddress, load: number, preload: number) => void - public luaL_buffinit: (L: LuaAddress, B: number | null) => void - public luaL_prepbuffsize: (B: number | null, sz: number) => string - public luaL_addlstring: (B: number | null, s: string | null, l: number) => void - public luaL_addstring: (B: number | null, s: string | null) => void - public luaL_addvalue: (B: number | null) => void - public luaL_pushresult: (B: number | null) => void - public luaL_pushresultsize: (B: number | null, sz: number) => void - public luaL_buffinitsize: (L: LuaAddress, B: number | null, sz: number) => string - public lua_newstate: (f: number | null, ud: number | null, seed: number) => LuaAddress - public lua_close: (L: LuaAddress) => void - public lua_newthread: (L: LuaAddress) => LuaAddress - public lua_closethread: (L: LuaAddress, from: LuaAddress | null) => LuaReturn - public lua_resetthread: (L: LuaAddress) => LuaReturn - public lua_atpanic: (L: LuaAddress, panicf: number) => number - public lua_version: (L: LuaAddress) => number - public lua_absindex: (L: LuaAddress, idx: number) => number - public lua_gettop: (L: LuaAddress) => number - public lua_settop: (L: LuaAddress, idx: number) => void - public lua_pushvalue: (L: LuaAddress, idx: number) => void - public lua_rotate: (L: LuaAddress, idx: number, n: number) => void - public lua_copy: (L: LuaAddress, fromidx: number, toidx: number) => void - public lua_checkstack: (L: LuaAddress, n: number) => number - public lua_xmove: (from: LuaAddress, to: LuaAddress, n: number) => void - public lua_isnumber: (L: LuaAddress, idx: number) => number - public lua_isstring: (L: LuaAddress, idx: number) => number - public lua_iscfunction: (L: LuaAddress, idx: number) => number - public lua_isinteger: (L: LuaAddress, idx: number) => number - public lua_isuserdata: (L: LuaAddress, idx: number) => number - public lua_type: (L: LuaAddress, idx: number) => LuaType - public lua_typename: (L: LuaAddress, tp: number) => string - public lua_tonumberx: (L: LuaAddress, idx: number, isnum: number | null) => number - public lua_tointegerx: (L: LuaAddress, idx: number, isnum: number | null) => bigint - public lua_toboolean: (L: LuaAddress, idx: number) => number - public lua_rawlen: (L: LuaAddress, idx: number) => bigint - public lua_tocfunction: (L: LuaAddress, idx: number) => number - public lua_touserdata: (L: LuaAddress, idx: number) => LuaAddress - public lua_tothread: (L: LuaAddress, idx: number) => LuaAddress - public lua_topointer: (L: LuaAddress, idx: number) => LuaAddress - public lua_arith: (L: LuaAddress, op: number) => void - public lua_rawequal: (L: LuaAddress, idx1: number, idx2: number) => number - public lua_compare: (L: LuaAddress, idx1: number, idx2: number, op: number) => number - public lua_pushnil: (L: LuaAddress) => void - public lua_pushnumber: (L: LuaAddress, n: number) => void - public lua_pushinteger: (L: LuaAddress, n: number | bigint) => void - public lua_pushlstring: (L: LuaAddress, s: number, len: number) => void - public lua_pushcclosure: (L: LuaAddress, fn: number, n: number) => void - public lua_pushboolean: (L: LuaAddress, b: number) => void - public lua_pushlightuserdata: (L: LuaAddress, p: number | null) => void - public lua_pushthread: (L: LuaAddress) => number - public lua_getglobal: (L: LuaAddress, name: string | null) => LuaType - public lua_gettable: (L: LuaAddress, idx: number) => LuaType - public lua_getfield: (L: LuaAddress, idx: number, k: string | null) => LuaType - public lua_geti: (L: LuaAddress, idx: number, n: number | bigint) => LuaType - public lua_rawget: (L: LuaAddress, idx: number) => LuaType - public lua_rawgeti: (L: LuaAddress, idx: number, n: number | bigint) => LuaType - public lua_rawgetp: (L: LuaAddress, idx: number, p: number | null) => LuaType - public lua_createtable: (L: LuaAddress, narr: number, nrec: number) => void - public lua_newuserdatauv: (L: LuaAddress, sz: number, nuvalue: number) => LuaAddress - public lua_getmetatable: (L: LuaAddress, objindex: number) => number - public lua_getiuservalue: (L: LuaAddress, idx: number, n: number) => LuaType - public lua_setglobal: (L: LuaAddress, name: string | null) => void - public lua_settable: (L: LuaAddress, idx: number) => void - public lua_setfield: (L: LuaAddress, idx: number, k: string | null) => void - public lua_seti: (L: LuaAddress, idx: number, n: number | bigint) => void - public lua_rawset: (L: LuaAddress, idx: number) => void - public lua_rawseti: (L: LuaAddress, idx: number, n: number | bigint) => void - public lua_rawsetp: (L: LuaAddress, idx: number, p: number | null) => void - public lua_setmetatable: (L: LuaAddress, objindex: number) => number - public lua_setiuservalue: (L: LuaAddress, idx: number, n: number) => number - public lua_callk: (L: LuaAddress, nargs: number, nresults: number, ctx: number, k: number | null) => void - public lua_pcallk: (L: LuaAddress, nargs: number, nresults: number, errfunc: number, ctx: number, k: number | null) => LuaReturn - public lua_load: (L: LuaAddress, reader: number | null, dt: number | null, chunkname: string | null, mode: string | null) => LuaReturn - public lua_dump: (L: LuaAddress, writer: number | null, data: number | null, strip: number) => number - public lua_yieldk: (L: LuaAddress, nresults: number, ctx: number, k: number | null) => number - public lua_resume: (L: LuaAddress, from: LuaAddress | null, narg: number, nres: number | null) => LuaReturn - public lua_status: (L: LuaAddress) => LuaReturn - public lua_isyieldable: (L: LuaAddress) => number - public lua_setwarnf: (L: LuaAddress, f: number | null, ud: number | null) => void - public lua_warning: (L: LuaAddress, msg: string | null, tocont: number) => void - public lua_error: (L: LuaAddress) => number - public lua_next: (L: LuaAddress, idx: number) => number - public lua_concat: (L: LuaAddress, n: number) => void - public lua_len: (L: LuaAddress, idx: number) => void - public lua_stringtonumber: (L: LuaAddress, s: string | null) => number - public lua_getallocf: (L: LuaAddress, ud: number | null) => number - public lua_setallocf: (L: LuaAddress, f: number | null, ud: number | null) => void - public lua_toclose: (L: LuaAddress, idx: number) => void - public lua_closeslot: (L: LuaAddress, idx: number) => void - public lua_getstack: (L: LuaAddress, level: number, ar: number | null) => number - public lua_getinfo: (L: LuaAddress, what: string | null, ar: number | null) => number - public lua_getlocal: (L: LuaAddress, ar: number | null, n: number) => string - public lua_setlocal: (L: LuaAddress, ar: number | null, n: number) => string - public lua_getupvalue: (L: LuaAddress, funcindex: number, n: number) => string - public lua_setupvalue: (L: LuaAddress, funcindex: number, n: number) => string - public lua_upvalueid: (L: LuaAddress, fidx: number, n: number) => LuaAddress - public lua_upvaluejoin: (L: LuaAddress, fidx1: number, n1: number, fidx2: number, n2: number) => void - public lua_sethook: (L: LuaAddress, func: number | null, mask: number, count: number) => void + declare public luaL_loadstring: (L: LuaAddress, s: string | null) => LuaReturn + declare public luaL_newstate: () => LuaAddress + declare public luaL_len: (L: LuaAddress, idx: number) => bigint + declare public luaL_addgsub: (b: number | null, s: string | null, p: string | null, r: string | null) => void + declare public luaL_gsub: (L: LuaAddress, s: string | null, p: string | null, r: string | null) => string + declare public luaL_setfuncs: (L: LuaAddress, l: number | null, nup: number) => void + declare public luaL_getsubtable: (L: LuaAddress, idx: number, fname: string | null) => number + declare public luaL_traceback: (L: LuaAddress, L1: LuaAddress, msg: string | null, level: number) => void + declare public luaL_requiref: (L: LuaAddress, modname: string | null, openf: number, glb: number) => void + declare public luaL_openselectedlibs: (L: LuaAddress, load: number, preload: number) => void + declare public luaL_buffinit: (L: LuaAddress, B: number | null) => void + declare public luaL_prepbuffsize: (B: number | null, sz: number) => string + declare public luaL_addlstring: (B: number | null, s: string | null, l: number) => void + declare public luaL_addstring: (B: number | null, s: string | null) => void + declare public luaL_addvalue: (B: number | null) => void + declare public luaL_pushresult: (B: number | null) => void + declare public luaL_pushresultsize: (B: number | null, sz: number) => void + declare public luaL_buffinitsize: (L: LuaAddress, B: number | null, sz: number) => string + declare public lua_newstate: (f: number | null, ud: number | null, seed: number) => LuaAddress + declare public lua_close: (L: LuaAddress) => void + declare public lua_newthread: (L: LuaAddress) => LuaAddress + declare public lua_closethread: (L: LuaAddress, from: LuaAddress | null) => LuaReturn + declare public lua_atpanic: (L: LuaAddress, panicf: number) => number + declare public lua_version: (L: LuaAddress) => number + declare public lua_absindex: (L: LuaAddress, idx: number) => number + declare public lua_gettop: (L: LuaAddress) => number + declare public lua_settop: (L: LuaAddress, idx: number) => void + declare public lua_pushvalue: (L: LuaAddress, idx: number) => void + declare public lua_rotate: (L: LuaAddress, idx: number, n: number) => void + declare public lua_copy: (L: LuaAddress, fromidx: number, toidx: number) => void + declare public lua_checkstack: (L: LuaAddress, n: number) => number + declare public lua_xmove: (from: LuaAddress, to: LuaAddress, n: number) => void + declare public lua_isnumber: (L: LuaAddress, idx: number) => number + declare public lua_isstring: (L: LuaAddress, idx: number) => number + declare public lua_iscfunction: (L: LuaAddress, idx: number) => number + declare public lua_isinteger: (L: LuaAddress, idx: number) => number + declare public lua_isuserdata: (L: LuaAddress, idx: number) => number + declare public lua_type: (L: LuaAddress, idx: number) => LuaType + declare public lua_typename: (L: LuaAddress, tp: number) => string + declare public lua_tonumberx: (L: LuaAddress, idx: number, isnum: number | null) => number + declare public lua_tointegerx: (L: LuaAddress, idx: number, isnum: number | null) => bigint + declare public lua_toboolean: (L: LuaAddress, idx: number) => number + declare public lua_rawlen: (L: LuaAddress, idx: number) => bigint + declare public lua_tocfunction: (L: LuaAddress, idx: number) => number + declare public lua_touserdata: (L: LuaAddress, idx: number) => LuaAddress + declare public lua_tothread: (L: LuaAddress, idx: number) => LuaAddress + declare public lua_topointer: (L: LuaAddress, idx: number) => LuaAddress + declare public lua_arith: (L: LuaAddress, op: number) => void + declare public lua_rawequal: (L: LuaAddress, idx1: number, idx2: number) => number + declare public lua_compare: (L: LuaAddress, idx1: number, idx2: number, op: number) => number + declare public lua_pushnil: (L: LuaAddress) => void + declare public lua_pushnumber: (L: LuaAddress, n: number) => void + declare public lua_pushinteger: (L: LuaAddress, n: number | bigint) => void + declare public lua_pushlstring: (L: LuaAddress, s: number, len: number) => void + declare public lua_pushcclosure: (L: LuaAddress, fn: number, n: number) => void + declare public lua_pushboolean: (L: LuaAddress, b: number) => void + declare public lua_pushlightuserdata: (L: LuaAddress, p: number | null) => void + declare public lua_pushthread: (L: LuaAddress) => number + declare public lua_getglobal: (L: LuaAddress, name: string | null) => LuaType + declare public lua_gettable: (L: LuaAddress, idx: number) => LuaType + declare public lua_getfield: (L: LuaAddress, idx: number, k: string | null) => LuaType + declare public lua_geti: (L: LuaAddress, idx: number, n: number | bigint) => LuaType + declare public lua_rawget: (L: LuaAddress, idx: number) => LuaType + declare public lua_rawgeti: (L: LuaAddress, idx: number, n: number | bigint) => LuaType + declare public lua_rawgetp: (L: LuaAddress, idx: number, p: number | null) => LuaType + declare public lua_createtable: (L: LuaAddress, narr: number, nrec: number) => void + declare public lua_newuserdatauv: (L: LuaAddress, sz: number, nuvalue: number) => LuaAddress + declare public lua_getmetatable: (L: LuaAddress, objindex: number) => number + declare public lua_getiuservalue: (L: LuaAddress, idx: number, n: number) => LuaType + declare public lua_setglobal: (L: LuaAddress, name: string | null) => void + declare public lua_settable: (L: LuaAddress, idx: number) => void + declare public lua_setfield: (L: LuaAddress, idx: number, k: string | null) => void + declare public lua_seti: (L: LuaAddress, idx: number, n: number | bigint) => void + declare public lua_rawset: (L: LuaAddress, idx: number) => void + declare public lua_rawseti: (L: LuaAddress, idx: number, n: number | bigint) => void + declare public lua_rawsetp: (L: LuaAddress, idx: number, p: number | null) => void + declare public lua_setmetatable: (L: LuaAddress, objindex: number) => number + declare public lua_setiuservalue: (L: LuaAddress, idx: number, n: number) => number + declare public lua_callk: (L: LuaAddress, nargs: number, nresults: number, ctx: number, k: number | null) => void + declare public lua_pcallk: (L: LuaAddress, nargs: number, nresults: number, errfunc: number, ctx: number, k: number | null) => LuaReturn + declare public lua_load: ( + L: LuaAddress, + reader: number | null, + dt: number | null, + chunkname: string | null, + mode: string | null, + ) => LuaReturn + declare public lua_dump: (L: LuaAddress, writer: number | null, data: number | null, strip: number) => number + declare public lua_yieldk: (L: LuaAddress, nresults: number, ctx: number, k: number | null) => number + declare public lua_resume: (L: LuaAddress, from: LuaAddress | null, narg: number, nres: number | null) => LuaReturn + declare public lua_status: (L: LuaAddress) => LuaReturn + declare public lua_isyieldable: (L: LuaAddress) => number + declare public lua_setwarnf: (L: LuaAddress, f: number | null, ud: number | null) => void + declare public lua_warning: (L: LuaAddress, msg: string | null, tocont: number) => void + declare public lua_error: (L: LuaAddress) => number + declare public lua_next: (L: LuaAddress, idx: number) => number + declare public lua_concat: (L: LuaAddress, n: number) => void + declare public lua_len: (L: LuaAddress, idx: number) => void + declare public lua_stringtonumber: (L: LuaAddress, s: string | null) => number + declare public lua_getallocf: (L: LuaAddress, ud: number | null) => number + declare public lua_setallocf: (L: LuaAddress, f: number | null, ud: number | null) => void + declare public lua_toclose: (L: LuaAddress, idx: number) => void + declare public lua_closeslot: (L: LuaAddress, idx: number) => void + declare public lua_getstack: (L: LuaAddress, level: number, ar: number | null) => number + declare public lua_getinfo: (L: LuaAddress, what: string | null, ar: number | null) => number + declare public lua_getlocal: (L: LuaAddress, ar: number | null, n: number) => string + declare public lua_setlocal: (L: LuaAddress, ar: number | null, n: number) => string + declare public lua_getupvalue: (L: LuaAddress, funcindex: number, n: number) => string + declare public lua_setupvalue: (L: LuaAddress, funcindex: number, n: number) => string + declare public lua_upvalueid: (L: LuaAddress, fidx: number, n: number) => LuaAddress + declare public lua_upvaluejoin: (L: LuaAddress, fidx1: number, n1: number, fidx2: number, n2: number) => void + declare public lua_sethook: (L: LuaAddress, func: number | null, mask: number, count: number) => void /** Installs the await hook the {@link wasmoon_push_jsfunction} closures suspend through. */ - public wasmoon_set_await_hook: (hook: number) => void + declare public wasmoon_set_await_hook: (hook: number, resumeHook?: number) => void /** Pops the reference box on the stack and pushes a JS function closure over it and `callHook`. */ - public wasmoon_push_jsfunction: (L: LuaAddress, callHook: number) => void - public lua_gethook: (L: LuaAddress) => number - public lua_gethookmask: (L: LuaAddress) => number - public lua_gethookcount: (L: LuaAddress) => number - public lua_setcstacklimit: (_L: LuaAddress, _limit: number) => number - public luaopen_base: (L: LuaAddress) => number - public luaopen_coroutine: (L: LuaAddress) => number - public luaopen_table: (L: LuaAddress) => number - public luaopen_io: (L: LuaAddress) => number - public luaopen_os: (L: LuaAddress) => number - public luaopen_string: (L: LuaAddress) => number - public luaopen_utf8: (L: LuaAddress) => number - public luaopen_math: (L: LuaAddress) => number - public luaopen_debug: (L: LuaAddress) => number - public luaopen_package: (L: LuaAddress) => number - public luaL_openlibs: (L: LuaAddress) => void - public lua_gc: (L: LuaAddress, what: number, a: number, b: number) => number + declare public wasmoon_push_jsfunction: (L: LuaAddress, callHook: number) => void + declare public lua_gethook: (L: LuaAddress) => number + declare public lua_gethookmask: (L: LuaAddress) => number + declare public lua_gethookcount: (L: LuaAddress) => number + declare public luaopen_base: (L: LuaAddress) => number + declare public luaopen_coroutine: (L: LuaAddress) => number + declare public luaopen_table: (L: LuaAddress) => number + declare public luaopen_io: (L: LuaAddress) => number + declare public luaopen_os: (L: LuaAddress) => number + declare public luaopen_string: (L: LuaAddress) => number + declare public luaopen_utf8: (L: LuaAddress) => number + declare public luaopen_math: (L: LuaAddress) => number + declare public luaopen_debug: (L: LuaAddress) => number + declare public luaopen_package: (L: LuaAddress) => number /** The mounts that are live, so a later one can be checked against them. */ private readonly mounts: ResolvedMount[] private readonly cStringCache = new Map() private readonly trampolineModules = new Map() - private referenceTracker = new WeakMap() - private referenceMap = new Map() - private availableReferences: number[] = [] + // A live slot holds a value and its holder count; a released slot holds the negated next free + // index. Combining them keeps just one array slot per hole when a high live index prevents + // trimming, instead of retaining separate value and count arrays. Records exist only while + // live. External indices are one-based so a reference box never carries a null pointer. + // Released tails are trimmed when at least half the slots can be dropped. + private readonly references: (ReferenceEntry | number)[] = [] + private firstFreeReference = 0 + private highestReference = 0 + private readonly referenceIndexes = new WeakMap() private lastRefIndex?: number // Lua strings are byte arrays that may contain NUL, so they cannot go through Emscripten's @@ -629,23 +638,10 @@ export default class LuaModule { */ public stackCanSuspend = false /** - * The promise a JSPI `:await()` stashed for the C trampoline's await hook to suspend on, along - * with how to marshal its settled value back onto the Lua stack. Read synchronously by the - * await hook right after the await closure returns, so a single slot is reentrancy safe. + * Read synchronously by the await hook right after the await closure returns, so a single slot + * is reentrancy safe. */ - public pendingSuspend: - | { - run: Thread - promise: PromiseLike - signal: AbortSignal | undefined - deadline: number | undefined - isClosed: () => boolean - onResolve: (value: unknown) => number - onReject: (error: unknown) => number - onInterrupt: (error: LuaInterruptError) => number - } - | undefined - private awaitHookPointer: number | undefined + public pendingSuspend: PendingSuspend | undefined /** The innermost Lua driver. Installed only while entering or continuing Lua. */ public activeRun: Thread | undefined private asyncSteps = 0 @@ -669,6 +665,12 @@ export default class LuaModule { | ((L: LuaAddress, from: LuaAddress | null, narg: number, nres: number) => Promise) | undefined private stringBuffer = 0 + // Initialized together on the first short ASCII read. Numeric-only runtimes need no cache. + // Empty slots hold '', which no non-empty read can match, under a hash of 0. + private decodedStrings: string[] | undefined + private decodedStringHashes!: Int32Array + // The hash last missed in each slot, so a string is kept only once it has been read twice. + private candidateStringHashes!: Int32Array /** Built on first use by {@link referenceGcFunction}, then kept for the module's lifetime. */ private referenceGcPointer: number | undefined @@ -691,168 +693,162 @@ export default class LuaModule { ) } - this.luaL_checkversion_ = this.cwrap('luaL_checkversion_', null, ['number', 'number', 'number']) - this.luaL_getmetafield = this.cwrap('luaL_getmetafield', 'number', ['number', 'number', 'string']) - this.luaL_callmeta = this.cwrap('luaL_callmeta', 'number', ['number', 'number', 'string']) - this.luaL_argerror = this.cwrap('luaL_argerror', 'number', ['number', 'number', 'string']) - this.luaL_typeerror = this.cwrap('luaL_typeerror', 'number', ['number', 'number', 'string']) - this.luaL_checklstring = this.cwrap('luaL_checklstring', 'string', ['number', 'number', 'number']) - this.luaL_optlstring = this.cwrap('luaL_optlstring', 'string', ['number', 'number', 'string', 'number']) - this.luaL_checknumber = this.cwrap('luaL_checknumber', 'number', ['number', 'number']) - this.luaL_optnumber = this.cwrap('luaL_optnumber', 'number', ['number', 'number', 'number']) - this.luaL_checkinteger = this.cwrap('luaL_checkinteger', 'number', ['number', 'number']) - this.luaL_optinteger = this.cwrap('luaL_optinteger', 'number', ['number', 'number', 'number']) - this.luaL_checkstack = this.cwrap('luaL_checkstack', null, ['number', 'number', 'string']) - this.luaL_checktype = this.cwrap('luaL_checktype', null, ['number', 'number', 'number']) - this.luaL_checkany = this.cwrap('luaL_checkany', null, ['number', 'number']) - this.luaL_newmetatable = this.cwrap('luaL_newmetatable', 'number', ['number', 'string']) - this.luaL_setmetatable = this.cwrap('luaL_setmetatable', null, ['number', 'string']) - this.luaL_testudata = this.cwrap('luaL_testudata', 'number', ['number', 'number', 'string']) - this.luaL_checkudata = this.cwrap('luaL_checkudata', 'number', ['number', 'number', 'string']) - this.luaL_where = this.cwrap('luaL_where', null, ['number', 'number']) - this.luaL_fileresult = this.cwrap('luaL_fileresult', 'number', ['number', 'number', 'string']) - this.luaL_execresult = this.cwrap('luaL_execresult', 'number', ['number', 'number']) - this.luaL_ref = this.cwrap('luaL_ref', 'number', ['number', 'number']) - this.luaL_unref = this.cwrap('luaL_unref', null, ['number', 'number', 'number']) - this.luaL_loadfilex = this.cwrap('luaL_loadfilex', 'number', ['number', 'string', 'string']) - this.luaL_loadbufferx = this.cwrap('luaL_loadbufferx', 'number', ['number', 'string|number', 'number', 'string|number', 'string']) - this.luaL_loadstring = this.cwrap('luaL_loadstring', 'number', ['number', 'string']) - this.luaL_newstate = this.cwrap('luaL_newstate', 'number', []) - this.luaL_len = this.cwrap('luaL_len', 'number', ['number', 'number']) - this.luaL_addgsub = this.cwrap('luaL_addgsub', null, ['number', 'string', 'string', 'string']) - this.luaL_gsub = this.cwrap('luaL_gsub', 'string', ['number', 'string', 'string', 'string']) - this.luaL_setfuncs = this.cwrap('luaL_setfuncs', null, ['number', 'number', 'number']) - this.luaL_getsubtable = this.cwrap('luaL_getsubtable', 'number', ['number', 'number', 'string']) - this.luaL_traceback = this.cwrap('luaL_traceback', null, ['number', 'number', 'string', 'number']) - this.luaL_requiref = this.cwrap('luaL_requiref', null, ['number', 'string', 'number', 'number']) - this.luaL_openselectedlibs = this.cwrap('luaL_openselectedlibs', null, ['number', 'number', 'number']) - this.luaL_buffinit = this.cwrap('luaL_buffinit', null, ['number', 'number']) - this.luaL_prepbuffsize = this.cwrap('luaL_prepbuffsize', 'string', ['number', 'number']) - this.luaL_addlstring = this.cwrap('luaL_addlstring', null, ['number', 'string', 'number']) - this.luaL_addstring = this.cwrap('luaL_addstring', null, ['number', 'string']) - this.luaL_addvalue = this.cwrap('luaL_addvalue', null, ['number']) - this.luaL_pushresult = this.cwrap('luaL_pushresult', null, ['number']) - this.luaL_pushresultsize = this.cwrap('luaL_pushresultsize', null, ['number', 'number']) - this.luaL_buffinitsize = this.cwrap('luaL_buffinitsize', 'string', ['number', 'number', 'number']) - this.lua_newstate = this.cwrap('lua_newstate', 'number', ['number', 'number', 'number']) - this.lua_close = this.cwrap('lua_close', null, ['number']) - this.lua_newthread = this.cwrap('lua_newthread', 'number', ['number']) - this.lua_closethread = this.cwrap('lua_closethread', 'number', ['number', 'number']) - this.lua_resetthread = (L) => this.lua_closethread(L, null) - this.lua_atpanic = this.cwrap('lua_atpanic', 'number', ['number', 'number']) - this.lua_version = this.cwrap('lua_version', 'number', ['number']) - this.lua_absindex = this.cwrap('lua_absindex', 'number', ['number', 'number']) - this.lua_gettop = this.cwrap('lua_gettop', 'number', ['number']) - this.lua_settop = this.cwrap('lua_settop', null, ['number', 'number']) - this.lua_pushvalue = this.cwrap('lua_pushvalue', null, ['number', 'number']) - this.lua_rotate = this.cwrap('lua_rotate', null, ['number', 'number', 'number']) - this.lua_copy = this.cwrap('lua_copy', null, ['number', 'number', 'number']) - this.lua_checkstack = this.cwrap('lua_checkstack', 'number', ['number', 'number']) - this.lua_xmove = this.cwrap('lua_xmove', null, ['number', 'number', 'number']) - this.lua_isnumber = this.cwrap('lua_isnumber', 'number', ['number', 'number']) - this.lua_isstring = this.cwrap('lua_isstring', 'number', ['number', 'number']) - this.lua_iscfunction = this.cwrap('lua_iscfunction', 'number', ['number', 'number']) - this.lua_isinteger = this.cwrap('lua_isinteger', 'number', ['number', 'number']) - this.lua_isuserdata = this.cwrap('lua_isuserdata', 'number', ['number', 'number']) - this.lua_type = this.cwrap('lua_type', 'number', ['number', 'number']) - this.lua_typename = this.cwrap('lua_typename', 'string', ['number', 'number']) - this.lua_tonumberx = this.cwrap('lua_tonumberx', 'number', ['number', 'number', 'number']) - this.lua_tointegerx = this.cwrap('lua_tointegerx', 'number', ['number', 'number', 'number']) - this.lua_toboolean = this.cwrap('lua_toboolean', 'number', ['number', 'number']) - this.lua_rawlen = this.cwrap('lua_rawlen', 'number', ['number', 'number']) - this.lua_tocfunction = this.cwrap('lua_tocfunction', 'number', ['number', 'number']) - this.lua_touserdata = this.cwrap('lua_touserdata', 'number', ['number', 'number']) - this.lua_tothread = this.cwrap('lua_tothread', 'number', ['number', 'number']) - this.lua_topointer = this.cwrap('lua_topointer', 'number', ['number', 'number']) - this.lua_arith = this.cwrap('lua_arith', null, ['number', 'number']) - this.lua_rawequal = this.cwrap('lua_rawequal', 'number', ['number', 'number', 'number']) - this.lua_compare = this.cwrap('lua_compare', 'number', ['number', 'number', 'number', 'number']) - this.lua_pushnil = this.cwrap('lua_pushnil', null, ['number']) - this.lua_pushnumber = this.cwrap('lua_pushnumber', null, ['number', 'number']) - this.lua_pushinteger = this.withIntegerArgument('lua_pushinteger', null, ['number', 'number']) - this.lua_pushcclosure = this.cwrap('lua_pushcclosure', null, ['number', 'number', 'number']) - this.lua_pushboolean = this.cwrap('lua_pushboolean', null, ['number', 'number']) - this.lua_pushlightuserdata = this.cwrap('lua_pushlightuserdata', null, ['number', 'number']) - this.lua_pushthread = this.cwrap('lua_pushthread', 'number', ['number']) - this.lua_getglobal = this.cwrap('lua_getglobal', 'number', ['number', 'string']) - this.lua_gettable = this.cwrap('lua_gettable', 'number', ['number', 'number']) - this.lua_getfield = this.cwrap('lua_getfield', 'number', ['number', 'number', 'string']) - this.lua_geti = this.withIntegerArgument('lua_geti', 'number', ['number', 'number', 'number']) - this.lua_rawget = this.cwrap('lua_rawget', 'number', ['number', 'number']) - this.lua_rawgeti = this.withIntegerArgument('lua_rawgeti', 'number', ['number', 'number', 'number']) - this.lua_rawgetp = this.cwrap('lua_rawgetp', 'number', ['number', 'number', 'number']) - this.lua_createtable = this.cwrap('lua_createtable', null, ['number', 'number', 'number']) - this.lua_newuserdatauv = this.cwrap('lua_newuserdatauv', 'number', ['number', 'number', 'number']) - this.lua_getmetatable = this.cwrap('lua_getmetatable', 'number', ['number', 'number']) - this.lua_getiuservalue = this.cwrap('lua_getiuservalue', 'number', ['number', 'number', 'number']) - this.lua_setglobal = this.cwrap('lua_setglobal', null, ['number', 'string']) - this.lua_settable = this.cwrap('lua_settable', null, ['number', 'number']) - this.lua_setfield = this.cwrap('lua_setfield', null, ['number', 'number', 'string']) - this.lua_seti = this.withIntegerArgument('lua_seti', null, ['number', 'number', 'number']) - this.lua_rawset = this.cwrap('lua_rawset', null, ['number', 'number']) - this.lua_rawseti = this.withIntegerArgument('lua_rawseti', null, ['number', 'number', 'number']) - this.lua_rawsetp = this.cwrap('lua_rawsetp', null, ['number', 'number', 'number']) - this.lua_setmetatable = this.cwrap('lua_setmetatable', 'number', ['number', 'number']) - this.lua_setiuservalue = this.cwrap('lua_setiuservalue', 'number', ['number', 'number', 'number']) - this.lua_callk = this.cwrap('lua_callk', null, ['number', 'number', 'number', 'number', 'number']) - this.lua_pcallk = this.cwrap('lua_pcallk', 'number', ['number', 'number', 'number', 'number', 'number', 'number']) - this.lua_load = this.cwrap('lua_load', 'number', ['number', 'number', 'number', 'string', 'string']) - this.lua_dump = this.cwrap('lua_dump', 'number', ['number', 'number', 'number', 'number']) - this.lua_yieldk = this.cwrap('lua_yieldk', 'number', ['number', 'number', 'number', 'number']) - this.lua_resume = this.cwrap('lua_resume', 'number', ['number', 'number', 'number', 'number']) - this.lua_status = this.cwrap('lua_status', 'number', ['number']) - this.lua_isyieldable = this.cwrap('lua_isyieldable', 'number', ['number']) - this.lua_setwarnf = this.cwrap('lua_setwarnf', null, ['number', 'number', 'number']) - this.lua_warning = this.cwrap('lua_warning', null, ['number', 'string', 'number']) - this.lua_error = this.cwrap('lua_error', 'number', ['number']) - this.lua_next = this.cwrap('lua_next', 'number', ['number', 'number']) - this.lua_concat = this.cwrap('lua_concat', null, ['number', 'number']) - this.lua_len = this.cwrap('lua_len', null, ['number', 'number']) - this.lua_stringtonumber = this.cwrap('lua_stringtonumber', 'number', ['number', 'string']) - this.lua_getallocf = this.cwrap('lua_getallocf', 'number', ['number', 'number']) - this.lua_setallocf = this.cwrap('lua_setallocf', null, ['number', 'number', 'number']) - this.lua_toclose = this.cwrap('lua_toclose', null, ['number', 'number']) - this.lua_closeslot = this.cwrap('lua_closeslot', null, ['number', 'number']) - this.lua_getstack = this.cwrap('lua_getstack', 'number', ['number', 'number', 'number']) - this.lua_getinfo = this.cwrap('lua_getinfo', 'number', ['number', 'string', 'number']) - this.lua_getlocal = this.cwrap('lua_getlocal', 'string', ['number', 'number', 'number']) - this.lua_setlocal = this.cwrap('lua_setlocal', 'string', ['number', 'number', 'number']) - this.lua_getupvalue = this.cwrap('lua_getupvalue', 'string', ['number', 'number', 'number']) - this.lua_setupvalue = this.cwrap('lua_setupvalue', 'string', ['number', 'number', 'number']) - this.lua_upvalueid = this.cwrap('lua_upvalueid', 'number', ['number', 'number', 'number']) - this.lua_upvaluejoin = this.cwrap('lua_upvaluejoin', null, ['number', 'number', 'number', 'number', 'number']) - this.lua_sethook = this.cwrap('lua_sethook', null, ['number', 'number', 'number', 'number']) - this.wasmoon_set_await_hook = this.cwrap('wasmoon_set_await_hook', null, ['number']) - this.wasmoon_push_jsfunction = this.cwrap('wasmoon_push_jsfunction', null, ['number', 'number']) - this.lua_gethook = this.cwrap('lua_gethook', 'number', ['number']) - this.lua_gethookmask = this.cwrap('lua_gethookmask', 'number', ['number']) - this.lua_gethookcount = this.cwrap('lua_gethookcount', 'number', ['number']) - // Deprecated in Lua 5.5; keep the JS API surface as a no-op compatibility shim. - this.lua_setcstacklimit = () => 0 - this.luaopen_base = this.cwrap('luaopen_base', 'number', ['number']) - this.luaopen_coroutine = this.cwrap('luaopen_coroutine', 'number', ['number']) - this.luaopen_table = this.cwrap('luaopen_table', 'number', ['number']) - this.luaopen_io = this.cwrap('luaopen_io', 'number', ['number']) - this.luaopen_os = this.cwrap('luaopen_os', 'number', ['number']) - this.luaopen_string = this.cwrap('luaopen_string', 'number', ['number']) - this.luaopen_utf8 = this.cwrap('luaopen_utf8', 'number', ['number']) - this.luaopen_math = this.cwrap('luaopen_math', 'number', ['number']) - this.luaopen_debug = this.cwrap('luaopen_debug', 'number', ['number']) - this.luaopen_package = this.cwrap('luaopen_package', 'number', ['number']) - this.luaL_openlibs = (L) => this.luaL_openselectedlibs(L, -1, 0) - // lua_gc is variadic: the wasm32 ABI passes `...` as a pointer to the arguments laid out - // in memory, and every argument lua_gc reads is 32 bit. - this.rawLuaGc = this.cwrap('lua_gc', 'number', ['number', 'number', 'number']) - this.lua_gc = (L, what, a, b) => { - this.writePointer(this.gcArgsScratch, a) - this.writePointer(this.gcArgsScratch + PointerSize, b) - return this.rawLuaGc(L, what, this.gcArgsScratch) - } - - this.rawLuaToLString = this.cwrap('lua_tolstring', 'number', ['number', 'number', 'number']) - this.rawLuaLToLString = this.cwrap('luaL_tolstring', 'number', ['number', 'number', 'number']) - this.rawLuaPushString = this.cwrap('lua_pushstring', 'number', ['number', 'number']) - this.lua_pushlstring = this.cwrap('lua_pushlstring', 'number', ['number', 'number', 'number']) + // The bindings that marshal a string or take a lua_Integer are wrapped over the raw export. + // Every other binding crosses only numbers and is the export itself. + this.luaL_getmetafield = this.wrapWithStringArguments(this.exported('luaL_getmetafield'), 'nnns') + this.luaL_callmeta = this.wrapWithStringArguments(this.exported('luaL_callmeta'), 'nnns') + this.luaL_argerror = this.wrapWithStringArguments(this.exported('luaL_argerror'), 'nnns') + this.luaL_typeerror = this.wrapWithStringArguments(this.exported('luaL_typeerror'), 'nnns') + this.luaL_checklstring = this.wrapWithStringArguments(this.exported('luaL_checklstring'), 'snnn') + this.luaL_optlstring = this.wrapWithStringArguments(this.exported('luaL_optlstring'), 'snnsn') + this.luaL_checkstack = this.wrapWithStringArguments(this.exported('luaL_checkstack'), 'nnns') + this.luaL_newmetatable = this.wrapWithStringArguments(this.exported('luaL_newmetatable'), 'nns') + this.luaL_setmetatable = this.wrapWithStringArguments(this.exported('luaL_setmetatable'), 'nns') + this.luaL_testudata = this.wrapWithStringArguments(this.exported('luaL_testudata'), 'nnns') + this.luaL_checkudata = this.wrapWithStringArguments(this.exported('luaL_checkudata'), 'nnns') + this.luaL_fileresult = this.wrapWithStringArguments(this.exported('luaL_fileresult'), 'nnns') + this.luaL_loadfilex = this.wrapWithStringArguments(this.exported('luaL_loadfilex'), 'nnss') + this.luaL_loadbufferx = this.wrapWithStringArguments(this.exported('luaL_loadbufferx'), 'nnSnSs') + this.luaL_loadstring = this.wrapWithStringArguments(this.exported('luaL_loadstring'), 'nns') + this.luaL_addgsub = this.wrapWithStringArguments(this.exported('luaL_addgsub'), 'nnsss') + this.luaL_gsub = this.wrapWithStringArguments(this.exported('luaL_gsub'), 'snsss') + this.luaL_getsubtable = this.wrapWithStringArguments(this.exported('luaL_getsubtable'), 'nnns') + this.luaL_traceback = this.wrapWithStringArguments(this.exported('luaL_traceback'), 'nnnsn') + this.luaL_requiref = this.wrapWithStringArguments(this.exported('luaL_requiref'), 'nnsnn') + this.luaL_prepbuffsize = this.wrapWithStringArguments(this.exported('luaL_prepbuffsize'), 'snn') + this.luaL_addlstring = this.wrapWithStringArguments(this.exported('luaL_addlstring'), 'nnsn') + this.luaL_addstring = this.wrapWithStringArguments(this.exported('luaL_addstring'), 'nns') + this.luaL_buffinitsize = this.wrapWithStringArguments(this.exported('luaL_buffinitsize'), 'snnn') + this.lua_typename = this.wrapWithStringArguments(this.exported('lua_typename'), 'snn') + this.lua_getglobal = this.wrapWithStringArguments(this.exported('lua_getglobal'), 'nns') + this.lua_getfield = this.wrapWithStringArguments(this.exported('lua_getfield'), 'nnns') + this.lua_setglobal = this.wrapWithStringArguments(this.exported('lua_setglobal'), 'nns') + this.lua_setfield = this.wrapWithStringArguments(this.exported('lua_setfield'), 'nnns') + this.lua_load = this.wrapWithStringArguments(this.exported('lua_load'), 'nnnnss') + this.lua_warning = this.wrapWithStringArguments(this.exported('lua_warning'), 'nnsn') + this.lua_stringtonumber = this.wrapWithStringArguments(this.exported('lua_stringtonumber'), 'nns') + this.lua_getinfo = this.wrapWithStringArguments(this.exported('lua_getinfo'), 'nnsn') + this.lua_getlocal = this.wrapWithStringArguments(this.exported('lua_getlocal'), 'snnn') + this.lua_setlocal = this.wrapWithStringArguments(this.exported('lua_setlocal'), 'snnn') + this.lua_getupvalue = this.wrapWithStringArguments(this.exported('lua_getupvalue'), 'snnn') + this.lua_setupvalue = this.wrapWithStringArguments(this.exported('lua_setupvalue'), 'snnn') + this.lua_pushinteger = this.withIntegerArgument('lua_pushinteger', true) + this.lua_geti = this.withIntegerArgument('lua_geti') + this.lua_rawgeti = this.withIntegerArgument('lua_rawgeti') + this.lua_seti = this.withIntegerArgument('lua_seti') + this.lua_rawseti = this.withIntegerArgument('lua_rawseti') + + this.rawLuaGc = this.exported('lua_gc') + this.rawLuaToLString = this.exported('lua_tolstring') + this.rawLuaLToLString = this.exported('luaL_tolstring') + this.rawLuaPushString = this.exported('lua_pushstring') + + // Numeric bindings are the exports themselves. Named stores avoid enumerating every + // field and assigning bindings through computed property names on each construction. + this.luaL_checkversion_ = this.exported('luaL_checkversion_') + this.luaL_checknumber = this.exported('luaL_checknumber') + this.luaL_optnumber = this.exported('luaL_optnumber') + this.luaL_checkinteger = this.exported('luaL_checkinteger') + this.luaL_optinteger = this.exported('luaL_optinteger') + this.luaL_checktype = this.exported('luaL_checktype') + this.luaL_checkany = this.exported('luaL_checkany') + this.luaL_where = this.exported('luaL_where') + this.luaL_execresult = this.exported('luaL_execresult') + this.luaL_ref = this.exported('luaL_ref') + this.luaL_unref = this.exported('luaL_unref') + this.luaL_newstate = this.exported('luaL_newstate') + this.luaL_len = this.exported('luaL_len') + this.luaL_setfuncs = this.exported('luaL_setfuncs') + this.luaL_openselectedlibs = this.exported('luaL_openselectedlibs') + this.luaL_buffinit = this.exported('luaL_buffinit') + this.luaL_addvalue = this.exported('luaL_addvalue') + this.luaL_pushresult = this.exported('luaL_pushresult') + this.luaL_pushresultsize = this.exported('luaL_pushresultsize') + this.lua_newstate = this.exported('lua_newstate') + this.lua_close = this.exported('lua_close') + this.lua_newthread = this.exported('lua_newthread') + this.lua_closethread = this.exported('lua_closethread') + this.lua_atpanic = this.exported('lua_atpanic') + this.lua_version = this.exported('lua_version') + this.lua_absindex = this.exported('lua_absindex') + this.lua_gettop = this.exported('lua_gettop') + this.lua_settop = this.exported('lua_settop') + this.lua_pushvalue = this.exported('lua_pushvalue') + this.lua_rotate = this.exported('lua_rotate') + this.lua_copy = this.exported('lua_copy') + this.lua_checkstack = this.exported('lua_checkstack') + this.lua_xmove = this.exported('lua_xmove') + this.lua_isnumber = this.exported('lua_isnumber') + this.lua_isstring = this.exported('lua_isstring') + this.lua_iscfunction = this.exported('lua_iscfunction') + this.lua_isinteger = this.exported('lua_isinteger') + this.lua_isuserdata = this.exported('lua_isuserdata') + this.lua_type = this.exported('lua_type') + this.lua_tonumberx = this.exported('lua_tonumberx') + this.lua_tointegerx = this.exported('lua_tointegerx') + this.lua_toboolean = this.exported('lua_toboolean') + this.lua_rawlen = this.exported('lua_rawlen') + this.lua_tocfunction = this.exported('lua_tocfunction') + this.lua_touserdata = this.exported('lua_touserdata') + this.lua_tothread = this.exported('lua_tothread') + this.lua_topointer = this.exported('lua_topointer') + this.lua_arith = this.exported('lua_arith') + this.lua_rawequal = this.exported('lua_rawequal') + this.lua_compare = this.exported('lua_compare') + this.lua_pushnil = this.exported('lua_pushnil') + this.lua_pushnumber = this.exported('lua_pushnumber') + this.lua_pushlstring = this.exported('lua_pushlstring') + this.lua_pushcclosure = this.exported('lua_pushcclosure') + this.lua_pushboolean = this.exported('lua_pushboolean') + this.lua_pushlightuserdata = this.exported('lua_pushlightuserdata') + this.lua_pushthread = this.exported('lua_pushthread') + this.lua_gettable = this.exported('lua_gettable') + this.lua_rawget = this.exported('lua_rawget') + this.lua_rawgetp = this.exported('lua_rawgetp') + this.lua_createtable = this.exported('lua_createtable') + this.lua_newuserdatauv = this.exported('lua_newuserdatauv') + this.lua_getmetatable = this.exported('lua_getmetatable') + this.lua_getiuservalue = this.exported('lua_getiuservalue') + this.lua_settable = this.exported('lua_settable') + this.lua_rawset = this.exported('lua_rawset') + this.lua_rawsetp = this.exported('lua_rawsetp') + this.lua_setmetatable = this.exported('lua_setmetatable') + this.lua_setiuservalue = this.exported('lua_setiuservalue') + this.lua_callk = this.exported('lua_callk') + this.lua_pcallk = this.exported('lua_pcallk') + this.lua_dump = this.exported('lua_dump') + this.lua_yieldk = this.exported('lua_yieldk') + this.lua_resume = this.exported('lua_resume') + this.lua_status = this.exported('lua_status') + this.lua_isyieldable = this.exported('lua_isyieldable') + this.lua_setwarnf = this.exported('lua_setwarnf') + this.lua_error = this.exported('lua_error') + this.lua_next = this.exported('lua_next') + this.lua_concat = this.exported('lua_concat') + this.lua_len = this.exported('lua_len') + this.lua_getallocf = this.exported('lua_getallocf') + this.lua_setallocf = this.exported('lua_setallocf') + this.lua_toclose = this.exported('lua_toclose') + this.lua_closeslot = this.exported('lua_closeslot') + this.lua_getstack = this.exported('lua_getstack') + this.lua_upvalueid = this.exported('lua_upvalueid') + this.lua_upvaluejoin = this.exported('lua_upvaluejoin') + this.lua_sethook = this.exported('lua_sethook') + this.wasmoon_set_await_hook = this.exported('wasmoon_set_await_hook') + this.wasmoon_push_jsfunction = this.exported('wasmoon_push_jsfunction') + this.lua_gethook = this.exported('lua_gethook') + this.lua_gethookmask = this.exported('lua_gethookmask') + this.lua_gethookcount = this.exported('lua_gethookcount') + this.luaopen_base = this.exported('luaopen_base') + this.luaopen_coroutine = this.exported('luaopen_coroutine') + this.luaopen_table = this.exported('luaopen_table') + this.luaopen_io = this.exported('luaopen_io') + this.luaopen_os = this.exported('luaopen_os') + this.luaopen_string = this.exported('luaopen_string') + this.luaopen_utf8 = this.exported('luaopen_utf8') + this.luaopen_math = this.exported('luaopen_math') + this.luaopen_debug = this.exported('luaopen_debug') + this.luaopen_package = this.exported('luaopen_package') this.sizeScratch = module._malloc(PointerSize) this.resultCountScratch = module._malloc(PointerSize) @@ -873,21 +869,23 @@ export default class LuaModule { /** {@link promising}-wrapped `lua_resume`, built on first use and kept. */ public promisingResume(): (L: LuaAddress, from: LuaAddress | null, narg: number, nres: number) => Promise { - this.promisingResumeFunction ??= this.promising(this.lua_resume as (...args: any[]) => LuaReturn) + this.promisingResumeFunction ??= WebAssembly.promising(this.lua_resume) return this.promisingResumeFunction } /** - * Installs the single C await hook every JS function closure suspends through under JSPI. It - * awaits the promise the {@link pendingSuspend} slot was left holding, having first freed this - * run's slice of the shared linear-memory C stack so other runs can use it while parked, then - * restores that slice and marshals the settled value back before returning into Lua. + * Saves the linear-memory stack while awaiting, then restores it in a synchronous C hook. + * Restoring inside the async hook leaves a microtask gap before Wasm resumes: another ready + * run could overwrite the saved frames in that gap. The await returns a reference to its + * restore callback instead, which the C trampoline invokes immediately after resumption. */ private installAwaitHook(): void { - this.awaitHookPointer = this.emscripten.addFunction( + const resumes = new Map number>() + let nextReference = 0 + const awaitHook = this.emscripten.addFunction( // The C signature passes the running coroutine, but it is always the one the await // parked on, which the pendingSuspend marshallers already hold; nothing here needs it. - this.suspending(async (): Promise => { + new WebAssembly.Suspending(async (): Promise => { const suspend = this.pendingSuspend this.pendingSuspend = undefined if (suspend === undefined) { @@ -901,40 +899,48 @@ export default class LuaModule { this.activeRun = undefined this.stackCanSuspend = false const pause = this.scheduleAsync() - // Attach a rejection handler before yielding to the event loop. - const settling = settleOrInterrupt(suspend.promise, suspend.signal, suspend.deadline) + // Observe rejection before taking the fairness pause. + let outcome: SettleOutcome + if (suspend.signal === undefined && suspend.deadline === undefined) { + try { + outcome = { status: 'fulfilled', value: await suspend.promise } + } catch (error) { + outcome = { status: 'rejected', error } + } + } else { + outcome = await settleOrInterrupt(suspend.promise, suspend.signal, suspend.deadline) + } if (pause) { await pause } - const outcome = await settling - // The state was closed while parked: lua_close has freed the stack this would - // resume into, so stay suspended forever rather than resume into freed memory. The - // run itself was already rejected by its close listener. - if (suspend.isClosed()) { - await new Promise(() => undefined) - } - - // Back on this run's stack: put its frames back before touching Lua, and mark the - // stack promising again for any further await this resume reaches. - this.heap.set(savedStack, stackPointer) - this.stackRestore(stackPointer) - this.stackCanSuspend = true - this.activeRun = suspend.run - - if (outcome.interrupted) { - return suspend.onInterrupt(outcome.error) - } - // A fairness pause can outlast the deadline even when the promise settled first. - const interrupt = limitError(suspend.signal, suspend.deadline) - if (interrupt) { - return suspend.onInterrupt(interrupt) - } - return outcome.resolved ? suspend.onResolve(outcome.value) : suspend.onReject(outcome.error) + const reference = (nextReference = (nextReference + 1) | 0) + resumes.set(reference, () => { + // No promise reaction can run between this check and entering Lua again. + if (suspend.run.isClosed()) { + throw new Error('the Lua state is closed') + } + // Back on this run's stack: put its frames back before touching Lua, and mark the + // stack promising again for any further await this resume reaches. + this.heap.set(savedStack, stackPointer) + this.stackRestore(stackPointer) + this.stackCanSuspend = true + this.activeRun = suspend.run + + // A fairness pause can outlast the deadline even after settlement. + const interrupt = outcome.status === 'interrupted' ? undefined : limitError(suspend.signal, suspend.deadline) + return suspend.resume(interrupt ? { status: 'interrupted', error: interrupt } : outcome) + }) + return reference }), 'ii', ) - this.wasmoon_set_await_hook(this.awaitHookPointer) + const resumeHook = this.addFunction((reference: number): number => { + const resume = resumes.get(reference)! + resumes.delete(reference) + return resume() + }, 'ii') + this.wasmoon_set_await_hook(awaitHook, resumeHook) } /** @@ -948,10 +954,7 @@ export default class LuaModule { const mount = resolveMount(virtualPath, hostPath) assertMountFits(this.mounts, mount) - - const fs = this.emscripten.FS - fs.mkdirTree(mount.virtualPath) - fs.mount(fs.filesystems.NODEFS, { root: mount.hostPath }, mount.virtualPath) + mountHostDirectory(this.emscripten.FS, mount) this.mounts.push(mount) } @@ -1018,7 +1021,7 @@ export default class LuaModule { } /** - * The counterpart to {@link writeString}. A short ASCII string is gathered and built in one + * The counterpart to {@link writeString}. A short ASCII string is built with one * `fromCharCode`: Emscripten's own decoder concatenates a character at a time below its * TextDecoder threshold, which cost more than the decode itself for the names and keys that * make up most reads here. A NUL is an ordinary byte, since the length is already known. @@ -1029,17 +1032,44 @@ export default class LuaModule { } const heap = this.heap if (length <= INLINE_DECODE_LIMIT) { - const codes = new Array(length) + // One pass hashes the bytes, stopping at the first that is not ASCII. + let hash = length let index = 0 while (index < length) { const code = heap[pointer + index] if (code > 0x7f) { break } - codes[index++] = code + hash = (Math.imul(hash, 31) + code) | 0 + index++ } if (index === length) { - return String.fromCharCode.apply(null, codes) + let strings = this.decodedStrings + if (!strings) { + this.decodedStringHashes = new Int32Array(DECODED_STRING_CACHE_SIZE) + this.candidateStringHashes = new Int32Array(DECODED_STRING_CACHE_SIZE) + this.decodedStrings = strings = new Array(DECODED_STRING_CACHE_SIZE).fill('') + } + // The bytes are only compared once the whole hash matches, so a miss costs little + // more than the hashing pass. + const slot = hash & (DECODED_STRING_CACHE_SIZE - 1) + if (this.decodedStringHashes[slot] === hash) { + const cached = strings[slot] + if (cached.length === length && isAsciiAt(cached, heap, pointer)) { + return cached + } + } + const text = decodeAscii(heap, pointer, length) + // Kept on a repeated hash. A string seen once -- each value of a table being + // copied, say -- is normally not stored, which spares the store and keeps such a + // stream from pushing out the names read in between. + if (this.candidateStringHashes[slot] === hash) { + strings[slot] = text + this.decodedStringHashes[slot] = hash + } else { + this.candidateStringHashes[slot] = hash + } + return text } // Anything non-ASCII is decoded from the start, the same as the long strings below. } @@ -1109,9 +1139,7 @@ export default class LuaModule { * anywhere instead of only at a coroutine boundary. Needs the VM support and a glue built with * `SUPPORT_LONGJMP=wasm`, without which a suspend trap fires on the `invoke_*` JS trampolines. */ - public readonly jspiSupported: boolean = - typeof (WebAssembly as { Suspending?: unknown }).Suspending === 'function' && - typeof (WebAssembly as { promising?: unknown }).promising === 'function' + public readonly jspiSupported: boolean = typeof WebAssembly.Suspending === 'function' && typeof WebAssembly.promising === 'function' /** The current wasm stack pointer, saved so a suspended run's C frames can be restored. */ public stackSave(): number { @@ -1122,16 +1150,6 @@ export default class LuaModule { this.emscripten.stackRestore(pointer) } - /** Wraps a wasm export so calling it runs Lua on a JSPI stack that can suspend. */ - public promising any>(fn: T): (...args: Parameters) => Promise> { - return (WebAssembly as unknown as { promising: (fn: T) => (...args: Parameters) => Promise> }).promising(fn) - } - - /** Wraps a JS callback so a Lua import can suspend the JSPI stack while it awaits. */ - public suspending(fn: (...args: any[]) => any): any { - return new (WebAssembly as unknown as { Suspending: new (fn: (...args: any[]) => any) => unknown }).Suspending(fn) - } - /** * Puts a JS callback in the indirect function table and returns the pointer Lua calls it * through. Release it with {@link removeFunction}. @@ -1191,6 +1209,29 @@ export default class LuaModule { return pointer ? this.readString(pointer, this.readPointer(lengthPointer)) : '' } + public lua_resetthread(L: LuaAddress): LuaReturn { + return this.lua_closethread(L, null) + } + + /** Deprecated in Lua 5.5; kept as a no-op so the JS API surface stays. */ + public lua_setcstacklimit(_L: LuaAddress, _limit: number): number { + return 0 + } + + public luaL_openlibs(L: LuaAddress): void { + this.luaL_openselectedlibs(L, -1, 0) + } + + /** + * lua_gc is variadic: the wasm32 ABI passes `...` as a pointer to the arguments laid out in + * memory, and every argument lua_gc reads is 32 bit. + */ + public lua_gc(L: LuaAddress, what: number, a: number, b: number): number { + this.writePointer(this.gcArgsScratch, a) + this.writePointer(this.gcArgsScratch + PointerSize, b) + return this.rawLuaGc(L, what, this.gcArgsScratch) + } + public lua_remove(luaState: LuaAddress, index: number): void { this.lua_rotate(luaState, index, -1) this.lua_pop(luaState, 1) @@ -1213,20 +1254,24 @@ export default class LuaModule { } public ref(data: unknown): number { - const existing = this.referenceTracker.get(data) - if (existing) { - existing.refCount++ - return existing.index + const existing = this.referenceIndexes.get(data as WeakKey) + if (existing !== undefined) { + const entry = this.references[existing - 1] as ReferenceEntry + entry.count++ + return existing } - const availableIndex = this.availableReferences.pop() - // +1 so the index is always truthy and not a "nullptr". - const index = availableIndex === undefined ? this.referenceMap.size + 1 : availableIndex - this.referenceMap.set(index, data) - this.referenceTracker.set(data, { - refCount: 1, - index, - }) + // The slot is only taken once the WeakMap has accepted the value: it rejects one that cannot + // be held weakly (a primitive) with a TypeError, which must consume nothing. + const index = this.firstFreeReference || this.references.length + 1 + this.referenceIndexes.set(data as WeakKey, index) + if (index === this.firstFreeReference) { + this.firstFreeReference = -(this.references[index - 1] as number) + } + this.references[index - 1] = { value: data, count: 1 } + if (index > this.highestReference) { + this.highestReference = index + } this.lastRefIndex = index @@ -1234,30 +1279,43 @@ export default class LuaModule { } public unref(index: number): void { - const ref = this.referenceMap.get(index) - if (ref === undefined) { + const entry = this.references[index - 1] + if (typeof entry !== 'object') { return } - const metadata = this.referenceTracker.get(ref) - if (metadata === undefined) { - // Dropping the map entry too, both to release the value and to keep the invariant the - // index allocation above relies on: every index below the high water mark is either - // live in referenceMap or waiting in availableReferences, never neither and never both. - this.referenceMap.delete(index) - this.availableReferences.push(index) + if (--entry.count > 0) { return } - metadata.refCount-- - if (metadata.refCount <= 0) { - this.referenceTracker.delete(ref) - this.referenceMap.delete(index) - this.availableReferences.push(index) + this.referenceIndexes.delete(entry.value as WeakKey) + this.references[index - 1] = 0 - this.firstFreeReference + this.firstFreeReference = index + if (index === this.highestReference) { + while (this.highestReference > 0 && typeof this.references[this.highestReference - 1] === 'number') { + this.highestReference-- + } + if (this.references.length > 256 && this.highestReference < this.references.length / 2) { + this.trimReferences() + } + } + } + + private trimReferences(): void { + // Shrink only by at least half, amortizing the free-list rebuild across released slots. + // Live indices stay put: Lua userdata and other states can still hold them. + this.references.length = this.highestReference + this.firstFreeReference = 0 + for (let index = this.highestReference; index > 0; index--) { + if (typeof this.references[index - 1] === 'number') { + this.references[index - 1] = 0 - this.firstFreeReference + this.firstFreeReference = index + } } } public getRef(index: number): unknown { - return this.referenceMap.get(index) + const entry = this.references[index - 1] + return typeof entry === 'object' ? entry.value : undefined } /** @@ -1284,12 +1342,12 @@ export default class LuaModule { */ public getReferenceBox(L: LuaAddress, index: number, metatableName?: string): unknown { const userDataPointer = metatableName === undefined ? this.lua_touserdata(L, index) : this.luaL_testudata(L, index, metatableName) - return userDataPointer ? this.referenceMap.get(this.readPointer(userDataPointer)) : undefined + return userDataPointer ? this.getRef(this.readPointer(userDataPointer)) : undefined } /** The index {@link ref} already holds for `data`, without taking a count, or undefined. */ public getRefIndex(data: unknown): number | undefined { - return this.referenceTracker.get(data)?.index + return this.referenceIndexes.get(data as WeakKey) } // This is needed for some tests @@ -1298,8 +1356,11 @@ export default class LuaModule { } public printRefs(log = console.log): void { - for (const [key, value] of this.referenceMap.entries()) { - log(key, value) + for (let index = 1; index <= this.references.length; index++) { + const entry = this.references[index - 1] + if (typeof entry === 'object') { + log(index, entry.value) + } } } @@ -1340,20 +1401,12 @@ export default class LuaModule { * double taking twin of the same name in src/native/wasmoon.c, saving the BigInt conversion on * every call. The integer is the last argument of each of these. */ - private withIntegerArgument( - name: string, - returnType: Emscripten.JSType | null, - argTypes: Emscripten.JSType[], - ): (...args: any[]) => any { - const bigintBinding = this.cwrap(name, returnType, argTypes) - const numberBinding = this.cwrap(name.replace('lua_', 'wasmoon_'), returnType, argTypes) - const integerLast = argTypes.length === 2 - if (!integerLast && argTypes.length !== 3) { - throw new Error(`withIntegerArgument only covers arities 2 and 3, not ${argTypes.length}`) - } + private withIntegerArgument(name: string, twoArguments = false): (...args: any[]) => any { + const bigintBinding = this.exported(name) + const numberBinding = this.exported(name.replace('lua_', 'wasmoon_')) return (a: any, b: any, c?: any): any => { - const n = integerLast ? b : c + const n = twoArguments ? b : c if (typeof n === 'bigint') { return bigintBinding(a, b, c) } @@ -1364,56 +1417,44 @@ export default class LuaModule { } } - private cwrap( - name: string, - returnType: Emscripten.JSType | null, - argTypes: Array, - ): (...args: any[]) => any { - const raw = (this.emscripten as unknown as Record any>)[`_${name}`] + /** The wasm export `name`, which for a function that crosses only numbers is the binding itself. */ + private exported(name: string): (...args: any[]) => any { + const raw = (this.emscripten as unknown as Record)[`_${name}`] if (typeof raw !== 'function') { throw new Error(`the wasm module does not export '${name}'`) } - - // Emscripten's own cwrap specializes exactly this case and nothing else, so it is inlined - // here rather than exported: a signature that needs nothing marshalled in either direction - // is just the wasm export. - if (argTypes.every((argType) => argType === 'number') && returnType !== 'string') { - return raw - } - - // Everything else, C string arguments included, goes through one hand rolled wrapper, since - // upstream would fall back to ccall -- which rebuilds its converter table, argument array - // and return handler on every call. That is most of the cost of the small C API functions, - // and these are hot: metatable names, globals, table fields. - return this.wrapWithStringArguments(raw, returnType, argTypes) + return raw as (...args: any[]) => any } /** - * Rest arguments and a spread call would land on every C API call that takes a name, so the - * arguments are named and both the argument positions and the arity are unrolled. Which slots - * hold a C string is fixed when the binding is wrapped, so it is not worked out per call. + * Wraps a C API export that marshals strings, as described by a {@link STRING_BINDINGS} + * signature. Upstream's cwrap would fall back to ccall for these -- which rebuilds its converter + * table, argument array and return handler on every call, most of the cost of the small C API + * functions, and these are hot: metatable names, globals, table fields. Rest arguments and a + * spread call would land on every one of them too, so the arguments are named and both the + * argument positions and the arity are unrolled. Which slots hold a C string is fixed when the + * binding is wrapped, so it is not worked out per call. */ - private wrapWithStringArguments( - raw: (...args: any[]) => any, - returnType: Emscripten.JSType | null, - argTypes: Array, - ): (...args: any[]) => any { + private wrapWithStringArguments(raw: (...args: any[]) => any, signature: string): (...args: any[]) => any { const emscripten = this.emscripten - const arity = argTypes.length + const arity = signature.length - 1 if (arity < 2 || arity > 5) { throw new Error(`wrapWithStringArguments only unrolls arities 2 to 5, not ${arity}`) } - if (argTypes[0] !== 'number') { + if (signature[1] !== 'n') { // Every binding takes the lua_State there, so that slot is not unrolled below. throw new Error('wrapWithStringArguments does not marshal the first argument') } - const returnsString = returnType === 'string' - // `string` is a fixed name worth caching; `string|number` is a chunk of source or another - // one-off, which would fill the cache and push the names that dominate these calls out of it. - const [, s1, s2, s3, s4] = argTypes.map((argType) => - argType === 'string' ? StringArgument.Cached : argType === 'string|number' ? StringArgument.Uncached : StringArgument.None, - ) + const returnsString = signature[0] === 's' + // `s` is a fixed name worth caching; `S` is a chunk of source or another one-off, which + // would fill the cache and push the names that dominate these calls out of it. + const mode = (letter: string | undefined): StringArgument => + letter === 's' ? StringArgument.Cached : letter === 'S' ? StringArgument.Uncached : StringArgument.None + const s1 = mode(signature[2]) + const s2 = mode(signature[3]) + const s3 = mode(signature[4]) + const s4 = mode(signature[5]) return (a?: any, b?: any, c?: any, d?: any, e?: any): any => { // Only an argument that misses the cache needs scratch space, and the fixed names that @@ -1526,6 +1567,69 @@ export default class LuaModule { } } +// Common keys fit in eight bytes. Fixed-arity calls avoid a temporary array on cache misses. +function decodeAscii(heap: Uint8Array, pointer: number, length: number): string { + switch (length) { + case 1: + return String.fromCharCode(heap[pointer]) + case 2: + return String.fromCharCode(heap[pointer], heap[pointer + 1]) + case 3: + return String.fromCharCode(heap[pointer], heap[pointer + 1], heap[pointer + 2]) + case 4: + return String.fromCharCode(heap[pointer], heap[pointer + 1], heap[pointer + 2], heap[pointer + 3]) + case 5: + return String.fromCharCode(heap[pointer], heap[pointer + 1], heap[pointer + 2], heap[pointer + 3], heap[pointer + 4]) + case 6: + return String.fromCharCode( + heap[pointer], + heap[pointer + 1], + heap[pointer + 2], + heap[pointer + 3], + heap[pointer + 4], + heap[pointer + 5], + ) + case 7: + return String.fromCharCode( + heap[pointer], + heap[pointer + 1], + heap[pointer + 2], + heap[pointer + 3], + heap[pointer + 4], + heap[pointer + 5], + heap[pointer + 6], + ) + case 8: + return String.fromCharCode( + heap[pointer], + heap[pointer + 1], + heap[pointer + 2], + heap[pointer + 3], + heap[pointer + 4], + heap[pointer + 5], + heap[pointer + 6], + heap[pointer + 7], + ) + default: { + const codes = new Array(length) + for (let index = 0; index < length; index++) { + codes[index] = heap[pointer + index] + } + return String.fromCharCode.apply(null, codes) + } + } +} + +/** Whether `text`, ASCII of the length being read, is exactly the bytes at `pointer`. */ +function isAsciiAt(text: string, heap: Uint8Array, pointer: number): boolean { + for (let index = 0; index < text.length; index++) { + if (text.charCodeAt(index) !== heap[pointer + index]) { + return false + } + } + return true +} + /** * The callback is asked for more input whenever the C side runs out, and each call satisfies a * single read: once the returned text is consumed the read ends, so the next one asks again diff --git a/src/native/wasmoon.c b/src/native/wasmoon.c index 3261468..a56b386 100644 --- a/src/native/wasmoon.c +++ b/src/native/wasmoon.c @@ -1,5 +1,24 @@ #include "lua.h" +/* Matches the iteration order used to copy a table into a JS array. Empty tables + * remain objects. This walk leaves the stack unchanged and invokes no metamethods. */ +int wasmoon_isarray(lua_State *L, int idx) { + if (lua_rawlen(L, idx) == 0) { + return 0; + } + idx = lua_absindex(L, idx); + lua_Integer count = 0; + lua_pushnil(L); + while (lua_next(L, idx)) { + if (!lua_isinteger(L, -2) || lua_tointeger(L, -2) != ++count) { + lua_pop(L, 2); + return 0; + } + lua_pop(L, 1); + } + return 1; +} + /* * Twins of the lua_Integer entry points that take a double where the originals take a 64 bit * integer. lua_Integer crosses the wasm boundary as a BigInt, so pushing a plain JS number would @@ -34,21 +53,28 @@ void wasmoon_rawseti(lua_State *L, int idx, double n) { * asked to suspend, and the await hook is reached from this wasm frame with no JS frame in between, * which is what the JSPI engine needs to switch the stack. The await hook is a plain never * suspending stub under the fallback engine, where the call hook never returns -1. + * With a resume hook, the await returns a JS reference, consumed synchronously to restore the + * linear-memory stack before Lua can read it. Promise reactions cannot interleave that restore. */ static lua_CFunction await_hook; +static int (*resume_hook)(int); static int wasmoon_jsfunction(lua_State *L) { lua_CFunction call_hook = (lua_CFunction)lua_touserdata(L, lua_upvalueindex(2)); int n = call_hook(L); if (n == -1) { n = await_hook(L); + if (resume_hook) { + n = resume_hook(n); + } } return n; } -void wasmoon_set_await_hook(lua_CFunction hook) { +void wasmoon_set_await_hook(lua_CFunction hook, int (*resume)(int)) { await_hook = hook; + resume_hook = resume; } /* Pops the reference box already on the stack and pushes the closure over it and call_hook. */ diff --git a/src/state.ts b/src/state.ts index efd3d6f..b8225b8 100755 --- a/src/state.ts +++ b/src/state.ts @@ -120,7 +120,6 @@ export default class LuaState extends Thread { private readonly allocatorFunctionPointer: number | undefined private readonly defaultMaxInstructions: number | undefined - private readonly closeListeners: (() => void)[] = [] public constructor(cmodule: LuaModule, options: CreateStateOptions = {}) { const { libs = true, objects = 'proxy', errors = objects === 'copy', inject = false, memory, limits, gc, onWarn } = options @@ -259,17 +258,6 @@ export default class LuaState extends Thread { } } - /** Notified once when this state closes, so an owner can drop its reference. Returns a function that removes the listener. */ - public onClose(listener: () => void): () => void { - this.closeListeners.push(listener) - return () => { - const index = this.closeListeners.indexOf(listener) - if (index >= 0) { - this.closeListeners.splice(index, 1) - } - } - } - /** Closes the state and frees everything it owns. Safe to call more than once. */ public override close(): void { if (this.isClosed()) { @@ -291,11 +279,6 @@ export default class LuaState extends Thread { for (const wrapper of this.typeExtensions) { wrapper.extension.close() } - - // Listeners may unsubscribe themselves while rejecting a parked run. - while (this.closeListeners.length > 0) { - this.closeListeners.pop()!() - } } /** Folds the state wide budget in, so run() does the save and restore in one place. */ @@ -333,8 +316,9 @@ export default class LuaState extends Thread { const { thread, reference } = this.newAnchoredThread() try { // Seeded from the state so a state wide setLimits reaches the async path too, which - // runs on a child thread rather than on the state itself. - thread.setLimits(this.getLimits()) + // runs on a child thread rather than on the state itself. setLimits takes a snapshot, + // so going through getLimits first would copy the same configuration twice. + thread.setLimits(this.limits) loader(thread) return (await thread.run(0, options))[0] } finally { diff --git a/src/thread.ts b/src/thread.ts index 85d13ce..8e5e33a 100755 --- a/src/thread.ts +++ b/src/thread.ts @@ -39,6 +39,13 @@ const LUA_INTEGER_BITS = 64 const NO_RESTORE = (): void => undefined const NO_OPTIONS: Readonly = Object.freeze({}) +/** + * The limits of a thread nothing has been set on, shared so a thread is not an object heavier than + * it has to be: a JS callback made from a coroutine gets a wrapper of its own each time. Frozen, so + * a write to it fails loudly; {@link Thread.setDeadline} is the one path that writes in place, and + * it takes an object of its own first. + */ +const NO_LIMITS: Readonly = Object.freeze({}) export default class Thread { public readonly address: LuaAddress @@ -67,7 +74,7 @@ export default class Thread { private removeCloseListener: (() => void) | undefined private hookFunctionPointer: number | undefined private hookCount = INSTRUCTION_HOOK_COUNT - private limits: LuaThreadLimits = {} + protected limits: LuaThreadLimits = NO_LIMITS private instructionsUsed = 0 /** * The error the debug hook unwound the current run with. See {@link LuaModule.interruptToken} @@ -77,6 +84,7 @@ export default class Thread { private pendingInterrupt: LuaInterruptError | undefined // Only the root owns a map. Callback wrappers and run threads share its records. private awaits: Map | undefined + private closeListeners: (() => void)[] | undefined public getPendingAwait(address = this.address): PendingAwait | undefined { return this.rootThread.awaits?.get(address) @@ -160,10 +168,10 @@ export default class Thread { * swallow it. Used by the JSPI await hook to abandon a run parked past its deadline or on an * aborted signal. Returns what `lua_error` returns, which never actually returns. */ - public interruptWith(error: LuaInterruptError): number { + public interruptWith(error: LuaInterruptError, L = this.address): number { ;(this.module.activeRun ?? this).pendingInterrupt = error - this.module.lua_pushlightuserdata(this.address, this.module.interruptToken) - return this.module.lua_error(this.address) + this.module.lua_pushlightuserdata(L, this.module.interruptToken) + return this.module.lua_error(L) } public resume(argCount = 0): LuaResumeResult { @@ -171,26 +179,24 @@ export default class Thread { // by anything else that got to run in the meantime. this.assertNotClosed() this.pendingInterrupt = undefined + const module = this.module // The shared slot is safe for the same reason the one behind it is: C writes the count as it // returns and it is read straight after, with nothing interleaved. A nested resume has // finished with the slot by the time this one's lua_resume writes to it. - const dataPointer = this.module.resultCountScratch - this.module.writePointer(dataPointer, 0) - const previousRun = this.module.activeRun - const previousCanSuspend = this.module.stackCanSuspend - this.module.activeRun = this - this.module.stackCanSuspend = false - let luaResult: LuaReturn + const dataPointer = module.resultCountScratch + module.writePointer(dataPointer, 0) + const previousRun = module.activeRun + const previousCanSuspend = module.stackCanSuspend + module.activeRun = this + module.stackCanSuspend = false + let result: LuaReturn try { - luaResult = this.module.lua_resume(this.address, null, argCount, dataPointer) + result = module.lua_resume(this.address, null, argCount, dataPointer) } finally { - this.module.activeRun = previousRun - this.module.stackCanSuspend = previousCanSuspend - } - return { - result: luaResult, - resultCount: this.module.readPointer(dataPointer), + module.activeRun = previousRun + module.stackCanSuspend = previousCanSuspend } + return { result, resultCount: module.readPointer(dataPointer) } } public getTop(): number { @@ -212,42 +218,48 @@ export default class Thread { } public async run(argCount = 0, options?: LuaRunOptions): Promise { - this.assertNotClosed() - if (this.running) { - throw new Error('the Lua thread is already running') - } - const restore = this.applyRunOptions(options) - this.running = true + this.startRun() + let restore = NO_RESTORE try { - if (!this.module.useJspi) { - const first = this.resumeYielding(argCount) - if (first.result !== LuaReturn.Yield) { - this.assertOk(first.result) - return this.getStackValues() - } - return await this.watchRun(this.driveYielding(first, options)) + restore = this.applyRunOptions(options) + if (this.module.useJspi) { + return await this.watchRun(this.runJspi(argCount, options)) } - const nresPointer = this.module.emscripten._malloc(PointerSize) - if (!nresPointer) { - throw new Error('failed to allocate the JSPI result count slot') - } - try { - return await this.watchRun(this.runJspi(argCount, nresPointer, options)) - } finally { - this.module.emscripten._free(nresPointer) + const first = this.resume(argCount) + if (first.result !== LuaReturn.Yield) { + this.assertOk(first.result) + return this.getStackValues() } + return await this.watchRun(this.driveYielding(first, options)) } finally { this.finishRun() restore() } } + /** The yielding run loop, continued from an already obtained resume result. */ + public async continueYielding(first: LuaResumeResult, options?: LuaRunOptions): Promise { + this.startRun() + try { + return await this.watchRun(this.driveYielding(first, options)) + } finally { + this.finishRun() + } + } + + private startRun(): void { + this.assertNotClosed() + if (this.running) { + throw new Error('the Lua thread is already running') + } + this.running = true + } + /** One close listener and promise per asynchronous entry, rather than one race per resume. */ private watchRun(pending: Promise): Promise { return new Promise((resolve, reject) => { - const root = this.rootThread as unknown as { onClose(listener: () => void): () => void } this.rejectRun = () => reject(new Error('the Lua state is closed')) - this.removeCloseListener = root.onClose(this.rejectRun) + this.removeCloseListener = this.rootThread.onClose(this.rejectRun) pending.then(resolve, reject) if (this.isClosed()) { this.rejectRun() @@ -263,40 +275,21 @@ export default class Thread { this.clearPendingAwait() } - /** - * Runs `fn` with suspension forced off, so an `:await()` it reaches parks by yielding the - * coroutine rather than suspending the wasm stack. The synchronous `lua_pcallk` entry points - * use this scope; resume inlines it to avoid allocating a closure on the callback hot path. - */ - private withSuspensionDisabled(fn: () => T): T { - const previousCanSuspend = this.module.stackCanSuspend - const previousRun = this.module.activeRun - this.module.stackCanSuspend = false - this.module.activeRun = this - try { - return fn() - } finally { - this.module.stackCanSuspend = previousCanSuspend - this.module.activeRun = previousRun + private dropResults(resumeResult: LuaResumeResult): void { + if (resumeResult.resultCount > 0) { + this.pop(resumeResult.resultCount) } } - /** A resume of the yielding loop, forced onto the yield path rather than a wasm suspension. */ - public resumeYielding(argCount = 0): LuaResumeResult { - return this.resume(argCount) - } - /** * Throws the pending limit error if this parked thread has exceeded its deadline or been * aborted, dropping the yielded values first. The hook only fires while Lua runs, so a parked * thread is checked here instead. */ - private throwIfLimitReached(resumeResult: LuaResumeResult): void { - const error = this.checkYieldLimits() + private dropIfLimitReached(resumeResult: LuaResumeResult): void { + const error = this.limitReached() if (error) { - if (resumeResult.resultCount > 0) { - this.pop(resumeResult.resultCount) - } + this.dropResults(resumeResult) throw error } } @@ -307,59 +300,37 @@ export default class Thread { * when there is no handler. */ private async handleHostYield(resumeResult: LuaResumeResult, options?: LuaRunOptions): Promise { - if (options?.onYield) { - const values = this.getStackValues(this.getTop() - resumeResult.resultCount) - this.pop(resumeResult.resultCount) - const outcome = await settleOrInterrupt(options.onYield(values), this.limits.signal, this.limits.deadline) - this.assertNotClosed() - const interrupt = this.checkYieldLimits() - if (interrupt) { - throw interrupt - } - if (outcome.interrupted) { - throw outcome.error - } - if (!outcome.resolved) { - throw outcome.error - } - return this.pushReturnValues(outcome.value) - } - if (resumeResult.resultCount > 0) { - this.pop(resumeResult.resultCount) + if (!options?.onYield) { + this.dropResults(resumeResult) + return 0 } - return 0 - } - - /** The yielding run loop, continued from an already obtained resume result. */ - public async continueYielding(first: LuaResumeResult, options?: LuaRunOptions): Promise { + const values = this.getStackValues(this.getTop() - resumeResult.resultCount) + this.dropResults(resumeResult) + const outcome = await settleOrInterrupt(options.onYield(values), this.limits.signal, this.limits.deadline) this.assertNotClosed() - if (this.running) { - throw new Error('the Lua thread is already running') - } - this.running = true - try { - return await this.watchRun(this.driveYielding(first, options)) - } finally { - this.finishRun() + this.assertLimits() + if (outcome.status !== 'fulfilled') { + throw outcome.error } + return this.pushReturnValues(outcome.value) } private async driveYielding(first: LuaResumeResult, options?: LuaRunOptions): Promise { - let resumeResult: LuaResumeResult = first + let resumeResult = first while (resumeResult.result === LuaReturn.Yield) { - this.throwIfLimitReached(resumeResult) + this.dropIfLimitReached(resumeResult) const awaited = this.getPendingAwait() let nextArgCount = 0 if (awaited) { - this.pop(resumeResult.resultCount) + this.dropResults(resumeResult) if (this.limits.signal === undefined && this.limits.deadline === undefined) { // The continuation's promise already records rejection, so the usual await // needs no extra promise, reaction, or outcome object. await awaited.promise } else { const outcome = await settleOrInterrupt(awaited.promise, this.limits.signal, this.limits.deadline) - if (outcome.interrupted) { + if (outcome.status === 'interrupted') { throw outcome.error } } @@ -373,12 +344,8 @@ export default class Thread { // The wait itself can outlast the deadline, and resuming would hand Lua another full // slice before the hook noticed. - const waitError = this.checkYieldLimits() - if (waitError) { - throw waitError - } - - resumeResult = this.resumeYielding(nextArgCount) + this.assertLimits() + resumeResult = this.resume(nextArgCount) } this.assertOk(resumeResult.result) @@ -390,32 +357,37 @@ export default class Thread { * a host `coroutine.yield` returns control here, and it is handled the same as in the yielding * engine; the awaits resolve inside the promising resume without the loop seeing them. */ - private async runJspi(argCount: number, nresPointer: number, options?: LuaRunOptions): Promise { + private async runJspi(argCount: number, options?: LuaRunOptions): Promise { const module = this.module - let resumeResult = await this.resumeJspi(argCount, nresPointer) - while (resumeResult.result === LuaReturn.Yield) { - this.throwIfLimitReached(resumeResult) - const nextArgCount = await this.handleHostYield(resumeResult, options) - const pause = module.scheduleAsync() - if (pause) { - await pause + const nresPointer = module.emscripten._malloc(PointerSize) + if (!nresPointer) { + throw new Error('failed to allocate the JSPI result count slot') + } + try { + let resumeResult = await this.resumeJspi(argCount, nresPointer) + while (resumeResult.result === LuaReturn.Yield) { + this.dropIfLimitReached(resumeResult) + const nextArgCount = await this.handleHostYield(resumeResult, options) + const pause = module.scheduleAsync() + if (pause) { + await pause + } + this.assertLimits() + resumeResult = await this.resumeJspi(nextArgCount, nresPointer) } - const interrupt = this.checkYieldLimits() + this.assertOk(resumeResult.result) + // A parked run interrupted by its deadline or signal raises the interrupt into Lua, so a + // pcall in the script could swallow it and let the run finish. As with the debug hook, + // the interrupt still ends the run rather than being catchable from Lua. + const interrupt = this.pendingInterrupt if (interrupt) { + this.pendingInterrupt = undefined throw interrupt } - resumeResult = await this.resumeJspi(nextArgCount, nresPointer) - } - this.assertOk(resumeResult.result) - // A parked run interrupted by its deadline or signal raises the interrupt into Lua, so a - // pcall in the script could swallow it and let the run finish. As with the debug hook, - // the interrupt still ends the run rather than being catchable from Lua. - const interrupt = this.pendingInterrupt - if (interrupt) { - this.pendingInterrupt = undefined - throw interrupt + return this.getStackValues() + } finally { + module.emscripten._free(nresPointer) } - return this.getStackValues() } /** @@ -460,9 +432,10 @@ export default class Thread { * Pushes a JS value onto the stack as Lua results and returns how many: nothing for `undefined`, * `count` for a {@link RawResult}, one per element for a {@link MultiReturn}, else the single * value. Shared by the run loops and the JS function wrapper. + * @param nilOnUndefined Preserve undefined as one Lua nil, as `:await()` requires. */ - public pushReturnValues(value: unknown): number { - if (value === undefined) { + public pushReturnValues(value: unknown, nilOnUndefined = false): number { + if (value === undefined && !nilOnUndefined) { return 0 } if (value instanceof RawResult) { @@ -480,13 +453,10 @@ export default class Thread { public runSync(argCount = 0, options?: LuaRunOptions): MultiReturn { this.assertNotClosed() - this.pendingInterrupt = undefined const restore = this.applyRunOptions(options) try { const base = this.getTop() - argCount - 1 // The 1 is for the function to run - // A synchronous call: an `:await()` reached through it must yield rather than suspend, - // and then fail because a pcalled thread cannot yield. - this.withSuspensionDisabled(() => this.assertOk(this.module.lua_pcallk(this.address, argCount, LUA_MULTRET, 0, 0, null))) + this.pcall(argCount) return this.getStackValues(base) } finally { restore() @@ -499,7 +469,6 @@ export default class Thread { public call(name: string, ...args: any[]): MultiReturn { this.assertNotClosed() - this.pendingInterrupt = undefined const type = this.module.lua_getglobal(this.address, name) if (type !== LuaType.Function) { throw new TypeError(`cannot call '${name}': expected a function, got ${LuaType[type]}`) @@ -510,10 +479,31 @@ export default class Thread { } const base = this.getTop() - args.length - 1 // The 1 is for the function to run - this.withSuspensionDisabled(() => this.assertOk(this.module.lua_pcallk(this.address, args.length, LUA_MULTRET, 0, 0, null))) + this.pcall(args.length) return this.getStackValues(base) } + /** + * A synchronous call: an `:await()` reached through it must yield rather than suspend, and then + * fail because a pcalled thread cannot yield. + */ + private pcall(argCount: number): void { + const module = this.module + this.pendingInterrupt = undefined + const previousRun = module.activeRun + const previousCanSuspend = module.stackCanSuspend + module.activeRun = this + module.stackCanSuspend = false + let result: LuaReturn + try { + result = module.lua_pcallk(this.address, argCount, LUA_MULTRET, 0, 0, null) + } finally { + module.activeRun = previousRun + module.stackCanSuspend = previousCanSuspend + } + this.assertOk(result) + } + public getStackValues(start = 0): MultiReturn { const returns = this.getTop() - start const returnValues = new MultiReturn(returns) @@ -696,17 +686,36 @@ export default class Thread { return } + this.closed = true this.clearPendingAwait() - if (this === this.rootThread) { - this.awaits?.clear() - } if (this.hookFunctionPointer) { this.module.removeFunction(this.hookFunctionPointer) this.hookFunctionPointer = undefined } - - this.closed = true this.rejectRun?.() + + if (this === this.rootThread) { + this.awaits = undefined + const listeners = this.closeListeners + this.closeListeners = undefined + if (listeners) { + for (const listener of listeners) { + listener() + } + } + } + } + + /** Notified once when this state closes, so an owner can drop its reference. Returns a function that removes the listener. */ + public onClose(listener: () => void): () => void { + const root = this.rootThread + ;(root.closeListeners ??= []).push(listener) + return () => { + const index = root.closeListeners?.indexOf(listener) ?? -1 + if (index >= 0) { + root.closeListeners!.splice(index, 1) + } + } } public [Symbol.dispose](): void { @@ -735,6 +744,11 @@ export default class Thread { */ public setDeadline(deadline: number | undefined): void { this.assertNotClosed() + // In place rather than by copy, since a function timeout sets one on every call: only the + // shared empty snapshot is replaced, once, and by the thread's own object. + if (this.limits === NO_LIMITS) { + this.limits = {} + } this.limits.deadline = deadline && deadline > 0 ? deadline : undefined this.applyHook() } @@ -947,11 +961,10 @@ export default class Thread { this.hookFunctionPointer = this.module.addFunction((hookL: LuaAddress): void => { // Reads this.limits rather than closing over them, so a hook allocated for an // earlier configuration still honours the current one. - const error = (this.module.activeRun ?? this).checkHookLimits(hookL) + const run = this.module.activeRun ?? this + const error = run.checkHookLimits(hookL) if (error) { - ;(this.module.activeRun ?? this).pendingInterrupt = error - this.module.lua_pushlightuserdata(hookL, this.module.interruptToken) - this.module.lua_error(hookL) + run.interruptWith(error, hookL) } }, 'vii') } @@ -972,13 +985,20 @@ export default class Thread { this.module.lua_sethook(hookL, this.hookFunctionPointer ?? null, LuaEventMasks.Count, remaining) } } - return this.checkYieldLimits() + return this.limitReached() } - private checkYieldLimits(): LuaInterruptError | undefined { + private limitReached(): LuaInterruptError | undefined { return limitError(this.limits.signal, this.limits.deadline) } + private assertLimits(): void { + const error = this.limitReached() + if (error) { + throw error + } + } + /** * `lua_absindex` is the identity for an index that is already absolute, so the common case * skips the call into wasm. diff --git a/src/type-extension.ts b/src/type-extension.ts index c8a1c6d..72a5629 100644 --- a/src/type-extension.ts +++ b/src/type-extension.ts @@ -15,21 +15,27 @@ export default abstract class LuaTypeExtension { * in Lua. Weak, so the cache never keeps a Lua value alive: an entry goes as soon as Lua drops * the value, before the userdata's `__gc` releases the reference index it is keyed by. Per * extension, because the same value pushed through two extensions must not share a userdata - * carrying the wrong metatable. + * carrying the wrong metatable. Created on first use: table copies never use this cache, + * and states need not allocate caches for reference types they never push. */ - protected readonly pushedValueCacheReference: number + private cacheReference = 0 public constructor(state: LuaState, name: string) { this.state = state this.name = name + } - const module = state.module - module.lua_createtable(state.address, 0, 0) - module.lua_createtable(state.address, 0, 1) - module.lua_pushstring(state.address, 'v') - module.lua_setfield(state.address, -2, '__mode') - module.lua_setmetatable(state.address, -2) - this.pushedValueCacheReference = module.luaL_ref(state.address, LUA_REGISTRYINDEX) + protected get pushedValueCacheReference(): number { + if (!this.cacheReference) { + const { module, address } = this.state + module.lua_createtable(address, 0, 0) + module.lua_createtable(address, 0, 1) + module.lua_pushstring(address, 'v') + module.lua_setfield(address, -2, '__mode') + module.lua_setmetatable(address, -2) + this.cacheReference = module.luaL_ref(address, LUA_REGISTRYINDEX) + } + return this.cacheReference } public isType(_thread: Thread, _index: number, type: LuaType, name?: string): boolean { diff --git a/src/type-extensions/function.ts b/src/type-extensions/function.ts index 1b82b3c..c0fcf53 100644 --- a/src/type-extensions/function.ts +++ b/src/type-extensions/function.ts @@ -1,4 +1,5 @@ import { Decoration, type DecorationOptions } from '../decoration' +import type MultiReturn from '../multireturn' import type LuaState from '../state' import type Thread from '../thread' import TypeExtension from '../type-extension' @@ -215,8 +216,7 @@ class FunctionTypeExtension extends TypeExtension { // A call can leave its thread in an inconsistent state, so each one gets a thread that // is either fresh or has been reset since the last call. const callThread = this.acquireCallThread() - let handedOff = false - let failed = false + let result: unknown try { const internalType = callThread.module.lua_rawgeti(callThread.address, LUA_REGISTRYINDEX, func) if (internalType !== LuaType.Function) { @@ -238,21 +238,18 @@ class FunctionTypeExtension extends TypeExtension { // Run on the coroutine rather than through lua_pcallk, so an `:await()` reached // inside can park by yielding. If it does, the call has become asynchronous and a // promise is returned; the common case runs to completion in this one resume. - const first = callThread.resumeYielding(args.length) + const first = callThread.resume(args.length) if (first.result === LuaReturn.Yield) { - handedOff = true return this.finishAsyncCall(callThread, first) } callThread.assertOk(first.result) - return callThread.getTop() >= 1 ? callThread.getValue(1) : null + result = first.resultCount >= 1 ? callThread.getValue(1) : null } catch (err) { - failed = true + this.releaseCallThread(callThread, true) throw err - } finally { - if (!handedOff) { - this.releaseCallThread(callThread, failed) - } } + this.releaseCallThread(callThread, false) + return result } this.functionRegistry.register(jsFunc, func) @@ -262,16 +259,15 @@ class FunctionTypeExtension extends TypeExtension { /** Drives a callback that parked on an await to completion, resolving to its first result. */ private async finishAsyncCall(callThread: Thread, first: LuaResumeResult): Promise { - let failed = false + let values: MultiReturn try { - const values = await callThread.continueYielding(first) - return values.length >= 1 ? values[0] : null + values = await callThread.continueYielding(first) } catch (err) { - failed = true + this.releaseCallThread(callThread, true) throw err - } finally { - this.releaseCallThread(callThread, failed) } + this.releaseCallThread(callThread, false) + return values.length >= 1 ? values[0] : null } } diff --git a/src/type-extensions/promise.ts b/src/type-extensions/promise.ts index d2f5e53..0ad68ea 100644 --- a/src/type-extensions/promise.ts +++ b/src/type-extensions/promise.ts @@ -1,6 +1,5 @@ import { decorate, type Decoration } from '../decoration' import type LuaState from '../state' -import MultiReturn from '../multireturn' import RawResult from '../raw-result' import type Thread from '../thread' import TypeExtension from '../type-extension' @@ -56,7 +55,7 @@ class PromiseTypeExtension extends TypeExtension> { if (status === 'rejected') { return this.marshalRejected(continuanceThread, value) } - return this.marshalResolved(continuanceThread, value) + return continuanceThread.pushReturnValues(value, true) }, 'iiii') this.defineMetatable({ @@ -164,29 +163,18 @@ class PromiseTypeExtension extends TypeExtension> { promise, signal, deadline, - isClosed: () => run.isClosed(), - onResolve: (value: unknown) => this.marshalResolved(thread, value), - onReject: (error: unknown) => this.marshalRejected(thread, error), - onInterrupt: (error) => thread.interruptWith(error), + resume: (outcome) => { + if (outcome.status === 'interrupted') { + return thread.interruptWith(outcome.error) + } + return outcome.status === 'fulfilled' + ? thread.pushReturnValues(outcome.value, true) + : this.marshalRejected(thread, outcome.error) + }, } return SUSPEND } - /** Pushes a settled promise value as Lua results and returns how many; `undefined` becomes nil. */ - private marshalResolved(thread: Thread, value: unknown): number { - if (value instanceof RawResult) { - return value.count - } - if (value instanceof MultiReturn) { - for (const item of value) { - thread.pushValue(item) - } - return value.length - } - thread.pushValue(value) - return 1 - } - /** Raises a rejected promise as a Lua error on `thread`. */ private marshalRejected(thread: Thread, error: unknown): number { thread.pushValue(error || new Error('promise rejected with no error')) diff --git a/src/type-extensions/table.ts b/src/type-extensions/table.ts index 1ce2d3a..15b0f4b 100644 --- a/src/type-extensions/table.ts +++ b/src/type-extensions/table.ts @@ -22,7 +22,7 @@ class TableTypeExtension extends TypeExtension { let table = seenMap.get(pointer) as TableType | undefined if (!table) { - table = this.isSequential(thread, index) ? [] : {} + table = thread.module.emscripten._wasmoon_isarray(thread.address, index) ? [] : {} // Registered before the values are read, so a table that contains itself resolves to // this same object rather than to a second copy of it. @@ -49,28 +49,22 @@ class TableTypeExtension extends TypeExtension { try { const tableIndex = thread.getTop() + 1 - const createTable = (arrayCount: number, keyCount: number): void => { - thread.module.lua_createtable(thread.address, arrayCount, keyCount) - const ref = thread.module.luaL_ref(thread.address, LUA_REGISTRYINDEX) - seenMap.set(target, ref) - thread.module.lua_rawgeti(thread.address, LUA_REGISTRYINDEX, ref) - } - - if (Array.isArray(target)) { - createTable(target.length, 0) + // A for..in loop would also copy inherited members. + const keys = Array.isArray(target) ? undefined : Object.keys(target) + thread.module.lua_createtable(thread.address, keys ? 0 : (target as any[]).length, keys?.length ?? 0) + thread.module.lua_pushvalue(thread.address, tableIndex) + seenMap.set(target, thread.module.luaL_ref(thread.address, LUA_REGISTRYINDEX)) - for (let i = 0; i < target.length; i++) { - thread.pushValue(target[i], seenMap) + if (!keys) { + const array = target as any[] + for (let i = 0; i < array.length; i++) { + thread.pushValue(array[i], seenMap) // Raw, so the table being built cannot be observed through metamethods. thread.module.lua_rawseti(thread.address, tableIndex, i + 1) } } else { - // A for..in loop would also walk the prototype chain and copy inherited members. - const keys = Object.keys(target) - createTable(0, keys.length) - for (const key of keys) { - thread.pushValue(key, seenMap) + thread.module.lua_pushstring(thread.address, key) thread.pushValue((target as Record)[key], seenMap) thread.module.lua_rawset(thread.address, tableIndex) @@ -88,40 +82,6 @@ class TableTypeExtension extends TypeExtension { return true } - /** - * A table becomes a JS array only when `lua_next` walks exactly the integer keys 1..n in that - * order, which is Lua's own notion of a sequence. The keys this pass looks at are read again - * alongside the values, so it stops as soon as that is ruled out. - */ - private isSequential(thread: Thread, index: number): boolean { - const module = thread.module - - // A border of 0 means t[1] is nil, which settles every table read as an object -- the - // common case -- with one call instead of starting a walk. - if (module.lua_rawlen(thread.address, index) === 0n) { - return false - } - - let count = 0 - module.lua_pushnil(thread.address) - while (module.lua_next(thread.address, index)) { - // Compared as a number rather than through tostring, which would format the key in C - // and decode it in JS for every element. A float key with an integral value is stored - // as an integer, so this is the same test. - if (module.lua_type(thread.address, -2) !== LuaType.Number || module.lua_tonumberx(thread.address, -2, null) !== count + 1) { - // Pop the key and the value, since the walk is being abandoned part way. - thread.pop(2) - return false - } - count++ - // Pop the value. - thread.pop() - } - - // Non-empty, since a border above 0 means some element is present. - return true - } - private readTableValues(thread: Thread, index: number, seenMap: LuaGetCache, table: TableType): void { const isArray = Array.isArray(table) // lua_next leaves each key and value in the same two slots, so the indexes are resolved diff --git a/test/api.test.js b/test/api.test.js index a1eea99..d1f9dad 100644 --- a/test/api.test.js +++ b/test/api.test.js @@ -55,6 +55,90 @@ describe('RawResult', () => { }) }) +describe('Reference bookkeeping', () => { + it('reuses holes below a live high index without exposing free-list links', async () => { + const { module } = await getLua() + const refs = Array.from({ length: 2048 }, () => module.ref({})) + const anchor = Symbol('anchor') + const high = module.ref(anchor) + for (const ref of refs) { + module.unref(ref) + expect(module.getRef(ref)).to.equal(undefined) + } + for (const index of [-1, 0, high + 1]) { + module.unref(index) + expect(module.getRef(index)).to.equal(undefined) + } + const value = {} + const reused = module.ref(value) + expect(refs).to.include(reused) + expect(module.getRef(high)).to.equal(anchor) + expect(module.getRefIndex(anchor)).to.equal(high) + module.unref(high) + expect(module.getRef(reused)).to.equal(value) + module.unref(reused) + }) + + it('preserves live indices and reuses released slots after a large batch', async () => { + const { module } = await getLua() + const values = Array.from({ length: 2048 }, () => ({})) + const refs = values.map((value) => module.ref(value)) + // Keep several low indices alive, including a value held twice, while the tail shrinks. + module.ref(values[16]) + for (let i = 0; i < refs.length; i++) { + if (i !== 0 && i !== 32) module.unref(refs[i]) + } + for (const i of [0, 16, 32]) { + expect(module.getRef(refs[i])).to.equal(values[i]) + expect(module.getRefIndex(values[i])).to.equal(refs[i]) + } + const replacements = values.map(() => ({})) + const next = replacements.map((value) => module.ref(value)) + expect(new Set(next).size).to.equal(next.length) + for (const i of [0, 16, 32]) expect(next).not.to.include(refs[i]) + for (let i = 0; i < next.length; i++) expect(module.getRef(next[i])).to.equal(replacements[i]) + // Descending release also exercises shrinking while the free list has holes. + for (let i = next.length - 1; i >= 0; i--) module.unref(next[i]) + for (const i of [0, 16, 32]) module.unref(refs[i]) + const remaining = [] + module.printRefs((index) => remaining.push(index)) + expect(remaining).to.deep.equal([]) + }) + + it('failed registration leaves live references and reusable slots intact', async () => { + const { module } = await getLua() + const live = {} + const first = module.ref(live) + const reusable = module.ref({}) + module.unref(reusable) + + for (const value of [undefined, null, true, 1, 'not a weak key', Symbol.for('registered')]) { + expect(() => module.ref(value)).to.throw(TypeError) + } + + const references = [] + module.printRefs((index, value) => references.push([index, value])) + expect(references).to.deep.equal([[first, live]]) + expect(module.ref({})).to.equal(reusable) + expect(module.getRef(first)).to.equal(live) + }) + + it('reuses a slot only after its final reference is released', async () => { + const { module } = await getLua() + const value = {} + const reference = module.ref(value) + expect(module.ref(value)).to.equal(reference) + module.unref(reference) + expect(module.getRef(reference)).to.equal(value) + module.unref(reference) + expect(module.getRefIndex(value)).to.equal(undefined) + module.unref(reference) + const reused = module.ref({}) + expect(reused).to.equal(reference) + expect(module.ref({})).not.to.equal(reused) + }) +}) + describe('Decoration options', () => { it('self should bind the receiver and drop it from the arguments', async () => { using state = await getState() diff --git a/test/async.test.js b/test/async.test.js index d9b6317..dbf6844 100644 --- a/test/async.test.js +++ b/test/async.test.js @@ -350,6 +350,43 @@ describe('Async run isolation', () => { await checked }) + it('does not marshal a settled await into a state closed before resumption', async () => { + for (let depth = 0; depth < 12; depth++) { + using state = await getState() + let release + state.set( + 'gate', + new Promise((resolve) => { + release = resolve + }), + ) + const pushNil = state.module.lua_pushnil + let touchedClosedState = false + state.module.lua_pushnil = (address) => { + if (state.isClosed()) { + touchedClosedState = true + throw new Error('attempted to marshal into a closed state') + } + return pushNil(address) + } + try { + const observed = state.doString('gate:await() return 42').then( + (value) => value, + (error) => error.message, + ) + release() + for (let i = 0; i < depth; i++) await Promise.resolve() + state.close() + expect(await observed).to.be.oneOf([42, 'the Lua state is closed']) + // The close listener can reject the run before its native continuation reacts. + for (let i = 0; i < 10; i++) await Promise.resolve() + expect(touchedClosedState, `close at microtask ${depth}`).to.equal(false) + } finally { + state.module.lua_pushnil = pushNil + } + } + }) + it('can interleave many runs with different suspension depths and settlement orders', async () => { using state = await getState() state.set('pause', () => Promise.resolve()) diff --git a/test/browser.test.js b/test/browser.test.js index 74e9766..f19912a 100644 --- a/test/browser.test.js +++ b/test/browser.test.js @@ -358,7 +358,7 @@ async function writeInlinedPage() { ` `, @@ -366,3 +366,21 @@ window.__ready = true return { htmlFile, cleanup: () => rm(tempDir, { recursive: true, force: true }) } } + +/** + * The bundle's own name for one of its exports. Inlined into a page it cannot be imported from, and + * its top level names are minified, so the export clause is the only way to get hold of a binding. + */ +function exportedBinding(bundle, exported) { + const clause = /export\s*\{([^}]*)\}/.exec(bundle) + if (!clause) { + throw new Error('the bundle has no export clause') + } + for (const entry of clause[1].split(',')) { + const [local, name = local] = entry.trim().split(/\s+as\s+/) + if (name === exported) { + return local + } + } + throw new Error(`the bundle does not export ${exported}`) +} diff --git a/test/cli.test.js b/test/cli.test.js index 736ca71..5a045ab 100644 --- a/test/cli.test.js +++ b/test/cli.test.js @@ -7,7 +7,7 @@ import { expect } from 'chai' import pkg from '../package.json' with { type: 'json' } // Absolute, so a test can hand the child a cwd of its own. -const CLI = fileURLToPath(new URL('../bin/wasmoon', import.meta.url)) +const CLI = fileURLToPath(new URL('../dist/cli.js', import.meta.url)) // stdin defaults to closed, matching a piped invocation with nothing to read. Never a TTY here, // so the REPL branch and `-i` stay out of reach. diff --git a/test/limits.test.js b/test/limits.test.js index dd4416d..fb96248 100644 --- a/test/limits.test.js +++ b/test/limits.test.js @@ -71,6 +71,23 @@ describe('Run limits', () => { expect(() => state.doStringSync(busyLoop)).to.throw(LuaInstructionLimitError) }) + it('a parked run keeps its deadline snapshot when the state deadline changes', async () => { + using state = await getState() + let release + state.set( + 'gate', + new Promise((resolve) => { + release = resolve + }), + ) + state.setDeadline(Date.now() + 60_000) + const pending = state.doString('gate:await() return 42') + state.setDeadline(Date.now() - 1) + release() + expect(await pending).to.equal(42) + await expect(state.doString('gate:await()')).to.eventually.be.rejectedWith(LuaTimeoutError) + }) + it('every limit shares one catchable base', async function () { this.timeout(20_000) using state = await getState() diff --git a/test/promises.test.js b/test/promises.test.js index 73e8244..c5c7979 100644 --- a/test/promises.test.js +++ b/test/promises.test.js @@ -1,8 +1,25 @@ import { expect } from 'chai' import { getLua, getState, tick } from './utils.js' import { mock } from 'node:test' +import { LuaMultiReturn } from '../dist/index.js' describe('Promises', () => { + it('keeps an awaited undefined distinct from an empty return list', async () => { + using state = await getState() + state.set('nothing', () => undefined) + state.set('pending', Promise.resolve(undefined)) + state.set('empty', Promise.resolve(LuaMultiReturn.of())) + expect( + await state.doString(` + assert(select('#', nothing()) == 0) + assert(select('#', pending:await()) == 1) + assert(pending:await() == nil) + assert(select('#', empty:await()) == 0) + return true + `), + ).to.equal(true) + }) + it('use promise next should succeed', async () => { using state = await getState() const check = mock.fn() diff --git a/test/state.test.js b/test/state.test.js index 1e9d6db..4b7cdb7 100644 --- a/test/state.test.js +++ b/test/state.test.js @@ -148,6 +148,10 @@ describe('State', () => { hole = { [2] = 'b' }, string_keys = { ['1'] = 'a', ['2'] = 'b' }, mixed = { 'a', 'b', name = 'c' }, + numeric_string = { 'a', 'b', ['3'] = 'c' }, + fractional = { 'a', [1.5] = 'b' }, + zero = { 'a', [0] = 'b' }, + negative = { 'a', [-1] = 'b' }, empty = {}, } `) @@ -158,6 +162,10 @@ describe('State', () => { hole: { 2: 'b' }, string_keys: { 1: 'a', 2: 'b' }, mixed: { 1: 'a', 2: 'b', name: 'c' }, + numeric_string: { 1: 'a', 2: 'b', 3: 'c' }, + fractional: { 1: 'a', 1.5: 'b' }, + zero: { 0: 'b', 1: 'a' }, + negative: { '1': 'a', '-1': 'b' }, empty: {}, }) expect(Array.isArray(value.string_keys)).to.be.false @@ -1023,6 +1031,15 @@ describe('State', () => { expect(await state.doString('return str')).to.be.equal('') }) + it('short ASCII strings should retain every byte on first and repeated reads', async () => { + using state = await getState() + for (let length = 0; length <= 40; length++) { + const value = String.fromCharCode(...Array.from({ length }, (_, index) => (index * 19) % 128)) + state.set('value', value) + for (let read = 0; read < 3; read++) expect(state.get('value')).to.equal(value) + } + }) + it('getStringBytes should expose bytes that are not valid UTF-8', async () => { using state = await getState() await state.doString('value = string.char(0, 255, 128, 65)') diff --git a/utils/build-wasm.sh b/utils/build-wasm.sh index 19255ea..2e02437 100755 --- a/utils/build-wasm.sh +++ b/utils/build-wasm.sh @@ -8,7 +8,7 @@ if [ "$1" == "dev" ]; then extension=(-O0 -g3 -s ASSERTIONS=1 -s SAFE_HEAP=1 -s STACK_OVERFLOW_CHECK=2) else - extension=(-Oz -fno-inline-functions -DLUA_USE_JUMPTABLE=0 -s BINARYEN_EXTRA_PASSES=gufa-optimizing,converge) + extension=(-Oz -DLUA_USE_JUMPTABLE=0 -s BINARYEN_EXTRA_PASSES=gufa-optimizing,converge) fi # Everything that is not about the filesystem, shared by both glues below so they can share one @@ -55,7 +55,15 @@ COMMON=( -s EXPORT_ES6=1 -s MALLOC=emmalloc -s STACK_SIZE=1MB - -s WASM_BIGINT + # The heap starts small and grows on demand (ALLOW_MEMORY_GROWTH below): a fresh state is + # around 20 KB and a hello world never grows, while the 16 MB default was almost entirely + # untouched address space that every heap snapshot and memory profile still counted. + # Growing is cheap here (twelve 20% steps from 2 to 18 MB measure well under a millisecond), + # and the JS side never caches a heap view across a call that can grow it. + -s INITIAL_HEAP=1MB + # The engines package.json promises, so the glue carries no fallbacks for older ones. The browser + # minimums go on the web glue alone below: the host glue is Node only and would warn about them. + -s MIN_NODE_VERSION=240000 -s EXPORTED_FUNCTIONS="[ '_malloc', \ '_free', \ @@ -208,6 +216,7 @@ COMMON=( '_luaopen_package', \ '_luaL_openselectedlibs', \ '_lua_gc', \ + '_wasmoon_isarray', \ '_wasmoon_pushinteger', \ '_wasmoon_geti', \ '_wasmoon_rawgeti', \ @@ -224,6 +233,9 @@ COMMON=( emcc "${COMMON[@]}" \ -lnodefs.js \ -s ENVIRONMENT="web,worker,node" \ + -s MIN_CHROME_VERSION=134 \ + -s MIN_FIREFOX_VERSION=138 \ + -s MIN_SAFARI_VERSION=260000 \ -o ../build/glue.js \ ${LUA_SRC} From bad8112d31c7828c340860eccbe6c96ef796e514 Mon Sep 17 00:00:00 2001 From: ceifa Date: Sun, 15 Nov 2026 19:05:00 -0300 Subject: [PATCH 68/83] jspi only async JSPI is now the only way an :await() suspends; the coroutine yielding engine and the `async` load option are gone. On a platform without JSPI everything else still runs and an :await() raises an error naming the versions that have it. - fix the C stack pointer leak: a run started inside another run's JS callback that outlived it left the idle stack pointer lower for good, and after ~100 of those the instance trapped with "memory access out of bounds" - a Lua function called from JS is always synchronous; state.callAsync(fn, args, options) runs it as a run of its own, and promise next/catch/finally call their Lua reactions through it - a top level coroutine.yield() without an onYield handler gives the event loop a turn every time again - engines: node >= 26; CI runs Node 26 without the JSPI flag or the engine matrix --- .github/workflows/publish.yml | 4 +- .github/workflows/test.yml | 7 +- README.md | 85 +++--- bench/async.js | 115 ++++---- docs/async-redesign/README.md | 12 + docs/performance/async-entries.mjs | 26 +- docs/performance/bindings.mjs | 4 +- docs/performance/multiple-returns.mjs | 40 ++- docs/performance/ready-await-memory.mjs | 2 +- docs/performance/runtime.mjs | 2 +- docs/performance/settled-awaits.mjs | 2 +- package.json | 2 +- src/async.ts | 16 +- src/module.ts | 67 ++--- src/native/wasmoon.c | 13 +- src/state.ts | 29 +- src/thread.ts | 197 ++++---------- src/type-extensions/function.ts | 143 ++++++---- src/type-extensions/promise.ts | 117 ++------ src/types.ts | 8 +- test/async.test.js | 340 ++++++++++++++++++++---- test/browser.test.js | 56 ++-- test/bundling.test.js | 2 +- test/utils.js | 6 +- utils/build-wasm.sh | 2 +- 25 files changed, 708 insertions(+), 589 deletions(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index a9132c6..d5ffe80 100755 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -19,10 +19,10 @@ jobs: version: 6.0.4 actions-cache-folder: emsdk-cache - - name: Use Node.js 24.x + - name: Use Node.js 26.x uses: actions/setup-node@v7 with: - node-version: 24.x + node-version: 26.x - name: Install dependencies run: npm ci diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 9b41299..6d2c7e5 100755 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -10,12 +10,7 @@ jobs: strategy: matrix: - node-version: [24] - async-engine: [yield, jspi] - - env: - WASMOON_ASYNC: ${{ matrix.async-engine }} - NODE_OPTIONS: ${{ matrix.async-engine == 'jspi' && '--experimental-wasm-jspi' || '' }} + node-version: [26] steps: - uses: actions/checkout@v7 diff --git a/README.md b/README.md index aa9f537..f235994 100644 --- a/README.md +++ b/README.md @@ -246,53 +246,70 @@ try { } ``` -### Async engine +### Where `:await()` works -There are two engines: +An `:await()` suspends the WebAssembly stack itself, through +[JSPI](https://github.com/WebAssembly/js-promise-integration). That makes it work anywhere inside an +asynchronous run (`doString`, `doFile`, `thread.run`, `callAsync`): at the top level, inside a +`pcall`, across C-call boundaries such as a `table.sort` comparator or a `string.gsub` callback, and +inside a coroutine that Lua code resumes, whose resumer simply waits. -- **Coroutine yielding** is the fallback when JSPI is unavailable. An `:await()` parks by yielding - the running coroutine, so it works at the top level of a run and anywhere Lua can yield. -- **JSPI** is selected automatically where available. It suspends the WebAssembly stack, allowing awaits across C-call - boundaries such as `table.sort` comparators and `string.gsub` callbacks, and inside - Lua-resumed coroutines. It requires a platform with JSPI support. +It needs a platform with JSPI: Chrome or Edge 137, Firefox 153, Safari 27, Node.js 25, or newer. +Everything else works without it, and an `:await()` raises an error saying so; +`lua.module.jspiSupported` tells which one you are on. -```js -const lua = await LuaRuntime.load() // JSPI when available, yielding otherwise -const accelerated = await LuaRuntime.load({ async: 'jspi' }) // requires JSPI -const portable = await LuaRuntime.load({ async: 'yield' }) // coroutine yielding on every platform -``` +A synchronous call cannot be suspended, so an `:await()` reached through `doStringSync`, +`doFileSync`, `call` or a Lua function called directly from JS is an error. -Both engines use the same run isolation, cancellation, and host-yield contract. Each run owns -its limits and interrupt state, even when several runs or states share a runtime. Repeated awaits -and host yields give the event loop a turn every 256 async steps, so timers can run without paying -for a macrotask on every await. +#### Calling a Lua function that awaits -A run parked on a promise can be interrupted by a `timeout` or an `AbortSignal`, without waiting for -the promise to settle. This also applies while an `onYield` handler is pending; closing the state -rejects its parked runs and callbacks: +A Lua function handed to JS is called synchronously and returns its value directly. To let it +await, call it through `callAsync`, which runs it as a run of its own and returns a `Promise` of its +first result: ```js -await state.doString('sleep(60000):await()', { timeout: 1000 }) // rejects after ~1s +state.set('sleep', (length) => new Promise((resolve) => setTimeout(resolve, length))) +const handler = await state.doString('return function(x) sleep(10):await() return x + 1 end') + +handler(5) // throws: cannot await inside a synchronous call +await state.callAsync(handler, [5]) // 6 +await state.callAsync(handler, [5], { timeout: 1000 }) // takes the same options as a run ``` -#### Awaiting in a JS→Lua callback +The Lua functions given to a promise's `next`, `catch` and `finally` are called this way already, +so they can await: -A Lua function called from JS runs synchronously and returns its value directly. If it `:await()`s, -the call becomes asynchronous and returns a `Promise` instead. These callbacks use coroutine -yielding even when JSPI is enabled, so they cannot await across C-call boundaries: +```lua +local res = sleep(1):next(function() + sleep(10):await() + return 15 +end) +print("res", res:await()) +``` + +#### Interrupting a parked run + +A run parked on a promise is interrupted by its `timeout` or `AbortSignal` without waiting for the +promise to settle, and so is one waiting on an `onYield` handler. Closing the state rejects its +parked runs. ```js -state.set('handler', null) -await state.doString('handler = function(x) return sleep(10):await() + x end') -const handler = state.get('handler') -console.log(await handler(5)) // a promise, because the callback awaited +await state.doString('sleep(60000):await()', { timeout: 1000 }) // rejects after ~1s ``` +The interrupt is raised as an error at the `:await()`, so the scopes it unwinds close their +to-be-closed variables. A `pcall` around the await catches it like any other error, but the run +still rejects with it, and every `:await()` the script reaches afterwards is interrupted at once. + +Each run owns its limits and interrupt state, even when several runs or states share a runtime. A +loop of awaits gives the event loop a turn every 256 of them, so timers can run without paying for a +macrotask on every await. + #### Handling a top-level `coroutine.yield` -A top level `coroutine.yield` that is not an `:await()` is a _host yield_. Pass `onYield` to receive -its values and decide what the resume hands back; its return may be a promise, a `LuaMultiReturn` of -several values, or a single value: +A top level `coroutine.yield` is a _host yield_. Pass `onYield` to receive its values and decide +what the resume hands back; its return may be a promise, a `LuaMultiReturn` of several values, or a +single value: ```js const thread = state.newThread() @@ -306,6 +323,6 @@ const [result] = await thread.run(0, { console.log(result) // "pong" ``` -A promise passed to `coroutine.yield` is a host value, not an internal await. The handler receives -it unchanged. Without a handler, yielded values are discarded and the coroutine resumes without -arguments. +A promise passed to `coroutine.yield` is a host value like any other, which the handler receives +unchanged. Without a handler the yielded values are discarded, the event loop gets a turn, and the +coroutine resumes without arguments. diff --git a/bench/async.js b/bench/async.js index 4cc9ab9..46aa7c6 100644 --- a/bench/async.js +++ b/bench/async.js @@ -7,67 +7,64 @@ import { pathToFileURL } from 'node:url' const { LuaRuntime } = await import(pathToFileURL(resolve(process.argv[2] ?? 'dist/index.js')).href) const median = (values) => values.sort((a, b) => a - b)[Math.floor(values.length / 2)] -for (const engine of ['yield', 'jspi']) { - const runtime = await LuaRuntime.load({ async: engine }) - const state = runtime.createState({ inject: true, memory: { trace: true } }) - state.set('ready', Promise.resolve(1)) - state.set('add', (a, b) => a + b) - state.doStringSync('function addLua(a, b) return a + b end') - const addLua = state.get('addLua') - const workloads = { - '20k settled awaits': () => state.doString('local n = 0 for i=1,20000 do n = n + ready:await() end return n'), - '20k JS to Lua calls': () => { - for (let i = 0; i < 20000; i++) assert.equal(addLua(i, 1), i + 1) - }, - '20k Lua to JS calls': () => state.doStringSync('local n = 0 for i=1,20000 do n = add(n, 1) end return n'), - '1k async entries': async () => { - for (let i = 0; i < 1000; i++) assert.equal(await state.doString('return 1'), 1) - }, - 'CPU loop': () => state.doStringSync('local n = 0 for i=1,1000000 do n = n + i end return n'), - } - const timings = {} - for (const [name, run] of Object.entries(workloads)) { - for (let i = 0; i < 3; i++) await run() - const samples = [] - for (let i = 0; i < 7; i++) { - const start = performance.now() - await run() - samples.push(performance.now() - start) - } - timings[name] = Number(median(samples).toFixed(2)) +const runtime = await LuaRuntime.load() +const state = runtime.createState({ inject: true, memory: { trace: true } }) +state.set('ready', Promise.resolve(1)) +state.set('add', (a, b) => a + b) +state.doStringSync('function addLua(a, b) return a + b end') +const addLua = state.get('addLua') +const workloads = { + '20k settled awaits': () => state.doString('local n = 0 for i=1,20000 do n = n + ready:await() end return n'), + '20k JS to Lua calls': () => { + for (let i = 0; i < 20000; i++) assert.equal(addLua(i, 1), i + 1) + }, + '20k Lua to JS calls': () => state.doStringSync('local n = 0 for i=1,20000 do n = add(n, 1) end return n'), + '1k async entries': async () => { + for (let i = 0; i < 1000; i++) assert.equal(await state.doString('return 1'), 1) + }, + 'CPU loop': () => state.doStringSync('local n = 0 for i=1,1000000 do n = n + i end return n'), +} +const timings = {} +for (const [name, run] of Object.entries(workloads)) { + for (let i = 0; i < 3; i++) await run() + const samples = [] + for (let i = 0; i < 7; i++) { + const start = performance.now() + await run() + samples.push(performance.now() - start) } + timings[name] = Number(median(samples).toFixed(2)) +} - const heapSamples = [] - const bufferSamples = [] - const luaSamples = [] - for (let sample = 0; sample < 5; sample++) { - let release - state.set( - 'gate', - new Promise((resolve) => { - release = resolve - }), - ) - state.gc.collect() - global.gc?.() - const before = process.memoryUsage() - const luaBefore = state.memory.used - const runs = Array.from({ length: 1000 }, () => state.doString('gate:await() return 1')) - await new Promise((resolve) => setTimeout(resolve, 20)) - global.gc?.() - const during = process.memoryUsage() - heapSamples.push(during.heapUsed - before.heapUsed) - bufferSamples.push(during.arrayBuffers - before.arrayBuffers) - luaSamples.push(state.memory.used - luaBefore) - release() - assert.ok((await Promise.all(runs)).every((value) => value === 1)) - } - console.log( - JSON.stringify({ - engine, - medianMs: timings, - parked1000: { jsHeapBytes: median(heapSamples), arrayBufferBytes: median(bufferSamples), luaBytes: median(luaSamples) }, +const heapSamples = [] +const bufferSamples = [] +const luaSamples = [] +for (let sample = 0; sample < 5; sample++) { + let release + state.set( + 'gate', + new Promise((resolve) => { + release = resolve }), ) - state.close() + state.gc.collect() + global.gc?.() + const before = process.memoryUsage() + const luaBefore = state.memory.used + const runs = Array.from({ length: 1000 }, () => state.doString('gate:await() return 1')) + await new Promise((resolve) => setTimeout(resolve, 20)) + global.gc?.() + const during = process.memoryUsage() + heapSamples.push(during.heapUsed - before.heapUsed) + bufferSamples.push(during.arrayBuffers - before.arrayBuffers) + luaSamples.push(state.memory.used - luaBefore) + release() + assert.ok((await Promise.all(runs)).every((value) => value === 1)) } +console.log( + JSON.stringify({ + medianMs: timings, + parked1000: { jsHeapBytes: median(heapSamples), arrayBufferBytes: median(bufferSamples), luaBytes: median(luaSamples) }, + }), +) +state.close() diff --git a/docs/async-redesign/README.md b/docs/async-redesign/README.md index 72043e0..4fc0d00 100644 --- a/docs/async-redesign/README.md +++ b/docs/async-redesign/README.md @@ -3,6 +3,18 @@ Design proposal, 2026-09-05. Everything marked *measured* below was run against the current `dist/` (Node 26.7, V8 14.6) or against a one-off wasm build; the scripts are in `experiments/`. +> **What shipped differs from this proposal.** It is kept for its reasoning and measurements; the +> README section "Where `:await()` works" describes the behaviour. +> +> - JSPI is the only way to await. The coroutine-yielding engine (the YieldSuspender of §5.2) and +> the `async` load option were removed once JSPI reached every target, so an `:await()` on a +> platform without JSPI is an error and everything else still runs there. +> - A Lua function called from JS is always synchronous. The sync-or-promise callable of §5.5 was +> replaced by `state.callAsync(fn, args, options)`, which a promise's `next`, `catch` and +> `finally` use for their Lua reactions. +> - `Promise.async`, `decorate(fn, { call })`, `runtime.engine` and the ephemeron registry of §5.6 +> were not built. + ## TL;DR The current model has one primitive, "yield the Lua coroutine and let a JS loop look at what was diff --git a/docs/performance/async-entries.mjs b/docs/performance/async-entries.mjs index 4e19451..3edb681 100644 --- a/docs/performance/async-entries.mjs +++ b/docs/performance/async-entries.mjs @@ -2,17 +2,15 @@ import assert from 'node:assert/strict' import { performance } from 'node:perf_hooks' const paths = process.argv.slice(2) if (paths.length !== 2) throw new Error('Pass absolute paths to baseline and candidate index.js files') -for (const engine of ['yield', 'jspi']) { - const runtimes = await Promise.all(paths.map(async (path) => (await import(path)).LuaRuntime.load({ async: engine }))) - const states = runtimes.map((lua) => lua.createState()) - const samples = [[], []] - for (let round = 0; round < 30; round++) - for (const variant of round % 2 ? [1, 0] : [0, 1]) { - const start = performance.now() - for (let i = 0; i < 1000; i++) assert.equal(await states[variant].doString('return 1'), 1) - if (round >= 10) samples[variant].push(performance.now() - start) - } - const medians = samples.map((s) => s.sort((a, b) => a - b)[s.length >> 1]) - console.log({ engine, medians, improvement: 1 - medians[1] / medians[0] }) - states.forEach((state) => state.close()) -} +const runtimes = await Promise.all(paths.map(async (path) => (await import(path)).LuaRuntime.load())) +const states = runtimes.map((lua) => lua.createState()) +const samples = [[], []] +for (let round = 0; round < 30; round++) + for (const variant of round % 2 ? [1, 0] : [0, 1]) { + const start = performance.now() + for (let i = 0; i < 1000; i++) assert.equal(await states[variant].doString('return 1'), 1) + if (round >= 10) samples[variant].push(performance.now() - start) + } +const medians = samples.map((s) => s.sort((a, b) => a - b)[s.length >> 1]) +console.log({ medians, improvement: 1 - medians[1] / medians[0] }) +states.forEach((state) => state.close()) diff --git a/docs/performance/bindings.mjs b/docs/performance/bindings.mjs index 44c6ada..5372a2b 100644 --- a/docs/performance/bindings.mjs +++ b/docs/performance/bindings.mjs @@ -3,14 +3,14 @@ import { performance } from 'node:perf_hooks' const paths = process.argv.slice(2) if (paths.length !== 2) throw new Error('Pass absolute paths to baseline and candidate index.js files') const libraries = await Promise.all(paths.map((path) => import(path))) -const runtimes = await Promise.all(libraries.map(({ LuaRuntime }) => LuaRuntime.load({ async: 'yield' }))) +const runtimes = await Promise.all(libraries.map(({ LuaRuntime }) => LuaRuntime.load())) const samples = [[], []] for (let round = 0; round < 30; round++) { for (const variant of round % 2 ? [1, 0] : [0, 1]) { const raw = runtimes[variant].module.emscripten const start = performance.now() for (let i = 0; i < 1000; i++) { - const module = new libraries[variant].LuaModule(raw, undefined, 'memory', [], 'yield') + const module = new libraries[variant].LuaModule(raw) assert.equal(module.lua_gettop, raw._lua_gettop) for (const name of ['sizeScratch', 'resultCountScratch', 'gcArgsScratch', 'interruptToken']) raw._free(module[name]) } diff --git a/docs/performance/multiple-returns.mjs b/docs/performance/multiple-returns.mjs index 3cdc084..a731fd5 100644 --- a/docs/performance/multiple-returns.mjs +++ b/docs/performance/multiple-returns.mjs @@ -3,25 +3,23 @@ import { performance } from 'node:perf_hooks' const paths = process.argv.slice(2) if (paths.length !== 2) throw new Error('Pass absolute paths to baseline and candidate index.js files') const libs = await Promise.all(paths.map((path) => import(path))) -for (const engine of ['yield', 'jspi']) { - const runtimes = await Promise.all(libs.map((lib) => lib.LuaRuntime.load({ async: engine }))) - const states = runtimes.map((lua) => lua.createState({ inject: true })) - for (let i = 0; i < 2; i++) { - const values = libs[i].LuaMultiReturn.of(1, 2, 3) - states[i].set('values', Promise.resolve(values)) - states[i].set('callback', () => values) - } - for (const kind of ['callback', 'await']) { - const code = `local n=0; for i=1,20000 do local a,b,c=${kind === 'callback' ? 'callback()' : 'values:await()'}; n=n+a+b+c end return n` - const samples = [[], []] - for (let round = 0; round < 30; round++) - for (const variant of round % 2 ? [1, 0] : [0, 1]) { - const start = performance.now() - assert.equal(await states[variant].doString(code), 120000) - if (round >= 10) samples[variant].push(performance.now() - start) - } - const medians = samples.map((s) => s.sort((a, b) => a - b)[s.length >> 1]) - console.log({ engine, kind, medians, improvement: 1 - medians[1] / medians[0] }) - } - states.forEach((state) => state.close()) +const runtimes = await Promise.all(libs.map((lib) => lib.LuaRuntime.load())) +const states = runtimes.map((lua) => lua.createState({ inject: true })) +for (let i = 0; i < 2; i++) { + const values = libs[i].LuaMultiReturn.of(1, 2, 3) + states[i].set('values', Promise.resolve(values)) + states[i].set('callback', () => values) } +for (const kind of ['callback', 'await']) { + const code = `local n=0; for i=1,20000 do local a,b,c=${kind === 'callback' ? 'callback()' : 'values:await()'}; n=n+a+b+c end return n` + const samples = [[], []] + for (let round = 0; round < 30; round++) + for (const variant of round % 2 ? [1, 0] : [0, 1]) { + const start = performance.now() + assert.equal(await states[variant].doString(code), 120000) + if (round >= 10) samples[variant].push(performance.now() - start) + } + const medians = samples.map((s) => s.sort((a, b) => a - b)[s.length >> 1]) + console.log({ kind, medians, improvement: 1 - medians[1] / medians[0] }) +} +states.forEach((state) => state.close()) diff --git a/docs/performance/ready-await-memory.mjs b/docs/performance/ready-await-memory.mjs index 3246125..b88b287 100644 --- a/docs/performance/ready-await-memory.mjs +++ b/docs/performance/ready-await-memory.mjs @@ -1,6 +1,6 @@ if (!global.gc || !process.argv[2]) throw new Error('Use --expose-gc and pass an absolute path to index.js') const { LuaRuntime } = await import(process.argv[2]) -const lua = await LuaRuntime.load({ async: 'jspi' }) +const lua = await LuaRuntime.load() const results = [] for (let depth = 0; depth < 7; depth++) { const state = lua.createState() diff --git a/docs/performance/runtime.mjs b/docs/performance/runtime.mjs index f929eab..5ede6eb 100644 --- a/docs/performance/runtime.mjs +++ b/docs/performance/runtime.mjs @@ -9,7 +9,7 @@ for (let round = 0; round < 30; round++) { global.gc() const start = performance.now() for (let i = 0; i < 10; i++) { - const lua = await libraries[variant].LuaRuntime.load({ async: 'yield' }) + const lua = await libraries[variant].LuaRuntime.load() const state = lua.createState() state.doStringSync('return 1+1') state.close() diff --git a/docs/performance/settled-awaits.mjs b/docs/performance/settled-awaits.mjs index 28568c0..9708794 100644 --- a/docs/performance/settled-awaits.mjs +++ b/docs/performance/settled-awaits.mjs @@ -2,7 +2,7 @@ import assert from 'node:assert/strict' import { performance } from 'node:perf_hooks' const paths = process.argv.slice(2) if (paths.length !== 2) throw new Error('Pass absolute paths to baseline and candidate index.js files') -const runtimes = await Promise.all(paths.map(async (path) => (await import(path)).LuaRuntime.load({ async: 'jspi' }))) +const runtimes = await Promise.all(paths.map(async (path) => (await import(path)).LuaRuntime.load())) const states = runtimes.map((lua) => lua.createState()) for (const state of states) state.set('ready', Promise.resolve(1)) const samples = [[], []] diff --git a/package.json b/package.json index 3750d9b..c25620b 100755 --- a/package.json +++ b/package.json @@ -37,7 +37,7 @@ "!dist/*.map" ], "engines": { - "node": ">=24" + "node": ">=26" }, "browserslist": [ "chrome >= 134", diff --git a/src/async.ts b/src/async.ts index 4248d49..f5ea81a 100644 --- a/src/async.ts +++ b/src/async.ts @@ -33,7 +33,7 @@ export const yieldToEventLoop = (): Promise => { /** * The interrupt a deadline or aborted signal calls for, or undefined when neither has fired. The * single source of both the abort-vs-timeout classification and its message, shared by the debug - * hook's limit check and the JSPI await hook. + * hook's limit check and the await hook. */ export function limitError(signal: AbortSignal | undefined, deadline: number | undefined): LuaInterruptError | undefined { if (signal?.aborted) { @@ -51,7 +51,7 @@ export type SettleOutcome = | { status: 'interrupted'; error: LuaInterruptError } /** - * The promise a JSPI `:await()` stashed for the C trampoline's await hook to suspend on, along + * The promise an `:await()` stashed for the C trampoline's await hook to suspend on, along * with how to marshal its settled value back onto the Lua stack. */ export interface PendingSuspend { @@ -64,8 +64,8 @@ export interface PendingSuspend { /** * Awaits `promise`, but reports an interruption instead if `signal` aborts or `deadline` passes - * first. Used by the JSPI await hook, which unwinds the suspended run with a Lua error when it is - * interrupted rather than waiting for the promise it was parked on. + * first. Used for an `onYield` handler, and by the await hook, which unwinds the suspended run with + * a Lua error when it is interrupted rather than waiting for the promise it was parked on. */ export function settleOrInterrupt(promise: unknown, signal: AbortSignal | undefined, deadline: number | undefined): Promise { const settled: Promise = Promise.resolve(promise).then( @@ -127,13 +127,7 @@ export function settleOrInterrupt(promise: unknown, signal: AbortSignal | undefi } /** - * Returned by a JS function through the C trampoline to ask it to suspend the JSPI stack. The + * Returned by a JS function through the C trampoline to ask it to suspend the wasm stack. The * function extension turns it into the -1 the trampoline reads; nothing else produces it. */ export const SUSPEND: unique symbol = Symbol('wasmoon.suspend') - -/** One record per coroutine await, shared by the continuation and its host driver. */ -export interface PendingAwait { - promise: Promise - result: { status: 'fulfilled' | 'rejected'; value: unknown } | undefined -} diff --git a/src/module.ts b/src/module.ts index a39d1eb..0781d5d 100755 --- a/src/module.ts +++ b/src/module.ts @@ -98,12 +98,6 @@ export interface LuaModuleOptions { * that state overrides it. Defaults to `console.warn`. */ onWarn?: LuaWarnHandler | undefined - /** - * Which async engine to run under. `'auto'` (the default) uses JSPI where supported, with - * coroutine yielding as its fallback. `'jspi'` requires JSPI and throws if it is unavailable. - * `'yield'` uses coroutine yielding on every platform. - */ - async?: 'auto' | 'jspi' | 'yield' | undefined } // One-shot conversions, so a single stateless codec pair is shared by every module. Streaming @@ -185,6 +179,9 @@ function buildTrampolineModule(signature: string): WebAssembly.Module { return new WebAssembly.Module(Uint8Array.from([0, 0x61, 0x73, 0x6d, 1, 0, 0, 0, ...typeSection, ...importSection, ...exportSection])) } +/** `lua_resume`, or its `WebAssembly.promising` wrapper where a resume can suspend. */ +type SuspendableResume = (...args: Parameters) => Promise | LuaReturn + /** A {@link LuaModuleOptions.mounts} entry with both sides checked, ready for `FS.mount`. */ interface ResolvedMount { /** Absolute, with no trailing slash and no `.` or `..` in it. */ @@ -358,14 +355,12 @@ export default class LuaModule { throw new Error(`fs: 'host' needs glue-host.js, which the bundle replaced with a stub because it targets the browser`) } - const asyncEngine = opts.async ?? 'auto' const load = async (wasmFile?: string): Promise => { return new LuaModule( await init({ ...(wasmFile === undefined ? {} : { locateFile: () => wasmFile }), preRun, printErr }), opts.onWarn, fs, mounts, - asyncEngine, ) } @@ -416,8 +411,6 @@ export default class LuaModule { public readonly onWarn: LuaWarnHandler | undefined /** Which filesystem this module was loaded with, as {@link LuaModuleOptions.fs}. */ public readonly fs: LuaFileSystem - /** The async engine requested at load, as {@link LuaModuleOptions.async}. */ - public readonly asyncEngine: 'auto' | 'jspi' | 'yield' declare public luaL_checkversion_: (L: LuaAddress, ver: number, sz: number) => void declare public luaL_getmetafield: (L: LuaAddress, obj: number, e: string | null) => LuaType @@ -564,7 +557,7 @@ export default class LuaModule { declare public lua_upvaluejoin: (L: LuaAddress, fidx1: number, n1: number, fidx2: number, n2: number) => void declare public lua_sethook: (L: LuaAddress, func: number | null, mask: number, count: number) => void /** Installs the await hook the {@link wasmoon_push_jsfunction} closures suspend through. */ - declare public wasmoon_set_await_hook: (hook: number, resumeHook?: number) => void + declare public wasmoon_set_await_hook: (hook: number, resumeHook: number) => void /** Pops the reference box on the stack and pushes a JS function closure over it and `callHook`. */ declare public wasmoon_push_jsfunction: (L: LuaAddress, callHook: number) => void declare public lua_gethook: (L: LuaAddress) => number @@ -626,15 +619,15 @@ export default class LuaModule { public readonly interruptToken: number /** * The wasm stack pointer while control is in JS with none of our wasm frames below, captured - * once. A JSPI suspension frees the C stack from the run's frontier up to here, and restores it + * once. A suspension frees the C stack from the run's frontier up to here, and restores it * before resuming. See {@link installAwaitHook}. */ public readonly mainStackPointer: number /** - * Set true only while a JSPI promising resume is the innermost driver on the stack, so an - * `:await()` knows a suspend would reach a promising boundary. A synchronous entry point - * (doStringSync, a JS→Lua callback) sets it false around its own resume, so an await there - * takes the yield path instead of trapping. + * Set true only while a promising resume is the innermost driver on the stack, so an `:await()` + * knows a suspend would reach a promising boundary. A synchronous entry point (doStringSync, a + * JS→Lua callback) sets it false around its own call, so an await there raises an error instead + * of trapping. */ public stackCanSuspend = false /** @@ -655,15 +648,8 @@ export default class LuaModule { return yieldToEventLoop() } - /** - * Whether runs on this module go through JSPI. On unless the platform lacks it or `async` asked - * for the yielding engine, in which case an `:await()` can only park at a coroutine boundary. - */ - public readonly useJspi: boolean - /** `promising(lua_resume)`, built once. */ - private promisingResumeFunction: - | ((L: LuaAddress, from: LuaAddress | null, narg: number, nres: number) => Promise) - | undefined + /** Built on first use by {@link suspendableResume}, then kept for the module's lifetime. */ + private suspendableResumeFunction: SuspendableResume | undefined private stringBuffer = 0 // Initialized together on the first short ASCII read. Numeric-only runtimes need no cache. // Empty slots hold '', which no non-empty read can match, under a hash of 0. @@ -679,19 +665,11 @@ export default class LuaModule { onWarn?: LuaWarnHandler, fs: LuaFileSystem = 'memory', mounts: readonly ResolvedMount[] = [], - asyncEngine: 'auto' | 'jspi' | 'yield' = 'auto', ) { this.emscripten = module this.onWarn = onWarn this.fs = fs this.mounts = [...mounts] - this.asyncEngine = asyncEngine - - if (asyncEngine === 'jspi' && !this.jspiSupported) { - throw new Error( - "async: 'jspi' needs a platform with the JavaScript Promise Integration API and a glue built with SUPPORT_LONGJMP=wasm", - ) - } // The bindings that marshal a string or take a lua_Integer are wrapped over the raw export. // Every other binding crosses only numbers and is the export itself. @@ -861,16 +839,19 @@ export default class LuaModule { // Captured while no Lua is running, so it is the top of the C stack in JS land. this.mainStackPointer = this.stackSave() - this.useJspi = this.jspiSupported && this.asyncEngine !== 'yield' - if (this.useJspi) { + if (this.jspiSupported) { this.installAwaitHook() } } - /** {@link promising}-wrapped `lua_resume`, built on first use and kept. */ - public promisingResume(): (L: LuaAddress, from: LuaAddress | null, narg: number, nres: number) => Promise { - this.promisingResumeFunction ??= WebAssembly.promising(this.lua_resume) - return this.promisingResumeFunction + /** + * The `lua_resume` async runs are driven through: wrapped in `WebAssembly.promising`, so an + * `:await()` inside it can suspend the wasm stack. Where the platform has no JSPI it is the plain + * export, and a run is a resume nothing can suspend. + */ + public suspendableResume(): SuspendableResume { + this.suspendableResumeFunction ??= this.jspiSupported ? WebAssembly.promising(this.lua_resume) : this.lua_resume + return this.suspendableResumeFunction } /** @@ -889,7 +870,7 @@ export default class LuaModule { const suspend = this.pendingSuspend this.pendingSuspend = undefined if (suspend === undefined) { - throw new Error('the JSPI await hook ran with no pending suspend') + throw new Error('the await hook ran with no pending suspend') } const stackPointer = this.stackSave() @@ -1135,9 +1116,9 @@ export default class LuaModule { } /** - * Whether this runtime can run Lua under JSPI, so an `:await()` can suspend the wasm stack - * anywhere instead of only at a coroutine boundary. Needs the VM support and a glue built with - * `SUPPORT_LONGJMP=wasm`, without which a suspend trap fires on the `invoke_*` JS trampolines. + * Whether the platform has JSPI (the WebAssembly JavaScript Promise Integration API), which is + * what lets an `:await()` suspend the wasm stack. Without it everything else works and an + * `:await()` is an error. */ public readonly jspiSupported: boolean = typeof WebAssembly.Suspending === 'function' && typeof WebAssembly.promising === 'function' diff --git a/src/native/wasmoon.c b/src/native/wasmoon.c index a56b386..7105e9b 100644 --- a/src/native/wasmoon.c +++ b/src/native/wasmoon.c @@ -51,10 +51,10 @@ void wasmoon_rawseti(lua_State *L, int idx, double n) { * * The call hook runs the JS function. When it returns -1 the JS side has stashed a promise and * asked to suspend, and the await hook is reached from this wasm frame with no JS frame in between, - * which is what the JSPI engine needs to switch the stack. The await hook is a plain never - * suspending stub under the fallback engine, where the call hook never returns -1. - * With a resume hook, the await returns a JS reference, consumed synchronously to restore the - * linear-memory stack before Lua can read it. Promise reactions cannot interleave that restore. + * which is what JSPI needs to switch the stack. The await hook answers with a JS reference, which + * the resume hook consumes synchronously to restore the linear-memory stack before Lua can read + * it: no promise reaction can interleave that restore. Neither hook is set on a platform without + * JSPI, where the call hook never returns -1. */ static lua_CFunction await_hook; @@ -64,10 +64,7 @@ static int wasmoon_jsfunction(lua_State *L) { lua_CFunction call_hook = (lua_CFunction)lua_touserdata(L, lua_upvalueindex(2)); int n = call_hook(L); if (n == -1) { - n = await_hook(L); - if (resume_hook) { - n = resume_hook(n); - } + n = resume_hook(await_hook(L)); } return n; } diff --git a/src/state.ts b/src/state.ts index b8225b8..1cd57fb 100755 --- a/src/state.ts +++ b/src/state.ts @@ -3,7 +3,7 @@ import type LuaModule from './module' import Thread from './thread' import type LuaTypeExtension from './type-extension' import createErrorType from './type-extensions/error' -import createFunctionType from './type-extensions/function' +import createFunctionType, { type FunctionTypeExtension } from './type-extensions/function' import createNullType from './type-extensions/null' import createPromiseType from './type-extensions/promise' import createProxyType from './type-extensions/proxy' @@ -120,6 +120,7 @@ export default class LuaState extends Thread { private readonly allocatorFunctionPointer: number | undefined private readonly defaultMaxInstructions: number | undefined + private readonly functions: FunctionTypeExtension public constructor(cmodule: LuaModule, options: CreateStateOptions = {}) { const { libs = true, objects = 'proxy', errors = objects === 'copy', inject = false, memory, limits, gc, onWarn } = options @@ -139,7 +140,8 @@ export default class LuaState extends Thread { // Generic handlers - These may be required to be registered for additional types. this.registerTypeExtension(BUILT_IN_PRIORITY.table, createTableType(this)) - this.registerTypeExtension(BUILT_IN_PRIORITY.function, createFunctionType(this, limits?.functionTimeout)) + this.functions = createFunctionType(this, limits?.functionTimeout) + this.registerTypeExtension(BUILT_IN_PRIORITY.function, this.functions) // Contains the :await functionality. this.registerTypeExtension(BUILT_IN_PRIORITY.promise, createPromiseType(this, inject)) @@ -187,21 +189,36 @@ export default class LuaState extends Thread { } /** - * Executes Lua code from a string synchronously. The script cannot yield, so `:await()` and a - * top level `coroutine.yield` are errors here. + * Executes Lua code from a string synchronously. Nothing can suspend a synchronous run, so + * `:await()` and a top level `coroutine.yield` are errors here. */ public doStringSync(script: string, options?: LuaDoOptions): T { return this.callByteCodeSync((thread) => thread.loadString(script, options), this.runOptions(options)) } /** - * Executes Lua code from a file synchronously. The script cannot yield, so `:await()` and a - * top level `coroutine.yield` are errors here. + * Executes Lua code from a file synchronously. Nothing can suspend a synchronous run, so + * `:await()` and a top level `coroutine.yield` are errors here. */ public doFileSync(filename: string, options?: LuaDoOptions): T { return this.callByteCodeSync((thread) => thread.loadFile(filename, options), this.runOptions(options)) } + /** + * Calls a Lua function obtained from this state as a run of its own, which is what lets it + * `:await()`: called directly it runs synchronously, and an await in it is an error. Resolves + * to the function's first result. `limits.functionTimeout` applies unless `options.timeout` + * replaces it. + */ + public callAsync(fn: (...args: any[]) => any, args: unknown[] = [], options?: LuaRunOptions): Promise { + return this.functions.callAsync(fn, args, options) as Promise + } + + /** Whether `value` is a Lua function obtained from this state, the kind {@link callAsync} takes. */ + public isLuaFunction(value: unknown): value is (...args: any[]) => any { + return this.functions.isLuaFunction(value) + } + /** * Registers a type extension for Lua objects. * Higher priority is more important and will be evaluated first. diff --git a/src/thread.ts b/src/thread.ts index 8e5e33a..0db910f 100755 --- a/src/thread.ts +++ b/src/thread.ts @@ -23,7 +23,7 @@ import { PointerSize, } from './types' import { isEmscriptenUnwind } from './utils' -import { limitError, type PendingAwait, settleOrInterrupt } from './async' +import { limitError, settleOrInterrupt, yieldToEventLoop } from './async' import RawResult from './raw-result' export interface OrderedExtension { @@ -82,27 +82,8 @@ export default class Thread { * coroutine, so it writes to the active driver, which also owns its limits and lifecycle. */ private pendingInterrupt: LuaInterruptError | undefined - // Only the root owns a map. Callback wrappers and run threads share its records. - private awaits: Map | undefined private closeListeners: (() => void)[] | undefined - public getPendingAwait(address = this.address): PendingAwait | undefined { - return this.rootThread.awaits?.get(address) - } - - public setPendingAwait(address: LuaAddress, pending: PendingAwait): void { - ;(this.rootThread.awaits ??= new Map()).set(address, pending) - } - - public clearPendingAwait(address = this.address): void { - this.rootThread.awaits?.delete(address) - } - - /** Whether the host run loop owns this coroutine's yielded values. */ - public get isRunning(): boolean { - return this.running - } - /** The driver itself is the run context; no separate context allocation is needed. */ public get runLimits(): Readonly { return this.limits @@ -140,7 +121,6 @@ export default class Thread { public resetThread(): void { this.assertNotClosed() - this.clearPendingAwait() this.assertOk(this.module.lua_resetthread(this.address)) } @@ -163,10 +143,10 @@ export default class Thread { } /** - * Unwinds the currently running coroutine at `L` with a limit error, the same way the debug - * hook does: the token identifies it in {@link assertOk}, so a `pcall` in the script cannot - * swallow it. Used by the JSPI await hook to abandon a run parked past its deadline or on an - * aborted signal. Returns what `lua_error` returns, which never actually returns. + * Raises a limit error in the coroutine running at `L`: the debug hook's way of stopping a run, + * and the await hook's for one parked past its deadline or on an aborted signal. The token is + * what {@link assertOk} recognises the error by. Returns what `lua_error` returns, which never + * actually returns. */ public interruptWith(error: LuaInterruptError, L = this.address): number { ;(this.module.activeRun ?? this).pendingInterrupt = error @@ -175,8 +155,6 @@ export default class Thread { } public resume(argCount = 0): LuaResumeResult { - // Also covers the resumes `run` makes after an await, where the state can have been closed - // by anything else that got to run in the meantime. this.assertNotClosed() this.pendingInterrupt = undefined const module = this.module @@ -222,31 +200,13 @@ export default class Thread { let restore = NO_RESTORE try { restore = this.applyRunOptions(options) - if (this.module.useJspi) { - return await this.watchRun(this.runJspi(argCount, options)) - } - const first = this.resume(argCount) - if (first.result !== LuaReturn.Yield) { - this.assertOk(first.result) - return this.getStackValues() - } - return await this.watchRun(this.driveYielding(first, options)) + return await this.watchRun(this.drive(argCount, options)) } finally { this.finishRun() restore() } } - /** The yielding run loop, continued from an already obtained resume result. */ - public async continueYielding(first: LuaResumeResult, options?: LuaRunOptions): Promise { - this.startRun() - try { - return await this.watchRun(this.driveYielding(first, options)) - } finally { - this.finishRun() - } - } - private startRun(): void { this.assertNotClosed() if (this.running) { @@ -272,7 +232,6 @@ export default class Thread { this.removeCloseListener = undefined this.rejectRun = undefined this.running = false - this.clearPendingAwait() } private dropResults(resumeResult: LuaResumeResult): void { @@ -282,26 +241,14 @@ export default class Thread { } /** - * Throws the pending limit error if this parked thread has exceeded its deadline or been - * aborted, dropping the yielded values first. The hook only fires while Lua runs, so a parked - * thread is checked here instead. - */ - private dropIfLimitReached(resumeResult: LuaResumeResult): void { - const error = this.limitReached() - if (error) { - this.dropResults(resumeResult) - throw error - } - } - - /** - * Handles a host yield -- a top level `coroutine.yield` that is not an await -- by handing its - * values to `onYield` and returning how many values the resume passes back, or dropping them - * when there is no handler. + * Handles a host yield -- a top level `coroutine.yield`, which is never an await -- and returns + * how many values the resume passes back. With a handler those are whatever `onYield` answers + * with; without one the yield is a request for the event loop to take a turn. */ private async handleHostYield(resumeResult: LuaResumeResult, options?: LuaRunOptions): Promise { if (!options?.onYield) { this.dropResults(resumeResult) + await yieldToEventLoop() return 0 } const values = this.getStackValues(this.getTop() - resumeResult.resultCount) @@ -312,73 +259,47 @@ export default class Thread { if (outcome.status !== 'fulfilled') { throw outcome.error } - return this.pushReturnValues(outcome.value) - } - - private async driveYielding(first: LuaResumeResult, options?: LuaRunOptions): Promise { - let resumeResult = first - while (resumeResult.result === LuaReturn.Yield) { - this.dropIfLimitReached(resumeResult) - - const awaited = this.getPendingAwait() - let nextArgCount = 0 - if (awaited) { - this.dropResults(resumeResult) - if (this.limits.signal === undefined && this.limits.deadline === undefined) { - // The continuation's promise already records rejection, so the usual await - // needs no extra promise, reaction, or outcome object. - await awaited.promise - } else { - const outcome = await settleOrInterrupt(awaited.promise, this.limits.signal, this.limits.deadline) - if (outcome.status === 'interrupted') { - throw outcome.error - } - } - } else { - nextArgCount = await this.handleHostYield(resumeResult, options) - } - const pause = this.module.scheduleAsync() - if (pause) { - await pause - } - - // The wait itself can outlast the deadline, and resuming would hand Lua another full - // slice before the hook noticed. - this.assertLimits() - resumeResult = this.resume(nextArgCount) + const resultCount = this.pushReturnValues(outcome.value) + // A handler that answers at once would otherwise never let a timer fire. + const pause = this.module.scheduleAsync() + if (pause) { + await pause } - - this.assertOk(resumeResult.result) - return this.getStackValues() + return resultCount } /** - * Runs under JSPI, so an `:await()` suspends the wasm stack instead of yielding a promise. Only - * a host `coroutine.yield` returns control here, and it is handled the same as in the yielding - * engine; the awaits resolve inside the promising resume without the loop seeing them. + * Drives the coroutine to completion. An `:await()` suspends the wasm stack inside the resume + * and continues there once its promise settles, so the only thing that brings control back here + * before the end is a host yield. */ - private async runJspi(argCount: number, options?: LuaRunOptions): Promise { + private async drive(argCount: number, options?: LuaRunOptions): Promise { const module = this.module + // A slot of its own rather than the shared scratch one: a resume that suspended reports its + // count long after it was entered, by when other runs have been through the shared slot. const nresPointer = module.emscripten._malloc(PointerSize) if (!nresPointer) { - throw new Error('failed to allocate the JSPI result count slot') + throw new Error('failed to allocate the result count slot of an async run') } try { - let resumeResult = await this.resumeJspi(argCount, nresPointer) + let resumeResult = await this.resumeSuspendable(argCount, nresPointer) while (resumeResult.result === LuaReturn.Yield) { - this.dropIfLimitReached(resumeResult) - const nextArgCount = await this.handleHostYield(resumeResult, options) - const pause = module.scheduleAsync() - if (pause) { - await pause + // The hook only fires while Lua runs, so a deadline that passed or a signal that + // aborted while the coroutine was getting here is noticed now. + const limit = this.limitReached() + if (limit) { + this.dropResults(resumeResult) + throw limit } + const nextArgCount = await this.handleHostYield(resumeResult, options) + // The wait itself can outlast the deadline, and resuming would hand Lua another full + // slice before the hook noticed. this.assertLimits() - resumeResult = await this.resumeJspi(nextArgCount, nresPointer) + resumeResult = await this.resumeSuspendable(nextArgCount, nresPointer) } this.assertOk(resumeResult.result) - // A parked run interrupted by its deadline or signal raises the interrupt into Lua, so a - // pcall in the script could swallow it and let the run finish. As with the debug hook, - // the interrupt still ends the run rather than being catchable from Lua. + // A parked run interrupted by its deadline or signal raises the interrupt into Lua, where + // a pcall can catch it and let the script reach its end. The run still reports it. const interrupt = this.pendingInterrupt if (interrupt) { this.pendingInterrupt = undefined @@ -391,32 +312,32 @@ export default class Thread { } /** - * One promising `lua_resume`. The promise it returns resolves only once the resume runs to a - * host yield, a return or an error -- an `:await()` in between suspends and resumes the wasm - * stack invisibly. The stack pointer is put back after the synchronous portion so a sync call - * made while this run is parked reuses the C stack rather than growing past it. + * One `lua_resume` that an `:await()` can suspend. The promise it returns resolves only once the + * resume runs to a host yield, a return or an error; an await in between suspends and resumes + * the wasm stack without this seeing it. */ - private async resumeJspi(argCount: number, nresPointer: number): Promise { + private async resumeSuspendable(argCount: number, nresPointer: number): Promise { this.assertNotClosed() this.pendingInterrupt = undefined const module = this.module const previousCanSuspend = module.stackCanSuspend const previousRun = module.activeRun - module.stackCanSuspend = true + module.stackCanSuspend = module.jspiSupported module.activeRun = this const entryStackPointer = module.stackSave() module.writePointer(nresPointer, 0) + let pending: Promise | LuaReturn try { - let pending: Promise - try { - pending = module.promisingResume()(this.address, null, argCount, nresPointer) - } finally { - // Restore the caller immediately, not when this suspended run eventually settles. - module.activeRun = previousRun - module.stackCanSuspend = previousCanSuspend - module.stackRestore(entryStackPointer) - } - const result: LuaReturn = await pending + pending = module.suspendableResume()(this.address, null, argCount, nresPointer) + } finally { + // Restore the caller immediately, not when this suspended run eventually settles: a call + // made while it is parked then reuses the C stack rather than growing past it. + module.activeRun = previousRun + module.stackCanSuspend = previousCanSuspend + module.stackRestore(entryStackPointer) + } + try { + const result = await pending this.assertNotClosed() return { result, resultCount: module.readPointer(nresPointer) } } finally { @@ -424,14 +345,17 @@ export default class Thread { module.activeRun = undefined module.stackCanSuspend = false } - module.stackRestore(entryStackPointer) + // Everything past the await runs from an empty JS stack, where no C frame is live. Not + // the entry pointer again: the caller it belonged to is long gone, and putting it back + // would leave everything above it unusable for good. + module.stackRestore(module.mainStackPointer) } } /** * Pushes a JS value onto the stack as Lua results and returns how many: nothing for `undefined`, * `count` for a {@link RawResult}, one per element for a {@link MultiReturn}, else the single - * value. Shared by the run loops and the JS function wrapper. + * value. Shared by the run loop and the JS function wrapper. * @param nilOnUndefined Preserve undefined as one Lua nil, as `:await()` requires. */ public pushReturnValues(value: unknown, nilOnUndefined = false): number { @@ -483,10 +407,7 @@ export default class Thread { return this.getStackValues(base) } - /** - * A synchronous call: an `:await()` reached through it must yield rather than suspend, and then - * fail because a pcalled thread cannot yield. - */ + /** A synchronous call, which nothing can suspend: an `:await()` reached through it is an error. */ private pcall(argCount: number): void { const module = this.module this.pendingInterrupt = undefined @@ -687,7 +608,6 @@ export default class Thread { } this.closed = true - this.clearPendingAwait() if (this.hookFunctionPointer) { this.module.removeFunction(this.hookFunctionPointer) this.hookFunctionPointer = undefined @@ -695,7 +615,6 @@ export default class Thread { this.rejectRun?.() if (this === this.rootThread) { - this.awaits = undefined const listeners = this.closeListeners this.closeListeners = undefined if (listeners) { diff --git a/src/type-extensions/function.ts b/src/type-extensions/function.ts index c0fcf53..2f55c40 100644 --- a/src/type-extensions/function.ts +++ b/src/type-extensions/function.ts @@ -1,14 +1,16 @@ import { Decoration, type DecorationOptions } from '../decoration' -import type MultiReturn from '../multireturn' import type LuaState from '../state' import type Thread from '../thread' import TypeExtension from '../type-extension' -import { LUA_REGISTRYINDEX, LuaReturn, type LuaAddress, type LuaResumeResult, LuaType } from '../types' +import { LUA_REGISTRYINDEX, LuaReturn, type LuaAddress, type LuaRunOptions, LuaType } from '../types' import { isEmscriptenUnwind } from '../utils' import { SUSPEND } from '../async' export type FunctionType = (...args: any[]) => Promise | any +/** A Lua function as JS sees it, carrying the registry reference of the function it calls. */ +type LuaFunction = FunctionType & Record + const NO_OPTIONS: DecorationOptions = {} /** Whether the wrapper would behave any differently for these options than for none. */ @@ -16,12 +18,19 @@ function affectsCall(options: DecorationOptions): boolean { return options.self !== undefined || options.receiveThread === true || options.receiveArgsQuantity === true } -class FunctionTypeExtension extends TypeExtension { +export class FunctionTypeExtension extends TypeExtension { private readonly functionRegistry = new FinalizationRegistry((func: number) => { if (!this.state.isClosed()) { this.state.module.luaL_unref(this.state.address, LUA_REGISTRYINDEX, func) } }) + /** + * Keys the registry reference on each Lua function handed to JS, which is how {@link callAsync} + * finds the function to run. A symbol of this state's own, so another state's function does not + * answer to it, and a property rather than a WeakMap entry, which cost more than the rest of + * creating the wrapper put together. + */ + private readonly luaFunction = Symbol('wasmoon.luaFunction') private functionWrapper: number private callbackContext: Thread @@ -33,9 +42,6 @@ class FunctionTypeExtension extends TypeExtension { */ private readonly pooledCallThread: Thread private pooledCallThreadInUse = false - /** Registry reference anchoring each in-flight non-pooled call thread, so async calls that - * overlap can be released in any order rather than only as a stack. */ - private readonly callThreadReferences = new Map() /** Milliseconds a Lua function called from JS may run before being interrupted. */ private readonly functionTimeout: number | undefined @@ -125,11 +131,8 @@ class FunctionTypeExtension extends TypeExtension { private acquireCallThread(): Thread { if (this.pooledCallThreadInUse) { - // Anchored rather than left on the callback context's stack: an async call keeps its - // thread past the return, so overlapping ones must release independently, not as a stack. - const { thread, reference } = this.callbackContext.newAnchoredThread() - this.callThreadReferences.set(thread, reference) - return thread + // Left on the callback context's stack, which synchronous calls unwind in order. + return this.callbackContext.newThread() } this.pooledCallThreadInUse = true @@ -137,19 +140,13 @@ class FunctionTypeExtension extends TypeExtension { } private releaseCallThread(callThread: Thread, failed: boolean): void { - callThread.clearPendingAwait() if (this.state.isClosed()) { - this.callThreadReferences.delete(callThread) this.pooledCallThreadInUse = false return } if (callThread !== this.pooledCallThread) { callThread.close() - const reference = this.callThreadReferences.get(callThread) - if (reference !== undefined) { - this.callThreadReferences.delete(callThread) - this.state.module.luaL_unref(this.callbackContext.address, LUA_REGISTRYINDEX, reference) - } + this.callbackContext.pop() return } @@ -189,8 +186,8 @@ class FunctionTypeExtension extends TypeExtension { const referent: unknown = affectsCall(decoration.options) ? decoration : decoration.target // Pushed through the C trampoline rather than a bare closure, so an `:await()` inside the - // function can suspend the wasm stack under JSPI. The trampoline holds the reference box as - // its first upvalue and the wrapper as its second. + // function can suspend the wasm stack. The trampoline holds the reference box as its first + // upvalue and the wrapper as its second. this.pushReference(thread, referent, (L) => this.state.module.wasmoon_push_jsfunction(L, this.functionWrapper)) return true } @@ -202,29 +199,18 @@ class FunctionTypeExtension extends TypeExtension { const func = thread.module.luaL_ref(thread.address, LUA_REGISTRYINDEX) const jsFunc = (...args: any[]): any => { - // Calling a function would ideally be in the Lua context that's calling it. For example if the JS function - // setInterval were exposed to Lua then the calling thread would be created in that Lua context for executing - // the function call back to Lua through JS. However, if getValue were called in a thread, the thread then - // destroyed, and then this JS func were called it would be calling from a dead context. That means the safest - // thing to do is to have a thread you know will always exist. - if (this.callbackContext.isClosed()) { - // Returning undefined here surfaced the mistake several layers away from the - // call that actually used a dead state. - throw new Error('cannot call a Lua function after its state has been closed') - } + this.assertCallable() // A call can leave its thread in an inconsistent state, so each one gets a thread that // is either fresh or has been reset since the last call. const callThread = this.acquireCallThread() let result: unknown try { + // Spelled out rather than shared with callAsync through a helper: this is the call + // the interop benchmarks measure, and the extra frame showed up in them. const internalType = callThread.module.lua_rawgeti(callThread.address, LUA_REGISTRYINDEX, func) if (internalType !== LuaType.Function) { - const callMetafieldType = callThread.module.luaL_getmetafield(callThread.address, -1, '__call') - callThread.pop() - if (callMetafieldType !== LuaType.Function) { - throw new TypeError(`cannot call a value of type ${LuaType[internalType]}: it has no __call metamethod`) - } + this.assertHasCallMetamethod(callThread, internalType) } for (const arg of args) { @@ -235,15 +221,14 @@ class FunctionTypeExtension extends TypeExtension { callThread.setDeadline(Date.now() + this.functionTimeout) } - // Run on the coroutine rather than through lua_pcallk, so an `:await()` reached - // inside can park by yielding. If it does, the call has become asynchronous and a - // promise is returned; the common case runs to completion in this one resume. - const first = callThread.resume(args.length) - if (first.result === LuaReturn.Yield) { - return this.finishAsyncCall(callThread, first) + // Resumed rather than pcalled, which costs the same and reports a yield as a status + // this can name, instead of as Lua's error about yielding outside a coroutine. + const resumed = callThread.resume(args.length) + if (resumed.result === LuaReturn.Yield) { + throw new Error('cannot yield in a Lua function called synchronously from JS, use callAsync to let it') } - callThread.assertOk(first.result) - result = first.resultCount >= 1 ? callThread.getValue(1) : null + callThread.assertOk(resumed.result) + result = resumed.resultCount >= 1 ? callThread.getValue(1) : null } catch (err) { this.releaseCallThread(callThread, true) throw err @@ -253,24 +238,76 @@ class FunctionTypeExtension extends TypeExtension { } this.functionRegistry.register(jsFunc, func) + ;(jsFunc as LuaFunction)[this.luaFunction] = func return jsFunc } - /** Drives a callback that parked on an await to completion, resolving to its first result. */ - private async finishAsyncCall(callThread: Thread, first: LuaResumeResult): Promise { - let values: MultiReturn + /** Whether `value` is one of this state's Lua functions, as {@link getValue} hands them to JS. */ + public isLuaFunction(value: unknown): value is FunctionType { + return typeof value === 'function' && (value as LuaFunction)[this.luaFunction] !== undefined + } + + /** + * Calls a Lua function as a run of its own instead of synchronously, which is what lets it + * `:await()`. Resolves to its first result, the same value a direct call returns. + */ + public async callAsync(jsFunc: FunctionType, args: unknown[], options?: LuaRunOptions): Promise { + const func = (jsFunc as LuaFunction | undefined)?.[this.luaFunction] + if (func === undefined) { + throw new TypeError('callAsync expects a Lua function obtained from this state') + } + this.assertCallable() + + // A thread of its own rather than the pooled one, which a parked run would keep from every + // synchronous call made in the meantime. + const { thread, reference } = this.callbackContext.newAnchoredThread() try { - values = await callThread.continueYielding(first) - } catch (err) { - this.releaseCallThread(callThread, true) - throw err + const internalType = thread.module.lua_rawgeti(thread.address, LUA_REGISTRYINDEX, func) + if (internalType !== LuaType.Function) { + this.assertHasCallMetamethod(thread, internalType) + } + for (const arg of args) { + thread.pushValue(arg) + } + // The limit a direct call runs under, the function timeout, rather than the ones a + // doString run is seeded with. + const timeout = options?.timeout ?? this.functionTimeout + const values = await thread.run(args.length, timeout === undefined ? options : { ...options, timeout }) + return values.length >= 1 ? values[0] : null + } finally { + // The same teardown as LuaState.callByteCode. Sharing it through a helper costs each + // parked doString a closure its suspended frame keeps alive. + thread.close() + if (!this.state.isClosed()) { + this.state.module.luaL_unref(this.callbackContext.address, LUA_REGISTRYINDEX, reference) + } + } + } + + private assertCallable(): void { + // Calling a function would ideally be in the Lua context that's calling it. For example if the JS function + // setInterval were exposed to Lua then the calling thread would be created in that Lua context for executing + // the function call back to Lua through JS. However, if getValue were called in a thread, the thread then + // destroyed, and then this JS func were called it would be calling from a dead context. That means the safest + // thing to do is to have a thread you know will always exist. + if (this.callbackContext.isClosed()) { + // Returning undefined here surfaced the mistake several layers away from the + // call that actually used a dead state. + throw new Error('cannot call a Lua function after its state has been closed') + } + } + + /** Throws unless the non-function on top of the stack, a value of `type`, can be called anyway. */ + private assertHasCallMetamethod(thread: Thread, type: LuaType): void { + const callMetafieldType = thread.module.luaL_getmetafield(thread.address, -1, '__call') + thread.pop() + if (callMetafieldType !== LuaType.Function) { + throw new TypeError(`cannot call a value of type ${LuaType[type]}: it has no __call metamethod`) } - this.releaseCallThread(callThread, false) - return values.length >= 1 ? values[0] : null } } -export default function createTypeExtension(state: LuaState, functionTimeout?: number): TypeExtension { +export default function createTypeExtension(state: LuaState, functionTimeout?: number): FunctionTypeExtension { return new FunctionTypeExtension(state, functionTimeout) } diff --git a/src/type-extensions/promise.ts b/src/type-extensions/promise.ts index 0ad68ea..0f26629 100644 --- a/src/type-extensions/promise.ts +++ b/src/type-extensions/promise.ts @@ -1,11 +1,9 @@ import { decorate, type Decoration } from '../decoration' import type LuaState from '../state' -import RawResult from '../raw-result' import type Thread from '../thread' import TypeExtension from '../type-extension' -import type { LuaAddress } from '../types' import { isPromise } from '../utils' -import { SUSPEND, type PendingAwait } from '../async' +import { SUSPEND } from '../async' /** * A bare thenable reaches here too, and only `then` is guaranteed on one. Adopting it into a real @@ -19,98 +17,41 @@ const asPromise = (self: unknown): Promise => { return Promise.resolve(self) } -class PromiseTypeExtension extends TypeExtension> { - /** - * One continuation for every await on this state. Building one per await meant compiling and - * instantiating a wasm trampoline each time, and leaked the table slot whenever the coroutine - * was abandoned before the continuation ran -- a run cut short by a deadline, say. - */ - private readonly continuancePointer: number +/** What a promise calls once it settles: a callback from Lua or JS, or nothing. */ +type Reaction = ((...args: any[]) => unknown) | null | undefined +/** Why an `:await()` reached outside a suspendable run fails, for a platform with JSPI and one without. */ +const SYNCHRONOUS_AWAIT = 'cannot await inside a synchronous call: run the script with doString, or the function with callAsync' +const UNSUPPORTED_AWAIT = + 'cannot await: this platform has no WebAssembly JSPI support (it needs Chrome 137, Firefox 153, Safari 27 or Node.js 25, or newer)' + +class PromiseTypeExtension extends TypeExtension> { public constructor(state: LuaState, injectObject: boolean) { super(state, 'js_promise') - this.continuancePointer = state.module.addFunction((continuanceState: LuaAddress): number => { - const pending = state.getPendingAwait(continuanceState) - if (!pending) { - // Nothing sensible is left to resume with, and returning would hand Lua a stack it - // does not expect. - throw new Error('a promise continuation ran without a pending await') - } - - // If this yield has been called from within a coroutine and so manually resumed - // then there may not yet be any results. In that case yield again. The continuation - // runs on the thread that yielded, so this is the address the await parked on. - if (!pending.result) { - // 0 because this is called between resumes so the first one should've popped the - // promise before returning the result. This is true within Lua's coroutine.resume - // too. - return state.module.lua_yieldk(continuanceState, 0, 0, this.continuancePointer) - } - - const { status, value } = pending.result - state.clearPendingAwait(continuanceState) - const continuanceThread = state.stateToThread(continuanceState) - - if (status === 'rejected') { - return this.marshalRejected(continuanceThread, value) - } - return continuanceThread.pushReturnValues(value, true) - }, 'iiii') + // A Lua function handed to a promise runs as a run of its own, so that it can await like the + // async function it stands in for. Anything else is passed through as it is. + const reaction = (callback: Reaction): Reaction => + state.isLuaFunction(callback) ? (...args: unknown[]) => state.callAsync(callback, args) : callback this.defineMetatable({ // A plain object, which the table extension (registered before this one) copies into a // Lua table of methods. __index: { - next: (self: unknown, ...args: Parameters['then']>) => asPromise(self).then(...args), - catch: (self: unknown, ...args: Parameters['catch']>) => asPromise(self).catch(...args), - finally: (self: unknown, ...args: Parameters['finally']>) => asPromise(self).finally(...args), + next: (self: unknown, onFulfilled: Reaction, onRejected: Reaction) => + asPromise(self).then(reaction(onFulfilled), reaction(onRejected)), + catch: (self: unknown, onRejected: Reaction) => asPromise(self).catch(reaction(onRejected)), + finally: (self: unknown, onFinally: Reaction) => asPromise(self).finally(reaction(onFinally)), await: decorate( (functionThread: Thread, rawSelf: unknown) => { const self = asPromise(rawSelf) - const module = state.module - - // Under JSPI an await can suspend the wasm stack from anywhere, including a - // C-call boundary a yield could not cross, so long as the run reached here - // through a promising resume rather than a synchronous entry point (which - // `stackCanSuspend` is exactly true for). - if (module.useJspi && module.stackCanSuspend) { - return this.suspend(functionThread, self) + // Only a promising resume leaves a boundary the wasm stack can suspend to. A + // synchronous entry point (doStringSync, a JS→Lua callback) has JS frames in + // the way, and suspending through those traps. + if (!state.module.stackCanSuspend) { + throw new Error(state.module.jspiSupported ? SYNCHRONOUS_AWAIT : UNSUPPORTED_AWAIT) } - - // Otherwise it can only park by yielding the coroutine, which a thread - // entered through lua_pcall (doStringSync, a JS→Lua callback) cannot do. - if (!module.lua_isyieldable(functionThread.address)) { - throw new Error( - module.useJspi - ? 'cannot await here: a synchronous call is on the stack, use doString instead of doStringSync' - : 'cannot await across a C-call boundary without JSPI; run this through doString', - ) - } - - const pending: PendingAwait = { - result: undefined, - promise: self.then( - (value) => { - pending.result = { status: 'fulfilled', value } - return value - }, - (value) => { - pending.result = { status: 'rejected', value } - }, - ), - } - state.setPendingAwait(functionThread.address, pending) - - // Host-driven awaits are registered out of band: no promise userdata or - // Lua stack value is needed. A manually resumed coroutine still receives - // its promise, preserving the low-level coroutine.resume contract. - let resultCount = 0 - if (!functionThread.isRunning) { - functionThread.pushValue(pending.promise) - resultCount = 1 - } - return new RawResult(module.lua_yieldk(functionThread.address, resultCount, 0, this.continuancePointer)) + return this.suspend(functionThread, self) }, { receiveThread: true }, ), @@ -134,11 +75,6 @@ class PromiseTypeExtension extends TypeExtension> { } } - public override close(): void { - super.close() - this.state.module.removeFunction(this.continuancePointer) - } - public pushValue(thread: Thread, decoration: Decoration): boolean { if (!isPromise(decoration.target)) { return false @@ -147,10 +83,9 @@ class PromiseTypeExtension extends TypeExtension> { } /** - * The JSPI await. It hands the promise and how to marshal its result to the module's await - * hook, then returns the sentinel that makes the C trampoline reach that hook and suspend the - * wasm stack. The stack unwinds to the promising resume driving the run and resumes there once - * the promise settles, so nothing here yields the Lua coroutine. + * Hands the promise and how to marshal its result to the module's await hook, then returns the + * sentinel that makes the C trampoline reach that hook and suspend the wasm stack. The stack + * unwinds to the promising resume driving the run and resumes there once the promise settles. */ private suspend(thread: Thread, promise: Promise): typeof SUSPEND { // Captured now so a deadline or abort observed while parked interrupts the run rather than diff --git a/src/types.ts b/src/types.ts index f1222ba..eb05fa6 100755 --- a/src/types.ts +++ b/src/types.ts @@ -127,15 +127,15 @@ export interface LuaRunOptions { * * Interrupts parked awaits and onYield handlers without waiting for their promises to settle. * A signal cannot fire while the event loop is blocked, so a timer cannot abort a tight Lua - * loop without async steps; use `timeout` or `maxInstructions` for those. Repeated awaits and - * host yields periodically give timers a turn. + * loop without async steps; use `timeout` or `maxInstructions` for those. Repeated awaits + * periodically give timers a turn, and a top level `coroutine.yield` without a handler always does. */ signal?: AbortSignal | undefined /** - * Called with the values of a top level `coroutine.yield` that is not an `:await()`. Its return + * Called with the values of a top level `coroutine.yield`. Its return * becomes the result of that yield when the run resumes; a returned promise is awaited first, a * `LuaMultiReturn` becomes several values, and `undefined` resumes with none. Without a handler - * such a yield resumes with nothing. Both engines periodically yield to the event loop. + * such a yield gives the event loop a turn and resumes with nothing. */ onYield?: ((values: MultiReturn) => unknown | Promise) | undefined } diff --git a/test/async.test.js b/test/async.test.js index dbf6844..76f5090 100644 --- a/test/async.test.js +++ b/test/async.test.js @@ -7,7 +7,11 @@ import { expect } from 'chai' import { LuaRuntime, LuaTimeoutError, LuaAbortError, LuaMultiReturn } from '../dist/index.js' import { getState } from './utils.js' -describe('Async engine', () => { +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) +/** Settles with `value` a moment later. */ +const later = (value) => new Promise((resolve) => setTimeout(() => resolve(value), 1)) + +describe('Async runs', () => { it('a top level coroutine.yield hands its values to onYield and resumes with its return', async () => { using state = await getState() const thread = state.newThread() @@ -42,7 +46,7 @@ describe('Async engine', () => { it('a timeout interrupts a run parked on a promise promptly', async () => { using state = await getState() - state.set('sleep', (ms) => new Promise((resolve) => setTimeout(resolve, ms))) + state.set('sleep', sleep) const started = Date.now() await expect(state.doString('sleep(1000):await() return 1', { timeout: 10 })).to.eventually.be.rejectedWith(LuaTimeoutError) @@ -51,7 +55,7 @@ describe('Async engine', () => { it('an abort signal interrupts a parked run promptly', async () => { using state = await getState() - state.set('sleep', (ms) => new Promise((resolve) => setTimeout(resolve, ms))) + state.set('sleep', sleep) const controller = new AbortController() setTimeout(() => controller.abort(), 10) @@ -62,28 +66,54 @@ describe('Async engine', () => { expect(Date.now() - started).to.be.below(500) }) - it('interrupting a parked await is catchable by pcall on a fresh run', async () => { + it('a pcall around an interrupted await does not keep the run from reporting the interrupt', async () => { using state = await getState() - state.set('sleep', (ms) => new Promise((resolve) => setTimeout(resolve, ms))) + state.set('sleep', sleep) - // The interrupt unwinds like a limit error: a pcall inside the script cannot swallow it. + // The interrupt is raised into Lua, so the pcall sees it; the run reports it all the same. await expect( state.doString('local ok = pcall(function() sleep(1000):await() end) return ok', { timeout: 10 }), ).to.eventually.be.rejectedWith(LuaTimeoutError) }) - describe('across a C-call boundary', () => { - const itJspi = (name, fn) => { - it(name, async function () { - using state = await getState() - if (!state.module.useJspi) { - this.skip() - } - await fn(state) - }) - } + it('an await reached after the interrupt is interrupted at once', async () => { + using state = await getState() + state.set('sleep', sleep) + + const started = Date.now() + await expect( + state.doString('for i = 1, 5 do pcall(function() sleep(1000):await() end) end', { timeout: 10 }), + ).to.eventually.be.rejectedWith(LuaTimeoutError) + expect(Date.now() - started, 'none of the later sleeps was waited for').to.be.below(500) + }) + + it('an interrupted await still closes the to-be-closed variables of the scopes it unwinds', async () => { + using state = await getState() + state.set('sleep', sleep) + let closed = false + state.set('markClosed', () => { + closed = true + }) + + // Why the interrupt is an error raised into Lua rather than the run being dropped where it + // stands: cleanup that the script registered gets to run. + await expect( + state.doString( + ` + pcall(function() + local guard = setmetatable({}, { __close = function() markClosed() end }) + sleep(1000):await() + end) + `, + { timeout: 10 }, + ), + ).to.eventually.be.rejectedWith(LuaTimeoutError) + expect(closed).to.be.equal(true) + }) - itJspi('awaits inside a table.sort comparator', async (state) => { + describe('across a C-call boundary', () => { + it('awaits inside a table.sort comparator', async () => { + using state = await getState() state.set('sleep', (ms) => new Promise((resolve) => setTimeout(() => resolve(ms), ms))) const result = await state.doString(` local t = {3, 1, 2} @@ -93,13 +123,15 @@ describe('Async engine', () => { expect(result).to.be.equal('1,2,3') }) - itJspi('awaits inside a gsub callback', async (state) => { + it('awaits inside a gsub callback', async () => { + using state = await getState() state.set('sleep', (ms) => new Promise((resolve) => setTimeout(() => resolve(ms), ms))) const result = await state.doString(`return (("abc"):gsub(".", function(c) sleep(1):await() return c:upper() end))`) expect(result).to.be.equal('ABC') }) - itJspi('awaits inside a promise:next callback', async (state) => { + it('awaits inside a promise:next callback', async () => { + using state = await getState() state.set('sleep', (ms) => new Promise((resolve) => setTimeout(() => resolve(ms), ms))) const result = await state.doString(` return sleep(1):next(function() sleep(1):await() return 15 end):await() @@ -107,7 +139,8 @@ describe('Async engine', () => { expect(result).to.be.equal(15) }) - itJspi('awaits inside a coroutine nothing drives from the host', async (state) => { + it('awaits inside a coroutine nothing drives from the host', async () => { + using state = await getState() state.set('sleep', (ms) => new Promise((resolve) => setTimeout(() => resolve(ms), ms))) const result = await state.doString(` local co = coroutine.wrap(function() return sleep(1):await() + 1 end) @@ -117,12 +150,44 @@ describe('Async engine', () => { }) }) - it('a state closed while a JSPI run is parked rejects rather than resuming into freed memory', async () => { + it('awaits inside a generator do not surface as one of its values', async () => { using state = await getState() - if (!state.module.useJspi) { - return + state.set('later', later) + const result = await state.doString(` + local values = coroutine.wrap(function() + for i = 1, 3 do coroutine.yield(later(i * 10):await()) end + end) + return table.concat({ values(), values(), values() }, ",") + `) + expect(result).to.be.equal('10,20,30') + }) + + it('gives the C stack back when a run started inside another run outlives it', async () => { + using state = await getState() + const { module } = state + state.set('sleep', sleep) + const started = [] + state.set('start', () => { + started.push(state.doString('sleep(1):await() return 1')) + }) + + for (let round = 0; round < 3; round++) { + // Several C frames deep when the inner run starts, so its entry is far from the top. + await state.doString(` + local function deep(n) + if n == 0 then start() return end + pcall(string.gsub, "x", "x", function() deep(n - 1) end) + end + deep(10) + `) + expect(await Promise.all(started.splice(0))).to.be.eql([1]) + expect(module.stackSave(), `round ${round}`).to.be.equal(module.mainStackPointer) } - state.set('sleep', (ms) => new Promise((resolve) => setTimeout(resolve, ms))) + }) + + it('a state closed while a run is parked rejects rather than resuming into freed memory', async () => { + using state = await getState() + state.set('sleep', sleep) const running = state.doString('sleep(20):await() return 1') state.close() @@ -130,13 +195,160 @@ describe('Async engine', () => { }) }) -// Run with WASMOON_ASYNC=yield and WASMOON_ASYNC=jspi; the same contract must hold under both. -describe('Async run isolation', () => { - it('preserves automatic engine selection', async () => { - await using runtime = await LuaRuntime.load() - expect(runtime.module.useJspi).to.equal(runtime.module.jspiSupported) +describe('Awaiting outside an async run', () => { + it('is an error in a synchronous run', async () => { + using state = await getState() + state.set('ready', Promise.resolve(1)) + expect(() => state.doStringSync('return ready:await()')).to.throw('cannot await inside a synchronous call') }) + it('is an error in a Lua function called directly from JS', async () => { + using state = await getState() + state.set('ready', Promise.resolve(1)) + const fn = state.doStringSync('return function() return ready:await() end') + expect(() => fn()).to.throw('cannot await inside a synchronous call') + // The failed call leaves the state usable. + expect(await state.doString('return ready:await()')).to.be.equal(1) + }) + + it('reports a yield in a Lua function called directly from JS', async () => { + using state = await getState() + const fn = state.doStringSync('return function() coroutine.yield() end') + expect(() => fn()).to.throw('cannot yield in a Lua function called synchronously') + // The call thread is reusable afterwards. + expect(state.doStringSync('return function() return 5 end')()).to.be.equal(5) + }) + + it('is an error everywhere on a platform without JSPI, where everything else still runs', async () => { + const { Suspending } = WebAssembly + WebAssembly.Suspending = undefined + let runtime + try { + runtime = await LuaRuntime.load() + } finally { + WebAssembly.Suspending = Suspending + } + await using lua = runtime + using state = lua.createState() + expect(lua.module.jspiSupported).to.be.equal(false) + + state.set('ready', Promise.resolve(1)) + expect(await state.doString('return 1 + 1')).to.be.equal(2) + expect(await state.doString('return coroutine.yield(20)', { onYield: ([value]) => value + 1 })).to.be.equal(21) + expect(state.doStringSync('return function(a) return a * 2 end')(4)).to.be.equal(8) + await expect(state.doString('return ready:await()')).to.eventually.be.rejectedWith('no WebAssembly JSPI support') + // The failed await leaves the state usable. + expect(await state.doString('return 3')).to.be.equal(3) + }) +}) + +describe('callAsync', () => { + it('runs a Lua function that awaits and resolves to its first result', async () => { + using state = await getState() + state.set('later', later) + const fn = state.doStringSync('return function(a, b) return later(a):await() + b, "ignored" end') + expect(await state.callAsync(fn, [1, 2])).to.be.equal(3) + }) + + it('resolves to null for a function that returns nothing, like a direct call', async () => { + using state = await getState() + const fn = state.doStringSync('return function() end') + expect(fn()).to.be.equal(null) + expect(await state.callAsync(fn)).to.be.equal(null) + }) + + it('can await across a C-call boundary', async () => { + using state = await getState() + state.set('later', later) + const sorted = state.doStringSync(` + return function(t) + table.sort(t, function(a, b) later(0):await() return a < b end) + return table.concat(t, ",") + end + `) + expect(await state.callAsync(sorted, [[3, 1, 2]])).to.be.equal('1,2,3') + }) + + it('rejects with the Lua error the function raises', async () => { + using state = await getState() + state.set('later', later) + const fn = state.doStringSync('return function() later(1):await() error("boom") end') + await expect(state.callAsync(fn)).to.eventually.be.rejectedWith('boom') + }) + + it('runs overlapping calls of one function independently', async () => { + using state = await getState() + state.set('later', later) + const fn = state.doStringSync('return function(value) return later(value):await() * 2 end') + expect(await Promise.all([1, 2, 3].map((value) => state.callAsync(fn, [value])))).to.be.eql([2, 4, 6]) + // Synchronous calls keep working while those are parked, and after. + const pending = state.callAsync(fn, [5]) + expect(state.doStringSync('return function(value) return value + 1 end')(1)).to.be.equal(2) + expect(await pending).to.be.equal(10) + }) + + it('takes a timeout and a signal, which interrupt a parked call', async () => { + using state = await getState() + state.set('never', new Promise(() => {})) + const fn = state.doStringSync('return function() never:await() end') + + await expect(state.callAsync(fn, [], { timeout: 10 })).to.eventually.be.rejectedWith(LuaTimeoutError) + + const controller = new AbortController() + const aborted = expect(state.callAsync(fn, [], { signal: controller.signal })).to.eventually.be.rejectedWith(LuaAbortError) + controller.abort() + await aborted + }) + + it('falls back to the function timeout of the state', async () => { + using state = await getState({ limits: { functionTimeout: 10 } }) + state.set('never', new Promise(() => {})) + const fn = state.doStringSync('return function() never:await() end') + await expect(state.callAsync(fn)).to.eventually.be.rejectedWith(LuaTimeoutError) + }) + + it('only takes a Lua function of the same state', async () => { + using state = await getState() + using other = await getState() + const foreign = other.doStringSync('return function() return 1 end') + + expect(state.isLuaFunction(state.doStringSync('return function() end'))).to.be.equal(true) + expect(state.isLuaFunction(foreign)).to.be.equal(false) + expect(state.isLuaFunction(() => 1)).to.be.equal(false) + await expect(state.callAsync(() => 1)).to.eventually.be.rejectedWith(TypeError) + await expect(state.callAsync(foreign)).to.eventually.be.rejectedWith(TypeError) + }) + + it('is what a promise calls its Lua reactions through, so they can await', async () => { + using state = await getState() + state.set('later', later) + state.set('failed', () => Promise.reject(new Error('nope'))) + const result = await state.doString(` + local log = {} + local value = later(1) + :next(function(v) return later(v + 1):await() end) + :finally(function() later(0):await() log[#log + 1] = "finally" end) + :await() + local recovered = failed():catch(function() return later("recovered"):await() end):await() + return table.concat({ value, recovered, log[1] }, ",") + `) + expect(result).to.be.equal('2,recovered,finally') + }) + + it('leaves a JS reaction handed through Lua as it was', async () => { + using state = await getState() + const seen = [] + state.set('ready', Promise.resolve(7)) + state.set('record', function (value) { + seen.push([this, value]) + return value * 2 + }) + expect(await state.doString('return ready:next(record):await()')).to.be.equal(14) + expect(seen).to.be.eql([[undefined, 7]]) + }) +}) + +describe('Async run isolation', () => { it('keeps Node alive until queued continuations finish, then exits', () => { const entry = new URL('../dist/index.js', import.meta.url).href const stdout = execFileSync( @@ -146,7 +358,7 @@ describe('Async run isolation', () => { '-e', ` import { LuaRuntime } from ${JSON.stringify(entry)} - const runtime = await LuaRuntime.load({ async: 'yield' }) + const runtime = await LuaRuntime.load() const state = runtime.createState() console.log(await state.doString('for i=1,1000 do coroutine.yield() end return 42')) state.close() @@ -189,30 +401,47 @@ describe('Async run isolation', () => { ).to.equal(42) }) - for (const expression of ['ready:await()', 'coroutine.yield()']) { - it(`lets timers run during repeated ${expression}`, async () => { - using state = await getState() - state.set('ready', Promise.resolve()) - let fired = false - state.set('fired', () => fired) - const timer = setTimeout(() => { - fired = true - }, 0) - try { - expect( - await state.doString(` - for i = 1, 10000 do - ${expression} - if fired() then return true end - end - return false - `), - ).to.equal(true) - } finally { - clearTimeout(timer) + it('gives the event loop a turn on every top level coroutine.yield without a handler', async () => { + using state = await getState() + let turns = 0 + let spinning = true + const spin = () => { + turns++ + if (spinning) { + setImmediate(spin) } - }) - } + } + setImmediate(spin) + try { + await state.doString('for i = 1, 50 do coroutine.yield() end') + } finally { + spinning = false + } + expect(turns).to.be.at.least(50) + }) + + it('lets timers run during repeated ready:await()', async () => { + using state = await getState() + state.set('ready', Promise.resolve()) + let fired = false + state.set('fired', () => fired) + const timer = setTimeout(() => { + fired = true + }, 0) + try { + expect( + await state.doString(` + for i = 1, 10000 do + ready:await() + if fired() then return true end + end + return false + `), + ).to.equal(true) + } finally { + clearTimeout(timer) + } + }) it('keeps a deadline through a second await while another run is parked', async () => { using state = await getState() @@ -270,7 +499,6 @@ describe('Async run isolation', () => { it('does not lose a caught interrupt when Lua starts another run', async () => { using state = await getState() - if (!state.module.useJspi) return state.set('never', new Promise(() => {})) let nested state.set('start', () => { @@ -329,8 +557,8 @@ describe('Async run isolation', () => { const runs = [ state.doString('never:await()'), state.doString('never:await()'), - state.get('callback')(), - state.get('callback')(), + state.callAsync(state.get('callback')), + state.callAsync(state.get('callback')), state.doString('coroutine.yield()', { onYield: () => new Promise(() => {}) }), ] const checked = runs.map((run) => expect(run).to.eventually.be.rejectedWith('the Lua state is closed')) diff --git a/test/browser.test.js b/test/browser.test.js index f19912a..331f3a6 100644 --- a/test/browser.test.js +++ b/test/browser.test.js @@ -134,35 +134,33 @@ describe('Browser environment', () => { } } - for (const engine of ['yield', 'jspi']) { - it(`isolates async runs and lets timers run under ${engine}`, async function () { - this.timeout(30_000) - const result = await runInBrowser(` - const runtime = await LuaRuntime.load({ wasmFile, async: '${engine}' }) - const state = runtime.createState() - try { - let fired = false - state.set('ready', Promise.resolve()) - state.set('fired', () => fired) - setTimeout(() => { fired = true }, 0) - const fair = await state.doString('for i=1,10000 do ready:await() if fired() then return true end end return false') - let releaseFirst, releaseOther - state.set('first', new Promise((resolve) => { releaseFirst = resolve })) - state.set('other', new Promise((resolve) => { releaseOther = resolve })) - state.set('never', new Promise(() => {})) - const timed = state.doString('first:await() never:await()', { timeout: 30 }).catch((error) => error.name) - const other = state.doString('other:await() return 42') - releaseFirst() - const error = await timed - releaseOther() - return { fair, error, other: await other } - } finally { - state.close() - } - `) - expect(result).to.eql({ fair: true, error: 'LuaTimeoutError', other: 42 }) - }) - } + it('isolates async runs and lets timers run', async function () { + this.timeout(30_000) + const result = await runInBrowser(` + const runtime = await LuaRuntime.load({ wasmFile }) + const state = runtime.createState() + try { + let fired = false + state.set('ready', Promise.resolve()) + state.set('fired', () => fired) + setTimeout(() => { fired = true }, 0) + const fair = await state.doString('for i=1,10000 do ready:await() if fired() then return true end end return false') + let releaseFirst, releaseOther + state.set('first', new Promise((resolve) => { releaseFirst = resolve })) + state.set('other', new Promise((resolve) => { releaseOther = resolve })) + state.set('never', new Promise(() => {})) + const timed = state.doString('first:await() never:await()', { timeout: 30 }).catch((error) => error.name) + const other = state.doString('other:await() return 42') + releaseFirst() + const error = await timed + releaseOther() + return { fair, error, other: await other } + } finally { + state.close() + } + `) + expect(result).to.eql({ fair: true, error: 'LuaTimeoutError', other: 42 }) + }) it('load Lua engine in browser should succeed', async function () { this.timeout(30_000) diff --git a/test/bundling.test.js b/test/bundling.test.js index f8cf7a9..4ed5462 100644 --- a/test/bundling.test.js +++ b/test/bundling.test.js @@ -47,7 +47,7 @@ describe('Bundling', () => { }) const getMinifiedState = async (config = {}) => { - const lua = await minified.LuaRuntime.load({ wasmFile: WASM_FILE, async: process.env.WASMOON_ASYNC }) + const lua = await minified.LuaRuntime.load({ wasmFile: WASM_FILE }) return lua.createState({ inject: true, ...config }) } diff --git a/test/utils.js b/test/utils.js index ea1a149..648192b 100644 --- a/test/utils.js +++ b/test/utils.js @@ -3,12 +3,8 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { LuaRuntime } from '../dist/index.js' -// Lets the whole suite run under either async engine: WASMOON_ASYNC=yield forces the fallback, -// 'jspi' requires JSPI, and the default lets the platform choose. -const asyncEngine = process.env.WASMOON_ASYNC - export const getLua = (options) => { - return LuaRuntime.load(asyncEngine ? { async: asyncEngine, ...options } : options) + return LuaRuntime.load(options) } export const getState = async (config = {}) => { diff --git a/utils/build-wasm.sh b/utils/build-wasm.sh index 2e02437..27cc68e 100755 --- a/utils/build-wasm.sh +++ b/utils/build-wasm.sh @@ -63,7 +63,7 @@ COMMON=( -s INITIAL_HEAP=1MB # The engines package.json promises, so the glue carries no fallbacks for older ones. The browser # minimums go on the web glue alone below: the host glue is Node only and would warn about them. - -s MIN_NODE_VERSION=240000 + -s MIN_NODE_VERSION=260000 -s EXPORTED_FUNCTIONS="[ '_malloc', \ '_free', \ From accf0097f470099b6fd3bd6f9764b8ed9d018dc3 Mon Sep 17 00:00:00 2001 From: ceifa Date: Sun, 15 Nov 2026 19:47:33 -0300 Subject: [PATCH 69/83] async(fn) for lua functions that await With `inject`, `async(fn)` returns a function that runs `fn` as a run of its own and hands back a promise of its first result: what `async function` is to JS. A callback wrapped in it can await when a JS API calls it synchronously, which a bare Lua function cannot now that calls from JS are always synchronous. The wrapper is a Lua closure over `fn`, compiled on first use, and the arguments of a call move between Lua stacks without becoming JS values. --- README.md | 19 +++++++ src/state.ts | 4 ++ src/type-extensions/function.ts | 95 ++++++++++++++++++++++++++++----- src/types.ts | 2 +- test/async.test.js | 93 ++++++++++++++++++++++++++++++++ 5 files changed, 199 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index f235994..c047342 100644 --- a/README.md +++ b/README.md @@ -287,6 +287,25 @@ end) print("res", res:await()) ``` +From Lua, with `inject: true`, `async(fn)` is what `async function` is in JS: it returns a function +that runs `fn` as a run of its own and gives back a promise of its first result. Wrap a callback in +it before handing it to a JS API, and it can await whoever calls it: + +```lua +-- setTimeout calls the function synchronously, which on its own could not await +setTimeout(async(function() + sleep(10):await() + print("later") +end), 100) + +-- and it is how to start work without waiting for it +local fetchAll = async(function(url) return fetch(url):await() end) +local pages = Promise.all({ fetchAll(a), fetchAll(b) }):await() +``` + +As with an async function in JS, an error in it rejects the promise it returned, so await or +`catch` that promise if the error matters. + #### Interrupting a parked run A run parked on a promise is interrupted by its `timeout` or `AbortSignal` without waiting for the diff --git a/src/state.ts b/src/state.ts index 1cd57fb..0f542fc 100755 --- a/src/state.ts +++ b/src/state.ts @@ -169,6 +169,10 @@ export default class LuaState extends Thread { } this.defaultMaxInstructions = limits?.maxInstructions + + if (inject) { + this.functions.injectAsync() + } } /** diff --git a/src/type-extensions/function.ts b/src/type-extensions/function.ts index 2f55c40..7b32901 100644 --- a/src/type-extensions/function.ts +++ b/src/type-extensions/function.ts @@ -1,4 +1,5 @@ -import { Decoration, type DecorationOptions } from '../decoration' +import { decorate, Decoration, type DecorationOptions } from '../decoration' +import RawResult from '../raw-result' import type LuaState from '../state' import type Thread from '../thread' import TypeExtension from '../type-extension' @@ -13,6 +14,15 @@ type LuaFunction = FunctionType & Record const NO_OPTIONS: DecorationOptions = {} +/** + * What `async(fn)` returns, as a chunk that takes the JS function starting the run and gives back + * the function doing the wrapping. See {@link FunctionTypeExtension.injectAsync}. + */ +const ASYNC_SOURCE = `local start = ... +return function(fn) + return function(...) return start(fn, ...) end +end` + /** Whether the wrapper would behave any differently for these options than for none. */ function affectsCall(options: DecorationOptions): boolean { return options.self !== undefined || options.receiveThread === true || options.receiveArgsQuantity === true @@ -252,17 +262,12 @@ export class FunctionTypeExtension extends TypeExtension { * Calls a Lua function as a run of its own instead of synchronously, which is what lets it * `:await()`. Resolves to its first result, the same value a direct call returns. */ - public async callAsync(jsFunc: FunctionType, args: unknown[], options?: LuaRunOptions): Promise { - const func = (jsFunc as LuaFunction | undefined)?.[this.luaFunction] - if (func === undefined) { - throw new TypeError('callAsync expects a Lua function obtained from this state') - } - this.assertCallable() - - // A thread of its own rather than the pooled one, which a parked run would keep from every - // synchronous call made in the meantime. - const { thread, reference } = this.callbackContext.newAnchoredThread() - try { + public callAsync(jsFunc: FunctionType, args: unknown[], options?: LuaRunOptions): Promise { + return this.runCall((thread) => { + const func = (jsFunc as LuaFunction | undefined)?.[this.luaFunction] + if (func === undefined) { + throw new TypeError('callAsync expects a Lua function obtained from this state') + } const internalType = thread.module.lua_rawgeti(thread.address, LUA_REGISTRYINDEX, func) if (internalType !== LuaType.Function) { this.assertHasCallMetamethod(thread, internalType) @@ -270,10 +275,74 @@ export class FunctionTypeExtension extends TypeExtension { for (const arg of args) { thread.pushValue(arg) } + return args.length + }, options) + } + + /** + * Defines the Lua global `async`: what `async function` is to JS. `async(fn)` returns a function + * that runs `fn` as a run of its own, so that it can `:await()` wherever it is called from, and + * hands back a promise of its first result. + * + * What it returns is a Lua closure over `fn`, built by {@link ASYNC_SOURCE}, rather than a JS + * function holding it: that way nothing has to be collected across the two heaps, and the + * arguments of a call move from one Lua stack to another without ever becoming JS values. + */ + public injectAsync(): void { + const { state } = this + const module = state.module + const raw = { receiveThread: true, receiveArgsQuantity: true } + // Called with the function and then its arguments, which are still on the caller's stack. + const start = decorate( + (caller: Thread, valueCount: number) => + this.runCall((thread) => { + module.lua_xmove(caller.address, thread.address, valueCount) + return valueCount - 1 + }), + raw, + ) + // Compiled by the first call rather than for every state that injects it, most of which + // never make one: loading it up front cost a quarter of creating the state. + let wrap: number | undefined + + state.set( + 'async', + decorate((thread: Thread) => { + const L = thread.address + const type = module.lua_type(L, 1) + if (type !== LuaType.Function) { + throw new TypeError(`async expects a function, got ${module.lua_typename(L, type)}`) + } + if (wrap === undefined) { + thread.loadString(ASYNC_SOURCE, { name: '=async' }) + thread.pushValue(start) + module.lua_callk(L, 1, 1, 0, null) + wrap = module.luaL_ref(L, LUA_REGISTRYINDEX) + } + module.lua_rawgeti(L, LUA_REGISTRYINDEX, wrap) + module.lua_pushvalue(L, 1) + module.lua_callk(L, 1, 1, 0, null) + return new RawResult(1) + }, raw), + ) + } + + /** + * Runs what `prepare` leaves on a new thread -- a function, and as many arguments as it returns + * the count of -- as a run of its own, and resolves to its first result. + */ + private async runCall(prepare: (thread: Thread) => number, options?: LuaRunOptions): Promise { + this.assertCallable() + + // A thread of its own rather than the pooled one, which a parked run would keep from every + // synchronous call made in the meantime. + const { thread, reference } = this.callbackContext.newAnchoredThread() + try { + const argCount = prepare(thread) // The limit a direct call runs under, the function timeout, rather than the ones a // doString run is seeded with. const timeout = options?.timeout ?? this.functionTimeout - const values = await thread.run(args.length, timeout === undefined ? options : { ...options, timeout }) + const values = await thread.run(argCount, timeout === undefined ? options : { ...options, timeout }) return values.length >= 1 ? values[0] : null } finally { // The same teardown as LuaState.callByteCode. Sharing it through a helper costs each diff --git a/src/types.ts b/src/types.ts index eb05fa6..c3f07b7 100755 --- a/src/types.ts +++ b/src/types.ts @@ -108,7 +108,7 @@ export interface CreateStateOptions { * because the proxy already covers errors when it is enabled. */ errors?: boolean | undefined - /** Injects `Error`, `Promise` and `null` into the Lua globals. */ + /** Injects `Error`, `Promise`, `null` and `async` into the Lua globals. */ inject?: boolean | undefined memory?: LuaMemoryOptions | undefined limits?: LuaLimitOptions | undefined diff --git a/test/async.test.js b/test/async.test.js index 76f5090..5afbb8c 100644 --- a/test/async.test.js +++ b/test/async.test.js @@ -348,6 +348,99 @@ describe('callAsync', () => { }) }) +describe('async', () => { + it('wraps a Lua function so that calling it starts a run and returns its promise', async () => { + using state = await getState() + state.set('later', later) + expect(await state.doString('return async(function(a, b) return later(a):await() + b end)(1, 2):await()')).to.be.equal(3) + }) + + it('lets a function handed straight to a JS API await', async () => { + using state = await getState() + state.set('later', later) + let outcome + const called = new Promise((resolve) => { + state.set('schedule', (callback) => { + setTimeout(() => { + outcome = callback(20) + resolve() + }, 1) + }) + }) + await state.doString('schedule(async(function(x) return later(x):await() + 1 end))') + await called + expect(outcome).to.be.instanceOf(Promise) + expect(await outcome).to.be.equal(21) + }) + + it('runs the calls it starts concurrently', async () => { + using state = await getState() + const order = [] + state.set('mark', (value) => void order.push(value)) + state.set('sleep', sleep) + await state.doString(` + local work = async(function(name, ms) mark(name .. " in") sleep(ms):await() mark(name .. " out") end) + Promise.all({ work("slow", 20), work("fast", 1) }):await() + `) + expect(order).to.be.eql(['slow in', 'fast in', 'fast out', 'slow out']) + }) + + it('passes its arguments as the Lua values they are', async () => { + // Under 'copy' a table that went through JS would come back as another table. + using state = await getState({ objects: 'copy' }) + state.set('later', later) + const result = await state.doString(` + local t = {} + local same = async(function(x) later(1):await() x.seen = true return x == t end)(t):await() + return same and t.seen + `) + expect(result).to.be.equal(true) + }) + + it('can await across a C-call boundary and from a synchronous run', async () => { + using state = await getState() + state.set('later', later) + const promise = state.doStringSync(` + return async(function() + local t = {3, 1, 2} + table.sort(t, function(a, b) later(0):await() return a < b end) + return table.concat(t, ",") + end)() + `) + expect(promise).to.be.instanceOf(Promise) + expect(await promise).to.be.equal('1,2,3') + }) + + it('rejects the promise with the error the function raises', async () => { + using state = await getState() + state.set('later', later) + await expect(state.doString('return async(function() later(1):await() error("boom") end)():await()')).to.eventually.be.rejectedWith( + 'boom', + ) + }) + + it('runs under the function timeout of the state', async () => { + using state = await getState({ limits: { functionTimeout: 10 } }) + state.set('never', new Promise(() => {})) + await expect(state.doStringSync('return async(function() never:await() end)()')).to.eventually.be.rejectedWith(LuaTimeoutError) + }) + + it('only wraps a function', async () => { + using state = await getState() + await expect(state.doString('return async(42)')).to.eventually.be.rejectedWith('async expects a function, got number') + await expect(state.doString('return async()')).to.eventually.be.rejectedWith('async expects a function, got no value') + }) + + it('is not there without inject, and does not need the standard libraries', async () => { + using plain = await getState({ inject: false }) + expect(plain.doStringSync('return async')).to.be.equal(null) + + using bare = await getState({ libs: false }) + bare.set('later', later) + expect(await bare.doString('return async(function() return later(3):await() end)():await()')).to.be.equal(3) + }) +}) + describe('Async run isolation', () => { it('keeps Node alive until queued continuations finish, then exits', () => { const entry = new URL('../dist/index.js', import.meta.url).href From 9b4a9a831342df1a86f21cb220f50a54e8289962 Mon Sep 17 00:00:00 2001 From: ceifa Date: Sun, 15 Nov 2026 20:14:32 -0300 Subject: [PATCH 70/83] friendlier async api - state.async(fn, options) replaces callAsync: it returns the asynchronous counterpart of a Lua function, the mirror of async(fn) in Lua, ready to hand to whatever takes a callback - inject takes the names to define (['Promise', 'async']), so async and Promise no longer come with the null sentinel - asynchronous runs of a function start under the same limits as a doString, the state's instruction budget included, with the function timeout on top - LuaRuntime.canAwait tells whether the platform can await, before loading anything - onAsyncError receives the error of an async(fn) call nothing was waiting on, which is otherwise an unhandled rejection - a function that returns nothing or nil resolves to undefined, as a run does, and the await error names async(fn) and state.async(fn) --- README.md | 66 +++++++++++--------- docs/async-redesign/README.md | 4 +- src/async.ts | 42 +++++++++++++ src/index.ts | 1 + src/module.ts | 4 +- src/runtime.ts | 9 +++ src/state.ts | 34 +++++++---- src/type-extensions/function.ts | 99 +++++++++++++++++------------- src/type-extensions/promise.ts | 6 +- src/types.ts | 33 ++++++++-- test/async.test.js | 104 ++++++++++++++++++++++++++------ 11 files changed, 292 insertions(+), 110 deletions(-) diff --git a/README.md b/README.md index c047342..2b595ea 100644 --- a/README.md +++ b/README.md @@ -224,7 +224,7 @@ build. ### Null -`null` is injected as userdata type if `inject` is set to `true`. This works as expected except that it will evaluate to `true` in Lua. +`null` is injected as userdata type if `inject` is `true` or names `'null'`. This works as expected except that it will evaluate to `true` in Lua. ### Promises @@ -250,34 +250,50 @@ try { An `:await()` suspends the WebAssembly stack itself, through [JSPI](https://github.com/WebAssembly/js-promise-integration). That makes it work anywhere inside an -asynchronous run (`doString`, `doFile`, `thread.run`, `callAsync`): at the top level, inside a -`pcall`, across C-call boundaries such as a `table.sort` comparator or a `string.gsub` callback, and -inside a coroutine that Lua code resumes, whose resumer simply waits. +asynchronous run (`doString`, `doFile`, `thread.run`, a function made asynchronous as below): at the +top level, inside a `pcall`, across C-call boundaries such as a `table.sort` comparator or a +`string.gsub` callback, and inside a coroutine that Lua code resumes, whose resumer simply waits. It needs a platform with JSPI: Chrome or Edge 137, Firefox 153, Safari 27, Node.js 25, or newer. -Everything else works without it, and an `:await()` raises an error saying so; -`lua.module.jspiSupported` tells which one you are on. +Everything else works without it, and an `:await()` raises an error saying so; `LuaRuntime.canAwait` +tells which one you are on. A synchronous call cannot be suspended, so an `:await()` reached through `doStringSync`, `doFileSync`, `call` or a Lua function called directly from JS is an error. -#### Calling a Lua function that awaits +#### Functions that await A Lua function handed to JS is called synchronously and returns its value directly. To let it -await, call it through `callAsync`, which runs it as a run of its own and returns a `Promise` of its -first result: +await, make it asynchronous, the way `async function` does in JS. From JS that is `state.async`, +which returns a function that starts the Lua one as a run of its own and gives back a promise of +its first result: ```js state.set('sleep', (length) => new Promise((resolve) => setTimeout(resolve, length))) const handler = await state.doString('return function(x) sleep(10):await() return x + 1 end') handler(5) // throws: cannot await inside a synchronous call -await state.callAsync(handler, [5]) // 6 -await state.callAsync(handler, [5], { timeout: 1000 }) // takes the same options as a run +await state.async(handler)(5) // 6 +emitter.on('request', state.async(handler)) // or hand it to whatever takes a callback +state.async(handler, { timeout: 1000 }) // takes the same options as a run ``` -The Lua functions given to a promise's `next`, `catch` and `finally` are called this way already, -so they can await: +From Lua it is `async`, one of the globals `inject` defines. Wrap a callback in it before handing +it to a JS API, and it can await whoever calls it: + +```lua +-- setTimeout calls the function synchronously, which on its own could not await +setTimeout(async(function() + sleep(10):await() + print("later") +end), 100) + +-- and it is how to start work without waiting for it +local fetchPage = async(function(url) return fetch(url):await() end) +local pages = Promise.all({ fetchPage(a), fetchPage(b) }):await() +``` + +The Lua functions given to a promise's `next`, `catch` and `finally` are asynchronous already: ```lua local res = sleep(1):next(function() @@ -287,24 +303,20 @@ end) print("res", res:await()) ``` -From Lua, with `inject: true`, `async(fn)` is what `async function` is in JS: it returns a function -that runs `fn` as a run of its own and gives back a promise of its first result. Wrap a callback in -it before handing it to a JS API, and it can await whoever calls it: +Each call of an asynchronous function is a run like a `doString`, under the same limits, with +`limits.functionTimeout` on top. -```lua --- setTimeout calls the function synchronously, which on its own could not await -setTimeout(async(function() - sleep(10):await() - print("later") -end), 100) +As with an async function in JS, an error in one rejects the promise it returned. When a JS API +called it and dropped that promise, the rejection is unhandled, which by default ends a Node +process. Pass `onAsyncError` when creating the state to receive those errors instead: --- and it is how to start work without waiting for it -local fetchAll = async(function(url) return fetch(url):await() end) -local pages = Promise.all({ fetchAll(a), fetchAll(b) }):await() +```js +const state = lua.createState({ inject: true, onAsyncError: (error) => console.error(error) }) ``` -As with an async function in JS, an error in it rejects the promise it returned, so await or -`catch` that promise if the error matters. +`inject: true` defines `Promise`, `async`, `Error` and `null`. That last one is a sentinel a JS +`null` is marshalled as, and it is truthy in Lua; to leave it out, name the ones you want: +`inject: ['Promise', 'async']`. #### Interrupting a parked run diff --git a/docs/async-redesign/README.md b/docs/async-redesign/README.md index 4fc0d00..b581c6a 100644 --- a/docs/async-redesign/README.md +++ b/docs/async-redesign/README.md @@ -10,8 +10,8 @@ Design proposal, 2026-09-05. Everything marked *measured* below was run against > the `async` load option were removed once JSPI reached every target, so an `:await()` on a > platform without JSPI is an error and everything else still runs there. > - A Lua function called from JS is always synchronous. The sync-or-promise callable of §5.5 was -> replaced by `state.callAsync(fn, args, options)`, which a promise's `next`, `catch` and -> `finally` use for their Lua reactions. +> replaced by an explicit asynchronous counterpart, `state.async(fn)` in JS and `async(fn)` in +> Lua, which a promise's `next`, `catch` and `finally` use for their Lua reactions. > - `Promise.async`, `decorate(fn, { call })`, `runtime.engine` and the ephemeron registry of §5.6 > were not built. diff --git a/src/async.ts b/src/async.ts index f5ea81a..6cb7a3c 100644 --- a/src/async.ts +++ b/src/async.ts @@ -26,6 +26,48 @@ const macrotask: Macrotask = (() => { return (task: () => void) => void setTimeout(task, 0) })() +/** + * Whether the platform has JSPI (the WebAssembly JavaScript Promise Integration API), which is what + * lets an `:await()` suspend the wasm stack. + */ +export const canSuspend = (): boolean => typeof WebAssembly.Suspending === 'function' && typeof WebAssembly.promising === 'function' + +/** A promise that knows whether anything has asked for its outcome. */ +class ObservedPromise extends Promise { + // What `then` derives is an ordinary promise, with nobody to report to. + public static override get [Symbol.species](): PromiseConstructor { + return Promise + } + + public observed = false + + public override then( + onFulfilled?: ((value: unknown) => A | PromiseLike) | null, + onRejected?: ((reason: unknown) => B | PromiseLike) | null, + ): Promise { + this.observed = true + return super.then(onFulfilled, onRejected) + } +} + +/** + * Follows `run`, and hands its failure to `report` when nothing turned out to be waiting for it. + * With that the failure is never an unhandled rejection, which is the host's to decide about and + * in Node ends the process. + */ +export function reportIfUnobserved(run: Promise, report: (error: unknown) => void): Promise { + const promise = new ObservedPromise((resolve, reject) => void run.then(resolve, reject)) + // Through the prototype: the promise's own `then` would count this as somebody waiting. + void Promise.prototype.then.call(promise, undefined, async (error: unknown) => { + // Whoever was handed the promise gets until the event loop turns to start waiting on it. + await yieldToEventLoop() + if (!promise.observed) { + report(error) + } + }) + return promise +} + export const yieldToEventLoop = (): Promise => { return new Promise((resolve) => macrotask(resolve)) } diff --git a/src/index.ts b/src/index.ts index 9f36d98..32f34aa 100755 --- a/src/index.ts +++ b/src/index.ts @@ -38,6 +38,7 @@ export { LUA_LIB_BITS, PointerSize, type LuaAddress, + type LuaInjectName, type LuaLibName, type LuaLoadMode, type LuaWarnHandler, diff --git a/src/module.ts b/src/module.ts index 0781d5d..f9882d7 100755 --- a/src/module.ts +++ b/src/module.ts @@ -3,7 +3,7 @@ // `/// ` at the top of the emitted declarations to cover everyone // else. tsc drops the directive when it is written here, hence the build step. import initWasmModule from '../build/glue.js' -import { limitError, type PendingSuspend, settleOrInterrupt, type SettleOutcome, yieldToEventLoop } from './async' +import { canSuspend, limitError, type PendingSuspend, settleOrInterrupt, type SettleOutcome, yieldToEventLoop } from './async' import type Thread from './thread' import { defaultWarnHandler, LUA_REGISTRYINDEX, type LuaAddress, LuaReturn, LuaType, type LuaWarnHandler, PointerSize } from './types' // A rolldown plugin will resolve this to the current version on package.json @@ -1120,7 +1120,7 @@ export default class LuaModule { * what lets an `:await()` suspend the wasm stack. Without it everything else works and an * `:await()` is an error. */ - public readonly jspiSupported: boolean = typeof WebAssembly.Suspending === 'function' && typeof WebAssembly.promising === 'function' + public readonly jspiSupported: boolean = canSuspend() /** The current wasm stack pointer, saved so a suspended run's C frames can be restored. */ public stackSave(): number { diff --git a/src/runtime.ts b/src/runtime.ts index e60de6a..e3ebc09 100755 --- a/src/runtime.ts +++ b/src/runtime.ts @@ -1,3 +1,4 @@ +import { canSuspend } from './async' import LuaModule, { type EmscriptenFS, type EmscriptenPath, type LuaModuleOptions } from './module' import LuaState from './state' import type { CreateStateOptions } from './types' @@ -9,6 +10,14 @@ import type { CreateStateOptions } from './types' * otherwise independent. */ export default class LuaRuntime { + /** + * Whether Lua can `:await()` a promise on this platform, which takes JSPI: Chrome or Edge 137, + * Firefox 153, Safari 27, Node.js 25, or newer. Everything else works without it. + */ + public static get canAwait(): boolean { + return canSuspend() + } + /** Loads the Lua wasm module. Stdio and the filesystem are shared by every state on it. */ public static async load(luaModuleOpts: Readonly = {}): Promise { return new LuaRuntime(await LuaModule.initialize(luaModuleOpts)) diff --git a/src/state.ts b/src/state.ts index 0f542fc..14395a1 100755 --- a/src/state.ts +++ b/src/state.ts @@ -14,6 +14,7 @@ import { LUA_REGISTRYINDEX, type LuaAddress, type LuaDoOptions, + type LuaInjectName, type LuaMemoryOptions, type LuaRunOptions, LuaType, @@ -124,6 +125,7 @@ export default class LuaState extends Thread { public constructor(cmodule: LuaModule, options: CreateStateOptions = {}) { const { libs = true, objects = 'proxy', errors = objects === 'copy', inject = false, memory, limits, gc, onWarn } = options + const injects = (name: LuaInjectName): boolean => inject === true || (inject !== false && inject.includes(name)) const created = createAddress(cmodule, memory) super(cmodule, [], created.address) @@ -140,18 +142,18 @@ export default class LuaState extends Thread { // Generic handlers - These may be required to be registered for additional types. this.registerTypeExtension(BUILT_IN_PRIORITY.table, createTableType(this)) - this.functions = createFunctionType(this, limits?.functionTimeout) + this.functions = createFunctionType(this, { ...limits, onAsyncError: options.onAsyncError }) this.registerTypeExtension(BUILT_IN_PRIORITY.function, this.functions) // Contains the :await functionality. - this.registerTypeExtension(BUILT_IN_PRIORITY.promise, createPromiseType(this, inject)) + this.registerTypeExtension(BUILT_IN_PRIORITY.promise, createPromiseType(this, injects('Promise'))) - if (inject) { + if (injects('null')) { this.registerTypeExtension(BUILT_IN_PRIORITY.null, createNullType(this)) } if (errors) { - this.registerTypeExtension(BUILT_IN_PRIORITY.error, createErrorType(this, inject)) + this.registerTypeExtension(BUILT_IN_PRIORITY.error, createErrorType(this, injects('Error'))) } if (objects === 'proxy') { @@ -170,7 +172,7 @@ export default class LuaState extends Thread { this.defaultMaxInstructions = limits?.maxInstructions - if (inject) { + if (injects('async')) { this.functions.injectAsync() } } @@ -209,16 +211,24 @@ export default class LuaState extends Thread { } /** - * Calls a Lua function obtained from this state as a run of its own, which is what lets it - * `:await()`: called directly it runs synchronously, and an await in it is an error. Resolves - * to the function's first result. `limits.functionTimeout` applies unless `options.timeout` - * replaces it. + * The asynchronous counterpart of a Lua function obtained from this state, as `async function` + * is to `function`. Called directly a Lua function runs synchronously, and an `:await()` in it + * is an error; what this returns starts it as a run of its own instead, and gives back a + * promise of its first result. + * + * ```js + * emitter.on('request', state.async(handler)) + * const body = await state.async(fetchPage, { timeout: 1000 })(url) + * ``` + * + * Each call is a run like a `doString`, under the same limits, with `limits.functionTimeout` + * on top unless `options.timeout` replaces it. */ - public callAsync(fn: (...args: any[]) => any, args: unknown[] = [], options?: LuaRunOptions): Promise { - return this.functions.callAsync(fn, args, options) as Promise + public async(fn: (...args: any[]) => any, options?: LuaRunOptions): (...args: any[]) => Promise { + return this.functions.async(fn, options) as (...args: any[]) => Promise } - /** Whether `value` is a Lua function obtained from this state, the kind {@link callAsync} takes. */ + /** Whether `value` is a Lua function obtained from this state, the kind {@link async} takes. */ public isLuaFunction(value: unknown): value is (...args: any[]) => any { return this.functions.isLuaFunction(value) } diff --git a/src/type-extensions/function.ts b/src/type-extensions/function.ts index 7b32901..1475d8a 100644 --- a/src/type-extensions/function.ts +++ b/src/type-extensions/function.ts @@ -5,13 +5,23 @@ import type Thread from '../thread' import TypeExtension from '../type-extension' import { LUA_REGISTRYINDEX, LuaReturn, type LuaAddress, type LuaRunOptions, LuaType } from '../types' import { isEmscriptenUnwind } from '../utils' -import { SUSPEND } from '../async' +import { reportIfUnobserved, SUSPEND } from '../async' export type FunctionType = (...args: any[]) => Promise | any /** A Lua function as JS sees it, carrying the registry reference of the function it calls. */ type LuaFunction = FunctionType & Record +/** The parts of the state's options that bear on calling a Lua function. */ +export interface FunctionCallOptions { + /** Milliseconds a Lua function called from JS may run before being interrupted. */ + functionTimeout?: number | undefined + /** Instructions an asynchronous run of a function may execute, as for any other run. */ + maxInstructions?: number | undefined + /** See `CreateStateOptions.onAsyncError`. */ + onAsyncError?: ((error: unknown) => void) | undefined +} + const NO_OPTIONS: DecorationOptions = {} /** @@ -35,7 +45,7 @@ export class FunctionTypeExtension extends TypeExtension { } }) /** - * Keys the registry reference on each Lua function handed to JS, which is how {@link callAsync} + * Keys the registry reference on each Lua function handed to JS, which is how {@link async} * finds the function to run. A symbol of this state's own, so another state's function does not * answer to it, and a property rather than a WeakMap entry, which cost more than the rest of * creating the wrapper put together. @@ -52,13 +62,14 @@ export class FunctionTypeExtension extends TypeExtension { */ private readonly pooledCallThread: Thread private pooledCallThreadInUse = false - /** Milliseconds a Lua function called from JS may run before being interrupted. */ private readonly functionTimeout: number | undefined + private readonly options: FunctionCallOptions - public constructor(state: LuaState, functionTimeout?: number) { + public constructor(state: LuaState, options: FunctionCallOptions = {}) { super(state, 'js_function') - this.functionTimeout = functionTimeout + this.options = options + this.functionTimeout = options.functionTimeout // Create a thread off of the global thread to be used to create function call threads without // interfering with the global context. This creates a callback context that will always exist // even if the thread that called getValue() has been destroyed. Neither anchor is ever @@ -216,7 +227,7 @@ export class FunctionTypeExtension extends TypeExtension { const callThread = this.acquireCallThread() let result: unknown try { - // Spelled out rather than shared with callAsync through a helper: this is the call + // Spelled out rather than shared with async through a helper: this is the call // the interop benchmarks measure, and the extra frame showed up in them. const internalType = callThread.module.lua_rawgeti(callThread.address, LUA_REGISTRYINDEX, func) if (internalType !== LuaType.Function) { @@ -235,7 +246,7 @@ export class FunctionTypeExtension extends TypeExtension { // this can name, instead of as Lua's error about yielding outside a coroutine. const resumed = callThread.resume(args.length) if (resumed.result === LuaReturn.Yield) { - throw new Error('cannot yield in a Lua function called synchronously from JS, use callAsync to let it') + throw new Error('cannot yield in a Lua function called synchronously from JS, wrap it with state.async to let it') } callThread.assertOk(resumed.result) result = resumed.resultCount >= 1 ? callThread.getValue(1) : null @@ -259,24 +270,28 @@ export class FunctionTypeExtension extends TypeExtension { } /** - * Calls a Lua function as a run of its own instead of synchronously, which is what lets it - * `:await()`. Resolves to its first result, the same value a direct call returns. + * The asynchronous counterpart of a Lua function: calling what this returns starts the function + * as a run of its own instead of synchronously, which is what lets it `:await()`, and gives + * back a promise of its first result. */ - public callAsync(jsFunc: FunctionType, args: unknown[], options?: LuaRunOptions): Promise { - return this.runCall((thread) => { - const func = (jsFunc as LuaFunction | undefined)?.[this.luaFunction] - if (func === undefined) { - throw new TypeError('callAsync expects a Lua function obtained from this state') - } - const internalType = thread.module.lua_rawgeti(thread.address, LUA_REGISTRYINDEX, func) - if (internalType !== LuaType.Function) { - this.assertHasCallMetamethod(thread, internalType) - } - for (const arg of args) { - thread.pushValue(arg) - } - return args.length - }, options) + public async(jsFunc: FunctionType, options?: LuaRunOptions): (...args: unknown[]) => Promise { + if (!this.isLuaFunction(jsFunc)) { + throw new TypeError('async expects a Lua function obtained from this state') + } + return (...args) => + this.runCall((thread) => { + // Read off the function on every call rather than once above: holding on to it is + // what keeps its registry reference from being released. + const func = (jsFunc as LuaFunction)[this.luaFunction]! + const internalType = thread.module.lua_rawgeti(thread.address, LUA_REGISTRYINDEX, func) + if (internalType !== LuaType.Function) { + this.assertHasCallMetamethod(thread, internalType) + } + for (const arg of args) { + thread.pushValue(arg) + } + return args.length + }, options) } /** @@ -292,15 +307,15 @@ export class FunctionTypeExtension extends TypeExtension { const { state } = this const module = state.module const raw = { receiveThread: true, receiveArgsQuantity: true } + const { onAsyncError } = this.options // Called with the function and then its arguments, which are still on the caller's stack. - const start = decorate( - (caller: Thread, valueCount: number) => - this.runCall((thread) => { - module.lua_xmove(caller.address, thread.address, valueCount) - return valueCount - 1 - }), - raw, - ) + const start = decorate((caller: Thread, valueCount: number) => { + const run = this.runCall((thread) => { + module.lua_xmove(caller.address, thread.address, valueCount) + return valueCount - 1 + }) + return onAsyncError ? reportIfUnobserved(run, onAsyncError) : run + }, raw) // Compiled by the first call rather than for every state that injects it, most of which // never make one: loading it up front cost a quarter of creating the state. let wrap: number | undefined @@ -329,7 +344,9 @@ export class FunctionTypeExtension extends TypeExtension { /** * Runs what `prepare` leaves on a new thread -- a function, and as many arguments as it returns - * the count of -- as a run of its own, and resolves to its first result. + * the count of -- as a run of its own, and resolves to its first result. A function that + * returned nil resolves to undefined like one that returned nothing, rather than to the null + * that `inject` marshals back into Lua as a sentinel, which is truthy there. */ private async runCall(prepare: (thread: Thread) => number, options?: LuaRunOptions): Promise { this.assertCallable() @@ -338,12 +355,12 @@ export class FunctionTypeExtension extends TypeExtension { // synchronous call made in the meantime. const { thread, reference } = this.callbackContext.newAnchoredThread() try { - const argCount = prepare(thread) - // The limit a direct call runs under, the function timeout, rather than the ones a - // doString run is seeded with. - const timeout = options?.timeout ?? this.functionTimeout - const values = await thread.run(argCount, timeout === undefined ? options : { ...options, timeout }) - return values.length >= 1 ? values[0] : null + // The limits any other run starts under, and the function timeout on top of them. + thread.setLimits(this.state.getLimits()) + const { functionTimeout: timeout, maxInstructions } = this.options + const defaults = timeout !== undefined || maxInstructions !== undefined + const values = await thread.run(prepare(thread), defaults ? { timeout, maxInstructions, ...options } : options) + return values[0] ?? undefined } finally { // The same teardown as LuaState.callByteCode. Sharing it through a helper costs each // parked doString a closure its suspended frame keeps alive. @@ -377,6 +394,6 @@ export class FunctionTypeExtension extends TypeExtension { } } -export default function createTypeExtension(state: LuaState, functionTimeout?: number): FunctionTypeExtension { - return new FunctionTypeExtension(state, functionTimeout) +export default function createTypeExtension(state: LuaState, options?: FunctionCallOptions): FunctionTypeExtension { + return new FunctionTypeExtension(state, options) } diff --git a/src/type-extensions/promise.ts b/src/type-extensions/promise.ts index 0f26629..63422df 100644 --- a/src/type-extensions/promise.ts +++ b/src/type-extensions/promise.ts @@ -21,7 +21,8 @@ const asPromise = (self: unknown): Promise => { type Reaction = ((...args: any[]) => unknown) | null | undefined /** Why an `:await()` reached outside a suspendable run fails, for a platform with JSPI and one without. */ -const SYNCHRONOUS_AWAIT = 'cannot await inside a synchronous call: run the script with doString, or the function with callAsync' +const SYNCHRONOUS_AWAIT = + 'cannot await inside a synchronous call: run the script with doString, or make the function asynchronous with async(fn) in Lua or state.async(fn) in JS' const UNSUPPORTED_AWAIT = 'cannot await: this platform has no WebAssembly JSPI support (it needs Chrome 137, Firefox 153, Safari 27 or Node.js 25, or newer)' @@ -31,8 +32,7 @@ class PromiseTypeExtension extends TypeExtension> { // A Lua function handed to a promise runs as a run of its own, so that it can await like the // async function it stands in for. Anything else is passed through as it is. - const reaction = (callback: Reaction): Reaction => - state.isLuaFunction(callback) ? (...args: unknown[]) => state.callAsync(callback, args) : callback + const reaction = (callback: Reaction): Reaction => (state.isLuaFunction(callback) ? state.async(callback) : callback) this.defineMetatable({ // A plain object, which the table extension (registered before this one) copies into a diff --git a/src/types.ts b/src/types.ts index c3f07b7..fcc0e90 100755 --- a/src/types.ts +++ b/src/types.ts @@ -72,12 +72,21 @@ export interface LuaMemoryOptions { } export interface LuaLimitOptions { - /** Milliseconds a Lua function called from JS may run before being interrupted. */ + /** + * Milliseconds a Lua function called from JS may run before being interrupted, whether it is + * called directly or as a run of its own through `state.async` or Lua's `async`. + */ functionTimeout?: number | undefined - /** Instructions a single run may execute before being interrupted. */ + /** + * Instructions a single run may execute before being interrupted. A run is a `doString` or + * `doFile`, or a function started through `state.async`, Lua's `async` or a promise reaction. + */ maxInstructions?: number | undefined } +/** A global that `CreateStateOptions.inject` can define. */ +export type LuaInjectName = 'Error' | 'Promise' | 'null' | 'async' + /** * The tunables of `collectgarbage('param', ...)`. `pause`, `stepmul` and `stepsize` drive the * incremental collector, the other three the generational one. @@ -108,8 +117,24 @@ export interface CreateStateOptions { * because the proxy already covers errors when it is enabled. */ errors?: boolean | undefined - /** Injects `Error`, `Promise`, `null` and `async` into the Lua globals. */ - inject?: boolean | undefined + /** + * Which helpers to define as Lua globals. `true` defines all of them, or name them + * individually: + * + * - `Promise`: `Promise.create`, `Promise.all` and `Promise.resolve`. + * - `async`: `async(fn)` returns a function that runs `fn` as a run of its own and gives back + * a promise of its first result, so that it can `:await()` whoever calls it. + * - `Error`: `Error.create`, where the error bridge is registered (see `errors`). + * - `null`: a sentinel that a JS `null` is marshalled as instead of `nil`. It is truthy in Lua. + */ + inject?: LuaInjectName[] | boolean | undefined + /** + * Called with the error of a function started through Lua's `async` when nothing was waiting + * on the promise it returned: a callback a JS API called and forgot about, say. Without a + * handler such a failure is an unhandled promise rejection, which is the host's to deal with + * and by default ends a Node process. + */ + onAsyncError?: ((error: unknown) => void) | undefined memory?: LuaMemoryOptions | undefined limits?: LuaLimitOptions | undefined gc?: LuaGcOptions | undefined diff --git a/test/async.test.js b/test/async.test.js index 5afbb8c..a013fd2 100644 --- a/test/async.test.js +++ b/test/async.test.js @@ -4,7 +4,7 @@ import chaiAsPromised from 'chai-as-promised' use(chaiAsPromised) import { expect } from 'chai' -import { LuaRuntime, LuaTimeoutError, LuaAbortError, LuaMultiReturn } from '../dist/index.js' +import { LuaRuntime, LuaTimeoutError, LuaAbortError, LuaInstructionLimitError, LuaMultiReturn } from '../dist/index.js' import { getState } from './utils.js' const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) @@ -206,7 +206,7 @@ describe('Awaiting outside an async run', () => { using state = await getState() state.set('ready', Promise.resolve(1)) const fn = state.doStringSync('return function() return ready:await() end') - expect(() => fn()).to.throw('cannot await inside a synchronous call') + expect(() => fn()).to.throw('make the function asynchronous with async(fn) in Lua or state.async(fn) in JS') // The failed call leaves the state usable. expect(await state.doString('return ready:await()')).to.be.equal(1) }) @@ -224,6 +224,7 @@ describe('Awaiting outside an async run', () => { WebAssembly.Suspending = undefined let runtime try { + expect(LuaRuntime.canAwait).to.be.equal(false) runtime = await LuaRuntime.load() } finally { WebAssembly.Suspending = Suspending @@ -231,6 +232,7 @@ describe('Awaiting outside an async run', () => { await using lua = runtime using state = lua.createState() expect(lua.module.jspiSupported).to.be.equal(false) + expect(LuaRuntime.canAwait).to.be.equal(true) state.set('ready', Promise.resolve(1)) expect(await state.doString('return 1 + 1')).to.be.equal(2) @@ -242,19 +244,26 @@ describe('Awaiting outside an async run', () => { }) }) -describe('callAsync', () => { +describe('state.async', () => { it('runs a Lua function that awaits and resolves to its first result', async () => { using state = await getState() state.set('later', later) const fn = state.doStringSync('return function(a, b) return later(a):await() + b, "ignored" end') - expect(await state.callAsync(fn, [1, 2])).to.be.equal(3) + expect(await state.async(fn)(1, 2)).to.be.equal(3) }) - it('resolves to null for a function that returns nothing, like a direct call', async () => { + it('resolves to undefined for a function that returns nothing or nil, like a run does for nothing', async () => { using state = await getState() - const fn = state.doStringSync('return function() end') - expect(fn()).to.be.equal(null) - expect(await state.callAsync(fn)).to.be.equal(null) + expect(await state.async(state.doStringSync('return function() end'))()).to.be.equal(undefined) + expect(await state.async(state.doStringSync('return function() return nil end'))()).to.be.equal(undefined) + expect(await state.doString('')).to.be.equal(undefined) + }) + + it('returns a function to hand to whatever takes a callback', async () => { + using state = await getState() + state.set('later', later) + const double = state.async(state.doStringSync('return function(value) return later(value):await() * 2 end')) + expect(await Promise.all([1, 2, 3].map(double))).to.be.eql([2, 4, 6]) }) it('can await across a C-call boundary', async () => { @@ -266,23 +275,23 @@ describe('callAsync', () => { return table.concat(t, ",") end `) - expect(await state.callAsync(sorted, [[3, 1, 2]])).to.be.equal('1,2,3') + expect(await state.async(sorted)([3, 1, 2])).to.be.equal('1,2,3') }) it('rejects with the Lua error the function raises', async () => { using state = await getState() state.set('later', later) const fn = state.doStringSync('return function() later(1):await() error("boom") end') - await expect(state.callAsync(fn)).to.eventually.be.rejectedWith('boom') + await expect(state.async(fn)()).to.eventually.be.rejectedWith('boom') }) it('runs overlapping calls of one function independently', async () => { using state = await getState() state.set('later', later) const fn = state.doStringSync('return function(value) return later(value):await() * 2 end') - expect(await Promise.all([1, 2, 3].map((value) => state.callAsync(fn, [value])))).to.be.eql([2, 4, 6]) + expect(await Promise.all([1, 2, 3].map((value) => state.async(fn)(value)))).to.be.eql([2, 4, 6]) // Synchronous calls keep working while those are parked, and after. - const pending = state.callAsync(fn, [5]) + const pending = state.async(fn)(5) expect(state.doStringSync('return function(value) return value + 1 end')(1)).to.be.equal(2) expect(await pending).to.be.equal(10) }) @@ -292,10 +301,10 @@ describe('callAsync', () => { state.set('never', new Promise(() => {})) const fn = state.doStringSync('return function() never:await() end') - await expect(state.callAsync(fn, [], { timeout: 10 })).to.eventually.be.rejectedWith(LuaTimeoutError) + await expect(state.async(fn, { timeout: 10 })()).to.eventually.be.rejectedWith(LuaTimeoutError) const controller = new AbortController() - const aborted = expect(state.callAsync(fn, [], { signal: controller.signal })).to.eventually.be.rejectedWith(LuaAbortError) + const aborted = expect(state.async(fn, { signal: controller.signal })()).to.eventually.be.rejectedWith(LuaAbortError) controller.abort() await aborted }) @@ -304,7 +313,21 @@ describe('callAsync', () => { using state = await getState({ limits: { functionTimeout: 10 } }) state.set('never', new Promise(() => {})) const fn = state.doStringSync('return function() never:await() end') - await expect(state.callAsync(fn)).to.eventually.be.rejectedWith(LuaTimeoutError) + await expect(state.async(fn)()).to.eventually.be.rejectedWith(LuaTimeoutError) + }) + + it('runs under the instruction budget of the state, like any other run', async () => { + using state = await getState({ limits: { maxInstructions: 10_000 } }) + state.set('ready', Promise.resolve()) + const spin = state.doStringSync('return function() ready:await() while true do end end') + + await expect(state.async(spin)()).to.eventually.be.rejectedWith(LuaInstructionLimitError) + await expect( + state.doString('return async(function() ready:await() while true do end end)():await()'), + ).to.eventually.be.rejectedWith(LuaInstructionLimitError) + await expect(state.doStringSync('return ready:next(function() while true do end end)')).to.eventually.be.rejectedWith( + LuaInstructionLimitError, + ) }) it('only takes a Lua function of the same state', async () => { @@ -315,8 +338,8 @@ describe('callAsync', () => { expect(state.isLuaFunction(state.doStringSync('return function() end'))).to.be.equal(true) expect(state.isLuaFunction(foreign)).to.be.equal(false) expect(state.isLuaFunction(() => 1)).to.be.equal(false) - await expect(state.callAsync(() => 1)).to.eventually.be.rejectedWith(TypeError) - await expect(state.callAsync(foreign)).to.eventually.be.rejectedWith(TypeError) + expect(() => state.async(() => 1)).to.throw(TypeError) + expect(() => state.async(foreign)).to.throw(TypeError) }) it('is what a promise calls its Lua reactions through, so they can await', async () => { @@ -431,6 +454,49 @@ describe('async', () => { await expect(state.doString('return async()')).to.eventually.be.rejectedWith('async expects a function, got no value') }) + it('gives nil back to Lua for a function that returned nil, not the truthy null sentinel', async () => { + using state = await getState() + state.set('later', later) + const result = await state.doString(` + local found = async(function() later(1):await() return nil end)():await() + return found == nil and not found + `) + expect(result).to.be.equal(true) + }) + + it('hands a failure nothing was waiting on to onAsyncError instead of leaving it unhandled', async () => { + const reported = [] + using state = await getState({ onAsyncError: (error) => reported.push(error) }) + state.set('later', later) + // Called and forgotten, the way an event emitter or a timer treats its callback. + state.set('fire', (callback) => void callback()) + + await state.doString('fire(async(function() later(1):await() error("lost") end))') + await sleep(20) + expect(reported).to.have.length(1) + expect(reported[0].message).to.include('lost') + + // Someone waiting on the promise gets the error, and the handler is left out of it. + await expect(state.doString('return async(function() later(1):await() error("seen") end)():await()')).to.eventually.be.rejectedWith( + 'seen', + ) + expect( + await state.doString('return select(2, pcall(function() async(function() error("caught") end)():await() end)) ~= nil'), + ).to.be.equal(true) + await sleep(20) + expect(reported).to.have.length(1) + }) + + it('can be injected on its own', async () => { + using state = await getState({ inject: ['async', 'Promise'] }) + state.set('later', later) + const types = await state.doString('return table.concat({ type(async), type(Promise), type(null), type(Error) }, ",")') + expect(types).to.be.equal('function,table,nil,nil') + // Without the null sentinel a JS null is nil in Lua. + state.set('nothing', null) + expect(await state.doString('return nothing == nil')).to.be.equal(true) + }) + it('is not there without inject, and does not need the standard libraries', async () => { using plain = await getState({ inject: false }) expect(plain.doStringSync('return async')).to.be.equal(null) @@ -650,8 +716,8 @@ describe('Async run isolation', () => { const runs = [ state.doString('never:await()'), state.doString('never:await()'), - state.callAsync(state.get('callback')), - state.callAsync(state.get('callback')), + state.async(state.get('callback'))(), + state.async(state.get('callback'))(), state.doString('coroutine.yield()', { onYield: () => new Promise(() => {}) }), ] const checked = runs.map((run) => expect(run).to.eventually.be.rejectedWith('the Lua state is closed')) From 63ab32f44f8203b16fe8baa2e62b7fc90851022b Mon Sep 17 00:00:00 2001 From: ceifa Date: Sun, 15 Nov 2026 21:08:37 -0300 Subject: [PATCH 71/83] drop investigation docs, simplify async helpers --- .oxfmtrc.json | 2 +- .oxlintrc.json | 2 +- README.md | 8 +- bench/async.js | 168 ++-- bench/index.js | 5 + bench/utils.js | 6 +- docs/async-redesign/README.md | 461 ----------- .../experiments/build-wasm-eh.sh | 222 ----- .../experiments/current-behavior.mjs | 34 - .../async-redesign/experiments/jspi-modes.mjs | 98 --- docs/async-redesign/experiments/jspi-raw.mjs | 52 -- docs/async-redesign/experiments/jspi-sp.mjs | 23 - .../async-redesign/experiments/jspi-stack.mjs | 61 -- docs/async-redesign/experiments/perf-dist.mjs | 25 - docs/async-redesign/experiments/perf-raw.mjs | 60 -- docs/performance/README.md | 778 ------------------ docs/performance/async-entries.mjs | 16 - docs/performance/bindings.mjs | 21 - docs/performance/cache-memory.mjs | 26 - docs/performance/call-lua.mjs | 23 - docs/performance/callbacks.mjs | 29 - docs/performance/create-state.mjs | 22 - docs/performance/multiple-returns.mjs | 25 - docs/performance/read-table.mjs | 38 - docs/performance/ready-await-memory.mjs | 33 - docs/performance/reference-memory.mjs | 26 - docs/performance/references.mjs | 29 - docs/performance/retained-memory.mjs | 36 - docs/performance/runtime.mjs | 21 - docs/performance/settled-awaits.mjs | 17 - docs/performance/string-cache-memory.mjs | 16 - docs/performance/string-cache-variants.mjs | 142 ---- docs/performance/string-cache.mjs | 39 - docs/performance/string-decode.mjs | 57 -- docs/performance/table-copy.mjs | 31 - docs/performance/vm.mjs | 42 - src/async.ts | 81 +- src/module.ts | 39 +- src/thread.ts | 4 +- src/type-extensions/function.ts | 10 +- test/async.test.js | 6 +- 41 files changed, 170 insertions(+), 2664 deletions(-) delete mode 100644 docs/async-redesign/README.md delete mode 100755 docs/async-redesign/experiments/build-wasm-eh.sh delete mode 100644 docs/async-redesign/experiments/current-behavior.mjs delete mode 100644 docs/async-redesign/experiments/jspi-modes.mjs delete mode 100644 docs/async-redesign/experiments/jspi-raw.mjs delete mode 100644 docs/async-redesign/experiments/jspi-sp.mjs delete mode 100644 docs/async-redesign/experiments/jspi-stack.mjs delete mode 100644 docs/async-redesign/experiments/perf-dist.mjs delete mode 100644 docs/async-redesign/experiments/perf-raw.mjs delete mode 100644 docs/performance/README.md delete mode 100644 docs/performance/async-entries.mjs delete mode 100644 docs/performance/bindings.mjs delete mode 100644 docs/performance/cache-memory.mjs delete mode 100644 docs/performance/call-lua.mjs delete mode 100644 docs/performance/callbacks.mjs delete mode 100644 docs/performance/create-state.mjs delete mode 100644 docs/performance/multiple-returns.mjs delete mode 100644 docs/performance/read-table.mjs delete mode 100644 docs/performance/ready-await-memory.mjs delete mode 100644 docs/performance/reference-memory.mjs delete mode 100644 docs/performance/references.mjs delete mode 100644 docs/performance/retained-memory.mjs delete mode 100644 docs/performance/runtime.mjs delete mode 100644 docs/performance/settled-awaits.mjs delete mode 100644 docs/performance/string-cache-memory.mjs delete mode 100644 docs/performance/string-cache-variants.mjs delete mode 100644 docs/performance/string-cache.mjs delete mode 100644 docs/performance/string-decode.mjs delete mode 100644 docs/performance/table-copy.mjs delete mode 100644 docs/performance/vm.mjs diff --git a/.oxfmtrc.json b/.oxfmtrc.json index 1095bb1..600545a 100644 --- a/.oxfmtrc.json +++ b/.oxfmtrc.json @@ -7,5 +7,5 @@ "printWidth": 140, "tabWidth": 4, "sortPackageJson": false, - "ignorePatterns": ["rolldown.config.*.js", "docs/**"] + "ignorePatterns": ["rolldown.config.*.js"] } diff --git a/.oxlintrc.json b/.oxlintrc.json index 0a9cd20..c9c4b84 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -11,7 +11,7 @@ "consistent-function-scoping": "off", "promise/always-return": "off" }, - "ignorePatterns": ["dist/**", "build/**", "docs/**", "rolldown.config.ts", "rolldown.config.*.js", "utils/**"], + "ignorePatterns": ["dist/**", "build/**", "rolldown.config.ts", "rolldown.config.*.js", "utils/**"], "env": { "builtin": true } diff --git a/README.md b/README.md index 2b595ea..153b32f 100644 --- a/README.md +++ b/README.md @@ -138,10 +138,10 @@ Wasmoon is **~10x faster** than fengari for pure Lua execution. If your use case Fengari is smaller than wasmoon, which can improve the user experience if in web environments. Both minified, and wasmoon counted as its JS plus `glue.wasm`: -| | wasmoon | fengari | -| ----------- | ---------------- | ------- | -| **plain** | 294kB (97 + 197) | 228kB | -| **gzipped** | 124kB (29 + 95) | 74kB | +| | wasmoon | fengari | +| ----------- | ----------------- | ------- | +| **plain** | 302kB (108 + 194) | 228kB | +| **gzipped** | 128kB (34 + 94) | 74kB | Almost all of wasmoon's weight is the wasm, which is a separate file: it is fetched in parallel with your JS rather than parsed as part of it, and it caches on its own across releases of your app. diff --git a/bench/async.js b/bench/async.js index 46aa7c6..46e5d4f 100644 --- a/bench/async.js +++ b/bench/async.js @@ -1,70 +1,114 @@ -// node --expose-gc bench/async.js [path/to/index.js] -// An alternate bundle makes before/after comparisons use exactly the same workloads. +import { LuaRuntime } from '../dist/index.js' import assert from 'node:assert/strict' -import { resolve } from 'node:path' -import { pathToFileURL } from 'node:url' +import { isMainModule, parseBenchOptions, runBenchmarks } from './utils.js' -const { LuaRuntime } = await import(pathToFileURL(resolve(process.argv[2] ?? 'dist/index.js')).href) -const median = (values) => values.sort((a, b) => a - b)[Math.floor(values.length / 2)] +// The cost of the asynchronous paths on their own: every promise here is settled already, so what +// is timed is the suspend and resume around it rather than whatever it would be waiting for. +const AWAIT_COUNT = 20000 +const RUN_COUNT = 1000 +const PARKED_RUNS = 1000 -const runtime = await LuaRuntime.load() -const state = runtime.createState({ inject: true, memory: { trace: true } }) -state.set('ready', Promise.resolve(1)) -state.set('add', (a, b) => a + b) -state.doStringSync('function addLua(a, b) return a + b end') -const addLua = state.get('addLua') -const workloads = { - '20k settled awaits': () => state.doString('local n = 0 for i=1,20000 do n = n + ready:await() end return n'), - '20k JS to Lua calls': () => { - for (let i = 0; i < 20000; i++) assert.equal(addLua(i, 1), i + 1) - }, - '20k Lua to JS calls': () => state.doStringSync('local n = 0 for i=1,20000 do n = add(n, 1) end return n'), - '1k async entries': async () => { - for (let i = 0; i < 1000; i++) assert.equal(await state.doString('return 1'), 1) - }, - 'CPU loop': () => state.doStringSync('local n = 0 for i=1,1000000 do n = n + i end return n'), +function withState(lua, body) { + return async () => { + const state = lua.createState({ inject: true }) + try { + return await body(state) + } finally { + state.close() + } + } +} + +function createSettledAwaitBenchmark(lua) { + return withState(lua, async (state) => { + state.set('ready', Promise.resolve(1)) + const total = await state.doString(` + local sum = 0 + for i = 1, ${AWAIT_COUNT} do sum = sum + ready:await() end + return sum + `) + assert.equal(total, AWAIT_COUNT) + }) +} + +function createDoStringBenchmark(lua) { + return withState(lua, async (state) => { + for (let i = 0; i < RUN_COUNT; i++) { + assert.equal(await state.doString('return 1'), 1) + } + }) +} + +function createStateAsyncBenchmark(lua) { + return withState(lua, async (state) => { + state.doStringSync('function add(a, b) return a + b end') + const add = state.async(state.get('add')) + for (let i = 0; i < RUN_COUNT; i++) { + assert.equal(await add(i, 1), i + 1) + } + }) +} + +function createLuaAsyncBenchmark(lua) { + return withState(lua, async (state) => { + const total = await state.doString(` + local add = async(function(a, b) return a + b end) + local sum = 0 + for i = 1, ${RUN_COUNT} do sum = sum + add(i, 1):await() end + return sum + `) + assert.equal(total, (RUN_COUNT * (RUN_COUNT + 1)) / 2 + RUN_COUNT) + }) } -const timings = {} -for (const [name, run] of Object.entries(workloads)) { - for (let i = 0; i < 3; i++) await run() - const samples = [] - for (let i = 0; i < 7; i++) { - const start = performance.now() - await run() - samples.push(performance.now() - start) + +// What a run costs while it waits, which no timing shows. Needs `node --expose-gc`. +async function printParkedRunMemory(lua) { + if (typeof globalThis.gc !== 'function') { + console.log('\nMemory of a parked run: skipped, run node with --expose-gc to measure it') + return + } + + const state = lua.createState({ memory: { trace: true } }) + try { + const gate = Promise.withResolvers() + state.set('gate', gate.promise) + state.gc.collect() + globalThis.gc() + const jsBefore = process.memoryUsage().heapUsed + const luaBefore = state.memory.used + + const runs = Array.from({ length: PARKED_RUNS }, () => state.doString('gate:await() return 1')) + // The runs park as their await hooks get to run, which takes a turn of the event loop. + await new Promise((resolve) => setTimeout(resolve, 20)) + globalThis.gc() + const js = (process.memoryUsage().heapUsed - jsBefore) / PARKED_RUNS + const lua = (state.memory.used - luaBefore) / PARKED_RUNS + + gate.resolve() + await Promise.all(runs) + console.log(`\nMemory of a parked run: ${js.toFixed(0)} bytes of JS heap, ${lua.toFixed(0)} bytes of Lua heap`) + } finally { + state.close() } - timings[name] = Number(median(samples).toFixed(2)) } -const heapSamples = [] -const bufferSamples = [] -const luaSamples = [] -for (let sample = 0; sample < 5; sample++) { - let release - state.set( - 'gate', - new Promise((resolve) => { - release = resolve - }), - ) - state.gc.collect() - global.gc?.() - const before = process.memoryUsage() - const luaBefore = state.memory.used - const runs = Array.from({ length: 1000 }, () => state.doString('gate:await() return 1')) - await new Promise((resolve) => setTimeout(resolve, 20)) - global.gc?.() - const during = process.memoryUsage() - heapSamples.push(during.heapUsed - before.heapUsed) - bufferSamples.push(during.arrayBuffers - before.arrayBuffers) - luaSamples.push(state.memory.used - luaBefore) - release() - assert.ok((await Promise.all(runs)).every((value) => value === 1)) +export async function runAsyncBench(options = {}) { + const lua = await LuaRuntime.load() + + const results = await runBenchmarks({ + title: 'Async benchmarks', + benches: [ + { name: 'Await a settled promise', run: createSettledAwaitBenchmark(lua) }, + { name: 'doString', run: createDoStringBenchmark(lua) }, + { name: 'Call Lua from JS with state.async', run: createStateAsyncBenchmark(lua) }, + { name: 'Call a Lua async function', run: createLuaAsyncBenchmark(lua) }, + ], + options, + }) + await printParkedRunMemory(lua) + return results +} + +if (isMainModule(import.meta.url)) { + await runAsyncBench(parseBenchOptions()) } -console.log( - JSON.stringify({ - medianMs: timings, - parked1000: { jsHeapBytes: median(heapSamples), arrayBufferBytes: median(bufferSamples), luaBytes: median(luaSamples) }, - }), -) -state.close() diff --git a/bench/index.js b/bench/index.js index 630b047..7424264 100644 --- a/bench/index.js +++ b/bench/index.js @@ -1,3 +1,4 @@ +import { runAsyncBench } from './async.js' import { runComparisonBench } from './comparisons.js' import { runInteropBench } from './interop.js' import { runStepBench } from './steps.js' @@ -20,6 +21,10 @@ if (options.suite === 'all' || options.suite === 'interop') { await runInteropBench(options) } +if (options.suite === 'all' || options.suite === 'async') { + await runAsyncBench(options) +} + if (options.suite === 'all' || options.suite === 'comparisons') { await runComparisonBench(options) } diff --git a/bench/utils.js b/bench/utils.js index 5804245..2cc79e3 100644 --- a/bench/utils.js +++ b/bench/utils.js @@ -64,7 +64,7 @@ export function printBenchUsage() { Options: -i, --iterations Measured iterations per benchmark (default: ${DEFAULT_OPTIONS.iterations}) -w, --warmup Warmup iterations per benchmark (default: ${DEFAULT_OPTIONS.warmup}) - -s, --suite Which suite to run: all, steps, interop, comparisons + -s, --suite Which suite to run: all, steps, interop, async, comparisons -f, --filter Only run benchmarks whose name includes the given text -h, --help Show this help message`) } @@ -221,8 +221,8 @@ function parseIntegerOption(rawValue, flagName, { min }) { function parseSuiteOption(rawValue, flagName) { const value = parseStringOption(rawValue, flagName) - if (!['all', 'comparisons', 'interop', 'steps'].includes(value)) { - throw new Error(`${flagName} must be one of: all, comparisons, interop, steps`) + if (!['all', 'async', 'comparisons', 'interop', 'steps'].includes(value)) { + throw new Error(`${flagName} must be one of: all, async, comparisons, interop, steps`) } return value } diff --git a/docs/async-redesign/README.md b/docs/async-redesign/README.md deleted file mode 100644 index b581c6a..0000000 --- a/docs/async-redesign/README.md +++ /dev/null @@ -1,461 +0,0 @@ -# Rethinking async in wasmoon - -Design proposal, 2026-09-05. Everything marked *measured* below was run against the current -`dist/` (Node 26.7, V8 14.6) or against a one-off wasm build; the scripts are in `experiments/`. - -> **What shipped differs from this proposal.** It is kept for its reasoning and measurements; the -> README section "Where `:await()` works" describes the behaviour. -> -> - JSPI is the only way to await. The coroutine-yielding engine (the YieldSuspender of §5.2) and -> the `async` load option were removed once JSPI reached every target, so an `:await()` on a -> platform without JSPI is an error and everything else still runs there. -> - A Lua function called from JS is always synchronous. The sync-or-promise callable of §5.5 was -> replaced by an explicit asynchronous counterpart, `state.async(fn)` in JS and `async(fn)` in -> Lua, which a promise's `next`, `catch` and `finally` use for their Lua reactions. -> - `Promise.async`, `decorate(fn, { call })`, `runtime.engine` and the ephemeron registry of §5.6 -> were not built. - -## TL;DR - -The current model has one primitive, "yield the Lua coroutine and let a JS loop look at what was -yielded", and everything (awaiting, time slicing, cancellation, callbacks) is squeezed through it. -That is why awaits fail inside `table.sort`, `gsub`, `promise:next(luaFn)` and every JS→Lua -callback, why top-level `coroutine.yield` values are silently dropped, why a parked run cannot be -aborted or timed out, and why a loop of awaits starves the event loop. - -Proposal, in two layers: - -1. **A real scheduler in JS, engine-agnostic.** Every asynchronous entry point becomes a *run*: - one Lua coroutine, one JS promise, one cancellation scope. The scheduler owns parking and - resuming, uses an explicit yield protocol instead of sniffing the last yielded value, resumes - in microtasks with a starvation guard, can cancel a parked run, and lets JS→Lua callbacks - return a promise when the Lua side suspends. This fixes most of the list above with no wasm - change and is required anyway as the fallback engine. -2. **JSPI as the primary engine where available.** With `-sSUPPORT_LONGJMP=wasm` (+47 bytes of - wasm, -746 bytes of glue JS, and *measured* 30-45% faster `pcall`/`error`/yield paths on its - own) the interpreter runs under `WebAssembly.promising`, and an await anywhere, including - across C boundaries and inside coroutines nobody drives, simply suspends the wasm stack. - *Measured*: a suspension costs 0.3-1.6 µs depending on the stack strategy versus 6 µs for - today's coroutine round trip; CPU-bound code is unaffected; 1000 parked runs cost ~4 MB, the - same as today. Two things make it work in this codebase: a C-side trampoline that calls a plain - import first and a `Suspending` import only when suspension is allowed, and saving each run's - slice of the linear-memory C stack across a suspension (without that, interleaved runs corrupt - each other; both *measured*). See §6 for the full numbers. - -JSPI is in Chrome/Edge 137+, Firefox 153+, Node 25+ (Node 24 only behind a flag) and not in -Safari, so the scheduler layer stays the contract and JSPI is a feature-detected accelerator with -identical observable semantics wherever both can express them. - ---- - -## 1. How it works today - -``` -doString(code) Lua JS function `sleep` - │ newAnchoredThread + load │ │ - │ thread.run() ── lua_resume ────────► │ sleep(10):await() │ - │ │ └► promise ext `await`: │ - │ │ pendingAwaits[L] = {…} │ - │ │ push(promise) │ - │ │ lua_yieldk(L, 1, 0, k) ─────┼──► longjmp → JS exception - │ ◄── LUA_YIELD, 1 value ──────────────┘ │ (EmscriptenEH, rethrown) - │ getValue(-1); isPromise? await it │ - │ else: setImmediate / setTimeout(0) │ - │ lua_resume(L, 0) ──────────────────► │ continuation k: │ - │ │ result ready? push, return 1 │ - │ │ not ready? lua_yieldk again │ - │ ◄── LUA_OK ── getStackValues() │ │ -``` - -Relevant code: `Thread.run` (`src/thread.ts:158`), the promise extension -(`src/type-extensions/promise.ts`), `FunctionTypeExtension.getValue` which calls Lua from JS -with a synchronous `lua_pcallk` (`src/type-extensions/function.ts:191`), and the limit hook -(`src/thread.ts` `applyHook`/`limitReached`). - -Properties of this model: - -- The *only* way to park is `lua_yieldk` on the coroutine `run()` is driving. Anything that is - not that coroutine, or has a C frame between it and the await, cannot park. -- The host decides what a yield *means* by looking at the last yielded value. Await and - "cooperative time slice" share one channel; user yields have no channel at all. -- JS→Lua calls are always synchronous. The callback runs on a pooled thread under `lua_pcallk` - and a yield is an error. -- Awaits inside a coroutine that Lua code resumes (not the host) work by *polling*: the - continuation re-yields with zero values until the promise has settled, and the resumer has to - `coroutine.yield()` to the host between attempts (see the README workaround). -- Limits are checked by the debug hook while Lua runs and by `run()` around yields only. - -## 2. What is wrong (all *measured*, `experiments/current-behavior.mjs`) - -| # | Behaviour | Result today | -|---|---|---| -| 1 | `coroutine.yield(io.stdout)` at top level of `doString` | throws `TypeError: the Lua type 'userdata' with metatable 'FILE*' has no JS representation`. `run()` calls `getValue(-1)` on whatever the script yielded. | -| 2 | `local a, b = coroutine.yield(1, 2)` at top level | `a`, `b` are nil. Values are popped and discarded, resume passes nothing back. | -| 3 | `:await()` inside a `table.sort` comparator or a `gsub` callback | `cannot await in a thread that cannot yield, use doString instead of doStringSync`. Wrong diagnosis: we *are* in `doString`, this is a C-call boundary. | -| 4 | `:await()` inside `promise:next(function() ... end)` | same error. The callback is entered from JS via `lua_pcallk`. | -| 5 | JS calls a Lua function that awaits (`state.get('f')(2)`) | same error. No way to get a promise back. | -| 6 | `while not flag() do Promise.resolve(1):await() end` with a 5 ms timer setting `flag` | 20 000 iterations, timer never fires. Resumes are microtasks with no macrotask boundary. | -| 7 | `sleep(300):await()` with `{ signal }` aborted at 10 ms, or `{ timeout: 10 }` | rejects after **301 ms**. Limits are only observed after the promise settles. | -| 8 | 200 bare `coroutine.yield()` round trips | 6 ms in Node. In browsers `setTimeout(0)` is clamped to 4 ms when nested, so the same script takes ~800 ms. | -| 9 | Cost of one await round trip on an already settled promise | ~6 µs (10k in 59 ms): two `lua_resume` calls, a longjmp through a JS exception, a Map lookup, a promise `then`. | -| 10 | Nested `coroutine.resume(co)` where `co` awaits | returns `true` immediately with the promise as its value; the caller must poll. Also `pendingAwaits` keeps the record until the state closes if `co` is never resumed again (documented leak, `promise.ts:141`). | - -Things that do work and should keep working: awaits inside `pcall`, inside Lua metamethods -called from Lua (`__index` from Lua code is yieldable in 5.4+), inside Lua iterators, several -host-driven runs interleaving on one state, `Promise.all`, rejection → Lua error and back. - -Smaller structural issues worth fixing while there: - -- `pendingInterrupt` lives on the root thread and every `resume()` clears it, so two interleaved - runs can clobber each other's interrupt (safe today only because hook → `lua_error` → - `assertOk` never crosses an await). -- `stateToThread` allocates a fresh `Thread` for every callback made from a coroutine the JS side - has not seen before. -- Every `lua_yieldk` from a C function longjmps, which under `SUPPORT_LONGJMP=emscripten` is a JS - exception plus the `isEmscriptenUnwind` brand hack in `rolldown.config.ts`. - -## 3. Constraints - -- **Size and speed budget.** `glue.wasm` is 192,923 bytes after a long flag sweep; the JS bundle - was cut to ~98 KB. Asyncify would roughly double the wasm and slow the interpreter by tens of - percent, so it is out. -- **Targets.** `browserslist`: Chrome ≥134, Firefox ≥138, Safari ≥26; `engines`: Node ≥24. JSPI - coverage today: Chrome/Edge 137+, Firefox 153+, Node 25+ by default (`--experimental-wasm-jspi` - on Node 24), Safari none. Any design needs a non-JSPI path with the same API. -- **One wasm instance, many states, one linear-memory C stack.** Everything that suspends shares - the 1 MB Emscripten stack. This is the one place JSPI needs help (section 5.4). -- **Lua's own rules stay.** A `lua_State` cannot be entered twice concurrently (*measured*: two - promising `lua_pcallk` on the same thread → `memory access out of bounds`), so every run still - needs its own coroutine, as `callByteCode` already does. - -## 4. Options considered - -**A. Asyncify.** Solves the C-boundary problem by rewriting the wasm. Rejected on size and speed, -and it still allows only one in-flight suspension per instance. - -**B. Keep `lua_yieldk`, fix the scheduler.** No wasm change. Fixes 1, 2, 4, 5, 6, 7, 8, 10 and the -misleading message in 3. Does *not* fix 3 itself (C-call boundary) and cannot make an await inside -a Lua-resumed coroutine transparent. Needed regardless as the fallback. - -**C. JSPI.** Fixes everything in the table including 3, and awaits inside Lua-resumed coroutines -become transparent (the resumer simply waits). *Measured* on a `-sSUPPORT_LONGJMP=wasm` build, -raw glue, Node 26 (`experiments/jspi-raw.mjs`): - -| Measurement | Result | -|---|---| -| await inside `table.sort` comparator, `gsub` callback, `coroutine.wrap` body | all work | -| Lua `error()` after a suspension, `lua_error` from a suspended import | caught by `pcall` correctly | -| `coroutine.yield` alongside JSPI | works | -| Suspending import called while **not** under `promising` | traps `trying to suspend without WebAssembly.promising` **even when it does not return a promise** | -| Suspending import called with a JS `invoke_*` longjmp trampoline on the stack (today's build) | traps `trying to suspend JS frames` | -| 10k `lua_pcallk` round trips, sync vs `promising` | 17.2 ms vs 39.3 ms (+2.2 µs per entry) | -| 100k imports that never suspend, plain vs `Suspending` | 4.1 ms vs 13.1 ms (+0.09 µs per call) | -| 10k suspensions on an already settled promise | 2.6 ms (0.26 µs each; today 6 µs) | -| 200k-element `table.sort`, sync vs `promising` | 100 ms vs 91 ms (noise) | -| wasm size, `SUPPORT_LONGJMP=emscripten` → `wasm` | 192,923 → 192,970 bytes; glue JS 87,012 → 86,266 | -| 100k `pcall(f)` without error, same switch | 12.2 ms → 6.8 ms | -| 100k `pcall(error, "x")`, same switch | 136 ms → 87 ms | -| 100k Lua-only `coroutine.yield`/resume, same switch | 97 ms → 65 ms | -| 100k `lua_yieldk` / `lua_error` from a JS function, same switch | 115 → 83 ms / 145 → 103 ms | -| heapsort.lua, same switch | 13.4 ms → 13.5 ms | - -Two concurrent runs on different states interleaving deep C recursion (`pcall` + `gsub` buffers) -across suspensions **corrupt each other** unless the linear-memory stack is managed: a Lua longjmp -escapes as a raw `WebAssembly.Exception`, then `C stack overflow`, then `memory access out of -bounds` (`experiments/jspi-stack.mjs`, unmanaged). With the management described in 5.4 the same -test passes every round. Pyodide documents the same problem and fix for CPython -(blog.pyodide.org, "Integrating JSPI with the WebAssembly C Runtime"). - -**Recommendation: B as the contract, C as the engine when present.** The visible API is defined -by B; C removes B's remaining limitations where the platform allows and is detected at load. - -## 5. Proposed architecture - -### 5.1 The run - -```ts -/** One asynchronous entry into Lua. Owned by the scheduler, never exposed as is. */ -interface Run { - thread: Thread // its own coroutine (lua_newthread), anchored in the registry - limits: LuaThreadLimits // deadline, budget, signal; replaces the root pendingInterrupt slot - settle: Deferred - parked?: Parked // what it is waiting on, if anything - onYield?: (values: MultiReturn) => unknown | Promise -} -``` - -`doString`, `doFile`, `Thread.run` and (new) asynchronous Lua function calls all create a run. -Sync entry points (`doStringSync`, `call`, `runSync`) do not; they increment a module-wide -`syncDepth` counter for the duration of the call (see 5.3). - -### 5.2 One suspender interface, two engines - -```ts -interface Suspender { - /** Called by the promise extension from inside a Lua→JS call. Must not return normally - * unless it has a value to hand back. */ - park(thread: Thread, promise: PromiseLike): number // returns a Lua result count - /** Drives a run to completion. */ - drive(run: Run, argCount: number): Promise -} -``` - -**YieldSuspender (fallback, today's mechanism cleaned up).** - -- `park`: refuses unless `lua_isyieldable`; records `{ promise }` on the run (or, for a coroutine - Lua code is resuming, in an ephemeron-keyed registry table, see 5.6); yields **two** values: - the module's await token (a lightuserdata the module owns, like `interruptToken`) and the - promise. Continuation `k` is one shared function pointer as now. -- `drive`: `lua_resume` loop. On `LUA_YIELD`: if slot `-2` is the await token (pointer compare, no - `getValue` on user values) → await the promise, resume; otherwise it is a **host yield** → - hand `getStackValues` to `run.onYield`, resume with whatever it returns (awaited if a promise). - Default `onYield` is "give the event loop a turn and resume with nothing", which is today's - behaviour minus the discarded values bug. -- Resume happens in the promise's own microtask. A per-run counter forces a macrotask boundary - after N consecutive microtask resumes (or after T ms of continuous running), which fixes #6 - without paying a macrotask per await. -- Macrotask = `scheduler.yield()` if present, else `MessageChannel` (no 4 ms clamp), else - `setImmediate`/`setTimeout`. Fixes #8. - -**JspiSuspender.** - -- Enabled when `typeof WebAssembly.Suspending === 'function'` *and* the glue was built with - `SUPPORT_LONGJMP=wasm`. `drive` calls `promising(lua_resume)`; host yields work exactly as - above, so the run loop is shared. -- `park` never yields; it returns a marker that tells the C trampoline (5.3) to call the - `Suspending` import, which returns the promise and lets the VM switch stacks. -- Nothing is recorded anywhere: the pending state *is* the suspended wasm stack. #10's leak and - the polling protocol disappear, and an await inside a coroutine that Lua resumes just makes the - resumer wait, which is what users expect. The README polling pattern keeps working unchanged - (the loop observes the coroutine finishing). - -### 5.3 The C trampoline, and when suspension is allowed - -Today each JS function is a C closure whose C function is an `addFunction` trampoline -(`functionWrapper`). Two facts from the measurements shape the replacement: a `Suspending` import -traps whenever it is reached outside a `promising` call, and it traps if a JS frame sits between -it and the `promising` boundary. So the decision to suspend has to be taken *before* touching the -`Suspending` import, and from a wasm frame. - -```c -/* src/native/wasmoon.c */ -extern int wasmoon_call(lua_State *L); /* plain import: runs the JS function */ -extern int wasmoon_await(lua_State *L); /* Suspending import: returns the stashed promise */ - -static int wasmoon_jsfunction(lua_State *L) { - int n = wasmoon_call(L); /* >= 0: results pushed; -1: a promise is pending */ - if (n == -1) n = wasmoon_await(L); /* wasm frame → import, no JS in between */ - return n; -} -``` - -`wasmoon_call` is today's `functionWrapper` body plus the promise extension's `await`, and ends -with one decision: - -| Situation | `wasmoon_call` does | -|---|---| -| result is not an await request | push results, return count (unchanged) | -| `:await()` and `syncDepth === 0` and JSPI engine | stash the promise, return -1 → VM suspends | -| `:await()` and `syncDepth > 0` (a sync entry point is on the JS stack) or no JSPI | `YieldSuspender.park` if `lua_isyieldable`, else the error, now worded "cannot await here: a synchronous call is on the stack" / "…across a C-call boundary" | - -`syncDepth` is exact because resumptions only ever happen from an empty JS stack (promise -reactions are microtasks), and a sync entry point cannot yield to the event loop. The one edge, a -run *started* from inside a sync callback, degrades to the yield path, which is correct. - -Both imports are provided through Emscripten's `instantiateWasm` hook so `wasmoon_await` can be -wrapped in `WebAssembly.Suspending` when available and be a plain never-called stub otherwise; no -`-sJSPI` flag, no Asyncify glue. `addFunction` stays for user-registered raw C functions and the -hook; the per-state trampoline pool becomes one C function with the JS reference in an upvalue, -as today. - -### 5.4 Linear-memory stack management (JSPI only) - -JSPI switches the wasm stack, not the `__stack_pointer` global or the memory it points at. When a -resumed run returns through a frame (which restores `__stack_pointer` to that frame's entry) and -then pushes new frames, it writes over any other suspended run's frames below. *Measured*: a Lua -longjmp escapes as a raw `WebAssembly.Exception`, then `C stack overflow`, then `memory access out -of bounds`; the pointer also drifts down 224 bytes per interleaving. Pyodide hit and documented the -same thing for CPython. - -Two strategies were measured (`experiments/jspi-modes.mjs`); both pass the interleaving stress and -the nested-start case (a run started from inside another run's JS callback): - -| | **copy** (recommended) | **region** | -|---|---|---| -| Mechanism | on suspension copy `[sp, mainSP)` to a JS buffer and set SP back; before resuming copy it back and restore `sp`. The promising wrapper restores its own entry SP after the call returns. | `malloc` a 256 KB region per promising run, set SP to its top; the suspension saves/restores SP. | -| Suspension on a settled promise | 1.6 µs | 0.5 µs | -| Suspension 30 `pcall` levels deep (~30 KB of C frames) | 3.9 µs | 0.5 µs | -| 1000 parked runs | rss +4.4 MB, wasm memory +0 | rss +224 MB, wasm memory +247 MB | -| Bytes copied per suspension in the stress test | 23 KB avg | 0 | - -Copy is Pyodide's "simplest fix" and is what the numbers favour: parked runs are the common -steady state for anything event driven, and a suspension is still 4x cheaper than today's round -trip in the worst case measured. Worst-case slice size is bounded by Lua's own C-call limit: -*measured* 108 KB (nested `gsub` to the limit), 45 KB (nested `pcall`), 22 KB (`table.sort` -comparators). Follow-ups if the copy ever shows up in a profile: copy `[sp, entrySP)` instead of -up to the main top (needs the run's entry SP, i.e. run tracking), and pool the buffers by size -class instead of `slice`. - -Why copying back stale bytes over another run's range is safe: a resume only ever happens from an -empty JS stack, at which point every other run is either finished or suspended and therefore -holding its own copy, which it restores on its own resume. Sync entry points push below whatever -the current SP is and finish before anything can resume. - -### 5.5 JS→Lua calls become sync-or-promise - -`getValue` for a function returns a callable that: - -1. acquires a coroutine (pool as today) and runs the function with `lua_resume`, not `lua_pcallk`; -2. if it finishes, returns the value synchronously (unchanged fast path, no promise allocated); -3. if it yields with the await protocol, hands the coroutine to the scheduler as a run and - **returns a Promise**; a host yield inside a callback is an error, as now. - -Under JSPI the same callable still uses `lua_resume` synchronously (a `promising` entry would -cost +2.2 µs on the hot interop path and would *always* return a promise). An await inside it -takes the yield path because `syncDepth > 0`, so `promise:next(function() sleep():await() end)`, -`array:map(luaFn)` with an awaiting `luaFn`, and `await state.get('handler')(req)` all work in -both engines. The footgun ("sometimes a promise") is real but is the only shape that composes with -JS APIs that accept callbacks; `decorate(fn, { call: 'sync' })` can opt a function out (throw on -suspension) and `{ call: 'async' }` can force a promise. - -### 5.6 Cancellation and limits while parked - -- A run's `signal`/`timeout` is raced against every park. On abort the run is resumed with the - interrupt token pushed and `lua_error` (the hook's existing mechanism), so `__close`/to-be-closed - variables run, `pcall` in the script cannot swallow it (token check in `assertOk` as today), and - the coroutine ends in a defined state. Same code path in both engines; in JSPI the resume is - "return from the `Suspending` import, then `lua_error`", never a foreign JS exception thrown - into wasm. The eventual settlement of the abandoned promise is ignored. Fixes #7. -- `pendingInterrupt` moves onto the run. Nested coroutines inherit the hook and report to the - run that owns them (they already inherit the hook function pointer). -- Fallback engine, coroutine resumed by Lua code (not a run): the pending record is keyed in a - registry ephemeron table `{ [thread] = box }` whose box `__gc` drops the JS record, so an - abandoned awaiting coroutine is collected with the thread instead of at `state.close()`. - -### 5.7 Lua-side surface - -- `promise:await()` unchanged. -- `Promise.async(fn, ...)` (inject mode) starts `fn` as its own run and returns a promise. This is - the README workaround implemented in JS with no polling, and the recommended way to fan out. - Works identically in both engines. -- Under the fallback engine, `coroutine.resume(co)` where `co` awaits keeps today's semantics - (yields the promise up; resumer polls). Under JSPI the resumer waits. Documented as "the - fallback is a subset". - -## 6. Performance and memory - -Everything here is *measured* (Node 26.7, `experiments/perf-dist.mjs`, `perf-raw.mjs`, -`jspi-modes.mjs`), best of 5. - -**Hot paths that must not regress** - -| Path | Today | Proposed | Why | -|---|---|---|---| -| Lua→JS function call that does not await | 0.04 µs import | same + one C call | the plain import runs first; the `Suspending` import is only reached when suspension was decided | -| JS→Lua callback (100k calls, pooled thread) | `lua_pcallk` 14.6 ms; through `getValue` wrapper 16.4 ms | `lua_resume` 14.8 ms | same cost; a promise is only allocated when the callback actually suspends | -| CPU-bound Lua (heapsort.lua) | 13.4 ms | 13.5 ms under wasm EH; 91 vs 100 ms for a 200k `table.sort` under `promising` | no Asyncify instrumentation, JSPI is free while not suspending | -| `pcall`, `error`, coroutine yield/resume | see §4 | 30-45% faster | wasm EH replaces the `invoke_*` JS trampolines and JS exceptions | - -**Per-run and per-await costs** - -| | Today | Fallback engine | JSPI engine | -|---|---|---|---| -| Starting a run (`doString('return 1')`) | 4.1 µs | ~same (a `Run` object and a deferred on top) | +2.2 µs for the `promising` entry (39.3 vs 17.2 ms per 10k) | -| Await of a settled promise | 6 µs (two resumes, a JS-exception longjmp, Map lookup) | ~4 µs (wasm-EH longjmp, no Map, starvation counter) | 1.6 µs copy / 0.5 µs region | -| Await 30 C levels deep | error today | error | 3.9 µs copy / 0.5 µs region | -| Bare `coroutine.yield()` round trip | 30 µs Node, ~4 ms browsers | ~µs (`MessageChannel`), no clamp | same loop | -| Resume 1000 parked runs | 2.5 ms | ~same | 0.9 ms | - -**Memory** - -| | Today | Fallback engine | JSPI engine (copy) | JSPI engine (region) | -|---|---|---|---|---| -| 1000 concurrently parked runs | rss +3.8 MB (1.9 MB JS heap; a Lua thread and a pending record each) | ~same, minus the leaked records | rss +4.4 MB (V8 suspended stack ~4-5 KB each, saved slice a few KB) | rss +224 MB | -| Per parked await, steady state | pending record until resume or `state.close()` | pending record until resume, cancel, or the thread's `__gc` | the saved stack slice, freed on resume | the region, freed on completion | -| Abandoned awaiting coroutine | leaks until `state.close()` | collected with the thread (ephemeron) | nothing to leak | nothing to leak | -| Extra bundle | | ~1-2 KB (scheduler) | + a few hundred bytes (wrapper, copy) | | - -Take-aways: the redesign does not touch the interop or interpreter hot paths; awaits get 1.5-10x -cheaper depending on engine; wasm EH is a straight speed win for error handling; and the copy -strategy keeps memory flat in the number of parked runs, which the region strategy does not. - -## 7. API changes (JS) - -| Today | Proposed | Notes | -|---|---|---| -| `doString/doFile` → Promise | unchanged | now a run; abortable while parked | -| `doStringSync/doFileSync` | unchanged | `syncDepth++` around the call | -| `thread.run(argCount, options)` | `+ options.onYield(values) → resume values \| Promise` | top-level `coroutine.yield` becomes a usable host channel; default keeps time-slicing behaviour | -| `thread.runSync`, `thread.call` | unchanged | | -| Lua function from `getValue`: sync, throws on yield | sync result **or** Promise when it suspends | `decorate(fn, { call: 'sync' \| 'async' })` to pin | -| `LuaRunOptions.signal` "observed after the promise settles" | interrupts a parked run immediately | doc change + behaviour | -| `Promise.create/all/resolve` (inject) | `+ Promise.async` | | -| `LuaRuntime.load()` | `+ options.async?: 'auto' \| 'jspi' \| 'yield'` and `runtime.engine` | `'auto'` default; `'yield'` for tests and for diffing behaviour | -| error `cannot await in a thread that cannot yield, use doString instead of doStringSync` | split into "synchronous call on the stack" and "C-call boundary (use the JSPI engine or Promise.async)" | | - -Breaking: (a) callbacks can now return promises; (b) top-level yield values are no longer -discarded; (c) `signal`/`timeout` fire while parked. All three are today's bugs rather than -features, but (a) deserves a major version note. - -## 8. Build changes - -- `-sSUPPORT_LONGJMP=wasm` in `utils/build-wasm.sh`. Required for JSPI (no `invoke_*` JS frames), - +47 bytes wasm, smaller glue, and a native longjmp instead of a JS exception on every - `lua_yieldk`/`lua_error` from a C function. `isEmscriptenUnwind` becomes - `err instanceof WebAssembly.Exception` and the `EmscriptenEH` brand plugin in - `rolldown.config.ts` goes away. All target browsers support wasm EH. -- `src/native/wasmoon.c` gains `wasmoon_jsfunction` and the two imports; the imports are - resolved in `Module.instantiateWasm`. -- No `-sJSPI`, no `-sASYNCIFY`. Feature detection at load, both engines in the bundle (the JSPI - part is a few hundred bytes). - -## 9. Phasing - -1. **Scheduler rewrite (fallback engine only).** `Run`, await token protocol, `onYield`, macrotask - policy, starvation guard, cancellation while parked, per-run interrupt slot, ephemeron for - nested awaits, sync-or-promise callbacks. Ship behind no flag; this is a bugfix release with - one semver-major note. Tests: everything in §2 becomes a test. -2. **`SUPPORT_LONGJMP=wasm` + `wasmoon_jsfunction` in C.** Behaviour-neutral on its own; measure - heapsort and interop benches (memory says the current `-Oz` set wins on heapsort, this flag - was size-neutral in that sweep and was not speed-tested). -3. **JspiSuspender.** `promising(lua_resume)`, stack slice copy (§5.4), `syncDepth` gate, - `Suspending` import via `instantiateWasm`. Gate on the §6 numbers: interop bench unchanged, - heapsort unchanged, 1000 parked runs under 10 MB. Run the whole test suite under `async: 'jspi'` and - `async: 'yield'` on Node ≥25 and browsers; add the interleaving stress from - `experiments/jspi-stack.mjs` as a test. -4. **Docs.** Replace the README "Async/Await" workaround with `Promise.async`, describe the two - engines and the one semantic difference (§5.7). - -## 10. Risks and open questions - -- **Copy cost on deep stacks.** 4 µs at 30 C levels; a pathological script awaiting inside deeply - nested `gsub` callbacks pays ~10 µs per await. Acceptable, and the `[sp, entrySP)` follow-up - halves it. -- **`stackRestore` interaction with Emscripten internals.** `stringToUTF8OnStack`/`withCString` - use the C stack; they must not straddle a park. Today `pushValue` never does, keep it that way. -- **JSPI and the debug hook.** Untested: a hook that fires and `lua_error`s while another run is - suspended. Should be fine (same thread only), needs a test. -- **Firefox/Safari fallback fidelity.** The C-call-boundary case stays an error on Safari and - Firefox <153. Message must point at `Promise.async` or restructuring. -- **Same-function two trampolines?** Not needed: one C function, decision at call time. Verify - `lua_pushcclosure` with a real C function (not `addFunction`) does not change `getReferenceBox` - upvalue handling. -- **Name of `Promise.async` / `decorate` options.** Bikeshed. - -## Appendix: experiments - -All in `experiments/`, run from the repo root. - -- `current-behavior.mjs`: the table in §2 against `dist/`. -- `build-wasm-eh.sh`: the build script with `-sSUPPORT_LONGJMP=wasm`, output to `/out`; run via - `podman run --rm -v "$PWD:/wasmoon" -v "$OUT:/out" docker.io/emscripten/emsdk /out/build-wasm-eh.sh`. -- `jspi-raw.mjs `: JSPI feature and timing matrix (§4 C) against the raw glue. -- `jspi-sp.mjs `: prints `__stack_pointer` around suspensions (shows the drift). -- `jspi-stack.mjs [mitigate]`: the interleaving stress; fails without `mitigate`, passes - with it. -- `jspi-modes.mjs `: the two stack strategies of §5.4 against the - stress, the nested start, suspension timings and memory for 1000 parked runs. Run with - `--expose-gc`. -- `perf-raw.mjs [jspi]`: heapsort, `pcall`/`error`/yield throughput, worst-case C stack - depth; with `jspi`, memory and entry costs. Run on both glues to get the wasm EH comparison. -- `perf-dist.mjs`: today's callback call cost and parked-run memory against `dist/`. diff --git a/docs/async-redesign/experiments/build-wasm-eh.sh b/docs/async-redesign/experiments/build-wasm-eh.sh deleted file mode 100755 index 3a2ffef..0000000 --- a/docs/async-redesign/experiments/build-wasm-eh.sh +++ /dev/null @@ -1,222 +0,0 @@ -#!/bin/bash -e -cd /wasmoon/utils -true - -LUA_SRC=$(ls ../lua/*.c | grep -v "luac.c" | grep -v "lua.c" | tr "\n" " ") - -# Do not add --closure here: it renames properties, which would strip the brand the JS build puts on -# the glue's longjmp unwind classes (see rolldown.config.ts) and turn every unwind into a Lua error. -if [ "$1" == "dev" ]; -then - extension=(-O0 -g3 -s ASSERTIONS=1 -s SAFE_HEAP=1 -s STACK_OVERFLOW_CHECK=2) -else - extension=(-Oz -fno-inline-functions -DLUA_USE_JUMPTABLE=0 -s BINARYEN_EXTRA_PASSES=gufa-optimizing,converge) -fi - -# Everything that is not about the filesystem, shared by both glues below so they can share one -# `glue.wasm`. -COMMON=( - -s WASM=1 - -s SUPPORT_LONGJMP=wasm - "${extension[@]}" - -s EXPORTED_RUNTIME_METHODS="[ - 'addFunction', \ - 'removeFunction', \ - 'FS', \ - 'PATH', \ - 'ENV', \ - 'getValue', \ - 'setValue', \ - 'lengthBytesUTF8', \ - 'stringToUTF8', \ - 'stringToNewUTF8', \ - 'stringToUTF8OnStack', \ - 'stackSave', \ - 'stackRestore', \ - 'UTF8ToString', \ - 'HEAPU8', \ - 'HEAPU32' - ]" - -s DEFAULT_LIBRARY_FUNCS_TO_INCLUDE="[ - '\$FS_mkdirTree', \ - '\$PATH', \ - '\$PATH_FS' - ]" - -s INCOMING_MODULE_JS_API="[ - 'locateFile', \ - 'preRun', \ - 'print', \ - 'printErr' \ - ]" - -s MODULARIZE=1 - -s ALLOW_TABLE_GROWTH=1 - -s EXPORT_NAME="initWasmModule" - -s ALLOW_MEMORY_GROWTH=1 - -s STRICT=1 - -s EXPORT_ES6=1 - -s MALLOC=emmalloc - -s STACK_SIZE=1MB - -s WASM_BIGINT - -s EXPORTED_FUNCTIONS="[ - '_malloc', \ - '_free', \ - '_realloc', \ - '_luaL_checkversion_', \ - '_luaL_getmetafield', \ - '_luaL_callmeta', \ - '_luaL_tolstring', \ - '_luaL_argerror', \ - '_luaL_typeerror', \ - '_luaL_checklstring', \ - '_luaL_optlstring', \ - '_luaL_checknumber', \ - '_luaL_optnumber', \ - '_luaL_checkinteger', \ - '_luaL_optinteger', \ - '_luaL_checkstack', \ - '_luaL_checktype', \ - '_luaL_checkany', \ - '_luaL_newmetatable', \ - '_luaL_setmetatable', \ - '_luaL_testudata', \ - '_luaL_checkudata', \ - '_luaL_where', \ - '_luaL_fileresult', \ - '_luaL_execresult', \ - '_luaL_ref', \ - '_luaL_unref', \ - '_luaL_loadfilex', \ - '_luaL_loadbufferx', \ - '_luaL_loadstring', \ - '_luaL_newstate', \ - '_luaL_len', \ - '_luaL_addgsub', \ - '_luaL_gsub', \ - '_luaL_setfuncs', \ - '_luaL_getsubtable', \ - '_luaL_traceback', \ - '_luaL_requiref', \ - '_luaL_buffinit', \ - '_luaL_prepbuffsize', \ - '_luaL_addlstring', \ - '_luaL_addstring', \ - '_luaL_addvalue', \ - '_luaL_pushresult', \ - '_luaL_pushresultsize', \ - '_luaL_buffinitsize', \ - '_lua_newstate', \ - '_lua_close', \ - '_lua_newthread', \ - '_lua_closethread', \ - '_lua_atpanic', \ - '_lua_version', \ - '_lua_absindex', \ - '_lua_gettop', \ - '_lua_settop', \ - '_lua_pushvalue', \ - '_lua_rotate', \ - '_lua_copy', \ - '_lua_checkstack', \ - '_lua_xmove', \ - '_lua_isnumber', \ - '_lua_isstring', \ - '_lua_iscfunction', \ - '_lua_isinteger', \ - '_lua_isuserdata', \ - '_lua_type', \ - '_lua_typename', \ - '_lua_tonumberx', \ - '_lua_tointegerx', \ - '_lua_toboolean', \ - '_lua_tolstring', \ - '_lua_rawlen', \ - '_lua_tocfunction', \ - '_lua_touserdata', \ - '_lua_tothread', \ - '_lua_topointer', \ - '_lua_arith', \ - '_lua_rawequal', \ - '_lua_compare', \ - '_lua_pushnil', \ - '_lua_pushnumber', \ - '_lua_pushinteger', \ - '_lua_pushlstring', \ - '_lua_pushstring', \ - '_lua_pushcclosure', \ - '_lua_pushboolean', \ - '_lua_pushlightuserdata', \ - '_lua_pushthread', \ - '_lua_getglobal', \ - '_lua_gettable', \ - '_lua_getfield', \ - '_lua_geti', \ - '_lua_rawget', \ - '_lua_rawgeti', \ - '_lua_rawgetp', \ - '_lua_createtable', \ - '_lua_newuserdatauv', \ - '_lua_getmetatable', \ - '_lua_getiuservalue', \ - '_lua_setglobal', \ - '_lua_settable', \ - '_lua_setfield', \ - '_lua_seti', \ - '_lua_rawset', \ - '_lua_rawseti', \ - '_lua_rawsetp', \ - '_lua_setmetatable', \ - '_lua_setiuservalue', \ - '_lua_callk', \ - '_lua_pcallk', \ - '_lua_load', \ - '_lua_dump', \ - '_lua_yieldk', \ - '_lua_resume', \ - '_lua_status', \ - '_lua_isyieldable', \ - '_lua_setwarnf', \ - '_lua_warning', \ - '_lua_error', \ - '_lua_next', \ - '_lua_concat', \ - '_lua_len', \ - '_lua_stringtonumber', \ - '_lua_getallocf', \ - '_lua_setallocf', \ - '_lua_toclose', \ - '_lua_closeslot', \ - '_lua_getstack', \ - '_lua_getinfo', \ - '_lua_getlocal', \ - '_lua_setlocal', \ - '_lua_getupvalue', \ - '_lua_setupvalue', \ - '_lua_upvalueid', \ - '_lua_upvaluejoin', \ - '_lua_sethook', \ - '_lua_gethook', \ - '_lua_gethookmask', \ - '_lua_gethookcount', \ - '_luaopen_base', \ - '_luaopen_coroutine', \ - '_luaopen_table', \ - '_luaopen_io', \ - '_luaopen_os', \ - '_luaopen_string', \ - '_luaopen_utf8', \ - '_luaopen_math', \ - '_luaopen_debug', \ - '_luaopen_package', \ - '_luaL_openselectedlibs', \ - '_lua_gc' \ - ]" -) - -# The default glue, for every environment. Its filesystem is Emscripten's in-memory one, and -# -lnodefs.js adds the NODEFS backend so a host directory can be mounted into it (LuaModuleOptions -# `mounts`). Nothing here reaches the host on its own. -emcc "${COMMON[@]}" \ - -lnodefs.js \ - -s ENVIRONMENT="web,worker,node" \ - -o /out/glue.js \ - ${LUA_SRC} diff --git a/docs/async-redesign/experiments/current-behavior.mjs b/docs/async-redesign/experiments/current-behavior.mjs deleted file mode 100644 index 4b256c2..0000000 --- a/docs/async-redesign/experiments/current-behavior.mjs +++ /dev/null @@ -1,34 +0,0 @@ -import { LuaRuntime } from '../../../dist/index.js' -const lua = await LuaRuntime.load() -const state = lua.createState({ inject: true }) -state.set('sleep', (ms) => new Promise((r) => setTimeout(r, ms))) -const probe = async (name, code, opts) => { - const t = Date.now() - try { const r = await state.doString(code, opts); console.log(`[${name}] ok ->`, r, `${Date.now()-t}ms`) } - catch (e) { console.log(`[${name}] ERR ->`, String(e.message).split('\n')[0], `${Date.now()-t}ms`) } -} -await probe('top-level yield of unrepresentable value', `coroutine.yield(io.stdout) return 1`) -await probe('top-level yield values discarded', `local a, b = coroutine.yield(1, 2) return a, b`) -await probe('await inside table.sort comparator', `local t = {3,2,1} table.sort(t, function(a,b) sleep(1):await() return a', await state.get('callback')(2)) } catch (e) { console.log('[JS calls Lua fn that awaits] ERR ->', e.message.split('\n')[0]) } -let fired = false; setTimeout(() => { fired = true }, 5) -state.set('fired', () => fired) -await probe('resolved await loop starves timers? (cap 20000 iterations)', `local n=0 while not fired() and n < 20000 do Promise.resolve(1):await() n=n+1 end return n, fired()`) -await probe('200 bare coroutine.yield() round trips', `for i=1,200 do coroutine.yield() end return 1`) -const ac = new AbortController(); setTimeout(() => ac.abort(), 10) -await probe('abort while parked on 300ms sleep', `sleep(300):await() return 1`, { signal: ac.signal }) -await probe('timeout 10ms while parked on 300ms sleep', `sleep(300):await() return 1`, { timeout: 10 }) -const t0 = Date.now() -const rs = await Promise.all([1,2,3].map(i => state.doString(`sleep(30):await() return ${i}`))) -console.log('[3 concurrent doString on one state] ->', rs, `${Date.now()-t0}ms`) -await probe('nested coroutine.resume of awaiting coroutine, no polling', `local co = coroutine.create(function() sleep(1):await() return 3 end) local ok, v = coroutine.resume(co) return ok, tostring(v), coroutine.status(co)`) -// cost of one await round trip on an already-resolved promise -await probe('10000 awaits of resolved promise (timing)', `local p = Promise.resolve(1) for i=1,10000 do p:await() end return 1`) -state.close() diff --git a/docs/async-redesign/experiments/jspi-modes.mjs b/docs/async-redesign/experiments/jspi-modes.mjs deleted file mode 100644 index f0e46bb..0000000 --- a/docs/async-redesign/experiments/jspi-modes.mjs +++ /dev/null @@ -1,98 +0,0 @@ -// Compares three ways of handling the linear-memory C stack under JSPI: -// none : nothing (known to corrupt) -// region : a malloc'd stack region per promising run, SP saved/restored around each suspension -// copy : shared stack; on suspension copy out [sp, mainSP) and restore it before resuming -// Usage: node jspi-modes.mjs -const mode = process.argv[3] -const { default: init } = await import(process.argv[2]) -const M = await init({}) -const sleep = (ms) => new Promise((r) => setTimeout(r, ms)) -const cstr = (s) => M.stringToNewUTF8(s) -const tostr = (L, i) => M.UTF8ToString(M._lua_tolstring(L, i, 0)) -const newState = () => { const L = M._luaL_newstate(); M._luaL_openselectedlibs(L, 0xffff, 0); return L } -const load = (L, code) => { const p = cstr(code); const st = M._luaL_loadbufferx(L, p, M.lengthBytesUTF8(code), p, 0); M._free(p); if (st) throw new Error('load: ' + tostr(L, -1)) } -const pcallRaw = WebAssembly.promising(M._lua_pcallk) -const REGION = 256 * 1024 -const mainSP = M.stackSave() -let copiedBytes = 0, suspensions = 0 -const pcallAsync = async (L, ...args) => { - if (mode === 'copy') { - // Restore whatever SP the caller had, so a run started from inside an active run's callback - // hands the stack back to that run when it completes or first suspends. - const entry = M.stackSave() - const p = pcallRaw(L, ...args); M.stackRestore(entry); return p - } - if (mode !== 'region') return pcallRaw(L, ...args) - const region = M._malloc(REGION) - M.stackRestore(region + REGION) - try { const p = pcallRaw(L, ...args); M.stackRestore(mainSP); return await p } - finally { M.stackRestore(mainSP); M._free(region) } -} -const suspending = (fn) => new WebAssembly.Suspending( - mode === 'region' ? async (...args) => { const sp = M.stackSave(); try { return await fn(...args) } finally { M.stackRestore(sp) } } - : mode === 'copy' ? async (...args) => { - const sp = M.stackSave() - const saved = M.HEAPU8.slice(sp, mainSP) // the frames this run needs back - copiedBytes += saved.length; suspensions++ - try { return await fn(...args) } finally { M.HEAPU8.set(saved, sp); M.stackRestore(sp) } - } - : fn) -const run = async (L, code) => { const top = M._lua_gettop(L); load(L, code); const st = await pcallAsync(L, 0, 1, 0, 0, 0); const v = tostr(L, -1); M._lua_settop(L, top); if (st) throw new Error(`status ${st}: ${v}`); return v } -const def = (L, name, ptr) => { M._lua_pushcclosure(L, ptr, 0); const p = cstr(name); M._lua_setglobal(L, p); M._free(p) } -const sleepPtr = M.addFunction(suspending(async (L) => { await sleep(M._lua_tonumberx(L, 1, 0)); M._lua_pushinteger(L, 42n); return 1 }), 'ii') -const microPtr = M.addFunction(suspending(async (L) => { await Promise.resolve(); M._lua_pushinteger(L, 1n); return 1 }), 'ii') -const mk = () => { const L = newState(); def(L, 'jspiSleep', sleepPtr); def(L, 'jspiMicro', microPtr); return L } -const deep = (ms, depth, tag) => ` - local function f(n) - if n == 0 then jspiSleep(${ms}) return "" end - local mine = ("${tag}"):rep(200) .. ("%03d"):format(n) - local inner - local r = (mine):gsub("%d%d%d", function(d) - local ok, v = pcall(function() return f(n - 1) end) - if not ok then error(v, 0) end - inner = v - return d - end, 1) - assert(r == mine, "gsub buffer clobbered at level " .. n) - return inner .. mine - end - local out = f(${depth}) - assert(#out == ${depth} * 203, "result length clobbered") - return "ok"` -const A = mk(), B = mk(), C = mk() -const fmt = (e) => `${e?.constructor?.name}: ${String(e?.message ?? e)}`.slice(0, 120) -console.log(`mode: ${mode}`) -for (let round = 1; round <= 3; round++) { - try { - const r = await Promise.all([ - run(A, `pcall(function() jspiSleep(2) end) ${deep(0, 40, "A")}`), - run(B, deep(30, 40, "B")), - run(C, `for i = 1, 5 do pcall(function() jspiSleep(3) end) ${deep(1, 20, "C")} end return "ok"`), - ]) - console.log(` interleaving round ${round}:`, r.join(',')) - } catch (e) { console.log(` interleaving round ${round}: FAILED:`, fmt(e)) } -} -// Nested start: a run started from inside another run's JS callback while that run is active. -try { - let inner - const startInner = M.addFunction((L) => { inner = run(C, deep(5, 30, "N")); return 0 }, 'ii'); def(A, 'startInner', startInner) - const outer = run(A, `startInner() ${deep(2, 30, "O")}`) - console.log(' nested start:', await outer, await inner) -} catch (e) { console.log(' nested start: FAILED:', fmt(e)) } -console.log(` stack bytes copied per suspension (avg): ${suspensions ? Math.round(copiedBytes / suspensions).toLocaleString() : 'n/a'}`) - -let s = performance.now(); await run(A, `for i=1,10000 do jspiMicro() end`) -console.log(` 10k suspensions on a settled promise: ${(performance.now() - s).toFixed(1)} ms`) -s = performance.now(); await run(A, `local function f(n) if n == 0 then for i=1,2000 do jspiMicro() end return end pcall(f, n-1) end f(30)`) -console.log(` 2k suspensions 30 pcall levels deep: ${(performance.now() - s).toFixed(1)} ms`) - -// Memory for 1000 concurrently parked runs. -let release; const gate = new Promise((r) => { release = r }) -const waitPtr = M.addFunction(suspending(async () => { await gate; return 0 }), 'ii') -const L0 = newState(); M._lua_checkstack(L0, 1100); const threads = [] -for (let i = 0; i < 1000; i++) { const T = M._lua_newthread(L0); def(T, 'wait', waitPtr); threads.push(T) } -global.gc?.(); const before = process.memoryUsage(); const heapBefore = M.HEAPU8.length -const runs = threads.map((T) => { load(T, `wait() return 1`); return pcallAsync(T, 0, 1, 0, 0, 0) }) -global.gc?.(); const during = process.memoryUsage() -console.log(` 1000 parked runs: rss +${((during.rss - before.rss) / 1048576).toFixed(1)} MB, js heap +${((during.heapUsed - before.heapUsed) / 1048576).toFixed(1)} MB, wasm memory +${((M.HEAPU8.length - heapBefore) / 1048576).toFixed(1)} MB`) -s = performance.now(); release(); await Promise.all(runs); console.log(` resume all 1000: ${(performance.now() - s).toFixed(1)} ms`) diff --git a/docs/async-redesign/experiments/jspi-raw.mjs b/docs/async-redesign/experiments/jspi-raw.mjs deleted file mode 100644 index 320a56a..0000000 --- a/docs/async-redesign/experiments/jspi-raw.mjs +++ /dev/null @@ -1,52 +0,0 @@ -// Drives the raw Emscripten glue (no wasmoon TS layer) so it can point at an experimental build. -const glue = process.argv[2] -const { default: init } = await import(glue) -const M = await init({}) -const sleep = (ms) => new Promise((r) => setTimeout(r, ms)) -const cstr = (s) => M.stringToNewUTF8(s) -const tostr = (L, i) => M.UTF8ToString(M._lua_tolstring(L, i, 0)) -const newState = () => { const L = M._luaL_newstate(); M._luaL_openselectedlibs(L, 0xffff, 0); return L } -const load = (L, code) => { const p = cstr(code); const n = M.lengthBytesUTF8(code); const st = M._luaL_loadbufferx(L, p, n, p, 0); M._free(p); if (st) throw new Error('load: ' + tostr(L, -1)) } -const pcallAsync = WebAssembly.promising(M._lua_pcallk) -const run = async (L, code) => { const top = M._lua_gettop(L); load(L, code); const st = await pcallAsync(L, 0, 1, 0, 0, 0); const v = tostr(L, -1); M._lua_settop(L, top); if (st) throw new Error(`status ${st}: ${v}`); return v } -const runSync = (L, code) => { const top = M._lua_gettop(L); load(L, code); const st = M._lua_pcallk(L, 0, 1, 0, 0, 0); const v = tostr(L, -1); M._lua_settop(L, top); if (st) throw new Error(`status ${st}: ${v}`); return v } -const def = (L, name, ptr) => { M._lua_pushcclosure(L, ptr, 0); const p = cstr(name); M._lua_setglobal(L, p); M._free(p) } - -const fns = { - jspiSleep: M.addFunction(new WebAssembly.Suspending(async (L) => { const ms = M._lua_tonumberx(L, 1, 0); await sleep(ms); M._lua_pushinteger(L, 42n); return 1 }), 'ii'), - jspiSync: M.addFunction(new WebAssembly.Suspending((L) => { M._lua_pushinteger(L, 1n); return 1 }), 'ii'), - jspiMicro: M.addFunction(new WebAssembly.Suspending(async (L) => { await Promise.resolve(); M._lua_pushinteger(L, 1n); return 1 }), 'ii'), - jspiThrow: M.addFunction(new WebAssembly.Suspending(async (L) => { await sleep(1); const p = cstr('boom after suspend'); M._lua_pushstring(L, p); M._free(p); return M._lua_error(L) }), 'ii'), - plainFn: M.addFunction((L) => { M._lua_pushinteger(L, 1n); return 1 }, 'ii'), -} -const mk = () => { const L = newState(); for (const [n, p] of Object.entries(fns)) def(L, n, p); return L } -const L1 = mk(), L2 = mk() -const t = async (name, f) => { try { console.log(`[${name}]`, await f()) } catch (e) { console.log(`[${name}] FAILED:`, e.message.split('\n')[0]) } } - -await t('await in C function', () => run(L1, `return jspiSleep(5) * 2`)) -await t('inside table.sort comparator', () => run(L1, `local t={3,2,1} table.sort(t, function(a,b) jspiSleep(1) return a run(L1, `return (("abc"):gsub(".", function(c) jspiSleep(1) return c:upper() end))`)) -await t('inside coroutine, no host yield', () => run(L1, `local co=coroutine.wrap(function() return jspiSleep(1) end) return co()`)) -await t('lua error after suspend is pcall-able', () => run(L1, `local ok, e = pcall(jspiThrow) return tostring(ok) .. " " .. tostring(e)`)) -await t('lua error() after suspend in Lua', () => run(L1, `local ok, e = pcall(function() jspiSleep(1) error("boom") end) return tostring(e)`)) -await t('coroutine.yield still works alongside', () => run(L1, `local co = coroutine.create(function() jspiSleep(1) coroutine.yield(7) return 8 end) local _, a = coroutine.resume(co) local _, b = coroutine.resume(co) return a .. b`)) -await t('sync pcall with a suspending import (expected to fail)', () => runSync(L1, `return jspiSleep(1)`)) -await t('sync pcall with non-suspending Suspending import', () => runSync(L1, `return jspiSync()`)) - -const stress = (L, ms) => run(L, `for i=1,40 do local r = ("x"):rep(64):gsub(".", function() jspiSleep(${ms}) return "y" end) assert(r == ("y"):rep(64), "clobbered") end return "ok"`) -await t('two states interleaving suspended runs (shadow stack)', () => Promise.all([stress(L1, 1), stress(L2, 2)])) -await t('same state, two concurrent promising pcalls', () => Promise.all([stress(L1, 1), stress(L1, 2)])) -// Deep C recursion live across suspensions on both sides. -const deep = (L, ms) => run(L, `local function f(n) if n == 0 then jspiSleep(${ms}) return 0 end return 1 + tonumber(("%d"):format(f(n-1))) end for i=1,20 do assert(f(150) == 150) end return "ok"`) -await t('deep interleaved recursion across suspensions', () => Promise.all([deep(L1, 1), deep(L2, 2)])) - -const time = async (name, f) => { const s = performance.now(); await f(); console.log(` ${name}: ${(performance.now() - s).toFixed(1)} ms`) } -await time('100k Suspending imports that never suspend (promising pcall)', () => run(L1, `for i=1,100000 do jspiSync() end`)) -await time('100k plain imports (promising pcall)', () => run(L1, `for i=1,100000 do plainFn() end`)) -await time('100k plain imports (sync pcall)', async () => runSync(L1, `for i=1,100000 do plainFn() end`)) -await time('10k promising pcall round trips', async () => { for (let i = 0; i < 10000; i++) await run(L1, `return 1`) }) -await time('10k sync pcall round trips', async () => { for (let i = 0; i < 10000; i++) runSync(L1, `return 1`) }) -await time('10k suspensions on resolved promise', () => run(L1, `for i=1,10000 do jspiMicro() end`)) -await time('1k suspensions on setTimeout(0)', () => run(L1, `for i=1,1000 do jspiSleep(0) end`)) -await time('heapsort-ish CPU loop, sync pcall', async () => runSync(L1, `local t={} for i=1,200000 do t[i]=(i*7919)%1000 end table.sort(t)`)) -await time('heapsort-ish CPU loop, promising pcall', () => run(L1, `local t={} for i=1,200000 do t[i]=(i*7919)%1000 end table.sort(t)`)) diff --git a/docs/async-redesign/experiments/jspi-sp.mjs b/docs/async-redesign/experiments/jspi-sp.mjs deleted file mode 100644 index 8c21ef0..0000000 --- a/docs/async-redesign/experiments/jspi-sp.mjs +++ /dev/null @@ -1,23 +0,0 @@ -const { default: init } = await import(process.argv[2]) -const M = await init({}) -const sleep = (ms) => new Promise((r) => setTimeout(r, ms)) -const cstr = (s) => M.stringToNewUTF8(s) -const newState = () => { const L = M._luaL_newstate(); M._luaL_openselectedlibs(L, 0xffff, 0); return L } -const load = (L, code) => { const p = cstr(code); M._luaL_loadbufferx(L, p, M.lengthBytesUTF8(code), p, 0); M._free(p) } -const pcallRaw = WebAssembly.promising(M._lua_pcallk) -const log = (tag) => console.log(tag.padEnd(46), 'SP =', M.stackSave()) -log('main, before anything') -const ptr = M.addFunction(new WebAssembly.Suspending(async (L) => { - const name = M.UTF8ToString(M._lua_tolstring(L, 1, 0)); const ms = M._lua_tonumberx(L, 2, 0) - log(`import entry (${name})`) - await sleep(ms) - log(`import after await, before resume (${name})`) - M._lua_pushinteger(L, 1n); return 1 -}), 'ii') -const def = (L) => { M._lua_pushcclosure(L, ptr, 0); const p = cstr('susp'); M._lua_setglobal(L, p); M._free(p) } -const A = newState(), B = newState(); def(A); def(B) -load(A, `susp("A shallow", 5) local function f(n) if n == 0 then susp("A deep", 5) return end f(n-1) end f(60)`) -load(B, `local function f(n) if n == 0 then susp("B deep", 20) return end f(n-1) end f(60)`) -const pa = pcallRaw(A, 0, 0, 0, 0, 0); log('main, after A suspended') -const pb = pcallRaw(B, 0, 0, 0, 0, 0); log('main, after B suspended') -await Promise.all([pa, pb]); log('main, both done') diff --git a/docs/async-redesign/experiments/jspi-stack.mjs b/docs/async-redesign/experiments/jspi-stack.mjs deleted file mode 100644 index 3ef1e1f..0000000 --- a/docs/async-redesign/experiments/jspi-stack.mjs +++ /dev/null @@ -1,61 +0,0 @@ -// Adversarial for the linear-memory C stack. Lua->Lua calls do not recurse in C, so recursion goes -// through pcall (a lua_longjmp with a setjmp buffer per level on the C stack) and gsub (a -// luaL_Buffer per level), each level verifying its own C-stack data after the inner levels ran. -const mitigate = process.argv[3] === 'mitigate' -const { default: init } = await import(process.argv[2]) -const M = await init({}) -const sleep = (ms) => new Promise((r) => setTimeout(r, ms)) -const cstr = (s) => M.stringToNewUTF8(s) -const tostr = (L, i) => M.UTF8ToString(M._lua_tolstring(L, i, 0)) -const newState = () => { const L = M._luaL_newstate(); M._luaL_openselectedlibs(L, 0xffff, 0); return L } -const load = (L, code) => { const p = cstr(code); const st = M._luaL_loadbufferx(L, p, M.lengthBytesUTF8(code), p, 0); M._free(p); if (st) throw new Error('load: ' + tostr(L, -1)) } -const pcallRaw = WebAssembly.promising(M._lua_pcallk) -const REGION = 256 * 1024 -const mainSP = M.stackSave() -const pcallAsync = async (L, ...args) => { - if (!mitigate) return pcallRaw(L, ...args) - const region = M._malloc(REGION) - M.stackRestore(region + REGION) - try { const p = pcallRaw(L, ...args); M.stackRestore(mainSP); return await p } - finally { M.stackRestore(mainSP); M._free(region) } -} -const suspending = (fn) => new WebAssembly.Suspending(mitigate - ? async (...args) => { const sp = M.stackSave(); try { return await fn(...args) } finally { M.stackRestore(sp) } } - : fn) -const run = async (L, code) => { const top = M._lua_gettop(L); load(L, code); const st = await pcallAsync(L, 0, 1, 0, 0, 0); const v = tostr(L, -1); M._lua_settop(L, top); if (st) throw new Error(`status ${st}: ${v}`); return v } -const def = (L, name, ptr) => { M._lua_pushcclosure(L, ptr, 0); const p = cstr(name); M._lua_setglobal(L, p); M._free(p) } -const sleepPtr = M.addFunction(suspending(async (L) => { const ms = M._lua_tonumberx(L, 1, 0); await sleep(ms); M._lua_pushinteger(L, 42n); return 1 }), 'ii') -const mk = () => { const L = newState(); def(L, 'jspiSleep', sleepPtr); return L } -const deep = (ms, depth, tag) => ` - local function f(n) - if n == 0 then jspiSleep(${ms}) return "" end - local mine = ("${tag}"):rep(200) .. ("%03d"):format(n) - local inner - local r = (mine):gsub("%d%d%d", function(d) - local ok, v = pcall(function() return f(n - 1) end) - if not ok then error(v, 0) end - inner = v - return d - end, 1) - assert(r == mine, "gsub buffer clobbered at level " .. n) - return inner .. mine - end - local out = f(${depth}) - assert(#out == ${depth} * 203, "result length clobbered") - return "ok"` -const A = mk(), B = mk() -for (let round = 1; round <= 3; round++) { - try { - const r = await Promise.all([ - run(A, `pcall(function() jspiSleep(2) end) ${deep(0, 40, "A")}`), // shallow park, then deep C recursion while B is parked - run(B, deep(30, 40, "B")), // deep C recursion, then park for 30ms - ]) - console.log(`round ${round}:`, r) - } catch (e) { console.log(`round ${round}: FAILED:`, `${e?.constructor?.name}: ${String(e?.message ?? e)}`.slice(0, 160)) } -} -try { - // Single run: park deep, and while parked let the main JS thread make deep sync calls. - const parked = run(A, deep(20, 40, "A")) - load(B, deep(0, 40, "B").replace('jspiSleep(0)', '')); const st = M._lua_pcallk(B, 0, 1, 0, 0, 0); const v = tostr(B, -1); M._lua_settop(B, 0) - console.log('deep sync call while A parked deep:', st, v, '| A ->', await parked) -} catch (e) { console.log('sync-while-parked FAILED:', `${e?.constructor?.name}: ${String(e?.message ?? e)}`.slice(0, 160)) } diff --git a/docs/async-redesign/experiments/perf-dist.mjs b/docs/async-redesign/experiments/perf-dist.mjs deleted file mode 100644 index 5f089c3..0000000 --- a/docs/async-redesign/experiments/perf-dist.mjs +++ /dev/null @@ -1,25 +0,0 @@ -import { LuaRuntime } from '../../../dist/index.js' -const lua = await LuaRuntime.load() -const M = lua.module -const state = lua.createState({ inject: true }) -const time = (name, f, n = 5) => { let best = Infinity; for (let i = 0; i < n; i++) { const s = performance.now(); f(); best = Math.min(best, performance.now() - s) } console.log(` ${name}: ${best.toFixed(1)} ms (best of ${n})`) } - -console.log('== callbacks: lua_pcallk vs lua_resume on a pooled thread ==') -state.doStringSync('function f(x) return x + 1 end') -const T = state.newThread() -const N = 100000 -time(`${N} lua_pcallk calls`, () => { for (let i = 0; i < N; i++) { M.lua_getglobal(T.address, 'f'); M.lua_pushinteger(T.address, i); M.lua_pcallk(T.address, 1, 1, 0, 0, null); M.lua_settop(T.address, 0) } }) -time(`${N} lua_resume calls`, () => { for (let i = 0; i < N; i++) { M.lua_getglobal(T.address, 'f'); M.lua_pushinteger(T.address, i); M.lua_resume(T.address, null, 1, M.resultCountScratch); M.lua_settop(T.address, 0) } }) -const jsF = state.get('f') -time(`${N} calls through today's getValue wrapper`, () => { for (let i = 0; i < N; i++) jsF(i) }) - -console.log('== today: memory for 1000 concurrently parked doString awaits ==') -let release; const gate = new Promise((r) => { release = r }) -state.set('wait', () => gate) -global.gc?.(); const before = process.memoryUsage(); const heapBefore = M.emscripten.HEAPU8.length -const runs = []; for (let i = 0; i < 1000; i++) runs.push(state.doString('wait():await() return 1')) -await new Promise((r) => setTimeout(r, 20)); global.gc?.(); const during = process.memoryUsage() -console.log(` 1000 parked runs: rss +${((during.rss - before.rss) / 1048576).toFixed(1)} MB, js heap +${((during.heapUsed - before.heapUsed) / 1048576).toFixed(1)} MB, wasm memory grew ${(M.emscripten.HEAPU8.length - heapBefore) / 1048576} MB`) -const s = performance.now(); release(); await Promise.all(runs); console.log(` resuming all 1000: ${(performance.now() - s).toFixed(1)} ms`) -time('1000 doString of "return 1" (run setup cost today)', () => { const ps = []; for (let i = 0; i < 1000; i++) ps.push(state.doString('return 1')) }, 3) -state.close() diff --git a/docs/async-redesign/experiments/perf-raw.mjs b/docs/async-redesign/experiments/perf-raw.mjs deleted file mode 100644 index bccbb3f..0000000 --- a/docs/async-redesign/experiments/perf-raw.mjs +++ /dev/null @@ -1,60 +0,0 @@ -// Raw-glue measurements. Usage: node perf-raw.mjs [jspi] -const { default: init } = await import(process.argv[2]) -const jspi = process.argv[3] === 'jspi' -const M = await init({}) -const cstr = (s) => M.stringToNewUTF8(s) -const tostr = (L, i) => M.UTF8ToString(M._lua_tolstring(L, i, 0)) -const L = M._luaL_newstate(); M._luaL_openselectedlibs(L, 0xffff, 0) -const load = (T, code) => { const p = cstr(code); const st = M._luaL_loadbufferx(T, p, M.lengthBytesUTF8(code), p, 0); M._free(p); if (st) throw new Error('load: ' + tostr(T, -1)) } -const runSync = (T, code) => { const top = M._lua_gettop(T); load(T, code); const st = M._lua_pcallk(T, 0, 1, 0, 0, 0); const v = tostr(T, -1); M._lua_settop(T, top); if (st) throw new Error(`status ${st}: ${v}`); return v } -const time = (name, f, n = 5) => { let best = Infinity; for (let i = 0; i < n; i++) { const s = performance.now(); f(); best = Math.min(best, performance.now() - s) } console.log(` ${name}: ${best.toFixed(1)} ms (best of ${n})`) } -const heapsort = (await import('node:fs')).readFileSync(new URL('../../../bench/heapsort.lua', import.meta.url), 'utf8') - -console.log('== CPU / error paths ==') -runSync(L, 'hs = (function() ' + heapsort + ' end)()'); time('heapsort.lua', () => runSync(L, 'return hs()')) -time('100k pcall(error) round trips', () => runSync(L, `for i=1,100000 do pcall(error, "x") end`)) -time('100k pcall(f) no error', () => runSync(L, `local f = function() end for i=1,100000 do pcall(f) end`)) -time('100k coroutine.yield/resume (Lua only)', () => runSync(L, `local co = coroutine.wrap(function() while true do coroutine.yield() end end) for i=1,100000 do co() end`)) -// A C function that yields: lua_yieldk from C is a longjmp. Use a JS import that yields. -const yieldPtr = M.addFunction((T) => M._lua_yieldk(T, 0, 0, 0), 'ii') -M._lua_pushcclosure(L, yieldPtr, 0); { const p = cstr('cyield'); M._lua_setglobal(L, p); M._free(p) } -time('100k yields from a C (JS) function via longjmp', () => runSync(L, `local co = coroutine.wrap(function() while true do cyield() end end) for i=1,100000 do co() end`)) -const errPtr = M.addFunction((T) => { const p = cstr('e'); M._lua_pushstring(T, p); M._free(p); return M._lua_error(T) }, 'ii') -M._lua_pushcclosure(L, errPtr, 0); { const p = cstr('cerror'); M._lua_setglobal(L, p); M._free(p) } -time('100k lua_error from a C (JS) function', () => runSync(L, `for i=1,100000 do pcall(cerror) end`)) - -console.log('== C stack depth ==') -const minSP = { v: Infinity } -const probePtr = M.addFunction((T) => { minSP.v = Math.min(minSP.v, M.stackSave()); return 0 }, 'ii') -M._lua_pushcclosure(L, probePtr, 0); { const p = cstr('probe'); M._lua_setglobal(L, p); M._free(p) } -const top = M.stackSave() -for (const [name, code] of [ - ['pcall recursion to the C limit', `local n = 0 local function f() n = n + 1 probe() local ok, e = pcall(f) if not ok and n == 1 then return e end end f() return n`], - ['gsub recursion to the C limit', `local n = 0 local function f() n = n + 1 probe() local ok, e = pcall(function() ("a"):gsub("a", f) end) end f() return n`], - ['string.format/ tostring / sort nesting', `local n = 0 local function f() n = n + 1 probe() pcall(table.sort, {2,1}, function(a,b) f() return a { release = r }) - const waitPtr = M.addFunction(new WebAssembly.Suspending(async (T) => { await gate; return 0 }), 'ii') - const N = 1000 - M._lua_checkstack(L, N + 10); const threads = [] - for (let i = 0; i < N; i++) { const T = M._lua_newthread(L); M._lua_pushcclosure(T, waitPtr, 0); const p = cstr('wait'); M._lua_setglobal(T, p); M._free(p); threads.push(T) } - // threads stay anchored on the main stack - global.gc?.(); const before = process.memoryUsage() - const heapBefore = M.HEAPU8.length - const runs = threads.map((T) => { load(T, `wait() return 1`); return pcallAsync(T, 0, 1, 0, 0, 0) }) - global.gc?.(); const during = process.memoryUsage() - console.log(` ${N} suspended runs: rss +${((during.rss - before.rss) / 1048576).toFixed(1)} MB, js heap +${((during.heapUsed - before.heapUsed) / 1048576).toFixed(1)} MB, external +${((during.external - before.external) / 1048576).toFixed(1)} MB, wasm memory grew ${(M.HEAPU8.length - heapBefore) / 1048576} MB`) - const s = performance.now(); release(); await Promise.all(runs) - console.log(` resuming all ${N}: ${(performance.now() - s).toFixed(1)} ms`) - // Cost of starting a promising run that completes synchronously, vs sync, on a fresh thread each time. - const T = M._lua_newthread(L) - time('10k promising pcall (sync completion) on one thread', () => { for (let i = 0; i < 10000; i++) { load(T, 'return 1'); pcallAsync(T, 0, 1, 0, 0, 0); M._lua_settop(T, 0) } }) - time('10k sync pcall on one thread', () => { for (let i = 0; i < 10000; i++) { load(T, 'return 1'); M._lua_pcallk(T, 0, 1, 0, 0, 0); M._lua_settop(T, 0) } }) - time('10k malloc/free of a 256 KB region', () => { for (let i = 0; i < 10000; i++) M._free(M._malloc(262144)) }) - time('10k malloc/free of a 64 KB region', () => { for (let i = 0; i < 10000; i++) M._free(M._malloc(65536)) }) -} diff --git a/docs/performance/README.md b/docs/performance/README.md deleted file mode 100644 index ef22bc4..0000000 --- a/docs/performance/README.md +++ /dev/null @@ -1,778 +0,0 @@ -# Performance measurements - -2026-09-07, Node 26.7.0, baseline commit `55c7d96`. - -The table push path now creates its registry anchor without retrieving the table -again, initializes tables without a helper closure, and pushes known string keys -directly. Cycles and shared references still use the same registry anchors. - -Build the baseline and preserve its dist directory, then build the candidate. Run: - -```sh -node docs/performance/table-copy.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js -``` - -The harness alternates baseline/candidate order, discards six warmup rounds and -compares medians from eighteen measured rounds. Two runs of the final change: - -| Input | Median time reduction | -| ---------------------------------------------- | --------------------- | -| Empty object, 20,000 pushes | 3.1–3.9% | -| Three-field object, 20,000 pushes | 4.9–5.8% | -| Array of 2,000 three-field objects, 100 pushes | 4.8–4.9% | - -These are local microbenchmarks, not a whole-library speedup claim. - -The emitted index.js shrank from 114,958 to 114,949 bytes; the sum of individually -gzipped published dist files decreased by 5 bytes. Other emitted files were unchanged. - -With `memory: { trace: true }`, GC stopped, and ten pushes of the nested array, -both versions reported 19,265 bytes before, 2,762,186 after, and 44,499 after a full -collection. Both Wasm heaps were 17,891,328 bytes. The change adds no retained JS -data structures and removes a per-table closure; JS heap allocation was not profiled. - -Validation: 391 tests passed, formatting/lint passed, and `git diff --check` passed. -The full tests require browser server and child-process access outside the sandbox. - -## Array reads and Lua calls - -Sequence classification now runs in C, using the same ordered integer-key walk and -empty-table rule. This eliminates per-key Wasm crossings without allocating a -cache or temporary table. The helper uses public Lua APIs and leaves the stack -unchanged. Its raw export is used directly, avoiding a second binding on LuaModule. - -The Lua function wrapper now uses the result count returned by `lua_resume` -instead of calling `lua_gettop` again. No-result calls still return null, and -multiple-result calls still return only the first value. - -```sh -node docs/performance/read-table.mjs /absolute/baseline/dist /absolute/candidate/dist -node docs/performance/call-lua.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js -node --expose-gc docs/performance/retained-memory.mjs /absolute/candidate/dist/index.js -``` - -The isolated classification comparison uses a baseline already containing the -table-push and result-count changes. Two final runs measured 18.6% and 20.4% less -time reading flat 2,000-element arrays. Nested-table reads changed by 0.4–2.1%; -object-table reads ranged from effectively unchanged to 1.1% slower, within the -observed timing variation. The result-count change measured about 2–3% less time -for 100,000 Lua calls with zero, one, or multiple results. - -For all changes together, actual `npm pack` archives compared against `55c7d96`: - -| Measurement | Baseline | Candidate | -| ---------------- | ------------: | ------------: | -| Package archive | 178,091 bytes | 178,086 bytes | -| Unpacked package | 459,197 bytes | 459,181 bytes | - -The native binary grows by 104 bytes, offset by the smaller JavaScript and other -published changes. Summing individually gzipped files is not the same measurement -as the npm archive; the archive above is the package-size check. - -Lua allocation totals matched for flat arrays, nested tables, object tables, and -function calls. Each Wasm heap remained 17,891,328 bytes. Three separate-process -retained-memory runs with 20 live runtimes/states measured about 10.83 MB of JS -heap for the baseline and 9.96 MB for the candidate after forced GC. This is -evidence for the measured workloads, not a guarantee for every application. - -Validation on the final native build: 391 default-engine tests passed; 387 -fallback-engine tests passed with 4 JSPI-only tests skipped; the upstream Lua -suite finished with `final OK !!!`. A deterministic comparison of 2,000 mixed -table shapes matched the baseline and left both stacks empty. Regression coverage -now also includes numeric string, fractional, zero, and negative keys alongside -array entries. Formatting/lint and `git diff --check` passed. - -## Numeric binding setup - -Numeric exports now omit their redundant conversion signatures. The constructor -previously allocated 108 signature arrays and checked each entry before returning -the unchanged Wasm export. Missing-export validation remains, as do string -conversion and integer-range checks. The integer binding helper takes its argument -position directly instead of inferring it from another temporary signature array. - -```sh -node docs/performance/bindings.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js -node --expose-gc docs/performance/runtime.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js -``` - -The isolated baseline includes the earlier table and call optimizations. The first -constructor comparison measured 22.188 ms versus 19.815 ms for 1,000 wrappers, -10.7% less time; an isolated repeat measured 23.043 ms versus 20.057 ms, 13.0% -less time. The harness releases each wrapper's scratch allocations and uses -the yielding engine to avoid installing an await hook per wrapper. Full runtime -load, state creation, script execution, and close measured 24.625 ms versus -24.297 ms per ten runs, only 1.3% less time; Wasm instantiation dominates that -larger operation. These are warm-process measurements, not cold-start claims. - -The combined package now measures 177,862 bytes compressed and 455,691 bytes -unpacked, compared with 178,091 and 459,197 at the original baseline. The binding -change alone removes 3,490 unpacked bytes. Lua allocation totals and Wasm heap -capacity remain equal. A retained-memory comparison with twenty live runtimes -measured 10.57 MB of JS heap before this change and 9.72 MB after; this diagnostic -is sensitive to compilation and GC and is not a universal memory-saving claim. - -All 391 tests, formatting/lint, and `git diff --check` pass after the binding -change. A broader interop sweep reproduced the table-push and Lua-call gains; -number and short-string round trips and `doStringSync` were effectively unchanged. -Callback and proxy timings varied with process order. Paired callback measurements -against the original baseline were 1.5–2.6% slower, despite a separate-process -repeat being effectively unchanged. Against the build immediately before the -binding simplification, callbacks were 1.1% slower and proxy access 0.2% slower. -The paired harness is `docs/performance/callbacks.mjs` and -takes the same two index.js paths as the constructor benchmark. - -A subsequent control compared two byte-identical copies of the pre-callback -experiment build. The second copy measured 2.3% slower for callbacks and 0.9% -slower for proxy access. Thus the small callback difference above does not -establish a code regression; it is comparable to the harness's control variation. -Removing redundant optional chaining did not improve timings and was reverted. - -## Lazy extension identity caches - -Extensions now create their weak Lua identity cache on first access. Table copies -never use it, and other extensions do not need it until a value of their type is -pushed. The protected cache reference remains available through a getter, so -custom extensions reading it still receive an initialized registry reference. - -```sh -node docs/performance/create-state.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js -node docs/performance/cache-memory.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js -``` - -Against the preceding build, two runs measured these reductions in time for -200 state creations and closes: - -| Options | Time reduction | Lua bytes saved per fresh state | -| ---------------- | -------------: | ------------------------------: | -| Defaults | 5.8–9.3% | 392 | -| Object copying | 5.4–6.1% | 392 | -| Injected helpers | 2.4–4.8% | 392 | - -After first pushes of proxies, opaque userdata, promises, and errors, the candidate -still used 152 fewer Lua bytes. Repeated pushes retained Lua identity, and both -stacks were empty. After collection it also retained 152 fewer Lua bytes. Wasm -heap capacity stayed at 17,891,328 bytes. Repeated twenty-runtime JS retained-heap -measurements overlapped at roughly 9.71–9.74 MB; they do not demonstrate a JS heap -reduction. A callback/proxy comparison remained within the identical-build -control variation described above. - -The combined npm archive is now 177,960 bytes, with 455,889 bytes unpacked, both -below the original 178,091/459,197-byte baseline. Lazy initialization itself adds -98 compressed bytes and 198 unpacked bytes compared with the preceding build. -The default-engine suite passes all 391 tests after this change; the fallback -suite passes 387 with 4 JSPI-only tests skipped. Formatting/lint and diff checks pass. - -## Rejected numeric and compiler experiments - -Calling the existing native integer helper directly after `pushValue` validates a -safe integer did not improve the global or callback workloads and made the -isolated push loop roughly 10% slower. The duplicate-check bypass was reverted. -Inserting extensions in priority order instead of re-sorting the small list also -produced no convincing setup improvement and was reverted. - -The VM harness now covers arithmetic, table allocation/traversal, Lua calls, -string formatting/concatenation, and the existing heapsort fixture. It seeds Lua's -random generator equally for reproducible heapsort inputs: - -```sh -node docs/performance/vm.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js -``` - -Compiler experiments retained `-Oz` and the existing Binaryen passes: - -| Change | Wasm size | Outcome | -| ---------------------------- | ------------: | --------------------------------------------------------------- | -| Existing no-inline build | 193,278 bytes | Baseline before the JSPI fix | -| Add LTO, retain no-inline | 193,565 bytes | No overall VM gain; rejected | -| Remove no-inline | 194,056 bytes | Faster arithmetic/calls/heapsort, but async correctness failure | -| Remove no-inline and add LTO | 198,945 bytes | Exceeds the size budget; rejected | - -Default inlining initially looked useful: about 11% faster arithmetic, 6% faster -Lua calls and heapsort, and 1% faster table work, with string formatting about 4% -slower. Its full package still fit below the original size limit. However, the -full suite failed `can interleave many runs with different suspension depths and -settlement orders` with a WebAssembly exception. Running that test alone -reproduced the failure; restoring the previous no-inline artifacts made it pass. -That initial faster but incorrect build was discarded. The investigation and fix -below subsequently made inlining usable; the compiler change had exposed a race -in the library's JSPI stack restoration. - -Reproduction against either build: - -```sh -node_modules/.bin/mocha --exit --require ./test/boot.js test/async.test.js --grep 'different suspension depths' -``` - -## Synchronous JSPI restoration - -The async await hook used to restore a run's linear-memory C stack before resolving -its promise. There is a microtask gap between that resolution and Wasm resumption, -during which another ready run can restore its own frames over the first run's. -Disabling inlining hid the failure in the existing concurrent-depth test, but a -close-during-settlement stress check also made the old no-inline build trap. - -The await hook now returns an integer identifying a ready continuation. A second, -synchronous C hook consumes that continuation and restores the stack immediately -before Lua executes again. A local map holds only ready continuations; entries -are deleted before invocation, including when invocation throws. The synchronous -hook also checks that the state is still open, covering closure during the -promise-resolution gap. Per-await marshalling now uses one outcome callback -instead of four callbacks to offset the new bookkeeping. - -The final compiler configuration uses default `-Oz` inlining, without LTO. The -previously failing concurrent-depth test passes, along with the new close-timing -regression, all 392 default-engine tests, 388 fallback tests (4 JSPI-only skips), -and the upstream Lua suite. Formatting/lint and diff checks pass. - -Against the immediately preceding no-inline build, the VM harness measured: - -| Workload | Change in median time | -| ------------------------------- | --------------------: | -| Arithmetic | 10.6% lower | -| Table allocation/traversal | 1.5% lower | -| Lua calls | 5.6% lower | -| Heapsort | 5.8% lower | -| String formatting/concatenation | 4.2% higher | - -The correctness fix costs time on settled JSPI awaits: two runs of -`bench/async.js` measured 32.8–35.0 ms per 20,000 awaits versus 29.6–30.3 ms before -the fix. This regression is explicit; an unsynchronized restore is not an -acceptable optimization. Further reduction of continuation overhead remains open. - -For 1,000 parked JSPI runs, measured JS heap growth fell from 4,682,456 to -4,520,328 bytes. Saved-stack ArrayBuffer measurements varied between runs (roughly -28–35 KB before and 30–62 KB after), while Lua allocation growth stayed at -1,177,950 bytes. Total sampled memory was lower. The ready-await diagnostic -samples successive microtask boundaries; its largest observed heap-plus-buffer -delta fell from 5,367,528 to 5,204,872 bytes. Individual phases are not equivalent -work-completion points, so they must not be compared as if they were. - -```sh -node --expose-gc bench/async.js /absolute/candidate/dist/index.js -node --expose-gc docs/performance/ready-await-memory.mjs /absolute/candidate/dist/index.js -``` - -Adding `--close-before-resume` to the latter command exercises the closure stress -case that trapped in the previous no-inline build. The fixed build completes it. - -The combined package measures 178,043 bytes compressed and 456,582 unpacked, -still below the original 178,091/459,197-byte baseline. These are measured workload -results, not a claim that every program is faster or uses less memory. - -## Direct awaits and compact outcomes - -The no-limit JSPI path now awaits the user's promise directly and records its -result in a try/catch. This avoids the extra promise and reactions previously -created by `settleOrInterrupt`. Limited runs still use that helper. Both paths -observe settlement before waiting for the already-scheduled fairness pause, so -rejections cannot go unhandled during the pause. Stack restoration and the final -close/deadline check remain in the synchronous resume hook. - -Outcomes now have one `status` discriminator (`fulfilled`, `rejected`, or -`interrupted`) instead of two boolean flags. This reduces outcome size and lets -host-yield error handling combine its two equivalent throw branches. - -```sh -node docs/performance/settled-awaits.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js -``` - -Compared with the preceding synchronized implementation, two isolated alternating -comparisons measured 29.363/28.635 ms and 29.578/28.835 ms for 20,000 settled awaits, -about 2.5% less time. This recovers part of the synchronization overhead; it is -not a claim that all of that overhead has been removed. - -The 1,000-parked-run benchmark's JS heap delta fell from 4,520,328 to 4,304,520 -bytes, with unchanged Lua allocation growth of 1,177,950 bytes. The ready-await -diagnostic's largest sampled heap-plus-buffer delta fell from 5,204,896 to -5,041,160 bytes. As above, ArrayBuffer measurements and individual microtask -phases vary; these figures describe the sampled workloads. - -The combined package is 178,052 bytes compressed and 456,727 unpacked, below the -original 178,091/459,197-byte baseline. All 392 default-engine tests and 388 -fallback tests pass (4 JSPI-only skips), including the close-timing regression. -The close-before-resume stress diagnostic and formatting/lint/diff checks pass. - -## One limits snapshot per async entry - -An async entry previously called the state's public `getLimits()` (which copies -the configuration), then the child's `setLimits()` (which copies it again). -`LuaState` now forwards the protected configuration directly to `setLimits`, -retaining the child's independent snapshot and the public getter's copy semantics -while eliminating one temporary object per entry. - -```sh -node docs/performance/async-entries.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js -``` - -Two alternating comparisons of 1,000 short async entries measured: - -| Engine | First baseline/candidate median | Repeat baseline/candidate median | -| ------ | ------------------------------: | -------------------------------: | -| Yield | 2.312 / 2.150 ms | 2.334 / 2.214 ms | -| JSPI | 4.767 / 4.412 ms | 4.913 / 4.569 ms | - -That is 5–7% less time for this workload. Retained-memory samples were essentially -unchanged, as expected for removing a temporary copy rather than a retained -structure. The new deadline-isolation regression verifies that changing the -state's deadline leaves a parked run's snapshot intact and affects subsequent -runs. All 393 default-engine tests and 389 fallback tests pass (4 JSPI-only skips), -as do formatting/lint/diff checks. - -The combined archive remains 178,052 bytes. Its unpacked contents are 456,741 -bytes, 14 bytes above the preceding build because the protected field retains its -type in the declaration file. Both remain below the original -178,091/459,197-byte package baseline. - -## Shared return marshalling - -Promise resolution and callback returns now share `Thread.pushReturnValues`. -Its optional `nilOnUndefined` flag preserves the one intentional difference: -an awaited undefined produces one Lua nil, while a normal callback returning -undefined produces no values. The duplicate RawResult/MultiReturn dispatch and -element loop were removed from the promise extension. No cache or per-call -container was added. - -```sh -node docs/performance/multiple-returns.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js -``` - -The harness reuses a three-element MultiReturn to isolate marshalling from array -construction. Two comparisons of 20,000 multi-value JSPI awaits measured -32.344/31.167 ms and 33.808/32.708 ms, a 3.3–3.6% reduction. Callback and fallback -await differences stayed below 1%; scalar settled JSPI awaits varied by about -1.3%, so no gain is claimed for those paths. - -The ready-await diagnostic reported identical largest JS heap and ArrayBuffer -deltas before and after (4,815,616 and 224,000 bytes). The combined archive is -178,067 bytes and its unpacked contents are 456,701 bytes, below the original -178,091/459,197 baseline. Relative to the preceding build, unpacked size drops -40 bytes while archive size rises 15 bytes due to compression and declarations. - -The nil-versus-empty-return distinction now has explicit regression coverage. -All 394 default-engine tests and 390 fallback tests pass (4 JSPI-only skips), -along with formatting/lint/diff checks. - -## Reference registration failure handling - -`LuaModule.ref` used to consume a free slot and retain the value in its strong -map before WeakMap registration could reject an unsupported key. Failed calls -could therefore retain rejected values and lose reusable slots. The regression -check reproduced a jump from reusable slot 1 to slot 7 after six rejected values. - -Registration now lets WeakMap validate the key first, then consumes and assigns -the reference index and commits the strong entry. The metadata record is the -same allocation as before. Every committed strong entry consequently has -metadata, allowing the old orphan-entry cleanup branch in `unref` to be removed. -Tests verify failed calls leave existing references and reusable slots intact, -and that repeated references release a slot only after the final unref. - -```sh -node docs/performance/references.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js -``` - -The final 100,000-registration/release comparisons measured 19.331/19.374 ms -with immediate slot reuse and 21.199/21.284 ms with batch release, both within -0.5% of baseline. No speed gain is claimed; the result is unchanged measured -throughput with corrected failure handling and less cleanup code. An initial -peek-before-commit variant was discarded because it slowed immediate reuse. - -All 396 default-engine tests and 392 fallback tests pass (4 JSPI-only skips), -as do formatting/lint/diff checks. The combined package measures 178,061 bytes -compressed and 456,636 unpacked, below the original 178,091/459,197 baseline. - -## Short-string decoder experiments - -The current decoder gathers short ASCII bytes in a temporary array and calls -`String.fromCharCode.apply`. Two alternatives were rejected: scanning ASCII and -passing a typed-array view to `apply`, and scanning before allocating the array. -The first reduced the temporary array's element storage but made 1–32-byte ASCII -decodes 1.9–3.3 times slower. The second added a second traversal and slowed the -same cases by about 3–15%. Neither offered a consistent Unicode improvement. - -```sh -node docs/performance/string-decode.mjs -node docs/performance/string-decode.mjs --cutoff -``` - -This isolated JavaScript probe alternates variant order, discards five warmup -rounds, and measures twenty rounds of 200,000 decodes. It checks decoded values, -including embedded NUL, malformed UTF-8, and multibyte characters. Default output -orders variants as current array gathering, typed-array view, and scan-first -array gathering; cutoff mode replaces the third variant with direct TextDecoder. -It does not establish whole-library or browser performance. - -The cutoff probe measured array gathering/direct TextDecoder at 24.454/31.565 ms -for 32 bytes, 29.233/31.812 ms for 40 bytes, and 37.289/32.035 ms for 48 bytes. -The existing 32-byte limit is retained: extending it would only help a narrow -ASCII range while allocating larger temporary arrays, including for Unicode -inputs that ultimately use TextDecoder. No production change or speedup is -claimed from these experiments; memory usage and package size are unchanged. - -The broader performance goal remains open. These measurements cover startup, -table conversion, and interop, not every workload supported by the library. - -## Cached decoding of short strings - -Profiling the proxy and table-read workloads showed no dominant JavaScript hotspot: a -bare JS-to-wasm call costs about 4 ns, so the marshalling is spread thinly across the -extension dispatch, argument arrays, and string decoding, which took 7–9% of samples. -The names read out of Lua repeat: table keys, globals, metamethod keys. `readString` -now keeps the string it built for a run of up to 32 ASCII bytes in a 256-slot -direct-mapped cache keyed by a 32-bit hash of the bytes, and returns it when the same -bytes come round again. The bytes are compared only when the stored hash matches, so a -miss costs the hashing pass; a string is stored only on its second sighting, so a stream -of values read once (the elements of a table being copied) is never stored and cannot -push out the names read between them. Hits also hand `self[key]` lookups the same, -already internalized string. Non-ASCII and longer strings take the TextDecoder path as before. - -```sh -node docs/performance/string-cache-variants.mjs -node docs/performance/string-cache.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js -node --expose-gc docs/performance/string-cache-memory.mjs /absolute/candidate/dist/index.js -``` - -The isolated probe compares the decoder alone. Verifying bytes on every equal-length -slot, or storing on every miss, made streams of distinct strings 25–90% slower in -isolation; the hash guard and second-touch rule cut that to the hashing pass, about -6 ns per string, while keeping the repeated-name gains. Paired runs of the final -build against the `55c7d96`-based baseline: - -| Workload | Baseline / candidate median | Change | -| ---------------------------------------------------------- | --------------------------: | --------- | -| 100,000 `data.nested.value` proxy reads from Lua | 91.1 / 78.0 ms | 14% less | -| 100 reads of 2,000 `{id, name, active}` tables | 147.1 / 118.4 ms | 20% less | -| 100 reads of 2,000 integers under distinct string keys | 51.0 / 54.9 ms | 8% more | -| 20,000 global round trips, 8 and 24 character strings | 5.24 / 5.00 and 9.01 / 8.60 ms | 5% less | -| 50 reads of 2,000 distinct string keys and values | 36.3 / 38.3 ms | 6% more | - -Flat array reads, table pushes, Lua calls from JS, callbacks into JS, and the VM -workloads were unchanged within 1–3%. The regression is confined to short ASCII -strings that are each read once; it is the hashing pass, and is accepted for the gains -on the repeated names that make up most reads. - -Memory: the cache is per runtime, not per state. Twenty runtimes retained 9.70 MB of -JS heap before and 9.75 MB after, about 2.3 KB each for the two 256-entry hash arrays -and the slot array. Filling every slot with a 32-byte string retained 16 KB more than -the baseline in the worst case probe. Nothing is retained per state, and repeated -reads allocate fewer strings. The Wasm heap is unchanged at 17,891,328 bytes. - -## Package size and build targets - -The bundle now mangles module level names as well, keeping class names (`keepNames`) -so `LuaState.name` and console output are unchanged; helpers between the classes are -renamed, as they already are inside every method. The browser suite's inlined-page test -referred to the runtime by its bundle-internal name, so it now resolves it through the -export clause. The glue is built for the engines package.json declares (Node 24 and -the browserslist minimums), which drops a `node:crypto` fallback from both glues; the -Wasm is byte-identical. - -| Measurement | Original baseline | Before this change | Now | -| ---------------- | ----------------: | -----------------: | ------------: | -| Package archive | 178,091 bytes | 178,061 bytes | 177,822 bytes | -| Unpacked package | 459,197 bytes | 456,636 bytes | 455,025 bytes | - -## Rejected: native helpers for stack traffic - -Four C helpers were tried and reverted: the metatable address in one call, `lua_next` -returning both entry types, and a get/set pair for the pushed-value identity cache. -They removed two to three wasm calls per proxy read, table entry, or cached push. The -paired harnesses measured 0.4–1.7% on an idle machine (a first run under a concurrent -test suite showed a 20% swing in both directions, which did not reproduce), for 175 -more archive bytes from the export names in the Wasm and both glues. With a call -costing about 4 ns, a helper pays off only when it replaces a loop of calls, as -`wasmoon_isarray` does. - -Validation of the final build: 396 default-engine tests and 392 fallback-engine tests -pass (4 JSPI-only skips), the upstream Lua suite finishes with `final OK !!!`, and -formatting/lint and `git diff --check` pass. The Wasm binary is byte-identical to the -preceding build, so the VM measurements above are a control rather than a claim. - -## Derived bindings and a built CLI - -`LuaModule` used to name each of its 145 bindings in the constructor, one `cwrap` call per -export, which was 8.3 KB of the minified bundle. The bindings that cross only numbers are the wasm -exports themselves, so the constructor now fills every declared binding field still empty with the -export of its name, and only the 37 bindings that marshal a string are listed, in one string of -`name:signature` entries that the wrapper reads directly. The field declarations stay, since they -are what keeps the module out of V8 dictionary mode (`%HasFastProperties` still holds), and a -declared binding with no export still fails at construction rather than at first call. The four -helpers that never were exports (`lua_gc`, `lua_resetthread`, `lua_setcstacklimit`, -`luaL_openlibs`) are methods now, like `lua_pop` and `lua_remove`, so the fill pass has no -exceptions to know about and each module carries four fewer own fields and closures. - -The CLI is built by rolldown as a second entry, `dist/cli.js`, and `bin` points there. It imports -the library by the package's own name at run time rather than bundling a copy, and the source -moved to `src/cli.js`. Minified it is 4,687 bytes where `bin/wasmoon` shipped 15,547 bytes of -source. - -```sh -node docs/performance/bindings.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js -node --expose-gc docs/performance/runtime.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js -node --expose-gc docs/performance/retained-memory.mjs /absolute/candidate/dist/index.js -``` - -| Measurement | Before this change | Now | -| -------------------------- | -----------------: | ------------: | -| `dist/index.js` | 109,564 bytes | 102,407 bytes | -| CLI | 15,547 bytes | 4,687 bytes | -| Package archive | 177,822 bytes | 174,001 bytes | -| Unpacked package | 455,025 bytes | 437,691 bytes | - -Filling the fields by name costs the constructor: three paired runs measured 22.1/35.0, 21.3/33.6 -and 21.5/33.6 ms for 1,000 constructions, about 12 µs more each. The stores are keyed rather than -named, the fill pass reads each field once, and the signature string is split; a first version -that walked the module's exports (a dictionary of 177 entries) or tested a regex per field was -slower still, and was replaced. The construction happens once per `LuaRuntime.load`, which -instantiating the wasm dominates: two paired runs of ten load, create, run and close cycles -measured 23.31/23.17 and 23.23/23.46 ms, unchanged within the harness's variation. Twenty live -runtimes retained 9,688,440 bytes of JS heap against 9,751,312 before, and the Wasm heap stayed at -17,891,328 bytes. The wasm binary is unchanged. - -All 396 tests pass, including the CLI suite against the built entry, as do formatting/lint and -`git diff --check`. - -## A small initial heap and lighter reference bookkeeping - -Every heap snapshot so far reported the Wasm heap at 17,891,328 bytes, of which a fresh state used -about 20 KB: Emscripten's default `INITIAL_HEAP` is 16 MB, on top of the 1 MB stack and the static -data. The build now passes `-s INITIAL_HEAP=1MB` and relies on the `ALLOW_MEMORY_GROWTH` it already -had. A fresh runtime's memory is 2,162,688 bytes and the binary is one byte smaller. In Node the -untouched pages never cost RSS either way (a 17.9 MB memory that is never written adds nothing, -touching all of it adds 24 MB), so what this cuts is the address space reserved per runtime, what -`HEAPU8.length`, heap snapshots and browser memory panels count, and the footprint on platforms that -commit the initial memory. Twenty runtimes reserve 43 MB instead of 358 MB. - -Growing is cheap: from 2 MB to 18 MB in Emscripten's 20% steps is twelve `memory.grow` calls, which -measure 0.038 ms in total, and the module never caches a heap view across a call that can grow -(`heap` is a getter). A 200,000-table workload that holds 17.9 MB of Lua data ends at a 29,097,984 -byte heap against 30,998,528 before, since growth now follows the allocations rather than starting -from 16 MB. - -The JS side of a reference has changed too. `LuaModule.ref` used to allocate a metadata record per -JS value Lua holds and keep it in a `WeakMap`, alongside a `Map` from index to value and a list of -free indices. Values and counts are now two dense arrays indexed by the reference index, with the -free slots threaded through the counts array as negated links (a released slot's count is zero or -less), and the `WeakMap` maps a value to its index alone. The slot is taken only after the `WeakMap` -has accepted the value, so a primitive is still rejected without consuming one. `printRefs` walks -the arrays. Threads also start from one shared, frozen empty limits object instead of allocating -`{}` each, which a JS callback made from a Lua coroutine used to do on every call; `setDeadline` is -the one in-place writer and takes an object of its own first. - -```sh -node docs/performance/vm.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js -node docs/performance/callbacks.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js -node docs/performance/references.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js -node docs/performance/create-state.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js -node docs/performance/call-lua.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js -node --expose-gc docs/performance/retained-memory.mjs /absolute/candidate/dist/index.js -``` - -Memory, against the preceding build: - -| Measurement | Before | Now | -| ---------------------------------------------------- | -------------: | -----------: | -| Wasm heap of a fresh runtime | 17,891,328 | 2,162,688 | -| Heap snapshot self size per runtime plus state | 18,286,275 | 2,554,344 | -| JS heap per live reference (100,000 proxied objects) | 120 B | 62 B | -| JS heap retained after releasing those 100,000 | 1,258,496 | 1,987,336 | -| Lua bytes of a fresh state (default options) | 19,052 | 19,052 | - -The one number that grows is the last memory row: the arrays keep the capacity of the most -references ever live at once, where the maps shrank as entries left. That is 16 bytes per slot of -high-water mark, against half the cost while the references are live, and the third list this -design would have needed was folded into the counts array to keep it there. The 390 KB of JS objects -a runtime retains is otherwise unchanged; the largest single piece of it is Emscripten's 4,096-slot -filesystem name table (32 KB), which is generated code and was left alone. - -Time, medians of the paired harnesses on an idle machine. The Wasm change alone was measured before -the JS change was built: arithmetic 0.9% less, table 0.1% more, calls 0.3% less, strings 1.4% less, -heapsort 0.3% more, callbacks 0.2% less, proxy reads 0.2% more, all inside the control variation -recorded above. With both changes: 100,000 ref/unref pairs 19.28 / 9.70 ms with immediate reuse and -22.45 / 14.20 ms in batches (50% and 37% less); callbacks 17.18 / 16.67 ms and proxy reads -75.63 / 72.82 ms (3% and 4% less); state creation 7.2%, 3.6% and 0.4% less for the default, copying -and injected configurations; Lua calls from JS 1% to 3.5% less. - -One paired result was misleading and is recorded so it is not chased again: `async-entries.mjs` -showed the Wasm change alone 8.5% slower under both engines, but that harness loads two runtimes -into one process, and two *different* wasm binaries no longer share V8's compiled module the way two -copies of one binary do. The heap does not grow at all during that workload (2,162,688 bytes before -and after), and one build per process, alternated three times, spreads over ±15% with no direction -(yield 2.26–2.84 vs 2.25–2.48 ms, JSPI 4.86–5.13 vs 4.58–5.39 ms). The JS change alone in the same -paired harness measured 1.4% (yield) and 7.5% (JSPI) less time. - -The package is 174,011 bytes compressed and 437,914 unpacked, against 174,001 and 437,691: the -private fields carry line comments rather than doc comments, since tsc copies the latter into the -published declarations. All 396 default-engine tests pass, 392 fallback tests with 4 JSPI-only skips, -the upstream Lua suite finishes with `final OK !!!` (its peak memory growing the heap to 64 MB along -the way), and formatting/lint and `git diff --check` pass. - -Considered and not done: `dlmalloc` in place of `emmalloc` costs about 20 KB of wasm and has the same -8-byte rounding on the small blocks Lua allocates, so it would not shrink the heap; a smaller -`MEMORY_GROWTH_GEOMETRIC_STEP` only trims slack that is never touched; a smaller stack than 1 MB -trades untouched pages for silent corruption on deep C recursion; and moving the per-state function -and continuation trampolines to the module would save two `WebAssembly.Instance` objects per state -at the cost of finding the state from the `lua_State` on every callback. - -## Run loop and lifecycle simplification - -2026-09-07, Node 26.7.0, against the preceding build (same wasm). A structural pass over `Thread` -with no change in what runs per call: `run` and `continueYielding` share `startRun`, `watchRun` -and `finishRun`; the JSPI result slot is allocated inside `runJspi`; `runSync` and `call` go -through one `pcall` that saves and restores the active run inline, replacing the closure taking -`withSuspensionDisabled`; `resumeYielding`, an alias of `resume`, is gone; the deadline and abort -checks are `limitReached` and `assertLimits`, and the hook unwinds through `interruptWith`. Close -listeners live on the root thread, so `watchRun` no longer casts to reach `LuaState.onClose`. The -function extension releases its call thread on the two exits instead of tracking `handedOff` and -`failed` flags. The `promising`/`suspending` wrappers on `LuaModule` are replaced by typed -`WebAssembly.promising`/`Suspending` declarations, and `PendingSuspend` is a named type in -`async.ts`. - -The resume hook keeps its reference map: two parked runs whose promises settle in the same tick -have both hook continuations run before either wasm stack resumes, so a single slot would hand the -first run the second run's restore. - -`dist/index.js` 102,579 → 101,894 bytes. One build per process, alternated, medians of 15 rounds -(new vs before): JSPI settled awaits 27.4–28.2 vs 27.8–28.9 ms, Lua→JS calls 3.55–3.67 vs -3.50–3.66 ms, JS→Lua calls 2.97–3.28 vs 3.01–3.05 ms, async entries 5.18–6.06 vs 5.18–6.01 ms; -yield settled awaits 64.3–64.6 vs 63.8–70.3 ms. Every interop row moved less than 3%, inside its -run-to-run variation. 396 tests pass on the default and JSPI engines, 392 with 4 JSPI-only skips -on the fallback, and the upstream Lua suite finishes with `final OK !!!`. - -## Reference capacity reclamation and direct binding setup - -The reference arrays now discard released tails when at least half their slots can be dropped. -A highest-live-index counter makes the tail walk incremental; rebuilding the free list only -after halving capacity amortizes that work. Tables of at most 256 slots retain their capacity -for reuse. Live indices never move, including indices held by other states. This addresses the -post-release memory regression recorded above without returning to a map and metadata record -per reference. A live reference near the high end still prevents reclamation of earlier holes; -this does not establish a universal bound in terms of the number of live references. - -```sh -node --expose-gc docs/performance/reference-memory.mjs /absolute/baseline/dist/index.js -node --expose-gc docs/performance/reference-memory.mjs /absolute/candidate/dist/index.js -node docs/performance/references.mjs /absolute/baseline/dist/index.js /absolute/candidate/dist/index.js -``` - -The memory probe warms registration first, keeps one low-index reference alive, then registers -and releases 100,000 objects. In the final comparison, JS heap growth while live was -11,690,296 / 11,690,608 bytes; after release it was 1,897,864 / 1,208 bytes. Repeats of the -candidate's released measurement ranged up to about 4 KB. Wasm heap capacity stayed at -2,162,688 bytes. The older map-based implementation measured 17,469,432 live and 923,032 -released bytes with this same probe. - -Trimming adds work: paired comparisons against the untrimmed arrays cost roughly 3–9% on -100,000 registration/release loops. Compared with the older map-based implementation, the -candidate still measured about 45% less time with immediate reuse and 34–37% less with batch -release. Callback and proxy comparisons varied in direction between runs; no interop speedup -is claimed from this change. - -Binding construction now uses explicit assignments again, keeping the numeric exports direct -and the compact string conversion signatures. This removes enumeration, computed binding -stores, signature splitting and substring allocations from each constructor. Binding fields -are type-only declarations; explicit stores keep V8 fast properties without first initializing -all 146 fields to undefined. Both variants were checked with `%HasFastProperties`. - -Against the reflective constructor, final paired runs took 20.5–20.8 ms rather than -33.8–34.5 ms per 1,000 wrappers, about 38–41% less time. Full load/create/run/close comparisons -were unchanged to 2% faster; Wasm instantiation dominates those operations. Twenty-runtime -retained-JS-heap probes measured about 10.48 MB before and 10.51 MB after this binding change, -so the larger generated code has a small retained cost despite eliminating transient arrays. -The overall memory constraint still needs broader auditing, particularly sparse reference -tables and the decoded-string cache; these results do not prove it for all workloads. - -The final npm archive is 174,453 bytes and unpacks to 442,767 bytes, below the original -178,091 / 459,197-byte baseline. The native binary is byte-identical to the preceding build. -Validation: 397 default-engine tests, 393 fallback tests with 4 JSPI-only skips, upstream Lua's -`final OK !!!`, formatting/lint and diff checks pass. The regression test covers partial and -descending releases, duplicate holders, live-index preservation and slot reuse. A separate -102,400-registration randomized comparison against a JS Map preserved all live values and -indices. All 146 binding fields match the previous build; missing numeric, string and native -exports still fail during construction. - -## Sparse references and a smaller decoder cache - -The sparse-reference audit kept one high-index reference alive after releasing 100,000 lower -ones. Tail trimming cannot help that case: the two arrays retained about 1.90 MB, versus -0.92 MB for the original map and free-list implementation. Replacing the value array with a -Map reduced retention but made registration/release 42–69% slower than the two arrays, so -that experiment was discarded. - -References now use one array. A live slot contains `{ value, count }`; a released slot contains -the negated next free index. Records disappear on release, leaving one backing slot per hole, -as in the original free list. External indices remain one-based, and the array itself is -zero-based. This also avoids paying for a second array while a high live index prevents trimming. - -```sh -node --expose-gc --no-flush-bytecode docs/performance/reference-memory.mjs /absolute/baseline/dist/index.js high -node --expose-gc --no-flush-bytecode docs/performance/reference-memory.mjs /absolute/candidate/dist/index.js high -``` - -The final comparison against the original baseline measured 17.46 / 14.71 MB of incremental -live JS heap, and 0.920 / 0.922 MB after release. Including the runtime and compiled code, -post-release JS heap was 6,055,616 / 6,038,448 bytes, so total retention was lower despite the -roughly 2 KB difference in the incremental measurement. Keeping a low-index anchor instead -allowed trimming to reduce the candidate's incremental retained heap to about 1 KB. Registration -and release still measured 41% less time with immediate reuse and 35% less with batch release -than the original map implementation. The live-record allocation costs about 10–14% on immediate -reuse compared with the two arrays; the batch comparison was approximately unchanged. - -The decoded-string cache is now allocated on the first short ASCII read and has 32 slots, -rather than 256. A saturated 256-slot cache failed the retained-memory constraint even after -the other savings. The smaller cache retains the repeated-name gains in the measured proxy and -nested-table workloads while fitting the full-cache memory check. Applications with larger -working sets of names can have more misses than with the 256-slot experiment. - -On a miss, decoding 1–8 ASCII bytes now calls `String.fromCharCode` with fixed arguments, avoiding -the temporary numeric array. Longer ASCII strings keep the existing gathering path; Unicode -still uses TextDecoder. Two isolated comparisons of this change measured 8–9% less time for -distinct short keys and values, 7–8% less for distinct short keys with numeric values, and 4–6% -less for nested records. These comparisons used the same cache capacity on both sides. With the -final 32-slot cache, comparison against the original baseline measured 19% less time reading -flat arrays, 23% less for nested records, and approximately unchanged time for distinct-key -objects. The earlier distinct-key regression is no longer established by these measurements. - -### Controlling retained-code variation - -An initial twenty-runtime comparison appeared to increase JS heap by about 0.75 MB. Heap -snapshots attributed most of that difference to bytecode and associated metadata, including -Node internals. Repeating the diagnostic changed which build retained that bytecode. The -retained-memory harness now reports V8 code statistics; disabling bytecode flushing during -this diagnostic keeps that variable comparable. This is a measurement flag, not a runtime -requirement or a performance recommendation. - -```sh -node --expose-gc --no-flush-bytecode docs/performance/retained-memory.mjs /absolute/baseline/dist/index.js -node --expose-gc --no-flush-bytecode docs/performance/retained-memory.mjs /absolute/candidate/dist/index.js -node --expose-gc --no-flush-bytecode docs/performance/retained-memory.mjs /absolute/baseline/dist/index.js --fill-cache -node --expose-gc --no-flush-bytecode docs/performance/retained-memory.mjs /absolute/candidate/dist/index.js --fill-cache -``` - -`--fill-cache` uses adjacent duplicates whose byte hashes cover every slot, reports the observed -slot count, then removes the Lua source table and collects it. Separate streaming passes of -distinct strings do not fill a cache that admits only repeated hashes; the earlier 4,096-string -probe did not guarantee full bucket coverage either. - -| Twenty live runtimes | Original baseline | Final candidate | -| ------------------------------------ | ----------------: | --------------: | -| Numeric workload: JS heap | 10,843,304 | 10,732,480 | -| Numeric workload: external memory | 1,871,809 | 1,871,809 | -| Filled-cache workload: JS heap | 10,926,704 | 10,872,512 | -| Filled-cache workload: external | 1,871,809 | 1,876,929 | -| Wasm heap capacity per runtime | 17,891,328 | 2,162,688 | - -The external-memory increase is the cache's two typed arrays: 256 bytes per runtime. JS heap -plus external memory is lower in both workloads. The 256-slot build instead measured 11,128,936 -bytes of JS heap and 1,912,769 external with the same filled-cache probe. These results cover -the measured Node workloads and do not claim every platform has identical object sizes. - -The final package is 174,571 bytes compressed and 443,303 unpacked, versus the original -178,091 / 459,197 bytes. The Wasm binary is unchanged in this pass. All 399 default-engine tests, -395 fallback tests (4 JSPI-only skips), upstream Lua tests, formatting/lint and diff checks pass. -New regressions cover holes below a high live index, symbolic values, invalid indices and -ASCII lengths 0–40 on first and repeated reads, including embedded NULs. - -The broader sweep still reproduces the compiler tradeoff: arithmetic, calls and heapsort are -about 5–9% faster, while string formatting is about 4% slower. Callback and proxy access measured -about 6% and 16% less time than the original baseline, and JS-to-Lua calls about 4–5% less. -Further VM profiling and browser performance measurements remain open. diff --git a/docs/performance/async-entries.mjs b/docs/performance/async-entries.mjs deleted file mode 100644 index 3edb681..0000000 --- a/docs/performance/async-entries.mjs +++ /dev/null @@ -1,16 +0,0 @@ -import assert from 'node:assert/strict' -import { performance } from 'node:perf_hooks' -const paths = process.argv.slice(2) -if (paths.length !== 2) throw new Error('Pass absolute paths to baseline and candidate index.js files') -const runtimes = await Promise.all(paths.map(async (path) => (await import(path)).LuaRuntime.load())) -const states = runtimes.map((lua) => lua.createState()) -const samples = [[], []] -for (let round = 0; round < 30; round++) - for (const variant of round % 2 ? [1, 0] : [0, 1]) { - const start = performance.now() - for (let i = 0; i < 1000; i++) assert.equal(await states[variant].doString('return 1'), 1) - if (round >= 10) samples[variant].push(performance.now() - start) - } -const medians = samples.map((s) => s.sort((a, b) => a - b)[s.length >> 1]) -console.log({ medians, improvement: 1 - medians[1] / medians[0] }) -states.forEach((state) => state.close()) diff --git a/docs/performance/bindings.mjs b/docs/performance/bindings.mjs deleted file mode 100644 index 5372a2b..0000000 --- a/docs/performance/bindings.mjs +++ /dev/null @@ -1,21 +0,0 @@ -import assert from 'node:assert/strict' -import { performance } from 'node:perf_hooks' -const paths = process.argv.slice(2) -if (paths.length !== 2) throw new Error('Pass absolute paths to baseline and candidate index.js files') -const libraries = await Promise.all(paths.map((path) => import(path))) -const runtimes = await Promise.all(libraries.map(({ LuaRuntime }) => LuaRuntime.load())) -const samples = [[], []] -for (let round = 0; round < 30; round++) { - for (const variant of round % 2 ? [1, 0] : [0, 1]) { - const raw = runtimes[variant].module.emscripten - const start = performance.now() - for (let i = 0; i < 1000; i++) { - const module = new libraries[variant].LuaModule(raw) - assert.equal(module.lua_gettop, raw._lua_gettop) - for (const name of ['sizeScratch', 'resultCountScratch', 'gcArgsScratch', 'interruptToken']) raw._free(module[name]) - } - if (round >= 10) samples[variant].push(performance.now() - start) - } -} -const medians = samples.map((s) => s.sort((a, b) => a - b)[s.length >> 1]) -console.log({ medians, improvement: 1 - medians[1] / medians[0] }) diff --git a/docs/performance/cache-memory.mjs b/docs/performance/cache-memory.mjs deleted file mode 100644 index a0070b2..0000000 --- a/docs/performance/cache-memory.mjs +++ /dev/null @@ -1,26 +0,0 @@ -import assert from 'node:assert/strict' -for (const path of process.argv.slice(2)) { - const { LuaRuntime, decorate } = await import(path) - const lua = await LuaRuntime.load() - const state = lua.createState({ inject: true, memory: { trace: true } }) - state.gc.stop() - const memory = [state.memory.used] - const object = { value: 1 } - for (const [name, value] of [ - ['proxy', object], - ['opaque', decorate(object, { as: 'userdata' })], - ['promise', Promise.resolve(1)], - ['error', new Error('example')], - ]) { - state.set(name, value) - state.set(name + '2', value) - assert.equal(state.doStringSync(`return rawequal(${name},${name}2)`), true) - } - memory.push(state.memory.used) - state.doStringSync('proxy=nil; proxy2=nil; opaque=nil; opaque2=nil; promise=nil; promise2=nil; error=nil; error2=nil') - state.gc.collect() - memory.push(state.memory.used) - assert.equal(state.getTop(), 0) - console.log({ path, memory, wasmHeap: lua.module.emscripten.HEAPU8.length }) - state.close() -} diff --git a/docs/performance/call-lua.mjs b/docs/performance/call-lua.mjs deleted file mode 100644 index a8555f8..0000000 --- a/docs/performance/call-lua.mjs +++ /dev/null @@ -1,23 +0,0 @@ -import assert from 'node:assert/strict' -import { performance } from 'node:perf_hooks' -const paths = process.argv.slice(2) -if (paths.length !== 2) throw new Error('Pass absolute paths to baseline and candidate index.js files') -const runtimes = await Promise.all(paths.map(async (path) => (await import(path)).LuaRuntime.load())) -for (const code of ['return function() end', 'return function(a,b) return a+b end', 'return function(a,b) return a,b end']) { - const states = runtimes.map((lua) => lua.createState({ memory: { trace: true } })) - const funcs = states.map((state) => state.doStringSync(code)) - const samples = [[], []] - for (let round = 0; round < 30; round++) { - for (const variant of round % 2 ? [1, 0] : [0, 1]) { - let result - const start = performance.now() - for (let i = 0; i < 100000; i++) result = funcs[variant](1, 2) - const elapsed = performance.now() - start - assert.equal(result, code.includes('a+b') ? 3 : code.includes('a,b end') ? 1 : null) - if (round >= 10) samples[variant].push(elapsed) - } - } - const medians = samples.map((s) => s.sort((a, b) => a - b)[s.length >> 1]) - console.log({ code, medians, improvement: 1 - medians[1] / medians[0], memory: states.map((s) => s.memory.used) }) - states.forEach((s) => s.close()) -} diff --git a/docs/performance/callbacks.mjs b/docs/performance/callbacks.mjs deleted file mode 100644 index 0f4984d..0000000 --- a/docs/performance/callbacks.mjs +++ /dev/null @@ -1,29 +0,0 @@ -import assert from 'node:assert/strict' -import { performance } from 'node:perf_hooks' -const paths = process.argv.slice(2) -if (paths.length !== 2) throw new Error('Pass absolute paths to baseline and candidate index.js files') -const runtimes = await Promise.all(paths.map(async (path) => (await import(path)).LuaRuntime.load())) -for (const kind of ['callback', 'proxy']) { - const states = runtimes.map((lua) => lua.createState()) - for (const state of states) { - state.set('add', (a, b) => a + b) - state.set('data', { nested: { value: 1 } }) - state.doStringSync( - `function run() local sum=0; for i=1,100000 do sum=sum+${kind === 'callback' ? 'add(i,1)' : 'data.nested.value'} end return sum end`, - ) - } - const fns = states.map((state) => state.get('run')) - const samples = [[], []] - for (let round = 0; round < 40; round++) { - for (const variant of round % 2 ? [1, 0] : [0, 1]) { - const start = performance.now() - const result = fns[variant]() - const elapsed = performance.now() - start - assert.equal(result, kind === 'callback' ? 5000150000 : 100000) - if (round >= 10) samples[variant].push(elapsed) - } - } - const medians = samples.map((s) => s.sort((a, b) => a - b)[s.length >> 1]) - console.log({ kind, medians, improvement: 1 - medians[1] / medians[0] }) - states.forEach((state) => state.close()) -} diff --git a/docs/performance/create-state.mjs b/docs/performance/create-state.mjs deleted file mode 100644 index 288e0c6..0000000 --- a/docs/performance/create-state.mjs +++ /dev/null @@ -1,22 +0,0 @@ -import { performance } from 'node:perf_hooks' -const paths = process.argv.slice(2) -if (paths.length !== 2) throw new Error('Pass absolute paths to baseline and candidate index.js files') -const runtimes = await Promise.all(paths.map(async (path) => (await import(path)).LuaRuntime.load())) -for (const options of [{}, { objects: 'copy' }, { inject: true }]) { - const samples = [[], []] - for (let round = 0; round < 30; round++) { - for (const variant of round % 2 ? [1, 0] : [0, 1]) { - const start = performance.now() - for (let i = 0; i < 200; i++) runtimes[variant].createState(options).close() - if (round >= 10) samples[variant].push(performance.now() - start) - } - } - const medians = samples.map((s) => s.sort((a, b) => a - b)[s.length >> 1]) - const memory = runtimes.map((lua) => { - const state = lua.createState({ ...options, memory: { trace: true } }) - const used = state.memory.used - state.close() - return used - }) - console.log({ options, medians, improvement: 1 - medians[1] / medians[0], memory }) -} diff --git a/docs/performance/multiple-returns.mjs b/docs/performance/multiple-returns.mjs deleted file mode 100644 index a731fd5..0000000 --- a/docs/performance/multiple-returns.mjs +++ /dev/null @@ -1,25 +0,0 @@ -import assert from 'node:assert/strict' -import { performance } from 'node:perf_hooks' -const paths = process.argv.slice(2) -if (paths.length !== 2) throw new Error('Pass absolute paths to baseline and candidate index.js files') -const libs = await Promise.all(paths.map((path) => import(path))) -const runtimes = await Promise.all(libs.map((lib) => lib.LuaRuntime.load())) -const states = runtimes.map((lua) => lua.createState({ inject: true })) -for (let i = 0; i < 2; i++) { - const values = libs[i].LuaMultiReturn.of(1, 2, 3) - states[i].set('values', Promise.resolve(values)) - states[i].set('callback', () => values) -} -for (const kind of ['callback', 'await']) { - const code = `local n=0; for i=1,20000 do local a,b,c=${kind === 'callback' ? 'callback()' : 'values:await()'}; n=n+a+b+c end return n` - const samples = [[], []] - for (let round = 0; round < 30; round++) - for (const variant of round % 2 ? [1, 0] : [0, 1]) { - const start = performance.now() - assert.equal(await states[variant].doString(code), 120000) - if (round >= 10) samples[variant].push(performance.now() - start) - } - const medians = samples.map((s) => s.sort((a, b) => a - b)[s.length >> 1]) - console.log({ kind, medians, improvement: 1 - medians[1] / medians[0] }) -} -states.forEach((state) => state.close()) diff --git a/docs/performance/read-table.mjs b/docs/performance/read-table.mjs deleted file mode 100644 index a070c60..0000000 --- a/docs/performance/read-table.mjs +++ /dev/null @@ -1,38 +0,0 @@ -import assert from 'node:assert/strict' -import { performance } from 'node:perf_hooks' -import { readFileSync, readdirSync } from 'node:fs' -import { gzipSync } from 'node:zlib' -const paths = process.argv.slice(2) -if (paths.length !== 2) throw new Error('Pass absolute paths to baseline and candidate dist directories') -const runtimes = await Promise.all(paths.map(async (path) => (await import(`${path}/index.js`)).LuaRuntime.load())) -for (const source of [ - 'data = {}; for i=1,2000 do data[i]=i end', - 'data = {}; for i=1,2000 do data[i]={id=i,name="item"..i,active=true} end', - 'data = {}; for i=1,2000 do data["item"..i]=i end', -]) { - const states = runtimes.map((lua) => lua.createState({ objects: 'copy', memory: { trace: true } })) - for (const state of states) state.doStringSync(source) - assert.deepEqual(states[0].get('data'), states[1].get('data')) - const samples = [[], []] - for (let round = 0; round < 24; round++) { - for (const variant of round % 2 ? [1, 0] : [0, 1]) { - const start = performance.now() - for (let i = 0; i < 100; i++) states[variant].get('data') - if (round >= 6) samples[variant].push(performance.now() - start) - } - } - const medians = samples.map((s) => s.sort((a, b) => a - b)[s.length >> 1]) - console.log({ source, medians, improvement: 1 - medians[1] / medians[0], memory: states.map((s) => s.memory.used) }) - states.forEach((s) => s.close()) -} -for (const path of paths) { - let bytes = 0, - gzip = 0 - for (const name of readdirSync(path, { recursive: true })) { - if (!/\.(js|ts|wasm)$/.test(name)) continue - const data = readFileSync(`${path}/${name}`) - bytes += data.length - gzip += gzipSync(data).length - } - console.log({ path, bytes, gzip }) -} diff --git a/docs/performance/ready-await-memory.mjs b/docs/performance/ready-await-memory.mjs deleted file mode 100644 index b88b287..0000000 --- a/docs/performance/ready-await-memory.mjs +++ /dev/null @@ -1,33 +0,0 @@ -if (!global.gc || !process.argv[2]) throw new Error('Use --expose-gc and pass an absolute path to index.js') -const { LuaRuntime } = await import(process.argv[2]) -const lua = await LuaRuntime.load() -const results = [] -for (let depth = 0; depth < 7; depth++) { - const state = lua.createState() - let release - state.set( - 'gate', - new Promise((resolve) => { - release = resolve - }), - ) - state.gc.collect() - global.gc() - const before = process.memoryUsage() - const runs = Array.from({ length: 1000 }, () => - state.doString('gate:await() return 1').then( - () => {}, - () => {}, - ), - ) - await new Promise((resolve) => setTimeout(resolve, 10)) - release() - for (let i = 0; i < depth; i++) await Promise.resolve() - global.gc() - const during = process.memoryUsage() - results.push({ depth, heap: during.heapUsed - before.heapUsed, buffers: during.arrayBuffers - before.arrayBuffers }) - if (process.argv.includes('--close-before-resume')) state.close() - await Promise.all(runs) - state.close() -} -console.log(JSON.stringify({ path: process.argv[2], results })) diff --git a/docs/performance/reference-memory.mjs b/docs/performance/reference-memory.mjs deleted file mode 100644 index 823dbd4..0000000 --- a/docs/performance/reference-memory.mjs +++ /dev/null @@ -1,26 +0,0 @@ -import assert from 'node:assert/strict' - -if (!global.gc || !process.argv[2]) throw new Error('Use --expose-gc and pass an absolute path to index.js') -const { LuaRuntime } = await import(process.argv[2]) -const { module } = await LuaRuntime.load() -const count = 100_000 -const refs = new Uint32Array(count) -const anchor = {} -const high = process.argv[3] === 'high' -let anchorRef = high ? undefined : module.ref(anchor) -const sample = () => { - for (let i = 0; i < 5; i++) global.gc() - return process.memoryUsage().heapUsed -} -// Warm the registration and release paths before measuring retained heap. -for (let i = 0; i < 10_000; i++) module.unref(module.ref({})) -const before = sample() -for (let i = 0; i < count; i++) refs[i] = module.ref({}) -if (high) anchorRef = module.ref(anchor) -const live = sample() -for (const ref of refs) module.unref(ref) -const released = sample() -assert.equal(module.getRef(anchorRef), anchor) -assert.equal(module.getRefIndex(anchor), anchorRef) -console.log({ path: process.argv[2], anchor: high ? 'high' : 'low', live: live - before, released: released - before, heapUsed: released, wasmHeap: module.emscripten.HEAPU8.length }) -module.unref(anchorRef) diff --git a/docs/performance/references.mjs b/docs/performance/references.mjs deleted file mode 100644 index 3b67d03..0000000 --- a/docs/performance/references.mjs +++ /dev/null @@ -1,29 +0,0 @@ -import assert from 'node:assert/strict' -import { performance } from 'node:perf_hooks' -const paths = process.argv.slice(2) -if (paths.length !== 2) throw new Error('Pass absolute paths to baseline and candidate index.js files') -const modules = await Promise.all(paths.map(async (path) => (await (await import(path)).LuaRuntime.load()).module)) -const values = Array.from({ length: 1000 }, () => ({})) -for (const mode of ['reuse', 'batch']) { - const samples = [[], []] - for (let round = 0; round < 30; round++) - for (const variant of round % 2 ? [1, 0] : [0, 1]) { - const module = modules[variant] - const start = performance.now() - for (let i = 0; i < 100; i++) { - if (mode === 'reuse') - for (const value of values) { - const ref = module.ref(value) - module.unref(ref) - } - else { - const refs = values.map((value) => module.ref(value)) - for (const ref of refs) module.unref(ref) - } - } - if (round >= 10) samples[variant].push(performance.now() - start) - } - const medians = samples.map((s) => s.sort((a, b) => a - b)[s.length >> 1]) - console.log({ mode, medians, improvement: 1 - medians[1] / medians[0] }) - for (const module of modules) for (const value of values) assert.equal(module.getRefIndex(value), undefined) -} diff --git a/docs/performance/retained-memory.mjs b/docs/performance/retained-memory.mjs deleted file mode 100644 index 3b4e103..0000000 --- a/docs/performance/retained-memory.mjs +++ /dev/null @@ -1,36 +0,0 @@ -import { getHeapCodeStatistics } from 'node:v8' - -if (!global.gc || !process.argv[2]) throw new Error('Use --expose-gc and pass an absolute path to index.js') -const { LuaRuntime } = await import(process.argv[2]) -const runtimes = [] -for (let i = 0; i < 20; i++) { - const lua = await LuaRuntime.load() - const state = lua.createState({ objects: 'copy' }) - state.doStringSync('data={}; for i=1,2000 do data[i]=i end') - for (let j = 0; j < 20; j++) state.get('data') - if (process.argv.includes('--fill-cache')) { - // For a 31-based hash, the final two bytes add every integer from 0 through 255. - // This covers every bucket in caches of up to 256 slots. Adjacent duplicates exercise - // second-touch admission; two separate streaming passes would not fill the cache. - state.doStringSync(` - cacheStrings = {} - for i = 0, 255 do - local s = string.rep('a', 30) .. string.char(i // 31, i % 31) - cacheStrings[2*i+1] = s - cacheStrings[2*i+2] = s - end - `) - state.get('cacheStrings') - state.doStringSync('cacheStrings=nil; collectgarbage("collect")') - } - runtimes.push({ lua, state }) -} -for (let i = 0; i < 5; i++) global.gc() -console.log({ - path: process.argv[2], - heapUsed: process.memoryUsage().heapUsed, - external: process.memoryUsage().external, - wasmHeap: runtimes[0].lua.module.emscripten.HEAPU8.length, - cacheSlots: runtimes[0].lua.module.decodedStrings?.filter(Boolean).length, - code: getHeapCodeStatistics(), -}) diff --git a/docs/performance/runtime.mjs b/docs/performance/runtime.mjs deleted file mode 100644 index 5ede6eb..0000000 --- a/docs/performance/runtime.mjs +++ /dev/null @@ -1,21 +0,0 @@ -if (!global.gc) throw new Error('Run with --expose-gc') -import { performance } from 'node:perf_hooks' -const paths = process.argv.slice(2) -if (paths.length !== 2) throw new Error('Pass absolute paths to baseline and candidate index.js files') -const libraries = await Promise.all(paths.map((path) => import(path))) -const samples = [[], []] -for (let round = 0; round < 30; round++) { - for (const variant of round % 2 ? [1, 0] : [0, 1]) { - global.gc() - const start = performance.now() - for (let i = 0; i < 10; i++) { - const lua = await libraries[variant].LuaRuntime.load() - const state = lua.createState() - state.doStringSync('return 1+1') - state.close() - } - if (round >= 10) samples[variant].push(performance.now() - start) - } -} -const medians = samples.map((s) => s.sort((a, b) => a - b)[s.length >> 1]) -console.log({ medians, improvement: 1 - medians[1] / medians[0] }) diff --git a/docs/performance/settled-awaits.mjs b/docs/performance/settled-awaits.mjs deleted file mode 100644 index 9708794..0000000 --- a/docs/performance/settled-awaits.mjs +++ /dev/null @@ -1,17 +0,0 @@ -import assert from 'node:assert/strict' -import { performance } from 'node:perf_hooks' -const paths = process.argv.slice(2) -if (paths.length !== 2) throw new Error('Pass absolute paths to baseline and candidate index.js files') -const runtimes = await Promise.all(paths.map(async (path) => (await import(path)).LuaRuntime.load())) -const states = runtimes.map((lua) => lua.createState()) -for (const state of states) state.set('ready', Promise.resolve(1)) -const samples = [[], []] -for (let round = 0; round < 30; round++) - for (const variant of round % 2 ? [1, 0] : [0, 1]) { - const start = performance.now() - assert.equal(await states[variant].doString('local n=0; for i=1,20000 do n=n+ready:await() end return n'), 20000) - if (round >= 10) samples[variant].push(performance.now() - start) - } -const medians = samples.map((s) => s.sort((a, b) => a - b)[s.length >> 1]) -console.log({ medians, improvement: 1 - medians[1] / medians[0] }) -states.forEach((state) => state.close()) diff --git a/docs/performance/string-cache-memory.mjs b/docs/performance/string-cache-memory.mjs deleted file mode 100644 index 1619bd5..0000000 --- a/docs/performance/string-cache-memory.mjs +++ /dev/null @@ -1,16 +0,0 @@ -// Worst case for the decoded string cache: every slot filled with a 32 byte string, read twice so -// it is kept. Reports the JS heap the cache retains per runtime after a full GC. -if (!global.gc) throw new Error('use --expose-gc') -const { LuaRuntime } = await import(process.argv[2]) -const lua = await LuaRuntime.load() -const state = lua.createState() -// 4096 distinct 32-char ASCII strings, each read twice: far more than 256 slots, so every slot ends up holding one. -state.doStringSync('t = {}; for i = 1, 4096 do t[i] = string.format("%032d", i) end') -const read = () => { for (let i = 0; i < 2; i++) state.doStringSync('return t[' + (i + 1) + ']') } -for (let g = 0; g < 5; g++) global.gc() -const before = process.memoryUsage().heapUsed -for (let i = 1; i <= 4096; i++) { state.doStringSync(`return t[${i}]`); state.doStringSync(`return t[${i}]`) } -for (let g = 0; g < 5; g++) global.gc() -const after = process.memoryUsage().heapUsed -console.log({ path: process.argv[2].split('/').slice(-2).join('/'), heapDelta: after - before }) -state.close() diff --git a/docs/performance/string-cache-variants.mjs b/docs/performance/string-cache-variants.mjs deleted file mode 100644 index f97946d..0000000 --- a/docs/performance/string-cache-variants.mjs +++ /dev/null @@ -1,142 +0,0 @@ -import assert from 'node:assert/strict' -import { performance } from 'node:perf_hooks' -const decoder = new TextDecoder() -const heap = new Uint8Array(1 << 16) -const SIZE = 256 -function original(pointer, length) { - const codes = new Array(length) - let index = 0 - while (index < length) { - const code = heap[pointer + index] - if (code > 127) break - codes[index++] = code - } - if (index === length) return String.fromCharCode.apply(null, codes) - return decoder.decode(heap.subarray(pointer, pointer + length)) -} -function same(text, pointer) { - for (let i = 0; i < text.length; i++) if (text.charCodeAt(i) !== heap[pointer + i]) return false - return true -} -// A: current (verify on equal length, two passes) -const aStrings = new Array(SIZE).fill(''), aHits = new Uint8Array(SIZE) -function current(pointer, length) { - let hash = length, index = 0 - while (index < length) { const code = heap[pointer + index]; if (code > 127) break; hash = (hash * 31 + code) | 0; index++ } - if (index === length) { - const slot = hash & (SIZE - 1), cached = aStrings[slot] - if (cached.length === length && same(cached, pointer)) { aHits[slot] = 1; return cached } - const codes = new Array(length) - for (index = 0; index < length; index++) codes[index] = heap[pointer + index] - const text = String.fromCharCode.apply(null, codes) - if (aHits[slot]) aHits[slot] = 0; else aStrings[slot] = text - return text - } - return decoder.decode(heap.subarray(pointer, pointer + length)) -} -// B: two passes, verify only when the stored hash matches -const bStrings = new Array(SIZE).fill(''), bHashes = new Int32Array(SIZE), bHits = new Uint8Array(SIZE) -function hashGuarded(pointer, length) { - let hash = length, index = 0 - while (index < length) { const code = heap[pointer + index]; if (code > 127) break; hash = (Math.imul(hash, 31) + code) | 0; index++ } - if (index === length) { - const slot = hash & (SIZE - 1) - if (bHashes[slot] === hash) { const cached = bStrings[slot]; if (cached.length === length && same(cached, pointer)) { bHits[slot] = 1; return cached } } - const codes = new Array(length) - for (index = 0; index < length; index++) codes[index] = heap[pointer + index] - const text = String.fromCharCode.apply(null, codes) - if (bHits[slot]) bHits[slot] = 0; else { bStrings[slot] = text; bHashes[slot] = hash } - return text - } - return decoder.decode(heap.subarray(pointer, pointer + length)) -} -// C: one pass gathering and hashing, verify only when the stored hash matches -const cStrings = new Array(SIZE).fill(''), cHashes = new Int32Array(SIZE), cHits = new Uint8Array(SIZE) -function singlePass(pointer, length) { - const codes = new Array(length) - let hash = length, index = 0 - while (index < length) { const code = heap[pointer + index]; if (code > 127) break; hash = (Math.imul(hash, 31) + code) | 0; codes[index++] = code } - if (index === length) { - const slot = hash & (SIZE - 1) - if (cHashes[slot] === hash) { const cached = cStrings[slot]; if (cached.length === length && same(cached, pointer)) { cHits[slot] = 1; return cached } } - const text = String.fromCharCode.apply(null, codes) - if (cHits[slot]) cHits[slot] = 0; else { cStrings[slot] = text; cHashes[slot] = hash } - return text - } - return decoder.decode(heap.subarray(pointer, pointer + length)) -} -// D: B without the second-chance bit -const dStrings = new Array(SIZE).fill(''), dHashes = new Int32Array(SIZE) -function plain(pointer, length) { - let hash = length, index = 0 - while (index < length) { const code = heap[pointer + index]; if (code > 127) break; hash = (Math.imul(hash, 31) + code) | 0; index++ } - if (index === length) { - const slot = hash & (SIZE - 1) - if (dHashes[slot] === hash) { const cached = dStrings[slot]; if (cached.length === length && same(cached, pointer)) return cached } - const codes = new Array(length) - for (index = 0; index < length; index++) codes[index] = heap[pointer + index] - const text = String.fromCharCode.apply(null, codes) - dStrings[slot] = text; dHashes[slot] = hash - return text - } - return decoder.decode(heap.subarray(pointer, pointer + length)) -} -// E: hash pass only, never stores (isolates the hashing cost) -const eHashes = new Int32Array(SIZE) -function hashOnly(pointer, length) { - let hash = length, index = 0 - while (index < length) { const code = heap[pointer + index]; if (code > 127) break; hash = (Math.imul(hash, 31) + code) | 0; index++ } - if (index === length) { - const slot = hash & (SIZE - 1) - if (eHashes[slot] === hash) return 'x' - const codes = new Array(length) - for (index = 0; index < length; index++) codes[index] = heap[pointer + index] - return String.fromCharCode.apply(null, codes) - } - return decoder.decode(heap.subarray(pointer, pointer + length)) -} -// F: store only on the second sighting of the same hash -const fStrings = new Array(SIZE).fill(''), fHashes = new Int32Array(SIZE), fSeen = new Int32Array(SIZE) -function secondTouch(pointer, length) { - let hash = length, index = 0 - while (index < length) { const code = heap[pointer + index]; if (code > 127) break; hash = (Math.imul(hash, 31) + code) | 0; index++ } - if (index === length) { - const slot = hash & (SIZE - 1) - if (fHashes[slot] === hash) { const cached = fStrings[slot]; if (cached.length === length && same(cached, pointer)) return cached } - const codes = new Array(length) - for (index = 0; index < length; index++) codes[index] = heap[pointer + index] - const text = String.fromCharCode.apply(null, codes) - if (fSeen[slot] === hash) { fStrings[slot] = text; fHashes[slot] = hash } else fSeen[slot] = hash - return text - } - return decoder.decode(heap.subarray(pointer, pointer + length)) -} -const variants = [original, plain, hashOnly, secondTouch] -const enc = new TextEncoder() -// Workloads: list of strings laid out in the heap, read cyclically. -function layout(strings) { let p = 8; const spans = []; for (const s of strings) { const b = enc.encode(s); heap.set(b, p); spans.push([p, b.length]); p += b.length + 1 } return spans } -const workloads = { - 'hot keys (id,name,active)': layout(['id', 'name', 'active']), - 'hot keys (nested,value)': layout(['nested', 'value']), - 'distinct keys item1..2000': layout(Array.from({ length: 2000 }, (_, i) => `item${i + 1}`)), - 'mixed: 3 keys + 1 distinct value per entry': (() => { const out = []; const keys = layout(['id', 'name', 'active']); const vals = layout(Array.from({ length: 2000 }, (_, i) => `item${i + 1}`)); for (let i = 0; i < 2000; i++) { out.push(keys[0], keys[1], vals[i], keys[2]) } return out })(), - '24-char repeated': layout(['abcdefghijabcdefghijabcd']), -} -for (const [name, spans] of Object.entries(workloads)) { - for (const v of variants) if (v !== hashOnly) for (const [p, l] of spans) assert.equal(v(p, l), original(p, l)) - const samples = variants.map(() => []) - const n = 200000 - for (let round = 0; round < 24; round++) { - const order = round % 2 ? [3, 2, 1, 0] : [0, 1, 2, 3] - for (const v of order) { - const f = variants[v] - let sink = 0 - const start = performance.now() - for (let i = 0; i < n; i++) { const [p, l] = spans[i % spans.length]; sink += f(p, l).length } - if (round >= 4) samples[v].push(performance.now() - start) - if (sink < 0) throw new Error() - } - } - const med = samples.map((s) => s.sort((a, b) => a - b)[s.length >> 1]) - console.log(name.padEnd(46), variants.map((v, i) => `${v.name}=${med[i].toFixed(2)}`).join(' ')) -} diff --git a/docs/performance/string-cache.mjs b/docs/performance/string-cache.mjs deleted file mode 100644 index 4419c7f..0000000 --- a/docs/performance/string-cache.mjs +++ /dev/null @@ -1,39 +0,0 @@ -import assert from 'node:assert/strict' -import { performance } from 'node:perf_hooks' -const paths = process.argv.slice(2) -const runtimes = await Promise.all(paths.map(async (path) => (await import(path)).LuaRuntime.load())) -for (const length of [8, 24, 200]) { - const value = 'abcdefghij'.repeat(Math.ceil(length / 10)).slice(0, length) - const states = runtimes.map((lua) => lua.createState()) - const samples = [[], []] - for (let round = 0; round < 30; round++) { - for (const variant of round % 2 ? [1, 0] : [0, 1]) { - const state = states[variant] - const start = performance.now() - for (let i = 0; i < 20000; i++) { - state.set('value', value) - if (state.get('value') !== value) throw new Error('mismatch') - } - if (round >= 6) samples[variant].push(performance.now() - start) - } - } - const medians = samples.map((s) => s.sort((a, b) => a - b)[s.length >> 1]) - console.log(JSON.stringify({ length, medians, improvement: 1 - medians[1] / medians[0] })) - states.forEach((s) => s.close()) -} -// Distinct keys streaming through: the cache's worst case. -{ - const states = runtimes.map((lua) => lua.createState({ objects: 'copy' })) - for (const state of states) state.doStringSync('data = {}; for i=1,2000 do data["k"..i] = "v"..i end') - const samples = [[], []] - for (let round = 0; round < 30; round++) { - for (const variant of round % 2 ? [1, 0] : [0, 1]) { - const start = performance.now() - for (let i = 0; i < 50; i++) assert.equal(Object.keys(states[variant].get('data')).length, 2000) - if (round >= 6) samples[variant].push(performance.now() - start) - } - } - const medians = samples.map((s) => s.sort((a, b) => a - b)[s.length >> 1]) - console.log(JSON.stringify({ workload: 'distinct string keys and values', medians, improvement: 1 - medians[1] / medians[0] })) - states.forEach((s) => s.close()) -} diff --git a/docs/performance/string-decode.mjs b/docs/performance/string-decode.mjs deleted file mode 100644 index 672aee4..0000000 --- a/docs/performance/string-decode.mjs +++ /dev/null @@ -1,57 +0,0 @@ -import assert from 'node:assert/strict' -import { performance } from 'node:perf_hooks' -const decoder = new TextDecoder() -const heap = new Uint8Array(1024) -function original(pointer, length) { - const codes = new Array(length) - let index = 0 - while (index < length) { - const code = heap[pointer + index] - if (code > 127) break - codes[index++] = code - } - if (index === length) return String.fromCharCode.apply(null, codes) - return decoder.decode(heap.subarray(pointer, pointer + length)) -} -function view(pointer, length) { - let index = 0 - while (index < length && heap[pointer + index] <= 127) index++ - const bytes = heap.subarray(pointer, pointer + length) - return index === length ? String.fromCharCode.apply(null, bytes) : decoder.decode(bytes) -} -function scanFirst(pointer, length) { - let index = 0 - while (index < length && heap[pointer + index] <= 127) index++ - if (index !== length) return decoder.decode(heap.subarray(pointer, pointer + length)) - const codes = new Array(length) - for (index = 0; index < length; index++) codes[index] = heap[pointer + index] - return String.fromCharCode.apply(null, codes) -} -// Isolates the short-string decoder; it does not measure Lua/Wasm crossings. -const cutoff = process.argv.includes('--cutoff') -const variants = cutoff - ? [original, view, (pointer, length) => decoder.decode(heap.subarray(pointer, pointer + length))] - : [original, view, scanFirst] -const values = cutoff - ? [32, 40, 48, 64, 80, 96, 128].map((n) => 'a'.repeat(n)) - : ['a', 'hello', 'abcdefghijklmno', 'a'.repeat(32), 'ação', 'こんにちは', 'a'.repeat(25) + 'é'] -for (const bytes of [new Uint8Array([0, 65, 0]), new Uint8Array([255, 128, 65]), new TextEncoder().encode('é😀')]) { - heap.set(bytes, 8) - for (const variant of variants) assert.equal(variant(8, bytes.length), decoder.decode(bytes)) -} -let sink = 0 -for (const value of values) { - const bytes = new TextEncoder().encode(value) - heap.set(bytes, 8) - for (const variant of variants) assert.equal(variant(8, bytes.length), value) - const samples = [[], [], []] - for (let round = 0; round < 25; round++) - for (const v of round % 2 ? [2, 1, 0] : [0, 1, 2]) { - const f = variants[v] - const start = performance.now() - for (let i = 0; i < 200000; i++) sink += f(8, bytes.length).length - if (round >= 5) samples[v].push(performance.now() - start) - } - console.log(JSON.stringify({ value, ms: samples.map((s) => s.sort((a, b) => a - b)[10]) })) -} -console.log(sink) diff --git a/docs/performance/table-copy.mjs b/docs/performance/table-copy.mjs deleted file mode 100644 index 8e53bcb..0000000 --- a/docs/performance/table-copy.mjs +++ /dev/null @@ -1,31 +0,0 @@ -import { performance } from 'node:perf_hooks' -import { statSync } from 'node:fs' -const paths = process.argv.slice(2) -if (paths.length !== 2) throw new Error('Pass absolute paths to baseline and candidate index.js files') -const runtimes = await Promise.all(paths.map(async (path) => (await import(path)).LuaRuntime.load())) -const values = [ - {}, - { id: 1, name: 'item', active: true }, - Array.from({ length: 2000 }, (_, id) => ({ id, name: `item${id}`, active: true })), -] -for (const [index, value] of values.entries()) { - const states = runtimes.map((runtime) => runtime.createState({ objects: 'copy' })) - const samples = [[], []] - const count = index === 2 ? 100 : 20000 - for (let round = 0; round < 24; round++) { - for (const variant of round % 2 ? [1, 0] : [0, 1]) { - const state = states[variant] - const start = performance.now() - for (let i = 0; i < count; i++) { - state.pushValue(value) - state.pop() - } - const elapsed = performance.now() - start - if (round >= 6) samples[variant].push(elapsed) - } - } - const medians = samples.map((sample) => sample.sort((a, b) => a - b)[sample.length >> 1]) - console.log(JSON.stringify({ index, count, medians, improvement: 1 - medians[1] / medians[0] })) - states.forEach((state) => state.close()) -} -console.log(paths.map((path) => ({ path, bytes: statSync(path).size }))) diff --git a/docs/performance/vm.mjs b/docs/performance/vm.mjs deleted file mode 100644 index 3002ab8..0000000 --- a/docs/performance/vm.mjs +++ /dev/null @@ -1,42 +0,0 @@ -import assert from 'node:assert/strict' -import { performance } from 'node:perf_hooks' -import { readFileSync } from 'node:fs' -const paths = process.argv.slice(2) -if (paths.length !== 2) throw new Error('Pass absolute paths to baseline and candidate index.js files') -const runtimes = await Promise.all(paths.map(async (path) => (await import(path)).LuaRuntime.load())) -const workloads = [ - ['arithmetic', 'return function() local sum=0; for i=1,1000000 do sum=sum+i end return sum end', 500000500000], - [ - 'table', - 'return function() local t={}; for i=1,100000 do t[i]=i end local sum=0; for i=1,#t do sum=sum+t[i] end return sum end', - 5000050000, - ], - [ - 'calls', - 'local function add(a,b) return a+b end; return function() local sum=0; for i=1,200000 do sum=add(sum,i) end return sum end', - 20000100000, - ], - [ - 'strings', - 'return function() local t={}; for i=1,10000 do t[i]=string.format("item:%d",i) end return #table.concat(t,",") end', - 98893, - ], - ['heapsort', readFileSync(new URL('../../bench/heapsort.lua', import.meta.url), 'utf8'), 10], -] -for (const [name, source, expected] of workloads) { - const states = runtimes.map((lua) => lua.createState()) - for (const state of states) state.doStringSync('math.randomseed(1)') - const fns = states.map((state) => state.doStringSync(source)) - const samples = [[], []] - for (let round = 0; round < 30; round++) - for (const variant of round % 2 ? [1, 0] : [0, 1]) { - const start = performance.now() - const result = fns[variant]() - const elapsed = performance.now() - start - assert.equal(result, expected) - if (round >= 10) samples[variant].push(elapsed) - } - const medians = samples.map((s) => s.sort((a, b) => a - b)[s.length >> 1]) - console.log({ name, medians, improvement: 1 - medians[1] / medians[0] }) - states.forEach((state) => state.close()) -} diff --git a/src/async.ts b/src/async.ts index 6cb7a3c..8d605cb 100644 --- a/src/async.ts +++ b/src/async.ts @@ -1,16 +1,11 @@ -/** - * A macrotask, so pending promise reactions *and* timers get a turn before Lua is resumed. A - * microtask would starve timer driven code such as setTimeout based sleeps. - * - * MessageChannel where it exists, because a browser clamps a nested setTimeout to 4ms while a - * message post is not clamped; setImmediate under Node; setTimeout as the last resort. - */ import type Thread from './thread' -import { LuaAbortError, type LuaInterruptError, LuaTimeoutError } from './types' - -type Macrotask = (task: () => void) => void +import { type LuaInterruptError, LuaAbortError, LuaTimeoutError } from './types' -const macrotask: Macrotask = (() => { +/** + * setImmediate under Node. In a browser a MessageChannel, because a nested setTimeout is clamped to + * 4ms there while a message post is not; setTimeout as the last resort. + */ +const macrotask: (task: () => void) => void = (() => { if (typeof setImmediate === 'function') { return (task: () => void) => void setImmediate(task) } @@ -68,9 +63,11 @@ export function reportIfUnobserved(run: Promise, report: (error: unknow return promise } -export const yieldToEventLoop = (): Promise => { - return new Promise((resolve) => macrotask(resolve)) -} +/** + * A macrotask, so pending promise reactions *and* timers get a turn before Lua is resumed. A + * microtask would starve timer driven code such as setTimeout based sleeps. + */ +export const yieldToEventLoop = (): Promise => new Promise((resolve) => macrotask(resolve)) /** * The interrupt a deadline or aborted signal calls for, or undefined when neither has fired. The @@ -119,52 +116,26 @@ export function settleOrInterrupt(promise: unknown, signal: AbortSignal | undefi } return new Promise((resolve) => { - let done = false + let timer: ReturnType | undefined + // Whichever comes first wins: resolving again does nothing, and neither does clearing. const finish = (outcome: SettleOutcome): void => { - if (done) { - return - } - done = true - if (timer !== undefined) { - clearTimeout(timer) - } - if (onAbort !== undefined) { - signal?.removeEventListener('abort', onAbort) - } + clearTimeout(timer) + signal?.removeEventListener('abort', check) resolve(outcome) } - - let timer: ReturnType | undefined - const scheduleDeadline = (): void => { - if (deadline === undefined) { - return + // The abort listener and the timer both end up here. A timer can fire early, and a delay + // above 2^31-1 overflows to 1ms in Node, so it is armed again until the deadline has passed. + const check = (): void => { + const error = limitError(signal, deadline) + if (error) { + finish({ status: 'interrupted', error }) + } else if (deadline !== undefined) { + timer = setTimeout(check, Math.min(0x7fffffff, deadline - Date.now())) } - // Timers can fire early and delays above 2^31-1 overflow to 1ms in Node. - timer = setTimeout( - () => { - const error = limitError(signal, deadline) - if (error) { - finish({ status: 'interrupted', error }) - } else { - scheduleDeadline() - } - }, - Math.min(0x7fffffff, Math.max(0, deadline - Date.now())), - ) } - scheduleDeadline() - - let onAbort: (() => void) | undefined - if (signal !== undefined) { - if (signal.aborted) { - finish({ status: 'interrupted', error: new LuaAbortError('thread aborted') }) - return - } - onAbort = () => finish({ status: 'interrupted', error: new LuaAbortError('thread aborted') }) - signal.addEventListener('abort', onAbort, { once: true }) - } - - settled.then(finish) + signal?.addEventListener('abort', check, { once: true }) + check() + void settled.then(finish) }) } diff --git a/src/module.ts b/src/module.ts index f9882d7..b5dfb98 100755 --- a/src/module.ts +++ b/src/module.ts @@ -142,7 +142,7 @@ const INLINE_DECODE_LIMIT = 32 // globals, metamethod names -- so the string built for a run of bytes is kept and handed back the // next time those bytes are read, which also gives the property lookups it usually feeds the // same, already internalized string. Direct mapped on a hash of the bytes; a power of two. Sized -// for a small working set of repeated names; a full cache must also fit the retained-memory budget. +// for a small working set of repeated names, since a full cache is memory every runtime keeps. const DECODED_STRING_CACHE_SIZE = 32 // The wasm value types Emscripten's function signature letters map to. `p` is a pointer, which is @@ -179,9 +179,6 @@ function buildTrampolineModule(signature: string): WebAssembly.Module { return new WebAssembly.Module(Uint8Array.from([0, 0x61, 0x73, 0x6d, 1, 0, 0, 0, ...typeSection, ...importSection, ...exportSection])) } -/** `lua_resume`, or its `WebAssembly.promising` wrapper where a resume can suspend. */ -type SuspendableResume = (...args: Parameters) => Promise | LuaReturn - /** A {@link LuaModuleOptions.mounts} entry with both sides checked, ready for `FS.mount`. */ interface ResolvedMount { /** Absolute, with no trailing slash and no `.` or `..` in it. */ @@ -623,6 +620,18 @@ export default class LuaModule { * before resuming. See {@link installAwaitHook}. */ public readonly mainStackPointer: number + /** + * Whether the platform has JSPI (the WebAssembly JavaScript Promise Integration API), which is + * what lets an `:await()` suspend the wasm stack. Without it everything else works and an + * `:await()` is an error. + */ + public readonly jspiSupported: boolean + /** + * The `lua_resume` async runs are driven through: wrapped in `WebAssembly.promising`, so an + * `:await()` inside it can suspend the wasm stack. Where the platform has no JSPI it is the plain + * export, and a run is a resume nothing can suspend. + */ + public readonly suspendableResume: (...args: Parameters) => Promise | LuaReturn /** * Set true only while a promising resume is the innermost driver on the stack, so an `:await()` * knows a suspend would reach a promising boundary. A synchronous entry point (doStringSync, a @@ -647,9 +656,6 @@ export default class LuaModule { this.asyncSteps = 0 return yieldToEventLoop() } - - /** Built on first use by {@link suspendableResume}, then kept for the module's lifetime. */ - private suspendableResumeFunction: SuspendableResume | undefined private stringBuffer = 0 // Initialized together on the first short ASCII read. Numeric-only runtimes need no cache. // Empty slots hold '', which no non-empty read can match, under a hash of 0. @@ -839,21 +845,13 @@ export default class LuaModule { // Captured while no Lua is running, so it is the top of the C stack in JS land. this.mainStackPointer = this.stackSave() + this.jspiSupported = canSuspend() + this.suspendableResume = this.jspiSupported ? WebAssembly.promising(this.lua_resume) : this.lua_resume if (this.jspiSupported) { this.installAwaitHook() } } - /** - * The `lua_resume` async runs are driven through: wrapped in `WebAssembly.promising`, so an - * `:await()` inside it can suspend the wasm stack. Where the platform has no JSPI it is the plain - * export, and a run is a resume nothing can suspend. - */ - public suspendableResume(): SuspendableResume { - this.suspendableResumeFunction ??= this.jspiSupported ? WebAssembly.promising(this.lua_resume) : this.lua_resume - return this.suspendableResumeFunction - } - /** * Saves the linear-memory stack while awaiting, then restores it in a synchronous C hook. * Restoring inside the async hook leaves a microtask gap before Wasm resumes: another ready @@ -1115,13 +1113,6 @@ export default class LuaModule { this.emscripten.HEAPU32[pointer >>> 2] = value } - /** - * Whether the platform has JSPI (the WebAssembly JavaScript Promise Integration API), which is - * what lets an `:await()` suspend the wasm stack. Without it everything else works and an - * `:await()` is an error. - */ - public readonly jspiSupported: boolean = canSuspend() - /** The current wasm stack pointer, saved so a suspended run's C frames can be restored. */ public stackSave(): number { return this.emscripten.stackSave() diff --git a/src/thread.ts b/src/thread.ts index 0db910f..0d86519 100755 --- a/src/thread.ts +++ b/src/thread.ts @@ -84,7 +84,7 @@ export default class Thread { private pendingInterrupt: LuaInterruptError | undefined private closeListeners: (() => void)[] | undefined - /** The driver itself is the run context; no separate context allocation is needed. */ + /** The limits of the run this thread is driving, as an `:await()` reads them when it parks. */ public get runLimits(): Readonly { return this.limits } @@ -328,7 +328,7 @@ export default class Thread { module.writePointer(nresPointer, 0) let pending: Promise | LuaReturn try { - pending = module.suspendableResume()(this.address, null, argCount, nresPointer) + pending = module.suspendableResume(this.address, null, argCount, nresPointer) } finally { // Restore the caller immediately, not when this suspended run eventually settles: a call // made while it is parked then reuses the C stack rather than growing past it. diff --git a/src/type-extensions/function.ts b/src/type-extensions/function.ts index 1475d8a..9d6cda4 100644 --- a/src/type-extensions/function.ts +++ b/src/type-extensions/function.ts @@ -63,13 +63,15 @@ export class FunctionTypeExtension extends TypeExtension { private readonly pooledCallThread: Thread private pooledCallThreadInUse = false private readonly functionTimeout: number | undefined - private readonly options: FunctionCallOptions + private readonly maxInstructions: number | undefined + private readonly onAsyncError: ((error: unknown) => void) | undefined public constructor(state: LuaState, options: FunctionCallOptions = {}) { super(state, 'js_function') - this.options = options this.functionTimeout = options.functionTimeout + this.maxInstructions = options.maxInstructions + this.onAsyncError = options.onAsyncError // Create a thread off of the global thread to be used to create function call threads without // interfering with the global context. This creates a callback context that will always exist // even if the thread that called getValue() has been destroyed. Neither anchor is ever @@ -307,7 +309,7 @@ export class FunctionTypeExtension extends TypeExtension { const { state } = this const module = state.module const raw = { receiveThread: true, receiveArgsQuantity: true } - const { onAsyncError } = this.options + const { onAsyncError } = this // Called with the function and then its arguments, which are still on the caller's stack. const start = decorate((caller: Thread, valueCount: number) => { const run = this.runCall((thread) => { @@ -357,7 +359,7 @@ export class FunctionTypeExtension extends TypeExtension { try { // The limits any other run starts under, and the function timeout on top of them. thread.setLimits(this.state.getLimits()) - const { functionTimeout: timeout, maxInstructions } = this.options + const { functionTimeout: timeout, maxInstructions } = this const defaults = timeout !== undefined || maxInstructions !== undefined const values = await thread.run(prepare(thread), defaults ? { timeout, maxInstructions, ...options } : options) return values[0] ?? undefined diff --git a/test/async.test.js b/test/async.test.js index a013fd2..68a042b 100644 --- a/test/async.test.js +++ b/test/async.test.js @@ -1,8 +1,4 @@ import { execFileSync } from 'node:child_process' -import { use } from 'chai' -import chaiAsPromised from 'chai-as-promised' - -use(chaiAsPromised) import { expect } from 'chai' import { LuaRuntime, LuaTimeoutError, LuaAbortError, LuaInstructionLimitError, LuaMultiReturn } from '../dist/index.js' import { getState } from './utils.js' @@ -38,7 +34,7 @@ describe('Async runs', () => { expect(result).to.be.eql([9]) }) - it('an unrepresentable top level yield no longer crashes the run', async () => { + it('an unrepresentable top level yield does not crash the run', async () => { using state = await getState() const result = await state.doString('coroutine.yield(io.stdout) return 7') expect(result).to.be.equal(7) From e477797b5ec08bce68223064e59869de66886375 Mon Sep 17 00:00:00 2001 From: ceifa Date: Sun, 15 Nov 2026 21:21:12 -0300 Subject: [PATCH 72/83] trim redundant comments --- src/async.ts | 22 +++++----------------- src/module.ts | 24 +++--------------------- src/thread.ts | 20 ++++++-------------- src/type-extension.ts | 1 - src/type-extensions/function.ts | 31 +++++++------------------------ src/type-extensions/promise.ts | 12 +++--------- test/async.test.js | 1 - 7 files changed, 24 insertions(+), 87 deletions(-) diff --git a/src/async.ts b/src/async.ts index 8d605cb..d8adbb7 100644 --- a/src/async.ts +++ b/src/async.ts @@ -21,10 +21,7 @@ const macrotask: (task: () => void) => void = (() => { return (task: () => void) => void setTimeout(task, 0) })() -/** - * Whether the platform has JSPI (the WebAssembly JavaScript Promise Integration API), which is what - * lets an `:await()` suspend the wasm stack. - */ +/** Whether the platform has JSPI, which is what lets an `:await()` suspend the wasm stack. */ export const canSuspend = (): boolean => typeof WebAssembly.Suspending === 'function' && typeof WebAssembly.promising === 'function' /** A promise that knows whether anything has asked for its outcome. */ @@ -69,11 +66,7 @@ export function reportIfUnobserved(run: Promise, report: (error: unknow */ export const yieldToEventLoop = (): Promise => new Promise((resolve) => macrotask(resolve)) -/** - * The interrupt a deadline or aborted signal calls for, or undefined when neither has fired. The - * single source of both the abort-vs-timeout classification and its message, shared by the debug - * hook's limit check and the await hook. - */ +/** The interrupt a deadline or aborted signal calls for, or undefined when neither has fired. */ export function limitError(signal: AbortSignal | undefined, deadline: number | undefined): LuaInterruptError | undefined { if (signal?.aborted) { return new LuaAbortError('thread aborted') @@ -101,11 +94,7 @@ export interface PendingSuspend { resume: (outcome: SettleOutcome) => number } -/** - * Awaits `promise`, but reports an interruption instead if `signal` aborts or `deadline` passes - * first. Used for an `onYield` handler, and by the await hook, which unwinds the suspended run with - * a Lua error when it is interrupted rather than waiting for the promise it was parked on. - */ +/** Awaits `promise`, but reports an interruption instead if `signal` aborts or `deadline` passes first. */ export function settleOrInterrupt(promise: unknown, signal: AbortSignal | undefined, deadline: number | undefined): Promise { const settled: Promise = Promise.resolve(promise).then( (value) => ({ status: 'fulfilled', value }), @@ -117,14 +106,13 @@ export function settleOrInterrupt(promise: unknown, signal: AbortSignal | undefi return new Promise((resolve) => { let timer: ReturnType | undefined - // Whichever comes first wins: resolving again does nothing, and neither does clearing. const finish = (outcome: SettleOutcome): void => { clearTimeout(timer) signal?.removeEventListener('abort', check) resolve(outcome) } - // The abort listener and the timer both end up here. A timer can fire early, and a delay - // above 2^31-1 overflows to 1ms in Node, so it is armed again until the deadline has passed. + // A timer can fire early, and a delay above 2^31-1 overflows to 1ms in Node, so it is armed + // again until the deadline has passed. const check = (): void => { const error = limitError(signal, deadline) if (error) { diff --git a/src/module.ts b/src/module.ts index b5dfb98..cdf9955 100755 --- a/src/module.ts +++ b/src/module.ts @@ -141,8 +141,7 @@ const INLINE_DECODE_LIMIT = 32 // The short strings read out of Lua are mostly the same few names over and over -- table keys, // globals, metamethod names -- so the string built for a run of bytes is kept and handed back the // next time those bytes are read, which also gives the property lookups it usually feeds the -// same, already internalized string. Direct mapped on a hash of the bytes; a power of two. Sized -// for a small working set of repeated names, since a full cache is memory every runtime keeps. +// same, already internalized string. Direct mapped on a hash of the bytes; a power of two. const DECODED_STRING_CACHE_SIZE = 32 // The wasm value types Emscripten's function signature letters map to. `p` is a pointer, which is @@ -553,9 +552,7 @@ export default class LuaModule { declare public lua_upvalueid: (L: LuaAddress, fidx: number, n: number) => LuaAddress declare public lua_upvaluejoin: (L: LuaAddress, fidx1: number, n1: number, fidx2: number, n2: number) => void declare public lua_sethook: (L: LuaAddress, func: number | null, mask: number, count: number) => void - /** Installs the await hook the {@link wasmoon_push_jsfunction} closures suspend through. */ declare public wasmoon_set_await_hook: (hook: number, resumeHook: number) => void - /** Pops the reference box on the stack and pushes a JS function closure over it and `callHook`. */ declare public wasmoon_push_jsfunction: (L: LuaAddress, callHook: number) => void declare public lua_gethook: (L: LuaAddress) => number declare public lua_gethookmask: (L: LuaAddress) => number @@ -580,7 +577,6 @@ export default class LuaModule { // index. Combining them keeps just one array slot per hole when a high live index prevents // trimming, instead of retaining separate value and count arrays. Records exist only while // live. External indices are one-based so a reference box never carries a null pointer. - // Released tails are trimmed when at least half the slots can be dropped. private readonly references: (ReferenceEntry | number)[] = [] private firstFreeReference = 0 private highestReference = 0 @@ -620,17 +616,9 @@ export default class LuaModule { * before resuming. See {@link installAwaitHook}. */ public readonly mainStackPointer: number - /** - * Whether the platform has JSPI (the WebAssembly JavaScript Promise Integration API), which is - * what lets an `:await()` suspend the wasm stack. Without it everything else works and an - * `:await()` is an error. - */ + /** Whether the platform has JSPI. Without it an `:await()` is an error and everything else works. */ public readonly jspiSupported: boolean - /** - * The `lua_resume` async runs are driven through: wrapped in `WebAssembly.promising`, so an - * `:await()` inside it can suspend the wasm stack. Where the platform has no JSPI it is the plain - * export, and a run is a resume nothing can suspend. - */ + /** `lua_resume` wrapped in `WebAssembly.promising`, or the plain export where there is no JSPI. */ public readonly suspendableResume: (...args: Parameters) => Promise | LuaReturn /** * Set true only while a promising resume is the innermost driver on the stack, so an `:await()` @@ -843,7 +831,6 @@ export default class LuaModule { throw new Error('failed to allocate the scratch buffers for C out parameters') } - // Captured while no Lua is running, so it is the top of the C stack in JS land. this.mainStackPointer = this.stackSave() this.jspiSupported = canSuspend() this.suspendableResume = this.jspiSupported ? WebAssembly.promising(this.lua_resume) : this.lua_resume @@ -862,8 +849,6 @@ export default class LuaModule { const resumes = new Map number>() let nextReference = 0 const awaitHook = this.emscripten.addFunction( - // The C signature passes the running coroutine, but it is always the one the await - // parked on, which the pendingSuspend marshallers already hold; nothing here needs it. new WebAssembly.Suspending(async (): Promise => { const suspend = this.pendingSuspend this.pendingSuspend = undefined @@ -899,8 +884,6 @@ export default class LuaModule { if (suspend.run.isClosed()) { throw new Error('the Lua state is closed') } - // Back on this run's stack: put its frames back before touching Lua, and mark the - // stack promising again for any further await this resume reaches. this.heap.set(savedStack, stackPointer) this.stackRestore(stackPointer) this.stackCanSuspend = true @@ -1011,7 +994,6 @@ export default class LuaModule { } const heap = this.heap if (length <= INLINE_DECODE_LIMIT) { - // One pass hashes the bytes, stopping at the first that is not ASCII. let hash = length let index = 0 while (index < length) { diff --git a/src/thread.ts b/src/thread.ts index 0d86519..14e3c67 100755 --- a/src/thread.ts +++ b/src/thread.ts @@ -40,10 +40,8 @@ const LUA_INTEGER_BITS = 64 const NO_RESTORE = (): void => undefined const NO_OPTIONS: Readonly = Object.freeze({}) /** - * The limits of a thread nothing has been set on, shared so a thread is not an object heavier than - * it has to be: a JS callback made from a coroutine gets a wrapper of its own each time. Frozen, so - * a write to it fails loudly; {@link Thread.setDeadline} is the one path that writes in place, and - * it takes an object of its own first. + * The limits of a thread nothing has been set on, shared because a JS callback made from a + * coroutine gets a thread wrapper of its own each time. Frozen, so a write to it fails loudly. */ const NO_LIMITS: Readonly = Object.freeze({}) @@ -145,8 +143,7 @@ export default class Thread { /** * Raises a limit error in the coroutine running at `L`: the debug hook's way of stopping a run, * and the await hook's for one parked past its deadline or on an aborted signal. The token is - * what {@link assertOk} recognises the error by. Returns what `lua_error` returns, which never - * actually returns. + * what {@link assertOk} recognises the error by. */ public interruptWith(error: LuaInterruptError, L = this.address): number { ;(this.module.activeRun ?? this).pendingInterrupt = error @@ -311,11 +308,7 @@ export default class Thread { } } - /** - * One `lua_resume` that an `:await()` can suspend. The promise it returns resolves only once the - * resume runs to a host yield, a return or an error; an await in between suspends and resumes - * the wasm stack without this seeing it. - */ + /** One `lua_resume` that an `:await()` can suspend, up to a host yield, a return or an error. */ private async resumeSuspendable(argCount: number, nresPointer: number): Promise { this.assertNotClosed() this.pendingInterrupt = undefined @@ -355,7 +348,7 @@ export default class Thread { /** * Pushes a JS value onto the stack as Lua results and returns how many: nothing for `undefined`, * `count` for a {@link RawResult}, one per element for a {@link MultiReturn}, else the single - * value. Shared by the run loop and the JS function wrapper. + * value. * @param nilOnUndefined Preserve undefined as one Lua nil, as `:await()` requires. */ public pushReturnValues(value: unknown, nilOnUndefined = false): number { @@ -663,8 +656,7 @@ export default class Thread { */ public setDeadline(deadline: number | undefined): void { this.assertNotClosed() - // In place rather than by copy, since a function timeout sets one on every call: only the - // shared empty snapshot is replaced, once, and by the thread's own object. + // In place rather than by copy, since a function timeout sets one on every call. if (this.limits === NO_LIMITS) { this.limits = {} } diff --git a/src/type-extension.ts b/src/type-extension.ts index 72a5629..1e90e88 100644 --- a/src/type-extension.ts +++ b/src/type-extension.ts @@ -147,7 +147,6 @@ export default abstract class LuaTypeExtension { module.lua_setmetatable(L, -2) if (wrapClosure !== undefined) { - // Pops the box and pushes a closure holding it as an upvalue. wrapClosure(L) } diff --git a/src/type-extensions/function.ts b/src/type-extensions/function.ts index 9d6cda4..bb31197 100644 --- a/src/type-extensions/function.ts +++ b/src/type-extensions/function.ts @@ -14,11 +14,8 @@ type LuaFunction = FunctionType & Record /** The parts of the state's options that bear on calling a Lua function. */ export interface FunctionCallOptions { - /** Milliseconds a Lua function called from JS may run before being interrupted. */ functionTimeout?: number | undefined - /** Instructions an asynchronous run of a function may execute, as for any other run. */ maxInstructions?: number | undefined - /** See `CreateStateOptions.onAsyncError`. */ onAsyncError?: ((error: unknown) => void) | undefined } @@ -26,7 +23,7 @@ const NO_OPTIONS: DecorationOptions = {} /** * What `async(fn)` returns, as a chunk that takes the JS function starting the run and gives back - * the function doing the wrapping. See {@link FunctionTypeExtension.injectAsync}. + * the function doing the wrapping. */ const ASYNC_SOURCE = `local start = ... return function(fn) @@ -47,8 +44,7 @@ export class FunctionTypeExtension extends TypeExtension { /** * Keys the registry reference on each Lua function handed to JS, which is how {@link async} * finds the function to run. A symbol of this state's own, so another state's function does not - * answer to it, and a property rather than a WeakMap entry, which cost more than the rest of - * creating the wrapper put together. + * answer to it, and a property rather than a WeakMap entry, which was slower to create. */ private readonly luaFunction = Symbol('wasmoon.luaFunction') @@ -129,8 +125,6 @@ export class FunctionTypeExtension extends TypeExtension { const result = target.apply(decorationOptions?.self, args) if (result === SUSPEND) { - // The JS function stashed a promise and asked to suspend: -1 tells the C - // trampoline to reach the await hook, which is the only value it treats specially. return -1 } return calledThread.pushReturnValues(result) @@ -209,8 +203,7 @@ export class FunctionTypeExtension extends TypeExtension { const referent: unknown = affectsCall(decoration.options) ? decoration : decoration.target // Pushed through the C trampoline rather than a bare closure, so an `:await()` inside the - // function can suspend the wasm stack. The trampoline holds the reference box as its first - // upvalue and the wrapper as its second. + // function can suspend the wasm stack. this.pushReference(thread, referent, (L) => this.state.module.wasmoon_push_jsfunction(L, this.functionWrapper)) return true } @@ -266,16 +259,10 @@ export class FunctionTypeExtension extends TypeExtension { return jsFunc } - /** Whether `value` is one of this state's Lua functions, as {@link getValue} hands them to JS. */ public isLuaFunction(value: unknown): value is FunctionType { return typeof value === 'function' && (value as LuaFunction)[this.luaFunction] !== undefined } - /** - * The asynchronous counterpart of a Lua function: calling what this returns starts the function - * as a run of its own instead of synchronously, which is what lets it `:await()`, and gives - * back a promise of its first result. - */ public async(jsFunc: FunctionType, options?: LuaRunOptions): (...args: unknown[]) => Promise { if (!this.isLuaFunction(jsFunc)) { throw new TypeError('async expects a Lua function obtained from this state') @@ -297,13 +284,10 @@ export class FunctionTypeExtension extends TypeExtension { } /** - * Defines the Lua global `async`: what `async function` is to JS. `async(fn)` returns a function - * that runs `fn` as a run of its own, so that it can `:await()` wherever it is called from, and - * hands back a promise of its first result. - * - * What it returns is a Lua closure over `fn`, built by {@link ASYNC_SOURCE}, rather than a JS - * function holding it: that way nothing has to be collected across the two heaps, and the - * arguments of a call move from one Lua stack to another without ever becoming JS values. + * Defines the Lua global `async`. What `async(fn)` returns is a Lua closure over `fn`, built by + * {@link ASYNC_SOURCE}, rather than a JS function holding it: that way nothing has to be + * collected across the two heaps, and the arguments of a call move from one Lua stack to + * another without ever becoming JS values. */ public injectAsync(): void { const { state } = this @@ -357,7 +341,6 @@ export class FunctionTypeExtension extends TypeExtension { // synchronous call made in the meantime. const { thread, reference } = this.callbackContext.newAnchoredThread() try { - // The limits any other run starts under, and the function timeout on top of them. thread.setLimits(this.state.getLimits()) const { functionTimeout: timeout, maxInstructions } = this const defaults = timeout !== undefined || maxInstructions !== undefined diff --git a/src/type-extensions/promise.ts b/src/type-extensions/promise.ts index 63422df..e872032 100644 --- a/src/type-extensions/promise.ts +++ b/src/type-extensions/promise.ts @@ -45,9 +45,6 @@ class PromiseTypeExtension extends TypeExtension> { await: decorate( (functionThread: Thread, rawSelf: unknown) => { const self = asPromise(rawSelf) - // Only a promising resume leaves a boundary the wasm stack can suspend to. A - // synchronous entry point (doStringSync, a JS→Lua callback) has JS frames in - // the way, and suspending through those traps. if (!state.module.stackCanSuspend) { throw new Error(state.module.jspiSupported ? SYNCHRONOUS_AWAIT : UNSUPPORTED_AWAIT) } @@ -84,13 +81,11 @@ class PromiseTypeExtension extends TypeExtension> { /** * Hands the promise and how to marshal its result to the module's await hook, then returns the - * sentinel that makes the C trampoline reach that hook and suspend the wasm stack. The stack - * unwinds to the promising resume driving the run and resumes there once the promise settles. + * sentinel that makes the C trampoline reach that hook and suspend the wasm stack. */ private suspend(thread: Thread, promise: Promise): typeof SUSPEND { - // Captured now so a deadline or abort observed while parked interrupts the run rather than - // waiting for the promise. Read from the resuming run, not this thread, whose JS wrapper is - // often a fresh object without the run's limits on it. + // Read from the run being resumed, not this thread, whose JS wrapper is often a fresh object + // without the run's limits on it. const run = this.state.module.activeRun! const { deadline, signal } = run.runLimits this.state.module.pendingSuspend = { @@ -110,7 +105,6 @@ class PromiseTypeExtension extends TypeExtension> { return SUSPEND } - /** Raises a rejected promise as a Lua error on `thread`. */ private marshalRejected(thread: Thread, error: unknown): number { thread.pushValue(error || new Error('promise rejected with no error')) return this.state.module.lua_error(thread.address) diff --git a/test/async.test.js b/test/async.test.js index 68a042b..c2db4f4 100644 --- a/test/async.test.js +++ b/test/async.test.js @@ -4,7 +4,6 @@ import { LuaRuntime, LuaTimeoutError, LuaAbortError, LuaInstructionLimitError, L import { getState } from './utils.js' const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) -/** Settles with `value` a moment later. */ const later = (value) => new Promise((resolve) => setTimeout(() => resolve(value), 1)) describe('Async runs', () => { From 5d99d387aaa3f449f7c58102146d72d172e99b58 Mon Sep 17 00:00:00 2001 From: ceifa Date: Thu, 19 Nov 2026 21:21:27 -0300 Subject: [PATCH 73/83] remove deno references --- .github/workflows/publish.yml | 31 ------------------------------- README.md | 2 +- 2 files changed, 1 insertion(+), 32 deletions(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index d5ffe80..b622272 100755 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -76,34 +76,3 @@ jobs: uses: JS-DevTools/npm-publish@v4 with: token: ${{ secrets.NPM_TOKEN }} - - # Emscripten still doesn't support deno - # publish_jsr: - # runs-on: ubuntu-latest - # needs: build - # permissions: - # contents: read - # id-token: write - # steps: - # - name: Download build artifact - # uses: actions/download-artifact@v8 - # with: - # name: build-artifact - # path: build-artifact - - # - name: Restore build artifact - # run: cp -r build-artifact/* . - - # - name: Generate jsr.json from package.json - # run: | - # node -e "const pkg = require('./package.json'); \ - # const jsr = { \ - # name: '@ceifa/' + pkg.name, \ - # version: pkg.version, \ - # exports: pkg.main, \ - # include: ['dist/**/*', 'bin/**/*'] - # }; \ - # require('fs').writeFileSync('jsr.json', JSON.stringify(jsr, null, 2));" - - # - name: Publish to JSR - # run: npx jsr publish diff --git a/README.md b/README.md index 153b32f..36d7611 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ This package aims to provide a way to: -- Embed Lua to any Node.js, Deno or Web Application. +- Embed Lua to any Node.js or Web Application. - Run lua code in any operational system - Interop Lua and JS without memory leaks (including the DOM) From b2845d3ab43141ff7090616d24171ef440b5d1c2 Mon Sep 17 00:00:00 2001 From: ceifa Date: Thu, 19 Nov 2026 21:26:08 -0300 Subject: [PATCH 74/83] generate the lua bindings from the headers utils/create-bindings.js now writes src/bindings.gen.ts and the emcc export list instead of printing blocks to paste, and build:wasm runs it. LuaModule extends the generated class, so each binding is declared once instead of in three hand-kept lists. No change to the bindings, their types or the wasm: the generated declarations match the hand-written ones, and glue.wasm and both glues come out byte for byte the same. --- .github/workflows/test.yml | 3 + .oxfmtrc.json | 2 +- README.md | 5 + src/bindings.gen.ts | 316 ++++++++++++++++++++++++++++++++++++ src/module.ts | 320 +------------------------------------ utils/build-wasm.js | 3 + utils/build-wasm.sh | 164 +------------------ utils/create-bindings.cjs | 220 ------------------------- utils/create-bindings.js | 209 ++++++++++++++++++++++++ utils/create-bindings.sh | 3 - 10 files changed, 547 insertions(+), 698 deletions(-) create mode 100644 src/bindings.gen.ts delete mode 100644 utils/create-bindings.cjs create mode 100644 utils/create-bindings.js delete mode 100755 utils/create-bindings.sh diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 6d2c7e5..ede4f3c 100755 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -28,6 +28,9 @@ jobs: - run: npm ci - run: npm run lint:nofix - run: npm run build:wasm + # build:wasm regenerates the bindings from the Lua headers, so a difference here means the + # committed file was edited by hand or left behind by a change to the generator. + - run: git diff --exit-code src/bindings.gen.ts - run: npm run build - run: npx playwright install --with-deps chromium - run: npm test diff --git a/.oxfmtrc.json b/.oxfmtrc.json index 600545a..7867648 100644 --- a/.oxfmtrc.json +++ b/.oxfmtrc.json @@ -7,5 +7,5 @@ "printWidth": 140, "tabWidth": 4, "sortPackageJson": false, - "ignorePatterns": ["rolldown.config.*.js"] + "ignorePatterns": ["rolldown.config.*.js", "src/bindings.gen.ts"] } diff --git a/README.md b/README.md index 153b32f..721739f 100644 --- a/README.md +++ b/README.md @@ -220,6 +220,11 @@ Building the wasm needs either [emscripten](https://emscripten.org/) or otherwise (always on Windows), so there is nothing to pick between. Drop the `:dev` for an optimized build. +The Lua C API bindings in `src/bindings.gen.ts`, and the list of functions the wasm exports, are +generated from the Lua headers by `utils/create-bindings.js`. `build:wasm` runs it, so after moving +the `lua` submodule the bindings follow; anything a header cannot say (a function to leave out, a +type to override) is listed at the top of that script. + ## Edge Cases ### Null diff --git a/src/bindings.gen.ts b/src/bindings.gen.ts new file mode 100644 index 0000000..3bca714 --- /dev/null +++ b/src/bindings.gen.ts @@ -0,0 +1,316 @@ +// Generated by utils/create-bindings.js from lua/lauxlib.h, lua/lua.h, lua/lualib.h. +// Do not edit: change the generator instead, and run it with `node utils/create-bindings.js`. +import type { LuaEmscriptenModule } from './module' +import type { LuaAddress, LuaReturn, LuaType } from './types' + +type Binding = (...args: any[]) => any + +/** + * The Lua C API, one binding for each function the wasm module exports. A binding that marshals a + * string or takes a lua_Integer is wrapped over the raw export; every other one crosses only + * numbers and is the export itself. + */ +export default abstract class LuaBindings { + public emscripten: LuaEmscriptenModule + + declare public luaL_checkversion_: (L: LuaAddress, ver: number, sz: number) => void + declare public luaL_getmetafield: (L: LuaAddress, obj: number, e: string | null) => LuaType + declare public luaL_callmeta: (L: LuaAddress, obj: number, e: string | null) => number + declare public luaL_argerror: (L: LuaAddress, arg: number, extramsg: string | null) => number + declare public luaL_typeerror: (L: LuaAddress, arg: number, tname: string | null) => number + declare public luaL_checklstring: (L: LuaAddress, arg: number, l: number | null) => string + declare public luaL_optlstring: (L: LuaAddress, arg: number, def: string | null, l: number | null) => string + declare public luaL_checknumber: (L: LuaAddress, arg: number) => number + declare public luaL_optnumber: (L: LuaAddress, arg: number, def: number) => number + declare public luaL_checkinteger: (L: LuaAddress, arg: number) => bigint + declare public luaL_optinteger: (L: LuaAddress, arg: number, def: bigint) => bigint + declare public luaL_checkstack: (L: LuaAddress, sz: number, msg: string | null) => void + declare public luaL_checktype: (L: LuaAddress, arg: number, t: number) => void + declare public luaL_checkany: (L: LuaAddress, arg: number) => void + declare public luaL_newmetatable: (L: LuaAddress, tname: string | null) => number + declare public luaL_setmetatable: (L: LuaAddress, tname: string | null) => void + declare public luaL_testudata: (L: LuaAddress, ud: number, tname: string | null) => LuaAddress + declare public luaL_checkudata: (L: LuaAddress, ud: number, tname: string | null) => LuaAddress + declare public luaL_where: (L: LuaAddress, lvl: number) => void + declare public luaL_fileresult: (L: LuaAddress, stat: number, fname: string | null) => number + declare public luaL_execresult: (L: LuaAddress, stat: number) => number + declare public luaL_ref: (L: LuaAddress, t: number) => number + declare public luaL_unref: (L: LuaAddress, t: number, ref: number) => void + declare public luaL_loadfilex: (L: LuaAddress, filename: string | null, mode: string | null) => LuaReturn + declare public luaL_loadbufferx: (L: LuaAddress, buff: string | number | null, sz: number, name: string | number | null, mode: string | null) => LuaReturn + declare public luaL_loadstring: (L: LuaAddress, s: string | null) => LuaReturn + declare public luaL_newstate: () => LuaAddress + declare public luaL_len: (L: LuaAddress, idx: number) => bigint + declare public luaL_addgsub: (b: number | null, s: string | null, p: string | null, r: string | null) => void + declare public luaL_gsub: (L: LuaAddress, s: string | null, p: string | null, r: string | null) => string + declare public luaL_setfuncs: (L: LuaAddress, l: number | null, nup: number) => void + declare public luaL_getsubtable: (L: LuaAddress, idx: number, fname: string | null) => number + declare public luaL_traceback: (L: LuaAddress, L1: LuaAddress, msg: string | null, level: number) => void + declare public luaL_requiref: (L: LuaAddress, modname: string | null, openf: number, glb: number) => void + declare public luaL_buffinit: (L: LuaAddress, B: number | null) => void + declare public luaL_prepbuffsize: (B: number | null, sz: number) => string + declare public luaL_addlstring: (B: number | null, s: string | null, l: number) => void + declare public luaL_addstring: (B: number | null, s: string | null) => void + declare public luaL_addvalue: (B: number | null) => void + declare public luaL_pushresult: (B: number | null) => void + declare public luaL_pushresultsize: (B: number | null, sz: number) => void + declare public luaL_buffinitsize: (L: LuaAddress, B: number | null, sz: number) => string + declare public lua_newstate: (f: number | null, ud: number | null, seed: number) => LuaAddress + declare public lua_close: (L: LuaAddress) => void + declare public lua_newthread: (L: LuaAddress) => LuaAddress + declare public lua_closethread: (L: LuaAddress, from: LuaAddress | null) => LuaReturn + declare public lua_atpanic: (L: LuaAddress, panicf: number) => number + declare public lua_version: (L: LuaAddress) => number + declare public lua_absindex: (L: LuaAddress, idx: number) => number + declare public lua_gettop: (L: LuaAddress) => number + declare public lua_settop: (L: LuaAddress, idx: number) => void + declare public lua_pushvalue: (L: LuaAddress, idx: number) => void + declare public lua_rotate: (L: LuaAddress, idx: number, n: number) => void + declare public lua_copy: (L: LuaAddress, fromidx: number, toidx: number) => void + declare public lua_checkstack: (L: LuaAddress, n: number) => number + declare public lua_xmove: (from: LuaAddress, to: LuaAddress, n: number) => void + declare public lua_isnumber: (L: LuaAddress, idx: number) => number + declare public lua_isstring: (L: LuaAddress, idx: number) => number + declare public lua_iscfunction: (L: LuaAddress, idx: number) => number + declare public lua_isinteger: (L: LuaAddress, idx: number) => number + declare public lua_isuserdata: (L: LuaAddress, idx: number) => number + declare public lua_type: (L: LuaAddress, idx: number) => LuaType + declare public lua_typename: (L: LuaAddress, tp: number) => string + declare public lua_tonumberx: (L: LuaAddress, idx: number, isnum: number | null) => number + declare public lua_tointegerx: (L: LuaAddress, idx: number, isnum: number | null) => bigint + declare public lua_toboolean: (L: LuaAddress, idx: number) => number + declare public lua_rawlen: (L: LuaAddress, idx: number) => bigint + declare public lua_tocfunction: (L: LuaAddress, idx: number) => number + declare public lua_touserdata: (L: LuaAddress, idx: number) => LuaAddress + declare public lua_tothread: (L: LuaAddress, idx: number) => LuaAddress + declare public lua_topointer: (L: LuaAddress, idx: number) => LuaAddress + declare public lua_arith: (L: LuaAddress, op: number) => void + declare public lua_rawequal: (L: LuaAddress, idx1: number, idx2: number) => number + declare public lua_compare: (L: LuaAddress, idx1: number, idx2: number, op: number) => number + declare public lua_pushnil: (L: LuaAddress) => void + declare public lua_pushnumber: (L: LuaAddress, n: number) => void + declare public lua_pushinteger: (L: LuaAddress, n: number | bigint) => void + declare public lua_pushlstring: (L: LuaAddress, s: number, len: number) => void + declare public lua_pushcclosure: (L: LuaAddress, fn: number, n: number) => void + declare public lua_pushboolean: (L: LuaAddress, b: number) => void + declare public lua_pushlightuserdata: (L: LuaAddress, p: number | null) => void + declare public lua_pushthread: (L: LuaAddress) => number + declare public lua_getglobal: (L: LuaAddress, name: string | null) => LuaType + declare public lua_gettable: (L: LuaAddress, idx: number) => LuaType + declare public lua_getfield: (L: LuaAddress, idx: number, k: string | null) => LuaType + declare public lua_geti: (L: LuaAddress, idx: number, n: number | bigint) => LuaType + declare public lua_rawget: (L: LuaAddress, idx: number) => LuaType + declare public lua_rawgeti: (L: LuaAddress, idx: number, n: number | bigint) => LuaType + declare public lua_rawgetp: (L: LuaAddress, idx: number, p: number | null) => LuaType + declare public lua_createtable: (L: LuaAddress, narr: number, nrec: number) => void + declare public lua_newuserdatauv: (L: LuaAddress, sz: number, nuvalue: number) => LuaAddress + declare public lua_getmetatable: (L: LuaAddress, objindex: number) => number + declare public lua_getiuservalue: (L: LuaAddress, idx: number, n: number) => LuaType + declare public lua_setglobal: (L: LuaAddress, name: string | null) => void + declare public lua_settable: (L: LuaAddress, idx: number) => void + declare public lua_setfield: (L: LuaAddress, idx: number, k: string | null) => void + declare public lua_seti: (L: LuaAddress, idx: number, n: number | bigint) => void + declare public lua_rawset: (L: LuaAddress, idx: number) => void + declare public lua_rawseti: (L: LuaAddress, idx: number, n: number | bigint) => void + declare public lua_rawsetp: (L: LuaAddress, idx: number, p: number | null) => void + declare public lua_setmetatable: (L: LuaAddress, objindex: number) => number + declare public lua_setiuservalue: (L: LuaAddress, idx: number, n: number) => number + declare public lua_callk: (L: LuaAddress, nargs: number, nresults: number, ctx: number, k: number | null) => void + declare public lua_pcallk: (L: LuaAddress, nargs: number, nresults: number, errfunc: number, ctx: number, k: number | null) => LuaReturn + declare public lua_load: (L: LuaAddress, reader: number | null, dt: number | null, chunkname: string | null, mode: string | null) => LuaReturn + declare public lua_dump: (L: LuaAddress, writer: number | null, data: number | null, strip: number) => number + declare public lua_yieldk: (L: LuaAddress, nresults: number, ctx: number, k: number | null) => number + declare public lua_resume: (L: LuaAddress, from: LuaAddress | null, narg: number, nres: number | null) => LuaReturn + declare public lua_status: (L: LuaAddress) => LuaReturn + declare public lua_isyieldable: (L: LuaAddress) => number + declare public lua_setwarnf: (L: LuaAddress, f: number | null, ud: number | null) => void + declare public lua_warning: (L: LuaAddress, msg: string | null, tocont: number) => void + declare public lua_error: (L: LuaAddress) => number + declare public lua_next: (L: LuaAddress, idx: number) => number + declare public lua_concat: (L: LuaAddress, n: number) => void + declare public lua_len: (L: LuaAddress, idx: number) => void + declare public lua_stringtonumber: (L: LuaAddress, s: string | null) => number + declare public lua_getallocf: (L: LuaAddress, ud: number | null) => number + declare public lua_setallocf: (L: LuaAddress, f: number | null, ud: number | null) => void + declare public lua_toclose: (L: LuaAddress, idx: number) => void + declare public lua_closeslot: (L: LuaAddress, idx: number) => void + declare public lua_getstack: (L: LuaAddress, level: number, ar: number | null) => number + declare public lua_getinfo: (L: LuaAddress, what: string | null, ar: number | null) => number + declare public lua_getlocal: (L: LuaAddress, ar: number | null, n: number) => string + declare public lua_setlocal: (L: LuaAddress, ar: number | null, n: number) => string + declare public lua_getupvalue: (L: LuaAddress, funcindex: number, n: number) => string + declare public lua_setupvalue: (L: LuaAddress, funcindex: number, n: number) => string + declare public lua_upvalueid: (L: LuaAddress, fidx: number, n: number) => LuaAddress + declare public lua_upvaluejoin: (L: LuaAddress, fidx1: number, n1: number, fidx2: number, n2: number) => void + declare public lua_sethook: (L: LuaAddress, func: number | null, mask: number, count: number) => void + declare public lua_gethook: (L: LuaAddress) => number + declare public lua_gethookmask: (L: LuaAddress) => number + declare public lua_gethookcount: (L: LuaAddress) => number + declare public luaopen_base: (L: LuaAddress) => number + declare public luaopen_package: (L: LuaAddress) => number + declare public luaopen_coroutine: (L: LuaAddress) => number + declare public luaopen_debug: (L: LuaAddress) => number + declare public luaopen_io: (L: LuaAddress) => number + declare public luaopen_math: (L: LuaAddress) => number + declare public luaopen_os: (L: LuaAddress) => number + declare public luaopen_string: (L: LuaAddress) => number + declare public luaopen_table: (L: LuaAddress) => number + declare public luaopen_utf8: (L: LuaAddress) => number + declare public luaL_openselectedlibs: (L: LuaAddress, load: number, preload: number) => void + + // Named stores in the constructor, rather than a loop over the names: that is what lets the + // engine lay the bindings out as fixed fields of the instance, which every call reads one of. + protected constructor(emscripten: LuaEmscriptenModule) { + this.emscripten = emscripten + + this.luaL_checkversion_ = this.exported('luaL_checkversion_') + this.luaL_getmetafield = this.wrapWithStringArguments(this.exported('luaL_getmetafield'), 'nnns') + this.luaL_callmeta = this.wrapWithStringArguments(this.exported('luaL_callmeta'), 'nnns') + this.luaL_argerror = this.wrapWithStringArguments(this.exported('luaL_argerror'), 'nnns') + this.luaL_typeerror = this.wrapWithStringArguments(this.exported('luaL_typeerror'), 'nnns') + this.luaL_checklstring = this.wrapWithStringArguments(this.exported('luaL_checklstring'), 'snnn') + this.luaL_optlstring = this.wrapWithStringArguments(this.exported('luaL_optlstring'), 'snnsn') + this.luaL_checknumber = this.exported('luaL_checknumber') + this.luaL_optnumber = this.exported('luaL_optnumber') + this.luaL_checkinteger = this.exported('luaL_checkinteger') + this.luaL_optinteger = this.exported('luaL_optinteger') + this.luaL_checkstack = this.wrapWithStringArguments(this.exported('luaL_checkstack'), 'nnns') + this.luaL_checktype = this.exported('luaL_checktype') + this.luaL_checkany = this.exported('luaL_checkany') + this.luaL_newmetatable = this.wrapWithStringArguments(this.exported('luaL_newmetatable'), 'nns') + this.luaL_setmetatable = this.wrapWithStringArguments(this.exported('luaL_setmetatable'), 'nns') + this.luaL_testudata = this.wrapWithStringArguments(this.exported('luaL_testudata'), 'nnns') + this.luaL_checkudata = this.wrapWithStringArguments(this.exported('luaL_checkudata'), 'nnns') + this.luaL_where = this.exported('luaL_where') + this.luaL_fileresult = this.wrapWithStringArguments(this.exported('luaL_fileresult'), 'nnns') + this.luaL_execresult = this.exported('luaL_execresult') + this.luaL_ref = this.exported('luaL_ref') + this.luaL_unref = this.exported('luaL_unref') + this.luaL_loadfilex = this.wrapWithStringArguments(this.exported('luaL_loadfilex'), 'nnss') + this.luaL_loadbufferx = this.wrapWithStringArguments(this.exported('luaL_loadbufferx'), 'nnSnSs') + this.luaL_loadstring = this.wrapWithStringArguments(this.exported('luaL_loadstring'), 'nns') + this.luaL_newstate = this.exported('luaL_newstate') + this.luaL_len = this.exported('luaL_len') + this.luaL_addgsub = this.wrapWithStringArguments(this.exported('luaL_addgsub'), 'nnsss') + this.luaL_gsub = this.wrapWithStringArguments(this.exported('luaL_gsub'), 'snsss') + this.luaL_setfuncs = this.exported('luaL_setfuncs') + this.luaL_getsubtable = this.wrapWithStringArguments(this.exported('luaL_getsubtable'), 'nnns') + this.luaL_traceback = this.wrapWithStringArguments(this.exported('luaL_traceback'), 'nnnsn') + this.luaL_requiref = this.wrapWithStringArguments(this.exported('luaL_requiref'), 'nnsnn') + this.luaL_buffinit = this.exported('luaL_buffinit') + this.luaL_prepbuffsize = this.wrapWithStringArguments(this.exported('luaL_prepbuffsize'), 'snn') + this.luaL_addlstring = this.wrapWithStringArguments(this.exported('luaL_addlstring'), 'nnsn') + this.luaL_addstring = this.wrapWithStringArguments(this.exported('luaL_addstring'), 'nns') + this.luaL_addvalue = this.exported('luaL_addvalue') + this.luaL_pushresult = this.exported('luaL_pushresult') + this.luaL_pushresultsize = this.exported('luaL_pushresultsize') + this.luaL_buffinitsize = this.wrapWithStringArguments(this.exported('luaL_buffinitsize'), 'snnn') + this.lua_newstate = this.exported('lua_newstate') + this.lua_close = this.exported('lua_close') + this.lua_newthread = this.exported('lua_newthread') + this.lua_closethread = this.exported('lua_closethread') + this.lua_atpanic = this.exported('lua_atpanic') + this.lua_version = this.exported('lua_version') + this.lua_absindex = this.exported('lua_absindex') + this.lua_gettop = this.exported('lua_gettop') + this.lua_settop = this.exported('lua_settop') + this.lua_pushvalue = this.exported('lua_pushvalue') + this.lua_rotate = this.exported('lua_rotate') + this.lua_copy = this.exported('lua_copy') + this.lua_checkstack = this.exported('lua_checkstack') + this.lua_xmove = this.exported('lua_xmove') + this.lua_isnumber = this.exported('lua_isnumber') + this.lua_isstring = this.exported('lua_isstring') + this.lua_iscfunction = this.exported('lua_iscfunction') + this.lua_isinteger = this.exported('lua_isinteger') + this.lua_isuserdata = this.exported('lua_isuserdata') + this.lua_type = this.exported('lua_type') + this.lua_typename = this.wrapWithStringArguments(this.exported('lua_typename'), 'snn') + this.lua_tonumberx = this.exported('lua_tonumberx') + this.lua_tointegerx = this.exported('lua_tointegerx') + this.lua_toboolean = this.exported('lua_toboolean') + this.lua_rawlen = this.exported('lua_rawlen') + this.lua_tocfunction = this.exported('lua_tocfunction') + this.lua_touserdata = this.exported('lua_touserdata') + this.lua_tothread = this.exported('lua_tothread') + this.lua_topointer = this.exported('lua_topointer') + this.lua_arith = this.exported('lua_arith') + this.lua_rawequal = this.exported('lua_rawequal') + this.lua_compare = this.exported('lua_compare') + this.lua_pushnil = this.exported('lua_pushnil') + this.lua_pushnumber = this.exported('lua_pushnumber') + this.lua_pushinteger = this.withIntegerArgument('lua_pushinteger', true) + this.lua_pushlstring = this.exported('lua_pushlstring') + this.lua_pushcclosure = this.exported('lua_pushcclosure') + this.lua_pushboolean = this.exported('lua_pushboolean') + this.lua_pushlightuserdata = this.exported('lua_pushlightuserdata') + this.lua_pushthread = this.exported('lua_pushthread') + this.lua_getglobal = this.wrapWithStringArguments(this.exported('lua_getglobal'), 'nns') + this.lua_gettable = this.exported('lua_gettable') + this.lua_getfield = this.wrapWithStringArguments(this.exported('lua_getfield'), 'nnns') + this.lua_geti = this.withIntegerArgument('lua_geti') + this.lua_rawget = this.exported('lua_rawget') + this.lua_rawgeti = this.withIntegerArgument('lua_rawgeti') + this.lua_rawgetp = this.exported('lua_rawgetp') + this.lua_createtable = this.exported('lua_createtable') + this.lua_newuserdatauv = this.exported('lua_newuserdatauv') + this.lua_getmetatable = this.exported('lua_getmetatable') + this.lua_getiuservalue = this.exported('lua_getiuservalue') + this.lua_setglobal = this.wrapWithStringArguments(this.exported('lua_setglobal'), 'nns') + this.lua_settable = this.exported('lua_settable') + this.lua_setfield = this.wrapWithStringArguments(this.exported('lua_setfield'), 'nnns') + this.lua_seti = this.withIntegerArgument('lua_seti') + this.lua_rawset = this.exported('lua_rawset') + this.lua_rawseti = this.withIntegerArgument('lua_rawseti') + this.lua_rawsetp = this.exported('lua_rawsetp') + this.lua_setmetatable = this.exported('lua_setmetatable') + this.lua_setiuservalue = this.exported('lua_setiuservalue') + this.lua_callk = this.exported('lua_callk') + this.lua_pcallk = this.exported('lua_pcallk') + this.lua_load = this.wrapWithStringArguments(this.exported('lua_load'), 'nnnnss') + this.lua_dump = this.exported('lua_dump') + this.lua_yieldk = this.exported('lua_yieldk') + this.lua_resume = this.exported('lua_resume') + this.lua_status = this.exported('lua_status') + this.lua_isyieldable = this.exported('lua_isyieldable') + this.lua_setwarnf = this.exported('lua_setwarnf') + this.lua_warning = this.wrapWithStringArguments(this.exported('lua_warning'), 'nnsn') + this.lua_error = this.exported('lua_error') + this.lua_next = this.exported('lua_next') + this.lua_concat = this.exported('lua_concat') + this.lua_len = this.exported('lua_len') + this.lua_stringtonumber = this.wrapWithStringArguments(this.exported('lua_stringtonumber'), 'nns') + this.lua_getallocf = this.exported('lua_getallocf') + this.lua_setallocf = this.exported('lua_setallocf') + this.lua_toclose = this.exported('lua_toclose') + this.lua_closeslot = this.exported('lua_closeslot') + this.lua_getstack = this.exported('lua_getstack') + this.lua_getinfo = this.wrapWithStringArguments(this.exported('lua_getinfo'), 'nnsn') + this.lua_getlocal = this.wrapWithStringArguments(this.exported('lua_getlocal'), 'snnn') + this.lua_setlocal = this.wrapWithStringArguments(this.exported('lua_setlocal'), 'snnn') + this.lua_getupvalue = this.wrapWithStringArguments(this.exported('lua_getupvalue'), 'snnn') + this.lua_setupvalue = this.wrapWithStringArguments(this.exported('lua_setupvalue'), 'snnn') + this.lua_upvalueid = this.exported('lua_upvalueid') + this.lua_upvaluejoin = this.exported('lua_upvaluejoin') + this.lua_sethook = this.exported('lua_sethook') + this.lua_gethook = this.exported('lua_gethook') + this.lua_gethookmask = this.exported('lua_gethookmask') + this.lua_gethookcount = this.exported('lua_gethookcount') + this.luaopen_base = this.exported('luaopen_base') + this.luaopen_package = this.exported('luaopen_package') + this.luaopen_coroutine = this.exported('luaopen_coroutine') + this.luaopen_debug = this.exported('luaopen_debug') + this.luaopen_io = this.exported('luaopen_io') + this.luaopen_math = this.exported('luaopen_math') + this.luaopen_os = this.exported('luaopen_os') + this.luaopen_string = this.exported('luaopen_string') + this.luaopen_table = this.exported('luaopen_table') + this.luaopen_utf8 = this.exported('luaopen_utf8') + this.luaL_openselectedlibs = this.exported('luaL_openselectedlibs') + } + + /** The wasm export `name`. */ + protected abstract exported(name: string): Binding + protected abstract wrapWithStringArguments(raw: Binding, signature: string): Binding + protected abstract withIntegerArgument(name: string, twoArguments?: boolean): Binding +} diff --git a/src/module.ts b/src/module.ts index cdf9955..e49fa8d 100755 --- a/src/module.ts +++ b/src/module.ts @@ -3,6 +3,7 @@ // `/// ` at the top of the emitted declarations to cover everyone // else. tsc drops the directive when it is written here, hence the build step. import initWasmModule from '../build/glue.js' +import LuaBindings from './bindings.gen' import { canSuspend, limitError, type PendingSuspend, settleOrInterrupt, type SettleOutcome, yieldToEventLoop } from './async' import type Thread from './thread' import { defaultWarnHandler, LUA_REGISTRYINDEX, type LuaAddress, LuaReturn, LuaType, type LuaWarnHandler, PointerSize } from './types' @@ -302,7 +303,7 @@ function createPreRun(config: PreRunConfig): (initializedModule: LuaEmscriptenMo } } -export default class LuaModule { +export default class LuaModule extends LuaBindings { public static async initialize(opts: Readonly = {}): Promise { const warn = opts.onWarn ?? defaultWarnHandler // Node rather than the browser, because the lookalikes (jsdom, an Electron renderer) are @@ -402,171 +403,13 @@ export default class LuaModule { } } - public emscripten: LuaEmscriptenModule /** The handler passed to {@link LuaModule.initialize}, which states created on it inherit. */ public readonly onWarn: LuaWarnHandler | undefined /** Which filesystem this module was loaded with, as {@link LuaModuleOptions.fs}. */ public readonly fs: LuaFileSystem - declare public luaL_checkversion_: (L: LuaAddress, ver: number, sz: number) => void - declare public luaL_getmetafield: (L: LuaAddress, obj: number, e: string | null) => LuaType - declare public luaL_callmeta: (L: LuaAddress, obj: number, e: string | null) => number - declare public luaL_argerror: (L: LuaAddress, arg: number, extramsg: string | null) => number - declare public luaL_typeerror: (L: LuaAddress, arg: number, tname: string | null) => number - declare public luaL_checklstring: (L: LuaAddress, arg: number, l: number | null) => string - declare public luaL_optlstring: (L: LuaAddress, arg: number, def: string | null, l: number | null) => string - declare public luaL_checknumber: (L: LuaAddress, arg: number) => number - declare public luaL_optnumber: (L: LuaAddress, arg: number, def: number) => number - // lua_Integer is 64 bit, and the module is built with WASM_BIGINT, so these cross as BigInt. - declare public luaL_checkinteger: (L: LuaAddress, arg: number) => bigint - declare public luaL_optinteger: (L: LuaAddress, arg: number, def: bigint) => bigint - declare public luaL_checkstack: (L: LuaAddress, sz: number, msg: string | null) => void - declare public luaL_checktype: (L: LuaAddress, arg: number, t: number) => void - declare public luaL_checkany: (L: LuaAddress, arg: number) => void - declare public luaL_newmetatable: (L: LuaAddress, tname: string | null) => number - declare public luaL_setmetatable: (L: LuaAddress, tname: string | null) => void - declare public luaL_testudata: (L: LuaAddress, ud: number, tname: string | null) => LuaAddress - declare public luaL_checkudata: (L: LuaAddress, ud: number, tname: string | null) => LuaAddress - declare public luaL_where: (L: LuaAddress, lvl: number) => void - declare public luaL_fileresult: (L: LuaAddress, stat: number, fname: string | null) => number - declare public luaL_execresult: (L: LuaAddress, stat: number) => number - declare public luaL_ref: (L: LuaAddress, t: number) => number - declare public luaL_unref: (L: LuaAddress, t: number, ref: number) => void - declare public luaL_loadfilex: (L: LuaAddress, filename: string | null, mode: string | null) => LuaReturn - declare public luaL_loadbufferx: ( - L: LuaAddress, - buff: string | number | null, - sz: number, - name: string | number | null, - mode: string | null, - ) => LuaReturn - declare public luaL_loadstring: (L: LuaAddress, s: string | null) => LuaReturn - declare public luaL_newstate: () => LuaAddress - declare public luaL_len: (L: LuaAddress, idx: number) => bigint - declare public luaL_addgsub: (b: number | null, s: string | null, p: string | null, r: string | null) => void - declare public luaL_gsub: (L: LuaAddress, s: string | null, p: string | null, r: string | null) => string - declare public luaL_setfuncs: (L: LuaAddress, l: number | null, nup: number) => void - declare public luaL_getsubtable: (L: LuaAddress, idx: number, fname: string | null) => number - declare public luaL_traceback: (L: LuaAddress, L1: LuaAddress, msg: string | null, level: number) => void - declare public luaL_requiref: (L: LuaAddress, modname: string | null, openf: number, glb: number) => void - declare public luaL_openselectedlibs: (L: LuaAddress, load: number, preload: number) => void - declare public luaL_buffinit: (L: LuaAddress, B: number | null) => void - declare public luaL_prepbuffsize: (B: number | null, sz: number) => string - declare public luaL_addlstring: (B: number | null, s: string | null, l: number) => void - declare public luaL_addstring: (B: number | null, s: string | null) => void - declare public luaL_addvalue: (B: number | null) => void - declare public luaL_pushresult: (B: number | null) => void - declare public luaL_pushresultsize: (B: number | null, sz: number) => void - declare public luaL_buffinitsize: (L: LuaAddress, B: number | null, sz: number) => string - declare public lua_newstate: (f: number | null, ud: number | null, seed: number) => LuaAddress - declare public lua_close: (L: LuaAddress) => void - declare public lua_newthread: (L: LuaAddress) => LuaAddress - declare public lua_closethread: (L: LuaAddress, from: LuaAddress | null) => LuaReturn - declare public lua_atpanic: (L: LuaAddress, panicf: number) => number - declare public lua_version: (L: LuaAddress) => number - declare public lua_absindex: (L: LuaAddress, idx: number) => number - declare public lua_gettop: (L: LuaAddress) => number - declare public lua_settop: (L: LuaAddress, idx: number) => void - declare public lua_pushvalue: (L: LuaAddress, idx: number) => void - declare public lua_rotate: (L: LuaAddress, idx: number, n: number) => void - declare public lua_copy: (L: LuaAddress, fromidx: number, toidx: number) => void - declare public lua_checkstack: (L: LuaAddress, n: number) => number - declare public lua_xmove: (from: LuaAddress, to: LuaAddress, n: number) => void - declare public lua_isnumber: (L: LuaAddress, idx: number) => number - declare public lua_isstring: (L: LuaAddress, idx: number) => number - declare public lua_iscfunction: (L: LuaAddress, idx: number) => number - declare public lua_isinteger: (L: LuaAddress, idx: number) => number - declare public lua_isuserdata: (L: LuaAddress, idx: number) => number - declare public lua_type: (L: LuaAddress, idx: number) => LuaType - declare public lua_typename: (L: LuaAddress, tp: number) => string - declare public lua_tonumberx: (L: LuaAddress, idx: number, isnum: number | null) => number - declare public lua_tointegerx: (L: LuaAddress, idx: number, isnum: number | null) => bigint - declare public lua_toboolean: (L: LuaAddress, idx: number) => number - declare public lua_rawlen: (L: LuaAddress, idx: number) => bigint - declare public lua_tocfunction: (L: LuaAddress, idx: number) => number - declare public lua_touserdata: (L: LuaAddress, idx: number) => LuaAddress - declare public lua_tothread: (L: LuaAddress, idx: number) => LuaAddress - declare public lua_topointer: (L: LuaAddress, idx: number) => LuaAddress - declare public lua_arith: (L: LuaAddress, op: number) => void - declare public lua_rawequal: (L: LuaAddress, idx1: number, idx2: number) => number - declare public lua_compare: (L: LuaAddress, idx1: number, idx2: number, op: number) => number - declare public lua_pushnil: (L: LuaAddress) => void - declare public lua_pushnumber: (L: LuaAddress, n: number) => void - declare public lua_pushinteger: (L: LuaAddress, n: number | bigint) => void - declare public lua_pushlstring: (L: LuaAddress, s: number, len: number) => void - declare public lua_pushcclosure: (L: LuaAddress, fn: number, n: number) => void - declare public lua_pushboolean: (L: LuaAddress, b: number) => void - declare public lua_pushlightuserdata: (L: LuaAddress, p: number | null) => void - declare public lua_pushthread: (L: LuaAddress) => number - declare public lua_getglobal: (L: LuaAddress, name: string | null) => LuaType - declare public lua_gettable: (L: LuaAddress, idx: number) => LuaType - declare public lua_getfield: (L: LuaAddress, idx: number, k: string | null) => LuaType - declare public lua_geti: (L: LuaAddress, idx: number, n: number | bigint) => LuaType - declare public lua_rawget: (L: LuaAddress, idx: number) => LuaType - declare public lua_rawgeti: (L: LuaAddress, idx: number, n: number | bigint) => LuaType - declare public lua_rawgetp: (L: LuaAddress, idx: number, p: number | null) => LuaType - declare public lua_createtable: (L: LuaAddress, narr: number, nrec: number) => void - declare public lua_newuserdatauv: (L: LuaAddress, sz: number, nuvalue: number) => LuaAddress - declare public lua_getmetatable: (L: LuaAddress, objindex: number) => number - declare public lua_getiuservalue: (L: LuaAddress, idx: number, n: number) => LuaType - declare public lua_setglobal: (L: LuaAddress, name: string | null) => void - declare public lua_settable: (L: LuaAddress, idx: number) => void - declare public lua_setfield: (L: LuaAddress, idx: number, k: string | null) => void - declare public lua_seti: (L: LuaAddress, idx: number, n: number | bigint) => void - declare public lua_rawset: (L: LuaAddress, idx: number) => void - declare public lua_rawseti: (L: LuaAddress, idx: number, n: number | bigint) => void - declare public lua_rawsetp: (L: LuaAddress, idx: number, p: number | null) => void - declare public lua_setmetatable: (L: LuaAddress, objindex: number) => number - declare public lua_setiuservalue: (L: LuaAddress, idx: number, n: number) => number - declare public lua_callk: (L: LuaAddress, nargs: number, nresults: number, ctx: number, k: number | null) => void - declare public lua_pcallk: (L: LuaAddress, nargs: number, nresults: number, errfunc: number, ctx: number, k: number | null) => LuaReturn - declare public lua_load: ( - L: LuaAddress, - reader: number | null, - dt: number | null, - chunkname: string | null, - mode: string | null, - ) => LuaReturn - declare public lua_dump: (L: LuaAddress, writer: number | null, data: number | null, strip: number) => number - declare public lua_yieldk: (L: LuaAddress, nresults: number, ctx: number, k: number | null) => number - declare public lua_resume: (L: LuaAddress, from: LuaAddress | null, narg: number, nres: number | null) => LuaReturn - declare public lua_status: (L: LuaAddress) => LuaReturn - declare public lua_isyieldable: (L: LuaAddress) => number - declare public lua_setwarnf: (L: LuaAddress, f: number | null, ud: number | null) => void - declare public lua_warning: (L: LuaAddress, msg: string | null, tocont: number) => void - declare public lua_error: (L: LuaAddress) => number - declare public lua_next: (L: LuaAddress, idx: number) => number - declare public lua_concat: (L: LuaAddress, n: number) => void - declare public lua_len: (L: LuaAddress, idx: number) => void - declare public lua_stringtonumber: (L: LuaAddress, s: string | null) => number - declare public lua_getallocf: (L: LuaAddress, ud: number | null) => number - declare public lua_setallocf: (L: LuaAddress, f: number | null, ud: number | null) => void - declare public lua_toclose: (L: LuaAddress, idx: number) => void - declare public lua_closeslot: (L: LuaAddress, idx: number) => void - declare public lua_getstack: (L: LuaAddress, level: number, ar: number | null) => number - declare public lua_getinfo: (L: LuaAddress, what: string | null, ar: number | null) => number - declare public lua_getlocal: (L: LuaAddress, ar: number | null, n: number) => string - declare public lua_setlocal: (L: LuaAddress, ar: number | null, n: number) => string - declare public lua_getupvalue: (L: LuaAddress, funcindex: number, n: number) => string - declare public lua_setupvalue: (L: LuaAddress, funcindex: number, n: number) => string - declare public lua_upvalueid: (L: LuaAddress, fidx: number, n: number) => LuaAddress - declare public lua_upvaluejoin: (L: LuaAddress, fidx1: number, n1: number, fidx2: number, n2: number) => void - declare public lua_sethook: (L: LuaAddress, func: number | null, mask: number, count: number) => void declare public wasmoon_set_await_hook: (hook: number, resumeHook: number) => void declare public wasmoon_push_jsfunction: (L: LuaAddress, callHook: number) => void - declare public lua_gethook: (L: LuaAddress) => number - declare public lua_gethookmask: (L: LuaAddress) => number - declare public lua_gethookcount: (L: LuaAddress) => number - declare public luaopen_base: (L: LuaAddress) => number - declare public luaopen_coroutine: (L: LuaAddress) => number - declare public luaopen_table: (L: LuaAddress) => number - declare public luaopen_io: (L: LuaAddress) => number - declare public luaopen_os: (L: LuaAddress) => number - declare public luaopen_string: (L: LuaAddress) => number - declare public luaopen_utf8: (L: LuaAddress) => number - declare public luaopen_math: (L: LuaAddress) => number - declare public luaopen_debug: (L: LuaAddress) => number - declare public luaopen_package: (L: LuaAddress) => number /** The mounts that are live, so a later one can be checked against them. */ private readonly mounts: ResolvedMount[] @@ -660,167 +503,18 @@ export default class LuaModule { fs: LuaFileSystem = 'memory', mounts: readonly ResolvedMount[] = [], ) { - this.emscripten = module + // Binds the Lua C API, which is generated from the headers: see utils/create-bindings.js. + super(module) this.onWarn = onWarn this.fs = fs this.mounts = [...mounts] - // The bindings that marshal a string or take a lua_Integer are wrapped over the raw export. - // Every other binding crosses only numbers and is the export itself. - this.luaL_getmetafield = this.wrapWithStringArguments(this.exported('luaL_getmetafield'), 'nnns') - this.luaL_callmeta = this.wrapWithStringArguments(this.exported('luaL_callmeta'), 'nnns') - this.luaL_argerror = this.wrapWithStringArguments(this.exported('luaL_argerror'), 'nnns') - this.luaL_typeerror = this.wrapWithStringArguments(this.exported('luaL_typeerror'), 'nnns') - this.luaL_checklstring = this.wrapWithStringArguments(this.exported('luaL_checklstring'), 'snnn') - this.luaL_optlstring = this.wrapWithStringArguments(this.exported('luaL_optlstring'), 'snnsn') - this.luaL_checkstack = this.wrapWithStringArguments(this.exported('luaL_checkstack'), 'nnns') - this.luaL_newmetatable = this.wrapWithStringArguments(this.exported('luaL_newmetatable'), 'nns') - this.luaL_setmetatable = this.wrapWithStringArguments(this.exported('luaL_setmetatable'), 'nns') - this.luaL_testudata = this.wrapWithStringArguments(this.exported('luaL_testudata'), 'nnns') - this.luaL_checkudata = this.wrapWithStringArguments(this.exported('luaL_checkudata'), 'nnns') - this.luaL_fileresult = this.wrapWithStringArguments(this.exported('luaL_fileresult'), 'nnns') - this.luaL_loadfilex = this.wrapWithStringArguments(this.exported('luaL_loadfilex'), 'nnss') - this.luaL_loadbufferx = this.wrapWithStringArguments(this.exported('luaL_loadbufferx'), 'nnSnSs') - this.luaL_loadstring = this.wrapWithStringArguments(this.exported('luaL_loadstring'), 'nns') - this.luaL_addgsub = this.wrapWithStringArguments(this.exported('luaL_addgsub'), 'nnsss') - this.luaL_gsub = this.wrapWithStringArguments(this.exported('luaL_gsub'), 'snsss') - this.luaL_getsubtable = this.wrapWithStringArguments(this.exported('luaL_getsubtable'), 'nnns') - this.luaL_traceback = this.wrapWithStringArguments(this.exported('luaL_traceback'), 'nnnsn') - this.luaL_requiref = this.wrapWithStringArguments(this.exported('luaL_requiref'), 'nnsnn') - this.luaL_prepbuffsize = this.wrapWithStringArguments(this.exported('luaL_prepbuffsize'), 'snn') - this.luaL_addlstring = this.wrapWithStringArguments(this.exported('luaL_addlstring'), 'nnsn') - this.luaL_addstring = this.wrapWithStringArguments(this.exported('luaL_addstring'), 'nns') - this.luaL_buffinitsize = this.wrapWithStringArguments(this.exported('luaL_buffinitsize'), 'snnn') - this.lua_typename = this.wrapWithStringArguments(this.exported('lua_typename'), 'snn') - this.lua_getglobal = this.wrapWithStringArguments(this.exported('lua_getglobal'), 'nns') - this.lua_getfield = this.wrapWithStringArguments(this.exported('lua_getfield'), 'nnns') - this.lua_setglobal = this.wrapWithStringArguments(this.exported('lua_setglobal'), 'nns') - this.lua_setfield = this.wrapWithStringArguments(this.exported('lua_setfield'), 'nnns') - this.lua_load = this.wrapWithStringArguments(this.exported('lua_load'), 'nnnnss') - this.lua_warning = this.wrapWithStringArguments(this.exported('lua_warning'), 'nnsn') - this.lua_stringtonumber = this.wrapWithStringArguments(this.exported('lua_stringtonumber'), 'nns') - this.lua_getinfo = this.wrapWithStringArguments(this.exported('lua_getinfo'), 'nnsn') - this.lua_getlocal = this.wrapWithStringArguments(this.exported('lua_getlocal'), 'snnn') - this.lua_setlocal = this.wrapWithStringArguments(this.exported('lua_setlocal'), 'snnn') - this.lua_getupvalue = this.wrapWithStringArguments(this.exported('lua_getupvalue'), 'snnn') - this.lua_setupvalue = this.wrapWithStringArguments(this.exported('lua_setupvalue'), 'snnn') - this.lua_pushinteger = this.withIntegerArgument('lua_pushinteger', true) - this.lua_geti = this.withIntegerArgument('lua_geti') - this.lua_rawgeti = this.withIntegerArgument('lua_rawgeti') - this.lua_seti = this.withIntegerArgument('lua_seti') - this.lua_rawseti = this.withIntegerArgument('lua_rawseti') - this.rawLuaGc = this.exported('lua_gc') this.rawLuaToLString = this.exported('lua_tolstring') this.rawLuaLToLString = this.exported('luaL_tolstring') this.rawLuaPushString = this.exported('lua_pushstring') - - // Numeric bindings are the exports themselves. Named stores avoid enumerating every - // field and assigning bindings through computed property names on each construction. - this.luaL_checkversion_ = this.exported('luaL_checkversion_') - this.luaL_checknumber = this.exported('luaL_checknumber') - this.luaL_optnumber = this.exported('luaL_optnumber') - this.luaL_checkinteger = this.exported('luaL_checkinteger') - this.luaL_optinteger = this.exported('luaL_optinteger') - this.luaL_checktype = this.exported('luaL_checktype') - this.luaL_checkany = this.exported('luaL_checkany') - this.luaL_where = this.exported('luaL_where') - this.luaL_execresult = this.exported('luaL_execresult') - this.luaL_ref = this.exported('luaL_ref') - this.luaL_unref = this.exported('luaL_unref') - this.luaL_newstate = this.exported('luaL_newstate') - this.luaL_len = this.exported('luaL_len') - this.luaL_setfuncs = this.exported('luaL_setfuncs') - this.luaL_openselectedlibs = this.exported('luaL_openselectedlibs') - this.luaL_buffinit = this.exported('luaL_buffinit') - this.luaL_addvalue = this.exported('luaL_addvalue') - this.luaL_pushresult = this.exported('luaL_pushresult') - this.luaL_pushresultsize = this.exported('luaL_pushresultsize') - this.lua_newstate = this.exported('lua_newstate') - this.lua_close = this.exported('lua_close') - this.lua_newthread = this.exported('lua_newthread') - this.lua_closethread = this.exported('lua_closethread') - this.lua_atpanic = this.exported('lua_atpanic') - this.lua_version = this.exported('lua_version') - this.lua_absindex = this.exported('lua_absindex') - this.lua_gettop = this.exported('lua_gettop') - this.lua_settop = this.exported('lua_settop') - this.lua_pushvalue = this.exported('lua_pushvalue') - this.lua_rotate = this.exported('lua_rotate') - this.lua_copy = this.exported('lua_copy') - this.lua_checkstack = this.exported('lua_checkstack') - this.lua_xmove = this.exported('lua_xmove') - this.lua_isnumber = this.exported('lua_isnumber') - this.lua_isstring = this.exported('lua_isstring') - this.lua_iscfunction = this.exported('lua_iscfunction') - this.lua_isinteger = this.exported('lua_isinteger') - this.lua_isuserdata = this.exported('lua_isuserdata') - this.lua_type = this.exported('lua_type') - this.lua_tonumberx = this.exported('lua_tonumberx') - this.lua_tointegerx = this.exported('lua_tointegerx') - this.lua_toboolean = this.exported('lua_toboolean') - this.lua_rawlen = this.exported('lua_rawlen') - this.lua_tocfunction = this.exported('lua_tocfunction') - this.lua_touserdata = this.exported('lua_touserdata') - this.lua_tothread = this.exported('lua_tothread') - this.lua_topointer = this.exported('lua_topointer') - this.lua_arith = this.exported('lua_arith') - this.lua_rawequal = this.exported('lua_rawequal') - this.lua_compare = this.exported('lua_compare') - this.lua_pushnil = this.exported('lua_pushnil') - this.lua_pushnumber = this.exported('lua_pushnumber') - this.lua_pushlstring = this.exported('lua_pushlstring') - this.lua_pushcclosure = this.exported('lua_pushcclosure') - this.lua_pushboolean = this.exported('lua_pushboolean') - this.lua_pushlightuserdata = this.exported('lua_pushlightuserdata') - this.lua_pushthread = this.exported('lua_pushthread') - this.lua_gettable = this.exported('lua_gettable') - this.lua_rawget = this.exported('lua_rawget') - this.lua_rawgetp = this.exported('lua_rawgetp') - this.lua_createtable = this.exported('lua_createtable') - this.lua_newuserdatauv = this.exported('lua_newuserdatauv') - this.lua_getmetatable = this.exported('lua_getmetatable') - this.lua_getiuservalue = this.exported('lua_getiuservalue') - this.lua_settable = this.exported('lua_settable') - this.lua_rawset = this.exported('lua_rawset') - this.lua_rawsetp = this.exported('lua_rawsetp') - this.lua_setmetatable = this.exported('lua_setmetatable') - this.lua_setiuservalue = this.exported('lua_setiuservalue') - this.lua_callk = this.exported('lua_callk') - this.lua_pcallk = this.exported('lua_pcallk') - this.lua_dump = this.exported('lua_dump') - this.lua_yieldk = this.exported('lua_yieldk') - this.lua_resume = this.exported('lua_resume') - this.lua_status = this.exported('lua_status') - this.lua_isyieldable = this.exported('lua_isyieldable') - this.lua_setwarnf = this.exported('lua_setwarnf') - this.lua_error = this.exported('lua_error') - this.lua_next = this.exported('lua_next') - this.lua_concat = this.exported('lua_concat') - this.lua_len = this.exported('lua_len') - this.lua_getallocf = this.exported('lua_getallocf') - this.lua_setallocf = this.exported('lua_setallocf') - this.lua_toclose = this.exported('lua_toclose') - this.lua_closeslot = this.exported('lua_closeslot') - this.lua_getstack = this.exported('lua_getstack') - this.lua_upvalueid = this.exported('lua_upvalueid') - this.lua_upvaluejoin = this.exported('lua_upvaluejoin') - this.lua_sethook = this.exported('lua_sethook') this.wasmoon_set_await_hook = this.exported('wasmoon_set_await_hook') this.wasmoon_push_jsfunction = this.exported('wasmoon_push_jsfunction') - this.lua_gethook = this.exported('lua_gethook') - this.lua_gethookmask = this.exported('lua_gethookmask') - this.lua_gethookcount = this.exported('lua_gethookcount') - this.luaopen_base = this.exported('luaopen_base') - this.luaopen_coroutine = this.exported('luaopen_coroutine') - this.luaopen_table = this.exported('luaopen_table') - this.luaopen_io = this.exported('luaopen_io') - this.luaopen_os = this.exported('luaopen_os') - this.luaopen_string = this.exported('luaopen_string') - this.luaopen_utf8 = this.exported('luaopen_utf8') - this.luaopen_math = this.exported('luaopen_math') - this.luaopen_debug = this.exported('luaopen_debug') - this.luaopen_package = this.exported('luaopen_package') this.sizeScratch = module._malloc(PointerSize) this.resultCountScratch = module._malloc(PointerSize) @@ -1355,7 +1049,7 @@ export default class LuaModule { * double taking twin of the same name in src/native/wasmoon.c, saving the BigInt conversion on * every call. The integer is the last argument of each of these. */ - private withIntegerArgument(name: string, twoArguments = false): (...args: any[]) => any { + protected withIntegerArgument(name: string, twoArguments = false): (...args: any[]) => any { const bigintBinding = this.exported(name) const numberBinding = this.exported(name.replace('lua_', 'wasmoon_')) @@ -1372,7 +1066,7 @@ export default class LuaModule { } /** The wasm export `name`, which for a function that crosses only numbers is the binding itself. */ - private exported(name: string): (...args: any[]) => any { + protected exported(name: string): (...args: any[]) => any { const raw = (this.emscripten as unknown as Record)[`_${name}`] if (typeof raw !== 'function') { throw new Error(`the wasm module does not export '${name}'`) @@ -1389,7 +1083,7 @@ export default class LuaModule { * argument positions and the arity are unrolled. Which slots hold a C string is fixed when the * binding is wrapped, so it is not worked out per call. */ - private wrapWithStringArguments(raw: (...args: any[]) => any, signature: string): (...args: any[]) => any { + protected wrapWithStringArguments(raw: (...args: any[]) => any, signature: string): (...args: any[]) => any { const emscripten = this.emscripten const arity = signature.length - 1 if (arity < 2 || arity > 5) { diff --git a/utils/build-wasm.js b/utils/build-wasm.js index 4913605..1836927 100644 --- a/utils/build-wasm.js +++ b/utils/build-wasm.js @@ -16,6 +16,9 @@ const execute = (command) => { } execute('git submodule update --init --recursive') +// On the host rather than in the script below, which may run in a container: what it writes into +// src/ would belong to that container's user. +execute(`node "${resolve(rootdir, 'utils/create-bindings.js')}"`) if (isUnix) { let emccInstalled = false diff --git a/utils/build-wasm.sh b/utils/build-wasm.sh index 27cc68e..ebde0ff 100755 --- a/utils/build-wasm.sh +++ b/utils/build-wasm.sh @@ -64,167 +64,9 @@ COMMON=( # The engines package.json promises, so the glue carries no fallbacks for older ones. The browser # minimums go on the web glue alone below: the host glue is Node only and would warn about them. -s MIN_NODE_VERSION=260000 - -s EXPORTED_FUNCTIONS="[ - '_malloc', \ - '_free', \ - '_realloc', \ - '_luaL_checkversion_', \ - '_luaL_getmetafield', \ - '_luaL_callmeta', \ - '_luaL_tolstring', \ - '_luaL_argerror', \ - '_luaL_typeerror', \ - '_luaL_checklstring', \ - '_luaL_optlstring', \ - '_luaL_checknumber', \ - '_luaL_optnumber', \ - '_luaL_checkinteger', \ - '_luaL_optinteger', \ - '_luaL_checkstack', \ - '_luaL_checktype', \ - '_luaL_checkany', \ - '_luaL_newmetatable', \ - '_luaL_setmetatable', \ - '_luaL_testudata', \ - '_luaL_checkudata', \ - '_luaL_where', \ - '_luaL_fileresult', \ - '_luaL_execresult', \ - '_luaL_ref', \ - '_luaL_unref', \ - '_luaL_loadfilex', \ - '_luaL_loadbufferx', \ - '_luaL_loadstring', \ - '_luaL_newstate', \ - '_luaL_len', \ - '_luaL_addgsub', \ - '_luaL_gsub', \ - '_luaL_setfuncs', \ - '_luaL_getsubtable', \ - '_luaL_traceback', \ - '_luaL_requiref', \ - '_luaL_buffinit', \ - '_luaL_prepbuffsize', \ - '_luaL_addlstring', \ - '_luaL_addstring', \ - '_luaL_addvalue', \ - '_luaL_pushresult', \ - '_luaL_pushresultsize', \ - '_luaL_buffinitsize', \ - '_lua_newstate', \ - '_lua_close', \ - '_lua_newthread', \ - '_lua_closethread', \ - '_lua_atpanic', \ - '_lua_version', \ - '_lua_absindex', \ - '_lua_gettop', \ - '_lua_settop', \ - '_lua_pushvalue', \ - '_lua_rotate', \ - '_lua_copy', \ - '_lua_checkstack', \ - '_lua_xmove', \ - '_lua_isnumber', \ - '_lua_isstring', \ - '_lua_iscfunction', \ - '_lua_isinteger', \ - '_lua_isuserdata', \ - '_lua_type', \ - '_lua_typename', \ - '_lua_tonumberx', \ - '_lua_tointegerx', \ - '_lua_toboolean', \ - '_lua_tolstring', \ - '_lua_rawlen', \ - '_lua_tocfunction', \ - '_lua_touserdata', \ - '_lua_tothread', \ - '_lua_topointer', \ - '_lua_arith', \ - '_lua_rawequal', \ - '_lua_compare', \ - '_lua_pushnil', \ - '_lua_pushnumber', \ - '_lua_pushinteger', \ - '_lua_pushlstring', \ - '_lua_pushstring', \ - '_lua_pushcclosure', \ - '_lua_pushboolean', \ - '_lua_pushlightuserdata', \ - '_lua_pushthread', \ - '_lua_getglobal', \ - '_lua_gettable', \ - '_lua_getfield', \ - '_lua_geti', \ - '_lua_rawget', \ - '_lua_rawgeti', \ - '_lua_rawgetp', \ - '_lua_createtable', \ - '_lua_newuserdatauv', \ - '_lua_getmetatable', \ - '_lua_getiuservalue', \ - '_lua_setglobal', \ - '_lua_settable', \ - '_lua_setfield', \ - '_lua_seti', \ - '_lua_rawset', \ - '_lua_rawseti', \ - '_lua_rawsetp', \ - '_lua_setmetatable', \ - '_lua_setiuservalue', \ - '_lua_callk', \ - '_lua_pcallk', \ - '_lua_load', \ - '_lua_dump', \ - '_lua_yieldk', \ - '_lua_resume', \ - '_lua_status', \ - '_lua_isyieldable', \ - '_lua_setwarnf', \ - '_lua_warning', \ - '_lua_error', \ - '_lua_next', \ - '_lua_concat', \ - '_lua_len', \ - '_lua_stringtonumber', \ - '_lua_getallocf', \ - '_lua_setallocf', \ - '_lua_toclose', \ - '_lua_closeslot', \ - '_lua_getstack', \ - '_lua_getinfo', \ - '_lua_getlocal', \ - '_lua_setlocal', \ - '_lua_getupvalue', \ - '_lua_setupvalue', \ - '_lua_upvalueid', \ - '_lua_upvaluejoin', \ - '_lua_sethook', \ - '_lua_gethook', \ - '_lua_gethookmask', \ - '_lua_gethookcount', \ - '_luaopen_base', \ - '_luaopen_coroutine', \ - '_luaopen_table', \ - '_luaopen_io', \ - '_luaopen_os', \ - '_luaopen_string', \ - '_luaopen_utf8', \ - '_luaopen_math', \ - '_luaopen_debug', \ - '_luaopen_package', \ - '_luaL_openselectedlibs', \ - '_lua_gc', \ - '_wasmoon_isarray', \ - '_wasmoon_pushinteger', \ - '_wasmoon_geti', \ - '_wasmoon_rawgeti', \ - '_wasmoon_seti', \ - '_wasmoon_rawseti', \ - '_wasmoon_set_await_hook', \ - '_wasmoon_push_jsfunction' \ - ]" + # The Lua C API and the functions of src/native/wasmoon.c, as listed by create-bindings.js from + # the headers. build-wasm.js runs it ahead of this script. + -s EXPORTED_FUNCTIONS=@../build/exported-functions.json ) # The default glue, for every environment. Its filesystem is Emscripten's in-memory one, and diff --git a/utils/create-bindings.cjs b/utils/create-bindings.cjs deleted file mode 100644 index 08d009b..0000000 --- a/utils/create-bindings.cjs +++ /dev/null @@ -1,220 +0,0 @@ -#!/usr/bin/env node - -const readline = require('readline') -const fs = require('fs') - -const rl = readline.createInterface({ - input: process.stdin, - terminal: false, -}) - -String.prototype.replaceAll = function (str, newStr) { - return this.split(str).join(newStr) -} - -const allFunctions = [] -const types = [] - -const functionPointerTypes = ['lua_KFunction', 'lua_Reader', 'lua_Writer', 'lua_Alloc', 'lua_Hook', 'lua_WarnFunction'] - -const bindingTypes = { - 'void': null, - 'lua_State*': 'number', - 'lua_Number': 'number', - 'size_t': 'number', - 'int': 'number', - 'char*': 'string', - 'size_t*': 'number', - 'lua_Integer': 'number', - 'void*': 'number', - 'luaL_Buffer*': 'number', - 'luaL_Reg*': 'number', - 'lua_CFunction': 'number', - 'int*': 'number', - 'lua_Unsigned': 'number', - 'lua_KContext': 'number', - 'lua_Debug*': 'number', -} - -const typescriptTypes = { - 'void': 'void', - 'lua_State*': 'LuaState', - 'lua_Number': 'number', - 'size_t': 'number', - 'int': 'number', - 'char*': 'string', - 'size_t*': 'number', - 'lua_Integer': 'number', - 'void*': 'number', - 'luaL_Buffer*': 'number', - 'luaL_Reg*': 'number', - 'lua_CFunction': 'number', - 'int*': 'number', - 'lua_Unsigned': 'number', - 'lua_KContext': 'number', - 'lua_Debug*': 'number', -} - -const functionsThatReturnType = [ - 'lua_getfield', - 'lua_getglobal', - 'lua_geti', - 'lua_gettable', - 'lua_getiuservalue', - 'lua_rawgeti', - 'lua_rawgetp', - 'lua_type', - 'luaL_getmetafield', - 'luaL_getmetatable', -] - -const functionsThatReturnState = [ - 'lua_load', - 'lua_pcall', - 'lua_resetthread', - 'lua_resume', - 'lua_status', - 'luaL_dofile', - 'luaL_dostring', - 'luaL_loadbuffer', - 'luaL_loadbufferx', - 'luaL_loadfile', - 'luaL_loadfilex', - 'luaL_loadstring', -] - -const bannedFunctions = [ - // Not a defined function in our builds. - 'debug_realloc', - // Accepts string array - 'luaL_checkoption', - 'luaB_opentests', -] - -function mapTsType(type, name) { - if (name && functionsThatReturnType.includes(name)) { - return 'LuaType' - } - if (name && functionsThatReturnState.includes(name)) { - return 'LuaReturn' - } - const mapped = typescriptTypes[type] - if (mapped === undefined) { - throw new Error('missing ts mapping') - } - if (type.endsWith('*') && mapped !== 'LuaState' && !name) { - // Pointers can be null, cast to nullptr. - return `${mapped} | null` - } - return mapped -} - -function parseNamedSymbol(symbol) { - const isPointer = symbol.includes('*') - - const [type, name] = symbol - .replaceAll('const', '') - .replaceAll('unsigned', '') - .replaceAll('*', '') - .split(' ') - .map((val) => val.trim()) - .filter((val) => !!val) - if (functionPointerTypes.includes(type)) { - return { type: 'void*', name } - } - const saneType = isPointer ? `${type}*` : type - types.push(saneType) - - return { type: saneType, name } -} - -function parseLine(line) { - const argStart = line.lastIndexOf('(') - if (argStart < 0) { - console.warn('Cannot find parameters on line', line) - return undefined - } - const starter = line.substring(0, argStart) - const retPlusSymbol = starter.substring(line.indexOf(' ')).replaceAll('(', ' ').replaceAll(')', '') - const rawArgs = line.substring(argStart).substring(1).split(')')[0].split(',') - return { - definition: parseNamedSymbol(retPlusSymbol), - args: rawArgs.map((arg) => parseNamedSymbol(arg)).filter((arg) => arg.type !== 'void'), - } -} - -rl.on('line', (file) => { - const rawFile = fs.readFileSync(file).toString() - - const statements = rawFile - .replace(/\/\*[\s\S]*?\*\/|\/\/.*/g, '') - .replaceAll('\\\n', '') - .split('\n') - .filter((line) => !line.trim().startsWith('#')) - .join('\n') - .split(';') - .map((statement) => statement.trim()) - const apiStatements = statements - .filter((statement) => { - const starter = statement.trim().split(' ')[0] - return starter.includes('_API') - }) - .map((statement) => statement.replaceAll('\n', '')) - allFunctions.push(...apiStatements.map((statement) => parseLine(statement)).filter((statement) => !!statement)) -}) - -rl.on('close', () => { - const bindings = allFunctions - .map((fn) => { - try { - if (bannedFunctions.includes(fn.definition.name)) { - throw new Error('skipping banned function') - } - const argArray = fn.args.map((arg) => { - const type = bindingTypes[arg.type] - if (type === undefined) { - throw new Error('missing binding type') - } - if (!arg.name) { - throw new Error('missing argument name') - } - return type === null ? null : `'${type}'` - }) - const returnType = bindingTypes[fn.definition.type] - if (returnType === undefined) { - throw new Error('missing binding return type') - } - const quotedReturn = returnType === null ? null : `'${returnType}'` - const binding = `this.${fn.definition.name} = this.module.cwrap('${fn.definition.name}', ${quotedReturn}, [${argArray.join( - ', ', - )}])` - - // public lua_newstate: (allocatorFunction: number, userData: number | null) => LuaState - const tsParams = fn.args.map((arg) => { - let mapped = mapTsType(arg.type) - if (fn.definition.name === 'lua_resume' && arg.name === 'from') { - mapped = `${mapped} | null` - } - return `${arg.name}: ${mapped}` - }) - const tsReturn = mapTsType(fn.definition.type, fn.definition.name) - const header = `public ${fn.definition.name}: (${tsParams.join(', ')}) => ${tsReturn}` - - const sh = ` '_${fn.definition.name}', \\` - - return { binding, header, sh } - } catch (err) { - console.warn(err.message, fn) - return undefined - } - }) - .filter((val) => !!val) - - console.log(bindings.map((binding) => binding.binding).join('\n')) - console.log('\n\n') - console.log(bindings.map((binding) => binding.header).join('\n')) - console.log('\n\n') - console.log(bindings.map((binding) => binding.sh).join('\n')) - - console.log(Array.from(new Set(types))) -}) diff --git a/utils/create-bindings.js b/utils/create-bindings.js new file mode 100644 index 0000000..bbe41b8 --- /dev/null +++ b/utils/create-bindings.js @@ -0,0 +1,209 @@ +// Turns the Lua headers into the two lists that have to agree with them: the bindings class +// LuaModule extends, and the functions emcc keeps in the wasm. Run by `npm run build:wasm`, and on +// its own (`node utils/create-bindings.js`) after moving the lua submodule. +import { mkdirSync, readFileSync, writeFileSync } from 'node:fs' +import { resolve } from 'node:path' + +const rootdir = resolve(import.meta.dirname, '..') +const HEADERS = ['lauxlib.h', 'lua.h', 'lualib.h'] +const BINDINGS_FILE = 'src/bindings.gen.ts' +const EXPORTS_FILE = 'build/exported-functions.json' + +// In the headers but not in the wasm. A variadic function is left out without being listed here. +const SKIPPED = [ + // Takes an array of strings. + 'luaL_checkoption', + // New in Lua 5.5 and not exposed so far. Removing a name from here is all it takes. + 'luaL_alloc', + 'luaL_makeseed', + 'lua_numbertocstring', + 'lua_pushexternalstring', +] + +// In the wasm, but bound by hand in src/module.ts: Lua strings carry a length, and lua_gc is variadic. +const HANDWRITTEN = ['lua_gc', 'lua_tolstring', 'luaL_tolstring', 'lua_pushstring'] + +const RETURNS_TYPE = [ + 'luaL_getmetafield', + 'lua_type', + 'lua_getglobal', + 'lua_gettable', + 'lua_getfield', + 'lua_geti', + 'lua_rawget', + 'lua_rawgeti', + 'lua_rawgetp', + 'lua_getiuservalue', +] + +const RETURNS_STATUS = [ + 'luaL_loadfilex', + 'luaL_loadbufferx', + 'luaL_loadstring', + 'lua_closethread', + 'lua_pcallk', + 'lua_load', + 'lua_resume', + 'lua_status', +] + +// Where the type a declaration maps to is not the one the binding takes. +const OVERRIDES = { + // The buffer and the chunk name can also be pointers, and neither is a name worth caching. + luaL_loadbufferx: { params: { buff: 'string | number | null', name: 'string | number | null' }, signature: 'nnSnSs' }, + // Takes a pointer and a length, so nothing is marshalled and the returned copy is not read. + lua_pushlstring: { params: { s: 'number' }, returns: 'void', raw: true }, + lua_closethread: { params: { from: 'LuaAddress | null' } }, + lua_resume: { params: { from: 'LuaAddress | null' } }, +} + +const NUMBERS = ['int', 'unsigned', 'size_t', 'lua_Number', 'lua_KContext'] +// 64 bit, and the module is built with WASM_BIGINT, so these cross as BigInt. +const BIGINTS = ['lua_Integer', 'lua_Unsigned'] +const NULLABLE_FUNCTION_POINTERS = ['lua_KFunction', 'lua_Reader', 'lua_Writer', 'lua_Alloc', 'lua_Hook', 'lua_WarnFunction'] + +function paramType(type) { + if (type === 'lua_State*') return 'LuaAddress' + if (type === 'char*') return 'string | null' + if (NUMBERS.includes(type) || type === 'lua_CFunction') return 'number' + if (BIGINTS.includes(type)) return 'bigint' + if (type.endsWith('*') || NULLABLE_FUNCTION_POINTERS.includes(type)) return 'number | null' + throw new Error(`no binding type for a '${type}' parameter`) +} + +function returnType(type, name) { + if (RETURNS_TYPE.includes(name)) return 'LuaType' + if (RETURNS_STATUS.includes(name)) return 'LuaReturn' + if (type === 'void') return 'void' + if (type === 'char*') return 'string' + if (type === 'lua_State*' || type === 'void*') return 'LuaAddress' + if (NUMBERS.includes(type) || type === 'lua_CFunction' || NULLABLE_FUNCTION_POINTERS.includes(type)) return 'number' + if (BIGINTS.includes(type)) return 'bigint' + throw new Error(`no binding type for a '${type}' return`) +} + +/** `const char *s` as `{ type: 'char*', name: 's' }`. */ +function parseSymbol(symbol) { + const words = symbol + .replace(/\bconst\b/g, '') + .replace(/\*/g, ' * ') + .trim() + .split(/\s+/) + const name = words.at(-1) === '*' || words.length === 1 ? undefined : words.pop() + return { type: words.join(''), name } +} + +/** Every function a header declares with LUA_API, LUALIB_API or LUAMOD_API. */ +function parseHeader(file) { + const statements = readFileSync(resolve(rootdir, 'lua', file), 'utf8') + .replace(/\/\*[\s\S]*?\*\//g, '') + .replace(/\\\n/g, '') + .split('\n') + .filter((line) => !line.trim().startsWith('#')) + .join(' ') + .split(';') + + const functions = [] + for (const statement of statements) { + const match = /^\s*(?:LUA|LUALIB|LUAMOD)_API\s+(.+?)\(?\b(\w+)\)?\s*\((.*)\)\s*$/.exec(statement) + if (!match) { + continue + } + const [, returns, name, params] = match + functions.push({ + name, + returns: parseSymbol(`${returns} ${name}`).type, + variadic: /\.\.\.|\bva_list\b/.test(params), + params: params.trim() === 'void' ? [] : params.split(',').map(parseSymbol), + }) + } + return functions +} + +/** The functions src/native/wasmoon.c defines for the JS side, all of which are exported. */ +function parseNativeExports() { + const source = readFileSync(resolve(rootdir, 'src/native/wasmoon.c'), 'utf8') + return [...source.matchAll(/^(?!static\b)\w[\w \t*]*?\b(wasmoon_\w+)\s*\(/gm)].map((match) => match[1]) +} + +const nativeExports = parseNativeExports() +const declared = HEADERS.flatMap(parseHeader) + +for (const name of [...SKIPPED, ...HANDWRITTEN, ...RETURNS_TYPE, ...RETURNS_STATUS, ...Object.keys(OVERRIDES)]) { + if (!declared.some((fn) => fn.name === name)) { + // A function Lua renamed or removed would otherwise leave its special case behind unnoticed. + throw new Error(`create-bindings lists '${name}', which the Lua headers no longer declare`) + } +} + +const exported = declared.filter((fn) => !SKIPPED.includes(fn.name) && (!fn.variadic || HANDWRITTEN.includes(fn.name))) +const bound = exported.filter((fn) => !HANDWRITTEN.includes(fn.name)) + +const declarations = [] +const assignments = [] +for (const fn of bound) { + const override = OVERRIDES[fn.name] ?? {} + for (const param of fn.params) { + if (!param.name) { + throw new Error(`${fn.name} declares a parameter with no name`) + } + } + + // A number that is a safe integer goes to the double taking twin in src/native/wasmoon.c. + const integerTwin = fn.params.at(-1)?.type === 'lua_Integer' && nativeExports.includes(fn.name.replace('lua_', 'wasmoon_')) + const params = fn.params.map((param, index) => { + const type = override.params?.[param.name] ?? paramType(param.type) + return `${param.name}: ${integerTwin && index === fn.params.length - 1 ? 'number | bigint' : type}` + }) + declarations.push(` declare public ${fn.name}: (${params.join(', ')}) => ${override.returns ?? returnType(fn.returns, fn.name)}`) + + // `s` marks a C string, in the return position first; see LuaModule.wrapWithStringArguments. + const signature = + override.signature ?? [fn.returns, ...fn.params.map((param) => param.type)].map((type) => (type === 'char*' ? 's' : 'n')).join('') + if (integerTwin) { + assignments.push(` this.${fn.name} = this.withIntegerArgument('${fn.name}'${fn.params.length === 2 ? ', true' : ''})`) + } else if (signature.includes('s') && !override.raw) { + assignments.push(` this.${fn.name} = this.wrapWithStringArguments(this.exported('${fn.name}'), '${signature}')`) + } else { + assignments.push(` this.${fn.name} = this.exported('${fn.name}')`) + } +} + +const bindings = `// Generated by utils/create-bindings.js from ${HEADERS.map((header) => `lua/${header}`).join(', ')}. +// Do not edit: change the generator instead, and run it with \`node utils/create-bindings.js\`. +import type { LuaEmscriptenModule } from './module' +import type { LuaAddress, LuaReturn, LuaType } from './types' + +type Binding = (...args: any[]) => any + +/** + * The Lua C API, one binding for each function the wasm module exports. A binding that marshals a + * string or takes a lua_Integer is wrapped over the raw export; every other one crosses only + * numbers and is the export itself. + */ +export default abstract class LuaBindings { + public emscripten: LuaEmscriptenModule + +${declarations.join('\n')} + + // Named stores in the constructor, rather than a loop over the names: that is what lets the + // engine lay the bindings out as fixed fields of the instance, which every call reads one of. + protected constructor(emscripten: LuaEmscriptenModule) { + this.emscripten = emscripten + +${assignments.join('\n')} + } + + /** The wasm export \`name\`. */ + protected abstract exported(name: string): Binding + protected abstract wrapWithStringArguments(raw: Binding, signature: string): Binding + protected abstract withIntegerArgument(name: string, twoArguments?: boolean): Binding +} +` + +const exportedFunctions = ['malloc', 'free', 'realloc', ...exported.map((fn) => fn.name), ...nativeExports].map((name) => `_${name}`) + +mkdirSync(resolve(rootdir, 'build'), { recursive: true }) +writeFileSync(resolve(rootdir, BINDINGS_FILE), bindings) +writeFileSync(resolve(rootdir, EXPORTS_FILE), `${JSON.stringify(exportedFunctions, null, 4)}\n`) +console.log(`create-bindings: ${bound.length} bindings in ${BINDINGS_FILE}, ${exportedFunctions.length} exports in ${EXPORTS_FILE}`) diff --git a/utils/create-bindings.sh b/utils/create-bindings.sh deleted file mode 100755 index 036c15e..0000000 --- a/utils/create-bindings.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/sh -e - -find ../lua/ -name "*.h" | ./create-bindings.cjs From 5ffbbd02f87c0b51d5b9f17cc428922145db0f3f Mon Sep 17 00:00:00 2001 From: ceifa Date: Thu, 19 Nov 2026 21:28:30 -0300 Subject: [PATCH 75/83] drop the readme note about the bindings generator --- README.md | 5 ----- 1 file changed, 5 deletions(-) diff --git a/README.md b/README.md index 721739f..153b32f 100644 --- a/README.md +++ b/README.md @@ -220,11 +220,6 @@ Building the wasm needs either [emscripten](https://emscripten.org/) or otherwise (always on Windows), so there is nothing to pick between. Drop the `:dev` for an optimized build. -The Lua C API bindings in `src/bindings.gen.ts`, and the list of functions the wasm exports, are -generated from the Lua headers by `utils/create-bindings.js`. `build:wasm` runs it, so after moving -the `lua` submodule the bindings follow; anything a header cannot say (a function to leave out, a -type to override) is listed at the top of that script. - ## Edge Cases ### Null From 936576dcd83960261357c2ca7c6e8299dc1f61f9 Mon Sep 17 00:00:00 2001 From: ceifa Date: Thu, 19 Nov 2026 22:06:52 -0300 Subject: [PATCH 76/83] declarative marshalling, one limits vocabulary copy/proxy/opaque/raw replace decorate, defineType and defineClass replace registerTypeExtension and its priorities, and a function is no longer guessed to be a class. LuaLimits (timeout, maxInstructions, signal) is the one shape for state.limits and for a run's options, and applies to every run, including a call of a Lua function and one made from inside another. --- README.md | 149 ++++++++- src/cli.js | 1 - src/decoration.ts | 51 --- src/index.ts | 14 +- src/marshal.ts | 99 ++++++ src/marshaller.ts | 219 ++++++++++++ src/module.ts | 8 +- src/raw-result.ts | 3 - src/state.ts | 185 ++++++----- src/thread.ts | 358 ++++++++++---------- src/type-extension.ts | 97 ++++-- src/type-extensions/class.ts | 220 +++++++++++++ src/type-extensions/defined.ts | 74 +++++ src/type-extensions/error.ts | 59 ++-- src/type-extensions/function.ts | 181 +++++----- src/type-extensions/null.ts | 18 +- src/type-extensions/promise.ts | 62 ++-- src/type-extensions/proxy.ts | 103 +++--- src/type-extensions/table.ts | 23 +- src/type-extensions/userdata.ts | 20 +- src/types.ts | 131 +++++--- test/api.test.js | 568 +++++++++++++++++++++++++++----- test/async.test.js | 8 +- test/bundling.test.js | 4 +- test/errors.test.js | 119 ++++--- test/initialization.test.js | 10 +- test/limits.test.js | 223 ++++++++++++- test/promises.test.js | 2 +- test/state.test.js | 231 +++++++++---- 29 files changed, 2366 insertions(+), 874 deletions(-) delete mode 100755 src/decoration.ts create mode 100644 src/marshal.ts create mode 100644 src/marshaller.ts delete mode 100644 src/raw-result.ts create mode 100644 src/type-extensions/class.ts create mode 100644 src/type-extensions/defined.ts diff --git a/README.md b/README.md index 153b32f..a04ba15 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,151 @@ sandbox. `lua.close()` closes every state created from it, and both types suppor await using lua = await LuaRuntime.load() ``` +## Passing values + +A value crosses into Lua by what it is, unless you say otherwise: + +| JS value | in Lua | +| --------------------------------- | ------------------------------------------------------------------------- | +| number, bigint, string, boolean | the same value | +| `undefined`, `null` | `nil` (see [Null](#null)) | +| function | a function | +| promise | a userdata with `:await()`, `:next()`, `:catch()` and `:finally()` | +| `Error` | a read-only userdata that renders as its message | +| any other object, arrays included | a proxy: a userdata that forwards to the object, which keeps its identity | + +A proxy exposes the object's members, so `obj.field`, `obj:method()`, `#arr`, `pairs(obj)` and +`arr[1]` (an array is indexed from 1, anything else by the key given) all reach the JS object. +Create the state with `objects: 'copy'` and an object is copied into a plain Lua table instead. + +An error exposes its `message`, `name`, `stack` and whatever it carries as own properties (`code`, +`cause`, ...), and nothing inherited. + +Coming back, a Lua table is copied into an object or an array, a Lua function becomes a JS +function, and a userdata that came from JS is the JS value it was. + +### One value: `copy`, `proxy`, `opaque`, `raw` + +```js +import { copy, proxy, opaque, raw } from 'wasmoon' + +// Plain Lua data, all the way down, whatever the state's `objects` says +state.set('config', copy({ retries: 3, hosts: ['a', 'b'] })) +// By reference. On a function it makes the function indexable, and `.new(...)` constructs +state.set('Date', proxy(Date)) // Date.now(), Date.new(0):toISOString() +// By reference with nothing reachable: Lua can hold it and hand it back +state.set('session', opaque(session)) +// A function that works on the Lua stack itself and returns how many values it pushed +state.set( + 'swap', + raw((thread) => { + thread.module.lua_rotate(thread.address, 1, 1) + return 2 + }), +) +``` + +They work anywhere a value crosses, a return value or a field of a copied object included. With +`objects: 'copy'` they, and the two below, are the only ways Lua gets to reach into a JS object. + +A function is always a function: nothing guesses whether it is a class. Wrap one in `proxy` to +reach its static members and construct it with `.new`, or define it. + +### A class: `defineClass` + +```js +class Vector { + static zero = () => new Vector(0, 0) + + constructor(x, y) { + this.x = x + this.y = y + } + + get length() { + return Math.hypot(this.x, this.y) + } + + add(other) { + return new Vector(this.x + other.x, this.y + other.y) + } +} + +state.defineClass(Vector, { + // Optional: the only members Lua can reach. Without it, all of them. + members: ['x', 'y', 'length', 'add'], + // Optional: metamethods, called with the instance first + metamethods: { __tostring: (v) => `(${v.x}, ${v.y})`, __add: (a, b) => a.add(b) }, +}) +state.set('Vector', Vector) + +await state.doString(` + local v = Vector(3, 4) + Vector.zero() -- or Vector.new(3, 4) + print(v, v.length, v:add(v).x) -- (3, 4) 5 6 +`) +``` + +Every instance, wherever it comes from, then crosses by reference as a userdata named after the +class, and reads back as itself. Methods follow Lua's convention and nothing else: the receiver is +the first argument, which `v:add(w)` passes and `v.add(w)` does not. An instance of a subclass uses +the nearest class that was defined. + +### A kind of value: `defineType` + +```js +// By reference, with a metatable of its own +state.defineType({ + name: 'Point', + match: (value) => value instanceof Point, + metatable: { __tostring: (point) => `Point(${point.x}, ${point.y})` }, +}) + +// Or converted on the way in, and back on the way out +state.defineType({ + name: 'Map', + match: (value) => value instanceof Map, + toLua: (map) => copy(Object.fromEntries(map)), + fromLua: (table) => new Map(Object.entries(table)), +}) +``` + +`fromLua` is given what the table reads as, for a table `toLua` produced and for one Lua code gave +a metatable whose `__name` is the type's name. + +The order is the whole rule: a wrapped value crosses the way its wrapper says; then the types take +what they match, the most recently defined first; then the classes take their instances, the most +derived first; and everything else goes by the table above. + +## Limits + +A run is each entry from JS into Lua: a `doString` or `doFile`, a call of a Lua function, and the +runs that `state.async`, Lua's `async` and a promise reaction start. What a run may use is said +with the same three fields everywhere: + +```js +// What every run on the state starts under +const state = lua.createState({ limits: { timeout: 1000, maxInstructions: 10_000_000 } }) + +// One run, where each field given replaces the state's, and Infinity lifts it +await state.doString(script, { timeout: 50, signal: controller.signal }) +await state.async(handler, { timeout: Infinity })(request) + +// Later runs, leaving the ones under way alone +state.limits.timeout = 200 +``` + +- `timeout`: milliseconds the run may take, awaits included. Raises `LuaTimeoutError`. +- `maxInstructions`: instructions it may execute. Raises `LuaInstructionLimitError`. +- `signal`: an `AbortSignal` that interrupts it. Raises `LuaAbortError`. + +All three extend `LuaInterruptError`. A run made from inside another, by a JS function that Lua +called calling back into Lua, stays within the outer one's limits as well as its own: it cannot +outlast its deadline, it spends from its budget (counted in steps of a thousand instructions), and +its signal aborts it. A run that goes on after its caller returns, as every asynchronous one does, +is on its own. + +`createState({ memory: { max } })` caps what a state may allocate, and `state.memory.max` changes it. + ## Filesystem Every state on a runtime shares one filesystem. By default it is in memory: the same in Node, the @@ -303,8 +448,8 @@ end) print("res", res:await()) ``` -Each call of an asynchronous function is a run like a `doString`, under the same limits, with -`limits.functionTimeout` on top. +Each call of an asynchronous function is a run like a `doString`, under the same +[limits](#limits). As with an async function in JS, an error in one rejects the promise it returned. When a JS API called it and dropped that promise, the rejection is unhandled, which by default ends a Node diff --git a/src/cli.js b/src/cli.js index 2d070a1..7d920a3 100755 --- a/src/cli.js +++ b/src/cli.js @@ -377,7 +377,6 @@ async function run({ argv, actions, forceInteractive, showVersion, ignoreEnv, sc const stackTop = state.getTop() const thread = state.newThread() try { - thread.setLimits(state.getLimits()) load(thread) for (const scriptArg of scriptArgs) { thread.pushValue(scriptArg) diff --git a/src/decoration.ts b/src/decoration.ts deleted file mode 100755 index 04d57ac..0000000 --- a/src/decoration.ts +++ /dev/null @@ -1,51 +0,0 @@ -/** - * How a value should be marshalled into Lua. - * - * - `'userdata'` wraps it in an opaque userdata holding a JS reference, with no members exposed. - * - `'proxy'` wraps it in a userdata whose metatable forwards index/call back into JS. - * - `'value'` skips the proxy layer, so objects are copied into Lua tables and functions are - * pushed as plain Lua functions. - * - * Leaving it undefined keeps the default behaviour for the state's `objects` option. - */ -export type DecorationTarget = 'userdata' | 'proxy' | 'value' - -export class Decoration { - public constructor( - public target: T, - public options: DecorationOptions, - ) {} -} - -/** - * A metatable to attach to a pushed value. Decorating it controls how it is pushed; on its own it - * is copied into a plain Lua table. - */ -export type LuaMetatable = object | Decoration - -export interface DecorationOptions { - /** Metatable to attach to the pushed value, itself decoratable to control how it is pushed. */ - metatable?: LuaMetatable | undefined - as?: DecorationTarget | undefined - /** Function only: bound as the receiver, and dropped from the argument list. */ - self?: unknown - /** Function only: receives the calling thread as the first argument. */ - receiveThread?: boolean | undefined - /** - * Function only: receives the argument count instead of the decoded arguments, and is - * expected to read the stack itself. This is a raw-level escape hatch. - */ - receiveArgsQuantity?: boolean | undefined -} - -/** - * Attaches marshalling instructions to a value before pushing it into Lua. - * - * ```js - * state.set('opaque', decorate(new Thing(), { as: 'userdata' })) - * state.set('bound', decorate(thing.method, { self: thing })) - * ``` - */ -export function decorate(target: T, options: DecorationOptions = {}): Decoration { - return new Decoration(target, options) -} diff --git a/src/index.ts b/src/index.ts index 32f34aa..894484e 100755 --- a/src/index.ts +++ b/src/index.ts @@ -1,10 +1,9 @@ export { default as LuaRuntime } from './runtime' export { default as LuaState, type LuaMemory } from './state' export type { default as LuaGarbageCollector } from './gc' -export { default as LuaThread, type OrderedExtension } from './thread' +export { default as LuaThread } from './thread' export { default as LuaMultiReturn } from './multireturn' -export { default as LuaRawResult } from './raw-result' -export { decorate, Decoration, type DecorationOptions, type DecorationTarget, type LuaMetatable } from './decoration' +export { copy, proxy, opaque, raw, LuaMarshalled, type LuaCopyOptions, type LuaMarshalMode, type LuaRawFunction } from './marshal' // Export the underlying bindings to allow users to just // use the bindings rather than the wrappers. export { @@ -16,9 +15,6 @@ export { type LuaFileSystem, type LuaModuleOptions, } from './module' -export { default as LuaTypeExtension } from './type-extension' -// The built in extensions are not exported, but the value types they marshal are, so a custom -// extension can describe what it handles. export type { FunctionType } from './type-extensions/function' export type { TableType } from './type-extensions/table' // Named rather than `export *`, so the library bitmask helpers and the warn default stay internal. @@ -44,14 +40,16 @@ export { type LuaWarnHandler, type CreateStateOptions, type LuaMemoryOptions, - type LuaLimitOptions, + type LuaLimits, + type LuaClass, + type LuaClassOptions, + type LuaTypeDefinition, type LuaGcOptions, type LuaGcMode, type LuaGcParam, type LuaRunOptions, type LuaLoadOptions, type LuaDoOptions, - type LuaThreadLimits, type LuaResumeResult, type LuaGetCache, type LuaPushCache, diff --git a/src/marshal.ts b/src/marshal.ts new file mode 100644 index 0000000..497ba1c --- /dev/null +++ b/src/marshal.ts @@ -0,0 +1,99 @@ +import type Thread from './thread' + +/** How a {@link LuaMarshalled} value crosses into Lua. `'method'` is the proxy's own, never handed out. */ +export type LuaMarshalMode = 'copy' | 'proxy' | 'opaque' | 'raw' | 'method' + +/** + * A value together with how it crosses into Lua, made by {@link copy}, {@link proxy}, + * {@link opaque} or {@link raw}. Without one a value crosses the way its type does by default. + */ +export class LuaMarshalled { + public constructor( + public readonly target: T, + public readonly as: LuaMarshalMode, + /** `copy` only: see {@link LuaCopyOptions.metatable}. */ + public readonly metatable?: object, + ) {} +} + +export interface LuaCopyOptions { + /** + * A metatable for the Lua table the value is copied into, itself copied into a table unless it + * is wrapped to say otherwise. Its functions are called with the Lua table read back into JS. + */ + metatable?: object | undefined +} + +/** + * A function called the way Lua calls a C function: it reads its `argCount` arguments off the + * thread's stack, pushes its results, and returns how many it pushed. + */ +export type LuaRawFunction = (thread: Thread, argCount: number) => number + +const unwrap = (value: T | LuaMarshalled): T => (value instanceof LuaMarshalled ? value.target : value) + +/** + * Crosses into Lua as plain Lua data: an object or array becomes a table and so does everything + * inside it, whatever the state's `objects` option says. What has a representation of its own + * (a function, a promise, an `Error`, a defined type or class) keeps it. + * + * ```js + * state.set('config', copy({ retries: 3, hosts: ['a', 'b'] })) + * ``` + */ +export function copy(value: T, options?: LuaCopyOptions): LuaMarshalled { + return new LuaMarshalled(unwrap(value), 'copy', options?.metatable) +} + +/** + * Crosses into Lua by reference, as a userdata that forwards indexing, assignment, calls, `#` and + * `pairs` to the JS value. The default for an object when the state's `objects` is `'proxy'`, and + * the way to make a function indexable: its properties are reachable, and `fn.new(...)` constructs. + * + * ```js + * state.set('Date', proxy(Date)) // Date.now(), Date.new(0):toISOString() + * ``` + */ +export function proxy(value: T): LuaMarshalled { + return new LuaMarshalled(unwrap(value), 'proxy') +} + +/** + * Crosses into Lua by reference with nothing reachable: a userdata Lua can hold, compare and hand + * back, which reads back as the same JS value. + */ +export function opaque(value: T): LuaMarshalled { + return new LuaMarshalled(unwrap(value), 'opaque') +} + +/** + * Crosses into Lua as a function that works on the stack itself, for what the marshalling of + * arguments and results cannot express or cannot afford. + * + * ```js + * state.set('swap', raw((thread) => { + * thread.module.lua_rotate(thread.address, 1, 1) + * return 2 + * })) + * ``` + */ +export function raw(fn: LuaRawFunction): LuaMarshalled { + if (typeof fn !== 'function') { + throw new TypeError('raw expects a function') + } + return new LuaMarshalled(fn, 'raw') +} + +/** + * A function a proxy handed out for one of its target's members. It is called on that target + * however Lua called it, so `obj.method(x)` and `obj:method(x)` both reach `obj.method(x)`: the + * receiver a `:` call passes ahead of the arguments is dropped. + */ +export class BoundMethod extends LuaMarshalled<(...args: any[]) => unknown> { + public constructor( + target: (...args: any[]) => unknown, + public readonly self: object, + ) { + super(target, 'method') + } +} diff --git a/src/marshaller.ts b/src/marshaller.ts new file mode 100644 index 0000000..6e8c2ed --- /dev/null +++ b/src/marshaller.ts @@ -0,0 +1,219 @@ +import { LuaMarshalled } from './marshal' +import type Thread from './thread' +import type LuaTypeExtension from './type-extension' +import type ClassTypeExtension from './type-extensions/class' +import type DefinedTypeExtension from './type-extensions/defined' +import type { ErrorTypeExtension } from './type-extensions/error' +import type { FunctionTypeExtension } from './type-extensions/function' +import type { NullTypeExtension } from './type-extensions/null' +import type { PromiseTypeExtension } from './type-extensions/promise' +import type { ProxyTypeExtension } from './type-extensions/proxy' +import type { TableTypeExtension } from './type-extensions/table' +import type { UserdataTypeExtension } from './type-extensions/userdata' +import { type LuaAddress, type LuaGetCache, type LuaPushCache, LuaType } from './types' +import { isPromise } from './utils' + +/** + * Decides how each value crosses between JS and Lua for one state, and is shared by every thread + * on it. The order is the whole rule, top to bottom: + * + * 1. A value wrapped by `copy`, `proxy`, `opaque` or `raw` crosses the way the wrapper says. + * 2. A type defined with `defineType` takes what it matches, the most recently defined first. + * 3. A class defined with `defineClass` takes its instances, the most derived class first, and + * itself. + * 4. Everything else goes by what it is: `null`, a function, a promise, an `Error`, and lastly + * any other object, which is proxied or copied as the state's `objects` option says. + */ +export default class Marshaller { + /** What an object nothing above claimed is pushed as. */ + public objects: 'proxy' | 'copy' = 'proxy' + + public functions!: FunctionTypeExtension + public tables!: TableTypeExtension + public proxies!: ProxyTypeExtension + public promises!: PromiseTypeExtension + public errors!: ErrorTypeExtension + public opaques!: UserdataTypeExtension + /** Only when the state injects `null`; without it a JS null is a Lua nil. */ + public nulls: NullTypeExtension | undefined + + /** + * The extension behind each metatable this state created, keyed by the metatable's address. + * Those metatables are registry anchored for the state's whole life, so an address in here + * can never be reused by anything else while the map exists -- and going by the address rather + * than by `__name` means nothing a script writes into a metatable of its own can pass a value + * off as a reference box. + */ + public readonly owners = new Map>() + /** Every extension's name, taken from the moment it is created. */ + public readonly names = new Set() + private readonly extensions: LuaTypeExtension[] = [] + + private readonly types: DefinedTypeExtension[] = [] + /** The defined types that also read Lua tables whose own metatable carries their `__name`. */ + private readonly typesByName = new Map() + private readonly classesByPrototype = new Map() + private readonly classesByConstructor = new Map() + + public addType(type: DefinedTypeExtension): void { + // Most recent first, so a later definition can take a narrower slice of an earlier one. + this.types.unshift(type) + if (type.readsByName) { + this.typesByName.set(type.name, type) + } + } + + public hasClass(ctor: unknown): boolean { + return this.classesByConstructor.has(ctor) + } + + public addClass(type: ClassTypeExtension): void { + this.classesByPrototype.set(type.ctor.prototype, type) + this.classesByConstructor.set(type.ctor, type) + } + + /** Pushes anything that is not a primitive: an object, a function, or null. */ + public push(thread: Thread, value: unknown, cache?: LuaPushCache): void { + if (value === null) { + if (this.nulls) { + this.nulls.push(thread) + } else { + thread.module.lua_pushnil(thread.address) + } + return + } + + if (value instanceof LuaMarshalled) { + this.pushMarshalled(thread, value, cache) + return + } + + const types = this.types + for (let i = 0; i < types.length; i++) { + if (types[i]!.push(thread, value, cache)) { + return + } + } + + if (typeof value === 'function') { + const type = this.classesByConstructor.size === 0 ? undefined : this.classesByConstructor.get(value) + if (type) { + type.classObject.push(thread) + } else { + this.functions.push(thread, value as (...args: any[]) => unknown) + } + return + } + + if (typeof value !== 'object') { + throw new Error(`The type '${typeof value}' is not supported by Lua`) + } + + if (this.classesByPrototype.size !== 0) { + for (let proto = Object.getPrototypeOf(value); proto !== null; proto = Object.getPrototypeOf(proto)) { + const type = this.classesByPrototype.get(proto) + if (type) { + type.push(thread, value) + return + } + } + } + + if (isPromise(value)) { + this.promises.push(thread, value) + } else if (value instanceof Error) { + this.errors.push(thread, value) + } else if (cache !== undefined || this.objects === 'copy') { + // A cache means this is a value inside a table being copied, and a copy is a deep one. + this.tables.push(thread, value, cache) + } else { + this.proxies.push(thread, value) + } + } + + /** Reads a table, a userdata or a function. */ + public get(thread: Thread, index: number, type: LuaType, cache?: LuaGetCache): unknown { + if (type === LuaType.Function) { + return this.functions.getValue(thread, index) + } + + if (type === LuaType.Table || type === LuaType.Userdata) { + const { module, address: L } = thread + if (module.lua_getmetatable(L, index)) { + let owner: LuaTypeExtension | undefined = this.owners.get(module.lua_topointer(L, -1)) + // Only a table, whose content is all the type gets to see: a reference box is + // recognised by its metatable's address and by nothing a script can write. + if (owner === undefined && type === LuaType.Table && this.typesByName.size !== 0) { + if (module.lua_getfield(L, -1, '__name') === LuaType.String) { + owner = this.typesByName.get(module.lua_tolstring(L, -1, null)) + } + module.lua_pop(L, 1) + } + module.lua_pop(L, 1) + if (owner !== undefined) { + return owner.getValue(thread, index, cache) + } + } + if (type === LuaType.Table) { + return this.tables.getValue(thread, index, cache) + } + } + + // Handing back an opaque Pointer hid the failure until the value was used, and + // it could not be pushed back into Lua anyway. + const typeName = thread.module.lua_typename(thread.address, type) + const metatableName = type === LuaType.Userdata ? thread.getMetatableName(index) : undefined + const withMetatable = metatableName ? ` with metatable '${metatableName}'` : '' + throw new TypeError( + `the Lua type '${typeName}'${withMetatable} has no JS representation; define a type to handle it, ` + + `or read the address with getPointer`, + ) + } + + /** + * Releases what the extensions own outside Lua. See `LuaTypeExtension.close` for when this may + * run and what it may touch. + */ + public close(): void { + for (const extension of this.extensions) { + extension.close() + } + } + + /** Called by every extension as it is created, so that {@link close} reaches it. */ + public track(extension: LuaTypeExtension): void { + this.extensions.push(extension) + } + + private pushMarshalled(thread: Thread, wrapped: LuaMarshalled, cache: LuaPushCache | undefined): void { + const { target } = wrapped + // A wrapper says how an object or a function crosses. A primitive has only one way. + if (target === null || (typeof target !== 'object' && typeof target !== 'function')) { + thread.pushValue(target) + return + } + + switch (wrapped.as) { + case 'opaque': + this.opaques.push(thread, target) + break + case 'proxy': + this.proxies.push(thread, target) + break + case 'raw': + case 'method': + this.functions.push(thread, wrapped as LuaMarshalled<(...args: any[]) => unknown>) + break + case 'copy': + if (typeof target === 'function') { + this.functions.push(thread, target as (...args: any[]) => unknown) + } else { + this.tables.push(thread, target, cache) + } + if (wrapped.metatable) { + thread.setMetatable(-1, wrapped.metatable) + } + break + } + } +} diff --git a/src/module.ts b/src/module.ts index cdf9955..5855c2c 100755 --- a/src/module.ts +++ b/src/module.ts @@ -602,10 +602,8 @@ export default class LuaModule { * ever pushes this address, and no Lua object can live at it, so finding it on the stack is * proof that the error came from a limit rather than from the script -- see `Thread.assertOk`. * - * Pushing the error itself is what this replaced: it goes through pushValue, and a state with no - * error extension registered marshals it into a plain table, losing the identity the recovery - * needs. `decorate(error, { as: 'userdata' })` would survive that, but not this: light userdata - * allocates nothing, and the hook fires at an arbitrary instruction, including under a + * Pushing the error itself is what this replaced. That allocates a userdata, where light + * userdata allocates nothing, and the hook fires at an arbitrary instruction, including under a * `memory.max` tight enough that a real userdata would fail and report a memory error in place * of the limit that was actually hit. */ @@ -1143,7 +1141,7 @@ export default class LuaModule { */ public referenceGcFunction(): number { this.referenceGcPointer ??= this.addFunction((L: LuaAddress): number => { - // Only a userdata pushed by LuaTypeExtension holds a reference index, and those are + // Only a userdata pushed by a type extension holds a reference index, and those are // exactly one pointer wide. The check stands in for the metatable name one a handler // built per extension can make: it rules out the io library's stream handles, the one // other userdata Lua code can reach and put one of these metatables on through diff --git a/src/raw-result.ts b/src/raw-result.ts deleted file mode 100644 index 9efbbf8..0000000 --- a/src/raw-result.ts +++ /dev/null @@ -1,3 +0,0 @@ -export default class RawResult { - public constructor(public readonly count: number) {} -} diff --git a/src/state.ts b/src/state.ts index 14395a1..d2c69f4 100755 --- a/src/state.ts +++ b/src/state.ts @@ -1,9 +1,11 @@ import LuaGarbageCollector from './gc' +import Marshaller from './marshaller' import type LuaModule from './module' import Thread from './thread' -import type LuaTypeExtension from './type-extension' +import ClassTypeExtension from './type-extensions/class' +import DefinedTypeExtension from './type-extensions/defined' import createErrorType from './type-extensions/error' -import createFunctionType, { type FunctionTypeExtension } from './type-extensions/function' +import createFunctionType from './type-extensions/function' import createNullType from './type-extensions/null' import createPromiseType from './type-extensions/promise' import createProxyType from './type-extensions/proxy' @@ -13,11 +15,15 @@ import { type CreateStateOptions, LUA_REGISTRYINDEX, type LuaAddress, + type LuaClass, + type LuaClassOptions, type LuaDoOptions, type LuaInjectName, + type LuaLimits, type LuaMemoryOptions, type LuaRunOptions, LuaType, + type LuaTypeDefinition, resolveLibraryMask, } from './types' @@ -32,23 +38,6 @@ export interface LuaMemory { max: number | undefined } -/** - * A more specific handler has to be consulted before a more general one. The values themselves - * cannot be renumbered: they are the scale {@link LuaState.registerTypeExtension} exposes, so - * anything a user registered against them would move too. - */ -const BUILT_IN_PRIORITY = { - table: 0, - function: 0, - promise: 1, - proxy: 3, - /** Beats proxy, which would otherwise claim every Error before this one is consulted. */ - error: 3.5, - /** Lets a custom userdata be exposed without its methods coming along. */ - userdata: 4, - null: 5, -} as const - interface CreatedState { address: LuaAddress memory?: LuaMemory @@ -120,19 +109,23 @@ export default class LuaState extends Thread { public readonly gc: LuaGarbageCollector private readonly allocatorFunctionPointer: number | undefined - private readonly defaultMaxInstructions: number | undefined - private readonly functions: FunctionTypeExtension public constructor(cmodule: LuaModule, options: CreateStateOptions = {}) { - const { libs = true, objects = 'proxy', errors = objects === 'copy', inject = false, memory, limits, gc, onWarn } = options + const { libs = true, objects = 'proxy', inject = false, memory, limits, gc, onWarn } = options const injects = (name: LuaInjectName): boolean => inject === true || (inject !== false && inject.includes(name)) + if (objects !== 'proxy' && objects !== 'copy') { + throw new TypeError(`unknown objects option '${String(objects)}', expected proxy or copy`) + } const created = createAddress(cmodule, memory) - super(cmodule, [], created.address) + const marshaller = new Marshaller() + super(cmodule, marshaller, created.address) this.memory = created.memory this.allocatorFunctionPointer = created.allocatorFunctionPointer this.onWarn = onWarn + // A copy, so that the caller's object and `state.limits` can change independently. + this.defaultLimits = { ...limits } if (this.isClosed()) { throw new Error('Lua state could not be created (probably due to lack of memory)') @@ -140,50 +133,53 @@ export default class LuaState extends Thread { this.gc = new LuaGarbageCollector(this, gc) - // Generic handlers - These may be required to be registered for additional types. - this.registerTypeExtension(BUILT_IN_PRIORITY.table, createTableType(this)) - this.functions = createFunctionType(this, { ...limits, onAsyncError: options.onAsyncError }) - this.registerTypeExtension(BUILT_IN_PRIORITY.function, this.functions) - + // Each takes what it needs from the ones before it: a metatable's functions are pushed + // through the function extension, and its tables through the table one. + marshaller.objects = objects + marshaller.tables = createTableType(this) + marshaller.functions = createFunctionType(this, { onAsyncError: options.onAsyncError }) + marshaller.opaques = createUserdataType(this) + marshaller.proxies = createProxyType(this) // Contains the :await functionality. - this.registerTypeExtension(BUILT_IN_PRIORITY.promise, createPromiseType(this, injects('Promise'))) - + marshaller.promises = createPromiseType(this, injects('Promise')) + marshaller.errors = createErrorType(this, injects('Error')) if (injects('null')) { - this.registerTypeExtension(BUILT_IN_PRIORITY.null, createNullType(this)) + marshaller.nulls = createNullType(this) } - if (errors) { - this.registerTypeExtension(BUILT_IN_PRIORITY.error, createErrorType(this, injects('Error'))) - } - - if (objects === 'proxy') { - // This extension only really overrides tables and arrays. - // When a function is looked up in one of it's tables it's bound and then - // handled by the function type extension. - this.registerTypeExtension(BUILT_IN_PRIORITY.proxy, createProxyType(this)) - } - - this.registerTypeExtension(BUILT_IN_PRIORITY.userdata, createUserdataType(this)) - const libraryMask = resolveLibraryMask(libs) if (libraryMask !== 0) { this.module.luaL_openselectedlibs(this.address, libraryMask, 0) } - this.defaultMaxInstructions = limits?.maxInstructions - if (injects('async')) { - this.functions.injectAsync() + marshaller.functions.injectAsync() } } + /** + * The limits every run on this state starts under: a `doString` or `doFile`, a call of a Lua + * function from JS, and the runs `state.async`, Lua's `async` and a promise reaction start. + * What a run is given itself (`doString(code, { timeout })`) goes over these field by field. + * + * Read when a run starts, so assigning it, or a field of it, changes the runs that start + * afterwards and leaves the ones under way alone. + */ + public get limits(): LuaLimits { + return this.defaultLimits + } + + public set limits(limits: LuaLimits | undefined) { + this.defaultLimits = { ...limits } + } + /** * Executes Lua code from a string asynchronously. * @returns A Promise that resolves to the result returned by the Lua script execution. Nothing * checks it against `T`, which only saves the caller a cast. */ public doString(script: string, options?: LuaDoOptions): Promise { - return this.callByteCode((thread) => thread.loadString(script, options), this.runOptions(options)) + return this.callByteCode((thread) => thread.loadString(script, options), options) } /** @@ -191,7 +187,7 @@ export default class LuaState extends Thread { * @returns A Promise that resolves to the result returned by the Lua script execution. */ public doFile(filename: string, options?: LuaDoOptions): Promise { - return this.callByteCode((thread) => thread.loadFile(filename, options), this.runOptions(options)) + return this.callByteCode((thread) => thread.loadFile(filename, options), options) } /** @@ -199,7 +195,7 @@ export default class LuaState extends Thread { * `:await()` and a top level `coroutine.yield` are errors here. */ public doStringSync(script: string, options?: LuaDoOptions): T { - return this.callByteCodeSync((thread) => thread.loadString(script, options), this.runOptions(options)) + return this.callByteCodeSync((thread) => thread.loadString(script, options), options) } /** @@ -207,7 +203,7 @@ export default class LuaState extends Thread { * `:await()` and a top level `coroutine.yield` are errors here. */ public doFileSync(filename: string, options?: LuaDoOptions): T { - return this.callByteCodeSync((thread) => thread.loadFile(filename, options), this.runOptions(options)) + return this.callByteCodeSync((thread) => thread.loadFile(filename, options), options) } /** @@ -221,33 +217,72 @@ export default class LuaState extends Thread { * const body = await state.async(fetchPage, { timeout: 1000 })(url) * ``` * - * Each call is a run like a `doString`, under the same limits, with `limits.functionTimeout` - * on top unless `options.timeout` replaces it. + * Each call is a run like a `doString`, under the state's {@link limits} with `options` over + * them. */ public async(fn: (...args: any[]) => any, options?: LuaRunOptions): (...args: any[]) => Promise { - return this.functions.async(fn, options) as (...args: any[]) => Promise + return this.marshaller.functions.async(fn, options) as (...args: any[]) => Promise } /** Whether `value` is a Lua function obtained from this state, the kind {@link async} takes. */ public isLuaFunction(value: unknown): value is (...args: any[]) => any { - return this.functions.isLuaFunction(value) + return this.marshaller.functions.isLuaFunction(value) + } + + /** + * Defines how a kind of JS value crosses into Lua, ahead of how it otherwise would. + * + * Without `toLua` the value crosses by reference: a userdata with a metatable named after the + * type, carrying the metamethods given, which reads back as the same JS value. + * + * ```js + * state.defineType({ + * name: 'Point', + * match: (value) => value instanceof Point, + * metatable: { __tostring: (point) => `Point(${point.x}, ${point.y})` }, + * }) + * ``` + * + * With `toLua` it is converted instead, and `fromLua` converts back what Lua returns: + * + * ```js + * state.defineType({ + * name: 'Map', + * match: (value) => value instanceof Map, + * toLua: (map) => copy(Object.fromEntries(map)), + * fromLua: (table) => new Map(Object.entries(table)), + * }) + * ``` + * + * Types are consulted before classes and before the built in handling, the most recently + * defined first. See {@link LuaTypeDefinition}. + */ + public defineType(definition: LuaTypeDefinition): void { + this.assertNotClosed() + this.marshaller.addType(new DefinedTypeExtension(this, definition) as DefinedTypeExtension) } /** - * Registers a type extension for Lua objects. - * Higher priority is more important and will be evaluated first. - * Allows library users to specify custom types + * Gives a class a metatable of its own in Lua. Its instances then cross by reference as + * userdata named after the class, whose methods are called the way Lua calls methods, with + * `:`, and the class itself crosses as a value that constructs when called and exposes its + * static members. + * + * ```js + * state.defineClass(Vector, { members: ['x', 'y', 'length', 'add'] }) + * state.set('Vector', Vector) + * await state.doString('local v = Vector(3, 4) return v:add(v):length()') + * ``` + * + * An instance of a subclass uses the nearest class that was defined. See + * {@link LuaClassOptions}. */ - public registerTypeExtension(priority: number, extension: LuaTypeExtension): void { - this.typeExtensions.push({ extension, priority }) - this.typeExtensions.sort((a, b) => b.priority - a.priority) - - // The extension's metatable is registry anchored for the life of the state, so from here - // on its address alone identifies its name -- getMetatableName's fast path. - if (this.module.luaL_getmetatable(this.address, extension.name) !== LuaType.Nil) { - this.metatableNames.set(this.getPointer(-1), extension.name) + public defineClass(ctor: LuaClass, options?: LuaClassOptions): void { + this.assertNotClosed() + if (this.marshaller.hasClass(ctor)) { + throw new Error(`the class '${ctor.name}' is already defined in this state`) } - this.pop(1) + this.marshaller.addClass(new ClassTypeExtension(this, ctor, options) as unknown as ClassTypeExtension) } /** Retrieves the value of a global variable. */ @@ -307,17 +342,7 @@ export default class LuaState extends Thread { this.module.removeFunction(this.allocatorFunctionPointer) } - for (const wrapper of this.typeExtensions) { - wrapper.extension.close() - } - } - - /** Folds the state wide budget in, so run() does the save and restore in one place. */ - private runOptions(options?: LuaDoOptions): LuaRunOptions | undefined { - if (this.defaultMaxInstructions === undefined) { - return options - } - return { maxInstructions: this.defaultMaxInstructions, ...options } + this.marshaller.close() } private callByteCodeSync(loader: (thread: Thread) => void, options?: LuaRunOptions): any { @@ -346,10 +371,6 @@ export default class LuaState extends Thread { // Anchored so the run doesn't pile threads up on the global stack. const { thread, reference } = this.newAnchoredThread() try { - // Seeded from the state so a state wide setLimits reaches the async path too, which - // runs on a child thread rather than on the state itself. setLimits takes a snapshot, - // so going through getLimits first would copy the same configuration twice. - thread.setLimits(this.limits) loader(thread) return (await thread.run(0, options))[0] } finally { diff --git a/src/thread.ts b/src/thread.ts index 14e3c67..0e20a04 100755 --- a/src/thread.ts +++ b/src/thread.ts @@ -1,7 +1,7 @@ -import { Decoration, type DecorationOptions, type LuaMetatable } from './decoration' +import { copy, LuaMarshalled } from './marshal' +import type Marshaller from './marshaller' import type LuaModule from './module' import MultiReturn from './multireturn' -import type LuaTypeExtension from './type-extension' import { defaultWarnHandler, LUA_MULTRET, @@ -12,24 +12,28 @@ import { type LuaGetCache, LuaInstructionLimitError, LuaInterruptError, + type LuaLimits, type LuaLoadOptions, type LuaPushCache, type LuaResumeResult, LuaReturn, type LuaRunOptions, - type LuaThreadLimits, LuaType, type LuaWarnHandler, PointerSize, } from './types' import { isEmscriptenUnwind } from './utils' import { limitError, settleOrInterrupt, yieldToEventLoop } from './async' -import RawResult from './raw-result' -export interface OrderedExtension { - // Bigger is more important - priority: number - extension: LuaTypeExtension +/** + * What the debug hook enforces while a run is on a thread: a run's {@link LuaLimits} once it has + * started, with the timeout turned into the moment it runs out. + */ +export interface ActiveLimits { + /** Absolute timestamp, as returned by `Date.now()`. */ + deadline?: number | undefined + maxInstructions?: number | undefined + signal?: AbortSignal | undefined } // When the debug count hook is set, call it every X instructions. @@ -38,12 +42,12 @@ const INSTRUCTION_HOOK_COUNT = 1000 const LUA_INTEGER_BITS = 64 const NO_RESTORE = (): void => undefined -const NO_OPTIONS: Readonly = Object.freeze({}) /** - * The limits of a thread nothing has been set on, shared because a JS callback made from a - * coroutine gets a thread wrapper of its own each time. Frozen, so a write to it fails loudly. + * The limits of a thread no run is on, shared because a JS callback made from a coroutine gets a + * thread wrapper of its own each time. Frozen, so a write to it fails loudly. */ -const NO_LIMITS: Readonly = Object.freeze({}) +const NO_LIMITS: Readonly = Object.freeze({}) +const NO_DEFAULT_LIMITS: Readonly = Object.freeze({}) export default class Thread { public readonly address: LuaAddress @@ -51,7 +55,8 @@ export default class Thread { public readonly module: LuaModule /** Set on the root state; threads created from it delegate here, as does {@link warn}. */ public onWarn: LuaWarnHandler | undefined - protected readonly typeExtensions: OrderedExtension[] + /** How values cross between JS and Lua, shared by every thread on the same state. */ + public readonly marshaller: Marshaller protected readonly parent: Thread | undefined /** * The state this thread belongs to, or itself when it is the state. Resolved once here rather @@ -60,19 +65,18 @@ export default class Thread { */ protected readonly rootThread: Thread /** - * The address of each registered extension's metatable, mapped to the extension's name. - * Populated by `LuaState.registerTypeExtension` and shared with every thread on the same - * state: those metatables are registry anchored for the state's whole life, so an address in - * here can never be reused by anything else while the map exists. + * The limits a run starts under unless its own options say otherwise, as `state.limits`. Held + * by the state and read from there, so it means nothing on any other thread. */ - protected readonly metatableNames: Map + protected defaultLimits: LuaLimits = NO_DEFAULT_LIMITS private closed = false private running = false private rejectRun: (() => void) | undefined private removeCloseListener: (() => void) | undefined private hookFunctionPointer: number | undefined private hookCount = INSTRUCTION_HOOK_COUNT - protected limits: LuaThreadLimits = NO_LIMITS + /** The limits of the run this thread is on. Installed when it starts, removed when it ends. */ + private active: ActiveLimits = NO_LIMITS private instructionsUsed = 0 /** * The error the debug hook unwound the current run with. See {@link LuaModule.interruptToken} @@ -80,20 +84,27 @@ export default class Thread { * coroutine, so it writes to the active driver, which also owns its limits and lifecycle. */ private pendingInterrupt: LuaInterruptError | undefined + /** + * Whether Lua has stopped calling the debug hook on this thread. It disables the hook while + * one runs and enables it again once that returns, which a hook that raises never does: a + * `pcall` on the way out restores the flag, and without one the thread dies with its hook off. + * Resetting such a thread brings it back to life without a hook that works, so it must not be + * run again under a limit. + */ + public hookLost = false private closeListeners: (() => void)[] | undefined /** The limits of the run this thread is driving, as an `:await()` reads them when it parks. */ - public get runLimits(): Readonly { - return this.limits + public get runLimits(): Readonly { + return this.active } - public constructor(cmodule: LuaModule, typeExtensions: OrderedExtension[], address: number, parent?: Thread) { + public constructor(cmodule: LuaModule, marshaller: Marshaller, address: number, parent?: Thread) { this.module = cmodule - this.typeExtensions = typeExtensions + this.marshaller = marshaller this.address = address this.parent = parent this.rootThread = parent ?? this - this.metatableNames = parent ? parent.metatableNames : new Map() } public newThread(): Thread { @@ -102,7 +113,7 @@ export default class Thread { if (!address) { throw new Error('lua_newthread returned a null pointer') } - return new Thread(this.module, this.typeExtensions, address, this.rootThread) + return new Thread(this.module, this.marshaller, address, this.rootThread) } /** @@ -119,7 +130,14 @@ export default class Thread { public resetThread(): void { this.assertNotClosed() - this.assertOk(this.module.lua_resetthread(this.address)) + const status = this.module.lua_resetthread(this.address) + if (this.hookLost) { + this.setTop(0) + throw new Error( + 'a thread that a limit interrupted cannot be reset, because no limit could be enforced on it again: use a new one', + ) + } + this.assertOk(status) } /** @param options.mode defaults to `'t'`. See {@link LuaLoadOptions.mode}. */ @@ -171,6 +189,10 @@ export default class Thread { module.activeRun = previousRun module.stackCanSuspend = previousCanSuspend } + if (result <= LuaReturn.Yield) { + // Alive, so whatever interrupt the hook raised was caught by a pcall on the way. + this.hookLost = false + } return { result, resultCount: module.readPointer(dataPointer) } } @@ -192,11 +214,15 @@ export default class Thread { this.module.lua_setfield(this.address, index, name) } + /** + * Runs the function and arguments on this thread's stack to completion, as a run that an + * `:await()` can suspend. Under the state's limits, with `options` over them. + */ public async run(argCount = 0, options?: LuaRunOptions): Promise { this.startRun() let restore = NO_RESTORE try { - restore = this.applyRunOptions(options) + restore = this.enterRun(options, false) return await this.watchRun(this.drive(argCount, options)) } finally { this.finishRun() @@ -250,7 +276,7 @@ export default class Thread { } const values = this.getStackValues(this.getTop() - resumeResult.resultCount) this.dropResults(resumeResult) - const outcome = await settleOrInterrupt(options.onYield(values), this.limits.signal, this.limits.deadline) + const outcome = await settleOrInterrupt(options.onYield(values), this.active.signal, this.active.deadline) this.assertNotClosed() this.assertLimits() if (outcome.status !== 'fulfilled') { @@ -332,6 +358,9 @@ export default class Thread { try { const result = await pending this.assertNotClosed() + if (result <= LuaReturn.Yield) { + this.hookLost = false + } return { result, resultCount: module.readPointer(nresPointer) } } finally { if (module.activeRun === this) { @@ -347,17 +376,13 @@ export default class Thread { /** * Pushes a JS value onto the stack as Lua results and returns how many: nothing for `undefined`, - * `count` for a {@link RawResult}, one per element for a {@link MultiReturn}, else the single - * value. + * one per element for a {@link MultiReturn}, else the single value. * @param nilOnUndefined Preserve undefined as one Lua nil, as `:await()` requires. */ public pushReturnValues(value: unknown, nilOnUndefined = false): number { if (value === undefined && !nilOnUndefined) { return 0 } - if (value instanceof RawResult) { - return value.count - } if (value instanceof MultiReturn) { for (const item of value) { this.pushValue(item) @@ -368,9 +393,13 @@ export default class Thread { return 1 } + /** + * The synchronous counterpart of {@link run}, which nothing can suspend. Started from inside + * another run it stays within that one's limits too. + */ public runSync(argCount = 0, options?: LuaRunOptions): MultiReturn { this.assertNotClosed() - const restore = this.applyRunOptions(options) + const restore = this.enterRun(options, true) try { const base = this.getTop() - argCount - 1 // The 1 is for the function to run this.pcall(argCount) @@ -396,8 +425,13 @@ export default class Thread { } const base = this.getTop() - args.length - 1 // The 1 is for the function to run - this.pcall(args.length) - return this.getStackValues(base) + const restore = this.enterRun(undefined, true) + try { + this.pcall(args.length) + return this.getStackValues(base) + } finally { + restore() + } } /** A synchronous call, which nothing can suspend: an `:await()` reached through it is an error. */ @@ -415,6 +449,8 @@ export default class Thread { module.activeRun = previousRun module.stackCanSuspend = previousCanSuspend } + // lua_pcall puts the flag back itself, which lua_resume does not. + this.hookLost = false this.assertOk(result) } @@ -437,100 +473,83 @@ export default class Thread { if (L === this.address) { return this } - return L === this.parent?.address ? this.parent : new Thread(this.module, this.typeExtensions, L, this.rootThread) + return L === this.parent?.address ? this.parent : new Thread(this.module, this.marshaller, L, this.rootThread) } - public pushValue(rawValue: unknown, cache?: LuaPushCache): void { - // Only the type extensions take a decoration, so pushing a plain primitive never has to - // allocate one. The default branch below synthesises one for the values that do need it. - const decoration = rawValue instanceof Decoration ? rawValue : undefined - const target = decoration ? decoration.target : rawValue - - if (target instanceof Thread) { - this.module.lua_pushthread(target.address) - if (target.address !== this.address) { - this.module.lua_xmove(target.address, this.address, 1) - } - return - } - - // Handle primitive types - switch (typeof target) { + /** + * Pushes a JS value onto the stack as one Lua value. A primitive has one way to cross; anything + * else crosses the way the state's {@link Marshaller} decides, which is where the order of + * `copy`, `proxy`, `opaque`, defined types and classes is spelled out. + */ + public pushValue(value: unknown, cache?: LuaPushCache): void { + switch (typeof value) { case 'undefined': this.module.lua_pushnil(this.address) break case 'number': // Only integers JS can represent exactly become Lua integers. Values like 1e300 // are integral but far outside int64, and would wrap silently if pushed as one. - if (Number.isSafeInteger(target)) { - this.module.lua_pushinteger(this.address, target) + if (Number.isSafeInteger(value)) { + this.module.lua_pushinteger(this.address, value) } else { - this.module.lua_pushnumber(this.address, target) + this.module.lua_pushnumber(this.address, value) } break case 'bigint': - if (BigInt.asIntN(LUA_INTEGER_BITS, target) !== target) { - throw new RangeError(`bigint ${target} does not fit in a 64 bit Lua integer`) + if (BigInt.asIntN(LUA_INTEGER_BITS, value) !== value) { + throw new RangeError(`bigint ${value} does not fit in a 64 bit Lua integer`) } - this.module.lua_pushinteger(this.address, target) + this.module.lua_pushinteger(this.address, value) break case 'string': - this.module.lua_pushstring(this.address, target) + this.module.lua_pushstring(this.address, value) break case 'boolean': - this.module.lua_pushboolean(this.address, target ? 1 : 0) + this.module.lua_pushboolean(this.address, value ? 1 : 0) break - default: { - // A type extension can be supplied by the caller, so unlike the pushes above it is - // not guaranteed to leave exactly one value behind. That is worth the two - // lua_gettop calls here, and not worth them on every primitive push. - const startTop = this.getTop() - if (this.pushWithExtension(decoration ?? new Decoration(target, NO_OPTIONS), cache)) { - const endTop = this.getTop() - if (endTop !== startTop + 1) { - throw new Error(`pushValue expected stack size ${startTop + 1}, got ${endTop}`) + default: + if (value instanceof Thread) { + this.module.lua_pushthread(value.address) + if (value.address !== this.address) { + this.module.lua_xmove(value.address, this.address, 1) } - } else if (target === null) { - this.module.lua_pushnil(this.address) } else { - throw new Error(`The type '${typeof target}' is not supported by Lua`) + this.marshaller.push(this, value, cache) } break - } - } - - // A synthesised decoration always has empty options, so this only ever acts on one the - // caller supplied. - const metatable = decoration?.options.metatable - if (metatable) { - this.setMetatable(-1, metatable) } } - public setMetatable(index: number, metatable: LuaMetatable): void { + /** + * Gives the Lua table at `index` a metatable, copied into a table of its own unless it is + * wrapped to cross some other way. + */ + public setMetatable(index: number, metatable: object): void { index = this.absIndex(index) + // Lua has one metatable for all functions, all strings and so on: setting it through one + // value would change every other, so only what owns its metatable can be given one. + if (this.module.lua_type(this.address, index) !== LuaType.Table) { + throw new TypeError('only a value copied into a Lua table can be given a metatable') + } if (this.module.lua_getmetatable(this.address, index)) { this.pop(1) const name = this.getMetatableName(index) throw new Error(`data already has associated metatable: ${name || 'unknown name'}`) } - this.pushValue(metatable) + this.pushValue(metatable instanceof LuaMarshalled ? metatable : copy(metatable)) this.module.lua_setmetatable(this.address, index) } + /** The name of the metatable of the value at `index`: its `__name`, or undefined without one. */ public getMetatableName(index: number): string | undefined { - // Resolving __name on every table and userdata read is most of what getValue spends on its - // dispatch, and it is nearly always one of the extension metatables that registration - // already recorded in metatableNames -- so the common case is these three raw calls and a - // map hit, with no string crossing the boundary in either direction. if (!this.module.lua_getmetatable(this.address, index)) { return undefined } - const pointer = this.module.lua_topointer(this.address, -1) - let name = this.metatableNames.get(pointer) + // One this state created is known by its address, with no string crossing the boundary. + let name = this.marshaller.owners.get(this.module.lua_topointer(this.address, -1))?.name if (name !== undefined) { this.pop(1) return name @@ -567,31 +586,8 @@ export default class Thread { return Boolean(this.module.lua_toboolean(this.address, index)) case LuaType.Thread: return this.stateToThread(this.module.lua_tothread(this.address, index)) - default: { - index = this.absIndex(index) - - let metatableName: string | undefined - if (type === LuaType.Table || type === LuaType.Userdata) { - metatableName = this.getMetatableName(index) - } - - const extensions = this.typeExtensions - for (let i = 0; i < extensions.length; i++) { - const extension = extensions[i].extension - if (extension.isType(this, index, type, metatableName)) { - return extension.getValue(this, index, cache) - } - } - - // Handing back an opaque Pointer hid the failure until the value was used, and - // it could not be pushed back into Lua anyway. - const typeName = this.module.lua_typename(this.address, type) - const withMetatable = metatableName ? ` with metatable '${metatableName}'` : '' - throw new TypeError( - `the Lua type '${typeName}'${withMetatable} has no JS representation; register a type ` + - `extension to handle it, or read the address with getPointer`, - ) - } + default: + return this.marshaller.get(this, this.absIndex(index), type, cache) } } @@ -634,40 +630,6 @@ export default class Thread { this.close() } - /** - * Installs the deadline, instruction budget and abort signal enforced while this thread runs. - * They share a single debug hook, because Lua only allows one hook per thread. - */ - public setLimits(limits: LuaThreadLimits | undefined): void { - this.assertNotClosed() - this.limits = { ...limits } - this.instructionsUsed = 0 - this.applyHook() - } - - public getLimits(): LuaThreadLimits { - return { ...this.limits } - } - - /** - * Shorthand for the deadline in {@link setLimits}. The argument is an absolute timestamp as - * returned by `Date.now()`, not a duration — pass `Date.now() + ms`, or undefined to disable. - * `LuaRunOptions.timeout` is the per-run equivalent that does take a duration. - */ - public setDeadline(deadline: number | undefined): void { - this.assertNotClosed() - // In place rather than by copy, since a function timeout sets one on every call. - if (this.limits === NO_LIMITS) { - this.limits = {} - } - this.limits.deadline = deadline && deadline > 0 ? deadline : undefined - this.applyHook() - } - - public getDeadline(): number | undefined { - return this.limits.deadline - } - /** * Diagnostics the library would otherwise have written straight to the console. Resolved on * every call rather than snapshotted, so clearing a state's handler falls back to the @@ -825,40 +787,86 @@ export default class Thread { return interrupt } - private applyRunOptions(options: LuaRunOptions | undefined): () => void { - const overrides = - options !== undefined && - (options.timeout !== undefined || options.maxInstructions !== undefined || options.signal !== undefined) - - if (!overrides) { + /** + * Puts this thread under the limits of a run that is about to start on it: the state's, with + * `options` over them field by field, where `Infinity` lifts one the state set. Returns what + * ends the run, which puts back whatever the thread was under before. + * + * A `nested` run is one started while another is on the JS stack -- a synchronous call back + * into Lua from a function Lua called -- and it runs inside that one: it cannot outlast its + * deadline, spends from its instruction budget, and is aborted by its signal. A run that goes + * on after its caller returns, as every asynchronous one does, is on its own. + * + * The budget is shared to the hook's granularity and no finer: instructions are counted a + * hook period at a time, so a nested run shorter than one period ends before any of it is + * counted. The deadline has no such gap. + */ + public enterRun(options: LuaLimits | undefined, nested: boolean): () => void { + const outer = nested ? this.module.activeRun : undefined + const limits = this.resolveLimits(options, outer) + const previous = this.active + // Nothing to install and nothing installed, which is every run of a state without limits. + if (limits === undefined && previous === NO_LIMITS) { return NO_RESTORE } - const previousLimits = this.limits const previousUsed = this.instructionsUsed - - this.setLimits({ - deadline: options.timeout !== undefined ? Date.now() + options.timeout : previousLimits.deadline, - maxInstructions: options.maxInstructions ?? previousLimits.maxInstructions, - signal: options.signal ?? previousLimits.signal, - }) + this.active = limits ?? NO_LIMITS + this.instructionsUsed = 0 + this.applyHook() return () => { - this.limits = previousLimits + const used = this.instructionsUsed + this.active = previous this.instructionsUsed = previousUsed + // What the nested run executed counts against the run it was made from, or calling + // back and forth would be a way around the budget. + if (outer !== undefined) { + outer.instructionsUsed += used + } this.applyHook() } } + private resolveLimits(options: LuaLimits | undefined, outer: Thread | undefined): ActiveLimits | undefined { + const defaults = this.rootThread.defaultLimits + const timeout = options?.timeout ?? defaults.timeout + let maxInstructions = options?.maxInstructions ?? defaults.maxInstructions + let signal = options?.signal ?? defaults.signal + let deadline = timeout === undefined || timeout === Infinity ? undefined : Date.now() + timeout + if (maxInstructions === Infinity) { + maxInstructions = undefined + } + + if (outer !== undefined && outer.active !== NO_LIMITS) { + const enclosing = outer.active + if (enclosing.deadline !== undefined && (deadline === undefined || enclosing.deadline < deadline)) { + deadline = enclosing.deadline + } + if (enclosing.maxInstructions !== undefined) { + const remaining = Math.max(0, enclosing.maxInstructions - outer.instructionsUsed) + if (maxInstructions === undefined || remaining < maxInstructions) { + maxInstructions = remaining + } + } + signal ??= enclosing.signal + } + + if (deadline === undefined && maxInstructions === undefined && signal === undefined) { + return undefined + } + return { deadline, maxInstructions, signal } + } + private applyHook(): void { - // The restore that `applyRunOptions` hands back runs in a finally, so it reaches here after + // The restore that `enterRun` hands back runs in a finally, so it reaches here after // a state closed midway through its own run. Returning rather than throwing, because that // finally must not replace whatever error is already on its way out. if (this.isClosed()) { return } - const { deadline, maxInstructions, signal } = this.limits + const { deadline, maxInstructions, signal } = this.active if (deadline === undefined && maxInstructions === undefined && signal === undefined) { this.module.lua_sethook(this.address, null, 0, 0) return @@ -870,11 +878,14 @@ export default class Thread { if (!this.hookFunctionPointer) { this.hookFunctionPointer = this.module.addFunction((hookL: LuaAddress): void => { - // Reads this.limits rather than closing over them, so a hook allocated for an - // earlier configuration still honours the current one. + // Reads the active limits rather than closing over them, so a hook allocated for + // an earlier run still honours the current one. const run = this.module.activeRun ?? this const error = run.checkHookLimits(hookL) if (error) { + if (hookL === run.address) { + run.hookLost = true + } run.interruptWith(error, hookL) } }, 'vii') @@ -884,7 +895,7 @@ export default class Thread { } private checkHookLimits(hookL: LuaAddress): LuaInterruptError | undefined { - const { maxInstructions } = this.limits + const { maxInstructions } = this.active if (maxInstructions !== undefined) { this.instructionsUsed += this.hookCount const remaining = maxInstructions - this.instructionsUsed @@ -900,7 +911,7 @@ export default class Thread { } private limitReached(): LuaInterruptError | undefined { - return limitError(this.limits.signal, this.limits.deadline) + return limitError(this.active.signal, this.active.deadline) } private assertLimits(): void { @@ -917,15 +928,4 @@ export default class Thread { private absIndex(index: number): number { return index > 0 ? index : this.module.lua_absindex(this.address, index) } - - /** Offers the value to each extension by descending priority. False if none claimed it. */ - private pushWithExtension(decoration: Decoration, cache: LuaPushCache | undefined): boolean { - const extensions = this.typeExtensions - for (let i = 0; i < extensions.length; i++) { - if (extensions[i].extension.pushValue(this, decoration, cache)) { - return true - } - } - return false - } } diff --git a/src/type-extension.ts b/src/type-extension.ts index 1e90e88..c2bb2e6 100644 --- a/src/type-extension.ts +++ b/src/type-extension.ts @@ -1,8 +1,23 @@ -import type { Decoration } from './decoration' +import { copy, LuaMarshalled } from './marshal' import type LuaState from './state' import type Thread from './thread' -import { type LuaAddress, LUA_REGISTRYINDEX, type LuaGetCache, type LuaPushCache, LuaType } from './types' +import { type LuaAddress, LUA_REGISTRYINDEX, type LuaGetCache, LuaType } from './types' +export interface MetatableOptions { + /** Fail when the name is taken rather than leave the existing metatable alone. */ + exclusive?: boolean + /** + * False for a metatable that goes on Lua tables rather than on reference boxes: it gets + * neither the `__gc` that releases a reference nor the protection from `getmetatable`. + */ + boxed?: boolean +} + +/** + * One way a kind of value crosses between JS and Lua, and the owner of the metatable that marks + * it on the Lua side. The state consults these in a fixed order (see `Marshaller`); what a caller + * adds goes through `LuaState.defineType` and `LuaState.defineClass`. + */ export default abstract class LuaTypeExtension { // Type name, for metatables and lookups. public readonly name: string @@ -19,8 +34,17 @@ export default abstract class LuaTypeExtension { * and states need not allocate caches for reference types they never push. */ private cacheReference = 0 + private deferredMetamethods: (() => Record) | undefined public constructor(state: LuaState, name: string) { + // Ahead of the registry, which only learns of a name once its metatable exists. + const { names } = state.marshaller + if (names.has(name)) { + throw new Error(`the name '${name}' is already taken in this state`) + } + names.add(name) + state.marshaller.track(this as LuaTypeExtension) + this.state = state this.name = name } @@ -38,10 +62,6 @@ export default abstract class LuaTypeExtension { return this.cacheReference } - public isType(_thread: Thread, _index: number, type: LuaType, name?: string): boolean { - return type === LuaType.Userdata && name === this.name - } - /** * Releases what the extension owns outside Lua: function pointers it took from `addFunction`, * and any JS side bookkeeping. Nothing, for an extension that has no more than @@ -58,53 +78,60 @@ export default abstract class LuaTypeExtension { } /** - * Creates the metatable named after this extension: protected from `getmetatable` and - * `setmetatable` in Lua, with the `__gc` that releases the reference a box pushed by - * {@link pushReference} holds, and with each of `metamethods` set on it. A metamethod is pushed - * the way any value is, so a function becomes a Lua function and a plain object a table -- by - * way of the extensions registered so far, which is why the built-ins register in dependency - * order. + * Creates the metatable named after this extension and records this extension as its owner, + * which is what a read recognises a value of this type by. A boxed one (the default) is + * protected from `getmetatable` and `setmetatable` in Lua and carries the `__gc` that releases + * the reference a box pushed by {@link pushReference} holds. Each of `metamethods` is set on it, + * pushed the way any value is, except that a plain object is copied into a table whatever the + * state's `objects` option says. * - * Only fills a metatable it created. A second extension registered under the same name on the - * same state finds the first one's and leaves it alone. + * Only fills a metatable it created. A second extension under the same name on the same state + * finds the first one's and leaves it alone, unless it asked to be `exclusive`. */ - protected defineMetatable(metamethods: Record = {}): void { + protected defineMetatable(metamethods: Record = {}, { exclusive = false, boxed = true }: MetatableOptions = {}): void { const state = this.state const module = state.module const L = state.address if (module.luaL_newmetatable(L, this.name)) { const metatableIndex = module.lua_gettop(L) + state.marshaller.owners.set(module.lua_topointer(L, metatableIndex), this) - module.lua_pushstring(L, 'protected metatable') - module.lua_setfield(L, metatableIndex, '__metatable') + if (boxed) { + module.lua_pushstring(L, 'protected metatable') + module.lua_setfield(L, metatableIndex, '__metatable') - module.lua_pushcclosure(L, module.referenceGcFunction(), 0) - module.lua_setfield(L, metatableIndex, '__gc') + module.lua_pushcclosure(L, module.referenceGcFunction(), 0) + module.lua_setfield(L, metatableIndex, '__gc') + } for (const key in metamethods) { - state.pushValue(metamethods[key]) + const value = metamethods[key] + state.pushValue(typeof value === 'object' && value !== null && !(value instanceof LuaMarshalled) ? copy(value) : value) module.lua_setfield(L, metatableIndex, key) } + } else if (exclusive) { + module.lua_pop(L, 1) + throw new Error(`the name '${this.name}' is already taken in this state`) } // Whether created here or found, the metatable is on the stack. module.lua_pop(L, 1) } - // A base implementation that assumes user data serialisation - public getValue(thread: Thread, index: number, _cache?: LuaGetCache): T { - const value = thread.module.getReferenceBox(thread.address, index, this.name) - if (value === undefined) { - throw new Error(`data does not have the expected metatable: ${this.name}`) - } - return value as T + /** + * {@link defineMetatable}, put off until the first value of this type is pushed: building a + * metatable is most of what an extension costs, and a state pays it for every one it creates. + */ + protected deferMetatable(metamethods: () => Record): void { + this.deferredMetamethods = metamethods } - // Return false if type not matched, otherwise true. This base method does not - // check the type. That must be done by the class extending this. - public pushValue(thread: Thread, decoratedValue: Decoration, _cache?: LuaPushCache): boolean { - this.pushReference(thread, decoratedValue.target) - return true + /** + * The JS value of the Lua value at `index`, which the caller has already established to carry + * this extension's metatable. This base reads a reference box. + */ + public getValue(thread: Thread, index: number, _cache?: LuaGetCache): T { + return thread.module.getReferenceBox(thread.address, index) as T } /** @@ -114,6 +141,12 @@ export default abstract class LuaTypeExtension { * over the box, which it sees as its first upvalue. */ protected pushReference(thread: Thread, referent: unknown, wrapClosure?: (L: LuaAddress) => void): void { + if (this.deferredMetamethods !== undefined) { + const metamethods = this.deferredMetamethods + this.deferredMetamethods = undefined + this.defineMetatable(metamethods()) + } + const module = thread.module const L = thread.address const cachedType = wrapClosure === undefined ? LuaType.Userdata : LuaType.Function diff --git a/src/type-extensions/class.ts b/src/type-extensions/class.ts new file mode 100644 index 0000000..0bb1ab7 --- /dev/null +++ b/src/type-extensions/class.ts @@ -0,0 +1,220 @@ +import { copy } from '../marshal' +import type LuaState from '../state' +import type Thread from '../thread' +import TypeExtension from '../type-extension' +import type { LuaClass, LuaClassOptions } from '../types' + +type AnyFunction = (...args: any[]) => any + +/** + * An instance's `__index`, as a chunk that takes the table of methods and the JS function that + * reads everything else. Looking a method up is then a table access inside Lua, and only a field + * or an accessor crosses into JS. + */ +const INDEX_SOURCE = `local methods, get = ... +return function(self, key) + local method = methods[key] + if method ~= nil then return method end + return get(self, key) +end` + +const RESERVED_METAMETHODS = ['__gc', '__metatable', '__name'] + +const classNameOf = (ctor: LuaClass, options: LuaClassOptions): string => { + if (typeof ctor !== 'function' || typeof ctor.prototype !== 'object' || ctor.prototype === null) { + throw new TypeError('defineClass expects a class') + } + const name = options.name ?? ctor.name + if (!name) { + throw new TypeError('defineClass needs a name for an anonymous class, pass one as options.name') + } + return name +} + +/** Where a number indexes from: an `Array` subclass is a sequence in Lua like any other array. */ +const toJsIndex = (target: unknown, key: number): number => (Array.isArray(target) ? key - 1 : key) + +/** The class itself in Lua: called to construct, indexed for its static members. */ +class ClassObjectExtension extends TypeExtension { + private readonly staticMethods = new Map() + private readonly construct: AnyFunction + + public constructor( + state: LuaState, + name: string, + private readonly ctor: LuaClass, + private readonly allowed: ReadonlySet | undefined, + ) { + super(state, `${name}.class`) + this.construct = (...args: any[]) => Reflect.construct(ctor, args) + + this.defineMetatable( + { + __call: (_self: unknown, ...args: any[]) => Reflect.construct(ctor, args), + __index: (_self: unknown, key: unknown) => this.get(key), + __tostring: () => `class ${name}`, + }, + { exclusive: true }, + ) + } + + public push(thread: Thread): void { + this.pushReference(thread, this.ctor) + } + + private get(key: unknown): unknown { + if (typeof key !== 'string') { + return undefined + } + if (this.allowed ? !this.allowed.has(key) : !this.isStatic(key)) { + // Constructing is always spelled both ways, `Class(...)` and `Class.new(...)`. + return key === 'new' ? this.construct : undefined + } + const value = (this.ctor as unknown as Record)[key] + return typeof value === 'function' ? this.staticMethod(key) : value + } + + /** Declared on the class or one it extends, rather than inherited from `Function`. */ + private isStatic(key: string): boolean { + if (key === 'prototype') { + return false + } + for (let ctor: unknown = this.ctor; typeof ctor === 'function' && ctor !== Function.prototype; ctor = Object.getPrototypeOf(ctor)) { + if (Object.hasOwn(ctor, key)) { + return true + } + } + return false + } + + /** One per name, so `Class.method == Class.method` in Lua. Called on the class, as JS would. */ + private staticMethod(name: string): AnyFunction { + let method = this.staticMethods.get(name) + if (!method) { + const ctor = this.ctor as unknown as Record + method = (...args: any[]) => ctor[name]!(...args) + this.staticMethods.set(name, method) + } + return method + } +} + +/** + * A class defined through `LuaState.defineClass`. Its instances cross into Lua by reference with a + * metatable of the class's own, where methods follow Lua's convention and nothing else: the + * receiver is the first argument, which `object:method(...)` passes. + */ +export default class ClassTypeExtension extends TypeExtension { + public readonly classObject: ClassObjectExtension + private readonly members: ReadonlySet | undefined + private readonly methods = new Map() + + public constructor( + state: LuaState, + public readonly ctor: LuaClass, + options: LuaClassOptions = {}, + ) { + super(state, classNameOf(ctor, options)) + this.members = options.members && new Set(options.members) + + const { metamethods = {} } = options + for (const key of RESERVED_METAMETHODS) { + if (key in metamethods) { + throw new TypeError(`defineClass cannot replace ${key}`) + } + } + + this.defineMetatable({ __newindex: this.set, ...metamethods }, { exclusive: true }) + if (!('__index' in metamethods)) { + this.installIndex() + } + this.classObject = new ClassObjectExtension(state, this.name, ctor, options.statics && new Set(options.statics)) + } + + public push(thread: Thread, instance: T): void { + this.pushReference(thread, instance) + } + + private allows(key: string): boolean { + return this.members === undefined || this.members.has(key) + } + + private installIndex(): void { + const { state } = this + const { module, address: L } = state + + module.luaL_getmetatable(L, this.name) + state.loadString(INDEX_SOURCE, { name: '=defineClass' }) + state.pushValue(copy(this.collectMethods())) + state.pushValue(this.get) + module.lua_callk(L, 2, 1, 0, null) + module.lua_setfield(L, -2, '__index') + module.lua_pop(L, 1) + } + + /** Every method the class and the ones it extends declare, short of `Object`'s own. */ + private collectMethods(): Record { + const methods: Record = Object.create(null) + const seen = new Set(['constructor']) + + for ( + let proto: object | null = this.ctor.prototype; + proto !== null && proto !== Object.prototype; + proto = Object.getPrototypeOf(proto) + ) { + for (const key of Object.getOwnPropertyNames(proto)) { + // Seen even when it turns out to be an accessor, which then shadows a method of + // the same name further up the chain the way it does in JS. + if (seen.has(key)) { + continue + } + seen.add(key) + if (this.allows(key) && typeof Object.getOwnPropertyDescriptor(proto, key)!.value === 'function') { + methods[key] = this.method(key) + } + } + } + return methods + } + + /** + * One per name and shared by every instance, so `a.method == b.method` in Lua. Looked up on + * the receiver at each call rather than captured here, which is what lets a subclass that was + * not defined itself still answer with its own override. + */ + private method(name: string): AnyFunction { + let method = this.methods.get(name) + if (!method) { + const { ctor, name: className } = this + method = (self: any, ...args: any[]) => { + if (!(self instanceof ctor)) { + throw new TypeError(`bad argument #1 to '${name}' (${className} expected), call it as object:${name}(...)`) + } + return (self as Record)[name]!(...args) + } + this.methods.set(name, method) + } + return method + } + + private readonly get = (self: any, key: unknown): unknown => { + if (typeof key === 'number') { + return this.members === undefined ? self[toJsIndex(self, key)] : undefined + } + if (typeof key !== 'string' || !this.allows(key)) { + return undefined + } + const value = self[key] + return typeof value === 'function' ? this.method(key) : value + } + + private readonly set = (self: any, key: unknown, value: unknown): void => { + if (typeof key === 'number' && this.members === undefined) { + self[toJsIndex(self, key)] = value + } else if (typeof key === 'string' && this.allows(key)) { + self[key] = value + } else { + throw new Error(`cannot set '${String(key)}' on a ${this.name}`) + } + } +} diff --git a/src/type-extensions/defined.ts b/src/type-extensions/defined.ts new file mode 100644 index 0000000..79ac840 --- /dev/null +++ b/src/type-extensions/defined.ts @@ -0,0 +1,74 @@ +import type LuaState from '../state' +import type Thread from '../thread' +import TypeExtension from '../type-extension' +import { type LuaGetCache, type LuaPushCache, LuaType, type LuaTypeDefinition } from '../types' + +/** A type defined through `LuaState.defineType`. */ +export default class DefinedTypeExtension extends TypeExtension { + private readonly match: (value: unknown) => boolean + private readonly toLua: ((value: T) => unknown) | undefined + private readonly fromLua: ((value: any) => T) | undefined + private readonly boxed: boolean + + public constructor(state: LuaState, definition: LuaTypeDefinition) { + if (typeof definition.name !== 'string' || !definition.name) { + throw new TypeError('defineType needs a name') + } + if (typeof definition.match !== 'function') { + throw new TypeError('defineType needs a match function') + } + super(state, definition.name) + this.match = definition.match + this.toLua = definition.toLua + this.fromLua = definition.fromLua + // A type that converts lives in Lua as a table, with no reference to release. + this.boxed = !this.toLua && !this.fromLua + + this.defineMetatable(definition.metatable, { exclusive: true, boxed: this.boxed }) + } + + /** Whether Lua tables whose metatable is merely named after this type are read through it. */ + public get readsByName(): boolean { + return this.fromLua !== undefined + } + + /** False when the value is not of this type, which leaves it to whatever is consulted next. */ + public push(thread: Thread, value: unknown, cache?: LuaPushCache): boolean { + if (!this.match(value)) { + return false + } + if (this.boxed) { + this.pushReference(thread, value) + return true + } + if (!this.toLua) { + return false + } + + const converted = this.toLua(value as T) + // Declining a value this way cannot recurse, where pushing it again would. + if (converted === value) { + return false + } + thread.pushValue(converted, cache) + + // Only a table can be told apart later. One that already has a metatable keeps it. + const { module, address: L } = thread + if (module.lua_type(L, -1) === LuaType.Table) { + if (module.lua_getmetatable(L, -1)) { + module.lua_pop(L, 1) + } else { + module.luaL_setmetatable(L, this.name) + } + } + return true + } + + public override getValue(thread: Thread, index: number, cache?: LuaGetCache): T { + if (this.boxed) { + return super.getValue(thread, index) + } + const value = this.state.marshaller.tables.getValue(thread, index, cache) + return this.fromLua ? this.fromLua(value) : (value as T) + } +} diff --git a/src/type-extensions/error.ts b/src/type-extensions/error.ts index 715ad1f..d370a9b 100644 --- a/src/type-extensions/error.ts +++ b/src/type-extensions/error.ts @@ -1,56 +1,61 @@ -import type { Decoration } from '../decoration' +import { copy } from '../marshal' import type LuaState from '../state' import type Thread from '../thread' import TypeExtension from '../type-extension' +/** + * A JS `Error` in Lua: a read-only userdata that renders as its message and exposes `message`, + * `name`, `stack` and whatever the error carries as own properties (`code`, `cause`, ...). + * Nothing inherited is reachable, so an error thrown into a state that copies its objects does not + * hand Lua a way back into JS. + */ class ErrorTypeExtension extends TypeExtension { public constructor(state: LuaState, injectObject: boolean) { super(state, 'js_error') - this.defineMetatable({ - __index: (jsRefError: Error, key: unknown) => { + this.deferMetatable(() => ({ + __index: (error: Error, key: unknown) => { switch (key) { case 'message': - return jsRefError.message + return error.message case 'name': - return jsRefError.name + return error.name case 'stack': - return jsRefError.stack + return error.stack default: - return undefined + return typeof key === 'string' && Object.hasOwn(error, key) + ? (error as unknown as Record)[key] + : undefined } }, // The message rather than toString to avoid the Error: prefix being // added. This fits better with Lua errors. - __tostring: (jsRefError: Error) => jsRefError.message, - }) + __tostring: (error: Error) => error.message, + })) if (injectObject) { // Lastly create a static Error constructor. - state.set('Error', { - create: (message: string | undefined) => { - if (message && typeof message !== 'string') { - throw new Error('message must be a string') - } + state.set( + 'Error', + copy({ + create: (message: string | undefined) => { + if (message && typeof message !== 'string') { + throw new Error('message must be a string') + } - return new Error(message) - }, - }) + return new Error(message) + }, + }), + ) } } - public pushValue(thread: Thread, decoration: Decoration): boolean { - if (!(decoration.target instanceof Error)) { - return false - } - // An explicit `as` names a representation this extension does not provide. - if (decoration.options.as !== undefined) { - return false - } - return super.pushValue(thread, decoration) + public push(thread: Thread, error: Error): void { + this.pushReference(thread, error) } } -export default function createTypeExtension(state: LuaState, injectObject: boolean): TypeExtension { +export default function createTypeExtension(state: LuaState, injectObject: boolean): ErrorTypeExtension { return new ErrorTypeExtension(state, injectObject) } +export type { ErrorTypeExtension } diff --git a/src/type-extensions/function.ts b/src/type-extensions/function.ts index bb31197..772e662 100644 --- a/src/type-extensions/function.ts +++ b/src/type-extensions/function.ts @@ -1,5 +1,4 @@ -import { decorate, Decoration, type DecorationOptions } from '../decoration' -import RawResult from '../raw-result' +import { BoundMethod, LuaMarshalled, type LuaRawFunction, raw } from '../marshal' import type LuaState from '../state' import type Thread from '../thread' import TypeExtension from '../type-extension' @@ -14,13 +13,9 @@ type LuaFunction = FunctionType & Record /** The parts of the state's options that bear on calling a Lua function. */ export interface FunctionCallOptions { - functionTimeout?: number | undefined - maxInstructions?: number | undefined onAsyncError?: ((error: unknown) => void) | undefined } -const NO_OPTIONS: DecorationOptions = {} - /** * What `async(fn)` returns, as a chunk that takes the JS function starting the run and gives back * the function doing the wrapping. @@ -30,11 +25,6 @@ return function(fn) return function(...) return start(fn, ...) end end` -/** Whether the wrapper would behave any differently for these options than for none. */ -function affectsCall(options: DecorationOptions): boolean { - return options.self !== undefined || options.receiveThread === true || options.receiveArgsQuantity === true -} - export class FunctionTypeExtension extends TypeExtension { private readonly functionRegistry = new FinalizationRegistry((func: number) => { if (!this.state.isClosed()) { @@ -56,24 +46,23 @@ export class FunctionTypeExtension extends TypeExtension { * context's stack, and handed out only when no other call is using it: a reentrant call (Lua → * JS → Lua) falls back to a thread of its own. */ - private readonly pooledCallThread: Thread + private pooledCallThread: Thread + private pooledCallReference: number private pooledCallThreadInUse = false - private readonly functionTimeout: number | undefined - private readonly maxInstructions: number | undefined private readonly onAsyncError: ((error: unknown) => void) | undefined public constructor(state: LuaState, options: FunctionCallOptions = {}) { super(state, 'js_function') - this.functionTimeout = options.functionTimeout - this.maxInstructions = options.maxInstructions this.onAsyncError = options.onAsyncError // Create a thread off of the global thread to be used to create function call threads without // interfering with the global context. This creates a callback context that will always exist // even if the thread that called getValue() has been destroyed. Neither anchor is ever // released, for the reason given on LuaTypeExtension.close. this.callbackContext = state.newAnchoredThread().thread - this.pooledCallThread = this.callbackContext.newAnchoredThread().thread + const pooled = this.callbackContext.newAnchoredThread() + this.pooledCallThread = pooled.thread + this.pooledCallReference = pooled.reference // Nothing but the box's own __gc: the metatable goes on the upvalue, not on the closure // Lua sees, so no metamethod on it could ever be reached. @@ -82,51 +71,48 @@ export class FunctionTypeExtension extends TypeExtension { this.functionWrapper = state.module.addFunction((calledL: LuaAddress) => { const calledThread = state.stateToThread(calledL) - // The upvalue is always the userdata pushValue closed this wrapper over, so the - // metatable check luaL_checkudata does (and the name it marshals) is saved on every - // call. Only a ref that resolves to neither a function nor a function decoration -- the - // upvalue replaced through the debug library -- falls back to it, for the error the C - // API would have raised. + // The upvalue is always the userdata a push closed this wrapper over, so the metatable + // check luaL_checkudata does (and the name it marshals) is saved on every call. Only a + // ref that resolves to nothing callable -- the upvalue replaced through the debug + // library -- falls back to it, for the error the C API would have raised. const upvalueIndex = state.module.lua_upvalueindex(1) const reference = state.module.getReferenceBox(calledL, upvalueIndex) - let target: FunctionType - let decorationOptions: DecorationOptions - if (typeof reference === 'function') { - target = reference as FunctionType - decorationOptions = NO_OPTIONS - } else if (reference instanceof Decoration && typeof reference.target === 'function') { - target = reference.target - decorationOptions = reference.options - } else { - // Raises the error the C API would have; the throw below is unreachable. - state.module.luaL_checkudata(calledL, upvalueIndex, this.name) - throw new Error('a js_function upvalue does not hold a function reference') - } - const argsQuantity = calledThread.getTop() - const args = [] - - if (decorationOptions.receiveThread) { - args.push(calledThread) - } - if (decorationOptions.receiveArgsQuantity) { - args.push(argsQuantity) - } else { - for (let i = 1; i <= argsQuantity; i++) { - const value = calledThread.getValue(i) - if (i !== 1 || !decorationOptions?.self || value !== decorationOptions.self) { - args.push(value) + try { + let result: unknown + if (typeof reference === 'function') { + const args = [] + for (let i = 1; i <= argsQuantity; i++) { + args.push(calledThread.getValue(i)) + } + result = (reference as FunctionType)(...args) + } else if (reference instanceof BoundMethod) { + const { self } = reference + const args = [] + for (let i = 1; i <= argsQuantity; i++) { + const value = calledThread.getValue(i) + // The receiver of a `:` call. The method is called on `self` either way. + if (i !== 1 || value !== self) { + args.push(value) + } + } + result = reference.target.apply(self, args) + } else if (reference instanceof LuaMarshalled && reference.as === 'raw') { + const count = (reference.target as LuaRawFunction)(calledThread, argsQuantity) as unknown + if (count === SUSPEND) { + return -1 + } + if (!Number.isInteger(count) || (count as number) < 0) { + throw new TypeError('a raw function has to return the number of values it pushed') } + return count as number + } else { + // Raises the error the C API would have; the throw below is unreachable. + state.module.luaL_checkudata(calledL, upvalueIndex, this.name) + throw new Error('a js_function upvalue does not hold a function reference') } - } - - try { - const result = target.apply(decorationOptions?.self, args) - if (result === SUSPEND) { - return -1 - } return calledThread.pushReturnValues(result) } catch (err) { if (isEmscriptenUnwind(err)) { @@ -176,38 +162,50 @@ export class FunctionTypeExtension extends TypeExtension { // already propagating -- the setTop clears the error object a failed reset leaves // behind instead. this.state.module.lua_resetthread(callThread.address) + if (callThread.hookLost) { + this.replacePooledCallThread() + return + } } callThread.setTop(0) this.pooledCallThreadInUse = false } - public isType(_thread: Thread, _index: number, type: LuaType): boolean { - return type === LuaType.Function - } + /** + * A limit that interrupts a call leaves the thread it ran on with its debug hook disabled for + * good (see {@link Thread.hookLost}), so reusing it would put every later call beyond the + * reach of any limit. That one is let go and the next call gets a thread of its own. + */ + private replacePooledCallThread(): void { + const { module } = this.state + const retired = this.pooledCallThread + const retiredReference = this.pooledCallReference + + const pooled = this.callbackContext.newAnchoredThread() + this.pooledCallThread = pooled.thread + this.pooledCallReference = pooled.reference + this.pooledCallThreadInUse = false - public pushValue(thread: Thread, decoration: Decoration): boolean { - if (typeof decoration.target !== 'function') { - return false - } + retired.close() + module.luaL_unref(this.callbackContext.address, LUA_REGISTRYINDEX, retiredReference) + } - // It's surprisingly inefficient to map JS functions to C functions so this creates a reference to the - // function which stays solely in JS. The cfunction called from Lua is created at the top of the class - // and it accesses the JS data through an upvalue. - // - // The wrapper only needs the decoration when it carries an option it acts on. Otherwise the - // bare function is referenced instead, so that every push of the same function -- decorated - // or not, since Thread.pushValue synthesises a fresh decoration for a plain one -- shares - // one reference and, through the cache below, one Lua closure. A decoration with options - // is referenced as it is: the same instance pushed twice still yields one closure, while - // the same function under different options stays distinct, as its behaviour is. - const referent: unknown = affectsCall(decoration.options) ? decoration : decoration.target - - // Pushed through the C trampoline rather than a bare closure, so an `:await()` inside the - // function can suspend the wasm stack. - this.pushReference(thread, referent, (L) => this.state.module.wasmoon_push_jsfunction(L, this.functionWrapper)) - return true + /** + * Pushes a JS function as a Lua one. It's surprisingly inefficient to map JS functions to C + * functions, so what is pushed is a closure over a reference that stays solely in JS: the + * cfunction created at the top of the class reads it from an upvalue. Through the C trampoline + * rather than a bare closure, so an `:await()` inside the function can suspend the wasm stack. + * + * The reference is the function itself, or the wrapper that says how to call it (a proxy's + * bound method, a `raw` function), so that every push of the same one shares one reference + * and, through the push cache, one Lua closure. + */ + public push(thread: Thread, referent: FunctionType | LuaMarshalled): void { + this.pushReference(thread, referent, this.wrapClosure) } + private readonly wrapClosure = (L: LuaAddress): void => this.state.module.wasmoon_push_jsfunction(L, this.functionWrapper) + public getValue(thread: Thread, index: number): FunctionType { // Create a copy of the function thread.module.lua_pushvalue(thread.address, index) @@ -220,6 +218,8 @@ export class FunctionTypeExtension extends TypeExtension { // A call can leave its thread in an inconsistent state, so each one gets a thread that // is either fresh or has been reset since the last call. const callThread = this.acquireCallThread() + // A call is a run: under the state's limits, and inside those of the run that made it. + const leaveRun = callThread.enterRun(undefined, true) let result: unknown try { // Spelled out rather than shared with async through a helper: this is the call @@ -233,10 +233,6 @@ export class FunctionTypeExtension extends TypeExtension { callThread.pushValue(arg) } - if (this.functionTimeout) { - callThread.setDeadline(Date.now() + this.functionTimeout) - } - // Resumed rather than pcalled, which costs the same and reports a yield as a status // this can name, instead of as Lua's error about yielding outside a coroutine. const resumed = callThread.resume(args.length) @@ -246,9 +242,11 @@ export class FunctionTypeExtension extends TypeExtension { callThread.assertOk(resumed.result) result = resumed.resultCount >= 1 ? callThread.getValue(1) : null } catch (err) { + leaveRun() this.releaseCallThread(callThread, true) throw err } + leaveRun() this.releaseCallThread(callThread, false) return result } @@ -292,23 +290,23 @@ export class FunctionTypeExtension extends TypeExtension { public injectAsync(): void { const { state } = this const module = state.module - const raw = { receiveThread: true, receiveArgsQuantity: true } const { onAsyncError } = this // Called with the function and then its arguments, which are still on the caller's stack. - const start = decorate((caller: Thread, valueCount: number) => { + const start = raw((caller, valueCount) => { const run = this.runCall((thread) => { module.lua_xmove(caller.address, thread.address, valueCount) return valueCount - 1 }) - return onAsyncError ? reportIfUnobserved(run, onAsyncError) : run - }, raw) + caller.pushValue(onAsyncError ? reportIfUnobserved(run, onAsyncError) : run) + return 1 + }) // Compiled by the first call rather than for every state that injects it, most of which // never make one: loading it up front cost a quarter of creating the state. let wrap: number | undefined state.set( 'async', - decorate((thread: Thread) => { + raw((thread) => { const L = thread.address const type = module.lua_type(L, 1) if (type !== LuaType.Function) { @@ -323,8 +321,8 @@ export class FunctionTypeExtension extends TypeExtension { module.lua_rawgeti(L, LUA_REGISTRYINDEX, wrap) module.lua_pushvalue(L, 1) module.lua_callk(L, 1, 1, 0, null) - return new RawResult(1) - }, raw), + return 1 + }), ) } @@ -341,10 +339,7 @@ export class FunctionTypeExtension extends TypeExtension { // synchronous call made in the meantime. const { thread, reference } = this.callbackContext.newAnchoredThread() try { - thread.setLimits(this.state.getLimits()) - const { functionTimeout: timeout, maxInstructions } = this - const defaults = timeout !== undefined || maxInstructions !== undefined - const values = await thread.run(prepare(thread), defaults ? { timeout, maxInstructions, ...options } : options) + const values = await thread.run(prepare(thread), options) return values[0] ?? undefined } finally { // The same teardown as LuaState.callByteCode. Sharing it through a helper costs each diff --git a/src/type-extensions/null.ts b/src/type-extensions/null.ts index f4c61c9..9a24a7a 100644 --- a/src/type-extensions/null.ts +++ b/src/type-extensions/null.ts @@ -1,10 +1,9 @@ -import type { Decoration } from '../decoration' import type LuaState from '../state' import type Thread from '../thread' import TypeExtension from '../type-extension' import { LUA_REGISTRYINDEX } from '../types' -class NullTypeExtension extends TypeExtension { +class NullTypeExtension extends TypeExtension { private nullReference: number public constructor(state: LuaState) { @@ -28,23 +27,16 @@ class NullTypeExtension extends TypeExtension { state.module.lua_setglobal(state.address, 'null') } - public getValue(thread: Thread, index: number): null { - const refUserData = thread.module.luaL_testudata(thread.address, index, this.name) - if (!refUserData) { - throw new Error(`data does not have the expected metatable: ${this.name}`) - } + public getValue(): null { return null } - public pushValue(thread: Thread, decoration: Decoration): boolean { - if (decoration.target !== null) { - return false - } + public push(thread: Thread): void { thread.module.lua_rawgeti(thread.address, LUA_REGISTRYINDEX, this.nullReference) - return true } } -export default function createTypeExtension(state: LuaState): TypeExtension { +export default function createTypeExtension(state: LuaState): NullTypeExtension { return new NullTypeExtension(state) } +export type { NullTypeExtension } diff --git a/src/type-extensions/promise.ts b/src/type-extensions/promise.ts index e872032..6206e05 100644 --- a/src/type-extensions/promise.ts +++ b/src/type-extensions/promise.ts @@ -1,4 +1,4 @@ -import { decorate, type Decoration } from '../decoration' +import { copy, type LuaRawFunction, raw } from '../marshal' import type LuaState from '../state' import type Thread from '../thread' import TypeExtension from '../type-extension' @@ -34,49 +34,46 @@ class PromiseTypeExtension extends TypeExtension> { // async function it stands in for. Anything else is passed through as it is. const reaction = (callback: Reaction): Reaction => (state.isLuaFunction(callback) ? state.async(callback) : callback) - this.defineMetatable({ - // A plain object, which the table extension (registered before this one) copies into a - // Lua table of methods. + this.deferMetatable(() => ({ + // A plain object, which a metatable copies into a Lua table of methods. __index: { next: (self: unknown, onFulfilled: Reaction, onRejected: Reaction) => asPromise(self).then(reaction(onFulfilled), reaction(onRejected)), catch: (self: unknown, onRejected: Reaction) => asPromise(self).catch(reaction(onRejected)), finally: (self: unknown, onFinally: Reaction) => asPromise(self).finally(reaction(onFinally)), - await: decorate( - (functionThread: Thread, rawSelf: unknown) => { - const self = asPromise(rawSelf) - if (!state.module.stackCanSuspend) { - throw new Error(state.module.jspiSupported ? SYNCHRONOUS_AWAIT : UNSUPPORTED_AWAIT) - } - return this.suspend(functionThread, self) - }, - { receiveThread: true }, - ), + // Raw for the thread it is called on, which is where the settled value has to go. + await: raw(((functionThread: Thread) => { + const self = asPromise(functionThread.getValue(1)) + if (!state.module.stackCanSuspend) { + throw new Error(state.module.jspiSupported ? SYNCHRONOUS_AWAIT : UNSUPPORTED_AWAIT) + } + return this.suspend(functionThread, self) + }) as unknown as LuaRawFunction), }, __eq: (self: Promise, other: Promise) => self === other, - }) + })) if (injectObject) { // Lastly create a static Promise constructor. - state.set('Promise', { - create: (callback: ConstructorParameters[0]) => new Promise(callback), - all: (promiseArray: any) => { - if (!Array.isArray(promiseArray)) { - throw new Error('argument must be an array of promises') - } + state.set( + 'Promise', + copy({ + create: (callback: ConstructorParameters[0]) => new Promise(callback), + all: (promiseArray: any) => { + if (!Array.isArray(promiseArray)) { + throw new Error('argument must be an array of promises') + } - return Promise.all(promiseArray.map((potentialPromise) => Promise.resolve(potentialPromise))) - }, - resolve: (value: any) => Promise.resolve(value), - }) + return Promise.all(promiseArray.map((potentialPromise) => Promise.resolve(potentialPromise))) + }, + resolve: (value: any) => Promise.resolve(value), + }), + ) } } - public pushValue(thread: Thread, decoration: Decoration): boolean { - if (!isPromise(decoration.target)) { - return false - } - return super.pushValue(thread, decoration) + public push(thread: Thread, promise: PromiseLike): void { + this.pushReference(thread, promise) } /** @@ -111,6 +108,7 @@ class PromiseTypeExtension extends TypeExtension> { } } -export default function createTypeExtension(state: LuaState, injectObject: boolean): TypeExtension> { - return new PromiseTypeExtension(state, injectObject) +export default function createTypeExtension(state: LuaState, injectObject: boolean): PromiseTypeExtension { + return new PromiseTypeExtension(state, injectObject) } +export type { PromiseTypeExtension } diff --git a/src/type-extensions/proxy.ts b/src/type-extensions/proxy.ts index 38d2382..33ea4a0 100644 --- a/src/type-extensions/proxy.ts +++ b/src/type-extensions/proxy.ts @@ -1,29 +1,20 @@ -import { decorate, Decoration } from '../decoration' +import { BoundMethod } from '../marshal' import type LuaState from '../state' import MultiReturn from '../multireturn' import type Thread from '../thread' import TypeExtension from '../type-extension' -import { isPromise } from '../utils' -const isClass = (target: unknown): target is new (...args: any[]) => any => - target === Date || (typeof target === 'function' && target.prototype?.constructor === target && target.toString().startsWith('class ')) - -const isClassLike = (target: unknown): boolean => { - if (typeof target !== 'function' || !target.prototype || target.prototype.constructor !== target) { - return false - } - return isClass(target) || Object.getOwnPropertyNames(target.prototype).length > 1 -} +type AnyFunction = (...args: any[]) => any /** - * Lua indexes js objects with the key as given, except that a number is mapped from Lua's 1 based - * indexing to JS's 0 -- which matters most for ipairs, which calls __index with 1, 2, 3... until - * it gets nil. + * Lua indexes a JS value with the key as given, except that an array is indexed from 1 the way a + * Lua sequence is -- which matters most for ipairs, which calls __index with 1, 2, 3... until it + * gets nil. Only an array: on any other object a number is the property it names. */ -const toJsKey = (key: unknown): string | number => { +const toJsKey = (target: unknown, key: unknown): string | number => { switch (typeof key) { case 'number': - return key - 1 + return Array.isArray(target) ? key - 1 : key case 'string': return key default: @@ -31,22 +22,34 @@ const toJsKey = (key: unknown): string | number => { } } +/** + * What an object is pushed as when the state's `objects` is `'proxy'`, and anything wrapped in + * `proxy(value)`: a userdata that forwards to the JS value. + */ class ProxyTypeExtension extends TypeExtension { - private readonly boundMethods = new WeakMap any, Decoration<(...args: any[]) => any>>>() + private readonly boundMethods = new WeakMap>() + private readonly constructors = new WeakMap() public constructor(state: LuaState) { super(state, 'js_proxy') - this.defineMetatable({ + this.deferMetatable(() => ({ __index: (self: any, key: unknown) => { - const value = self[toJsKey(key)] + const jsKey = toJsKey(self, key) + const value = self[jsKey] if (typeof value === 'function') { - return this.bindMethod(self, value as (...args: any[]) => any) + // A class the state knows crosses as that class, wherever it is found. + return state.marshaller.hasClass(value) ? value : this.bindMethod(self, value as AnyFunction) + } + // Lua has no `new`, and whether a function wants one cannot be told from the + // outside, so constructing is spelled out: `Class.new(...)`. + if (value === undefined && jsKey === 'new' && typeof self === 'function') { + return this.constructorOf(self as AnyFunction) } return value }, __newindex: (self: any, key: unknown, value: any) => { - self[toJsKey(key)] = value + self[toJsKey(self, key)] = value }, __tostring: (self: any) => self.toString?.() ?? typeof self, __len: (self: any) => self.length || 0, @@ -69,16 +72,15 @@ class ProxyTypeExtension extends TypeExtension { ) }, __eq: (self: any, other: any) => self === other, - __call: (self: any, ...args: any[]) => { - if (args[0] === self) { - args.shift() - } - return isClass(self) ? new self(...args) : self(...args) - }, - }) + __call: (self: any, ...args: any[]) => self(...args), + })) } - private bindMethod(self: object, method: (...args: any[]) => any): Decoration<(...args: any[]) => any> { + public push(thread: Thread, target: unknown): void { + this.pushReference(thread, target) + } + + private bindMethod(self: object, method: AnyFunction): BoundMethod { let methods = this.boundMethods.get(self) if (!methods) { methods = new WeakMap() @@ -86,47 +88,24 @@ class ProxyTypeExtension extends TypeExtension { } let bound = methods.get(method) if (!bound) { - bound = decorate(method, { self }) + bound = new BoundMethod(method, self) methods.set(method, bound) } return bound } - public getValue(thread: Thread, index: number): any { - // isType has already matched the metatable, so the check is not paid for again here. - return thread.module.getReferenceBox(thread.address, index) - } - - public pushValue(thread: Thread, decoratedValue: Decoration): boolean { - const { target, options } = decoratedValue - if (options.as === undefined) { - if (target === null || target === undefined) { - return false - } - - if (typeof target !== 'object' && !isClassLike(target)) { - return false - } - - if (isPromise(target)) { - return false - } - } else if (options.as !== 'proxy') { - // Both 'userdata' and 'value' mean "do not go through the proxy layer". - return false - } - - if (options.metatable && !(options.metatable instanceof Decoration)) { - // Otherwise the metatable will get converted into a JS ref rather than being set as a standard - // table. This forces it to use the standard table type. - decoratedValue.options.metatable = decorate(options.metatable, { as: 'value' }) - return false + /** One per function, so `Class.new == Class.new` in Lua. */ + private constructorOf(target: AnyFunction): AnyFunction { + let construct = this.constructors.get(target) + if (!construct) { + construct = (...args: any[]) => Reflect.construct(target, args) + this.constructors.set(target, construct) } - - return super.pushValue(thread, decoratedValue) + return construct } } -export default function createTypeExtension(state: LuaState): TypeExtension { +export default function createTypeExtension(state: LuaState): ProxyTypeExtension { return new ProxyTypeExtension(state) } +export type { ProxyTypeExtension } diff --git a/src/type-extensions/table.ts b/src/type-extensions/table.ts index 15b0f4b..e960768 100644 --- a/src/type-extensions/table.ts +++ b/src/type-extensions/table.ts @@ -1,4 +1,3 @@ -import { Decoration } from '../decoration' import type LuaState from '../state' import type Thread from '../thread' import TypeExtension from '../type-extension' @@ -11,10 +10,6 @@ class TableTypeExtension extends TypeExtension { super(state, 'js_table') } - public isType(_thread: Thread, _index: number, type: LuaType): boolean { - return type === LuaType.Table - } - public getValue(thread: Thread, index: number, cache?: LuaGetCache): TableType { // This is a map of Lua pointers to JS objects. const seenMap: LuaGetCache = cache ?? new Map() @@ -33,17 +28,18 @@ class TableTypeExtension extends TypeExtension { return table } - public pushValue(thread: Thread, { target }: Decoration, cache?: LuaPushCache): boolean { - if (typeof target !== 'object' || target === null) { - return false - } - + /** + * Copies an object or array into a new Lua table. Handing the cache on to the values inside is + * what makes the copy a deep one: a push that carries one copies the objects it meets, whatever + * the state would otherwise do with them. + */ + public push(thread: Thread, target: object, cache?: LuaPushCache): void { // This is a map of JS objects to luaL references. const seenMap: LuaPushCache = cache ?? new Map() const existingReference = seenMap.get(target) if (existingReference !== undefined) { thread.module.lua_rawgeti(thread.address, LUA_REGISTRYINDEX, existingReference) - return true + return } try { @@ -78,8 +74,6 @@ class TableTypeExtension extends TypeExtension { } } } - - return true } private readTableValues(thread: Thread, index: number, seenMap: LuaGetCache, table: TableType): void { @@ -114,6 +108,7 @@ class TableTypeExtension extends TypeExtension { } } -export default function createTypeExtension(state: LuaState): TypeExtension { +export default function createTypeExtension(state: LuaState): TableTypeExtension { return new TableTypeExtension(state) } +export type { TableTypeExtension } diff --git a/src/type-extensions/userdata.ts b/src/type-extensions/userdata.ts index fd8432d..b89d4f8 100644 --- a/src/type-extensions/userdata.ts +++ b/src/type-extensions/userdata.ts @@ -1,29 +1,21 @@ -import type { Decoration } from '../decoration' import type LuaState from '../state' import type Thread from '../thread' import TypeExtension from '../type-extension' +/** What `opaque(value)` is pushed as: a reference Lua can hold and hand back, with no members. */ class UserdataTypeExtension extends TypeExtension { public constructor(state: LuaState) { super(state, 'js_userdata') // Opaque: nothing but the box's own __gc. - this.defineMetatable() + this.deferMetatable(() => ({})) } - public getValue(thread: Thread, index: number): any { - // isType has already matched the metatable, so the check is not paid for again here. - return thread.module.getReferenceBox(thread.address, index) - } - - public pushValue(thread: Thread, decoratedValue: Decoration): boolean { - if (decoratedValue.options.as !== 'userdata') { - return false - } - - return super.pushValue(thread, decoratedValue) + public push(thread: Thread, target: unknown): void { + this.pushReference(thread, target) } } -export default function createTypeExtension(state: LuaState): TypeExtension { +export default function createTypeExtension(state: LuaState): UserdataTypeExtension { return new UserdataTypeExtension(state) } +export type { UserdataTypeExtension } diff --git a/src/types.ts b/src/types.ts index fcc0e90..86f7524 100755 --- a/src/types.ts +++ b/src/types.ts @@ -71,17 +71,32 @@ export interface LuaMemoryOptions { max?: number | undefined } -export interface LuaLimitOptions { - /** - * Milliseconds a Lua function called from JS may run before being interrupted, whether it is - * called directly or as a run of its own through `state.async` or Lua's `async`. - */ - functionTimeout?: number | undefined +/** + * What a run may use before it is interrupted. A run is each entry from JS into Lua: a `doString` + * or `doFile`, a call of a Lua function, and the runs that `state.async`, Lua's `async` and a + * promise reaction start. + * + * The same three fields everywhere a limit can be given: as `limits` when creating a state and as + * `state.limits` afterwards, where they are what every run starts under, and in the options of a + * single run, where each one given replaces the state's -- `Infinity` to lift it. + * + * A run made from inside another, by a JS function that Lua called calling back into Lua, stays + * within the outer one's limits as well as its own. + */ +export interface LuaLimits { + /** Milliseconds the run may take, awaits included. */ + timeout?: number | undefined + /** Instructions the run may execute. */ + maxInstructions?: number | undefined /** - * Instructions a single run may execute before being interrupted. A run is a `doString` or - * `doFile`, or a function started through `state.async`, Lua's `async` or a promise reaction. + * Interrupts the run when the signal aborts. + * + * Interrupts parked awaits and onYield handlers without waiting for their promises to settle. + * A signal cannot fire while the event loop is blocked, so a timer cannot abort a tight Lua + * loop without async steps; use `timeout` or `maxInstructions` for those. Repeated awaits + * periodically give timers a turn, and a top level `coroutine.yield` without a handler always does. */ - maxInstructions?: number | undefined + signal?: AbortSignal | undefined } /** A global that `CreateStateOptions.inject` can define. */ @@ -108,15 +123,14 @@ export interface CreateStateOptions { */ libs?: LuaLibName[] | boolean | undefined /** - * How plain JS objects and class instances cross into Lua. `'proxy'` keeps their identity and - * exposes their members, `'copy'` marshals them into plain Lua tables. + * How an object crosses into Lua when nothing says otherwise: `'proxy'` (the default) keeps + * its identity and exposes its members, `'copy'` marshals it into a plain Lua table. + * + * `copy(value)`, `proxy(value)` and `opaque(value)` say otherwise for one value, and + * `defineClass` and `defineType` for every value of a kind. With `'copy'` those are the only + * ways Lua gets to reach into a JS object, which is what a state running untrusted code wants. */ objects?: 'proxy' | 'copy' | undefined - /** - * Registers the JS `Error` to Lua error bridge. Defaults to true when `objects` is `'copy'`, - * because the proxy already covers errors when it is enabled. - */ - errors?: boolean | undefined /** * Which helpers to define as Lua globals. `true` defines all of them, or name them * individually: @@ -124,7 +138,7 @@ export interface CreateStateOptions { * - `Promise`: `Promise.create`, `Promise.all` and `Promise.resolve`. * - `async`: `async(fn)` returns a function that runs `fn` as a run of its own and gives back * a promise of its first result, so that it can `:await()` whoever calls it. - * - `Error`: `Error.create`, where the error bridge is registered (see `errors`). + * - `Error`: `Error.create`. * - `null`: a sentinel that a JS `null` is marshalled as instead of `nil`. It is truthy in Lua. */ inject?: LuaInjectName[] | boolean | undefined @@ -136,26 +150,15 @@ export interface CreateStateOptions { */ onAsyncError?: ((error: unknown) => void) | undefined memory?: LuaMemoryOptions | undefined - limits?: LuaLimitOptions | undefined + /** What every run on the state starts under, also reachable afterwards as `state.limits`. */ + limits?: LuaLimits | undefined gc?: LuaGcOptions | undefined /** Where diagnostics go. Defaults to the runtime's handler, and then to `console.warn`. */ onWarn?: LuaWarnHandler | undefined } -export interface LuaRunOptions { - /** Milliseconds before the run is interrupted. */ - timeout?: number | undefined - /** Instructions the run may execute before being interrupted. */ - maxInstructions?: number | undefined - /** - * Interrupts the run when the signal aborts. - * - * Interrupts parked awaits and onYield handlers without waiting for their promises to settle. - * A signal cannot fire while the event loop is blocked, so a timer cannot abort a tight Lua - * loop without async steps; use `timeout` or `maxInstructions` for those. Repeated awaits - * periodically give timers a turn, and a top level `coroutine.yield` without a handler always does. - */ - signal?: AbortSignal | undefined +/** The limits of one run, each replacing the state's, and what to do when it yields. */ +export interface LuaRunOptions extends LuaLimits { /** * Called with the values of a top level `coroutine.yield`. Its return * becomes the result of that yield when the run resumes; a returned promise is awaited first, a @@ -178,15 +181,61 @@ export interface LuaLoadOptions { export type LuaDoOptions = LuaRunOptions & LuaLoadOptions -/** - * Deadline and budget enforced by the debug hook while a thread runs. Every field accepts an - * explicit undefined, which clears that one limit. - */ -export interface LuaThreadLimits { - /** Absolute timestamp, as returned by `Date.now()`. */ - deadline?: number | undefined - maxInstructions?: number | undefined - signal?: AbortSignal | undefined +/** A class, abstract or not, as `defineClass` takes it. */ +export type LuaClass = abstract new (...args: any[]) => T + +export interface LuaClassOptions { + /** + * Names the metatable: what `tostring` and Lua's error messages call an instance. Defaults to + * the class's own name, and has to be unique in the state. + */ + name?: string | undefined + /** + * The only members Lua can reach on an instance -- methods, fields and accessors alike, with + * everything else reading as nil and refusing assignment. Without it every member is + * reachable, inherited ones included. + */ + members?: readonly (keyof T & string)[] | undefined + /** + * The only static members Lua can reach on the class. Without it, the ones the class and the + * classes it extends declare. + */ + statics?: readonly string[] | undefined + /** + * Metamethods for the instances, each called with the instance first: `__tostring`, `__eq`, + * `__len`, `__add`, `__close` and the rest. `__index` or `__newindex` replace the member + * lookup altogether. + */ + metamethods?: Record unknown> | undefined +} + +export interface LuaTypeDefinition { + /** + * Names the type's metatable: what `tostring` and Lua's error messages call a value of it. Has + * to be unique in the state. + */ + name: string + /** Whether a JS value about to cross into Lua is of this type. */ + match: (value: unknown) => boolean + /** + * Metamethods for the type's metatable. A function among them is called with JS values, the + * value of this type first. + */ + metatable?: Record | undefined + /** + * What to push in place of the value: anything that can cross into Lua, wrapped in `copy` and + * the like if need be. Returning the value itself declines it, leaving it to whatever would + * have handled it otherwise. + * + * Without this the value crosses by reference, as a userdata that reads back as itself. + */ + toLua?: ((value: T) => unknown) | undefined + /** + * Turns a Lua table of this type back into a JS value, given the object or array the table + * reads as. A table is of this type when `toLua` produced it, or when Lua code gave it a + * metatable whose `__name` is this type's name. + */ + fromLua?: ((value: any) => T) | undefined } export enum LuaReturn { diff --git a/test/api.test.js b/test/api.test.js index d1f9dad..62d06be 100644 --- a/test/api.test.js +++ b/test/api.test.js @@ -1,5 +1,5 @@ import { expect } from 'chai' -import { LuaMultiReturn, LuaRawResult, LuaReturn, LuaType, LuaTypeExtension, decorate } from '../dist/index.js' +import { LuaMultiReturn, LuaReturn, LuaType, copy, raw } from '../dist/index.js' import { getLua, getState } from './utils.js' describe('MultiReturn', () => { @@ -35,23 +35,78 @@ describe('MultiReturn', () => { }) }) -describe('RawResult', () => { - it('should hand back values the function pushed itself', async () => { +describe('raw', () => { + it('should hand back the values the function pushed itself', async () => { using state = await getState() state.set( - 'raw', - decorate( - (thread) => { - thread.pushValue('a') - thread.pushValue('b') - return new LuaRawResult(2) - }, - { receiveThread: true }, - ), + 'pair', + raw((thread) => { + thread.pushValue('a') + thread.pushValue('b') + return 2 + }), + ) + + expect(await state.doString('local x, y = pair() return x .. y')).to.be.equal('ab') + expect(await state.doString('return select("#", pair())')).to.be.equal(2) + }) + + it('should receive the calling thread and the argument count, with the arguments still on the stack', async () => { + using state = await getState() + state.set( + 'describe', + raw((thread, argCount) => { + const args = [] + for (let i = 1; i <= argCount; i++) { + args.push(thread.getValue(i)) + } + thread.pushValue(`${typeof thread.address}:${argCount}:${args.join(',')}`) + return 1 + }), + ) + + expect(await state.doString('return describe("a", "b")')).to.be.equal('number:2:a,b') + expect(await state.doString('return describe()')).to.be.equal('number:0:') + }) + + it('should return its own arguments without marshalling them', async () => { + using state = await getState() + state.set( + 'swap', + raw((thread) => { + thread.module.lua_rotate(thread.address, 1, 1) + return 2 + }), + ) + + // A table that went through JS would come back as another table. + expect(await state.doString('local t = {} local a, b = swap(1, t) return a == t and b == 1')).to.be.equal(true) + }) + + it('should raise a JS error it throws as a Lua error', async () => { + using state = await getState() + state.set( + 'fail', + raw(() => { + throw new Error('raw failure') + }), + ) + + expect(await state.doString('local ok, err = pcall(fail) return tostring(err)')).to.be.equal('raw failure') + }) + + it('should refuse a result count that is not one', async () => { + using state = await getState() + state.set( + 'forgot', + raw(() => undefined), ) - expect(await state.doString('local x, y = raw() return x .. y')).to.be.equal('ab') - expect(await state.doString('return select("#", raw())')).to.be.equal(2) + await expect(state.doString('forgot()')).to.eventually.be.rejectedWith('number of values it pushed') + }) + + it('should only wrap a function', () => { + expect(() => raw({})).to.throw('raw expects a function') }) }) @@ -139,55 +194,31 @@ describe('Reference bookkeeping', () => { }) }) -describe('Decoration options', () => { - it('self should bind the receiver and drop it from the arguments', async () => { - using state = await getState() - const counter = { - n: 41, - bump(by) { - this.n += by ?? 1 - return this.n - }, - } - state.set('bump', decorate(counter.bump, { self: counter })) - - expect(await state.doString('return bump()')).to.be.equal(42) - expect(await state.doString('return bump(8)')).to.be.equal(50) - expect(counter.n).to.be.equal(50) - }) - - it('receiveThread should pass the calling thread as the first argument', async () => { - using state = await getState() - state.set( - 'grab', - decorate((thread, ...args) => `${typeof thread.address}:${args.join(',')}`, { receiveThread: true }), - ) - - expect(await state.doString('return grab("a", "b")')).to.be.equal('number:a,b') - }) - +describe('Function identity', () => { it('should push the same function as the same Lua value', async () => { using state = await getState() const fn = () => 1 state.set('a', fn) state.set('b', fn) - state.set('c', decorate(fn, {})) + state.set('c', copy(fn)) expect(await state.doString('return a == b and b == c')).to.be.equal(true) }) - it('should push the same decoration as the same Lua value, and different options as different ones', async () => { + it('should push the same raw wrapper as the same Lua value, and another wrapper as another', async () => { using state = await getState() - const fn = (...args) => args.length - const bound = decorate(fn, { self: {} }) - state.set('plain', fn) - state.set('bound1', bound) - state.set('bound2', bound) - state.set('counting', decorate(fn, { receiveArgsQuantity: true })) + const count = (_thread, argCount) => { + _thread.pushValue(argCount) + return 1 + } + const wrapped = raw(count) + state.set('raw1', wrapped) + state.set('raw2', wrapped) + state.set('other', raw(count)) - expect(await state.doString('return bound1 == bound2')).to.be.equal(true) - expect(await state.doString('return plain ~= bound1 and plain ~= counting and bound1 ~= counting')).to.be.equal(true) - expect(await state.doString('return plain(1, 2), bound1(1, 2), counting(1, 2)')).to.be.equal(2) + expect(await state.doString('return raw1 == raw2')).to.be.equal(true) + expect(await state.doString('return raw1 ~= other')).to.be.equal(true) + expect(await state.doString('return raw1(1, 2) + other(1, 2, 3)')).to.be.equal(5) }) it('should hand out the same Lua value for the same proxied method', async () => { @@ -204,52 +235,53 @@ describe('Decoration options', () => { expect(state.get('obj').n).to.be.equal(3) }) - it('receiveArgsQuantity should pass the count instead of the arguments', async () => { + it('a proxied method should reach its object called with a dot or with a colon', async () => { using state = await getState() - state.set( - 'count', - decorate((quantity) => quantity, { receiveArgsQuantity: true }), - ) + const counter = { + n: 41, + bump(by) { + this.n += by ?? 1 + return this.n + }, + } + state.set('counter', counter) - expect(await state.doString('return count(1, 2, 3)')).to.be.equal(3) - expect(await state.doString('return count()')).to.be.equal(0) + expect(await state.doString('return counter.bump()')).to.be.equal(42) + expect(await state.doString('return counter:bump(8)')).to.be.equal(50) + expect(await state.doString('local bump = counter.bump return bump(1)')).to.be.equal(51) + expect(counter.n).to.be.equal(51) }) }) -describe('Custom type extensions', () => { +describe('defineType', () => { class Point { constructor(x) { this.x = x } } - // A dedicated metatable name is the thing no built in provides, and what proves the custom - // extension ran rather than the userdata one. - class PointExtension extends LuaTypeExtension { - constructor(state) { - super(state, 'js_point') - this.defineMetatable({ __tostring: (point) => `Point(${point.x})` }) - } - - pushValue(thread, decoration) { - return decoration.target instanceof Point ? super.pushValue(thread, decoration) : false - } - } + const definePoint = (state) => + state.defineType({ + name: 'js_point', + match: (value) => value instanceof Point, + metatable: { __tostring: (point) => `Point(${point.x})`, __index: { kind: 'point' } }, + }) - it('should take priority over the built in handling and round trip', async () => { + it('should take what it matches ahead of the built in handling, and round trip it', async () => { using state = await getState() - state.registerTypeExtension(6, new PointExtension(state)) + definePoint(state) const point = new Point(9) state.set('pt', point) expect(await state.doString('return type(pt)')).to.be.equal('userdata') expect(await state.doString('return tostring(pt)')).to.be.equal('Point(9)') + expect(await state.doString('return pt.kind')).to.be.equal('point') expect(state.get('pt')).to.be.equal(point) }) it('should get a protected metatable and release the reference once collected', async () => { using state = await getState() - state.registerTypeExtension(6, new PointExtension(state)) + definePoint(state) const point = new Point(1) state.set('pt', point) @@ -260,13 +292,393 @@ describe('Custom type extensions', () => { expect(state.module.getRefIndex(point)).to.be.undefined }) - it('should leave values it refuses to the built in handling', async () => { + it('should leave values it does not match to the built in handling', async () => { using state = await getState() - state.registerTypeExtension(6, new PointExtension(state)) + definePoint(state) state.set('other', { x: 1 }) expect(await state.doString('return other.x')).to.be.equal(1) }) + + it('should take its values wherever they come from', async () => { + using state = await getState({ objects: 'copy' }) + definePoint(state) + state.set('make', (x) => new Point(x)) + state.set('nested', { inner: new Point(3) }) + + expect(await state.doString('return tostring(make(7))')).to.be.equal('Point(7)') + expect(await state.doString('return tostring(nested.inner)')).to.be.equal('Point(3)') + }) + + it('should consult the most recently defined type first', async () => { + using state = await getState() + state.defineType({ name: 'any_point', match: (value) => value instanceof Point, metatable: { __tostring: () => 'any' } }) + state.defineType({ + name: 'origin', + match: (value) => value instanceof Point && value.x === 0, + metatable: { __tostring: () => 'origin' }, + }) + state.set('zero', new Point(0)) + state.set('one', new Point(1)) + + expect(await state.doString('return tostring(zero) .. "," .. tostring(one)')).to.be.equal('origin,any') + }) + + it('should refuse a name that is taken', async () => { + using state = await getState() + definePoint(state) + + expect(() => definePoint(state)).to.throw("the name 'js_point' is already taken") + expect(() => state.defineType({ name: 'js_proxy', match: () => false })).to.throw("the name 'js_proxy' is already taken") + }) + + it('should need a name and a match', async () => { + using state = await getState() + + expect(() => state.defineType({ match: () => true })).to.throw('defineType needs a name') + expect(() => state.defineType({ name: 'nameless' })).to.throw('defineType needs a match function') + }) + + describe('toLua and fromLua', () => { + const defineMap = (state) => + state.defineType({ + name: 'Map', + match: (value) => value instanceof Map, + toLua: (map) => copy(Object.fromEntries(map)), + fromLua: (table) => new Map(Object.entries(table)), + }) + + it('should push what toLua returns in place of the value', async () => { + using state = await getState() + defineMap(state) + state.set('map', new Map([['answer', 42]])) + + expect(await state.doString('return type(map)')).to.be.equal('table') + expect(await state.doString('return map.answer')).to.be.equal(42) + }) + + it('should read a table toLua produced back through fromLua', async () => { + using state = await getState() + defineMap(state) + state.set('map', new Map([['answer', 42]])) + + const back = await state.doString('map.added = true return map') + + expect(back).to.be.an.instanceOf(Map) + expect([...back.entries()].sort()).to.be.eql([ + ['added', true], + ['answer', 42], + ]) + }) + + it('should read a table Lua named after the type through fromLua', async () => { + using state = await getState() + defineMap(state) + + const made = await state.doString('return setmetatable({ lua = "made" }, { __name = "Map" })') + + expect(made).to.be.an.instanceOf(Map) + expect(made.get('lua')).to.be.equal('made') + }) + + it('should leave a table named after a reference type as a table', async () => { + using state = await getState() + state.defineType({ name: 'js_point', match: (value) => value instanceof Point }) + + // Only the metatable the state created marks a reference box, never a name. + expect(await state.doString('return setmetatable({ x = 1 }, { __name = "js_point" })')).to.be.eql({ x: 1 }) + expect(await state.doString('return setmetatable({ x = 1 }, { __name = "js_proxy" })')).to.be.eql({ x: 1 }) + }) + + it('should hand the JS value to the metamethods of a converted type', async () => { + using state = await getState() + state.defineType({ + name: 'Set', + match: (value) => value instanceof Set, + toLua: (set) => copy([...set]), + fromLua: (items) => new Set(items), + metatable: { __tostring: (set) => `Set of ${set.size}`, __len: (set) => set.size * 10 }, + }) + state.set('set', new Set(['a', 'b'])) + + expect(await state.doString('return tostring(set)')).to.be.equal('Set of 2') + expect(await state.doString('return #set')).to.be.equal(20) + expect(await state.doString('return set[1]')).to.be.equal('a') + }) + + it('should decline a value when toLua returns it unchanged', async () => { + using state = await getState() + state.defineType({ name: 'passthrough', match: (value) => value instanceof Point, toLua: (value) => value }) + state.set('pt', new Point(4)) + + // Fell through to the proxy, as if the type had not matched. + expect(await state.doString('return pt.x')).to.be.equal(4) + }) + + it('should convert to a primitive, which has no type to read back', async () => { + using state = await getState() + state.defineType({ name: 'Date', match: (value) => value instanceof Date, toLua: (date) => date.getTime() }) + state.set('epoch', new Date(86_400_000)) + + expect(await state.doString('return math.type(epoch)')).to.be.equal('integer') + expect(await state.doString('return epoch')).to.be.equal(86_400_000) + }) + }) +}) + +describe('defineClass', () => { + class Vector { + static unit = 1 + static zero() { + return new Vector(0, 0) + } + + constructor(x, y) { + this.x = x + this.y = y + } + + get length() { + return Math.hypot(this.x, this.y) + } + + add(other) { + return new Vector(this.x + other.x, this.y + other.y) + } + + describe() { + return `a vector of ${this.x}, ${this.y}` + } + } + + class Vector3 extends Vector { + constructor(x, y, z) { + super(x, y) + this.z = z + } + + describe() { + return `${super.describe()}, ${this.z}` + } + } + + const getVectorState = async (options) => { + const state = await getState() + state.defineClass(Vector, options) + state.set('Vector', Vector) + return state + } + + it('should construct the class when it is called, or through new', async () => { + using state = await getVectorState() + + expect(await state.doString('return Vector(3, 4)')).to.be.an.instanceOf(Vector) + expect(await state.doString('return Vector.new(3, 4).x')).to.be.equal(3) + expect(await state.doString('return Vector.new == Vector.new')).to.be.equal(true) + }) + + it('should call methods with a colon, and read fields and accessors', async () => { + using state = await getVectorState() + + expect(await state.doString('local v = Vector(3, 4) return v:add(v).length')).to.be.equal(10) + expect(await state.doString('return Vector(1, 2):describe()')).to.be.equal('a vector of 1, 2') + }) + + it('should write fields', async () => { + using state = await getVectorState() + const vector = new Vector(1, 2) + state.set('v', vector) + + await state.doString('v.x = 10') + + expect(vector.x).to.be.equal(10) + }) + + it('should not guess the receiver of a method called with a dot', async () => { + using state = await getVectorState() + + // The vector is taken for the receiver, which leaves `add` without its argument. + await expect(state.doString('local v = Vector(3, 4) return v.add(v)')).to.eventually.be.rejectedWith( + 'Cannot read properties of undefined', + ) + await expect(state.doString('local v = Vector(3, 4) return v.describe()')).to.eventually.be.rejectedWith( + "bad argument #1 to 'describe' (Vector expected), call it as object:describe(...)", + ) + // The receiver is an argument like any other, so passing it by hand is the same call. + expect(await state.doString('local v = Vector(3, 4) return v.describe(v)')).to.be.equal('a vector of 3, 4') + expect(await state.doString('local v = Vector(3, 4) return v:add(v):add(v).x')).to.be.equal(9) + }) + + it('should share one function per method between the instances', async () => { + using state = await getVectorState() + + expect(await state.doString('return Vector(1, 2).add == Vector(3, 4).add')).to.be.equal(true) + }) + + it('should name the instances after the class', async () => { + using state = await getVectorState() + + expect(await state.doString('return type(Vector(1, 2))')).to.be.equal('userdata') + expect(await state.doString('return tostring(Vector(1, 2))')).to.match(/^Vector: 0x/) + expect(await state.doString('return tostring(Vector)')).to.be.equal('class Vector') + await expect(state.doString('return Vector(1, 2) + 1')).to.eventually.be.rejectedWith( + 'attempt to perform arithmetic on a Vector value', + ) + }) + + it('should read an instance back as itself', async () => { + using state = await getVectorState() + const vector = new Vector(1, 2) + state.set('v', vector) + + expect(state.get('v')).to.be.equal(vector) + expect(await state.doString('return v == v')).to.be.equal(true) + expect(state.get('Vector')).to.be.equal(Vector) + }) + + it('should reach the static members the class declares, and nothing of Function', async () => { + using state = await getVectorState() + + expect(await state.doString('return Vector.zero().x')).to.be.equal(0) + expect(await state.doString('return Vector.unit')).to.be.equal(1) + expect(await state.doString('return Vector.zero == Vector.zero')).to.be.equal(true) + expect(await state.doString('return Vector.prototype == nil and Vector.bind == nil and Vector.call == nil')).to.be.equal(true) + }) + + it('should use the nearest defined class for a subclass, and the override it brings', async () => { + using state = await getVectorState() + state.set('v3', new Vector3(1, 2, 3)) + + expect(await state.doString('return tostring(v3)')).to.match(/^Vector: 0x/) + expect(await state.doString('return v3:describe()')).to.be.equal('a vector of 1, 2, 3') + expect(await state.doString('return v3.z')).to.be.equal(3) + }) + + it('should prefer the most derived class that was defined', async () => { + using state = await getVectorState() + state.defineClass(Vector3) + state.set('v2', new Vector(1, 2)) + state.set('v3', new Vector3(1, 2, 3)) + + expect(await state.doString('return tostring(v2)')).to.match(/^Vector: 0x/) + expect(await state.doString('return tostring(v3)')).to.match(/^Vector3: 0x/) + }) + + it('should take instances wherever they come from, whatever the objects option', async () => { + using state = await getState({ objects: 'copy' }) + state.defineClass(Vector) + state.set('data', { position: new Vector(5, 6), plain: { nested: true } }) + + expect(await state.doString('return type(data)')).to.be.equal('table') + expect(await state.doString('return type(data.plain)')).to.be.equal('table') + expect(await state.doString('return data.position:describe()')).to.be.equal('a vector of 5, 6') + }) + + describe('members', () => { + it('should make only the listed members reachable', async () => { + using state = await getVectorState({ members: ['x', 'add'] }) + + expect(await state.doString('local v = Vector(3, 4) return v:add(v).x')).to.be.equal(6) + expect(await state.doString('local v = Vector(3, 4) return v.y == nil and v.describe == nil and v.length == nil')).to.be.equal( + true, + ) + expect(await state.doString('return Vector(3, 4).constructor == nil')).to.be.equal(true) + }) + + it('should refuse to write anything else', async () => { + using state = await getVectorState({ members: ['x', 'add'] }) + const vector = new Vector(1, 2) + state.set('v', vector) + + await state.doString('v.x = 5') + await expect(state.doString('v.y = 5')).to.eventually.be.rejectedWith("cannot set 'y' on a Vector") + await expect(state.doString('v[1] = 5')).to.eventually.be.rejectedWith("cannot set '1' on a Vector") + + expect(vector).to.be.eql(new Vector(5, 2)) + }) + + it('statics should make only the listed static members reachable', async () => { + using state = await getVectorState({ statics: ['zero'] }) + + expect(await state.doString('return Vector.zero().x')).to.be.equal(0) + expect(await state.doString('return Vector.unit == nil')).to.be.equal(true) + expect(await state.doString('return Vector(1, 2).x')).to.be.equal(1) + }) + }) + + describe('options', () => { + it('name should name the metatable', async () => { + using state = await getVectorState({ name: 'Vec2' }) + + expect(await state.doString('return tostring(Vector(1, 2))')).to.match(/^Vec2: 0x/) + expect(await state.doString('return tostring(Vector)')).to.be.equal('class Vec2') + }) + + it('metamethods should be called with the instance first', async () => { + using state = await getVectorState({ + metamethods: { + __tostring: (vector) => `(${vector.x}, ${vector.y})`, + __add: (a, b) => a.add(b), + __eq: (a, b) => a.x === b.x && a.y === b.y, + __len: () => 2, + }, + }) + + expect(await state.doString('return tostring(Vector(1, 2) + Vector(3, 4))')).to.be.equal('(4, 6)') + expect(await state.doString('return Vector(1, 2) == Vector(1, 2)')).to.be.equal(true) + expect(await state.doString('return #Vector(1, 2)')).to.be.equal(2) + }) + + it('should refuse to replace the metamethods the reference depends on', async () => { + using state = await getState() + + expect(() => state.defineClass(Vector, { metamethods: { __gc: () => undefined } })).to.throw('defineClass cannot replace __gc') + }) + }) + + it('should refuse a class that is already defined, a name that is taken, and what is not a class', async () => { + using state = await getVectorState() + + expect(() => state.defineClass(Vector)).to.throw("the class 'Vector' is already defined") + expect(() => state.defineClass(class Vector {})).to.throw("the name 'Vector' is already taken") + expect(() => state.defineClass(class {})).to.throw('needs a name for an anonymous class') + expect(() => state.defineClass(() => undefined)).to.throw('defineClass expects a class') + expect(() => state.defineClass({})).to.throw('defineClass expects a class') + }) + + it('should index an Array subclass from 1', async () => { + using state = await getState() + class Stack extends Array { + peek() { + return this.at(-1) + } + } + state.defineClass(Stack) + state.set('stack', Stack.from(['a', 'b', 'c'])) + + expect(await state.doString('return stack[1] .. stack:peek()')).to.be.equal('ac') + await state.doString('stack[4] = "d"') + expect(state.get('stack')).to.have.lengthOf(4) + }) + + it('should release an instance once Lua has collected it', async () => { + using state = await getVectorState() + const vector = new Vector(1, 2) + state.set('v', vector) + expect(state.module.getRefIndex(vector)).to.not.be.undefined + + await state.doString('v = nil collectgarbage() collectgarbage()') + + expect(state.module.getRefIndex(vector)).to.be.undefined + }) + + it('should work without the standard libraries', async () => { + using state = await getState({ libs: false, inject: false }) + state.defineClass(Vector) + state.set('Vector', Vector) + + expect(await state.doString('return Vector(3, 4):add(Vector(1, 1)).x')).to.be.equal(4) + }) }) describe('Thread lifecycle', () => { @@ -351,7 +763,7 @@ describe('Thread lifecycle', () => { it('indexToString should call __tostring when there is one', async () => { using state = await getState() - state.set('thing', decorate({}, { metatable: { __tostring: () => 'rendered' } })) + state.set('thing', copy({}, { metatable: { __tostring: () => 'rendered' } })) state.module.lua_getglobal(state.address, 'thing') expect(state.indexToString(-1)).to.be.equal('rendered') diff --git a/test/async.test.js b/test/async.test.js index c2db4f4..aa0a440 100644 --- a/test/async.test.js +++ b/test/async.test.js @@ -304,8 +304,8 @@ describe('state.async', () => { await aborted }) - it('falls back to the function timeout of the state', async () => { - using state = await getState({ limits: { functionTimeout: 10 } }) + it('falls back to the timeout of the state', async () => { + using state = await getState({ limits: { timeout: 10 } }) state.set('never', new Promise(() => {})) const fn = state.doStringSync('return function() never:await() end') await expect(state.async(fn)()).to.eventually.be.rejectedWith(LuaTimeoutError) @@ -437,8 +437,8 @@ describe('async', () => { ) }) - it('runs under the function timeout of the state', async () => { - using state = await getState({ limits: { functionTimeout: 10 } }) + it('runs under the timeout of the state', async () => { + using state = await getState({ limits: { timeout: 10 } }) state.set('never', new Promise(() => {})) await expect(state.doStringSync('return async(function() never:await() end)()')).to.eventually.be.rejectedWith(LuaTimeoutError) }) diff --git a/test/bundling.test.js b/test/bundling.test.js index 4ed5462..610dc2e 100644 --- a/test/bundling.test.js +++ b/test/bundling.test.js @@ -83,13 +83,13 @@ describe('Bundling', () => { `) emitter.emit('resolve') - await expect(resPromise).to.eventually.be.rejectedWith('Error: attempt to yield across a C-call boundary') + await expect(resPromise).to.eventually.be.rejectedWith('attempt to yield across a C-call boundary') expect(await state.doString('return 42')).to.equal(42) }) it('a thread timeout inside a JS callback still surfaces as an error when minified', async () => { - const state = await getMinifiedState({ limits: { functionTimeout: 10 } }) + const state = await getMinifiedState({ limits: { timeout: 10 } }) state.set('promise', Promise.resolve()) const thread = state.newThread() thread.loadString(` diff --git a/test/errors.test.js b/test/errors.test.js index c7aaeb0..712fd18 100644 --- a/test/errors.test.js +++ b/test/errors.test.js @@ -1,4 +1,4 @@ -import { LuaRuntime, LuaError, decorate } from '../dist/index.js' +import { LuaRuntime, LuaError, copy, opaque, proxy } from '../dist/index.js' import { expect } from 'chai' import { getState } from './utils.js' @@ -35,104 +35,119 @@ describe('LuaError', () => { }) }) -describe('errors option', () => { - const setThrow = (state) => +describe('JS errors in Lua', () => { + const setThrow = (state, error = new Error('kaboom')) => state.set('boom', () => { - throw new Error('kaboom') + throw error }) const catchIt = (expression) => `local ok, err = pcall(boom) return ${expression}` - // The "Error: " prefix is the tell: js_error renders the bare message, the proxy layer - // leaves tostring to Error.prototype. - const matrix = [ - ['off by default', undefined, 'Error: kaboom'], - ['on when asked for', { errors: true }, 'kaboom'], - // errors used to sit below proxy, so opting in while leaving objects alone did nothing. - ['on when asked for even though objects is proxy', { objects: 'proxy', errors: true }, 'kaboom'], - ['on by default when objects is copy', { objects: 'copy' }, 'kaboom'], - ] - - for (const [name, options, expected] of matrix) { - it(`should be ${name}`, async () => { + // The bare message is the tell: the proxy layer would leave tostring to Error.prototype, which + // prefixes it with "Error: ". + for (const [name, options] of [ + ['a state that proxies its objects', { objects: 'proxy' }], + ['a state that copies its objects', { objects: 'copy' }], + ]) { + it(`should render as the message in ${name}`, async () => { using state = await getState(options) setThrow(state) - expect(await state.doString(catchIt('tostring(err)'))).to.be.equal(expected) + expect(await state.doString(catchIt('type(err)'))).to.be.equal('userdata') + expect(await state.doString(catchIt('tostring(err)'))).to.be.equal('kaboom') }) } - it('should leave the real properties reachable when off', async () => { + it('should expose the message, name and stack', async () => { using state = await getState() setThrow(state) - expect(await state.doString(catchIt('type(err.stack)'))).to.be.equal('string') - }) - - it('should expose the message when on', async () => { - using state = await getState({ errors: true }) - setThrow(state) - expect(await state.doString(catchIt('err.message'))).to.be.equal('kaboom') + expect(await state.doString(catchIt('err.name'))).to.be.equal('Error') + expect(await state.doString(catchIt('type(err.stack)'))).to.be.equal('string') }) - it('should expose name and stack when on', async () => { - using state = await getState({ errors: true }) - setThrow(state) + it('should expose what the error carries as its own properties', async () => { + using state = await getState() + setThrow(state, Object.assign(new Error('not found', { cause: new Error('root') }), { code: 'ENOENT', errno: -2 })) - expect(await state.doString(catchIt('err.name'))).to.be.equal('Error') - expect(await state.doString(catchIt('type(err.stack)'))).to.be.equal('string') + expect(await state.doString(catchIt('err.code'))).to.be.equal('ENOENT') + expect(await state.doString(catchIt('err.errno'))).to.be.equal(-2) + expect(await state.doString(catchIt('err.cause.message'))).to.be.equal('root') }) - it('should read an unknown field as nil when on', async () => { - using state = await getState({ errors: true }) + it('should read an unknown field as nil, and nothing inherited', async () => { + using state = await getState() setThrow(state) expect(await state.doString(catchIt('type(err.nope)'))).to.be.equal('nil') expect(await state.doString(catchIt('err.nope == nil'))).to.be.equal(true) + expect(await state.doString(catchIt('err.constructor == nil and err.toString == nil'))).to.be.equal(true) }) - it('should be read-only when on', async () => { - using state = await getState({ errors: true }) + it('should be read-only', async () => { + using state = await getState() setThrow(state) await expect(state.doString(catchIt('err.message = "rewritten"'))).to.eventually.be.rejected }) - it('should be overridable to off when objects is copy', async () => { - using state = await getState({ objects: 'copy', errors: false }) - setThrow(state) + it('should come back to JS as the error that was thrown', async () => { + using state = await getState({ objects: 'copy' }) + const thrown = new Error('kaboom') + setThrow(state, thrown) - expect(await state.doString(catchIt('type(err)'))).to.be.equal('table') + expect(await state.doString(catchIt('err'))).to.be.equal(thrown) }) - // Claiming every Error on type alone would swallow these, the way proxy used to swallow it. - describe('should defer to an explicit decoration', () => { + // Claiming every Error on type alone would swallow these. + describe('should defer to an explicit wrapper', () => { const cases = [ - ['userdata', 'userdata', 'js_userdata'], - ['proxy', 'userdata', 'Error: kaboom'], - ['value', 'table', 'table:'], + ['opaque', opaque, 'userdata', 'js_userdata'], + ['proxy', proxy, 'userdata', 'Error: kaboom'], + ['copy', copy, 'table', 'table:'], ] - for (const [as, luaType, rendering] of cases) { - it(`as: '${as}'`, async () => { - using state = await getState({ errors: true }) - state.set('decorated', decorate(new Error('kaboom'), { as })) + for (const [name, wrap, luaType, rendering] of cases) { + it(name, async () => { + using state = await getState() + state.set('wrapped', wrap(new Error('kaboom'))) - expect(await state.doString('return type(decorated)')).to.be.equal(luaType) - expect(await state.doString('return tostring(decorated)')).to.include(rendering) + expect(await state.doString('return type(wrapped)')).to.be.equal(luaType) + expect(await state.doString('return tostring(wrapped)')).to.include(rendering) }) } }) + it('should defer to a class defined for it', async () => { + using state = await getState() + class HttpError extends Error { + constructor(status) { + super(`status ${status}`) + this.status = status + } + isClientError() { + return this.status >= 400 && this.status < 500 + } + } + state.defineClass(HttpError) + const thrown = new HttpError(404) + setThrow(state, thrown) + + expect(await state.doString(catchIt('err:isClientError()'))).to.be.equal(true) + await expect(state.doString('boom()')).to.eventually.be.rejected.then((error) => { + expect(error.luaValue).to.be.equal(thrown) + }) + }) + it('should expose an Error constructor to lua when injecting', async () => { - using state = await getState({ errors: true }) + using state = await getState() expect(await state.doString('return tostring(Error.create("made in lua"))')).to.be.equal('made in lua') expect(await state.doString('return Error.create("made in lua").message')).to.be.equal('made in lua') }) - it('should not expose the Error constructor when the extension is off', async () => { - using state = await getState() + it('should not expose the Error constructor when it is not injected', async () => { + using state = await getState({ inject: ['Promise'] }) expect(await state.doString('return type(Error)')).to.be.equal('nil') }) diff --git a/test/initialization.test.js b/test/initialization.test.js index 3042477..c627c71 100644 --- a/test/initialization.test.js +++ b/test/initialization.test.js @@ -37,6 +37,12 @@ describe('Initialization', () => { expect(await state.doString('return type(null)')).to.be.equal('userdata') }) + it('create state with an unknown objects option should fail', async () => { + const lua = await LuaRuntime.load() + + expect(() => lua.createState({ objects: 'reference' })).to.throw("unknown objects option 'reference'") + }) + it('create with environment variables should succeed', async () => { const env = { ENV_TEST: 'test', @@ -178,8 +184,8 @@ describe('Disposal', () => { resetThread: (state) => state.resetThread(), resume: (state) => state.resume(), runSync: (state) => state.runSync(), - setLimits: (state) => state.setLimits({ maxInstructions: 10 }), - setDeadline: (state) => state.setDeadline(Date.now() + 10), + defineType: (state) => state.defineType({ name: 'late', match: () => false }), + defineClass: (state) => state.defineClass(class Late {}), } for (const [name, use] of Object.entries(syncEntryPoints)) { diff --git a/test/limits.test.js b/test/limits.test.js index fb96248..a16b06d 100644 --- a/test/limits.test.js +++ b/test/limits.test.js @@ -62,16 +62,34 @@ describe('Run limits', () => { expect(await state.doString('return 1 + 1')).to.be.equal(2) }) - it('setLimits on the state reaches both the sync and the async path', async function () { + it('state.limits reaches both the sync and the async path', async function () { this.timeout(20_000) using state = await getState() - state.setLimits({ maxInstructions: 5_000 }) + state.limits = { maxInstructions: 5_000 } await expect(state.doString(busyLoop)).to.eventually.be.rejectedWith(LuaInstructionLimitError) expect(() => state.doStringSync(busyLoop)).to.throw(LuaInstructionLimitError) + + // A field of it changes the same way as the whole. + state.limits.maxInstructions = undefined + state.limits.timeout = 20 + await expect(state.doString(busyLoop)).to.eventually.be.rejectedWith(LuaTimeoutError) + expect(() => state.doStringSync(busyLoop)).to.throw(LuaTimeoutError) + }) + + it('state.limits starts as a copy of the limits the state was created with', async () => { + const limits = { timeout: 1000, maxInstructions: 5_000 } + using state = await getState({ limits }) + + expect(state.limits).to.be.eql(limits) + state.limits.timeout = 5 + expect(limits.timeout).to.be.equal(1000) + + state.limits = undefined + expect(state.limits).to.be.eql({}) }) - it('a parked run keeps its deadline snapshot when the state deadline changes', async () => { + it('a parked run keeps the limits it started under when the ones of the state change', async () => { using state = await getState() let release state.set( @@ -80,9 +98,9 @@ describe('Run limits', () => { release = resolve }), ) - state.setDeadline(Date.now() + 60_000) + state.limits.timeout = 60_000 const pending = state.doString('gate:await() return 42') - state.setDeadline(Date.now() - 1) + state.limits.timeout = 0 release() expect(await pending).to.equal(42) await expect(state.doString('gate:await()')).to.eventually.be.rejectedWith(LuaTimeoutError) @@ -97,28 +115,197 @@ describe('Run limits', () => { } }) - it('limits are restored after a scoped run', async () => { + it('the limits of a run replace the ones of the state field by field', async function () { + this.timeout(20_000) + using state = await getState({ limits: { maxInstructions: 5_000 } }) + + // The budget is replaced, so the loop below fits. No timeout came from either side. + expect(await state.doString('local x = 0 for i = 1, 20000 do x = x + 1 end return x', { maxInstructions: 1_000_000 })).to.be.equal( + 20000, + ) + // The timeout is added, and the budget of the state still applies. + await expect(state.doString(busyLoop, { timeout: 60_000 })).to.eventually.be.rejectedWith(LuaInstructionLimitError) + // Infinity lifts it. + expect(await state.doString('local x = 0 for i = 1, 20000 do x = x + 1 end return x', { maxInstructions: Infinity })).to.be.equal( + 20000, + ) + expect(state.limits).to.be.eql({ maxInstructions: 5_000 }) + }) + + it('a run leaves no hook behind on the thread it used', async () => { using state = await getState() - state.setLimits({ maxInstructions: 999 }) - await state.doString('return 1', { maxInstructions: 10_000 }) + state.doStringSync('return 1', { maxInstructions: 10_000 }) + + expect(state.module.lua_gethook(state.address)).to.be.equal(0) + }) + + describe('every kind of run', () => { + const spin = 'while true do end' + + it('a call of a Lua function is under the limits of the state', async function () { + this.timeout(20_000) + using state = await getState() + const fn = state.doStringSync(`return function() ${spin} end`) + + state.limits = { timeout: 20 } + expect(() => fn()).to.throw(LuaTimeoutError) + + state.limits = { maxInstructions: 5_000 } + expect(() => fn()).to.throw(LuaInstructionLimitError) + + state.limits = { signal: AbortSignal.abort() } + expect(() => fn()).to.throw(LuaAbortError) + }) + + it('a call by name is under the limits of the state', async function () { + this.timeout(20_000) + using state = await getState({ limits: { maxInstructions: 5_000 } }) + state.doStringSync(`function spin() ${spin} end`) + + expect(() => state.call('spin')).to.throw(LuaInstructionLimitError) + }) + + it('a function that timed out does not put the next call beyond the limit', async function () { + this.timeout(20_000) + using state = await getState({ limits: { timeout: 20 } }) + const fn = state.doStringSync(`return function() ${spin} end`) + + // Lua leaves the debug hook disabled on a thread a hook raised an error out of, and + // calls reuse one thread: the second call used to run with no limit at all. + for (let call = 0; call < 3; call++) { + expect(() => fn(), `call ${call}`).to.throw(LuaTimeoutError) + } + expect(state.doStringSync('return 1 + 1')).to.be.equal(2) + }) + + it('a function that caught its interrupt keeps the limit for the next call', async function () { + this.timeout(20_000) + using state = await getState({ limits: { maxInstructions: 5_000 } }) + const caught = state.doStringSync(`return function() return (pcall(function() ${spin} end)) end`) + const fn = state.doStringSync(`return function() ${spin} end`) + + // The pcall swallows the interrupt and the function returns before the hook fires again. + expect(caught()).to.be.equal(false) + expect(() => fn()).to.throw(LuaInstructionLimitError) + expect(() => fn()).to.throw(LuaInstructionLimitError) + }) + }) + + describe('a run made from inside another', () => { + const spin = 'while true do end' + + // The run on the stack is a doString with limits of its own; the function below is what + // Lua hands to JS, which calls it back synchronously on another thread. + const callBack = (state, options, script = `each(function() ${spin} end)`) => { + state.set('each', (fn) => fn()) + return state.doString(script, options) + } + + it('cannot outlast the timeout of the outer one', async function () { + this.timeout(20_000) + using state = await getState() + + await expect(callBack(state, { timeout: 20 })).to.eventually.be.rejectedWith(LuaTimeoutError) + }) + + it('spends from the instruction budget of the outer one', async function () { + this.timeout(20_000) + using state = await getState() + + await expect(callBack(state, { maxInstructions: 5_000 })).to.eventually.be.rejectedWith(LuaInstructionLimitError) + }) + + it('is aborted by the signal of the outer one', async function () { + this.timeout(20_000) + using state = await getState() + + await expect(callBack(state, { signal: AbortSignal.abort() })).to.eventually.be.rejectedWith(LuaAbortError) + }) + + it('counts what it executed against the outer one', async function () { + this.timeout(20_000) + // Each call back stays inside the budget on its own, and together they do not. + using state = await getState() + const run = callBack( + state, + { maxInstructions: 20_000 }, + 'for _ = 1, 100 do each(function() local x = 0 for i = 1, 2000 do x = x + 1 end end) end', + ) + + await expect(run).to.eventually.be.rejectedWith(LuaInstructionLimitError) + }) + + it('is interrupted where the JS function that made it can see', async function () { + this.timeout(20_000) + using state = await getState() + let seen + state.set('each', (fn) => { + try { + fn() + } catch (error) { + seen = error + throw error + } + }) + + await expect(state.doString(`each(function() ${spin} end)`, { timeout: 20 })).to.eventually.be.rejectedWith(LuaTimeoutError) + expect(seen).to.be.an.instanceOf(LuaTimeoutError) + }) + + it('still has the limits of the state when the outer one has none', async function () { + this.timeout(20_000) + using state = await getState({ limits: { maxInstructions: 5_000 } }) + state.set('each', (fn) => fn()) + + await expect(state.doString(`each(function() ${spin} end)`, { maxInstructions: Infinity })).to.eventually.be.rejectedWith( + LuaInstructionLimitError, + ) + }) + + it('through doStringSync on the same thread stays inside the outer one too', async function () { + this.timeout(20_000) + using state = await getState() + state.set('nested', () => state.doStringSync(spin)) + + expect(() => state.doStringSync('nested()', { timeout: 20 })).to.throw(LuaTimeoutError) + expect(() => state.doStringSync('nested()', { maxInstructions: 5_000 })).to.throw(LuaInstructionLimitError) + expect(state.module.lua_gethook(state.address)).to.be.equal(0) + }) + + it('an asynchronous run started from inside another is on its own', async function () { + this.timeout(20_000) + using state = await getState() + state.set('sleep', (ms) => new Promise((resolve) => setTimeout(resolve, ms))) + + // The outer run returns the promise without waiting, well inside its 20ms; the run it + // started goes on for longer than that and is not cut short by it. + const started = await state.doString('return async(function() sleep(60):await() return "finished" end)()', { timeout: 20 }) + + expect(started).to.be.equal('finished') + }) + }) + + it('a thread that a limit interrupted cannot be reset', async function () { + this.timeout(20_000) + using state = await getState() + const thread = state.newThread() + thread.loadString(busyLoop) + await expect(thread.run(0, { timeout: 20 })).to.eventually.be.rejectedWith(LuaTimeoutError) - expect(state.getLimits().maxInstructions).to.be.equal(999) + // Lua leaves the hook of such a thread disabled, so a limit on its next run would be ignored. + expect(() => thread.resetThread()).to.throw('a thread that a limit interrupted cannot be reset') }) - // An interrupt used to be pushed into Lua as a JS error and recognised on the way back out by - // its identity, which only survived in a state whose extensions marshal an Error by reference. - // `objects: 'copy'` with `errors: false` -- a sandbox that keeps JS errors away from Lua, and so - // exactly the state most likely to set a limit in the first place -- turned every interrupt into - // an opaque `LuaError: table: 0x...`. + // An interrupt is raised as a token rather than as a JS error pushed into Lua, so that reporting + // it does not depend on how the state marshals anything. describe('state configurations', () => { const configs = [ ['the default proxy state', {}], ['objects: copy', { objects: 'copy' }], - ['objects: copy with errors off', { objects: 'copy', errors: false }], ['no injected globals', { inject: false }], ['no standard libraries', { libs: false }], - ['no libraries and nothing to marshal errors', { libs: false, objects: 'copy', errors: false, inject: false }], + ['no libraries and nothing injected', { libs: false, objects: 'copy', inject: false }], ] for (const [description, config] of configs) { @@ -136,7 +323,7 @@ describe('Run limits', () => { it('an interrupt the script caught does not stand in for the error that followed', async function () { this.timeout(20_000) - using state = await getState({ objects: 'copy', errors: false }) + using state = await getState({ objects: 'copy' }) // The budget is spent inside the pcall, so the interrupt is raised and swallowed there. The // hook re-raises within another hookCount instructions, which is room enough for the error @@ -169,7 +356,7 @@ describe('Run limits', () => { it('an interrupt token the script kept does not turn a later run into a limit error', async function () { this.timeout(20_000) - using state = await getState({ objects: 'copy', errors: false }) + using state = await getState({ objects: 'copy' }) state.doStringSync(`local ok, token = pcall(function () ${busyLoop} end) saved = token`, { maxInstructions: 5_000 }) diff --git a/test/promises.test.js b/test/promises.test.js index c5c7979..75907da 100644 --- a/test/promises.test.js +++ b/test/promises.test.js @@ -201,7 +201,7 @@ describe('Promises', () => { asyncThread.loadString(` local succeed, err = pcall(function() throw():await() end) - assert(tostring(err) == "Error: expected test error") + assert(tostring(err) == "expected test error") return succeed `) diff --git a/test/state.test.js b/test/state.test.js index 4b7cdb7..4cb6a36 100644 --- a/test/state.test.js +++ b/test/state.test.js @@ -1,5 +1,5 @@ import { EventEmitter } from 'events' -import { LuaReturn, LuaThread, LuaType, decorate } from '../dist/index.js' +import { LuaReturn, LuaThread, LuaType, copy, opaque, proxy } from '../dist/index.js' import { expect } from 'chai' import { getState, getLua } from './utils.js' import { setTimeout } from 'node:timers/promises' @@ -403,7 +403,7 @@ describe('State', () => { await state.doString(` local success, err = pcall(throw) assert(success == false) - assert(tostring(err) == "Error: expected error") + assert(tostring(err) == "expected error") check() `) @@ -641,9 +641,9 @@ describe('State', () => { using state = await getState() state.set('TestClass', { create: (name) => { - return decorate( + return copy( { - instance: decorate(new TestClass(name), { as: 'userdata' }), + instance: opaque(new TestClass(name)), }, { metatable: { @@ -679,26 +679,48 @@ describe('State', () => { expect(res).to.be.equal('demo name 2') }) - it('calling a class from lua constructs it', async () => { + it('a function is a function, whatever it looks like', async () => { using state = await getState() + function Legacy(name) { + this.name = name + } + Legacy.prototype.getName = function () { + return this.name + } state.set('TestClass', TestClass) + state.set('Legacy', Legacy) + + expect(await state.doString('return type(TestClass) .. "," .. type(Legacy)')).to.be.equal('function,function') + // A plain call stays a plain call, with the error JS gives for it. + await expect(state.doString('return TestClass("name")')).to.eventually.be.rejectedWith( + "Class constructor TestClass cannot be invoked without 'new'", + ) + await expect(state.doString('return Legacy("legacy name")')).to.eventually.be.rejectedWith('Cannot set properties of undefined') + await expect(state.doString('return TestClass.hello()')).to.eventually.be.rejectedWith('attempt to index a function value') + }) + + it('a proxied class is indexable, and constructs through new', async () => { + using state = await getState() + state.set('TestClass', proxy(TestClass)) const res = await state.doString(` - local instance = TestClass("demo name 3") + local instance = TestClass.new("demo name 3") return instance:getName() .. " " .. TestClass.hello() `) expect(res).to.be.equal('demo name 3 world') + expect(await state.doString('return TestClass.new == TestClass.new')).to.be.equal(true) + expect(state.get('TestClass')).to.be.equal(TestClass) }) - it('calling a class with no methods still constructs it', async () => { + it('a proxied class with no methods still constructs', async () => { using state = await getState() class Empty {} - state.set('Empty', Empty) + state.set('Empty', proxy(Empty)) - expect(await state.doString('return Empty()')).to.be.an.instanceOf(Empty) + expect(await state.doString('return Empty.new()')).to.be.an.instanceOf(Empty) }) - it('a function-style class is indexable but called, not constructed', async () => { + it('a proxied function-style class is indexable, constructs through new, and is otherwise called', async () => { using state = await getState() function Legacy(name) { this.name = name @@ -707,24 +729,35 @@ describe('State', () => { return this.name } Legacy.create = (name) => new Legacy(name) - state.set('Legacy', Legacy) + state.set('Legacy', proxy(Legacy)) // Statics are reachable through the proxy. expect(await state.doString('return Legacy.create("legacy name"):getName()')).to.be.equal('legacy name') + expect(await state.doString('return Legacy.new("made new"):getName()')).to.be.equal('made new') // A plain call stays a plain call: strict-mode `this` is undefined, as it would be in JS. await expect(state.doString('return Legacy("legacy name")')).to.eventually.be.rejectedWith('Cannot set properties of undefined') }) - it('calling Date constructs a date', async () => { + it('a member named new is the member, not the constructor', async () => { using state = await getState() - state.set('Date', Date) + const factory = () => 'called' + factory.new = () => 'its own new' + state.set('factory', proxy(factory)) - expect(await state.doString('return Date()')).to.be.an.instanceOf(Date) - expect(await state.doString('return Date(0):getTime()')).to.be.equal(0) + expect(await state.doString('return factory.new()')).to.be.equal('its own new') + }) + + it('a proxied Date constructs through new and is a function when called', async () => { + using state = await getState() + state.set('Date', proxy(Date)) + + expect(await state.doString('return Date.new()')).to.be.an.instanceOf(Date) + expect(await state.doString('return Date.new(0):getTime()')).to.be.equal(0) expect(await state.doString('return Date.UTC(2020, 0, 1)')).to.be.equal(1577836800000) + expect(await state.doString('return Date()')).to.be.a('string') }) - it('builtins that must not be constructed are still called', async () => { + it('builtins that must not be constructed are called', async () => { using state = await getState() state.set('String', String) state.set('BigInt', BigInt) @@ -734,9 +767,9 @@ describe('State', () => { expect(await state.doString('return BigInt(5)')).to.be.equal(5) }) - it('a builtin function-style class is indexable and constructible', async () => { + it('a proxied builtin function-style class is indexable and constructible', async () => { using state = await getState() - state.set('Buffer', Buffer) + state.set('Buffer', proxy(Buffer)) expect(await state.doString('return Buffer.from("abc"):toString("hex")')).to.be.equal('616263') expect(await state.doString('return Buffer.alloc(2).length')).to.be.equal(2) @@ -749,7 +782,7 @@ describe('State', () => { } state.set('add', add) state.set('addArrow', (a, b) => a + b) - state.set('addProxied', decorate(add, { as: 'proxy' })) + state.set('addProxied', proxy(add)) expect(await state.doString('return add(1, 2)')).to.be.equal(3) expect(await state.doString('return addArrow(1, 2)')).to.be.equal(3) @@ -785,15 +818,33 @@ describe('State', () => { expect(res).to.be.equal('wrapped: demo') }) - it('classes should be a userdata when proxied', async () => { + it('a defined class found on a proxied object is that class', async () => { using state = await getState() + state.defineClass(TestClass) state.set('obj', { TestClass }) - const testClass = await state.doString(` - return obj.TestClass - `) + expect(await state.doString('return obj.TestClass')).to.be.equal(TestClass) + expect(await state.doString('return obj.TestClass("nested"):getName()')).to.be.equal('nested') + }) + + it('a proxied class found on a proxied object is that class', async () => { + using state = await getState() + state.set('obj', { TestClass: proxy(TestClass) }) - expect(testClass).to.be.equal(TestClass) + expect(await state.doString('return obj.TestClass')).to.be.equal(TestClass) + expect(await state.doString('return obj.TestClass.new("nested"):getName()')).to.be.equal('nested') + }) + + it('a number indexes an array from 1 and any other object by the property it names', async () => { + using state = await getState() + state.set('arr', ['a', 'b']) + state.set('obj', { 0: 'zero', 1: 'one' }) + + expect(await state.doString('return arr[1] .. arr[2]')).to.be.equal('ab') + expect(await state.doString('return obj[0] .. obj[1]')).to.be.equal('zeroone') + await state.doString('arr[3] = "c" obj[2] = "two"') + expect(state.get('arr')).to.be.eql(['a', 'b', 'c']) + expect(state.get('obj')[2]).to.be.equal('two') }) it('timeout blocking lua program', async () => { @@ -806,29 +857,23 @@ describe('State', () => { await expect(state.run(0, { timeout: 5 })).eventually.to.be.rejectedWith('thread timeout exceeded') }) - it('the most recently set timeout should be the one that applies', async function () { + it('the timeout of a run should replace the one of the state', async function () { this.timeout(30_000) - using state = await getState() + using state = await getState({ limits: { timeout: 20 } }) const thread = state.newThread() - - thread.setDeadline(Date.now() + 20) - thread.setDeadline(Date.now() + 20_000) thread.loadString('local x = 0 for i = 1, 20000000 do x = x + 1 end return x') - expect((await thread.run(0))[0]).to.be.equal(20000000) + expect((await thread.run(0, { timeout: 20_000 }))[0]).to.be.equal(20000000) }) - it('clearing a timeout should disable the hook', async function () { + it('a timeout of Infinity should lift the one of the state', async function () { this.timeout(30_000) - using state = await getState() + using state = await getState({ limits: { timeout: 10 } }) const thread = state.newThread() - - thread.setDeadline(Date.now() + 10) - thread.setDeadline(undefined) thread.loadString('local x = 0 for i = 1, 5000000 do x = x + 1 end return 7') - expect(thread.getDeadline()).to.be.undefined - expect((await thread.run(0))[0]).to.be.equal(7) + expect((await thread.run(0, { timeout: Infinity }))[0]).to.be.equal(7) + expect(state.module.lua_gethook(thread.address)).to.be.equal(0) }) it('overwrite lib function', async () => { @@ -852,7 +897,7 @@ describe('State', () => { it('inject a userdata with a metatable should succeed', async () => { using state = await getState() - const obj = decorate( + const obj = copy( {}, { metatable: { __index: (_, k) => `Hello ${k}!` }, @@ -897,6 +942,7 @@ describe('State', () => { it('static methods should be callable on classes', async () => { using state = await getState() + state.defineClass(TestClass) state.set('TestClass', TestClass) const testHello = await state.doString(`return TestClass.hello()`) @@ -908,7 +954,7 @@ describe('State', () => { using state = await getState() const testFunction = () => undefined testFunction.hello = 'world' - state.set('TestFunction', decorate(testFunction, { as: 'proxy' })) + state.set('TestFunction', proxy(testFunction)) const testHello = await state.doString(`return TestFunction.hello`) @@ -1210,13 +1256,13 @@ describe('State', () => { `) testEmitter.emit('resolve') - await expect(resPromise).to.eventually.be.rejectedWith('Error: attempt to yield across a C-call boundary') + await expect(resPromise).to.eventually.be.rejectedWith('attempt to yield across a C-call boundary') expect(await state.doString(`return 42`)).to.equal(42) }) it('forced yield within JS callback from Lua doesnt cause vm to crash', async () => { - using state = await getState({ limits: { functionTimeout: 10 } }) + using state = await getState({ limits: { timeout: 10 } }) state.set('promise', Promise.resolve()) const thread = state.newThread() thread.loadString(` @@ -1397,7 +1443,7 @@ describe('Load mode', () => { }) }) -describe('Decoration', () => { +describe('Marshalling', () => { class Thing { constructor(name) { this.name = name @@ -1407,30 +1453,35 @@ describe('Decoration', () => { } } - it('as userdata hides the members', async () => { + it('opaque hides the members and reads back as the same value', async () => { using state = await getState() - state.set('thing', decorate(new Thing('bob'), { as: 'userdata' })) + const thing = new Thing('bob') + state.set('thing', opaque(thing)) // An opaque userdata has no __index of its own, so Lua refuses to index it at all. await expect(state.doString('return thing.name')).to.eventually.be.rejectedWith('attempt to index a js_userdata value') + expect(await state.doString('return thing')).to.be.equal(thing) }) - it('as userdata still cannot take a metatable of its own', async () => { + it('a metatable can only go on a value copied into a table', async () => { using state = await getState() - // The userdata extension owns the metatable slot. That is a constraint of the extension, - // not of the decoration API, so a custom metatable has to go on a wrapper. - expect(() => state.set('thing', decorate(new Thing('bob'), { as: 'userdata', metatable: { __name: 'js_thing' } }))).to.throw( - 'data already has associated metatable: js_userdata', - ) + // Lua has one metatable for every function, so setting it through one would change them all. + expect(() => + state.set( + 'fn', + copy(() => undefined, { metatable: { __name: 'js_fn' } }), + ), + ).to.throw('only a value copied into a Lua table can be given a metatable') + expect(await state.doString('return getmetatable(print) == nil')).to.be.equal(true) }) - it('a wrapper carries the metatable around an opaque userdata', async () => { + it('a copied wrapper carries the metatable around an opaque userdata', async () => { using state = await getState() state.set( 'thing', - decorate( - { inner: decorate(new Thing('bob'), { as: 'userdata' }) }, + copy( + { inner: opaque(new Thing('bob')) }, { metatable: { __name: 'js_thing', __index: (self, key) => (key === 'name' ? self.inner.getName() : null) } }, ), ) @@ -1438,21 +1489,85 @@ describe('Decoration', () => { expect(await state.doString('return thing.name')).to.be.equal('bob') }) - it('as value copies an object instead of proxying it', async () => { + it('copy copies an object instead of proxying it, and everything inside it', async () => { using state = await getState() - state.set('plain', decorate({ a: 1 }, { as: 'value' })) + state.set('plain', copy({ a: 1, list: [{ deep: true }], thing: new Thing('bob') })) expect(await state.doString('return type(plain)')).to.be.equal('table') + expect(await state.doString('return type(plain.list) .. "," .. type(plain.list[1])')).to.be.equal('table,table') + expect(await state.doString('return plain.list[1].deep')).to.be.equal(true) + // An instance is copied like any object: its own fields, and nothing of its prototype. + expect(await state.doString('return type(plain.thing) .. "," .. plain.thing.name .. "," .. type(plain.thing.getName)')).to.be.equal( + 'table,bob,nil', + ) + }) + + it('copy leaves what has a representation of its own, and what is wrapped to cross another way', async () => { + using state = await getState() + const thing = new Thing('bob') + state.set( + 'plain', + copy({ + fn: () => 'called', + promise: Promise.resolve(1), + error: new Error('kept'), + proxied: proxy(thing), + hidden: opaque(thing), + }), + ) + + expect(await state.doString('return plain.fn()')).to.be.equal('called') + expect(await state.doString('return plain.promise:await()')).to.be.equal(1) + expect(await state.doString('return tostring(plain.error)')).to.be.equal('kept') + expect(await state.doString('return plain.proxied:getName()')).to.be.equal('bob') + expect(await state.doString('return plain.hidden')).to.be.equal(thing) }) - it('as proxy forces a function through the proxy layer', async () => { + it('copy keeps cycles and shared references', async () => { + using state = await getState() + const shared = { n: 1 } + const root = { a: shared, b: shared } + root.self = root + state.set('root', copy(root)) + + expect(await state.doString('return root.self == root and root.a == root.b')).to.be.equal(true) + }) + + it('proxy forces a function through the proxy layer', async () => { using state = await getState() const fn = () => undefined fn.hello = 'world' - state.set('fn', decorate(fn, { as: 'proxy' })) + state.set('fn', proxy(fn)) expect(await state.doString('return fn.hello')).to.be.equal('world') }) + + it('proxy keeps an object by reference in a state that copies', async () => { + using state = await getState({ objects: 'copy' }) + const thing = new Thing('bob') + state.set('copied', thing) + state.set('proxied', proxy(thing)) + + expect(await state.doString('return type(copied) .. "," .. type(proxied)')).to.be.equal('table,userdata') + await state.doString('proxied.name = "alice"') + expect(thing.name).to.be.equal('alice') + }) + + it('the last wrapper is the one that counts', async () => { + using state = await getState() + state.set('thing', copy(opaque({ a: 1 }))) + + expect(await state.doString('return thing.a')).to.be.equal(1) + }) + + it('a wrapped primitive is the primitive', async () => { + using state = await getState() + state.set('n', copy(5)) + state.set('s', opaque('text')) + + expect(await state.doString('return n + 1')).to.be.equal(6) + expect(await state.doString('return s')).to.be.equal('text') + }) }) describe('Memory', () => { @@ -1498,6 +1613,6 @@ describe('Synchronous runs', () => { state.doStringSync('return 1', { timeout: 1000 }) - expect(state.getDeadline()).to.be.undefined + expect(state.module.lua_gethook(state.address)).to.be.equal(0) }) }) From dbde796d90ee6d68278f06217e9354e1b915281f Mon Sep 17 00:00:00 2001 From: ceifa Date: Thu, 19 Nov 2026 22:20:15 -0300 Subject: [PATCH 77/83] update the npm dependencies chai 6.3.0, mocha 12.0.3, oxfmt 0.79.0, oxlint 1.94.0, playwright 1.65.1, rolldown 1.3.3, tslib 2.9.1 and @types/node 26.6.6 in the lockfile, plus npm audit fix for the transitive brace-expansion and serialize-javascript. --- package-lock.json | 755 +++++++++++++++++++++++----------------------- package.json | 14 +- 2 files changed, 385 insertions(+), 384 deletions(-) diff --git a/package-lock.json b/package-lock.json index 9416a0d..18a406e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,39 +12,95 @@ "@types/emscripten": "1.41.6" }, "bin": { - "wasmoon": "bin/wasmoon" + "wasmoon": "dist/cli.js" }, "devDependencies": { "@types/node": "*", - "chai": "6.2.2", + "chai": "6.3.0", "chai-as-promised": "8.0.2", "fengari": "0.1.5", - "mocha": "12.0.0", - "oxfmt": "0.66.0", - "oxlint": "1.81.0", - "playwright": "1.62.1", - "rolldown": "1.2.6", - "tslib": "2.8.1", + "mocha": "12.0.3", + "oxfmt": "0.79.0", + "oxlint": "1.94.0", + "playwright": "1.65.1", + "rolldown": "1.3.3", + "tslib": "2.9.1", "typescript": "7.0.2" }, "engines": { - "node": ">=24" + "node": ">=26" + } + }, + "node_modules/@emnapi/core": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.2.tgz", + "integrity": "sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "2.2.0", + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/runtime": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-beta.2.tgz", + "integrity": "sha512-JcrSPzPvZuNZvJqPTF9Fw25LbOJ8avzFVlaf2grmH4Cku0oGP47tRgqPZadcfj3YoZMHkFVnCYFbQM8I+i5QEw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/wasi-threads": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.2.0.tgz", + "integrity": "sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@napi-rs/wasm-runtime": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.6.tgz", + "integrity": "sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.3" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1 || 2.0.0-beta.2", + "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2" } }, "node_modules/@oxc-project/types": { - "version": "0.147.0", - "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.147.0.tgz", - "integrity": "sha512-IJ3s6ltHLp45S0bh7phkX+gJO7A1Wuz2EaqpAhb8WjqDwbzMiWKHhyyT42tskaWjEYXtHtVCPpnBJVT9+dcRLg==", + "version": "0.159.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.159.0.tgz", + "integrity": "sha512-QWjWhxheluOJ82kDHNyps00UvRpQCtI34B5A/SzpgQycUD/79FuvT4I0aQIfE/bdPwKmX4QPftnywFBH6FxJhQ==", "dev": true, "license": "MIT", "funding": { - "url": "https://github.com/sponsors/Boshen" + "url": "https://github.com/sponsors/oxc-project" } }, "node_modules/@oxfmt/binding-android-arm-eabi": { - "version": "0.66.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm-eabi/-/binding-android-arm-eabi-0.66.0.tgz", - "integrity": "sha512-2Me9eoptv6ERdEuI2P8AOlYdHHraXebJaM6SC0kc2Dfb+mLrep2db+fedBPKaYn673h/vBgvP4tkOdAbaudX6w==", + "version": "0.79.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm-eabi/-/binding-android-arm-eabi-0.79.0.tgz", + "integrity": "sha512-xOCQ/rvokUXs8SxOQY5Wy2ukPaZJZ0PmdJovN0ryB1c8DVEtbcvliLdYtINUYh8QOTpmBOctIisSJk9tvh+J6w==", "cpu": [ "arm" ], @@ -59,9 +115,9 @@ } }, "node_modules/@oxfmt/binding-android-arm64": { - "version": "0.66.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm64/-/binding-android-arm64-0.66.0.tgz", - "integrity": "sha512-u7O+bSSF0HGsDKkQQxBqvLGVepu93RA+JKu+ONqvfh4sCnCEbj31wZj4iG5gk3XfRwrmYj0/8catkO2LcblQKQ==", + "version": "0.79.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm64/-/binding-android-arm64-0.79.0.tgz", + "integrity": "sha512-WMLDvCjjchUYtI6zXKOdzTDGm72BaYZiz1/VhB1rrxdakUZRlJh1aMr3CT6ui51uHcWVBycULIXSZHpw6u2pTQ==", "cpu": [ "arm64" ], @@ -76,9 +132,9 @@ } }, "node_modules/@oxfmt/binding-darwin-arm64": { - "version": "0.66.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-arm64/-/binding-darwin-arm64-0.66.0.tgz", - "integrity": "sha512-/ikyMIVjX/sdo7KtjxoEsSUosfPzveVhT9RWMx9yGqFDKFJ89JAEKuEeLBmurDjrkb4w8tOnAdSO3SBaplY3bw==", + "version": "0.79.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-arm64/-/binding-darwin-arm64-0.79.0.tgz", + "integrity": "sha512-+LzSN7w7tULz96ntS1Uqe5oI00XZ0o/m/t3+eSfiQp3aTPnj2eGUafqEWryMLk84j7x9NiF+GEP2YT4/BfClgA==", "cpu": [ "arm64" ], @@ -93,9 +149,9 @@ } }, "node_modules/@oxfmt/binding-darwin-x64": { - "version": "0.66.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-x64/-/binding-darwin-x64-0.66.0.tgz", - "integrity": "sha512-q5xUsKeFqawa9NXa6ZGXWimFV19m8MogKPdTaSVDAAk2EQKBmBZRDeluwcl1p8ty/OFc9s9888OKEh3xfPVH0g==", + "version": "0.79.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-x64/-/binding-darwin-x64-0.79.0.tgz", + "integrity": "sha512-KFiMRhKeiiooaS1dKc4r8AZgOrfOhwVe1yf/aRef+8BajJwtVjMtlsQl/BNRxtkFbq13GjEo/4Q+9YhFGU4o6g==", "cpu": [ "x64" ], @@ -110,9 +166,9 @@ } }, "node_modules/@oxfmt/binding-freebsd-x64": { - "version": "0.66.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-freebsd-x64/-/binding-freebsd-x64-0.66.0.tgz", - "integrity": "sha512-CR+x4VzMY0pRXLK/xFQ/RzsSFkP5t2Z2mef0QY6OP/rTRcMUoMLCOM62/3Fp/t0K+UDoBKxvMyeb6D0zPMjleA==", + "version": "0.79.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-freebsd-x64/-/binding-freebsd-x64-0.79.0.tgz", + "integrity": "sha512-lHVIp0g8ZOFKiqVscvttp+3HJkkRH6XkGgfAA0lVexIlE1mMFVp4V7RBdxz/P9p7T8pSNsYdapFWvdT21Mib9w==", "cpu": [ "x64" ], @@ -127,9 +183,9 @@ } }, "node_modules/@oxfmt/binding-linux-arm-gnueabihf": { - "version": "0.66.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-0.66.0.tgz", - "integrity": "sha512-ZEYmO/LbH9tTQCADILHGZE4GeOXOAj2VzedHkASNwjmwlwtutJCLpCJbIs37wRGTFgWRoEcD72jpMX+IBJUGjQ==", + "version": "0.79.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-0.79.0.tgz", + "integrity": "sha512-Pt35GoxiMUfnr+23cuzk07XQVvISDFxxPcp/aFVB87+RQvJoQaBo/XN7Re9XxgElvbELdyxTLnV9XM2aTfJeUA==", "cpu": [ "arm" ], @@ -144,9 +200,9 @@ } }, "node_modules/@oxfmt/binding-linux-arm-musleabihf": { - "version": "0.66.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-0.66.0.tgz", - "integrity": "sha512-hNtR9/oU0CeTkq7JnRkmBQwqe17v2ZaAMLC4VcN7IIOWeRyWDk0knSPWS9iiLmtbZ2RRBBtsG01jQgkZmKCJeQ==", + "version": "0.79.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-0.79.0.tgz", + "integrity": "sha512-zPi9Dni58VKp3r1QUcFvnbJNfBr49qyecq0vlM4SaX/MSjmguq77VngirghDua5tyhIDfqdUMTCK2KRlnZFp/g==", "cpu": [ "arm" ], @@ -161,9 +217,9 @@ } }, "node_modules/@oxfmt/binding-linux-arm64-gnu": { - "version": "0.66.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-0.66.0.tgz", - "integrity": "sha512-uwOVQ8i6I1LT/+eDzfsgrrcZp8Fn6NPVUPn8fF5gdFGekFf0PddF+LEuwsD0/pbNUcKZhDj2rQ5UpITh9gF4iQ==", + "version": "0.79.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-0.79.0.tgz", + "integrity": "sha512-XhRehATEWjwX7VVEgDUD+7pfHYncQIJaEU0qsHvEKtu9XX0QYzcKvXhU9+URfiGX9WRh3wy2Ow+YCc3EeHtImg==", "cpu": [ "arm64" ], @@ -181,9 +237,9 @@ } }, "node_modules/@oxfmt/binding-linux-arm64-musl": { - "version": "0.66.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-musl/-/binding-linux-arm64-musl-0.66.0.tgz", - "integrity": "sha512-tTkF2Dmx4nGAjmBlZb+UtTGqR/EK4ZrW9qBfzte07a9XWqzoGGKzpFFlyNDhQe+Uwql94+ReCTeNbhOXscw1Dg==", + "version": "0.79.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-musl/-/binding-linux-arm64-musl-0.79.0.tgz", + "integrity": "sha512-gbVjFZYug0MEyqvuTAzXGNxFJmBqBO32o1Fud1lG8bGs6oVz48ZtNQyEcAzqrOwaaG+Sxtv4gVzcsfht9aqmkg==", "cpu": [ "arm64" ], @@ -201,9 +257,9 @@ } }, "node_modules/@oxfmt/binding-linux-ppc64-gnu": { - "version": "0.66.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-0.66.0.tgz", - "integrity": "sha512-F3cKHUav4yXOHn6GFnwpBhSYsJOYKKf9eqO/9jlEuqPxNw9zb98E9ZFct79gcg8pibUGkbveEu9WDlmXJpDzKw==", + "version": "0.79.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-0.79.0.tgz", + "integrity": "sha512-0N0sD3vnllyuiNh1r6zKvNXWE/CakcPKJAespg7XE2+sfvxpz5Q1iFah8sF5aedsOmVvbZaOPZcSHVmMosT1fA==", "cpu": [ "ppc64" ], @@ -221,9 +277,9 @@ } }, "node_modules/@oxfmt/binding-linux-riscv64-gnu": { - "version": "0.66.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-0.66.0.tgz", - "integrity": "sha512-K5fDaNZfDyQMYA/3qL21bqyN0X9T15LLwwbFPt2aHc94+ZG7bh0vZEsy2y7NlRnjjHFSwN+Hzg6ldJtbOriH4Q==", + "version": "0.79.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-0.79.0.tgz", + "integrity": "sha512-YtjqUHolcX6cv0ZMZuKQCM4H0ae/okcowy0wGcPHJk4O+8zjy3TvNhzDQ1/KGCkMJO8Fwulm1JcPJsraVJ3p+w==", "cpu": [ "riscv64" ], @@ -241,9 +297,9 @@ } }, "node_modules/@oxfmt/binding-linux-riscv64-musl": { - "version": "0.66.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-0.66.0.tgz", - "integrity": "sha512-44Yc+I+qOmTElRcEhm5hUKIUJEQIOugymz4ua4tB0Wox7tGAfIbjzmXz/HDAtw1Ij6gmBwZlzh4hc9679RhWeA==", + "version": "0.79.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-0.79.0.tgz", + "integrity": "sha512-H2gb9bEBr5tcdP5FU8JYTfgOavXDorWcAAlwci/zEKF2jzgh/oEr/SAw6aHB9n3FLEvnKvOh0A1fjku+vgYoUA==", "cpu": [ "riscv64" ], @@ -261,9 +317,9 @@ } }, "node_modules/@oxfmt/binding-linux-s390x-gnu": { - "version": "0.66.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-0.66.0.tgz", - "integrity": "sha512-1e29Eg9hEj2kRBB19M0seIehPbbXHCk35GvImjDvb79rjjYjXCRmtbUNHJcgoktZAMIzXrTbxDBKmTc1V4bg3A==", + "version": "0.79.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-0.79.0.tgz", + "integrity": "sha512-aZUbyWW5dSOxT/u6suWc4S9GVDt7YPPNMKQon+z79M8dpXmosadcFHAb7jBhpU7Hdsd2GN6/y3nd0JFTsGddZw==", "cpu": [ "s390x" ], @@ -281,9 +337,9 @@ } }, "node_modules/@oxfmt/binding-linux-x64-gnu": { - "version": "0.66.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-gnu/-/binding-linux-x64-gnu-0.66.0.tgz", - "integrity": "sha512-vODY1UQo10gngn0+D4xHKU84F1Twm1LqrzV4SqPXvmQKSd87paehvZ6jqA5wKs6XQrlWul9clYMDVHcoW9CPMA==", + "version": "0.79.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-gnu/-/binding-linux-x64-gnu-0.79.0.tgz", + "integrity": "sha512-5pW/ZHYfjjQ71gQR+EKzDz8ZzWIDHlTUtWtxVFNgZbKxVZnRxiSXVrllbjpJtx1q8VtSPZ+Lyg9BLny3yw+PTA==", "cpu": [ "x64" ], @@ -301,9 +357,9 @@ } }, "node_modules/@oxfmt/binding-linux-x64-musl": { - "version": "0.66.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-musl/-/binding-linux-x64-musl-0.66.0.tgz", - "integrity": "sha512-YDzXx2JsT4+HL4MdkVrYjO55NS5lUKNm8rLC4ZPou8+seu0v0jhecSh+ufoO6+xEa8gccEezMlI2WHJi4ApUgw==", + "version": "0.79.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-musl/-/binding-linux-x64-musl-0.79.0.tgz", + "integrity": "sha512-3IVUerTDB7Dvd90c1EurAzlVnlE9Azl7Wn8e33qX3wL/IqnslF+P7HvwkD+VeMbHxRtuw0EEBGSArZFXpUAZrQ==", "cpu": [ "x64" ], @@ -321,9 +377,9 @@ } }, "node_modules/@oxfmt/binding-openharmony-arm64": { - "version": "0.66.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-openharmony-arm64/-/binding-openharmony-arm64-0.66.0.tgz", - "integrity": "sha512-mJjUYd8lj0+j4JkYyEM+5qKBf1Rnrpgjn/SVYKJhicVDqLz566ooa7Fs8zflPqt+dnZDV7X054rVIQX6ZcQNlQ==", + "version": "0.79.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-openharmony-arm64/-/binding-openharmony-arm64-0.79.0.tgz", + "integrity": "sha512-C5QDgJBtu9+/2BQScoP7ynv54PLOqfoSqhRWwI0D0RPOwYD4tYj0TUdJbXMO1fNegL/5zJiSOxkq6II2xvttWg==", "cpu": [ "arm64" ], @@ -338,9 +394,9 @@ } }, "node_modules/@oxfmt/binding-win32-arm64-msvc": { - "version": "0.66.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-0.66.0.tgz", - "integrity": "sha512-soV+0vESv7e5ntCHWC61x4gg8OSak6IHHnWsZmHrJFlvMj2AK+kmldErCNkVkrvc1Ts2/++rJXn+IuAb2WMXhw==", + "version": "0.79.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-0.79.0.tgz", + "integrity": "sha512-zlW1m8M49vNGgqQF/ze80KW8pZMicnW2XDZGBHuYtXTRYn4ewvgpqN9wwoqb6uLZZfb1R1zaQWKEB8cs7KYjwA==", "cpu": [ "arm64" ], @@ -355,9 +411,9 @@ } }, "node_modules/@oxfmt/binding-win32-ia32-msvc": { - "version": "0.66.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-0.66.0.tgz", - "integrity": "sha512-YCPi23uRIEYuIKTZohAkKbPFpujQ5QBuUM5iDv+UqbCmTPAkaFsxjsSuB8xlBpRT0G7eP/4HMF+cPDSqHtOD9A==", + "version": "0.79.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-0.79.0.tgz", + "integrity": "sha512-wbb7hFv2wK3SCTfu8dl1ydNsXM5dmH+PJMU3sojCkfKcG29VDpITL5/AtouCzXjkOc90QRkcAZcg36gP0KqoHA==", "cpu": [ "ia32" ], @@ -372,9 +428,9 @@ } }, "node_modules/@oxfmt/binding-win32-x64-msvc": { - "version": "0.66.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-x64-msvc/-/binding-win32-x64-msvc-0.66.0.tgz", - "integrity": "sha512-bwTQcv/JVRPkOqQtMF0X7vpvpncDQiBcXHxZ9S2hR12Hlo8bvBdUR5x5XnxzDZ3kM0qoZw1rv7KaD66Ly+pFWA==", + "version": "0.79.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-x64-msvc/-/binding-win32-x64-msvc-0.79.0.tgz", + "integrity": "sha512-JLaeaQ+4LkQiVXY06JIV1dBFEDJzssvDieK/3Poi6CsY+c4UxghZVrrsfcKGJ5R/0F2Sw3C5Lf5Hu0sM5qJfPw==", "cpu": [ "x64" ], @@ -389,9 +445,9 @@ } }, "node_modules/@oxlint/binding-android-arm-eabi": { - "version": "1.81.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm-eabi/-/binding-android-arm-eabi-1.81.0.tgz", - "integrity": "sha512-IcCRsXiedJoJopY6mpZUBEeVFsUrutmrG7dZ87zMuKJlhg70Ora9bBl1WcCxZQtyI10YpnVdEso5oCg7YcfSHw==", + "version": "1.94.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm-eabi/-/binding-android-arm-eabi-1.94.0.tgz", + "integrity": "sha512-730FKSBsKg/NawYnpI3gXRroXptOVqY32iYBPLUZaSx0vgYzOeiNtwojZL4gJdzo9wDvHUlstShmGRHrWcbRYg==", "cpu": [ "arm" ], @@ -406,9 +462,9 @@ } }, "node_modules/@oxlint/binding-android-arm64": { - "version": "1.81.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm64/-/binding-android-arm64-1.81.0.tgz", - "integrity": "sha512-GRrIPyTGVhx3L3h+0T5xT2A0jFAcdPv4+IfuXpGDLIdl6XeYhgg/zw72A5ILZoUgRqZuM8F1y+V/gfDriXSxzQ==", + "version": "1.94.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm64/-/binding-android-arm64-1.94.0.tgz", + "integrity": "sha512-8v8TICIiZpXLot1HSq5+vsG9NEKQ5czQBYlUqJR75OVfFDr3cGOmRU/CtHDWnS4tm8nW+Z4Y357qGToSfYqFvA==", "cpu": [ "arm64" ], @@ -423,9 +479,9 @@ } }, "node_modules/@oxlint/binding-darwin-arm64": { - "version": "1.81.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-arm64/-/binding-darwin-arm64-1.81.0.tgz", - "integrity": "sha512-qNQ9tXRgLuKbqSV1S2h9h4KPHjbovO7RRR2/enUOtHzTkFZ7B9X5zqqHJua8dRyc7dBy7Aoyq5pqTSLFVcAzGQ==", + "version": "1.94.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-arm64/-/binding-darwin-arm64-1.94.0.tgz", + "integrity": "sha512-NePcRMO/ltt1Pnytohl6pl0bd/QyRX8HbpptuDz9LK7FTsFD4lKxDMBt7di9k6IFLO0J05jO2nm7wGqIh6dRHA==", "cpu": [ "arm64" ], @@ -440,9 +496,9 @@ } }, "node_modules/@oxlint/binding-darwin-x64": { - "version": "1.81.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-x64/-/binding-darwin-x64-1.81.0.tgz", - "integrity": "sha512-q0QTm32jWga2Gv4j7IaVZN0jYMi9UV73sWVgFtDA4iIfqwMCLLZ3ve+9KwfYtsaKZSgQhmPaogeZWqDZpcY1Pw==", + "version": "1.94.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-x64/-/binding-darwin-x64-1.94.0.tgz", + "integrity": "sha512-QV+m+OaEgLmYyillvP1wKXhMm6tDZEWx3vG7Wjmx9ybg15+6YMfqzvp6e+uPukC6zNywuule0vMn0fZgihZzZA==", "cpu": [ "x64" ], @@ -457,9 +513,9 @@ } }, "node_modules/@oxlint/binding-freebsd-x64": { - "version": "1.81.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-freebsd-x64/-/binding-freebsd-x64-1.81.0.tgz", - "integrity": "sha512-/+8wVWDXEC7wHVAhOc59Fw/SkMc1arLkFD8iQCaSsmzenK1X4doFqquL9H1wrtGUzaiycVqkf/sSpcILK6W1UA==", + "version": "1.94.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-freebsd-x64/-/binding-freebsd-x64-1.94.0.tgz", + "integrity": "sha512-KVZjca581nrV6P71kZ9M1otBib9LH0IMn9rr4mrnbRp18V0HiZhBHbU26gji/Ieq2G34qMacnMc3zrmKmvWqWA==", "cpu": [ "x64" ], @@ -474,9 +530,9 @@ } }, "node_modules/@oxlint/binding-linux-arm-gnueabihf": { - "version": "1.81.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.81.0.tgz", - "integrity": "sha512-4xt422FEgioRq9hAL4Tq7fujGUWnc8z1BJ+Oi8RN8vB8axaP+sdK6a2xdlcQCCYnJg9QMuMFS0AucuIFx/EacA==", + "version": "1.94.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.94.0.tgz", + "integrity": "sha512-AMQtgQJk8DgdIV+qaQ5sFoHAko4iKa8zo+gYqELy2grtU8hXWB08DAGB3u90aQL1YSxbd3zqHjgcODBHDFyzBQ==", "cpu": [ "arm" ], @@ -491,9 +547,9 @@ } }, "node_modules/@oxlint/binding-linux-arm-musleabihf": { - "version": "1.81.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-1.81.0.tgz", - "integrity": "sha512-u3vna8KdGplH4DRCW9K54D68fcMo7IxVrkCJWwXnIhwtBdnDnYrmzOUA/XjmBlPpcLsgw9Z5BNdY4za9+Dj+MQ==", + "version": "1.94.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-1.94.0.tgz", + "integrity": "sha512-ZLzoGVGAmQkp9leeB5rNxAXLcvlmkmd/GY71LKd5uikk+28NEApY3S2FB3pq6MkfOCFFnFg6QgD9lJIjd07D0Q==", "cpu": [ "arm" ], @@ -508,9 +564,9 @@ } }, "node_modules/@oxlint/binding-linux-arm64-gnu": { - "version": "1.81.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.81.0.tgz", - "integrity": "sha512-3j9k+gsYsE7nv71GWotXsqsa2l9/aJenD7dVHNt/CBvsb0SgRjSMnHFeP59IXUAl1wvVFhqGl2wJNMwWU3UBlA==", + "version": "1.94.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.94.0.tgz", + "integrity": "sha512-N1dW6o7cY90hLVkDsvz8nWIFOwbO+n272pvW7uLYB7u47HagJVnLChfK6QA9dWFdiPudud9zfksVUOciHc5PNA==", "cpu": [ "arm64" ], @@ -528,9 +584,9 @@ } }, "node_modules/@oxlint/binding-linux-arm64-musl": { - "version": "1.81.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.81.0.tgz", - "integrity": "sha512-k5iAp3dNxW0/uDCBY+WSm8jKB2szu7SkEQZdgRRpDXvuDd69vvDcqhB3A/pWCfCwXyenjNjFn9Td1fVoyAc+Yg==", + "version": "1.94.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.94.0.tgz", + "integrity": "sha512-7tCF4OV/bGDQ2xxgb+sDI97SpmmDrUII4JxTG553voJVA9cnkbXSGSXzo78Ax73BuhEOPoQc2Qi6VrfT0cDG2A==", "cpu": [ "arm64" ], @@ -548,9 +604,9 @@ } }, "node_modules/@oxlint/binding-linux-ppc64-gnu": { - "version": "1.81.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.81.0.tgz", - "integrity": "sha512-TFqLja3uYmVSte6nof9GWrex9Z8WgdZrNiLC6Te5rXGDqXB2y4j/26iFhwosXiAFqDhE9JJVuuCkDKLwptTn1g==", + "version": "1.94.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.94.0.tgz", + "integrity": "sha512-B5vUHE4wNisVEuaYxwFUn6tY+vw7A+9APxxqGKI+UmP3yKLpkhnt0qsaCrzjpX55F8rCRHBaTvIDdYo32NE36g==", "cpu": [ "ppc64" ], @@ -568,9 +624,9 @@ } }, "node_modules/@oxlint/binding-linux-riscv64-gnu": { - "version": "1.81.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-1.81.0.tgz", - "integrity": "sha512-UEcySvGS0NOVo7h7n7CYyJL9+6gFAh7Zc/ToDXVScFvzHSTIxtzkMVU30rmQ6+nQ1LF+UdiRDdJajpDu+OylLg==", + "version": "1.94.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-1.94.0.tgz", + "integrity": "sha512-/U0b15+c4hTodo8YhEqDlQ6OjnGKvc8igjM/mh23ukqqCUBKiBCaxqUV8bcaofK9uZ+f8wCygkyXLS6LN25YSA==", "cpu": [ "riscv64" ], @@ -588,9 +644,9 @@ } }, "node_modules/@oxlint/binding-linux-riscv64-musl": { - "version": "1.81.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-1.81.0.tgz", - "integrity": "sha512-H+diDbhD00+wI1IRP8Kz88x/lat+DgtoBJzoTthS16xkTJGNaEkfb8gzmd1rzc/2uDQQMl7GNl+JFUacVeWxIA==", + "version": "1.94.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-1.94.0.tgz", + "integrity": "sha512-ba94Vwl0qOnwXIXNDR33AEbLXuX++ckM74t+9Te7CiPSPAHivhOYyeEkUAicrvOEei1pxXkWggLbFeBFFBTuHA==", "cpu": [ "riscv64" ], @@ -608,9 +664,9 @@ } }, "node_modules/@oxlint/binding-linux-s390x-gnu": { - "version": "1.81.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.81.0.tgz", - "integrity": "sha512-8znJ/5TekjOKg1j1Acho4PJMdiAHLtlcXuWEiipOhAMV6rQcXdmDdXCbheyDczN6TjBwiNfjcP81k4AthrKRzw==", + "version": "1.94.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.94.0.tgz", + "integrity": "sha512-GVwwwms3O8pdgbCiPavwq2vltyB4661GkDz6kJduZ0E5nsSJUDJ0svaP+ePYpuDVYi4+K1qhCKnWa/Ec8I4LUA==", "cpu": [ "s390x" ], @@ -628,9 +684,9 @@ } }, "node_modules/@oxlint/binding-linux-x64-gnu": { - "version": "1.81.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.81.0.tgz", - "integrity": "sha512-Q2Wj70yFsvn5QjlmifFzbj4H+kJy53bwqc41o1fzoM7MpLV1NIbhg/LpWXRfC6KOkSAdUx1Wd8VJsdPmhp/HRA==", + "version": "1.94.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.94.0.tgz", + "integrity": "sha512-iUfCFJN8ZIresSnpTfiIkhF3s8X+XA4I9KJ249QwR2QYTMwh0+pla1pj1xaFi+HtR9McjM4Jaemf70HzX7ilOQ==", "cpu": [ "x64" ], @@ -648,9 +704,9 @@ } }, "node_modules/@oxlint/binding-linux-x64-musl": { - "version": "1.81.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-musl/-/binding-linux-x64-musl-1.81.0.tgz", - "integrity": "sha512-cPInHp/ddEe5qkyK2IiyQ8Q3Mp2oLLEhhsGgTK2oZx4L6+llGam1H1yBvJZ7qHfOXj8N3hxBS8sj4tO+gtFlIg==", + "version": "1.94.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-musl/-/binding-linux-x64-musl-1.94.0.tgz", + "integrity": "sha512-RqWVeWpDACS4Oh0m21OBmy+CQ50CbbhuHFmNNPVS2P/4R3d188MjEuEuV7So82/tAM8UAT+UuMDtRDESd9NJ7g==", "cpu": [ "x64" ], @@ -668,9 +724,9 @@ } }, "node_modules/@oxlint/binding-openharmony-arm64": { - "version": "1.81.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-openharmony-arm64/-/binding-openharmony-arm64-1.81.0.tgz", - "integrity": "sha512-0CQxSX4ajqm07AHBf5U33qQzXKdd7wtq/oTL/7vpY6RNNuxrRi8W4bqUV1Jyu/vj+9KmxQyDhxfeVX1nQL6kfg==", + "version": "1.94.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-openharmony-arm64/-/binding-openharmony-arm64-1.94.0.tgz", + "integrity": "sha512-K/2DHOUoypwYVqzxJMRPdMuBKjAetZEAsGPP7rHimd+2+5J1TxM+17pG8kw+ayH4+rqBXiPd+H9wgPcU+fF77A==", "cpu": [ "arm64" ], @@ -685,9 +741,9 @@ } }, "node_modules/@oxlint/binding-win32-arm64-msvc": { - "version": "1.81.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.81.0.tgz", - "integrity": "sha512-l0hbeISm9673hVrrQU8j/p2M7YH9Ouoj7p7E/QM55NTrKVLP+P3PF8hLu+OY+x0VtGRW+ggiQKZqmdYps9H+TA==", + "version": "1.94.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.94.0.tgz", + "integrity": "sha512-hYOCaOJiB4ZCGswBWKl3JQrhqu6mnC5DCUw/1UMNzRXgsHIJ0V226J43LAVICVIDGlhFUZTYShFW+wHWpt6qCQ==", "cpu": [ "arm64" ], @@ -702,9 +758,9 @@ } }, "node_modules/@oxlint/binding-win32-ia32-msvc": { - "version": "1.81.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-1.81.0.tgz", - "integrity": "sha512-ksqPP5jbFXcYreEQ7zdJh06rJQBymCTyGRCdaXjfcf2aG4f8KxUWY5wcgYHmaTK+FJ4bPG5sUAdOX+6trnH1JA==", + "version": "1.94.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-1.94.0.tgz", + "integrity": "sha512-1l1FDlzbPmAeDoZ8UGspOE2dOmz1ZL6SlDsvOmRCmWSQjCdTy5LzUepS8mO/SGpAoz4D6WAt/yNZAUyHqbkmkQ==", "cpu": [ "ia32" ], @@ -719,9 +775,9 @@ } }, "node_modules/@oxlint/binding-win32-x64-msvc": { - "version": "1.81.0", - "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.81.0.tgz", - "integrity": "sha512-IZuUCwGw9emG5JtCp+fYGB+Z4OWEoeEcM8R5BA1pYw63/ieYFVdcU2ylxTpHbVHSenZnsYE+ZZ20uHAJszQ4cA==", + "version": "1.94.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.94.0.tgz", + "integrity": "sha512-I3eZdd4bemIJQDNv9XDV/FEofDxIoN32tzCv98wIgLdW05EqxZb5hF4AwPrRzHD/dQhl0n7KgPy5AQPfM0HWrA==", "cpu": [ "x64" ], @@ -736,9 +792,9 @@ } }, "node_modules/@rolldown/binding-android-arm-eabi": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.6.tgz", - "integrity": "sha512-b+jTcARdTiFLI6jB4a5XjTm0RWd6KcRfQj/I2356fxUZemiho9zQLxo0RtCuMDAyKcLo6cEltkgbQp6d1+sjjQ==", + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.3.3.tgz", + "integrity": "sha512-K1itOg1Xl50XyjLDa4qQZqaYsfiQbFbFRWXOEOupOsGr3whhm5ed4lgySd6Inohv2TB0+sdU4AxORKuS/TGang==", "cpu": [ "arm" ], @@ -753,9 +809,9 @@ } }, "node_modules/@rolldown/binding-android-arm64": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.6.tgz", - "integrity": "sha512-lkWU8ZJaRk9q3CIEY1Tc7vIFALp3Xw5NfGJo2hQg5oIqNgxWi1zI+IiDEK3r70BF5Dzol1tcXsnzsRc8NLhG+Q==", + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.3.3.tgz", + "integrity": "sha512-re+E0E3YSJXjEFzdOvBgkVUev1Gg49ileia04qy+Djn0lIMBr7pnwVOYQ+4vc9XbLClCmMziasqXHM7KTmKNKQ==", "cpu": [ "arm64" ], @@ -770,9 +826,9 @@ } }, "node_modules/@rolldown/binding-darwin-arm64": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.6.tgz", - "integrity": "sha512-dgR56NYnvAszm7Ob1B2/Vn0e8bUQYZH2UjVaMMtMVOCKFSfjhfLmuA/9+O+F+ajUdG6B/bSssrKW6JJYASa8jA==", + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.3.3.tgz", + "integrity": "sha512-6pMLYsUiQJXPkUj/CG447hOBKtbe+hjWw/wbxe/mucoPKgnLSVRTzey7s0kXfqrjxhDd3gQ2hj6lgUKRumsIzw==", "cpu": [ "arm64" ], @@ -787,9 +843,9 @@ } }, "node_modules/@rolldown/binding-darwin-x64": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.6.tgz", - "integrity": "sha512-vpVxFvUCFioJqug7OTvqptkc4yb8UX0AwfDmJpaR/0sWz+BUmqSVAf7c8JkUgnN8YLspb4a/N6NhTyMAmdyQ7Q==", + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.3.3.tgz", + "integrity": "sha512-Lz+TskwvhceQgwnP+0ox5ZeL7HDDXHKWVRpOqC1Eo05y6rYyfvvep0msGqC95kQTykXrmGgP6qwJB1NdgNZVhg==", "cpu": [ "x64" ], @@ -804,9 +860,9 @@ } }, "node_modules/@rolldown/binding-freebsd-x64": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.6.tgz", - "integrity": "sha512-h1wG6Y6K3JlRswxsI64qQJqBAy4vrLuHgRbc8CZMGSWTOFRY6ghMApM1NKzB2I0n5xV1fjkE18SuVl2QpLeNpA==", + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.3.3.tgz", + "integrity": "sha512-sIzqNDbA7GFDXU8k9/vcJyV1p45mCe+xHOLo9qD7gdbTbMlwB+SpnFoP7WSpC2iYdGfOX9pjBxCfViRn/Nu3Jw==", "cpu": [ "x64" ], @@ -821,9 +877,9 @@ } }, "node_modules/@rolldown/binding-linux-arm-gnueabihf": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.6.tgz", - "integrity": "sha512-tbCiqub0q2MVWJKgF5PoAlNWCtQydiOYSLIkd8sByqK/6MMYLJRcSXSYodqYtd0O+Fw7QaVmKKlS4oL94YRZ0w==", + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.3.3.tgz", + "integrity": "sha512-HYysnZZ7HD3FM5RIBN6wDMoxtOjw4LS9HhRuQ57MsZt5XGpGRPxVpplvr7vUXRN+9MD8zb6vn1JRP06PXIuMYQ==", "cpu": [ "arm" ], @@ -838,9 +894,9 @@ } }, "node_modules/@rolldown/binding-linux-arm64-gnu": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.6.tgz", - "integrity": "sha512-oxK9+baEBPhZG5HB4URY+uU04zJWeZlH6Tb9rB5DK4DF9XR1uXNLXt5Q5ZsugTKayNCNLhkcwz/ye74hRI98dg==", + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.3.3.tgz", + "integrity": "sha512-XAyLqWSoEKVc8wsDbCIz5o2sBY6ye+0YByK9ib5QxFReoM1KHyThSHsdUODa1DKNzlEfae+p9QwK62LsVwo6Nw==", "cpu": [ "arm64" ], @@ -858,9 +914,9 @@ } }, "node_modules/@rolldown/binding-linux-arm64-musl": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.6.tgz", - "integrity": "sha512-muWCk27FVBEZtv0MsK8gnfSmgczA8KQ0uRVJbTABKhkRfQc38aUrcb7fhi3BNiyseFmgcRsoMfQsSNJ+DbZdSw==", + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.3.3.tgz", + "integrity": "sha512-oVyicDPj6vUVFRnuoQS7M2Ab8EkGWoq3a5ntyQqjtZoXfgVykIJqN2IAJSi9q9UyNoQUW0vbBLQSgGtlPJ40Kg==", "cpu": [ "arm64" ], @@ -878,9 +934,9 @@ } }, "node_modules/@rolldown/binding-linux-ppc64-gnu": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.6.tgz", - "integrity": "sha512-eWDoSfU7Co2qj3vgB3Dt4lj1mG6CoWbcJQkRMP3XJplyCMtuaq3LHvPFjS9QIPvMGWVadJC04Xiy0IdcVPtnwQ==", + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.3.3.tgz", + "integrity": "sha512-k7aFSWgUoi/X7jCst7UEof7pS5jc5ymD8mT/pdFE+pO1IBBI2+JU5Os4HEDqS/tYhetRggwM7MOiLP3cg1bSBQ==", "cpu": [ "ppc64" ], @@ -898,9 +954,9 @@ } }, "node_modules/@rolldown/binding-linux-s390x-gnu": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.6.tgz", - "integrity": "sha512-2bWNjRSIayvupRKxXUY2tWG9fYdoUlTqWywHRvE8Eq3GvuQ+f2HeIkve697fIt+IQs/PV8yFsdWuhp1aJ1PdnA==", + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.3.3.tgz", + "integrity": "sha512-D5mxHpr1qIb1Pt5UT+Bm2p6vJ7+VxcxWcxZCYVDFzZwWRq9iLiEg4/ROsaXFQl1O8sDQZZJ55UoRWWMK64uH5w==", "cpu": [ "s390x" ], @@ -918,9 +974,9 @@ } }, "node_modules/@rolldown/binding-linux-x64-gnu": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.6.tgz", - "integrity": "sha512-KekI0gS0wLxe1UBSQSjenBVwou/JkcQPDzBPICGZjxUv9k3RteHDPBQaiOicZUFKRIH2wKEimGwVpnJsbPzu7w==", + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.3.3.tgz", + "integrity": "sha512-nmW1O4BbNEmQI9+KTHbJgbDv0EuyZy64oBnRlMCtLJ8lQMIJ/H/iziQ0g2IUlHEhNrSebGvs9cRrlRj8oEfP+g==", "cpu": [ "x64" ], @@ -938,9 +994,9 @@ } }, "node_modules/@rolldown/binding-linux-x64-musl": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.6.tgz", - "integrity": "sha512-TvtPnfVr+HtyGiDmPK4VWmlNm7QhNNAcK5Q9A7aOXsI8545yCyaoMaicXrFZ72JzeYjaUVk7yT243zT0jzjFKQ==", + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.3.3.tgz", + "integrity": "sha512-ivU4JFHK5nFzrRbzp3+vwYdLj8mFckH4oz3hEl5LH/YeThr9/m2N2vF3NvLevtHq6e0COimgrEVyYTwQhh4ODg==", "cpu": [ "x64" ], @@ -958,9 +1014,9 @@ } }, "node_modules/@rolldown/binding-openharmony-arm64": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.6.tgz", - "integrity": "sha512-iOo0VEay2XFhaCcH0sps5XIimkSuOnNaZrf6+ZkoSOQBJPKNU48RkmJv0/lSpipexu5P+ouFgafe5IGr/DiQfg==", + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.3.3.tgz", + "integrity": "sha512-XxZoRIkNZ/7pFgvOA8QJmx3uFjMyVz7zS2/urzlaFffoOGclDvpUAMu3AHKT551E8JBKXLxIjpYxYMdF6Mz9vQ==", "cpu": [ "arm64" ], @@ -974,10 +1030,29 @@ "node": "^20.19.0 || >=22.12.0" } }, + "node_modules/@rolldown/binding-wasm32-wasi": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.3.3.tgz", + "integrity": "sha512-bBl1MB2gF26PSPy3CiDLiv+A6JGI546WbsDR34LfKAywSGeBeQXaDanoDG6QdZDJs53M1QyJir5MTKTu1n4ptA==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "2.0.0-beta.2", + "@emnapi/runtime": "2.0.0-beta.2", + "@napi-rs/wasm-runtime": "1.2.6" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + } + }, "node_modules/@rolldown/binding-win32-arm64-msvc": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.6.tgz", - "integrity": "sha512-y5NTmmasMS455JlOCO4ZM9krIchv3Mvm1crL1iUPGOPgEzSkves9n0SdC5Sjz6+qWDFhd8/JpfWMH8NSWNHe+A==", + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.3.3.tgz", + "integrity": "sha512-6rZur0hyen4LPhOxWIg7az1YX+Eo8Vvauc0D6lFYGK/QCvN+1XpnB8aFe3jQc/PBUGIReJJnLX3sS8h33/5v7A==", "cpu": [ "arm64" ], @@ -992,9 +1067,9 @@ } }, "node_modules/@rolldown/binding-win32-x64-msvc": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.6.tgz", - "integrity": "sha512-np8iZSLfXlAD4kWhiyq/u0Yt8oZDtRQ8lGhQaCXo2rl37KNjeU0GjJuwr4P3oeZ++ROfofsKNBqR5LTO8aXyWQ==", + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.3.3.tgz", + "integrity": "sha512-Ggzyuq1mN7claruAZH10aiiM1N3LRCoMP5xDXPdU514ulL0D2bksCWgFqEmEM2/pDzEP7Dq+dcv7IH452jtr1w==", "cpu": [ "x64" ], @@ -1015,6 +1090,17 @@ "dev": true, "license": "MIT" }, + "node_modules/@tybys/wasm-util": { + "version": "0.10.5", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.5.tgz", + "integrity": "sha512-dOGOPxlaNV+G046mZzN+9C0dAcQZeSKcXiVaM0TYy/LM4ttTmgSBDxYfovcYI8Em3+eAbiAYpvWLOv8+ZVRJKA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, "node_modules/@types/emscripten": { "version": "1.41.6", "resolved": "https://registry.npmjs.org/@types/emscripten/-/emscripten-1.41.6.tgz", @@ -1022,13 +1108,13 @@ "license": "MIT" }, "node_modules/@types/node": { - "version": "26.4.1", - "resolved": "https://registry.npmjs.org/@types/node/-/node-26.4.1.tgz", - "integrity": "sha512-k97ENvZWtvA6yqz5/FS6a7duDgOPEeOQOc2iKS/nY6mX6qJUKtLnWzQS+Xj6tXweyj6ZcTAK2Qecetnvi9nCLA==", + "version": "26.6.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz", + "integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==", "dev": true, "license": "MIT", "dependencies": { - "undici-types": "~8.3.0" + "undici-types": "~8.9.0" } }, "node_modules/@typescript/typescript-aix-ppc64": { @@ -1389,9 +1475,9 @@ } }, "node_modules/brace-expansion": { - "version": "5.0.9", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.9.tgz", - "integrity": "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==", + "version": "5.0.13", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.13.tgz", + "integrity": "sha512-Vh3dmFbc4wZeox7M9I/0L9GfFd83Su4+yCck/OF9Gi/P/dAHn0RT7X4K9R7gMNMhDck3DvhR6QXsnQdjjgwNvQ==", "dev": true, "license": "MIT", "dependencies": { @@ -1409,9 +1495,9 @@ "license": "ISC" }, "node_modules/chai": { - "version": "6.2.2", - "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz", - "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==", + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz", + "integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==", "dev": true, "license": "MIT", "engines": { @@ -1497,42 +1583,23 @@ "tmp": "^0.2.5" } }, - "node_modules/find-up": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", - "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "node_modules/find-up-simple": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/find-up-simple/-/find-up-simple-1.0.1.tgz", + "integrity": "sha512-afd4O7zpqHeRyg4PfDQsXmlDe2PfdHtJt6Akt8jOWaApLOZk5JXs6VMR29lz03pRe9mpykrRCYIYxaJYcfpncQ==", "dev": true, "license": "MIT", - "dependencies": { - "locate-path": "^6.0.0", - "path-exists": "^4.0.0" - }, "engines": { - "node": ">=10" + "node": ">=18" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/fsevents": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", - "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^8.16.0 || ^10.6.0 || >=11.0.0" - } - }, "node_modules/glob": { - "version": "13.0.6", - "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", - "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==", + "version": "13.0.7", + "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.7.tgz", + "integrity": "sha512-wfsFgXQ8A3SEI9XGf7Nl3Y9l7ffSrGh7SUCT7vU/2CzYPep9kjxAn1S40F9OPKxAMGCVl7HtNlJhrCJUeUq83g==", "dev": true, "license": "BlueOak-1.0.0", "dependencies": { @@ -1558,13 +1625,16 @@ } }, "node_modules/is-path-inside": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.3.tgz", - "integrity": "sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-4.0.0.tgz", + "integrity": "sha512-lJJV/5dYS+RcL8uQdBDW9c9uWFLLBNRyFhnAKXw5tVqLlKZ4RMGZKv+YQ/IA3OhD+RpbJa1LLFM1FQPGyIXvOA==", "dev": true, "license": "MIT", "engines": { - "node": ">=8" + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/is-unicode-supported": { @@ -1603,22 +1673,6 @@ "js-yaml": "bin/js-yaml.mjs" } }, - "node_modules/locate-path": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", - "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", - "dev": true, - "license": "MIT", - "dependencies": { - "p-locate": "^5.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/lru-cache": { "version": "11.5.2", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.2.tgz", @@ -1656,9 +1710,9 @@ } }, "node_modules/mocha": { - "version": "12.0.0", - "resolved": "https://registry.npmjs.org/mocha/-/mocha-12.0.0.tgz", - "integrity": "sha512-NYNh5IFt6WYqm9bi4601m7vix8MZdXC0DwS4gY6WhXO2RgJWhivhISVmq1oklCif18OSI9l+vx5Mdm5oh1XGiQ==", + "version": "12.0.3", + "resolved": "https://registry.npmjs.org/mocha/-/mocha-12.0.3.tgz", + "integrity": "sha512-beammieDdiWdkjANWeWPpkxUROYGi5FN88fPOkLiticz7HTg3Y+Pho3EYE6SUdcuWnZ3h2WD8EXCA55JF4o6wg==", "dev": true, "license": "MIT", "dependencies": { @@ -1666,15 +1720,15 @@ "chokidar": "^5.0.0", "debug": "^4.3.5", "diff": "^9.0.0", - "find-up": "^5.0.0", + "find-up-simple": "^1.0.1", "glob": "^13.0.0", - "is-path-inside": "^3.0.3", + "is-path-inside": "^4.0.0", "is-unicode-supported": "^0.1.0", "js-yaml": "^5.0.0", "minimatch": "^10.2.2", "ms": "^2.1.3", "picocolors": "^1.1.1", - "serialize-javascript": "^7.0.2", + "serialize-javascript": "^7.1.1", "strip-json-comments": "^5.0.3", "supports-color": "^8.1.1", "workerpool": "^10.0.0" @@ -1710,13 +1764,13 @@ "license": "MIT" }, "node_modules/oxfmt": { - "version": "0.66.0", - "resolved": "https://registry.npmjs.org/oxfmt/-/oxfmt-0.66.0.tgz", - "integrity": "sha512-FfvqR8RFtV6JJpRrpkfqyVCQ7HDvZ/VriWFx7veftCgL1B5ZO9qNr+1rvPieycMQnNfVG0PWyJQiy7p0hq1I5w==", + "version": "0.79.0", + "resolved": "https://registry.npmjs.org/oxfmt/-/oxfmt-0.79.0.tgz", + "integrity": "sha512-92iLHGxAgtYk6jLp/1ZBnEeABveNduHZgMDQj7tyqO9iafuJG3q+YHJq0R5Aa4YT+E6xswMQXdmPZYMwynS8ig==", "dev": true, "license": "MIT", "dependencies": { - "tinypool": "2.1.0" + "tinypool": "2.2.0" }, "bin": { "oxfmt": "bin/oxfmt" @@ -1728,31 +1782,35 @@ "url": "https://github.com/sponsors/oxc-project" }, "optionalDependencies": { - "@oxfmt/binding-android-arm-eabi": "0.66.0", - "@oxfmt/binding-android-arm64": "0.66.0", - "@oxfmt/binding-darwin-arm64": "0.66.0", - "@oxfmt/binding-darwin-x64": "0.66.0", - "@oxfmt/binding-freebsd-x64": "0.66.0", - "@oxfmt/binding-linux-arm-gnueabihf": "0.66.0", - "@oxfmt/binding-linux-arm-musleabihf": "0.66.0", - "@oxfmt/binding-linux-arm64-gnu": "0.66.0", - "@oxfmt/binding-linux-arm64-musl": "0.66.0", - "@oxfmt/binding-linux-ppc64-gnu": "0.66.0", - "@oxfmt/binding-linux-riscv64-gnu": "0.66.0", - "@oxfmt/binding-linux-riscv64-musl": "0.66.0", - "@oxfmt/binding-linux-s390x-gnu": "0.66.0", - "@oxfmt/binding-linux-x64-gnu": "0.66.0", - "@oxfmt/binding-linux-x64-musl": "0.66.0", - "@oxfmt/binding-openharmony-arm64": "0.66.0", - "@oxfmt/binding-win32-arm64-msvc": "0.66.0", - "@oxfmt/binding-win32-ia32-msvc": "0.66.0", - "@oxfmt/binding-win32-x64-msvc": "0.66.0" + "@oxfmt/binding-android-arm-eabi": "0.79.0", + "@oxfmt/binding-android-arm64": "0.79.0", + "@oxfmt/binding-darwin-arm64": "0.79.0", + "@oxfmt/binding-darwin-x64": "0.79.0", + "@oxfmt/binding-freebsd-x64": "0.79.0", + "@oxfmt/binding-linux-arm-gnueabihf": "0.79.0", + "@oxfmt/binding-linux-arm-musleabihf": "0.79.0", + "@oxfmt/binding-linux-arm64-gnu": "0.79.0", + "@oxfmt/binding-linux-arm64-musl": "0.79.0", + "@oxfmt/binding-linux-ppc64-gnu": "0.79.0", + "@oxfmt/binding-linux-riscv64-gnu": "0.79.0", + "@oxfmt/binding-linux-riscv64-musl": "0.79.0", + "@oxfmt/binding-linux-s390x-gnu": "0.79.0", + "@oxfmt/binding-linux-x64-gnu": "0.79.0", + "@oxfmt/binding-linux-x64-musl": "0.79.0", + "@oxfmt/binding-openharmony-arm64": "0.79.0", + "@oxfmt/binding-win32-arm64-msvc": "0.79.0", + "@oxfmt/binding-win32-ia32-msvc": "0.79.0", + "@oxfmt/binding-win32-x64-msvc": "0.79.0" }, "peerDependencies": { + "@astrojs/compiler-rs": "^0.5.0", "svelte": "^5.0.0", "vite-plus": "*" }, "peerDependenciesMeta": { + "@astrojs/compiler-rs": { + "optional": true + }, "svelte": { "optional": true }, @@ -1762,9 +1820,9 @@ } }, "node_modules/oxlint": { - "version": "1.81.0", - "resolved": "https://registry.npmjs.org/oxlint/-/oxlint-1.81.0.tgz", - "integrity": "sha512-HyrJYqeoOCL0iqaLEzGewGT48ZX99P3hxYh8udAF9RGGIghSamkXE4ClUyBpEDNqasamThgmlPbuMOe7SAZmHg==", + "version": "1.94.0", + "resolved": "https://registry.npmjs.org/oxlint/-/oxlint-1.94.0.tgz", + "integrity": "sha512-Fnt+3wSKRhtLmvgRfxgRX0excSPCoyiXRol4eWKZLtXxWMQtwQ3KjKQUYXOw5loyinfnZfGzh4RCYf7opfL0vw==", "dev": true, "license": "MIT", "bin": { @@ -1777,28 +1835,28 @@ "url": "https://github.com/sponsors/oxc-project" }, "optionalDependencies": { - "@oxlint/binding-android-arm-eabi": "1.81.0", - "@oxlint/binding-android-arm64": "1.81.0", - "@oxlint/binding-darwin-arm64": "1.81.0", - "@oxlint/binding-darwin-x64": "1.81.0", - "@oxlint/binding-freebsd-x64": "1.81.0", - "@oxlint/binding-linux-arm-gnueabihf": "1.81.0", - "@oxlint/binding-linux-arm-musleabihf": "1.81.0", - "@oxlint/binding-linux-arm64-gnu": "1.81.0", - "@oxlint/binding-linux-arm64-musl": "1.81.0", - "@oxlint/binding-linux-ppc64-gnu": "1.81.0", - "@oxlint/binding-linux-riscv64-gnu": "1.81.0", - "@oxlint/binding-linux-riscv64-musl": "1.81.0", - "@oxlint/binding-linux-s390x-gnu": "1.81.0", - "@oxlint/binding-linux-x64-gnu": "1.81.0", - "@oxlint/binding-linux-x64-musl": "1.81.0", - "@oxlint/binding-openharmony-arm64": "1.81.0", - "@oxlint/binding-win32-arm64-msvc": "1.81.0", - "@oxlint/binding-win32-ia32-msvc": "1.81.0", - "@oxlint/binding-win32-x64-msvc": "1.81.0" + "@oxlint/binding-android-arm-eabi": "1.94.0", + "@oxlint/binding-android-arm64": "1.94.0", + "@oxlint/binding-darwin-arm64": "1.94.0", + "@oxlint/binding-darwin-x64": "1.94.0", + "@oxlint/binding-freebsd-x64": "1.94.0", + "@oxlint/binding-linux-arm-gnueabihf": "1.94.0", + "@oxlint/binding-linux-arm-musleabihf": "1.94.0", + "@oxlint/binding-linux-arm64-gnu": "1.94.0", + "@oxlint/binding-linux-arm64-musl": "1.94.0", + "@oxlint/binding-linux-ppc64-gnu": "1.94.0", + "@oxlint/binding-linux-riscv64-gnu": "1.94.0", + "@oxlint/binding-linux-riscv64-musl": "1.94.0", + "@oxlint/binding-linux-s390x-gnu": "1.94.0", + "@oxlint/binding-linux-x64-gnu": "1.94.0", + "@oxlint/binding-linux-x64-musl": "1.94.0", + "@oxlint/binding-openharmony-arm64": "1.94.0", + "@oxlint/binding-win32-arm64-msvc": "1.94.0", + "@oxlint/binding-win32-ia32-msvc": "1.94.0", + "@oxlint/binding-win32-x64-msvc": "1.94.0" }, "peerDependencies": { - "oxlint-tsgolint": ">=7.0.2001", + "oxlint-tsgolint": ">=7.0.2007", "vite-plus": "*" }, "peerDependenciesMeta": { @@ -1810,48 +1868,6 @@ } } }, - "node_modules/p-limit": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", - "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "yocto-queue": "^0.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/p-locate": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", - "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", - "dev": true, - "license": "MIT", - "dependencies": { - "p-limit": "^3.0.2" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/path-exists": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", - "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/path-scurry": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz", @@ -1877,28 +1893,25 @@ "license": "ISC" }, "node_modules/playwright": { - "version": "1.62.1", - "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.62.1.tgz", - "integrity": "sha512-0M+L3LAD8/nm554LOla9Ayx0j0tmFZ0FBcoQ7F1VuVHpM/XpiC8RcDzBQB8W5+hA8L22THxELzeF+2WcUzvcLg==", + "version": "1.65.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.65.1.tgz", + "integrity": "sha512-vJ1FuoOrNwOKHUIVEvSt3jT1L+wjjDpwhwIstKtfvTh8XIG4FG4bIFuvNdMxi81LGfAhUgUZleVFaOLY4RIUUw==", "dev": true, "license": "Apache-2.0", "dependencies": { - "playwright-core": "1.62.1" + "playwright-core": "1.65.1" }, "bin": { "playwright": "cli.js" }, "engines": { "node": ">=20" - }, - "optionalDependencies": { - "fsevents": "2.3.2" } }, "node_modules/playwright-core": { - "version": "1.62.1", - "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.62.1.tgz", - "integrity": "sha512-wPYSwEBJY9GHraISXqyqtx0na0LpO3XEX7jNDhntbex7tzUS7kLnZsOlFruFJB4Hi/rhDMjXGqHewDZ68nYZVw==", + "version": "1.65.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.1.tgz", + "integrity": "sha512-hqPpz7blSMPxWVdoeE1yiBSzXsKiVOd2k+kjCvmUywD2GPO2Dd9HfcWnq9NN0GHbNZDFgZ9JfBFr+X5/BLo0qw==", "dev": true, "license": "Apache-2.0", "bin": { @@ -1933,13 +1946,13 @@ } }, "node_modules/rolldown": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.6.tgz", - "integrity": "sha512-vMM4q3aixf46GiF1Kok8jDPFsEpXgFWGjUHXNkNHNm+Y2adXAG2dbX91jkti3i0ZRsOlcmbuzAz1poObSHCmUA==", + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.3.3.tgz", + "integrity": "sha512-ksB1g74e7haRy02OYm4lOQAlr6sK6hBpAY5R+YC30Gkv4L1COwF6M9umBAYAPxWpGow6Vr+IXtyDjH9fq7A+Zg==", "dev": true, "license": "MIT", "dependencies": { - "@oxc-project/types": "=0.147.0", + "@oxc-project/types": "=0.159.0", "@rolldown/pluginutils": "^1.0.0" }, "bin": { @@ -1949,27 +1962,28 @@ "node": "^20.19.0 || >=22.12.0" }, "optionalDependencies": { - "@rolldown/binding-android-arm-eabi": "1.2.6", - "@rolldown/binding-android-arm64": "1.2.6", - "@rolldown/binding-darwin-arm64": "1.2.6", - "@rolldown/binding-darwin-x64": "1.2.6", - "@rolldown/binding-freebsd-x64": "1.2.6", - "@rolldown/binding-linux-arm-gnueabihf": "1.2.6", - "@rolldown/binding-linux-arm64-gnu": "1.2.6", - "@rolldown/binding-linux-arm64-musl": "1.2.6", - "@rolldown/binding-linux-ppc64-gnu": "1.2.6", - "@rolldown/binding-linux-s390x-gnu": "1.2.6", - "@rolldown/binding-linux-x64-gnu": "1.2.6", - "@rolldown/binding-linux-x64-musl": "1.2.6", - "@rolldown/binding-openharmony-arm64": "1.2.6", - "@rolldown/binding-win32-arm64-msvc": "1.2.6", - "@rolldown/binding-win32-x64-msvc": "1.2.6" + "@rolldown/binding-android-arm-eabi": "1.3.3", + "@rolldown/binding-android-arm64": "1.3.3", + "@rolldown/binding-darwin-arm64": "1.3.3", + "@rolldown/binding-darwin-x64": "1.3.3", + "@rolldown/binding-freebsd-x64": "1.3.3", + "@rolldown/binding-linux-arm-gnueabihf": "1.3.3", + "@rolldown/binding-linux-arm64-gnu": "1.3.3", + "@rolldown/binding-linux-arm64-musl": "1.3.3", + "@rolldown/binding-linux-ppc64-gnu": "1.3.3", + "@rolldown/binding-linux-s390x-gnu": "1.3.3", + "@rolldown/binding-linux-x64-gnu": "1.3.3", + "@rolldown/binding-linux-x64-musl": "1.3.3", + "@rolldown/binding-openharmony-arm64": "1.3.3", + "@rolldown/binding-wasm32-wasi": "1.3.3", + "@rolldown/binding-win32-arm64-msvc": "1.3.3", + "@rolldown/binding-win32-x64-msvc": "1.3.3" } }, "node_modules/serialize-javascript": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-7.1.1.tgz", - "integrity": "sha512-k3CMsaIvvdSwm8oLB4MXSl0wH2/cwlH7xGcnRd2DaeRmBkbzYmyT8j0tsX60DwD1eRwHTpNpH8ljKu9oUT1MeQ==", + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-7.1.4.tgz", + "integrity": "sha512-FqlEuoTq/zRmA4Lg6aOqyH3lCHbUtCB0bmHCeFniX2GBdDqMJM3FwdvEhlE5Pim1dlt2FfBdVPmUNNiGhhKqpw==", "dev": true, "license": "BSD-3-Clause", "engines": { @@ -1997,9 +2011,9 @@ } }, "node_modules/tinypool": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-2.1.0.tgz", - "integrity": "sha512-Pugqs6M0m7Lv1I7FtxN4aoyToKg1C4tu+/381vH35y8oENM/Ai7f7C4StcoK4/+BSw9ebcS8jRiVrORFKCALLw==", + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-2.2.0.tgz", + "integrity": "sha512-jBrmx4lYmaC9k/mgPbylxs7kBUxHtD8256up+HjLaDFfXScKJQyil+SWXSvhAtT7XHo+yTVlpB81PGmHP8oLSQ==", "dev": true, "license": "MIT", "engines": { @@ -2017,9 +2031,9 @@ } }, "node_modules/tslib": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", - "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", "dev": true, "license": "0BSD" }, @@ -2059,9 +2073,9 @@ } }, "node_modules/undici-types": { - "version": "8.3.0", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz", - "integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==", + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", + "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==", "dev": true, "license": "MIT" }, @@ -2071,19 +2085,6 @@ "integrity": "sha512-6z2Iis68Wqth93/G/wJP9u+R3O+d2XTlgWChGCwuT1qLbBsOYueGRZuJ++v3mtDP5KjYdy+WzvWC+VWETSVXJA==", "dev": true, "license": "Apache-2.0" - }, - "node_modules/yocto-queue": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", - "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } } } } diff --git a/package.json b/package.json index c25620b..3d6346e 100755 --- a/package.json +++ b/package.json @@ -65,15 +65,15 @@ ], "devDependencies": { "@types/node": "*", - "chai": "6.2.2", + "chai": "6.3.0", "chai-as-promised": "8.0.2", "fengari": "0.1.5", - "mocha": "12.0.0", - "oxfmt": "0.66.0", - "oxlint": "1.81.0", - "playwright": "1.62.1", - "rolldown": "1.2.6", - "tslib": "2.8.1", + "mocha": "12.0.3", + "oxfmt": "0.79.0", + "oxlint": "1.94.0", + "playwright": "1.65.1", + "rolldown": "1.3.3", + "tslib": "2.9.1", "typescript": "7.0.2" }, "dependencies": { From f52eb0134a75e3fccaa364f6109daee75c13cf93 Mon Sep 17 00:00:00 2001 From: ceifa Date: Thu, 19 Nov 2026 22:20:15 -0300 Subject: [PATCH 78/83] update emscripten to 7.0.0 FS.filesystems is gone, so mounts reach NODEFS through the module instead, which the build now exports. FS.analyzePath is gone under STRICT, so exists() does the same lookup itself. The glue no longer declares EmscriptenEH, which the unwind brand plugin patched. It was never thrown in 6.0.4 either, only declared: with SUPPORT_LONGJMP=wasm every unwind is a WebAssembly.Exception, so the brand never did anything and goes with the plugin. The docker fallback of build:wasm ran the untagged emsdk image and is pinned to the version CI installs, so a local build makes the glue CI tests. The glue drops from 86.8 to 79 KB. --- .github/workflows/publish.yml | 2 +- .github/workflows/test.yml | 2 +- rolldown.config.ts | 20 -------------------- src/module.ts | 20 ++++++++------------ src/runtime.ts | 8 +++++++- src/utils.ts | 11 ++--------- test/filesystem.test.js | 2 +- utils/build-wasm.js | 5 ++++- utils/build-wasm.sh | 1 + 9 files changed, 25 insertions(+), 46 deletions(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index b622272..851970f 100755 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -16,7 +16,7 @@ jobs: - name: Setup EMSDK uses: emscripten-core/setup-emsdk@v16 with: - version: 6.0.4 + version: 7.0.0 actions-cache-folder: emsdk-cache - name: Use Node.js 26.x diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index ede4f3c..b21e1c7 100755 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -18,7 +18,7 @@ jobs: submodules: recursive - uses: emscripten-core/setup-emsdk@v16 with: - version: 6.0.4 + version: 7.0.0 actions-cache-folder: emsdk-cache - name: Use Node.js ${{ matrix.node-version }} uses: actions/setup-node@v7 diff --git a/rolldown.config.ts b/rolldown.config.ts index 8f8965f..96f13e1 100644 --- a/rolldown.config.ts +++ b/rolldown.config.ts @@ -1,7 +1,6 @@ import { copyFile } from 'node:fs/promises' import { defineConfig } from 'rolldown' import pkg from './package.json' with { type: 'json' } -import { UNWIND_BRAND } from './src/utils' export default defineConfig({ // The CLI is an entry of its own: it imports the library by package name at run time rather @@ -43,25 +42,6 @@ export default defineConfig({ } }, }, - { - // A consumer's minifier renames the glue's unwind class but not a string compared - // against its name, so isEmscriptenUnwind goes by a brand on the prototype instead. - name: 'emscripten-unwind-brand', - transform(code, id) { - if (!id.endsWith('glue.js')) { - return - } - const branded = code.replace(/class EmscriptenEH\s*\{\s*\}/, (match) => { - return `${match}EmscriptenEH.prototype.${UNWIND_BRAND}=true;` - }) - if (branded === code) { - // A silent miss would ship a build where every Lua error path is subtly wrong. - this.error('EmscriptenEH declaration not found in the glue, so the unwind brand would be a no-op') - } - // Generated code with no sourcemap of its own, so there is nothing to preserve. - return { code: branded, map: null } - }, - }, { // A node builtin is imported behind a runtime check for Node, which a bundler targeting // the browser does not see, so it refuses to resolve it. webpack takes the comment; the diff --git a/src/module.ts b/src/module.ts index 4440ee7..beb81af 100755 --- a/src/module.ts +++ b/src/module.ts @@ -40,13 +40,9 @@ export interface LuaEmscriptenModule extends EmscriptenModule { removeFunction: typeof removeFunction setValue: typeof setValue getValue: typeof getValue - // `filesystems` is the only member missing upstream; mkdirTree and the rest come from typeof FS. - FS: typeof FS & { - filesystems: { - NODEFS: Emscripten.FileSystemType - MEMFS: Emscripten.FileSystemType - } - } + FS: typeof FS + // Exported by the build, since Emscripten 7 no longer hangs the backends off FS.filesystems. + NODEFS: Emscripten.FileSystemType PATH: EmscriptenPath stringToNewUTF8: typeof stringToNewUTF8 lengthBytesUTF8: typeof lengthBytesUTF8 @@ -262,9 +258,9 @@ function assertMountFits(live: readonly ResolvedMount[], candidate: ResolvedMoun } } -function mountHostDirectory(fs: EmscriptenFS, { virtualPath, hostPath }: ResolvedMount): void { - fs.mkdirTree(virtualPath) - fs.mount(fs.filesystems.NODEFS, { root: hostPath }, virtualPath) +function mountHostDirectory(emscripten: LuaEmscriptenModule, { virtualPath, hostPath }: ResolvedMount): void { + emscripten.FS.mkdirTree(virtualPath) + emscripten.FS.mount(emscripten.NODEFS, { root: hostPath }, virtualPath) } /** Everything the wasm module needs before it starts, and nothing that outlives that. */ @@ -294,7 +290,7 @@ function createPreRun(config: PreRunConfig): (initializedModule: LuaEmscriptenMo // Nothing to do for `fs: 'host'`: that glue is NODERAWFS, so the filesystem already is the // host's, working directory included. for (const mount of config.mounts) { - mountHostDirectory(initializedModule.FS, mount) + mountHostDirectory(initializedModule, mount) } if (config.stdin || config.stdout || config.stderr) { @@ -608,7 +604,7 @@ export default class LuaModule extends LuaBindings { const mount = resolveMount(virtualPath, hostPath) assertMountFits(this.mounts, mount) - mountHostDirectory(this.emscripten.FS, mount) + mountHostDirectory(this.emscripten, mount) this.mounts.push(mount) } diff --git a/src/runtime.ts b/src/runtime.ts index e3ebc09..6e0d932 100755 --- a/src/runtime.ts +++ b/src/runtime.ts @@ -77,7 +77,13 @@ export default class LuaRuntime { } public exists(path: string): boolean { - return this.filesystem.analyzePath(path).exists + // Emscripten 7 dropped FS.analyzePath, which did this same lookup and caught its error. + try { + this.filesystem.lookupPath(path, { follow: true }) + return true + } catch { + return false + } } /** Where relative paths resolve from, `/` unless something changed it or `fs` is `'host'`. */ diff --git a/src/utils.ts b/src/utils.ts index 9cb46f8..6636dc3 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -9,18 +9,11 @@ export const isPromise = (target: unknown): target is PromiseLike => { return typeof target === 'object' && target !== null && typeof (target as PromiseLike).then === 'function' } -/** Read by the build, which brands the glue's unwind classes with it. */ -export const UNWIND_BRAND = '__emscriptenUnwind' - /** * A Lua longjmp out of a C function that a JS callback is on the stack of, which has to be rethrown * rather than turned into a Lua error. With `SUPPORT_LONGJMP=wasm` it is a `WebAssembly.Exception` - * the wasm caller resumes unwinding from; the branded `EmscriptenEH` covers the other unwinds - * Emscripten still throws from JS (its class is module local, hence the brand). + * the wasm caller resumes unwinding from, and the glue throws no unwind of its own from JS. */ export const isEmscriptenUnwind = (value: unknown): boolean => { - if (typeof WebAssembly.Exception === 'function' && value instanceof WebAssembly.Exception) { - return true - } - return (value as Record | null | undefined)?.[UNWIND_BRAND] === true + return value instanceof WebAssembly.Exception } diff --git a/test/filesystem.test.js b/test/filesystem.test.js index 19da1a8..f01cd49 100644 --- a/test/filesystem.test.js +++ b/test/filesystem.test.js @@ -116,7 +116,7 @@ describe('Filesystem', () => { const lua = await getLua() lua.writeFile('fs-probe.lua', 'return 1') - expect(lua.filesystem.analyzePath('/fs-probe.lua').exists).to.be.true + expect(lua.filesystem.readFile('/fs-probe.lua', { encoding: 'utf8' })).to.be.equal('return 1') }) it('path should expose the emscripten path helpers', async () => { diff --git a/utils/build-wasm.js b/utils/build-wasm.js index 1836927..9857339 100644 --- a/utils/build-wasm.js +++ b/utils/build-wasm.js @@ -47,6 +47,9 @@ try { } const dockerVolume = `${rootdir}:/wasmoon` -const command = `docker run --rm -v "${dockerVolume}" emscripten/emsdk /wasmoon/utils/build-wasm.sh ${args.join(' ')}` +// Pinned to the version the workflows in .github/ install, so a local build makes the same glue CI +// tests rather than whatever `latest` is today. +const EMSDK_VERSION = '7.0.0' +const command = `docker run --rm -v "${dockerVolume}" emscripten/emsdk:${EMSDK_VERSION} /wasmoon/utils/build-wasm.sh ${args.join(' ')}` execute(command) diff --git a/utils/build-wasm.sh b/utils/build-wasm.sh index ebde0ff..6eea05d 100755 --- a/utils/build-wasm.sh +++ b/utils/build-wasm.sh @@ -22,6 +22,7 @@ COMMON=( 'addFunction', \ 'removeFunction', \ 'FS', \ + 'NODEFS', \ 'PATH', \ 'ENV', \ 'getValue', \ From 96f9d740f8d8677587710cabebee874a315e7a0f Mon Sep 17 00:00:00 2001 From: ceifa Date: Thu, 19 Nov 2026 22:20:15 -0300 Subject: [PATCH 79/83] pin lua to the v5.5.1 tag It was on a commit between releases. CI now checks the submodule sits on a release tag of lua/lua, so it cannot drift back to one. --- .github/workflows/test.yml | 11 +++++++++++ lua | 2 +- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index b21e1c7..3157970 100755 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -25,6 +25,17 @@ jobs: with: node-version: ${{ matrix.node-version }} cache: npm + # The lua submodule follows release tags, never a commit in between them. Asked of the + # remote rather than the checkout, which fetches the submodule without its tags. + - name: Check the lua submodule is on a release tag + run: | + commit=$(git -C lua rev-parse HEAD) + tag=$(git ls-remote --tags https://github.com/lua/lua | awk -v c="$commit" '$1 == c { sub("refs/tags/", "", $2); sub(/\^\{\}$/, "", $2); print $2 }' | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | head -1) + if [ -z "$tag" ]; then + echo "lua is at $commit, which is not a release tag of lua/lua" >&2 + exit 1 + fi + echo "lua is at $tag" - run: npm ci - run: npm run lint:nofix - run: npm run build:wasm diff --git a/lua b/lua index c6b4848..7579fc9 160000 --- a/lua +++ b/lua @@ -1 +1 @@ -Subproject commit c6b484823806e08e1756b1a6066a3ace6f080fae +Subproject commit 7579fc9d7ed90240487251dfb69168f8e64e9294 From 2b90ae3210a31236f0498a02cd85cf4571da29a6 Mon Sep 17 00:00:00 2001 From: ceifa Date: Thu, 19 Nov 2026 22:50:03 -0300 Subject: [PATCH 80/83] build the bindings through locals the minifier can shorten The generated constructor spelled out this.exported( 147 times and this.wrapWithStringArguments( 37 times, and a minifier has to leave a method name alone. Two locals in the constructor take their place, so the named stores stay as they were and dist/index.js goes from 113.4 kB to 110.7 kB. The README size table was stale (108 + 194) and now carries the measured numbers. --- README.md | 4 +- src/bindings.gen.ts | 283 ++++++++++++++++++++------------------- utils/create-bindings.js | 9 +- 3 files changed, 153 insertions(+), 143 deletions(-) diff --git a/README.md b/README.md index d32cb3e..e42558d 100644 --- a/README.md +++ b/README.md @@ -285,8 +285,8 @@ Both minified, and wasmoon counted as its JS plus `glue.wasm`: | | wasmoon | fengari | | ----------- | ----------------- | ------- | -| **plain** | 302kB (108 + 194) | 228kB | -| **gzipped** | 128kB (34 + 94) | 74kB | +| **plain** | 305kB (111 + 194) | 228kB | +| **gzipped** | 129kB (35 + 94) | 74kB | Almost all of wasmoon's weight is the wasm, which is a separate file: it is fetched in parallel with your JS rather than parsed as part of it, and it caches on its own across releases of your app. diff --git a/src/bindings.gen.ts b/src/bindings.gen.ts index 3bca714..b1e8b52 100644 --- a/src/bindings.gen.ts +++ b/src/bindings.gen.ts @@ -163,150 +163,155 @@ export default abstract class LuaBindings { protected constructor(emscripten: LuaEmscriptenModule) { this.emscripten = emscripten - this.luaL_checkversion_ = this.exported('luaL_checkversion_') - this.luaL_getmetafield = this.wrapWithStringArguments(this.exported('luaL_getmetafield'), 'nnns') - this.luaL_callmeta = this.wrapWithStringArguments(this.exported('luaL_callmeta'), 'nnns') - this.luaL_argerror = this.wrapWithStringArguments(this.exported('luaL_argerror'), 'nnns') - this.luaL_typeerror = this.wrapWithStringArguments(this.exported('luaL_typeerror'), 'nnns') - this.luaL_checklstring = this.wrapWithStringArguments(this.exported('luaL_checklstring'), 'snnn') - this.luaL_optlstring = this.wrapWithStringArguments(this.exported('luaL_optlstring'), 'snnsn') - this.luaL_checknumber = this.exported('luaL_checknumber') - this.luaL_optnumber = this.exported('luaL_optnumber') - this.luaL_checkinteger = this.exported('luaL_checkinteger') - this.luaL_optinteger = this.exported('luaL_optinteger') - this.luaL_checkstack = this.wrapWithStringArguments(this.exported('luaL_checkstack'), 'nnns') - this.luaL_checktype = this.exported('luaL_checktype') - this.luaL_checkany = this.exported('luaL_checkany') - this.luaL_newmetatable = this.wrapWithStringArguments(this.exported('luaL_newmetatable'), 'nns') - this.luaL_setmetatable = this.wrapWithStringArguments(this.exported('luaL_setmetatable'), 'nns') - this.luaL_testudata = this.wrapWithStringArguments(this.exported('luaL_testudata'), 'nnns') - this.luaL_checkudata = this.wrapWithStringArguments(this.exported('luaL_checkudata'), 'nnns') - this.luaL_where = this.exported('luaL_where') - this.luaL_fileresult = this.wrapWithStringArguments(this.exported('luaL_fileresult'), 'nnns') - this.luaL_execresult = this.exported('luaL_execresult') - this.luaL_ref = this.exported('luaL_ref') - this.luaL_unref = this.exported('luaL_unref') - this.luaL_loadfilex = this.wrapWithStringArguments(this.exported('luaL_loadfilex'), 'nnss') - this.luaL_loadbufferx = this.wrapWithStringArguments(this.exported('luaL_loadbufferx'), 'nnSnSs') - this.luaL_loadstring = this.wrapWithStringArguments(this.exported('luaL_loadstring'), 'nns') - this.luaL_newstate = this.exported('luaL_newstate') - this.luaL_len = this.exported('luaL_len') - this.luaL_addgsub = this.wrapWithStringArguments(this.exported('luaL_addgsub'), 'nnsss') - this.luaL_gsub = this.wrapWithStringArguments(this.exported('luaL_gsub'), 'snsss') - this.luaL_setfuncs = this.exported('luaL_setfuncs') - this.luaL_getsubtable = this.wrapWithStringArguments(this.exported('luaL_getsubtable'), 'nnns') - this.luaL_traceback = this.wrapWithStringArguments(this.exported('luaL_traceback'), 'nnnsn') - this.luaL_requiref = this.wrapWithStringArguments(this.exported('luaL_requiref'), 'nnsnn') - this.luaL_buffinit = this.exported('luaL_buffinit') - this.luaL_prepbuffsize = this.wrapWithStringArguments(this.exported('luaL_prepbuffsize'), 'snn') - this.luaL_addlstring = this.wrapWithStringArguments(this.exported('luaL_addlstring'), 'nnsn') - this.luaL_addstring = this.wrapWithStringArguments(this.exported('luaL_addstring'), 'nns') - this.luaL_addvalue = this.exported('luaL_addvalue') - this.luaL_pushresult = this.exported('luaL_pushresult') - this.luaL_pushresultsize = this.exported('luaL_pushresultsize') - this.luaL_buffinitsize = this.wrapWithStringArguments(this.exported('luaL_buffinitsize'), 'snnn') - this.lua_newstate = this.exported('lua_newstate') - this.lua_close = this.exported('lua_close') - this.lua_newthread = this.exported('lua_newthread') - this.lua_closethread = this.exported('lua_closethread') - this.lua_atpanic = this.exported('lua_atpanic') - this.lua_version = this.exported('lua_version') - this.lua_absindex = this.exported('lua_absindex') - this.lua_gettop = this.exported('lua_gettop') - this.lua_settop = this.exported('lua_settop') - this.lua_pushvalue = this.exported('lua_pushvalue') - this.lua_rotate = this.exported('lua_rotate') - this.lua_copy = this.exported('lua_copy') - this.lua_checkstack = this.exported('lua_checkstack') - this.lua_xmove = this.exported('lua_xmove') - this.lua_isnumber = this.exported('lua_isnumber') - this.lua_isstring = this.exported('lua_isstring') - this.lua_iscfunction = this.exported('lua_iscfunction') - this.lua_isinteger = this.exported('lua_isinteger') - this.lua_isuserdata = this.exported('lua_isuserdata') - this.lua_type = this.exported('lua_type') - this.lua_typename = this.wrapWithStringArguments(this.exported('lua_typename'), 'snn') - this.lua_tonumberx = this.exported('lua_tonumberx') - this.lua_tointegerx = this.exported('lua_tointegerx') - this.lua_toboolean = this.exported('lua_toboolean') - this.lua_rawlen = this.exported('lua_rawlen') - this.lua_tocfunction = this.exported('lua_tocfunction') - this.lua_touserdata = this.exported('lua_touserdata') - this.lua_tothread = this.exported('lua_tothread') - this.lua_topointer = this.exported('lua_topointer') - this.lua_arith = this.exported('lua_arith') - this.lua_rawequal = this.exported('lua_rawequal') - this.lua_compare = this.exported('lua_compare') - this.lua_pushnil = this.exported('lua_pushnil') - this.lua_pushnumber = this.exported('lua_pushnumber') + // Locals rather than the methods themselves, which nearly every line below would otherwise + // spell out in full: a minifier shortens a local and has to leave a method name alone. + const raw = (name: string): Binding => this.exported(name) + const withStrings = (name: string, signature: string): Binding => this.wrapWithStringArguments(raw(name), signature) + + this.luaL_checkversion_ = raw('luaL_checkversion_') + this.luaL_getmetafield = withStrings('luaL_getmetafield', 'nnns') + this.luaL_callmeta = withStrings('luaL_callmeta', 'nnns') + this.luaL_argerror = withStrings('luaL_argerror', 'nnns') + this.luaL_typeerror = withStrings('luaL_typeerror', 'nnns') + this.luaL_checklstring = withStrings('luaL_checklstring', 'snnn') + this.luaL_optlstring = withStrings('luaL_optlstring', 'snnsn') + this.luaL_checknumber = raw('luaL_checknumber') + this.luaL_optnumber = raw('luaL_optnumber') + this.luaL_checkinteger = raw('luaL_checkinteger') + this.luaL_optinteger = raw('luaL_optinteger') + this.luaL_checkstack = withStrings('luaL_checkstack', 'nnns') + this.luaL_checktype = raw('luaL_checktype') + this.luaL_checkany = raw('luaL_checkany') + this.luaL_newmetatable = withStrings('luaL_newmetatable', 'nns') + this.luaL_setmetatable = withStrings('luaL_setmetatable', 'nns') + this.luaL_testudata = withStrings('luaL_testudata', 'nnns') + this.luaL_checkudata = withStrings('luaL_checkudata', 'nnns') + this.luaL_where = raw('luaL_where') + this.luaL_fileresult = withStrings('luaL_fileresult', 'nnns') + this.luaL_execresult = raw('luaL_execresult') + this.luaL_ref = raw('luaL_ref') + this.luaL_unref = raw('luaL_unref') + this.luaL_loadfilex = withStrings('luaL_loadfilex', 'nnss') + this.luaL_loadbufferx = withStrings('luaL_loadbufferx', 'nnSnSs') + this.luaL_loadstring = withStrings('luaL_loadstring', 'nns') + this.luaL_newstate = raw('luaL_newstate') + this.luaL_len = raw('luaL_len') + this.luaL_addgsub = withStrings('luaL_addgsub', 'nnsss') + this.luaL_gsub = withStrings('luaL_gsub', 'snsss') + this.luaL_setfuncs = raw('luaL_setfuncs') + this.luaL_getsubtable = withStrings('luaL_getsubtable', 'nnns') + this.luaL_traceback = withStrings('luaL_traceback', 'nnnsn') + this.luaL_requiref = withStrings('luaL_requiref', 'nnsnn') + this.luaL_buffinit = raw('luaL_buffinit') + this.luaL_prepbuffsize = withStrings('luaL_prepbuffsize', 'snn') + this.luaL_addlstring = withStrings('luaL_addlstring', 'nnsn') + this.luaL_addstring = withStrings('luaL_addstring', 'nns') + this.luaL_addvalue = raw('luaL_addvalue') + this.luaL_pushresult = raw('luaL_pushresult') + this.luaL_pushresultsize = raw('luaL_pushresultsize') + this.luaL_buffinitsize = withStrings('luaL_buffinitsize', 'snnn') + this.lua_newstate = raw('lua_newstate') + this.lua_close = raw('lua_close') + this.lua_newthread = raw('lua_newthread') + this.lua_closethread = raw('lua_closethread') + this.lua_atpanic = raw('lua_atpanic') + this.lua_version = raw('lua_version') + this.lua_absindex = raw('lua_absindex') + this.lua_gettop = raw('lua_gettop') + this.lua_settop = raw('lua_settop') + this.lua_pushvalue = raw('lua_pushvalue') + this.lua_rotate = raw('lua_rotate') + this.lua_copy = raw('lua_copy') + this.lua_checkstack = raw('lua_checkstack') + this.lua_xmove = raw('lua_xmove') + this.lua_isnumber = raw('lua_isnumber') + this.lua_isstring = raw('lua_isstring') + this.lua_iscfunction = raw('lua_iscfunction') + this.lua_isinteger = raw('lua_isinteger') + this.lua_isuserdata = raw('lua_isuserdata') + this.lua_type = raw('lua_type') + this.lua_typename = withStrings('lua_typename', 'snn') + this.lua_tonumberx = raw('lua_tonumberx') + this.lua_tointegerx = raw('lua_tointegerx') + this.lua_toboolean = raw('lua_toboolean') + this.lua_rawlen = raw('lua_rawlen') + this.lua_tocfunction = raw('lua_tocfunction') + this.lua_touserdata = raw('lua_touserdata') + this.lua_tothread = raw('lua_tothread') + this.lua_topointer = raw('lua_topointer') + this.lua_arith = raw('lua_arith') + this.lua_rawequal = raw('lua_rawequal') + this.lua_compare = raw('lua_compare') + this.lua_pushnil = raw('lua_pushnil') + this.lua_pushnumber = raw('lua_pushnumber') this.lua_pushinteger = this.withIntegerArgument('lua_pushinteger', true) - this.lua_pushlstring = this.exported('lua_pushlstring') - this.lua_pushcclosure = this.exported('lua_pushcclosure') - this.lua_pushboolean = this.exported('lua_pushboolean') - this.lua_pushlightuserdata = this.exported('lua_pushlightuserdata') - this.lua_pushthread = this.exported('lua_pushthread') - this.lua_getglobal = this.wrapWithStringArguments(this.exported('lua_getglobal'), 'nns') - this.lua_gettable = this.exported('lua_gettable') - this.lua_getfield = this.wrapWithStringArguments(this.exported('lua_getfield'), 'nnns') + this.lua_pushlstring = raw('lua_pushlstring') + this.lua_pushcclosure = raw('lua_pushcclosure') + this.lua_pushboolean = raw('lua_pushboolean') + this.lua_pushlightuserdata = raw('lua_pushlightuserdata') + this.lua_pushthread = raw('lua_pushthread') + this.lua_getglobal = withStrings('lua_getglobal', 'nns') + this.lua_gettable = raw('lua_gettable') + this.lua_getfield = withStrings('lua_getfield', 'nnns') this.lua_geti = this.withIntegerArgument('lua_geti') - this.lua_rawget = this.exported('lua_rawget') + this.lua_rawget = raw('lua_rawget') this.lua_rawgeti = this.withIntegerArgument('lua_rawgeti') - this.lua_rawgetp = this.exported('lua_rawgetp') - this.lua_createtable = this.exported('lua_createtable') - this.lua_newuserdatauv = this.exported('lua_newuserdatauv') - this.lua_getmetatable = this.exported('lua_getmetatable') - this.lua_getiuservalue = this.exported('lua_getiuservalue') - this.lua_setglobal = this.wrapWithStringArguments(this.exported('lua_setglobal'), 'nns') - this.lua_settable = this.exported('lua_settable') - this.lua_setfield = this.wrapWithStringArguments(this.exported('lua_setfield'), 'nnns') + this.lua_rawgetp = raw('lua_rawgetp') + this.lua_createtable = raw('lua_createtable') + this.lua_newuserdatauv = raw('lua_newuserdatauv') + this.lua_getmetatable = raw('lua_getmetatable') + this.lua_getiuservalue = raw('lua_getiuservalue') + this.lua_setglobal = withStrings('lua_setglobal', 'nns') + this.lua_settable = raw('lua_settable') + this.lua_setfield = withStrings('lua_setfield', 'nnns') this.lua_seti = this.withIntegerArgument('lua_seti') - this.lua_rawset = this.exported('lua_rawset') + this.lua_rawset = raw('lua_rawset') this.lua_rawseti = this.withIntegerArgument('lua_rawseti') - this.lua_rawsetp = this.exported('lua_rawsetp') - this.lua_setmetatable = this.exported('lua_setmetatable') - this.lua_setiuservalue = this.exported('lua_setiuservalue') - this.lua_callk = this.exported('lua_callk') - this.lua_pcallk = this.exported('lua_pcallk') - this.lua_load = this.wrapWithStringArguments(this.exported('lua_load'), 'nnnnss') - this.lua_dump = this.exported('lua_dump') - this.lua_yieldk = this.exported('lua_yieldk') - this.lua_resume = this.exported('lua_resume') - this.lua_status = this.exported('lua_status') - this.lua_isyieldable = this.exported('lua_isyieldable') - this.lua_setwarnf = this.exported('lua_setwarnf') - this.lua_warning = this.wrapWithStringArguments(this.exported('lua_warning'), 'nnsn') - this.lua_error = this.exported('lua_error') - this.lua_next = this.exported('lua_next') - this.lua_concat = this.exported('lua_concat') - this.lua_len = this.exported('lua_len') - this.lua_stringtonumber = this.wrapWithStringArguments(this.exported('lua_stringtonumber'), 'nns') - this.lua_getallocf = this.exported('lua_getallocf') - this.lua_setallocf = this.exported('lua_setallocf') - this.lua_toclose = this.exported('lua_toclose') - this.lua_closeslot = this.exported('lua_closeslot') - this.lua_getstack = this.exported('lua_getstack') - this.lua_getinfo = this.wrapWithStringArguments(this.exported('lua_getinfo'), 'nnsn') - this.lua_getlocal = this.wrapWithStringArguments(this.exported('lua_getlocal'), 'snnn') - this.lua_setlocal = this.wrapWithStringArguments(this.exported('lua_setlocal'), 'snnn') - this.lua_getupvalue = this.wrapWithStringArguments(this.exported('lua_getupvalue'), 'snnn') - this.lua_setupvalue = this.wrapWithStringArguments(this.exported('lua_setupvalue'), 'snnn') - this.lua_upvalueid = this.exported('lua_upvalueid') - this.lua_upvaluejoin = this.exported('lua_upvaluejoin') - this.lua_sethook = this.exported('lua_sethook') - this.lua_gethook = this.exported('lua_gethook') - this.lua_gethookmask = this.exported('lua_gethookmask') - this.lua_gethookcount = this.exported('lua_gethookcount') - this.luaopen_base = this.exported('luaopen_base') - this.luaopen_package = this.exported('luaopen_package') - this.luaopen_coroutine = this.exported('luaopen_coroutine') - this.luaopen_debug = this.exported('luaopen_debug') - this.luaopen_io = this.exported('luaopen_io') - this.luaopen_math = this.exported('luaopen_math') - this.luaopen_os = this.exported('luaopen_os') - this.luaopen_string = this.exported('luaopen_string') - this.luaopen_table = this.exported('luaopen_table') - this.luaopen_utf8 = this.exported('luaopen_utf8') - this.luaL_openselectedlibs = this.exported('luaL_openselectedlibs') + this.lua_rawsetp = raw('lua_rawsetp') + this.lua_setmetatable = raw('lua_setmetatable') + this.lua_setiuservalue = raw('lua_setiuservalue') + this.lua_callk = raw('lua_callk') + this.lua_pcallk = raw('lua_pcallk') + this.lua_load = withStrings('lua_load', 'nnnnss') + this.lua_dump = raw('lua_dump') + this.lua_yieldk = raw('lua_yieldk') + this.lua_resume = raw('lua_resume') + this.lua_status = raw('lua_status') + this.lua_isyieldable = raw('lua_isyieldable') + this.lua_setwarnf = raw('lua_setwarnf') + this.lua_warning = withStrings('lua_warning', 'nnsn') + this.lua_error = raw('lua_error') + this.lua_next = raw('lua_next') + this.lua_concat = raw('lua_concat') + this.lua_len = raw('lua_len') + this.lua_stringtonumber = withStrings('lua_stringtonumber', 'nns') + this.lua_getallocf = raw('lua_getallocf') + this.lua_setallocf = raw('lua_setallocf') + this.lua_toclose = raw('lua_toclose') + this.lua_closeslot = raw('lua_closeslot') + this.lua_getstack = raw('lua_getstack') + this.lua_getinfo = withStrings('lua_getinfo', 'nnsn') + this.lua_getlocal = withStrings('lua_getlocal', 'snnn') + this.lua_setlocal = withStrings('lua_setlocal', 'snnn') + this.lua_getupvalue = withStrings('lua_getupvalue', 'snnn') + this.lua_setupvalue = withStrings('lua_setupvalue', 'snnn') + this.lua_upvalueid = raw('lua_upvalueid') + this.lua_upvaluejoin = raw('lua_upvaluejoin') + this.lua_sethook = raw('lua_sethook') + this.lua_gethook = raw('lua_gethook') + this.lua_gethookmask = raw('lua_gethookmask') + this.lua_gethookcount = raw('lua_gethookcount') + this.luaopen_base = raw('luaopen_base') + this.luaopen_package = raw('luaopen_package') + this.luaopen_coroutine = raw('luaopen_coroutine') + this.luaopen_debug = raw('luaopen_debug') + this.luaopen_io = raw('luaopen_io') + this.luaopen_math = raw('luaopen_math') + this.luaopen_os = raw('luaopen_os') + this.luaopen_string = raw('luaopen_string') + this.luaopen_table = raw('luaopen_table') + this.luaopen_utf8 = raw('luaopen_utf8') + this.luaL_openselectedlibs = raw('luaL_openselectedlibs') } /** The wasm export `name`. */ diff --git a/utils/create-bindings.js b/utils/create-bindings.js index bbe41b8..03a0ae4 100644 --- a/utils/create-bindings.js +++ b/utils/create-bindings.js @@ -163,9 +163,9 @@ for (const fn of bound) { if (integerTwin) { assignments.push(` this.${fn.name} = this.withIntegerArgument('${fn.name}'${fn.params.length === 2 ? ', true' : ''})`) } else if (signature.includes('s') && !override.raw) { - assignments.push(` this.${fn.name} = this.wrapWithStringArguments(this.exported('${fn.name}'), '${signature}')`) + assignments.push(` this.${fn.name} = withStrings('${fn.name}', '${signature}')`) } else { - assignments.push(` this.${fn.name} = this.exported('${fn.name}')`) + assignments.push(` this.${fn.name} = raw('${fn.name}')`) } } @@ -191,6 +191,11 @@ ${declarations.join('\n')} protected constructor(emscripten: LuaEmscriptenModule) { this.emscripten = emscripten + // Locals rather than the methods themselves, which nearly every line below would otherwise + // spell out in full: a minifier shortens a local and has to leave a method name alone. + const raw = (name: string): Binding => this.exported(name) + const withStrings = (name: string, signature: string): Binding => this.wrapWithStringArguments(raw(name), signature) + ${assignments.join('\n')} } From e02ab18742cc78da90a8487ca5f767494298785b Mon Sep 17 00:00:00 2001 From: ceifa Date: Fri, 20 Nov 2026 12:37:46 -0300 Subject: [PATCH 81/83] add fs: 'none', a glue without the filesystem, and load every glue on demand --- bench/utils.js | 1 + rolldown.config.ts | 28 +++++++---- src/declarations.d.ts | 4 ++ src/module.ts | 74 +++++++++++++++++++++------ src/runtime.ts | 8 +-- test/browser.test.js | 24 +++++++-- test/bundling.test.js | 19 +++++-- test/no-filesystem.test.js | 100 +++++++++++++++++++++++++++++++++++++ utils/build-wasm.sh | 100 ++++++++++++++++++++----------------- utils/no-filesystem.js | 64 ++++++++++++++++++++++++ 10 files changed, 340 insertions(+), 82 deletions(-) create mode 100644 test/no-filesystem.test.js create mode 100644 utils/no-filesystem.js diff --git a/bench/utils.js b/bench/utils.js index 2cc79e3..2aae839 100644 --- a/bench/utils.js +++ b/bench/utils.js @@ -72,6 +72,7 @@ Options: export function printArtifactSizes() { const artifacts = [ { label: 'glue.js', path: path.resolve(import.meta.dirname, '../build/glue.js') }, + { label: 'glue.js (fs: none)', path: path.resolve(import.meta.dirname, '../build/none/glue.js') }, { label: 'glue.wasm', path: path.resolve(import.meta.dirname, '../build/glue.wasm') }, ] diff --git a/rolldown.config.ts b/rolldown.config.ts index 96f13e1..a7d3cb5 100644 --- a/rolldown.config.ts +++ b/rolldown.config.ts @@ -7,13 +7,21 @@ export default defineConfig({ // than bundling a second copy of it, and is minified the same way. input: { index: './src/index.ts', cli: './src/cli.js' }, output: { - // A directory rather than a single file, because the host filesystem glue that module.ts - // imports on demand has to stay a chunk of its own: a browser bundle then leaves it alone, - // and Node loads it only when someone asks for `fs: 'host'`. + // A directory rather than a single file, because each glue module.ts imports on demand has + // to stay a chunk of its own: a load fetches only the one its `fs` asks for, and a browser + // bundle leaves the Node only host one alone. dir: 'dist', entryFileNames: '[name].js', - // Named rather than hashed, so the `browser` field in package.json can point at it. - chunkFileNames: 'glue-host.js', + // Named rather than hashed, so the `browser` field in package.json can point at the host + // one. Nothing else is split off, and a chunk that is not a glue fails the build here + // rather than shipping under a glue's name. + chunkFileNames: ({ facadeModuleId }) => { + const glue = /\/build\/(?:(host|none)\/)?glue\.js$/.exec(facadeModuleId ?? '') + if (!glue) { + throw new Error(`unexpected chunk for ${facadeModuleId}: only the glues are split off`) + } + return `glue-${glue[1] ?? 'memory'}.js` + }, format: 'esm', sourcemap: true, // The glue arrives from emcc already minified and rolldown would otherwise re-print it @@ -77,8 +85,8 @@ export default defineConfig({ generateBundle(_options, bundle) { // Rewritten through the emitted files rather than the written ones, because // `chunk.map` is a snapshot of the Rust side and mutating it does not carry over. - // Counted per sourcemap: there is one for each glue now, and a single flag would - // call it a success while the other still shipped its copy. + // Counted per sourcemap: there is one for each glue, and a single flag would call + // it a success while another still shipped its copy. let trimmed = 0 for (const chunk of Object.values(bundle)) { const map = bundle[`${chunk.fileName}.map`] @@ -110,9 +118,9 @@ export default defineConfig({ map.source = JSON.stringify(parsed) trimmed++ } - // One for the entry's inlined glue, one for the host glue chunk. - if (trimmed !== 2) { - this.error(`expected to trim the glue out of 2 sourcemaps, trimmed ${trimmed}`) + // One for each glue chunk. + if (trimmed !== 3) { + this.error(`expected to trim the glue out of 3 sourcemaps, trimmed ${trimmed}`) } }, }, diff --git a/src/declarations.d.ts b/src/declarations.d.ts index 012517d..5f78bce 100644 --- a/src/declarations.d.ts +++ b/src/declarations.d.ts @@ -10,6 +10,10 @@ declare module '*/glue.js' { const initWasmModule: ( moduleArg?: Partial> & { preRun?: (module: import('./module').LuaEmscriptenModule) => void + // Read by the glue without a filesystem only; see utils/no-filesystem.js. + stdin?: (() => number | null) | null + stdout?: ((charCode: number | null) => void) | null + stderr?: ((charCode: number | null) => void) | null }, ) => Promise export default initWasmModule diff --git a/src/module.ts b/src/module.ts index beb81af..89534a7 100755 --- a/src/module.ts +++ b/src/module.ts @@ -2,7 +2,6 @@ // lists "emscripten" in their own tsconfig `types`, so utils/reference-types.js puts a // `/// ` at the top of the emitted declarations to cover everyone // else. tsc drops the directive when it is written here, hence the build step. -import initWasmModule from '../build/glue.js' import LuaBindings from './bindings.gen' import { canSuspend, limitError, type PendingSuspend, settleOrInterrupt, type SettleOutcome, yieldToEventLoop } from './async' import type Thread from './thread' @@ -21,8 +20,11 @@ export type EnvironmentVariables = Record * - `'host'`: the real filesystem, through Node. Paths, the working directory, symlinks and * permissions are the host's own, because every operation goes straight to `node:fs`. Node only, * and no sandbox: Lua can read and write anything the process can. + * - `'none'`: no filesystem at all, for a smaller download. Opening, removing or renaming a file + * fails, so does `require` of anything but a preloaded module, and the runtime's file methods + * throw. Stdio still works, through the stdin, stdout and stderr options. */ -export type LuaFileSystem = 'memory' | 'host' +export type LuaFileSystem = 'memory' | 'host' | 'none' /** Emscripten's own path helpers, which work on the virtual filesystem rather than the host one. */ export interface EmscriptenPath { @@ -40,6 +42,7 @@ export interface LuaEmscriptenModule extends EmscriptenModule { removeFunction: typeof removeFunction setValue: typeof setValue getValue: typeof getValue + // FS, NODEFS and PATH are missing from the glue for `fs: 'none'`. FS: typeof FS // Exported by the build, since Emscripten 7 no longer hangs the backends off FS.filesystems. NODEFS: Emscripten.FileSystemType @@ -185,7 +188,7 @@ interface ResolvedMount { // The only rule about `mounts` that is not about a single mount, so both the option and the method // report it with one voice. -const MOUNTS_NEED_MEMORY_FS = `mounts belong to fs: 'memory'; with 'host' every host path is already reachable` +const MOUNTS_NEED_MEMORY_FS = `mounts belong to fs: 'memory'; with 'host' every host path is already reachable, and 'none' has nothing to mount into` /** * Synchronous and lazy, which is what lets a mount be added after loading without the load path @@ -267,9 +270,9 @@ function mountHostDirectory(emscripten: LuaEmscriptenModule, { virtualPath, host interface PreRunConfig { env: EnvironmentVariables | undefined mounts: readonly ResolvedMount[] - stdin: LuaModuleOptions['stdin'] - stdout: LuaModuleOptions['stdout'] - stderr: LuaModuleOptions['stderr'] + stdin?: LuaModuleOptions['stdin'] + stdout?: LuaModuleOptions['stdout'] + stderr?: LuaModuleOptions['stderr'] } interface ReferenceEntry { @@ -312,7 +315,7 @@ export default class LuaModule extends LuaBindings { if (fs === 'host' && !isNode) { throw new Error(`fs: 'host' is the real filesystem, which only Node has; elsewhere use the default 'memory' one`) } - if (fs === 'host' && mountEntries.length > 0) { + if (fs !== 'memory' && mountEntries.length > 0) { throw new Error(MOUNTS_NEED_MEMORY_FS) } @@ -337,12 +340,33 @@ export default class LuaModule extends LuaBindings { } } - const preRun = createPreRun({ env: opts.env, mounts, stdin: opts.stdin, stdout: opts.stdout, stderr: opts.stderr }) - - // Two glues over the one wasm, differing only in their filesystem (see - // utils/build-wasm.sh). The host one is imported on demand, both because it throws outside - // Node and so that a browser bundle leaves it in a chunk it never loads. - const init = fs === 'host' ? (await import('../build/host/glue.js')).default : initWasmModule + // Without a filesystem there is no FS.init to hand stdio to, so that glue takes it directly, + // with the defaults the other glues fall back to when given nothing. + const stdio = + fs === 'none' + ? { + stdin: createInputReader(opts.stdin), + stdout: createOutputWriter(opts.stdout ?? ((line) => console.log(line))), + stderr: createOutputWriter(opts.stderr ?? printErr), + } + : {} + const preRun = createPreRun({ + env: opts.env, + mounts, + ...(fs === 'none' ? {} : { stdin: opts.stdin, stdout: opts.stdout, stderr: opts.stderr }), + }) + + // Three glues over the one wasm, differing only in their filesystem (see + // utils/build-wasm.sh). Each is a chunk of its own, imported on demand, so a load only + // downloads the one it asked for -- and a browser bundle never loads the host one, which + // throws outside Node. + const init = ( + fs === 'host' + ? await import('../build/host/glue.js') + : fs === 'none' + ? await import('../build/none/glue.js') + : await import('../build/glue.js') + ).default if (typeof init !== 'function') { // The `browser` field points bundlers at a stub, since the glue only runs under Node. throw new Error(`fs: 'host' needs glue-host.js, which the bundle replaced with a stub because it targets the browser`) @@ -350,7 +374,7 @@ export default class LuaModule extends LuaBindings { const load = async (wasmFile?: string): Promise => { return new LuaModule( - await init({ ...(wasmFile === undefined ? {} : { locateFile: () => wasmFile }), preRun, printErr }), + await init({ ...(wasmFile === undefined ? {} : { locateFile: () => wasmFile }), preRun, printErr, ...stdio }), opts.onWarn, fs, mounts, @@ -598,7 +622,7 @@ export default class LuaModule extends LuaBindings { * does at load time and with the same checks. Node only, and only with `fs: 'memory'`. */ public mount(virtualPath: string, hostPath: string): void { - if (this.fs === 'host') { + if (this.fs !== 'memory') { throw new Error(MOUNTS_NEED_MEMORY_FS) } @@ -608,9 +632,27 @@ export default class LuaModule extends LuaBindings { this.mounts.push(mount) } + /** The emscripten module's `FS`, which a module loaded with `fs: 'none'` does not have. */ + public get filesystem(): EmscriptenFS { + this.assertFilesystem() + return this.emscripten.FS + } + + /** The emscripten module's `PATH`, which comes and goes with the filesystem. */ + public get path(): EmscriptenPath { + this.assertFilesystem() + return this.emscripten.PATH + } + + private assertFilesystem(): void { + if (this.fs === 'none') { + throw new Error(`there is no filesystem with fs: 'none'; load with 'memory' (the default) or 'host' to have one`) + } + } + /** Detaches a {@link LuaModule.mount}, leaving its mount point behind as an empty directory. */ public unmount(virtualPath: string): void { - this.emscripten.FS.unmount(virtualPath) + this.filesystem.unmount(virtualPath) // Dropped only once Emscripten agrees it was a mount point, so a failed unmount leaves the // bookkeeping matching what is actually mounted. const index = this.mounts.findIndex((mount) => mount.virtualPath === virtualPath) diff --git a/src/runtime.ts b/src/runtime.ts index 6e0d932..23934b0 100755 --- a/src/runtime.ts +++ b/src/runtime.ts @@ -77,9 +77,11 @@ export default class LuaRuntime { } public exists(path: string): boolean { + // Outside the try, so that having no filesystem is an error rather than a missing file. + const filesystem = this.filesystem // Emscripten 7 dropped FS.analyzePath, which did this same lookup and caught its error. try { - this.filesystem.lookupPath(path, { follow: true }) + filesystem.lookupPath(path, { follow: true }) return true } catch { return false @@ -108,10 +110,10 @@ export default class LuaRuntime { /** Emscripten's own filesystem API, for everything the methods above do not cover. */ public get filesystem(): EmscriptenFS { - return this.module.emscripten.FS + return this.module.filesystem } public get path(): EmscriptenPath { - return this.module.emscripten.PATH + return this.module.path } } diff --git a/test/browser.test.js b/test/browser.test.js index 331f3a6..cbeae39 100644 --- a/test/browser.test.js +++ b/test/browser.test.js @@ -5,6 +5,7 @@ import { join } from 'node:path' import { fileURLToPath } from 'node:url' import { expect } from 'chai' import { chromium } from 'playwright' +import { rolldown } from 'rolldown' const DIST_DIR = fileURLToPath(new URL('../dist', import.meta.url)) @@ -162,6 +163,19 @@ describe('Browser environment', () => { expect(result).to.eql({ fair: true, error: 'LuaTimeoutError', other: 42 }) }) + it('fs: none downloads its own glue and not the default one', async function () { + this.timeout(30_000) + const result = await runInBrowser(` + const lua = await LuaRuntime.load({ fs: 'none' }) + return await lua.createState().doString('return 6 * 7') + `) + + expect(result).to.be.equal(42) + const glues = requested.filter((url) => /\/glue-\w+\.js$/.test(url)).map((url) => url.split('/').pop()) + expect(glues).to.be.deep.equal(['glue-none.js']) + expectNoExternalRequests() + }) + it('load Lua engine in browser should succeed', async function () { this.timeout(30_000) const result = await runInBrowser(` @@ -343,12 +357,16 @@ describe('Browser environment', () => { /** * A single self contained HTML file, the only shape that works from `file:`: Chromium refuses to - * load an ES module over that protocol, so the bundle is inlined. It is already a single chunk, and - * its exported bindings are in scope of the inline module. + * load an ES module over that protocol, so the bundle is inlined. Rebundled into one chunk first, + * glues included, the way a consumer's bundler builds such a page; its exported bindings are then + * in scope of the inline module. */ async function writeInlinedPage() { const tempDir = await mkdtemp(join(tmpdir(), 'wasmoon-file-')) - const bundle = await readFile(join(DIST_DIR, 'index.js'), 'utf8') + const build = await rolldown({ input: join(DIST_DIR, 'index.js'), platform: 'browser' }) + const { output } = await build.generate({ format: 'esm', codeSplitting: false }) + await build.close() + const bundle = output[0].code const htmlFile = join(tempDir, 'page.html') await writeFile( diff --git a/test/bundling.test.js b/test/bundling.test.js index 610dc2e..d594ece 100644 --- a/test/bundling.test.js +++ b/test/bundling.test.js @@ -26,12 +26,12 @@ describe('Bundling', () => { input: join(DIST_DIR, 'index.js'), external: ['node:module'], }) - // A directory rather than a single file, because the host filesystem glue stays a chunk of - // its own -- which is also how a consumer has to bundle us when they target Node. + // A directory rather than a single file, because each glue stays a chunk of its own -- + // which is also how a consumer has to bundle us when they target Node. await bundle.write({ dir: tempDir, entryFileNames: 'index.js', - chunkFileNames: 'glue-host.js', + chunkFileNames: '[name]-[hash].js', format: 'esm', minify: true, }) @@ -64,6 +64,19 @@ describe('Bundling', () => { expect(await readFile(join(DIST_DIR, 'index.js'), 'utf8')).to.include(stubbed[0].replace('./dist/', './')) }) + it('every glue is a chunk of its own, so a load only downloads the one it uses', async () => { + // Emscripten resolves the wasm next to the glue, which is how a glue is told apart. + const resolvesWasm = /new URL\(\s*['"`]glue\.wasm['"`]/ + const glues = ['glue-memory.js', 'glue-host.js', 'glue-none.js'] + const index = await readFile(join(DIST_DIR, 'index.js'), 'utf8') + + expect(index).to.not.match(resolvesWasm) + for (const glue of glues) { + expect(index).to.include(`./${glue}`) + expect(await readFile(join(DIST_DIR, glue), 'utf8')).to.match(resolvesWasm) + } + }) + it('minifying the bundle renames the unwind classes', async () => { // The premise of the tests below: a check by class name has nothing left to match on. const code = await readFile(join(tempDir, 'index.js'), 'utf8') diff --git a/test/no-filesystem.test.js b/test/no-filesystem.test.js new file mode 100644 index 0000000..c7a12f6 --- /dev/null +++ b/test/no-filesystem.test.js @@ -0,0 +1,100 @@ +import { expect } from 'chai' +import { LuaRuntime } from '../dist/index.js' + +const NO_FILESYSTEM = /there is no filesystem with fs: 'none'/ + +describe('No filesystem', () => { + let lua + + before(async () => { + lua = await LuaRuntime.load({ fs: 'none' }) + }) + + it('should run lua', async () => { + using state = lua.createState() + + expect(await state.doString('return string.format("%d %.1f", 42, 1.5)')).to.be.equal('42 1.5') + }) + + it('should report the filesystem it was loaded with', () => { + expect(lua.module.fs).to.be.equal('none') + }) + + it('opening a file should fail rather than hand back a handle', async () => { + using state = lua.createState() + + const message = await state.doString('local file, message = io.open("test.lua", "w") return file == nil and message') + + expect(message).to.be.equal('test.lua: Function not implemented') + }) + + it('removing or renaming a file should fail rather than claim to have done it', async () => { + using state = lua.createState() + + const results = await state.doString('return { os.remove("a") ~= nil, os.rename("a", "b") ~= nil }') + + expect(results).to.be.deep.equal([false, false]) + }) + + it('require should still find a preloaded module', async () => { + using state = lua.createState() + + const value = await state.doString('package.preload.answer = function() return 42 end return require("answer")') + + expect(value).to.be.equal(42) + }) + + it('doFile should throw', async () => { + using state = lua.createState() + + await expect(state.doFile('init.lua')).to.eventually.be.rejectedWith(/cannot open init\.lua/) + }) + + it('the runtime file methods should throw', () => { + expect(() => lua.writeFile('a.lua', 'return 1')).to.throw(NO_FILESYSTEM) + expect(() => lua.exists('a.lua')).to.throw(NO_FILESYSTEM) + expect(() => lua.filesystem).to.throw(NO_FILESYSTEM) + expect(() => lua.path).to.throw(NO_FILESYSTEM) + expect(() => lua.unmount('/scripts')).to.throw(NO_FILESYSTEM) + }) + + it('mounts should be refused', async () => { + expect(() => lua.mount('/scripts', '.')).to.throw(/mounts belong to fs: 'memory'/) + await expect(LuaRuntime.load({ fs: 'none', mounts: { '/scripts': '.' } })).to.eventually.be.rejectedWith( + /mounts belong to fs: 'memory'/, + ) + }) + + it('stdio should go through the callbacks', async () => { + const output = [] + const chunks = ['first\nsecond\n'] + const runtime = await LuaRuntime.load({ + fs: 'none', + stdin: () => chunks.shift() ?? '', + stdout: (content) => output.push(['stdout', content]), + stderr: (content) => output.push(['stderr', content]), + }) + using state = runtime.createState() + + const lines = await state.doString(` + print("héllo", 1) + io.stderr:write("oops\\n") + io.write("no newline") io.flush() + return { io.read("l"), io.read("l"), io.read("l") } + `) + await Promise.resolve() + + expect(lines).to.be.deep.equal(['first', 'second']) + expect(output).to.be.deep.equal([ + ['stdout', 'héllo\t1'], + ['stderr', 'oops'], + ['stdout', 'no newline'], + ]) + }) + + it('stdin should be at its end when there is no callback', async () => { + using state = lua.createState() + + expect(await state.doString('return io.read("l") == nil')).to.be.true + }) +}) diff --git a/utils/build-wasm.sh b/utils/build-wasm.sh index 6eea05d..27fe662 100755 --- a/utils/build-wasm.sh +++ b/utils/build-wasm.sh @@ -1,53 +1,31 @@ #!/bin/bash -e cd $(dirname $0) -mkdir -p ../build/host +mkdir -p ../build/host ../build/none LUA_SRC="$(ls ../lua/*.c | grep -v "luac.c" | grep -v "lua.c" | tr "\n" " ") ../src/native/wasmoon.c" if [ "$1" == "dev" ]; then - extension=(-O0 -g3 -s ASSERTIONS=1 -s SAFE_HEAP=1 -s STACK_OVERFLOW_CHECK=2) + # With assertions the filesystem glues export strerror for their error messages, and every glue + # has to export it for them all to share one wasm. + extension=(-O0 -g3 -s ASSERTIONS=1 -s SAFE_HEAP=1 -s STACK_OVERFLOW_CHECK=2 -Wl,--export=strerror) else extension=(-Oz -DLUA_USE_JUMPTABLE=0 -s BINARYEN_EXTRA_PASSES=gufa-optimizing,converge) fi -# Everything that is not about the filesystem, shared by both glues below so they can share one -# `glue.wasm`. +# What the JS side reaches into on every glue. The filesystem glues add FS, NODEFS and PATH to it. +RUNTIME_METHODS="'addFunction', 'removeFunction', 'ENV', 'getValue', 'setValue', 'lengthBytesUTF8', \ + 'stringToUTF8', 'stringToNewUTF8', 'stringToUTF8OnStack', 'stackSave', 'stackRestore', \ + 'UTF8ToString', 'HEAPU8', 'HEAPU32'" +INCOMING_API="'locateFile', 'preRun', 'print', 'printErr'" + +# Everything that is not about the filesystem, shared by all three glues below so they can share +# one `glue.wasm`. COMMON=( -s WASM=1 -s SUPPORT_LONGJMP=wasm -I../lua "${extension[@]}" - -s EXPORTED_RUNTIME_METHODS="[ - 'addFunction', \ - 'removeFunction', \ - 'FS', \ - 'NODEFS', \ - 'PATH', \ - 'ENV', \ - 'getValue', \ - 'setValue', \ - 'lengthBytesUTF8', \ - 'stringToUTF8', \ - 'stringToNewUTF8', \ - 'stringToUTF8OnStack', \ - 'stackSave', \ - 'stackRestore', \ - 'UTF8ToString', \ - 'HEAPU8', \ - 'HEAPU32' - ]" - -s DEFAULT_LIBRARY_FUNCS_TO_INCLUDE="[ - '\$FS_mkdirTree', \ - '\$PATH', \ - '\$PATH_FS' - ]" - -s INCOMING_MODULE_JS_API="[ - 'locateFile', \ - 'preRun', \ - 'print', \ - 'printErr' \ - ]" -s MODULARIZE=1 -s ALLOW_TABLE_GROWTH=1 -s EXPORT_NAME="initWasmModule" @@ -63,22 +41,34 @@ COMMON=( # and the JS side never caches a heap view across a call that can grow it. -s INITIAL_HEAP=1MB # The engines package.json promises, so the glue carries no fallbacks for older ones. The browser - # minimums go on the web glue alone below: the host glue is Node only and would warn about them. + # minimums are in BROWSERS below. -s MIN_NODE_VERSION=260000 # The Lua C API and the functions of src/native/wasmoon.c, as listed by create-bindings.js from # the headers. build-wasm.js runs it ahead of this script. -s EXPORTED_FUNCTIONS=@../build/exported-functions.json ) +FILESYSTEM=( + -s EXPORTED_RUNTIME_METHODS="[$RUNTIME_METHODS, 'FS', 'NODEFS', 'PATH']" + -s DEFAULT_LIBRARY_FUNCS_TO_INCLUDE="['\$FS_mkdirTree', '\$PATH', '\$PATH_FS']" + -s INCOMING_MODULE_JS_API="[$INCOMING_API]" +) +# The engines package.json promises for the browser. Only on the glues that run there: the host +# glue is Node only and would warn about them. +BROWSERS=( + -s MIN_CHROME_VERSION=134 + -s MIN_FIREFOX_VERSION=138 + -s MIN_SAFARI_VERSION=260000 +) + # The default glue, for every environment. Its filesystem is Emscripten's in-memory one, and # -lnodefs.js adds the NODEFS backend so a host directory can be mounted into it (LuaModuleOptions # `mounts`). Nothing here reaches the host on its own. emcc "${COMMON[@]}" \ + "${FILESYSTEM[@]}" \ + "${BROWSERS[@]}" \ -lnodefs.js \ -s ENVIRONMENT="web,worker,node" \ - -s MIN_CHROME_VERSION=134 \ - -s MIN_FIREFOX_VERSION=138 \ - -s MIN_SAFARI_VERSION=260000 \ -o ../build/glue.js \ ${LUA_SRC} @@ -87,19 +77,35 @@ emcc "${COMMON[@]}" \ # permissions are the host's rather than a mirror of them. NODE_HOST_ENV stays off so the # environment is still whatever LuaModuleOptions `env` says, as it is in the default glue. emcc "${COMMON[@]}" \ + "${FILESYSTEM[@]}" \ -s NODERAWFS=1 \ -s NODE_HOST_ENV=0 \ -s ENVIRONMENT="node" \ -o ../build/host/glue.js \ ${LUA_SRC} -# Both glues are the same wasm with a different filesystem bolted on in JS, which is what lets the +# The glue for `fs: 'none'`, with no filesystem at all: a third of the size of the default one, +# since Emscripten's FS is most of that. The file syscalls fail and stdio goes straight to the +# LuaModuleOptions callbacks, both through no-filesystem.js. +emcc "${COMMON[@]}" \ + "${BROWSERS[@]}" \ + -s FILESYSTEM=0 \ + -s EXPORTED_RUNTIME_METHODS="[$RUNTIME_METHODS]" \ + -s INCOMING_MODULE_JS_API="[$INCOMING_API, 'stdin', 'stdout', 'stderr']" \ + --js-library no-filesystem.js \ + -s ENVIRONMENT="web,worker,node" \ + -o ../build/none/glue.js \ + ${LUA_SRC} + +# The glues are the same wasm with a different filesystem bolted on in JS, which is what lets the # package ship one binary and pick a glue at load time. Checked rather than assumed, because a -# divergence would otherwise surface as a corrupt module for host users only. -if ! cmp -s ../build/glue.wasm ../build/host/glue.wasm; then - echo "build-wasm: the host glue produced a different glue.wasm, so the two cannot share one binary" >&2 - exit 1 -fi -# Dropped so only one copy is published; the host glue resolves 'glue.wasm' next to itself, and the -# bundle puts both of them in dist/ beside the shared binary. -rm ../build/host/glue.wasm +# divergence would otherwise surface as a corrupt module for the users of one glue only. +for glue in host none; do + if ! cmp -s ../build/glue.wasm ../build/$glue/glue.wasm; then + echo "build-wasm: the $glue glue produced a different glue.wasm, so the glues cannot share one binary" >&2 + exit 1 + fi + # Dropped so only one copy is published; each glue resolves 'glue.wasm' next to itself, and the + # bundle puts all of them in dist/ beside the shared binary. + rm ../build/$glue/glue.wasm +done diff --git a/utils/no-filesystem.js b/utils/no-filesystem.js new file mode 100644 index 0000000..8870dcd --- /dev/null +++ b/utils/no-filesystem.js @@ -0,0 +1,64 @@ +// Linked into the glue for `fs: 'none'`, which is built with FILESYSTEM=0. Emscripten's stand-ins +// for the file syscalls there report success without doing anything, so `io.open` would hand back +// a handle on fd 0 and `os.remove` would claim to have removed the file. These make every one of +// them fail with ENOSYS instead, and hand stdio to the same per byte callbacks FS.init takes in +// the other glues. +// +// Emscripten turns each function into source text, so nothing outside of them exists at run time: +// the errno values are written out in place (ENOSYS is 52, EBADF is 8). + +addToLibrary({ + __syscall_openat: () => -52, + __syscall_dup3: () => -52, + __syscall_readlinkat: () => -52, + __syscall_renameat: () => -52, + __syscall_rmdir: () => -52, + __syscall_unlinkat: () => -52, + + fd_write: (fd, iov, iovcnt, pnum) => { + // LuaModule passes both callbacks, defaults included, so a missing one is a closed stream. + const output = fd === 1 ? Module['stdout'] : fd === 2 ? Module['stderr'] : undefined + if (!output) { + return 8 + } + let written = 0 + for (let i = 0; i < iovcnt; i++, iov += 8) { + const pointer = HEAPU32[iov >> 2] + const length = HEAPU32[(iov + 4) >> 2] + for (let j = 0; j < length; j++) { + output(HEAPU8[pointer + j]) + } + written += length + } + HEAPU32[pnum >> 2] = written + return 0 + }, + + fd_read: (fd, iov, iovcnt, pnum) => { + if (fd !== 0) { + return 8 + } + const input = Module['stdin'] + let read = 0 + // With no callback there is nothing to read at all, and an empty read is EOF. + if (!input) { + HEAPU32[pnum >> 2] = read + return 0 + } + // A null from the callback ends the read, as it does for a TTY. + reading: for (let i = 0; i < iovcnt; i++, iov += 8) { + const pointer = HEAPU32[iov >> 2] + const length = HEAPU32[(iov + 4) >> 2] + for (let j = 0; j < length; j++) { + const byte = input() + if (byte === null) { + break reading + } + HEAPU8[pointer + j] = byte + read++ + } + } + HEAPU32[pnum >> 2] = read + return 0 + }, +}) From d6d040a8c0c77a501465fb3d515d5978a9218885 Mon Sep 17 00:00:00 2001 From: ceifa Date: Fri, 20 Nov 2026 14:25:03 -0300 Subject: [PATCH 82/83] fetch and compile the wasm alongside the glue, once per url --- src/declarations.d.ts | 3 +- src/module.ts | 165 ++++++++++++++++++++++++------------------ test/browser.test.js | 42 +++++++++++ test/bundling.test.js | 8 +- utils/build-wasm.sh | 3 +- 5 files changed, 143 insertions(+), 78 deletions(-) diff --git a/src/declarations.d.ts b/src/declarations.d.ts index 5f78bce..0f10b37 100644 --- a/src/declarations.d.ts +++ b/src/declarations.d.ts @@ -8,7 +8,8 @@ declare module '*.wasm' { // (see INCOMING_MODULE_JS_API in utils/build-wasm.sh). declare module '*/glue.js' { const initWasmModule: ( - moduleArg?: Partial> & { + moduleArg?: Partial> & { + instantiateWasm: (imports: WebAssembly.Imports, receive: (instance: WebAssembly.Instance) => void) => void preRun?: (module: import('./module').LuaEmscriptenModule) => void // Read by the glue without a filesystem only; see utils/no-filesystem.js. stdin?: (() => number | null) | null diff --git a/src/module.ts b/src/module.ts index 89534a7..4e11125 100755 --- a/src/module.ts +++ b/src/module.ts @@ -198,6 +198,67 @@ function nodeBuiltin(name: string): T | null { return (globalThis.process?.getBuiltinModule?.(name) as T | undefined) ?? null } +// Compiled once per URL and shared by every load from it, so another runtime skips both the download +// and the compile. A failure leaves the cache, so a later load can try again. +const compiledWasm = new Map>() + +function compileWasm(url: string, isNode: boolean): Promise { + let compiled = compiledWasm.get(url) + if (!compiled) { + compiled = fetchAndCompileWasm(url, isNode) + compiledWasm.set(url, compiled) + compiled.catch(() => compiledWasm.delete(url)) + } + return compiled +} + +async function fetchAndCompileWasm(url: string, isNode: boolean): Promise { + // Node's fetch takes no file: URL, and a wasmFile there may be a plain path too. + if (isNode && !/^(https?|data|blob):/.test(url)) { + const { readFile } = nodeBuiltin('node:fs/promises')! + return await WebAssembly.compile(await readFile(url.startsWith('file:') ? new URL(url) : url)) + } + + const response = await fetch(url) + if (!response.ok) { + throw new Error(`fetching ${url} failed with status ${response.status}`) + } + // Streaming compiles while the bytes are still arriving, but refuses a response that was not + // served as application/wasm. + if (response.headers.get('content-type')?.split(';')[0]?.trim() === 'application/wasm') { + return await WebAssembly.compileStreaming(response) + } + return await WebAssembly.compile(await response.arrayBuffer()) +} + +/** The wasm next to the bundle, or the published copy on unpkg when a browser cannot reach that. */ +async function compileDefaultWasm(isNode: boolean, warn: LuaWarnHandler): Promise { + try { + // Written in the shape bundlers look for, so they emit or inline the asset. + return await compileWasm(new URL('glue.wasm', import.meta.url).href, isNode) + } catch (err) { + // A browser can recover: a page opened from file: cannot fetch a sibling at all, and a + // bundler that neither emits nor inlines the asset leaves nothing there either. In Node it + // is just a broken install. + if (isNode) { + throw err + } + + // Pinned to this version, so it only covers a published release. + const remoteWasmFile = `https://unpkg.com/wasmoon@${version}/dist/glue.wasm` + warn(`could not load glue.wasm from next to the bundle, falling back to ${remoteWasmFile}`, err) + try { + return await compileWasm(remoteWasmFile, isNode) + } catch (remoteErr) { + throw new Error( + `failed to load the Lua wasm module, both from next to the bundle and from ${remoteWasmFile}. ` + + `The fallback only covers published versions of wasmoon, so pass wasmFile to point at your own copy.`, + { cause: remoteErr }, + ) + } + } +} + /** * Nothing here is left to fail later: an unreadable host path, or a mount point Emscripten would * put somewhere unexpected, is an error at once rather than a directory that silently turns up empty. @@ -329,15 +390,22 @@ export default class LuaModule extends LuaBindings { mounts.push(mount) } - // Emscripten reports load failures itself, which is noise while one can still be recovered - // from below, so they are held until the outcome is known. Null once handed over. - let buffered: string[] | null = [] - const printErr = (line: string): void => { - if (buffered) { - buffered.push(line) - } else { - warn(line) - } + // The wasm is fetched and compiled here rather than by the glue, so that it starts at once + // instead of after the glue chunk has arrived: the two downloads overlap, and the compile + // streams along with the wasm one. + const wasm = opts.wasmFile === undefined ? compileDefaultWasm(isNode, warn) : compileWasm(opts.wasmFile, isNode) + + // Three glues over the one wasm, differing only in their filesystem (see + // utils/build-wasm.sh). Each is a chunk of its own, imported on demand, so a load only + // downloads the one it asked for -- and a browser bundle never loads the host one, which + // throws outside Node. + const glue = + fs === 'host' ? import('../build/host/glue.js') : fs === 'none' ? import('../build/none/glue.js') : import('../build/glue.js') + + const [{ default: init }, wasmModule] = await Promise.all([glue, wasm]) + if (typeof init !== 'function') { + // The `browser` field points bundlers at a stub, since the glue only runs under Node. + throw new Error(`fs: 'host' needs glue-host.js, which the bundle replaced with a stub because it targets the browser`) } // Without a filesystem there is no FS.init to hand stdio to, so that glue takes it directly, @@ -347,7 +415,7 @@ export default class LuaModule extends LuaBindings { ? { stdin: createInputReader(opts.stdin), stdout: createOutputWriter(opts.stdout ?? ((line) => console.log(line))), - stderr: createOutputWriter(opts.stderr ?? printErr), + stderr: createOutputWriter(opts.stderr ?? warn), } : {} const preRun = createPreRun({ @@ -356,71 +424,24 @@ export default class LuaModule extends LuaBindings { ...(fs === 'none' ? {} : { stdin: opts.stdin, stdout: opts.stdout, stderr: opts.stderr }), }) - // Three glues over the one wasm, differing only in their filesystem (see - // utils/build-wasm.sh). Each is a chunk of its own, imported on demand, so a load only - // downloads the one it asked for -- and a browser bundle never loads the host one, which - // throws outside Node. - const init = ( - fs === 'host' - ? await import('../build/host/glue.js') - : fs === 'none' - ? await import('../build/none/glue.js') - : await import('../build/glue.js') - ).default - if (typeof init !== 'function') { - // The `browser` field points bundlers at a stub, since the glue only runs under Node. - throw new Error(`fs: 'host' needs glue-host.js, which the bundle replaced with a stub because it targets the browser`) - } - - const load = async (wasmFile?: string): Promise => { - return new LuaModule( - await init({ ...(wasmFile === undefined ? {} : { locateFile: () => wasmFile }), preRun, printErr, ...stdio }), - opts.onWarn, - fs, - mounts, - ) - } - - try { - if (opts.wasmFile !== undefined) { - return await load(opts.wasmFile) - } - - try { - // Left to emscripten, which resolves it with `new URL('glue.wasm', import.meta.url)` - // -- the shape bundlers look for to emit or inline the asset, and one a locateFile - // of our own would hide from them. - return await load() - } catch (err) { - // A browser can recover: a page opened from file: cannot fetch a sibling at all, and - // a bundler that neither emits nor inlines the asset leaves nothing there either. In - // Node it is just a broken install. - if (isNode) { - throw err - } - - // Pinned to this version, so it only covers a published release. - const remoteWasmFile = `https://unpkg.com/wasmoon@${version}/dist/glue.wasm` - warn(`could not load glue.wasm from next to the bundle, falling back to ${remoteWasmFile}`, err) - buffered = [] - + // Emscripten waits on instantiateWasm without a way to fail it, so a failed instantiation + // settles the load through this instead. + let instantiationFailed!: (error: unknown) => void + const failure = new Promise((_, reject) => { + instantiationFailed = reject + }) + const instantiateWasm = (imports: WebAssembly.Imports, receive: (instance: WebAssembly.Instance) => void): void => { + void (async () => { try { - return await load(remoteWasmFile) - } catch (remoteErr) { - throw new Error( - `failed to load the Lua wasm module, both from next to the bundle and from ${remoteWasmFile}. ` + - `The fallback only covers published versions of wasmoon, so pass wasmFile to point at your own copy.`, - { cause: remoteErr }, - ) + receive(await WebAssembly.instantiate(wasmModule, imports)) + } catch (error) { + instantiationFailed(error) } - } - } finally { - // What is left belongs to the attempt that decided the outcome. - for (const line of buffered ?? []) { - warn(line) - } - buffered = null + })() } + + const emscripten = await Promise.race([init({ instantiateWasm, preRun, printErr: (line) => warn(line), ...stdio }), failure]) + return new LuaModule(emscripten, opts.onWarn, fs, mounts) } /** The handler passed to {@link LuaModule.initialize}, which states created on it inherit. */ diff --git a/test/browser.test.js b/test/browser.test.js index cbeae39..ca5313c 100644 --- a/test/browser.test.js +++ b/test/browser.test.js @@ -302,6 +302,48 @@ describe('Browser environment', () => { expectNoExternalRequests() }) + it('fetches the wasm without waiting for the glue', async function () { + this.timeout(30_000) + await runInBrowser('await LuaRuntime.load(); return 1') + + const wasm = requested.indexOf(`http://127.0.0.1:${port}/glue.wasm`) + const glue = requested.indexOf(`http://127.0.0.1:${port}/glue-memory.js`) + expect(wasm).to.be.at.least(0) + expect(glue).to.be.above(wasm) + }) + + it('compiles the wasm once for every runtime loaded from it', async function () { + this.timeout(30_000) + const result = await runInBrowser(` + const [first, second] = await Promise.all([LuaRuntime.load(), LuaRuntime.load()]) + const third = await LuaRuntime.load() + return [first, second, third].map((lua) => lua.createState().doStringSync('return 1')) + `) + + expect(result).to.be.deep.equal([1, 1, 1]) + expect(requested.filter((url) => url.endsWith('/glue.wasm'))).to.have.lengthOf(1) + }) + + it('loads a wasm served without the wasm content type', async function () { + this.timeout(30_000) + const page = await openPage() + + try { + await page.route('**/glue.wasm', async (route) => { + await route.fulfill({ contentType: 'application/octet-stream', body: await readFile(join(DIST_DIR, 'glue.wasm')) }) + }) + const result = await page.evaluate(() => + window.__runTest('const lua = await LuaRuntime.load(); return lua.createState().doStringSync("return 5")'), + ) + + page.assertNoErrors() + expect(result).to.be.equal(5) + expectNoExternalRequests() + } finally { + await page.close() + } + }) + it('loads the wasm from the same origin inside a module worker', async function () { this.timeout(30_000) const page = await openPage() diff --git a/test/bundling.test.js b/test/bundling.test.js index d594ece..b47bb0a 100644 --- a/test/bundling.test.js +++ b/test/bundling.test.js @@ -65,15 +65,15 @@ describe('Bundling', () => { }) it('every glue is a chunk of its own, so a load only downloads the one it uses', async () => { - // Emscripten resolves the wasm next to the glue, which is how a glue is told apart. - const resolvesWasm = /new URL\(\s*['"`]glue\.wasm['"`]/ + // Emscripten's abort message survives minification, which is how a glue is told apart. + const glueCode = /Aborted\(/ const glues = ['glue-memory.js', 'glue-host.js', 'glue-none.js'] const index = await readFile(join(DIST_DIR, 'index.js'), 'utf8') - expect(index).to.not.match(resolvesWasm) + expect(index).to.not.match(glueCode) for (const glue of glues) { expect(index).to.include(`./${glue}`) - expect(await readFile(join(DIST_DIR, glue), 'utf8')).to.match(resolvesWasm) + expect(await readFile(join(DIST_DIR, glue), 'utf8')).to.match(glueCode) } }) diff --git a/utils/build-wasm.sh b/utils/build-wasm.sh index 27fe662..e224128 100755 --- a/utils/build-wasm.sh +++ b/utils/build-wasm.sh @@ -17,7 +17,8 @@ fi RUNTIME_METHODS="'addFunction', 'removeFunction', 'ENV', 'getValue', 'setValue', 'lengthBytesUTF8', \ 'stringToUTF8', 'stringToNewUTF8', 'stringToUTF8OnStack', 'stackSave', 'stackRestore', \ 'UTF8ToString', 'HEAPU8', 'HEAPU32'" -INCOMING_API="'locateFile', 'preRun', 'print', 'printErr'" +# The wasm is never fetched by the glue: LuaModule compiles it and hands it over through instantiateWasm. +INCOMING_API="'instantiateWasm', 'preRun', 'print', 'printErr'" # Everything that is not about the filesystem, shared by all three glues below so they can share # one `glue.wasm`. From 933e12f0fedc05f1510f51e67a74d4df6d6a7188 Mon Sep 17 00:00:00 2001 From: ceifa Date: Fri, 20 Nov 2026 15:16:33 -0300 Subject: [PATCH 83/83] fall back to jsdelivr and hold the wasm to this build's hash --- README.md | 7 ++--- rolldown.config.ts | 22 +++++++++++++++- src/declarations.d.ts | 5 ++++ src/module.ts | 24 +++++++++-------- test/browser.test.js | 61 +++++++++++++++++++++++++++++++++---------- 5 files changed, 90 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index e42558d..7573fe7 100644 --- a/README.md +++ b/README.md @@ -309,8 +309,9 @@ means depends on your bundler: | esbuild | does not handle the asset, see below | | Rollup | does not handle the asset, see below | -esbuild and Rollup leave nothing beside the bundle to fetch, so wasmoon falls back to unpkg with a -warning. That works, but it is a request to a third party pinned to wasmoon's version, so prefer +esbuild and Rollup leave nothing beside the bundle to fetch, so wasmoon falls back to jsDelivr with a +warning. That works, and the wasm it gets there is checked against the hash of the one your build +ships, but it is still a request to a third party pinned to wasmoon's version, so prefer copying the wasm next to your output as part of the build, after which nothing else is needed: ```js @@ -332,7 +333,7 @@ With Vite and webpack you want neither, since they already handle the asset. Ask ### A page opened from `file://` A page loaded over `file://` cannot fetch anything next to it, so the wasm has to come from -somewhere else and wasmoon falls back to unpkg. To keep such a page self contained, inline the wasm +somewhere else and wasmoon falls back to jsDelivr. To keep such a page self contained, inline the wasm and hand it over as a data URL: ```js diff --git a/rolldown.config.ts b/rolldown.config.ts index a7d3cb5..650d4a9 100644 --- a/rolldown.config.ts +++ b/rolldown.config.ts @@ -1,4 +1,5 @@ -import { copyFile } from 'node:fs/promises' +import { createHash } from 'node:crypto' +import { copyFile, readFile } from 'node:fs/promises' import { defineConfig } from 'rolldown' import pkg from './package.json' with { type: 'json' } @@ -50,6 +51,25 @@ export default defineConfig({ } }, }, + { + // The hash the CDN fallback holds the wasm it fetches to, so that a version published + // from other sources fails the fetch instead of instantiating against the wrong glue. + name: 'wasm-integrity', + resolveId(source) { + if (source === 'wasm-integrity') { + return 'wasm-integrity' + } + }, + async load(id) { + if (id === 'wasm-integrity') { + this.addWatchFile('build/glue.wasm') + const digest = createHash('sha256') + .update(await readFile('build/glue.wasm')) + .digest('base64') + return `export default 'sha256-${digest}'` + } + }, + }, { // A node builtin is imported behind a runtime check for Node, which a bundler targeting // the browser does not see, so it refuses to resolve it. webpack takes the comment; the diff --git a/src/declarations.d.ts b/src/declarations.d.ts index 0f10b37..e9fdf27 100644 --- a/src/declarations.d.ts +++ b/src/declarations.d.ts @@ -25,6 +25,11 @@ declare module 'package-version' { export default value } +declare module 'wasm-integrity' { + const value: string + export default value +} + declare namespace WebAssembly { function promising any>(fn: T): (...args: Parameters) => Promise> const Suspending: new (fn: (...args: any[]) => any) => (...args: any[]) => any diff --git a/src/module.ts b/src/module.ts index 4e11125..d287579 100755 --- a/src/module.ts +++ b/src/module.ts @@ -6,8 +6,9 @@ import LuaBindings from './bindings.gen' import { canSuspend, limitError, type PendingSuspend, settleOrInterrupt, type SettleOutcome, yieldToEventLoop } from './async' import type Thread from './thread' import { defaultWarnHandler, LUA_REGISTRYINDEX, type LuaAddress, LuaReturn, LuaType, type LuaWarnHandler, PointerSize } from './types' -// A rolldown plugin will resolve this to the current version on package.json +// Rolldown plugins resolve these to the version on package.json and the hash of build/glue.wasm import version from 'package-version' +import wasmIntegrity from 'wasm-integrity' export type EnvironmentVariables = Record @@ -69,7 +70,7 @@ export type EmscriptenFS = LuaEmscriptenModule['FS'] export interface LuaModuleOptions { /** - * Where to load `glue.wasm` from. Defaults to next to this module, falling back to unpkg when + * Where to load `glue.wasm` from. Defaults to next to this module, falling back to jsDelivr when * there is nothing there to fetch (a page opened from `file:`, say). */ wasmFile?: string | undefined @@ -202,24 +203,24 @@ function nodeBuiltin(name: string): T | null { // and the compile. A failure leaves the cache, so a later load can try again. const compiledWasm = new Map>() -function compileWasm(url: string, isNode: boolean): Promise { +function compileWasm(url: string, isNode: boolean, integrity = ''): Promise { let compiled = compiledWasm.get(url) if (!compiled) { - compiled = fetchAndCompileWasm(url, isNode) + compiled = fetchAndCompileWasm(url, isNode, integrity) compiledWasm.set(url, compiled) compiled.catch(() => compiledWasm.delete(url)) } return compiled } -async function fetchAndCompileWasm(url: string, isNode: boolean): Promise { +async function fetchAndCompileWasm(url: string, isNode: boolean, integrity: string): Promise { // Node's fetch takes no file: URL, and a wasmFile there may be a plain path too. if (isNode && !/^(https?|data|blob):/.test(url)) { const { readFile } = nodeBuiltin('node:fs/promises')! return await WebAssembly.compile(await readFile(url.startsWith('file:') ? new URL(url) : url)) } - const response = await fetch(url) + const response = await fetch(url, { integrity }) if (!response.ok) { throw new Error(`fetching ${url} failed with status ${response.status}`) } @@ -231,7 +232,7 @@ async function fetchAndCompileWasm(url: string, isNode: boolean): Promise { try { // Written in the shape bundlers look for, so they emit or inline the asset. @@ -244,15 +245,16 @@ async function compileDefaultWasm(isNode: boolean, warn: LuaWarnHandler): Promis throw err } - // Pinned to this version, so it only covers a published release. - const remoteWasmFile = `https://unpkg.com/wasmoon@${version}/dist/glue.wasm` + // Pinned to this version and to this build's hash, so it only covers a published release. + const remoteWasmFile = `https://cdn.jsdelivr.net/npm/wasmoon@${version}/dist/glue.wasm` warn(`could not load glue.wasm from next to the bundle, falling back to ${remoteWasmFile}`, err) try { - return await compileWasm(remoteWasmFile, isNode) + return await compileWasm(remoteWasmFile, isNode, wasmIntegrity) } catch (remoteErr) { throw new Error( `failed to load the Lua wasm module, both from next to the bundle and from ${remoteWasmFile}. ` + - `The fallback only covers published versions of wasmoon, so pass wasmFile to point at your own copy.`, + `The fallback only covers published builds of wasmoon, whose CDN copy matches this one byte for byte, ` + + `so pass wasmFile to point at your own copy.`, { cause: remoteErr }, ) } diff --git a/test/browser.test.js b/test/browser.test.js index ca5313c..7faa532 100644 --- a/test/browser.test.js +++ b/test/browser.test.js @@ -365,34 +365,67 @@ describe('Browser environment', () => { } }) - it('falls back to the CDN for a page opened from file:', async function () { - this.timeout(60_000) - // Served locally rather than for real, to keep the suite offline and because the - // published wasm belongs to another version. + /** + * Opens a self contained page from `file:`, where the only wasm to be had is the CDN's, and + * runs `code` on it. The CDN is served locally, to keep the suite offline and because the + * published wasm belongs to another version. + */ + async function loadFromCdn(cdnWasm, code) { const { htmlFile, cleanup } = await writeInlinedPage() const page = await context.newPage() const cdnRequests = [] try { - await page.route('https://unpkg.com/**', async (route) => { + await page.route('https://**/glue.wasm', async (route) => { cdnRequests.push(route.request().url()) - await route.fulfill({ contentType: 'application/wasm', body: await readFile(join(DIST_DIR, 'glue.wasm')) }) + await route.fulfill({ + contentType: 'application/wasm', + headers: { 'access-control-allow-origin': '*' }, + body: cdnWasm, + }) }) await page.goto(`file://${htmlFile}`) await page.waitForFunction(() => window.__ready === true, null, { timeout: 15_000 }) - const result = await page.evaluate(async () => { - const lua = await window.__LuaRuntime.load() - return await lua.createState().doString('return 3 * 3') - }) - - expect(result).to.be.equal(9) - expect(cdnRequests).to.have.lengthOf(1) - expect(cdnRequests[0]).to.match(/^https:\/\/unpkg\.com\/wasmoon@[^/]+\/dist\/glue\.wasm$/) + const result = await page.evaluate(async (c) => { + try { + return { value: await new Function('LuaRuntime', `return (async () => {${c}})()`)(window.__LuaRuntime) } + } catch (err) { + return { error: String(err), cause: String(err.cause) } + } + }, code) + return { result, cdnRequests } } finally { await page.close() await cleanup() } + } + + it('falls back to jsDelivr for a page opened from file:', async function () { + this.timeout(60_000) + const { result, cdnRequests } = await loadFromCdn( + await readFile(join(DIST_DIR, 'glue.wasm')), + 'const lua = await LuaRuntime.load(); return await lua.createState().doString("return 3 * 3")', + ) + + expect(result).to.be.eql({ value: 9 }) + expect(cdnRequests).to.have.lengthOf(1) + expect(cdnRequests[0]).to.match(/^https:\/\/cdn\.jsdelivr\.net\/npm\/wasmoon@[^/]+\/dist\/glue\.wasm$/) + }) + + it('refuses a CDN wasm that is not byte for byte the one this build ships', async function () { + this.timeout(60_000) + // Still a valid module, with an empty custom section appended, so only the integrity + // check can tell it apart: what a CDN serves for a version published from other sources. + const wasm = await readFile(join(DIST_DIR, 'glue.wasm')) + const { result, cdnRequests } = await loadFromCdn( + Buffer.concat([wasm, Buffer.from([0x00, 0x02, 0x01, 0x78])]), + 'await LuaRuntime.load(); return 1', + ) + + expect(cdnRequests).to.have.lengthOf(1) + expect(result.error).to.match(/failed to load the Lua wasm module/) + expect(result.cause).to.match(/Failed to fetch/) }) }) })