1+ import fs from 'fs' ;
2+ import path from 'path' ;
3+ import sizeOf from 'image-size' ;
14import { Browser , BrowserContext , Page } from "@playwright/test"
25import { Context } from "../types.js"
36import * as utils from "./utils.js"
@@ -133,4 +136,61 @@ export async function captureScreenshots(ctx: Context): Promise<Record<string,a
133136 utils . delDir ( 'screenshots' ) ;
134137
135138 return { capturedScreenshots, output } ;
136- }
139+ }
140+
141+ function getImageDimensions ( filePath : string ) : { width : number , height : number } | null {
142+ const buffer = fs . readFileSync ( filePath ) ;
143+ let width , height ;
144+
145+ if ( buffer . toString ( 'hex' , 0 , 2 ) === 'ffd8' ) {
146+ // JPEG
147+ let offset = 2 ;
148+ while ( offset < buffer . length ) {
149+ const marker = buffer . toString ( 'hex' , offset , offset + 2 ) ;
150+ offset += 2 ;
151+ const length = buffer . readUInt16BE ( offset ) ;
152+ if ( marker === 'ffc0' || marker === 'ffc2' ) {
153+ height = buffer . readUInt16BE ( offset + 3 ) ;
154+ width = buffer . readUInt16BE ( offset + 5 ) ;
155+ return { width, height } ;
156+ }
157+ offset += length ;
158+ }
159+ } else if ( buffer . toString ( 'hex' , 1 , 4 ) === '504e47' ) {
160+ // PNG
161+ width = buffer . readUInt32BE ( 16 ) ;
162+ height = buffer . readUInt32BE ( 20 ) ;
163+ return { width, height } ;
164+ }
165+
166+ return null ;
167+ }
168+
169+ export async function uploadScreenshots ( ctx : Context ) : Promise < void > {
170+ let screenshotsDir = ctx . uploadFilePath ;
171+
172+ // Read all files in the screenshots directory
173+ const files = fs . readdirSync ( screenshotsDir ) ;
174+
175+ for ( let file of files ) {
176+ let fileExtension = path . extname ( file ) . toLowerCase ( ) ;
177+ if ( fileExtension === '.png' || fileExtension === '.jpeg' || fileExtension === '.jpg' ) {
178+ let filePath = `${ screenshotsDir } /${ file } ` ;
179+ let ssId = path . basename ( file , fileExtension ) ;
180+
181+ let viewport = 'default'
182+
183+ if ( ! ctx . options . ignoreResolutions ) {
184+ const dimensions = getImageDimensions ( filePath ) ;
185+ if ( ! dimensions ) {
186+ throw new Error ( `Unable to determine dimensions for image: ${ filePath } ` ) ;
187+ }
188+ const width = dimensions . width ;
189+ const height = dimensions . height ;
190+ viewport = `${ width } x${ height } ` ;
191+ }
192+
193+ await ctx . client . uploadScreenshot ( ctx . build , filePath , ssId , 'default' , viewport , ctx . log ) ;
194+ }
195+ }
196+ }
0 commit comments