diff --git a/.changepacks/changepack_log_compiler_sessions.json b/.changepacks/changepack_log_compiler_sessions.json new file mode 100644 index 000000000..acaa995ce --- /dev/null +++ b/.changepacks/changepack_log_compiler_sessions.json @@ -0,0 +1,7 @@ +{ + "changes": { + "packages/plugin-utils/package.json": "Patch" + }, + "note": "New `openCompilerSession(compiler)`: it opens an engine session of its own on a shared compiler and returns `{ id, compiler, close }`. Every function of the scoped `compiler` selects the session before it runs, so two apps in one process keep their numbering, sheet, theme and settings apart; `close()` drops the session", + "date": "2026-11-15T00:00:00.000Z" +} diff --git a/.changepacks/changepack_log_engine_sessions_bindings.json b/.changepacks/changepack_log_engine_sessions_bindings.json new file mode 100644 index 000000000..f43836947 --- /dev/null +++ b/.changepacks/changepack_log_engine_sessions_bindings.json @@ -0,0 +1,8 @@ +{ + "changes": { + "bindings/devup-ui-wasm/package.json": "Patch", + "bindings/devup-ui-binding/package.json": "Patch" + }, + "note": "New `createSession()`, `selectSession(id)` and `dropSession(id)` exports on the WASM and native engines: a session is an engine state of its own (numbering, sheet, theme, settings and module resolver), and every call works on the selected one. Session 0 is selected from the start. `selectSession` and `dropSession` throw a `TypeError` for an id that is not an unsigned 32-bit integer, and an `Error` for an unknown session or for dropping session 0", + "date": "2026-11-15T00:00:00.000Z" +} diff --git a/bindings/argument-validation.cjs b/bindings/argument-validation.cjs index a0e3edb41..1488e41ba 100644 --- a/bindings/argument-validation.cjs +++ b/bindings/argument-validation.cjs @@ -5,6 +5,7 @@ module.exports = function createBoundary() { const descriptors = { codeExtract: extraction, codeExtractWithoutSourceMap: extraction, + dropSession: 'id:u', getCss: 'file_num:n import_main_css:b', getThemeInterface: 'package_name:s color_interface_name:s typography_interface_name:s length_interface_name:s shadows_interface_name:s theme_interface_name:s', @@ -20,6 +21,7 @@ module.exports = function createBoundary() { reserveClassSlots: 'rows:rows _package:s single_css:b import_main_css_in_code:b _import_main_css_in_css:b import_aliases:aliases', seedFileMap: 'files:a', + selectSession: 'id:u', setAtomHoist: 'threshold:n', setDebug: 'debug:b', setModuleResolver: 'resolver:f', @@ -32,6 +34,7 @@ module.exports = function createBoundary() { p: 'a string, null or undefined', f: 'a function, null or undefined', a: 'an array of strings', + u: 'a session id', aliases: 'an alias mapping', canonical: 'a canonical mapping', class: 'a nested class-index mapping', @@ -51,6 +54,7 @@ module.exports = function createBoundary() { p: (value) => value == null || typeof value === 'string', f: (value) => value == null || typeof value === 'function', a: Array.isArray, + u: (value) => Number.isInteger(value) && value >= 0 && value <= 0xffffffff, } let frame const fail = (slot) => { diff --git a/bindings/devup-ui-binding/README.md b/bindings/devup-ui-binding/README.md index 71afa1212..6014328dc 100644 --- a/bindings/devup-ui-binding/README.md +++ b/bindings/devup-ui-binding/README.md @@ -2,7 +2,7 @@ Synchronous native build-time compiler for Node.js and Bun. Both `require('@devup-ui/binding')` and named ESM imports expose exactly the existing -30 compiler names, with identical function/class identities and no default init. +33 compiler names, with identical function/class identities and no default init. Authored CommonJS/ESM declarations are included; no WASM dependency is required. The private loader selects one optional platform sibling: Windows MSVC, macOS, @@ -96,4 +96,4 @@ The decoder is private and target-bounded: unused Serde hints use trait forwardi Malformed-enum error paths follow shipped serde-wasm-bindgen 0.6.5: Object.entries result length is read and coerced once for the check, then read and coerced again for the invalid-length diagnostic when the first length is not one, before any index read. The second value supplies the diagnostic; errors thrown by its getter or coercion propagate unchanged. Valid enums retain one length read. -The shared native/WASM boundary validates ordinary calls at 46 argument positions in 19 functions: malformed inputs throw a genuine `TypeError` naming the function, parameter and required type before state mutation. Preflight defaults the entire alias map on schema failure (after diagnostics) or a caught iterator-import failure whose `new Error(String(error))` conversion succeeds. Raw access failures and conversion faults escape unchanged before resolver selection; conversion runs once with the pending failure cleared, so reentry is isolated and resolver changes take effect before the outer core starts. Extraction and reservation remain strict. For example, `setPrefix(false)` throws `setPrefix(): argument prefix must be a string, null or undefined`; string/nullish prefixes remain supported. Extraction wrappers retain the measured metadata, receiver, extra-argument and apply/construct policy; `seedFileMap` validates and copies the caller's array before engine entry without rereading its indices. Same-revision Node/Bun identity, 272-case invalid-input, 73-exception preservation and seed-safety gates cover these contracts, not optimized shipping-native performance or real Node-host Linux Rust/authored-JS 100% coverage, which remain public-delivery gates. +The shared native/WASM boundary validates ordinary calls at 48 argument positions in 21 functions: malformed inputs throw a genuine `TypeError` naming the function, parameter and required type before state mutation. Preflight defaults the entire alias map on schema failure (after diagnostics) or a caught iterator-import failure whose `new Error(String(error))` conversion succeeds. Raw access failures and conversion faults escape unchanged before resolver selection; conversion runs once with the pending failure cleared, so reentry is isolated and resolver changes take effect before the outer core starts. Extraction and reservation remain strict. For example, `setPrefix(false)` throws `setPrefix(): argument prefix must be a string, null or undefined`; string/nullish prefixes remain supported. Extraction wrappers retain the measured metadata, receiver, extra-argument and apply/construct policy; `seedFileMap` validates and copies the caller's array before engine entry without rereading its indices. Same-revision Node/Bun identity, 288-case invalid-input, 73-exception preservation and seed-safety gates cover these contracts, not optimized shipping-native performance or real Node-host Linux Rust/authored-JS 100% coverage, which remain public-delivery gates. diff --git a/bindings/devup-ui-binding/adapter.cjs b/bindings/devup-ui-binding/adapter.cjs index a34c93cac..0c3e24546 100644 --- a/bindings/devup-ui-binding/adapter.cjs +++ b/bindings/devup-ui-binding/adapter.cjs @@ -82,6 +82,8 @@ exports.createBinding = function createBinding(raw) { Output: raw.Output, codeExtract, codeExtractWithoutSourceMap, + createSession: () => raw.createSession(), + dropSession: (id) => raw.dropSession(id), exportCanonicalMap: raw.exportCanonicalMap, exportClassMap: raw.exportClassMap, exportFileMap: raw.exportFileMap, @@ -108,6 +110,7 @@ exports.createBinding = function createBinding(raw) { resetBuildState: () => raw.reset(false), resetStateForTesting: () => raw.reset(true), seedFileMap, + selectSession: (id) => raw.selectSession(id), setAtomHoist: (value) => raw.setAtomHoist(index(value)), setDebug: (value) => raw.setDebug(value), setModuleResolver, diff --git a/bindings/devup-ui-binding/index.d.cts b/bindings/devup-ui-binding/index.d.cts index eae4ba96a..153dfeb41 100644 --- a/bindings/devup-ui-binding/index.d.cts +++ b/bindings/devup-ui-binding/index.d.cts @@ -11,7 +11,7 @@ export class Output { readonly updatedBaseStyle: boolean } -// Positional signatures intentionally match the existing 30-name compiler ABI. +// Positional signatures intentionally match the existing 33-name compiler ABI. export function codeExtract( filename: string, code: string, @@ -32,6 +32,10 @@ export function codeExtractWithoutSourceMap( importMainCssInCss: boolean, importAliases: unknown, ): Output +/** Create an engine session with a clean state; select it before each call. */ +export function createSession(): number +/** Drop a session and its state; dropping the live one makes session 0 live. */ +export function dropSession(id: number): boolean export function exportCanonicalMap(): string export function exportClassMap(): string export function exportFileMap(): string @@ -78,6 +82,8 @@ export function reserveClassSlots( export function resetBuildState(): void export function resetStateForTesting(): void export function seedFileMap(files: string[]): void +/** Make a session live: later calls work on its state until another is selected. */ +export function selectSession(id: number): void export function setAtomHoist(threshold?: number | null): void export function setDebug(debug: boolean): void export function setModuleResolver( diff --git a/bindings/devup-ui-binding/index.mjs b/bindings/devup-ui-binding/index.mjs index 015b58724..9e71069c4 100644 --- a/bindings/devup-ui-binding/index.mjs +++ b/bindings/devup-ui-binding/index.mjs @@ -4,6 +4,8 @@ export const { Output, codeExtract, codeExtractWithoutSourceMap, + createSession, + dropSession, exportCanonicalMap, exportClassMap, exportFileMap, @@ -27,6 +29,7 @@ export const { resetBuildState, resetStateForTesting, seedFileMap, + selectSession, setAtomHoist, setDebug, setModuleResolver, diff --git a/bindings/devup-ui-binding/src/host.rs b/bindings/devup-ui-binding/src/host.rs index fd667e6a7..50a782fed 100644 --- a/bindings/devup-ui-binding/src/host.rs +++ b/bindings/devup-ui-binding/src/host.rs @@ -51,6 +51,25 @@ pub fn reset(env: Env, full: bool) -> Result<()> { } Ok(()) } +/// Create an engine session with a clean state and return its id. +#[napi] +pub fn create_session() -> u32 { + core::create_session() +} +/// Make session `id` live until another is selected. +#[napi] +pub fn select_session(env: Env, id: u32) -> Result<()> { + core::select_session(id) + .map(drop) + .map_err(|error| binding_error(env, error)) +} +/// Drop session `id` with its state and this environment's resolver for it. +#[napi] +pub fn drop_session(env: Env, id: u32) -> Result { + let dropped = core::drop_session(id).map_err(|error| binding_error(env, error))?; + state(&env)?.0.remove(id); + Ok(dropped) +} fn with_resolver( env: Env, diagnostics: core::ResolverState, diff --git a/bindings/devup-ui-binding/src/lib.rs b/bindings/devup-ui-binding/src/lib.rs index 7211b6d16..cc0eec980 100644 --- a/bindings/devup-ui-binding/src/lib.rs +++ b/bindings/devup-ui-binding/src/lib.rs @@ -5,7 +5,10 @@ mod host; mod output; mod value; -pub use host::{Resolved, extract, has_devup_ui, init, reserve, reset, set_resolver}; +pub use host::{ + Resolved, create_session, drop_session, extract, has_devup_ui, init, reserve, reset, + select_session, set_resolver, +}; pub use output::NativeOutput; use de::Wasm32Index; diff --git a/bindings/devup-ui-wasm/README.md b/bindings/devup-ui-wasm/README.md index 066708bcf..507b238b7 100644 --- a/bindings/devup-ui-wasm/README.md +++ b/bindings/devup-ui-wasm/README.md @@ -67,6 +67,16 @@ unwind. Binding tests compose these with sheet/resolver snapshots. Keep a named guard on its creating thread and retain `#[serial]`: guards clean up but do not serialize concurrent tests. Cleanup does not run for panic=abort. +## Sessions + +`createSession()` returns the id of a new engine session with a clean state, and +`selectSession(id)` makes it live: every later call reads and changes that +session's state, resolver included, until another is selected. Session 0 is +live from the start, so a single app needs neither. Two apps in one process +each select their own session before each call. `dropSession(id)` forgets a +session (dropping the live one makes session 0 live), and the full test reset +forgets every session but 0. + ## Errors A source the build cannot compile makes `codeExtract` throw an `Error`. Its diff --git a/bindings/devup-ui-wasm/script.js b/bindings/devup-ui-wasm/script.js index 7bc343dff..754f3bb39 100644 --- a/bindings/devup-ui-wasm/script.js +++ b/bindings/devup-ui-wasm/script.js @@ -50,9 +50,9 @@ types = types.replace(hookType, '') assert.equal(types.includes('install_panic_hook'), false) writeFileSync('pkg/index.d.ts', types, 'utf8') const names = [...source.matchAll(/^exports\.(\w+) = \1;/gm)] -assert.equal(names.length, 30) -assert.equal(new Set(names.map((match) => match[1])).size, 30) -assert.equal([...source.matchAll(/^exports\./gm)].length, 30) +assert.equal(names.length, 33) +assert.equal(new Set(names.map((match) => match[1])).size, 33) +assert.equal([...source.matchAll(/^exports\./gm)].length, 33) assert.equal(source.includes('module.exports'), false) for (const name of ['codeExtract', 'codeExtractWithoutSourceMap']) { const signatures = [ diff --git a/bindings/devup-ui-wasm/src/lib.rs b/bindings/devup-ui-wasm/src/lib.rs index 7c3166f2e..516044ce8 100644 --- a/bindings/devup-ui-wasm/src/lib.rs +++ b/bindings/devup-ui-wasm/src/lib.rs @@ -299,6 +299,40 @@ pub fn seed_file_map(files: Vec) { binding_core::seed_file_map(&files); } +/// Create an engine session with a clean state and return its id. +/// +/// Two apps in one process each keep their own session: select it before +/// every call so the call reads and changes only that app's state. Session 0 +/// is live until another is selected. +#[wasm_bindgen(js_name = "createSession")] +#[must_use] +pub fn create_session() -> u32 { + binding_core::create_session() +} + +/// Make session `id` live: every later call works on its state until +/// another session is selected. +#[wasm_bindgen(js_name = "selectSession")] +#[cfg(not(tarpaulin_include))] +pub fn select_session(id: u32) -> Result<(), JsValue> { + binding_core::select_session(id).map(drop).map_err(js_error) +} + +/// Drop session `id` with its state and resolver (testable without `JsValue`) +pub fn drop_session_internal(id: u32) -> Result { + let dropped = binding_core::drop_session(id)?; + MODULE_RESOLVER.with_borrow_mut(|resolvers| resolvers.remove(id)); + Ok(dropped) +} + +/// Drop session `id` with its state and module resolver, returning whether +/// it existed. Dropping the live session makes session 0 live. +#[wasm_bindgen(js_name = "dropSession")] +#[cfg(not(tarpaulin_include))] +pub fn drop_session(id: u32) -> Result { + drop_session_internal(id).map_err(js_error) +} + /// Forget a source file that was deleted or renamed away. /// /// Its global CSS, its own bucket and the class names handed out in it go, @@ -1729,6 +1763,25 @@ mod tests { assert!(json_str.starts_with('{') || json_str.starts_with("[]")); } + #[test] + #[serial] + fn sessions_keep_their_own_prefix_until_dropped() { + let _state = TestStateGuard::new(); + // Given: a second session with its own prefix + let session = create_session(); + assert_eq!(binding_core::select_session(session), Ok(0)); + set_prefix(Some("app-".into())); + // When / Then: session 0 keeps its own, and the dropped session goes + assert_eq!(binding_core::select_session(0), Ok(session)); + assert_eq!(get_prefix(), None); + assert_eq!( + drop_session_internal(0), + Err("engine session 0 cannot be dropped".to_string()) + ); + assert_eq!(drop_session_internal(session), Ok(true)); + assert_eq!(drop_session_internal(session), Ok(false)); + } + #[test] #[serial] fn remove_file_reports_whether_the_sheet_changed() { diff --git a/e2e/binding/corpus/state.mjs b/e2e/binding/corpus/state.mjs index 85f5e8b64..9a56e169f 100644 --- a/e2e/binding/corpus/state.mjs +++ b/e2e/binding/corpus/state.mjs @@ -42,6 +42,33 @@ add('reservation-malformed-second-row-arity-nonmutation', (h) => { h.call('reserveClassSlots', value, pkg, false, false, false, {}) h.call('reserveClassSlots', rows, pkg, false, false, false, { bad: 7 }) }) +add('sessions-keep-apart-until-dropped', (h) => { + h.call('setPrefix', 'zero-') + h.extract(source) + const session = h.call('createSession').value.value + h.call('selectSession', session) + h.call('registerTheme', theme) + h.extract(box('color="blue"'), { filename: 'src/second.tsx' }) + h.call('selectSession', 0) + h.extract(source) + h.call('selectSession', 7) + h.call('dropSession', 0) + h.call('selectSession', session) + h.call('dropSession', session) + h.call('dropSession', session) +}) +add('remove-file-stays-in-its-session', (h) => { + h.extract(source, { single: false }) + const session = h.call('createSession').value.value + h.call('selectSession', session) + h.extract(box('color="blue"'), { single: false }) + h.call('selectSession', 0) + h.call('removeFile', file) + h.call('removeFile', file) + h.call('selectSession', session) + h.call('removeFile', file) + h.call('dropSession', session) +}) add('remove-file-drops-its-own-styles', (h) => { h.call('importCanonicalMap', { 'src/child.tsx': 'src/root.tsx' }) h.extract(source, { single: false }) diff --git a/e2e/binding/host.mjs b/e2e/binding/host.mjs index a86141ce5..861eed8ba 100644 --- a/e2e/binding/host.mjs +++ b/e2e/binding/host.mjs @@ -68,7 +68,7 @@ save('provenance.json', { scenarios: corpus.map((c) => c.name), }) const names = - 'Output codeExtract codeExtractWithoutSourceMap exportCanonicalMap exportClassMap exportFileMap exportSheet getCss getDefaultTheme getPrefix getThemeInterface getUnreservedClassSlotCount hasDevupUI importCanonicalMap importClassMap importFileMap importFileRoutes importSheet isDebug registerShorthands registerTheme removeFile reserveClassSlots resetBuildState resetStateForTesting seedFileMap setAtomHoist setDebug setModuleResolver setPrefix'.split( + 'Output codeExtract codeExtractWithoutSourceMap createSession dropSession exportCanonicalMap exportClassMap exportFileMap exportSheet getCss getDefaultTheme getPrefix getThemeInterface getUnreservedClassSlotCount hasDevupUI importCanonicalMap importClassMap importFileMap importFileRoutes importSheet isDebug registerShorthands registerTheme removeFile reserveClassSlots resetBuildState resetStateForTesting seedFileMap selectSession setAtomHoist setDebug setModuleResolver setPrefix'.split( ' ', ) const abi = { @@ -199,8 +199,8 @@ const h = { ) }, } -assert.equal(corpus.length, 26) -assert.equal(new Set(corpus.map((c) => c.name)).size, 26) +assert.equal(corpus.length, 28) +assert.equal(new Set(corpus.map((c) => c.name)).size, 28) h.note('public-error-inventory', runDiagnostics(w)) for (const test of corpus) { scenario = test.name diff --git a/e2e/binding/package/consumer.mjs b/e2e/binding/package/consumer.mjs index 3940b9cca..c3bb6d17f 100644 --- a/e2e/binding/package/consumer.mjs +++ b/e2e/binding/package/consumer.mjs @@ -136,7 +136,7 @@ export async function consume(options) { ] .map((match) => match[1]) .sort() - assert.equal(names.length, 30) + assert.equal(names.length, 33) for (const manager of ['npm', 'bun']) { for (const omit of [false, true]) { const startRequest = server.requests.length diff --git a/e2e/binding/validation-cases.mjs b/e2e/binding/validation-cases.mjs index f69d04387..715538bdd 100644 --- a/e2e/binding/validation-cases.mjs +++ b/e2e/binding/validation-cases.mjs @@ -20,6 +20,7 @@ const extractSlots = export const positions = [ ['codeExtract', extractSlots, extraction], ['codeExtractWithoutSourceMap', extractSlots, extraction], + ['dropSession', 'id:session', () => [1]], ['getCss', 'file_num:n import_main_css:b', () => [null, false]], [ 'getThemeInterface', @@ -45,6 +46,7 @@ export const positions = [ () => [[row], pkg, false, false, false, {}], ], ['seedFileMap', 'files:seed', () => [['src/new.tsx']]], + ['selectSession', 'id:session', () => [0]], ['setAtomHoist', 'threshold:n', () => [2]], ['setDebug', 'debug:b', () => [true]], ['setModuleResolver', 'resolver:resolver', () => [null]], @@ -62,6 +64,7 @@ const labels = { prefix: 'a string, null or undefined', resolver: 'a function, null or undefined', seed: 'an array of strings', + session: 'a session id', aliases: 'an alias mapping', canonical: 'a canonical mapping', class: 'a nested class-index mapping', @@ -81,6 +84,7 @@ const invalid = { b: [7, 'false', null, undefined], n: ['2', false, 1n, Symbol('number'), {}], prefix: [false, true, 7, {}], + session: ['1', false, -1, 1.5, 2 ** 32, null, undefined, {}], resolver: [false, true, 7, 'callback', {}], seed: [ ...roots, @@ -154,6 +158,6 @@ export const cases = positions.flatMap((position) => .map((good, index) => (index === position.index ? value : good)), })), ) -assert.equal(positions.length, 46) -assert.equal(new Set(positions.map((p) => p.fn)).size, 19) +assert.equal(positions.length, 48) +assert.equal(new Set(positions.map((p) => p.fn)).size, 21) assert.equal(new Set(cases.map((c) => c.id)).size, cases.length) diff --git a/e2e/binding/validation.mjs b/e2e/binding/validation.mjs index 499bb1b34..d1ee1fe06 100644 --- a/e2e/binding/validation.mjs +++ b/e2e/binding/validation.mjs @@ -114,7 +114,7 @@ for (const [engine, entry] of [ const summary = { cases: cases.length, positions: positions.length, - functions: 18, + functions: 21, engines: 2, runs: runs.length, failed: runs.filter((run) => run.failed).length, diff --git a/packages/plugin-utils/src/__tests__/compiler-session.test.ts b/packages/plugin-utils/src/__tests__/compiler-session.test.ts new file mode 100644 index 000000000..519695be4 --- /dev/null +++ b/packages/plugin-utils/src/__tests__/compiler-session.test.ts @@ -0,0 +1,78 @@ +import * as wasm from '@devup-ui/wasm' +import { afterEach, describe, expect, it } from 'bun:test' + +import { openCompilerSession } from '../compiler-session' +import type { DevupCompiler } from '../compiler-types' + +const compiler: DevupCompiler = wasm +const pkg = '@devup-ui/react' +const source = `import { Box } from '${pkg}'; export const view = ` + +function extract(target: DevupCompiler, file: string) { + const output = target.codeExtract( + file, + source, + pkg, + 'df', + true, + false, + false, + {}, + ) + try { + return output.code + } finally { + output.free() + } +} + +afterEach(() => { + compiler.resetStateForTesting() +}) + +describe('openCompilerSession', () => { + it('keeps each session apart on one shared compiler', () => { + // Given: two apps, each with its own session and prefix. + const first = openCompilerSession(compiler) + const second = openCompilerSession(compiler) + expect(first.id).not.toBe(second.id) + first.compiler.setPrefix('one-') + second.compiler.setPrefix('two-') + + // When: their calls interleave on the shared compiler. + const one = extract(first.compiler, 'src/one.tsx') + const two = extract(second.compiler, 'src/two.tsx') + const again = extract(first.compiler, 'src/one.tsx') + + // Then: each call ran on its own session's state. + expect(one).toContain('one-') + expect(two).toContain('two-') + expect(again).toBe(one) + expect(first.compiler.getCss(null, false)).not.toContain('two-') + expect(second.compiler.getCss(null, false)).not.toContain('one-') + first.close() + second.close() + }) + + it('reuses one wrapper per function and passes other values through', () => { + // Given: a session over the module namespace. + const session = openCompilerSession(compiler) + + // When / Then: function reads stay stable, other reads are untouched. + expect(session.compiler.getCss).toBe(session.compiler.getCss) + expect(Reflect.get(session.compiler, Symbol.toStringTag)).toBe('Module') + session.close() + }) + + it('drops the session on close so later calls through it throw', () => { + // Given: a closed session. + const session = openCompilerSession(compiler) + session.close() + + // When / Then: selecting it again is refused by the engine. + expect(() => session.compiler.getCss(null, false)).toThrow( + `engine session ${session.id} does not exist`, + ) + expect(compiler.getCss(null, false)).toBeString() + }) +}) diff --git a/packages/plugin-utils/src/__tests__/compiler-types.test.ts b/packages/plugin-utils/src/__tests__/compiler-types.test.ts index c6b757714..adf52c2ff 100644 --- a/packages/plugin-utils/src/__tests__/compiler-types.test.ts +++ b/packages/plugin-utils/src/__tests__/compiler-types.test.ts @@ -78,7 +78,7 @@ describe('compiler structural types', () => { Object.keys(compiler).filter( (key) => key !== 'Output' && key !== 'default', ), - ).toHaveLength(29) + ).toHaveLength(32) } finally { compiler.resetStateForTesting() } diff --git a/packages/plugin-utils/src/__tests__/wasm-abi.test.ts b/packages/plugin-utils/src/__tests__/wasm-abi.test.ts index 45390ebfc..156cf48be 100644 --- a/packages/plugin-utils/src/__tests__/wasm-abi.test.ts +++ b/packages/plugin-utils/src/__tests__/wasm-abi.test.ts @@ -44,6 +44,8 @@ describe('@devup-ui/wasm exports', () => { 'Output', 'codeExtract', 'codeExtractWithoutSourceMap', + 'createSession', + 'dropSession', 'exportCanonicalMap', 'exportClassMap', 'exportFileMap', @@ -67,6 +69,7 @@ describe('@devup-ui/wasm exports', () => { 'resetBuildState', 'resetStateForTesting', 'seedFileMap', + 'selectSession', 'setAtomHoist', 'setDebug', 'setModuleResolver', @@ -394,3 +397,29 @@ describe('@devup-ui/wasm reservation', () => { expect(wasm.getUnreservedClassSlotCount()).toBe(0) }) }) + +describe('@devup-ui/wasm sessions', () => { + it('keeps each session apart until it is dropped', () => { + const prefix = wasm.getPrefix() + const session = wasm.createSession() + wasm.selectSession(session) + expect(wasm.getPrefix()).toBeUndefined() + wasm.setPrefix('app-') + wasm.selectSession(0) + expect(wasm.getPrefix()).toBe(prefix) + expect(() => wasm.selectSession(session + 1)).toThrow( + `engine session ${session + 1} does not exist`, + ) + expect(() => wasm.selectSession(-1)).toThrow( + 'selectSession(): argument id must be a session id', + ) + wasm.selectSession(session) + expect(wasm.getPrefix()).toBe('app-') + expect(wasm.dropSession(session)).toBe(true) + expect(wasm.getPrefix()).toBe(prefix) + expect(wasm.dropSession(session)).toBe(false) + expect(() => wasm.dropSession(0)).toThrow( + 'engine session 0 cannot be dropped', + ) + }) +}) diff --git a/packages/plugin-utils/src/compiler-session.ts b/packages/plugin-utils/src/compiler-session.ts new file mode 100644 index 000000000..3b514efb6 --- /dev/null +++ b/packages/plugin-utils/src/compiler-session.ts @@ -0,0 +1,46 @@ +import type { DevupCompiler } from './compiler-types' + +/** One app's engine session on a shared compiler. */ +export interface CompilerSession { + /** The engine session every call through `compiler` selects first. */ + readonly id: number + /** + * The shared compiler, scoped to this session: each function selects the + * session, then runs. JavaScript is single-threaded and the calls are + * synchronous, so no other session's call can run between the two. + */ + readonly compiler: DevupCompiler + /** Drop the session and its engine state; later calls through `compiler` throw. */ + close(): void +} + +/** + * Open an engine session of its own on `compiler`, so two apps in one process + * never read or change each other's numbering, sheet, theme or settings. + */ +export function openCompilerSession(compiler: DevupCompiler): CompilerSession { + const id = compiler.createSession() + const scoped = new Map() + return { + id, + compiler: new Proxy(compiler, { + get(target, key) { + const value: unknown = Reflect.get(target, key) + if (typeof value !== 'function') return value + let wrapper = scoped.get(key) + if (!wrapper) { + // Read the function at call time, so a later replacement applies + wrapper = function (this: unknown, ...args: unknown[]) { + target.selectSession(id) + return Reflect.apply(Reflect.get(target, key), this, args) + } + scoped.set(key, wrapper) + } + return wrapper + }, + }), + close() { + compiler.dropSession(id) + }, + } +} diff --git a/packages/plugin-utils/src/index.ts b/packages/plugin-utils/src/index.ts index 74abb94b0..2a76a3b24 100644 --- a/packages/plugin-utils/src/index.ts +++ b/packages/plugin-utils/src/index.ts @@ -4,6 +4,7 @@ export { type ResettableEngine, } from './build-session' export { loadCompiler } from './compiler' +export { type CompilerSession, openCompilerSession } from './compiler-session' export type { DevupCompiler, DevupCompilerOutput,