import {expect, test} from 'vitest'; import {first} from '@/swcx/builders.js'; import evaluate from '@/swcx/evaluate.js'; const scopeTest = test.extend({ scope: async ({}, use) => { await use({ S: {O: {}}, get(k) { return this.S[k]; }, set(k, v) { return this.S[k] = v; } }); }, }); scopeTest('evaluates calls', async ({scope}) => { scope.set('f', (...args) => args.reduce((l, r) => l + r, 0)); const evaluated = evaluate(await first('f(1, 2, 3)'), {scope}); expect(evaluated.value) .to.equal(6); }); scopeTest('evaluates async calls', async ({scope}) => { const f = (...args) => args.reduce((l, r) => l + r, 0); scope.set('f', f); scope.set('O', {f}); const evaluated = evaluate(await first('f(await 1, 2, 3)'), {scope}); expect(evaluated.async) .to.equal(true); expect(await evaluated.value) .to.equal(6); const evaluatedOptional = evaluate(await first('O?.f(await 1, 2, 3)'), {scope}); expect(evaluatedOptional.async) .to.equal(true); expect(await evaluatedOptional.value) .to.equal(6); }); scopeTest('evaluates member calls', async ({scope}) => { scope.set('O', {f: (...args) => args.reduce((l, r) => l + r, 0)}); expect(evaluate(await first('O.f(1, 2, 3)'), {scope}).value) .to.equal(6); expect(evaluate(await first('O["f"](1, 2, 3)'), {scope}).value) .to.equal(6); }); scopeTest('evaluates optional calls', async ({scope}) => { scope.set('O', {}); expect(evaluate(await first('g?.(1, 2, 3)'), {scope}).value) .to.equal(undefined); expect(evaluate(await first('O?.g(1, 2, 3)'), {scope}).value) .to.equal(undefined); expect(evaluate(await first('O?.g?.(1, 2, 3)'), {scope}).value) .to.equal(undefined); }); scopeTest('evaluates async calls', async ({scope}) => { scope.set('O', {f: (...args) => args.reduce((l, r) => l + r, 0)}); const evaluated = evaluate(await first('O.f(await 1, 2, 3)'), {scope}); expect(evaluated.async) .to.equal(true); expect(await evaluated.value) .to.equal(6); });