File tree Expand file tree Collapse file tree 2 files changed +44
-5
lines changed
Expand file tree Collapse file tree 2 files changed +44
-5
lines changed Original file line number Diff line number Diff line change 1+ import { GLOBAL_OBJ } from './worldwide' ;
2+
3+ export type MinimalCloudflareContext = {
4+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
5+ waitUntil ( promise : Promise < any > ) : void ;
6+ } ;
7+
8+ export const CloudflareContextKey = '__cloudflare-context__' ;
9+
10+ /**
11+ * Function that delays closing of a Cloudflare lambda until the provided promise is resolved.
12+ */
13+ export function cloudflareWaitUntil ( task : Promise < unknown > ) : boolean {
14+ try {
15+ const cfContextSymbol = Symbol . for ( CloudflareContextKey ) ;
16+ const globalWithCfContext = GLOBAL_OBJ as typeof GLOBAL_OBJ & {
17+ [ cfContextSymbol ] : {
18+ ctx : MinimalCloudflareContext ;
19+ } ;
20+ } ;
21+
22+ const context = globalWithCfContext [ cfContextSymbol ] . ctx ;
23+
24+ if ( typeof context . waitUntil === 'function' ) {
25+ // eslint-disable-next-line no-console
26+ console . log ( 'flushing with cf' ) ;
27+ context . waitUntil ( task ) ;
28+ return true ;
29+ }
30+
31+ return false ;
32+ } catch {
33+ return false ;
34+ }
35+ }
Original file line number Diff line number Diff line change 11import { flush } from '../exports' ;
2+ import { type MinimalCloudflareContext , CloudflareContextKey , cloudflareWaitUntil } from './cloudflareWaitUntil' ;
23import { debug } from './debug-logger' ;
34import { vercelWaitUntil } from './vercelWaitUntil' ;
45import { GLOBAL_OBJ } from './worldwide' ;
56
6- type MinimalCloudflareContext = {
7- // eslint-disable-next-line @typescript-eslint/no-explicit-any
8- waitUntil ( promise : Promise < any > ) : void ;
9- } ;
10-
117async function flushWithTimeout ( timeout : number ) : Promise < void > {
128 try {
139 debug . log ( 'Flushing events...' ) ;
@@ -58,6 +54,14 @@ export async function flushIfServerless(
5854 return ;
5955 }
6056
57+ // @ts -expect-error This is not typed
58+ if ( GLOBAL_OBJ [ Symbol . for ( CloudflareContextKey ) ] ) {
59+ // If the cloudflareWaitUntil function is available, use it to flush the events, if not then fallback to the regular flush
60+ if ( cloudflareWaitUntil ( flushWithTimeout ( timeout ) ) ) {
61+ return ;
62+ }
63+ }
64+
6165 if ( typeof process === 'undefined' ) {
6266 return ;
6367 }
You can’t perform that action at this time.
0 commit comments