2026-07-14 17:47:50 +08:00
import type { ProgressReporter } from "../application/ProgressReporter.js" ;
import type {
ObserveWebSessionInput ,
WebObservationSession ,
} from "../domain/browserSession.js" ;
2026-10-06 05:57:38 +08:00
import { AnalysisCancelledError } from "../domain/analysisErrorCore.js" ;
import { BrowserObservationError } from "../domain/browserObservationError.js" ;
2026-10-21 03:27:31 +08:00
import { WEB_RUNTIME_LIMITS } from "../domain/webRuntime.js" ;
2026-07-14 17:47:50 +08:00
import type { CdpEndpointDiscovery , CdpEndpointTarget } from "./CdpEndpoint.js" ;
2026-10-21 03:27:31 +08:00
import {
CdpConnection ,
type CdpEvent ,
type CdpTransportEvent ,
} from "./CdpConnection.js" ;
2026-07-14 17:47:50 +08:00
import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js" ;
2026-09-29 19:07:18 +08:00
import { authorizedMainFrame } from "./CdpAuthorizedMainFrame.js" ;
2026-07-14 17:47:50 +08:00
import {
allowedSanitizedUrl ,
2026-10-20 23:56:15 +08:00
delayWithCancellation ,
2026-07-14 17:47:50 +08:00
isHttpUrl ,
numberValue ,
recordValue ,
2026-10-21 03:27:31 +08:00
recordsValue ,
2026-10-07 11:23:37 +08:00
cdpStringValue ,
2026-07-14 17:47:50 +08:00
type UnknownRecord ,
} from "./CdpCaptureValues.js" ;
import { mainFrameUrl } from "./CdpCaptureDocuments.js" ;
2026-10-21 07:16:47 +08:00
import { cdpFrameIdentity } from "./CdpCaptureEventHelpers.js" ;
2026-10-07 21:45:07 +08:00
import { cdpTargetEventMatches } from "./CdpTargetEvents.js" ;
2026-07-14 17:47:50 +08:00
interface ObservationContext {
readonly connection : CdpConnection ;
2026-07-14 20:22:12 +00:00
readonly sessionId : string | undefined ;
2026-07-14 17:47:50 +08:00
readonly discovery : CdpEndpointDiscovery ;
readonly target : CdpEndpointTarget ;
readonly input : ObserveWebSessionInput ;
readonly signal? : AbortSignal ;
readonly progress? : ProgressReporter ;
}
type EndReason = WebObservationSession [ "window" ][ "end_reason" ];
type TimelineEvent = WebObservationSession [ "timeline" ][ number ];
2026-07-18 03:42:35 +00:00
interface TimelineEntryOptions {
readonly type : TimelineEvent [ "type" ];
readonly params : UnknownRecord ;
2026-10-21 03:27:31 +08:00
readonly timestamp? : number | null ;
2026-07-18 03:42:35 +00:00
readonly rawUrl? : string | null ;
readonly requestId? : string | null ;
readonly detail? : string | null ;
}
2026-07-14 17:47:50 +08:00
/** Observe external user actions without rejecting approved same-origin navigation. */
export const observeCdpSession = async (
context : ObservationContext ,
) : Promise < WebObservationSession > => {
const allowedOrigins = new Set ( context . input . allowed_origins );
2026-09-29 19:07:18 +08:00
const initial = await authorizedMainFrame ({
connection : context.connection ,
sessionId : context.sessionId ,
signal : context.signal ,
allowedOrigins ,
2026-10-07 21:45:07 +08:00
operation : "observe_web_session" ,
2026-09-29 19:07:18 +08:00
});
2026-07-14 17:47:50 +08:00
const initialUrl = mainFrameUrl ( initial ) ?? "" ;
const mainFrameId = frameId ( initial );
if ( mainFrameId === undefined )
throw new BrowserObservationError ( "inspect_web_page" , "protocol_error" );
2026-09-29 13:56:49 +08:00
const capture = new TimelineCapture ( allowedOrigins , mainFrameId , initialUrl );
2026-10-21 03:27:31 +08:00
let removeListener = () : void => {};
2026-07-14 20:38:33 +00:00
const removeDisconnectListener = context . connection . onDisconnect (() =>
2026-10-21 14:50:32 +08:00
capture . transportDisconnected (),
2026-07-14 20:38:33 +00:00
);
2026-07-14 17:47:50 +08:00
try {
await context . connection . send (
"Page.enable" ,
{},
context . sessionId ,
context . signal ,
);
await context . connection . send (
"Network.enable" ,
2026-09-29 13:56:49 +08:00
{},
2026-07-14 17:47:50 +08:00
context . sessionId ,
context . signal ,
);
2026-10-21 03:27:31 +08:00
await context . connection . send (
"Performance.enable" ,
{ timeDomain : "timeTicks" },
context . sessionId ,
context . signal ,
);
removeListener = context . connection . onEvent (( event ) => {
if ( cdpTargetEventMatches ( event , context . sessionId ))
capture . ingest ( event );
});
// Host wall time marks command dispatch. The returned browser monotonic
// timestamp is the authoritative cutoff for timestamped lifecycle facts.
const armedAt = new Date (). toISOString ();
const armTimestamp = performanceTimestamp (
await context . connection . send (
"Performance.getMetrics" ,
{},
context . sessionId ,
context . signal ,
),
);
capture . assertPreArmBufferWithinLimit ();
capture . arm ( armTimestamp );
2026-07-14 17:47:50 +08:00
await context . connection . send (
"Page.setLifecycleEventsEnabled" ,
{ enabled : true },
context . sessionId ,
context . signal ,
);
await context . progress ? . report ({
phase : "browser_observation" ,
completed : 1 ,
total : 2 ,
message :
2026-10-05 20:16:44 +08:00
"Browser observation armed; perform the requested user action now" ,
2026-07-14 17:47:50 +08:00
});
let endReason = await waitForWindow (
context . input . observation_ms ,
capture ,
context . signal ,
);
if ( endReason === "window_elapsed" )
endReason = await captureFinalUrl ( context , capture , allowedOrigins );
await context . progress ? . report ({
phase : "browser_observation" ,
completed : 2 ,
total : 2 ,
message : "Browser observation window ended" ,
terminal : true ,
});
2026-10-14 14:46:37 +08:00
if ( capture . scopeExcluded ) endReason = "target_left_scope" ;
2026-07-14 17:47:50 +08:00
return {
browser : context.discovery.version ,
target : {
target_id : context.target.id ,
initial_url : allowedSanitizedUrl ( initialUrl , allowedOrigins ) ? . url ?? "" ,
final_url : capture.finalUrl ,
},
window : {
armed_at : armedAt ,
ended_at : new Date (). toISOString (),
requested_ms : context.input.observation_ms ,
end_reason : endReason ,
},
timeline : capture.timeline ,
completeness : capture.completeness.snapshot (),
limitations : [
"The timeline begins after REA attaches; earlier navigation and network activity is unavailable." ,
"Only navigation metadata is retained; headers, bodies, cookies, console values, and payloads are not captured by this tool." ,
"An out-of-policy destination ends collection immediately and is recorded without its URL." ,
2026-10-21 03:27:31 +08:00
...( capture . hasUnknownEventTime
? [
"Timeline rows without a comparable producer timestamp have a null timestamp. Buffered events with unknown timing are retained as context only; they do not establish activity inside the selected observation window." ,
]
: []),
2026-07-14 17:47:50 +08:00
],
};
} finally {
removeListener ();
2026-07-14 20:38:33 +00:00
removeDisconnectListener ();
2026-07-14 17:47:50 +08:00
}
};
class TimelineCapture {
readonly timeline : TimelineEvent [] = [];
readonly completeness = new CdpCaptureCompleteness ([ "timeline" ]);
finalUrl : string | null ;
# sequence = 0 ;
# pendingReload = false ;
2026-10-14 14:46:37 +08:00
# scopeExcluded = false ;
2026-07-14 17:47:50 +08:00
# endReason : EndReason | undefined ;
2026-10-21 03:27:31 +08:00
# armTimestamp : number | undefined ;
# eventsBeforeArm : CdpTransportEvent [] = [];
# eventsBeforeArmBytes = 0 ;
# preArmBufferExceeded = false ;
# hasUnknownEventTime = false ;
2026-07-14 17:47:50 +08:00
readonly # listeners = new Set < ( reason : EndReason ) => void > ();
constructor (
private readonly allowedOrigins : ReadonlySet < string >,
2026-10-21 07:16:47 +08:00
private mainFrameId : string ,
2026-07-14 17:47:50 +08:00
initialUrl : string ,
) {
this . finalUrl =
allowedSanitizedUrl ( initialUrl , allowedOrigins ) ? . url ?? null ;
}
2026-10-21 03:27:31 +08:00
ingest ( event : CdpTransportEvent ) : void {
if ( this . # endReason !== undefined || this . # scopeExcluded ) return ;
if ( ! isTimelineEvent ( event . method )) return ;
if ( this . # armTimestamp === undefined ) {
this . # bufferBeforeArm ( event );
return ;
}
this . # ingestArmed ( event );
}
# ingestArmed ( event : CdpTransportEvent , bufferedBeforeArm = false ) : void {
2026-10-14 14:46:37 +08:00
if ( this . # endReason !== undefined || this . # scopeExcluded ) return ;
2026-07-14 17:47:50 +08:00
const params = recordValue ( event . params );
2026-10-21 07:16:47 +08:00
if ( params === undefined ) {
if (
event . method === "Page.frameRequestedNavigation" ||
event . method === "Page.frameNavigated" ||
event . method === "Page.navigatedWithinDocument"
)
this . completeness . exclude ( "timeline" , "invalid_protocol_value" );
return ;
}
2026-10-21 03:27:31 +08:00
const contextOnly =
bufferedBeforeArm && hasNoComparableProducerTimestamp ( event . method );
if ( contextOnly ) this . # hasUnknownEventTime = true ;
2026-07-14 17:47:50 +08:00
switch ( event . method ) {
case "Page.frameRequestedNavigation" :
2026-10-21 03:27:31 +08:00
this . # navigationRequested ( event , params , contextOnly );
2026-07-14 17:47:50 +08:00
break ;
case "Page.frameNavigated" :
2026-10-21 03:27:31 +08:00
this . # navigationCommitted ( event , params , contextOnly );
2026-07-14 17:47:50 +08:00
break ;
case "Page.navigatedWithinDocument" :
2026-10-21 03:27:31 +08:00
this . # sameDocument ( event , params , contextOnly );
2026-07-14 17:47:50 +08:00
break ;
case "Network.requestWillBeSent" :
2026-10-21 03:27:31 +08:00
this . # redirect ( params , bufferedBeforeArm );
2026-07-14 17:47:50 +08:00
break ;
case "Network.loadingFailed" :
2026-10-21 03:27:31 +08:00
this . # loadingFailed ( params , bufferedBeforeArm );
2026-07-14 17:47:50 +08:00
break ;
case "Page.lifecycleEvent" :
this . # lifecycle ( params );
break ;
case "Inspector.targetCrashed" :
2026-10-21 03:27:31 +08:00
this . targetTerminated ( params );
2026-07-14 17:47:50 +08:00
break ;
2026-10-21 14:50:32 +08:00
case "Target.detachedFromTarget" :
this . sessionDetached ( params );
break ;
2026-07-14 17:47:50 +08:00
}
}
2026-10-21 03:27:31 +08:00
arm ( timestamp : number ) : void {
this . # armTimestamp = timestamp ;
// Events can arrive after the browser samples Timestamp but before its
// command response. Defer interpretation so timestamped facts use the
// sampled cutoff instead of being lost at the transport boundary.
const pending = this . # eventsBeforeArm ;
this . # eventsBeforeArm = [];
this . # eventsBeforeArmBytes = 0 ;
for ( const event of pending ) this . # ingestArmed ( event , true );
}
assertPreArmBufferWithinLimit () : void {
if ( ! this . # preArmBufferExceeded ) return ;
this . # eventsBeforeArm = [];
this . # eventsBeforeArmBytes = 0 ;
throw new BrowserObservationError ( "observe_web_session" , "payload_limit" , {
detail : `The retained CDP event buffer exceeded its ${ String ( WEB_RUNTIME_LIMITS . retainedEventBytes ) } byte limit before the observation clock was sampled.` ,
});
}
# bufferBeforeArm ( event : CdpTransportEvent ) : void {
if ( this . # preArmBufferExceeded ) return ;
// The transport carries the original payload length, so budget admission
// does not reconstruct or reserialize parsed protocol data.
const bytes = event . wireBytes ;
if (
bytes >
WEB_RUNTIME_LIMITS . retainedEventBytes - this . # eventsBeforeArmBytes
) {
this . # preArmBufferExceeded = true ;
this . # eventsBeforeArm = [];
this . # eventsBeforeArmBytes = 0 ;
return ;
}
this . # eventsBeforeArm . push ( event );
this . # eventsBeforeArmBytes += bytes ;
}
2026-07-14 17:47:50 +08:00
onEnd ( listener : ( reason : EndReason ) => void ) : () => void {
if ( this . # endReason !== undefined ) listener ( this . # endReason );
else this . # listeners . add ( listener );
return () => this . # listeners . delete ( listener );
}
end ( reason : EndReason ) : void {
if ( this . # endReason !== undefined ) return ;
this . # endReason = reason ;
for ( const listener of this . # listeners ) listener ( reason );
this . # listeners . clear ();
}
2026-10-21 03:27:31 +08:00
targetTerminated ( params : UnknownRecord = {}) : void {
2026-07-14 20:38:33 +00:00
if ( this . # endReason !== undefined ) return ;
2026-07-18 03:42:35 +00:00
this . # add ({
type : "target_terminated" ,
2026-10-21 03:27:31 +08:00
params ,
timestamp : null ,
2026-07-18 03:42:35 +00:00
rawUrl : null ,
requestId : null ,
detail : "target_terminated" ,
});
2026-07-14 20:38:33 +00:00
this . end ( "target_terminated" );
}
2026-10-21 14:50:32 +08:00
sessionDetached ( params : UnknownRecord = {}) : void {
if ( this . # endReason !== undefined ) return ;
this . # add ({
type : "session_detached" ,
params ,
timestamp : null ,
rawUrl : null ,
requestId : null ,
detail : "session_detached" ,
});
this . end ( "session_detached" );
}
transportDisconnected () : void {
if ( this . # endReason !== undefined ) return ;
this . # add ({
type : "transport_disconnected" ,
params : {},
timestamp : null ,
rawUrl : null ,
requestId : null ,
detail : "transport_disconnected" ,
});
this . end ( "transport_disconnected" );
}
2026-07-14 17:47:50 +08:00
setFinalUrl ( rawUrl : string ) : void {
2026-10-14 14:46:37 +08:00
if ( this . # scopeExcluded ) return ;
2026-07-14 17:47:50 +08:00
const destination = scopedUrl ( rawUrl , this . allowedOrigins );
this . finalUrl = destination . scope === "approved" ? destination.url : null ;
}
2026-10-14 14:46:37 +08:00
get scopeExcluded () : boolean {
return this . # scopeExcluded ;
}
2026-10-21 03:27:31 +08:00
get hasUnknownEventTime () : boolean {
return this . # hasUnknownEventTime ;
}
2026-10-14 14:46:37 +08:00
excludeTargetScope (
reason : "invalid_protocol_value" | "out_of_target_scope" ,
) : void {
if ( this . # scopeExcluded ) return ;
this . # scopeExcluded = true ;
this . finalUrl = null ;
this . completeness . exclude ( "timeline" , reason );
}
2026-10-21 03:27:31 +08:00
# navigationRequested (
event : CdpEvent ,
params : UnknownRecord ,
contextOnly : boolean ,
) : void {
2026-10-21 07:16:47 +08:00
const identity = cdpFrameIdentity ( event , this . mainFrameId );
if ( identity . identityIssue !== null || identity . parentIssue !== null )
this . completeness . exclude ( "timeline" , "invalid_protocol_value" );
if ( identity . selection !== "main" ) return ;
2026-07-14 17:47:50 +08:00
const reason = safeDetail ( params . reason );
2026-10-21 03:27:31 +08:00
const rawUrl = cdpStringValue ( params . url );
const destination =
rawUrl === undefined ? undefined : scopedUrl ( rawUrl , this . allowedOrigins );
if ( ! contextOnly ) this . # pendingReload = reason === "reload" ;
2026-07-18 03:42:35 +00:00
this . # add ({
type : "navigation_requested" ,
2026-07-14 17:47:50 +08:00
params ,
2026-10-21 03:27:31 +08:00
timestamp : null ,
rawUrl : rawUrl ?? null ,
2026-07-18 03:42:35 +00:00
requestId : null ,
detail : reason ,
});
2026-10-21 03:27:31 +08:00
if ( destination !== undefined ) this . # stopIfOutOfScope ( destination );
2026-07-14 17:47:50 +08:00
}
2026-10-21 03:27:31 +08:00
# navigationCommitted (
event : CdpEvent ,
params : UnknownRecord ,
contextOnly : boolean ,
) : void {
2026-07-14 17:47:50 +08:00
const frame = recordValue ( params . frame );
2026-10-21 07:16:47 +08:00
const identity = cdpFrameIdentity ( event , this . mainFrameId );
if ( identity . identityIssue !== null || identity . parentIssue !== null )
this . completeness . exclude ( "timeline" , "invalid_protocol_value" );
if ( identity . selection !== "main" && ! identity . isRootReplacement ) return ;
2026-10-07 11:23:37 +08:00
const rawUrl = cdpStringValue ( frame ? . url );
2026-07-14 17:47:50 +08:00
const destination = scopedUrl ( rawUrl , this . allowedOrigins );
2026-10-21 07:16:47 +08:00
if ( identity . isRootReplacement ) {
this . mainFrameId = identity . frameId ?? this . mainFrameId ;
this . # pendingReload = false ;
if ( contextOnly ) {
this . # stopIfOutOfScope ( destination );
return ;
}
}
2026-07-18 03:42:35 +00:00
this . # add ({
2026-10-21 03:27:31 +08:00
type :
2026-10-21 07:16:47 +08:00
! identity . isRootReplacement && ! contextOnly && this . # pendingReload
2026-10-21 03:27:31 +08:00
? "same_origin_reload"
: "navigation_committed" ,
2026-07-18 03:42:35 +00:00
params : { ... params , frameId : frame?.id , loaderId : frame?.loaderId },
2026-10-21 03:27:31 +08:00
timestamp : null ,
2026-07-18 03:42:35 +00:00
rawUrl : rawUrl ?? null ,
requestId : null ,
detail : safeDetail ( frame ? . transitionType ),
});
2026-10-21 03:27:31 +08:00
if ( this . # stopIfOutOfScope ( destination )) return ;
if ( contextOnly ) return ;
2026-07-14 17:47:50 +08:00
this . # pendingReload = false ;
2026-10-21 03:27:31 +08:00
this . finalUrl = destination . url ;
2026-07-14 17:47:50 +08:00
}
2026-10-21 03:27:31 +08:00
# sameDocument (
event : CdpEvent ,
params : UnknownRecord ,
contextOnly : boolean ,
) : void {
2026-10-21 07:16:47 +08:00
const identity = cdpFrameIdentity ( event , this . mainFrameId );
if ( identity . identityIssue !== null || identity . parentIssue !== null )
this . completeness . exclude ( "timeline" , "invalid_protocol_value" );
if ( identity . selection !== "main" ) return ;
2026-10-07 11:23:37 +08:00
const rawUrl = cdpStringValue ( params . url );
2026-07-14 17:47:50 +08:00
const destination = scopedUrl ( rawUrl , this . allowedOrigins );
2026-07-18 03:42:35 +00:00
this . # add ({
type : "same_document_navigation" ,
params ,
2026-10-21 03:27:31 +08:00
timestamp : null ,
2026-07-18 03:42:35 +00:00
rawUrl : rawUrl ?? null ,
requestId : null ,
detail : null ,
});
2026-10-21 03:27:31 +08:00
if ( this . # stopIfOutOfScope ( destination )) return ;
if ( contextOnly ) return ;
this . finalUrl = destination . url ;
2026-07-14 17:47:50 +08:00
}
2026-10-21 03:27:31 +08:00
# redirect ( params : UnknownRecord , bufferedBeforeArm : boolean ) : void {
2026-10-07 11:23:37 +08:00
const resourceType = cdpStringValue ( params . type );
2026-10-05 02:58:14 -04:00
if ( resourceType !== undefined && resourceType !== "Document" ) return ;
2026-07-14 17:47:50 +08:00
if (
2026-10-07 11:23:37 +08:00
cdpStringValue ( params . frameId ) !== this . mainFrameId ||
2026-07-14 17:47:50 +08:00
recordValue ( params . redirectResponse ) === undefined
)
return ;
2026-10-21 03:27:31 +08:00
const eventTime = this . # networkEventTime ( params , bufferedBeforeArm );
if ( ! eventTime . keep ) return ;
2026-07-14 17:47:50 +08:00
const request = recordValue ( params . request );
2026-10-07 11:23:37 +08:00
const rawUrl = cdpStringValue ( request ? . url );
2026-07-14 17:47:50 +08:00
const destination = scopedUrl ( rawUrl , this . allowedOrigins );
2026-07-18 03:42:35 +00:00
this . # add ({
type : "redirect" ,
2026-07-14 17:47:50 +08:00
params ,
2026-10-21 03:27:31 +08:00
...( eventTime . timestamp === undefined
? {}
: { timestamp : eventTime.timestamp }),
2026-07-18 03:42:35 +00:00
rawUrl : rawUrl ?? null ,
2026-10-07 11:23:37 +08:00
requestId : cdpStringValue ( params . requestId ) ?? null ,
2026-07-18 03:42:35 +00:00
detail : null ,
});
2026-10-21 03:27:31 +08:00
if ( this . # stopIfOutOfScope ( destination )) return ;
2026-07-14 17:47:50 +08:00
}
2026-10-21 03:27:31 +08:00
# stopIfOutOfScope ( destination : {
readonly url : string | null ;
readonly scope : "approved" | "outside_policy" | "unsupported" ;
}) : boolean {
if ( destination . scope === "approved" ) return false ;
this . excludeTargetScope ( "out_of_target_scope" );
this . end ( "target_left_scope" );
return true ;
}
# loadingFailed ( params : UnknownRecord , bufferedBeforeArm : boolean ) : void {
2026-10-07 11:23:37 +08:00
const frame = cdpStringValue ( params . frameId );
2026-07-14 17:47:50 +08:00
if ( frame !== undefined && frame !== this . mainFrameId ) return ;
2026-10-21 03:27:31 +08:00
const eventTime = this . # networkEventTime ( params , bufferedBeforeArm );
if ( ! eventTime . keep ) return ;
2026-07-18 03:42:35 +00:00
this . # add ({
type : "load_failed" ,
2026-07-14 17:47:50 +08:00
params ,
2026-10-21 03:27:31 +08:00
...( eventTime . timestamp === undefined
? {}
: { timestamp : eventTime.timestamp }),
2026-07-18 03:42:35 +00:00
rawUrl : null ,
2026-10-07 11:23:37 +08:00
requestId : cdpStringValue ( params . requestId ) ?? null ,
2026-07-18 03:42:35 +00:00
detail : safeNetworkError ( params . errorText ),
});
2026-07-14 17:47:50 +08:00
}
2026-10-21 03:27:31 +08:00
# networkEventTime (
params : UnknownRecord ,
bufferedBeforeArm : boolean ,
) : {
readonly keep : boolean ;
readonly timestamp? : number | null ;
} {
if ( ! bufferedBeforeArm ) return { keep : true };
const timestamp = numberValue ( params . timestamp );
if ( timestamp === undefined || timestamp < 0 ) {
this . completeness . exclude ( "timeline" , "invalid_protocol_value" );
this . # hasUnknownEventTime = true ;
return { keep : true , timestamp : null };
}
if ( this . # armTimestamp === undefined || timestamp <= this . # armTimestamp )
return { keep : false , timestamp };
return { keep : true , timestamp };
}
2026-07-14 17:47:50 +08:00
# lifecycle ( params : UnknownRecord ) : void {
2026-10-07 11:23:37 +08:00
if ( cdpStringValue ( params . frameId ) !== this . mainFrameId ) return ;
2026-10-21 03:27:31 +08:00
const timestamp = numberValue ( params . timestamp );
if (
timestamp === undefined ||
timestamp < 0 ||
this . # armTimestamp === undefined
) {
this . completeness . exclude ( "timeline" , "invalid_protocol_value" );
return ;
}
if ( timestamp <= this . # armTimestamp ) return ;
2026-07-18 03:42:35 +00:00
this . # add ({
type : "lifecycle" ,
params ,
rawUrl : null ,
requestId : null ,
detail : safeDetail ( params . name ),
});
2026-07-14 17:47:50 +08:00
}
2026-07-18 03:42:35 +00:00
# add ( options : TimelineEntryOptions ) : void {
const {
type ,
params ,
rawUrl = null ,
requestId = null ,
detail = null ,
} = options ;
2026-07-14 17:47:50 +08:00
const destination =
rawUrl == null ? null : scopedUrl ( rawUrl , this . allowedOrigins );
2026-10-21 03:27:31 +08:00
const observedTimestamp = numberValue ( params . timestamp );
const timestamp =
options . timestamp === undefined ? observedTimestamp : options.timestamp ;
if (
timestamp === undefined ||
timestamp === null ||
( timestamp !== null && timestamp < 0 )
) {
this . # hasUnknownEventTime = true ;
}
if ( timestamp !== null && timestamp !== undefined && timestamp < 0 ) {
this . completeness . exclude ( "timeline" , "invalid_protocol_value" );
}
2026-07-14 17:47:50 +08:00
this . # sequence += 1 ;
this . timeline . push ({
sequence : this. # sequence ,
type ,
2026-10-21 03:27:31 +08:00
timestamp :
timestamp === undefined || ( timestamp !== null && timestamp < 0 )
? null
: timestamp ,
2026-07-14 17:47:50 +08:00
frame_id : boundedId ( params . frameId ),
loader_id : boundedId ( params . loaderId ),
2026-09-29 13:56:49 +08:00
request_id : requestId ?? null ,
2026-07-14 17:47:50 +08:00
url : destination?.scope === "approved" ? destination.url : null ,
destination_scope : destination?.scope ?? null ,
detail ,
});
}
}
2026-10-21 03:27:31 +08:00
const performanceTimestamp = ( value : unknown ) : number => {
const metrics = recordsValue ( recordValue ( value ) ? . metrics ). filter (
({ name }) => name === "Timestamp" ,
);
const timestamp = numberValue ( metrics [ 0 ] ? . value );
if ( metrics . length !== 1 || timestamp === undefined || timestamp < 0 )
throw new BrowserObservationError ( "observe_web_session" , "protocol_error" , {
detail :
"Performance.getMetrics returned no valid monotonic Timestamp metric." ,
});
return timestamp ;
};
2026-07-14 17:47:50 +08:00
const waitForWindow = async (
durationMs : number ,
capture : TimelineCapture ,
signal? : AbortSignal ,
) : Promise < EndReason > =>
await new Promise < EndReason >(( resolve , reject ) => {
2026-10-20 23:56:15 +08:00
const timerController = new AbortController ();
2026-07-14 17:47:50 +08:00
let settled = false ;
let removeEnd = () : void => {};
2026-10-20 23:56:15 +08:00
const settle = ( complete : () => void ) : void => {
2026-07-14 17:47:50 +08:00
if ( settled ) return ;
settled = true ;
2026-10-20 23:56:15 +08:00
timerController . abort ();
2026-07-14 17:47:50 +08:00
signal ? . removeEventListener ( "abort" , onAbort );
removeEnd ();
2026-10-20 23:56:15 +08:00
complete ();
2026-07-14 17:47:50 +08:00
};
2026-10-20 23:56:15 +08:00
const finish = ( reason : EndReason ) : void => settle (() => resolve ( reason ));
const onAbort = () : void =>
settle (() => {
reject (
new AnalysisCancelledError ( "observe_web_session" , {
cause : signal?.reason ,
}),
);
});
2026-07-14 17:47:50 +08:00
signal ? . addEventListener ( "abort" , onAbort , { once : true });
if ( signal ? . aborted === true ) onAbort ();
2026-10-20 23:56:15 +08:00
if ( ! settled ) removeEnd = capture . onEnd ( finish );
if ( settled ) return ;
void delayWithCancellation (
durationMs ,
"observe_web_session" ,
timerController . signal ,
). then (
() => finish ( "window_elapsed" ),
( cause : unknown ) => settle (() => reject ( cause )),
);
2026-07-14 17:47:50 +08:00
});
const captureFinalUrl = async (
context : ObservationContext ,
capture : TimelineCapture ,
allowedOrigins : ReadonlySet < string >,
) : Promise < EndReason > => {
2026-10-14 14:46:37 +08:00
if ( capture . scopeExcluded ) return "target_left_scope" ;
2026-07-14 17:47:50 +08:00
const result = await context . connection . send (
"Page.getFrameTree" ,
{},
context . sessionId ,
context . signal ,
);
2026-10-14 14:46:37 +08:00
if ( capture . scopeExcluded ) return "target_left_scope" ;
2026-07-14 17:47:50 +08:00
const url = mainFrameUrl ( result );
if (
url !== undefined &&
allowedSanitizedUrl ( url , allowedOrigins ) !== undefined
) {
capture . setFinalUrl ( url );
return "window_elapsed" ;
}
2026-10-14 14:46:37 +08:00
capture . excludeTargetScope (
2026-07-14 17:47:50 +08:00
url === undefined ? "invalid_protocol_value" : "out_of_target_scope" ,
);
return "target_left_scope" ;
};
const frameId = ( result : unknown ) : string | undefined =>
2026-10-07 11:23:37 +08:00
cdpStringValue (
2026-07-14 17:47:50 +08:00
recordValue ( recordValue ( recordValue ( result ) ? . frameTree ) ? . frame ) ? . id ,
);
2026-10-21 03:27:31 +08:00
const hasNoComparableProducerTimestamp = ( method : string ) : boolean =>
method === "Page.frameRequestedNavigation" ||
method === "Page.frameNavigated" ||
method === "Page.navigatedWithinDocument" ||
method === "Inspector.targetCrashed" ||
method === "Target.detachedFromTarget" ;
const isTimelineEvent = ( method : string ) : boolean =>
hasNoComparableProducerTimestamp ( method ) ||
method === "Network.requestWillBeSent" ||
method === "Network.loadingFailed" ||
method === "Page.lifecycleEvent" ;
2026-07-14 17:47:50 +08:00
const scopedUrl = (
value : string | undefined ,
allowedOrigins : ReadonlySet < string >,
) : {
readonly url : string | null ;
readonly scope : "approved" | "outside_policy" | "unsupported" ;
} => {
const allowed = allowedSanitizedUrl ( value , allowedOrigins );
if ( allowed !== undefined ) return { url : allowed.url , scope : "approved" };
return isHttpUrl ( value )
? { url : null , scope : "outside_policy" }
: { url : null , scope : "unsupported" };
};
2026-10-07 11:23:37 +08:00
const boundedId = ( value : unknown ) : string | null =>
cdpStringValue ( value ) ?? null ;
2026-07-14 17:47:50 +08:00
const safeDetail = ( value : unknown ) : string | null => {
2026-10-07 11:23:37 +08:00
const detail = cdpStringValue ( value ) ? . toLowerCase ();
2026-07-14 17:47:50 +08:00
return detail !== undefined && /^[a-z0-9_.:-]{1,100}$/u.test(detail)
? detail
: null ;
};
const safeNetworkError = ( value : unknown ) : string | null => {
2026-10-07 11:23:37 +08:00
const error = cdpStringValue ( value );
2026-07-14 17:47:50 +08:00
return error !== undefined && /^net::ERR_[A-Z0-9_]{1,100}$/u.test(error)
? error
: null ;
};