import { createContext, runInContext, Script } from 'node:vm'; import { WorkflowRuntimeError } from '@workflow/errors'; import { describe, expect, it } from 'vitest'; import { compileDynamicWorkflow, DYNAMIC_WORKFLOW_EXPORT_NAME_MAX_LENGTH, DYNAMIC_WORKFLOW_SOURCE_MAX_BYTES, readDynamicWorkflowMetadata, } from './dynamic-workflow.js'; const SOURCE = ` async function workflow(input) { "use workflow"; const user = await steps.fetchUser(input.userId); await steps.sendEmail(user.email); return { ok: true }; } `; const STEPS = { fetchUser: { stepId: 'step//./src/steps//fetchUser' }, sendEmail: { stepId: 'step//./src/steps//sendEmail' }, }; describe('compileDynamicWorkflow', () => { describe('generated code', () => { it('registers the function under the generated workflow id', async () => { const compiled = await compileDynamicWorkflow(SOURCE, { steps: STEPS }); expect(compiled.workflowName).toMatch( /^workflow\/\/dynamic\/[0-9a-f]{32}\/\/workflow$/ ); expect(compiled.workflowCode).toContain( `__dynamicGlobalThis.__private_workflows.set(${JSON.stringify(compiled.workflowName)}, __dynamicWorkflow)` ); // The id has to be on the function too — the runtime reads it back off // the registered function, same as a build-time transform stamps it. expect(compiled.workflowCode).toContain( `Object.defineProperty(__dynamicWorkflow, "workflowId"` ); expect(compiled.workflowCode).toContain(SOURCE.trim()); }); it('binds only the aliases it was given, through WORKFLOW_USE_STEP', async () => { const compiled = await compileDynamicWorkflow(SOURCE, { steps: STEPS }); expect(compiled.workflowCode).toContain( '["fetchUser"]: __dynamicUseStep("step//./src/steps//fetchUser")' ); expect(compiled.workflowCode).toContain( '["sendEmail"]: __dynamicUseStep("step//./src/steps//sendEmail")' ); // Frozen so ordinary generated code that reaches for a step it was not // given fails the run rather than silently adding one. expect(compiled.workflowCode).toContain( 'const __dynamicSteps = Object.freeze({' ); expect(compiled.workflowCode).not.toContain('notAllowed'); }); it('exposes sleep and createHook from the VM globals', async () => { const compiled = await compileDynamicWorkflow(SOURCE, { steps: STEPS }); expect(compiled.workflowCode).toContain( 'const __dynamicSleep = __dynamicGlobalThis[Symbol.for("WORKFLOW_SLEEP")]' ); expect(compiled.workflowCode).toContain( 'const __dynamicCreateHook = __dynamicGlobalThis[Symbol.for("WORKFLOW_CREATE_HOOK")]' ); }); it('honours a custom exportName', async () => { const source = `async function orchestrate() { "use workflow"; await steps.fetchUser(); }`; const compiled = await compileDynamicWorkflow(source, { steps: STEPS, exportName: 'orchestrate', }); expect(compiled.workflowName).toMatch(/\/\/orchestrate$/); expect(compiled.metadata.exportName).toBe('orchestrate'); expect(compiled.workflowCode).toContain( '__dynamicGlobalThis.__private_workflows.set(' ); }); }); describe('workflow id derivation', () => { it('is stable across calls', async () => { const a = await compileDynamicWorkflow(SOURCE, { steps: STEPS }); const b = await compileDynamicWorkflow(SOURCE, { steps: STEPS }); expect(a.workflowName).toBe(b.workflowName); expect(a.metadata.sourceHash).toBe(b.metadata.sourceHash); }); it('does not depend on the order the steps were declared in', async () => { // Otherwise the same workflow would land on two different queue topics // depending on how the caller happened to build the object. const a = await compileDynamicWorkflow(SOURCE, { steps: STEPS }); const b = await compileDynamicWorkflow(SOURCE, { steps: { sendEmail: STEPS.sendEmail, fetchUser: STEPS.fetchUser, }, }); expect(a.workflowName).toBe(b.workflowName); }); it('changes when the source changes', async () => { const a = await compileDynamicWorkflow(SOURCE, { steps: STEPS }); const b = await compileDynamicWorkflow( SOURCE.replace('{ ok: true }', '{ ok: false }'), { steps: STEPS } ); expect(a.workflowName).not.toBe(b.workflowName); }); it('changes when a step binding changes', async () => { // The bindings are as much part of what executes as the source is: the // same text over different steps is a different workflow. const a = await compileDynamicWorkflow(SOURCE, { steps: STEPS }); const b = await compileDynamicWorkflow(SOURCE, { steps: { ...STEPS, sendEmail: { stepId: 'step//./src/steps//sendSms' }, }, }); expect(a.workflowName).not.toBe(b.workflowName); }); }); describe('metadata', () => { it('records the version, hash, export name and step bindings', async () => { const compiled = await compileDynamicWorkflow(SOURCE, { steps: STEPS }); expect(compiled.metadata).toEqual({ version: 1, sourceHash: expect.stringMatching(/^[0-9a-f]{64}$/), exportName: 'workflow', steps: { fetchUser: 'step//./src/steps//fetchUser', sendEmail: 'step//./src/steps//sendEmail', }, }); }); it('carries no source or code, so it stays inside the plaintext budget', async () => { // The metadata is readable without decrypting anything, so the code // must not be in it — that is the whole point of storing the code // encrypted behind a ref. const compiled = await compileDynamicWorkflow(SOURCE, { steps: STEPS }); const encoded = JSON.stringify(compiled.metadata); expect(encoded).not.toContain('use workflow'); expect(new TextEncoder().encode(encoded).byteLength).toBeLessThan(1024); }); }); describe('validation', () => { it('rejects source with no matching async function', async () => { await expect( compileDynamicWorkflow('const x = 1;', { steps: STEPS }) ).rejects.toThrow(/must declare `async function workflow/); }); it('rejects a non-async function', async () => { await expect( compileDynamicWorkflow('function workflow() { "use workflow"; }', { steps: STEPS, }) ).rejects.toThrow(/must declare `async function workflow/); }); it.each([ [ 'TypeScript annotations', 'async function workflow(input: { id: string }) {\n "use workflow";\n return 1;\n}', undefined, ], [ 'a reserved word as the function name', 'async function class(input) {\n "use workflow";\n return 1;\n}', 'class', ], [ 'an unbalanced brace', 'async function workflow(input) {\n "use workflow";\n if (input) {\n return 1;\n}', undefined, ], ])('rejects source the engine cannot parse: %s', async (_label, source, exportName) => { // The shallow checks above pass all of these; without parsing the // generated code here they would only fail at replay, on every // delivery of a run that already exists. await expect( compileDynamicWorkflow(source, { steps: STEPS, exportName }) ).rejects.toThrow(/not valid JavaScript/); }); it('rejects an inline "use step" function', async () => { // Nothing transforms dynamic source, so the directive would be inert // and the function would run inside the workflow VM. const source = `async function workflow(input) { "use workflow"; async function fetchUser(id) { "use step"; return fetch("https://example.com/" + id); } return fetchUser(input.id); }`; await expect( compileDynamicWorkflow(source, { steps: STEPS }) ).rejects.toThrow(/cannot declare "use step"/); }); it.each([ [ 'explicit resource management syntax', `async function workflow() { "use workflow"; using resource = null; return resource; }`, ], [ 'regular expression modifiers', `async function workflow() { "use workflow"; return /(?i:a)/.test("A"); }`, ], ])('rejects syntax newer than the pinned 2024 grammar: %s', async (_label, source) => { await expect( compileDynamicWorkflow(source, { steps: STEPS }) ).rejects.toThrow(/not valid JavaScript/); }); it('accepts representative ECMAScript 2024 syntax', async () => { const source = ` async function workflow(input = {}) { "use workflow"; const copy = structuredClone(input); return { ...copy, value: copy?.value ?? 1 }; } `; const compiled = await compileDynamicWorkflow(source, { steps: STEPS }); expect(() => new Script(compiled.workflowCode)).not.toThrow(); }); it.each([ [ 'nested declaration', 'function outer() { async function workflow() { "use workflow"; } }', ], [ 'comment spoof', '// async function workflow() { "use workflow"; }\nconst value = 1;', ], [ 'string spoof', 'const value = `async function workflow() { "use workflow"; }`;', ], ])('rejects a %s instead of a top-level declaration', async (_label, source) => { await expect( compileDynamicWorkflow(source, { steps: STEPS }) ).rejects.toThrow(/at top level/); }); it.each([ ['Object', 'const Object = null;'], ['Map', 'let Map = null;'], ['Symbol', 'function Symbol() {}'], ['globalThis', 'var globalThis = null;'], ['__dynamicUseStep', 'const __dynamicUseStep = null;'], ['__dynamicWorkflow', 'let __dynamicWorkflow = null;'], ['__dynamicGlobalThis', 'function __dynamicGlobalThis() {}'], ['steps', 'var steps = null;'], ['sleep', 'const sleep = null;'], ['createHook', 'let createHook = null;'], ['Error', 'class Error {}'], ])('isolates caller %s declarations from wrapper bindings', async (_binding, declaration) => { const source = ` ${declaration} async function workflow() { "use workflow"; return 1; } `; const compiled = await compileDynamicWorkflow(source, { steps: STEPS }); const sandbox = { [Symbol.for('WORKFLOW_USE_STEP')]: () => async () => undefined, [Symbol.for('WORKFLOW_SLEEP')]: async () => undefined, [Symbol.for('WORKFLOW_CREATE_HOOK')]: () => Promise.resolve(), }; const context = createContext(sandbox); runInContext(compiled.workflowCode, context); const workflow = runInContext( `globalThis.__private_workflows.get(${JSON.stringify(compiled.workflowName)})`, context ) as { workflowId?: string }; expect(workflow).toBeTypeOf('function'); expect(workflow.workflowId).toBe(compiled.workflowName); }); it('emits __proto__ as a callable own step without changing the catalog prototype', async () => { const source = ` async function workflow() { "use workflow"; return { own: Object.hasOwn(steps, "__proto__"), ordinaryPrototype: Object.getPrototypeOf(steps) === Object.prototype, result: await steps.__proto__(), }; } `; const stepId = 'step//./src/steps//prototypeAlias'; const compiled = await compileDynamicWorkflow(source, { steps: { ['__proto__']: { stepId } }, }); const sandbox = { [Symbol.for('WORKFLOW_USE_STEP')]: (id: string) => async () => id, [Symbol.for('WORKFLOW_SLEEP')]: async () => undefined, [Symbol.for('WORKFLOW_CREATE_HOOK')]: () => Promise.resolve(), }; const context = createContext(sandbox); runInContext(compiled.workflowCode, context); const workflow = runInContext( `globalThis.__private_workflows.get(${JSON.stringify(compiled.workflowName)})`, context ) as () => Promise>; expect(await workflow()).toEqual({ own: true, ordinaryPrototype: true, result: stepId, }); expect(compiled.metadata.steps).toEqual( Object.fromEntries([['__proto__', stepId]]) ); expect(compiled.workflowCode).toContain('["__proto__"]:'); }); it('registers a workflow that closes over all injected bindings', async () => { const source = ` async function workflow() { "use workflow"; await steps.fetchUser("u_1"); await sleep("1s"); return createHook({ token: "hook_1" }); } `; const compiled = await compileDynamicWorkflow(source, { steps: STEPS }); const calls: string[] = []; const hook = Promise.resolve('hook-result'); const sandbox = { [Symbol.for('WORKFLOW_USE_STEP')]: (stepId: string) => async () => { calls.push(stepId); }, [Symbol.for('WORKFLOW_SLEEP')]: async () => { calls.push('sleep'); }, [Symbol.for('WORKFLOW_CREATE_HOOK')]: () => hook, }; const context = createContext(sandbox); runInContext(compiled.workflowCode, context); const workflow = runInContext( `globalThis.__private_workflows.get(${JSON.stringify(compiled.workflowName)})`, context ) as () => Promise; expect(await workflow()).toBe('hook-result'); expect(calls).toEqual(['step//./src/steps//fetchUser', 'sleep']); }); it('accepts a genuine top-level async declaration without evaluating source', async () => { const marker = '__dynamicWorkflowValidationExecuted'; delete (globalThis as Record)[marker]; const source = ` globalThis.${marker} = true; async function workflow() { "use workflow"; return 1; } `; await expect( compileDynamicWorkflow(source, { steps: STEPS }) ).resolves.toMatchObject({ metadata: { exportName: 'workflow' } }); expect((globalThis as Record)[marker]).toBeUndefined(); }); it('rejects a missing "use workflow" directive', async () => { await expect( compileDynamicWorkflow( 'async function workflow() { await steps.fetchUser(); }', { steps: STEPS } ) ).rejects.toThrow(/"use workflow" directive/); }); it.each([ ['named import', 'import { x } from "y";\n'], ['namespace import', 'import * as y from "y";\n'], ['bare import', 'import "y";\n'], ['indented import', ' import { x } from "y";\n'], ['export function', 'export function helper() {}\n'], ['export const', 'export const helper = 1;\n'], ['export default', 'export default 1;\n'], ['export list', 'export { workflow };\n'], ['export list without a space', 'export{ workflow };\n'], ['export star', 'export * from "y";\n'], ])('rejects module syntax: %s', async (_label, prefix) => { // The code is evaluated as a script in the workflow VM, so module // syntax is a replay-time syntax error — catching it here turns a run // that could never execute into a failed call. await expect( compileDynamicWorkflow(prefix + SOURCE, { steps: STEPS }) ).rejects.toThrow(/cannot use `import` or `export`/); }); it.each([ ['an identifier starting with import', 'let importData = null;\n'], ['an identifier starting with export', 'let exportName = "x";\n'], ['a member of exports', 'const exporter = { exports: 1 };\n'], ])('accepts %s at the start of a line', async (_label, prefix) => { // Only the keyword followed by whitespace or module-syntax punctuation // is module syntax. An identifier that merely begins with the word is // ordinary code, and rejecting it would cost the caller a working // workflow for nothing. await expect( compileDynamicWorkflow(prefix + SOURCE, { steps: STEPS }) ).resolves.toMatchObject({ metadata: { version: 1 } }); }); it('accepts source that merely mentions import inside a string', async () => { // The check is anchored to the start of a line for exactly this: a // false positive costs the caller a working workflow, and prose inside // string arguments is normal in generated orchestration. const source = ` async function workflow() { "use workflow"; await steps.fetchUser("nothing to import here"); } `; await expect( compileDynamicWorkflow(source, { steps: STEPS }) ).resolves.toMatchObject({ metadata: { version: 1 } }); }); it('rejects source over the size limit', async () => { const filler = `\n// ${'x'.repeat(DYNAMIC_WORKFLOW_SOURCE_MAX_BYTES)}`; await expect( compileDynamicWorkflow(SOURCE + filler, { steps: STEPS }) ).rejects.toThrow(/over the \d+-byte limit/); }); it('rejects an empty step map', async () => { await expect( compileDynamicWorkflow(SOURCE, { steps: {} }) ).rejects.toThrow(/at least one registered step/); }); it('rejects a step value with no stepId', async () => { await expect( compileDynamicWorkflow(SOURCE, { steps: { fetchUser: {} as { stepId: string } }, }) ).rejects.toThrow(/imported step function or an object with/); }); it.each([ ['a step alias', { steps: { 'not-an-identifier': STEPS.fetchUser } }], ['an export name', { steps: STEPS, exportName: 'not-an-identifier' }], ])('rejects %s that is not a JavaScript identifier', async (_label, options) => { // These are interpolated into generated code, so anything that is not // an identifier would produce a syntax error at replay time at best. await expect( compileDynamicWorkflow(SOURCE, options as never) ).rejects.toThrow(WorkflowRuntimeError); }); it('rejects an export name the workflow queue cannot address', async () => { await expect( compileDynamicWorkflow( 'async function $workflow() { "use workflow"; return 1; }', { steps: STEPS, exportName: '$workflow' } ) ).rejects.toThrow(/"\$" cannot appear in workflow queue names/); }); it('rejects an export name over the length limit', async () => { const exportName = 'w'.repeat( DYNAMIC_WORKFLOW_EXPORT_NAME_MAX_LENGTH + 1 ); await expect( compileDynamicWorkflow( `async function ${exportName}() { "use workflow"; return 1; }`, { steps: STEPS, exportName } ) ).rejects.toThrow( `Dynamic workflow exportName is ${exportName.length} characters, over the ${DYNAMIC_WORKFLOW_EXPORT_NAME_MAX_LENGTH}-character limit.` ); }); it('accepts an export name at the length limit', async () => { const exportName = 'w'.repeat(DYNAMIC_WORKFLOW_EXPORT_NAME_MAX_LENGTH); await expect( compileDynamicWorkflow( `async function ${exportName}() { "use workflow"; return 1; }`, { steps: STEPS, exportName } ) ).resolves.toMatchObject({ metadata: { exportName } }); }); it.each([ ['a string argument', 'await steps.fetchUser("use step");'], ['a single-quoted string', "const label = 'use step';"], ['a template literal', 'const label = `use step`;'], ['a string after the prologue', 'const x = 1;\n "use step";'], ])('accepts "use step" in %s', async (_label, statement) => { const source = `async function workflow() { "use workflow"; ${statement} return 1; }`; await expect( compileDynamicWorkflow(source, { steps: STEPS }) ).resolves.toMatchObject({ metadata: { version: 1 } }); }); it.each([ ['an arrow function', 'const f = async () => { "use step"; return 1; };'], ['a class method', 'class C { async run() { "use step"; return 1; } }'], [ 'an object method', "const o = { async run() { 'use step'; return 1; } };", ], ])('rejects a "use step" directive in %s', async (_label, statement) => { const source = `async function workflow() { "use workflow"; ${statement} return 1; }`; await expect( compileDynamicWorkflow(source, { steps: STEPS }) ).rejects.toThrow(/cannot declare "use step"/); }); it('rejects a "use step" directive in the script prologue', async () => { await expect( compileDynamicWorkflow(`"use step";\n${SOURCE}`, { steps: STEPS }) ).rejects.toThrow(/cannot declare "use step"/); }); it('hints at async when a parse failure may be an await', async () => { const source = `function workflow(input) { "use workflow"; return await steps.fetchUser(input.id); }`; await expect( compileDynamicWorkflow(source, { steps: STEPS }) ).rejects.toThrow( /not valid JavaScript: Unexpected token.*If the error is at an `await`, declare the function as `async function workflow\(\.\.\.\)`\./ ); }); it('validates a deeply nested expression without overflowing the stack', async () => { const source = `function helper(x) { return x${'.a'.repeat(30_000)}; } ${SOURCE}`; await expect( compileDynamicWorkflow(source, { steps: STEPS }) ).resolves.toMatchObject({ metadata: { version: 1 } }); }); it.each([ [ 'declared twice', `${SOURCE}\n${SOURCE}`, /exactly once, but declares `function workflow` 2 times/, ], [ 'not async', 'function workflow() { "use workflow"; return 1; }', /at top level, but `workflow` is not async/, ], [ 'a generator', 'async function* workflow() { "use workflow"; }', /at top level, but `workflow` is a generator function/, ], ])('says what is wrong when the workflow function is %s', async (_label, source, message) => { await expect( compileDynamicWorkflow(source, { steps: STEPS }) ).rejects.toThrow(message); }); it('still accepts "$" in step aliases', async () => { await expect( compileDynamicWorkflow( 'async function workflow() { "use workflow"; return await steps.$fetch(); }', { steps: { $fetch: STEPS.fetchUser } } ) ).resolves.toMatchObject({ workflowName: expect.stringMatching(/\/\/workflow$/), }); }); }); }); describe('readDynamicWorkflowMetadata', () => { it('reads back what compile produced', async () => { const compiled = await compileDynamicWorkflow(SOURCE, { steps: STEPS }); expect( readDynamicWorkflowMetadata({ dynamicWorkflow: compiled.metadata }) ).toEqual(compiled.metadata); }); it.each([ ['undefined context', undefined], ['no marker', { workflowCoreVersion: '5.0.0' }], ['a non-object marker', { dynamicWorkflow: 'yes' }], ['an unknown version', { dynamicWorkflow: { version: 2 } }], [ 'a missing exportName', { dynamicWorkflow: { version: 1, sourceHash: 'a' } }, ], [ 'a missing sourceHash', { dynamicWorkflow: { version: 1, exportName: 'workflow' } }, ], ])('returns undefined for %s', (_label, executionContext) => { // executionContext is client-supplied and passes through the backend // unchecked, so the runtime validates the shape rather than trusting it: // the alternative to "not dynamic" is executing arbitrary stored bytes as // code. expect(readDynamicWorkflowMetadata(executionContext)).toBeUndefined(); }); it('defaults absent step bindings to an empty map', () => { expect( readDynamicWorkflowMetadata({ dynamicWorkflow: { version: 1, sourceHash: 'abc', exportName: 'wf' }, }) ).toEqual({ version: 1, sourceHash: 'abc', exportName: 'wf', steps: {}, }); }); });