@@ -40,7 +40,7 @@ const offsetRanges: {
4040 { min : 5 , max : 24 , region : "ap-southeast-1" } , // UTC+5 to UTC+24
4141] ;
4242
43- function getClosestRegion ( timezone ?: string ) : BrowserbaseRegion {
43+ export function getClosestRegion ( timezone ?: string ) : BrowserbaseRegion {
4444 try {
4545 if ( ! timezone ) {
4646 return "us-west-2" ; // Default if no timezone provided
@@ -76,42 +76,61 @@ function getClosestRegion(timezone?: string): BrowserbaseRegion {
7676 }
7777}
7878
79+ export function buildBrowserSettings ( contextId : string ) : {
80+ advancedStealth : boolean ;
81+ context : { id : string ; persist : boolean } ;
82+ } {
83+ return {
84+ advancedStealth : true ,
85+ context : {
86+ id : contextId ,
87+ persist : true ,
88+ } ,
89+ } ;
90+ }
91+
92+ export function buildSessionCreateParams ( {
93+ projectId,
94+ timezone,
95+ contextId,
96+ } : {
97+ projectId : string ;
98+ timezone ?: string ;
99+ contextId : string ;
100+ } ) {
101+ return {
102+ projectId,
103+ browserSettings : buildBrowserSettings ( contextId ) ,
104+ keepAlive : true ,
105+ region : getClosestRegion ( timezone ) ,
106+ } as const ;
107+ }
108+
79109async function createSession ( timezone ?: string , contextId ?: string ) {
80110 const bb = new Browserbase ( {
81111 apiKey : process . env . BROWSERBASE_API_KEY ! ,
82112 } ) ;
83- const browserSettings : {
84- advancedStealth : boolean ;
85- context ?: { id : string ; persist : boolean } ;
86- } = {
87- advancedStealth : true ,
88- } ;
89- if ( contextId ) {
90- browserSettings . context = {
91- id : contextId ,
92- persist : true ,
93- } ;
94- } else {
113+ let sessionContextId = contextId ;
114+
115+ if ( ! sessionContextId ) {
95116 const context = await bb . contexts . create ( {
96117 projectId : process . env . BROWSERBASE_PROJECT_ID ! ,
97118 } ) ;
98- browserSettings . context = {
99- id : context . id ,
100- persist : true ,
101- } ;
119+ sessionContextId = context . id ;
102120 }
103121
104122 console . log ( "timezone " , timezone ) ;
105123 console . log ( "getClosestRegion(timezone)" , getClosestRegion ( timezone ) ) ;
106- const session = await bb . sessions . create ( {
107- projectId : process . env . BROWSERBASE_PROJECT_ID ! ,
108- browserSettings,
109- keepAlive : true ,
110- region : getClosestRegion ( timezone ) ,
111- } ) ;
124+ const session = await bb . sessions . create (
125+ buildSessionCreateParams ( {
126+ projectId : process . env . BROWSERBASE_PROJECT_ID ! ,
127+ timezone,
128+ contextId : sessionContextId ! ,
129+ } )
130+ ) ;
112131 return {
113132 session,
114- contextId : browserSettings . context ?. id ,
133+ contextId : sessionContextId ,
115134 } ;
116135}
117136
0 commit comments