import { createRequire } from 'node:module' import assert from 'node:assert/strict' import { pathToFileURL } from 'node:url' const require = createRequire(import.meta.url) const playwright = process.env.ESTILO_PLAYWRIGHT ? await import(pathToFileURL(process.env.ESTILO_PLAYWRIGHT + '/index.mjs')) : require('playwright') const origin = process.argv[2] const gis = `window.google={accounts:{oauth2:{ initTokenClient(c){return {requestAccessToken(){window.requestCount=(window.requestCount||0)+1; if(new URL(location).searchParams.has('popup')){c.error_callback({type:'popup_failed_to_open'});return} if(new URL(location).searchParams.has('popup-closed')){c.error_callback({type:'popup_closed'});return} setTimeout(()=>c.callback(new URL(location).searchParams.has('denied')?{error:'access_denied'}:{access_token:'test-google-bearer',scope:'https://www.googleapis.com/auth/drive.file'}),new URL(location).searchParams.has('slow-auth')?150:10)} }}, hasGrantedAllScopes(r,s){return r.scope===s} }}};` const gapi = `window.gapi={load(name,config){ window.google.picker={Action:{CANCEL:'cancel',PICKED:'picked'},DocsView:class{setMimeTypes(s){return this}}, PickerBuilder:class{setDeveloperKey(){return this}setAppId(){return this}setOAuthToken(){return this}setOrigin(){return this}addView(){return this}setCallback(fn){this.callback=fn;return this} build(){const cb=this.callback;let node;return{setVisible(){node=document.createElement('div');node.id='mock-picker'; const pick=document.createElement('button');pick.textContent='Pick example';pick.onclick=()=>{const result={action:'picked',docs:[{id:'file_1',name:'Example',mimeType:new URL(location).searchParams.has('shortcut')?'application/vnd.google-apps.shortcut':'application/vnd.google-apps.document'}]};cb(result);if(new URL(location).searchParams.has('duplicate'))cb(result)};node.append(pick); const cancel=document.createElement('button');cancel.textContent='Cancel picker';cancel.onclick=()=>cb({action:'cancel'});node.append(cancel);document.body.append(node)},dispose(){node?.remove()}}}}}; config.callback()}};` for (const engine of (process.env.ESTILO_BROWSERS || 'chromium,webkit').split(',')) { const browser = await playwright[engine].launch() try { const context = await browser.newContext({viewport:{width:320,height:700}}) const page = await context.newPage() const violations = [] const errors = [] page.on('pageerror',e=>errors.push(e.message)) await page.addInitScript(()=>document.addEventListener('securitypolicyviolation',e=>console.log('CSP-VIOLATION:'+e.violatedDirective))) page.on('console',m=>{if(m.text().startsWith('CSP-VIOLATION:'))violations.push(m.text())}) await context.route('https://accounts.google.com/gsi/client',route=>route.fulfill({contentType:'text/javascript',body:gis})) await context.route('https://apis.google.com/js/api.js',route=>route.fulfill({contentType:'text/javascript',body:gapi})) let exportMode = 'ok', calls=0 await context.route('https://www.googleapis.com/drive/v3/files/**',async route=>{ calls++ assert.equal(route.request().headers().authorization,'Bearer test-google-bearer') assert(!route.request().url().includes('test-google-bearer')) if(exportMode==='slow')await new Promise(r=>setTimeout(r,250)) await route.fulfill({status:exportMode==='error'?403:200,headers:{'Access-Control-Allow-Origin':'*'}, body:exportMode==='error'?'refused':'fixture-export-bytes'}) }) const choose=page.locator('[data-google-choose]'), status=page.locator('[data-google-status]') const start=async query=>{const response=await page.goto(origin+query);assert(!response.headers()['cross-origin-opener-policy']);await choose.waitFor({state:'visible'});await page.waitForFunction(()=>!document.querySelector('[data-google-choose]').disabled)} const select=async()=>{await choose.click();await page.getByText('Pick example',{exact:true}).click()} await start('/'); await choose.focus(); await page.keyboard.press('Enter'); await page.getByText('Cancel picker',{exact:true}).click() assert.match(await status.textContent(),/cancelled/) assert.equal(await choose.isEnabled(),true) assert.equal(calls,0) await select(); await page.waitForURL(origin+'/upload'); assert.equal(await page.textContent('body'),'Imported') assert.equal(calls,1) await start('/?popup=1');await choose.click();assert.match(await status.textContent(),/popup/);assert(await choose.isEnabled()) await start('/?popup-closed=1');await choose.click();assert.match(await status.textContent(),/cancelled/);assert(await choose.isEnabled()) await page.locator('#file').setInputFiles({name:'previous.docx',mimeType:'application/octet-stream',buffer:Buffer.from('previous export')}) await page.evaluate(()=>dispatchEvent(new PageTransitionEvent('pageshow',{persisted:true}))) assert.equal(await page.locator('#file').evaluate(input=>input.files.length),0) await start('/?denied=1');await choose.click();await page.waitForFunction(()=>document.querySelector('[data-google-status]').textContent.includes('did not allow'));assert(await choose.isEnabled()) await start('/?shortcut=1');await select();await page.waitForFunction(()=>document.querySelector('[data-google-status]').textContent.includes('could not be exported'));assert.equal(calls,1) exportMode='error';await start('/');await select();await page.waitForFunction(()=>document.querySelector('[data-google-status]').textContent.includes('did not allow'));assert(await choose.isEnabled()) exportMode='ok';await select();await page.waitForURL(origin+'/upload');assert.equal(calls,3) await start('/?slow-auth=1');await choose.click();await page.locator('[data-google-cancel]').click();await page.waitForTimeout(200) assert.equal(await page.locator('#mock-picker').count(),0);assert.equal(calls,3);assert.match(await status.textContent(),/cancelled/) await start('/?duplicate=1');await select();await page.waitForURL(origin+'/upload');assert.equal(calls,4) exportMode='slow';await start('/');await select();await page.locator('[data-google-cancel]').click();await page.waitForTimeout(350) assert.equal(page.url(),origin+'/');assert.match(await status.textContent(),/cancelled/);assert(await choose.isEnabled()) exportMode='ok' await start('/');const box=await choose.boundingBox();assert(box.width>=24&&box.height>=24) assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)) assert.deepEqual(await page.evaluate(()=>({local:Object.keys(localStorage),session:Object.keys(sessionStorage)})),{local:[],session:[]}) await page.goto(origin+'/?disabled=1');assert.equal(await page.locator('[estilo-google-import]').count(),0) assert.deepEqual(violations,[]);assert.deepEqual(errors,[]) const noJS=await browser.newContext({javaScriptEnabled:false});const plain=await noJS.newPage();await plain.goto(origin) assert.equal(await plain.locator('[data-google-choose]').isVisible(),false) assert.equal(await plain.locator('#file').isVisible(),true) assert.match(await plain.locator('noscript').textContent(),/JavaScript/) console.log(engine+': chooser, cancel, popup, denied scope, shortcut, export, retry, multipart, CSP, reflow and scriptless checks passed') await noJS.close();await context.close() } finally { await browser.close() } }