44
55import { SentienceBrowser } from './browser' ;
66import { Snapshot } from './types' ;
7+ import * as fs from 'fs' ;
8+ import * as path from 'path' ;
79
810export interface SnapshotOptions {
911 screenshot ?: boolean | { format : 'png' | 'jpeg' ; quality ?: number } ;
@@ -14,6 +16,30 @@ export interface SnapshotOptions {
1416 min_z_index ?: number ;
1517 } ;
1618 use_api ?: boolean ; // Force use of server-side API if True, local extension if False
19+ save_trace ?: boolean ; // Save raw_elements to JSON for benchmarking/training
20+ trace_path ?: string ; // Path to save trace file (default: "trace_{timestamp}.json")
21+ }
22+
23+ /**
24+ * Save raw_elements to a JSON file for benchmarking/training
25+ *
26+ * @param rawElements Raw elements data from snapshot
27+ * @param tracePath Path to save trace file. If undefined, uses "trace_{timestamp}.json"
28+ */
29+ function _saveTraceToFile ( rawElements : any [ ] , tracePath ?: string ) : void {
30+ // Default filename if none provided
31+ const filename = tracePath || `trace_${ Date . now ( ) } .json` ;
32+
33+ // Ensure directory exists
34+ const dir = path . dirname ( filename ) ;
35+ if ( dir !== '.' ) {
36+ fs . mkdirSync ( dir , { recursive : true } ) ;
37+ }
38+
39+ // Save the raw elements to JSON
40+ fs . writeFileSync ( filename , JSON . stringify ( rawElements , null , 2 ) ) ;
41+
42+ console . log ( `[SDK] Trace saved to: ${ filename } ` ) ;
1743}
1844
1945export async function snapshot (
@@ -83,6 +109,11 @@ async function snapshotViaExtension(
83109 return window . sentience . snapshot ( opts ) ;
84110 } , opts ) ;
85111
112+ // Save trace if requested
113+ if ( options . save_trace && result . raw_elements ) {
114+ _saveTraceToFile ( result . raw_elements , options . trace_path ) ;
115+ }
116+
86117 // Basic validation
87118 if ( result . status !== 'success' && result . status !== 'error' ) {
88119 throw new Error ( `Invalid snapshot status: ${ result . status } ` ) ;
@@ -122,6 +153,11 @@ async function snapshotViaApi(
122153 return ( window as any ) . sentience . snapshot ( opts ) ;
123154 } , rawOpts ) ;
124155
156+ // Save trace if requested (save raw data before API processing)
157+ if ( options . save_trace && rawResult . raw_elements ) {
158+ _saveTraceToFile ( rawResult . raw_elements , options . trace_path ) ;
159+ }
160+
125161 // Step 2: Send to server for smart ranking/filtering
126162 // Use raw_elements (raw data) instead of elements (processed data)
127163 // Server validates API key and applies proprietary ranking logic
0 commit comments