// Real Sheets app and jobs; synthesized workbook and controlled Google replies. import assert from 'node:assert/strict' const playwright = await import(process.env.PLAYWRIGHT || 'playwright') const config = JSON.parse(process.env.SHEETS_GOOGLE_IMPORT_TEST) const fixture = Buffer.from(config.fixture, 'base64') const gis = `window.google={accounts:{oauth2:{initTokenClient(c){return{requestAccessToken(){c.callback({access_token:'controlled-google-bearer',scope:'https://www.googleapis.com/auth/drive.file'})}}},hasGrantedAllScopes(r,s){return r.scope===s}}}};` const gapi = `window.gapi={load(name,c){google.picker={Action:{PICKED:'picked',CANCEL:'cancel'},DocsView:class{setMimeTypes(){return this}},PickerBuilder:class{setDeveloperKey(){return this}setAppId(){return this}setOAuthToken(){return this}setOrigin(){return this}addView(){return this}setCallback(fn){this.cb=fn;return this}build(){const cb=this.cb;let el;return{setVisible(){el=document.createElement('button');el.textContent='Select import fixture';el.onclick=()=>cb({action:'picked',docs:[{id:'controlled_file',name:'Import fixture',mimeType:'application/vnd.google-apps.spreadsheet'}]});document.body.append(el)},dispose(){el?.remove()}}}}};c.callback()}};` for (const engine of ['chromium', 'webkit']) { const browser = await playwright[engine].launch() try { const context = await browser.newContext({ ignoreHTTPSErrors: true, viewport: { width: 1050, height: 850 } }) const cookies = config.cookies.map(c => ({ name: c.Name, value: c.Value, url: config.origin, httpOnly: c.HttpOnly, secure: c.Secure, sameSite: 'Lax' })) await context.addCookies(cookies) const page = await context.newPage() const failures = [], violations = [] let exports = 0, leaked = false page.on('pageerror', e => failures.push(e.message)) await page.addInitScript(() => document.addEventListener('securitypolicyviolation', e => console.log('IMPORT-CSP:' + e.violatedDirective))) page.on('console', m => { if (m.text().startsWith('IMPORT-CSP:')) violations.push(m.text()) }) page.on('request', r => { if (r.url().startsWith(config.origin) && ((r.postData() || '').includes('controlled-google-bearer') || JSON.stringify(r.headers()).includes('controlled-google-bearer'))) leaked = true }) await context.route('https://accounts.google.com/gsi/client', r => r.fulfill({ contentType: 'text/javascript', body: gis })) await context.route('https://apis.google.com/js/api.js', r => r.fulfill({ contentType: 'text/javascript', body: gapi })) await context.route('https://www.googleapis.com/drive/v3/files/**', async r => { exports++ assert.equal(r.request().headers().authorization, 'Bearer controlled-google-bearer') await r.fulfill({ headers: { 'Access-Control-Allow-Origin': '*' }, contentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', body: fixture }) }) const waitForReport = async p => { await p.waitForURL(url => /^\/sheets\/\d+\/import-report$/.test(url.pathname), { timeout: 30000 }) assert.match(await p.locator('body').innerText(), /formula/i) assert.match(await p.locator('body').innerText(), /text/i) return p.url() } await page.goto(config.origin + '/sheets/import') assert.match(await page.locator('body').innerText(), /first\s+worksheet/i) await page.waitForFunction(() => !document.querySelector('[data-google-choose]')?.disabled) await page.locator('[data-google-choose]').click() await page.getByRole('button', { name: 'Select import fixture', exact: true }).click() const reportURL = await waitForReport(page) const sheetPath = new URL(reportURL).pathname.replace('/import-report', '') await page.goto(config.origin + sheetPath) const cell = (r, c) => page.locator(`td[data-x="${c}"][data-y="${r}"]`) await cell(0, 0).waitFor({ state: 'visible' }) for (const [r, c, value] of [[0, 0, '00123'], [0, 1, '7'], [1, 0, '2'], [1, 1, '5'], [2, 0, '=x'], [2, 1, 'TRUE']]) { await page.waitForFunction(([r,c,v]) => document.querySelector(`td[data-x="${c}"][data-y="${r}"]`)?.textContent.trim() === v, [r,c,value]) } await cell(1, 0).dblclick() const editor = cell(1, 0).locator('input,textarea') await editor.waitFor() await editor.fill('10') await editor.press('Enter') await page.waitForFunction(() => document.querySelector('td[data-x="1"][data-y="1"]')?.textContent.trim() === '13') await page.evaluate(() => SheetsCellQueue([], SheetsGrid.post)) await page.reload() await page.waitForFunction(() => document.querySelector('td[data-x="1"][data-y="1"]')?.textContent.trim() === '13') assert.equal((await cell(0, 0).innerText()).trim(), '00123') assert.equal((await cell(0, 1).innerText()).trim(), '7') await page.goto(reportURL) assert.match(await page.locator('body').innerText(), /formula/i) assert.equal(exports, 1) assert.equal(leaked, false) assert.deepEqual(violations, []) assert.deepEqual(failures, []) const plainContext = await browser.newContext({ ignoreHTTPSErrors: true, javaScriptEnabled: false }) await plainContext.addCookies(cookies) const plain = await plainContext.newPage() await plain.goto(config.origin + '/sheets/import') assert.equal(await plain.locator('[data-google-choose]').isVisible(), false) await plain.locator('input[type="file"]').setInputFiles({ name: 'scriptless.xlsx', mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', buffer: fixture }) await plain.locator('form:has(input[type="file"]) button[type="submit"]').click() // Scriptless job pages use their ordinary refresh link while the job runs. for (let i = 0; i < 30 && !/\/sheets\/\d+\/import-report$/.test(new URL(plain.url()).pathname); i++) { await plain.waitForTimeout(100) await plain.reload() } const plainReport = await waitForReport(plain) await plain.goto(plainReport.replace('/import-report', '/table')) assert.match(await plain.locator('table[data-cell-table]').innerText(), /00123/) assert.match(await plain.locator('table[data-cell-table]').innerText(), /=x/) await plainContext.close() await context.close() console.log(engine + ': real import job, typed text, frozen value, supported formula recalculation, reload, report and scriptless upload passed') } finally { await browser.close() } }