import { Awaitable , InputGate , OutputGate } from "@miniflare/shared" ; import { ExecutionContext } from "ava" ; export function triggerPromise < T > ( ) { let trigger = ( ) => { } ; const promise = new Promise < T > ( ( resolve ) => ( trigger = resolve ) ) ; return [ trigger , promise ] ; } export class TestInputGate extends InputGate { #waitedTrigger : ( ) => void ; waitedPromise : Promise < void > ; #waitedForOpen = false ; constructor ( ) { super ( ) ; [ this . #waitedTrigger , this . waitedPromise ] = triggerPromise < void > ( ) ; } resetWaitedPromise ( ) { [ this . #waitedTrigger , this . waitedPromise ] = triggerPromise < void > ( ) ; this . #waitedForOpen = false ; } waitForOpen ( ) { if ( this . #waitedForOpen ) this . #waitedTrigger ( ) ; else this . #waitedForOpen = true ; return super . waitForOpen ( ) ; } } export async function waitsForInputGate < T > ( t , closure ) { const inputGate = new TestInputGate ( ) ; const [ openTrigger , openPromise ] = triggerPromise < void > ( ) ; const events = [ ] ; const promise = inputGate . runWith ( async ( ) => { void inputGate . runWithClosed ( ( ) => openPromise ) ; const result = await closure ( ) ; events . push ( 1 ) ; return result ; } ) ; await inputGate . waitedPromise ; events . push ( 2 ) ; openTrigger ( ) ; await promise ; t . deepEqual ( events , [ 2 , 1 ] ) ; return promise ; } class TestOutputGate extends OutputGate { readonly #waitedTrigger : ( ) => void ; readonly waitedPromise : Promise < void > ; constructor ( ) { super ( ) ; [ this . #waitedTrigger , this . waitedPromise ] = triggerPromise < void > ( ) ; } waitForOpen ( ) { this . #waitedTrigger ( ) ; return super . waitForOpen ( ) ; } } export async function waitsForOutputGate < T > ( t , closure , observed ) { const outputGate = new TestOutputGate ( ) ; const [ openTrigger , openPromise ] = triggerPromise < void > ( ) ; outputGate . waitUntil ( openPromise ) ; const promise = outputGate . runWith ( closure ) ; await outputGate . waitedPromise ; t . falsy ( await observed ( ) ) ; openTrigger ( ) ; await promise ; t . truthy ( await observed ( ) ) ; return promise ; }