// Offline import of the application (R4.10, recette J1.7): one reference // PDF picked on Home while online (the editor opens, the worker chunk is // fetched once), then the network goes, back to Home (« Accueil »), the // same PDF picked again through « Remplacer le bilan en cours ? ». The // import must open the editor from the cached worker chunk and the page's // compiled module. Two ways to lose the network, a fresh browser each: // emulate Playwright's offline mode (context.setOffline) // stop the server process killed (connection refused, as a LAN host // that went away) // The server is serve.mjs in its own process, so `stop` kills its sockets // too; its Cache-Control lines are checked first against docker/nginx.conf // (env.js no-store, /assets/ immutable). Headless WebKit never reuses the // HTTP cache for a worker script offline (R4.10 finding): its rows are // reported, not counted. Exit code 1 when a Chromium or Firefox row does // not open the editor, or any row shows a page error or leaves the page // without an answer (no editor, no inline line). // // PLAYWRIGHT_NODE_MODULES=... node scripts/browser/r4-offline-import.mjs \ // [--engines chromium,firefox,webkit] [--out ] import { spawn } from 'node:child_process' import { readdirSync, writeFileSync } from 'node:fs' import { join } from 'node:path' import { parseArgs } from 'node:util' import { IMPORT_ERROR, PICK_LABEL } from './import-baseline.mjs' import { checkBuild } from './lib/app-build.mjs' import { tagged, timeoutAfter } from './lib/async.mjs' import { probedPage } from './lib/page-probes.mjs' import { DIST_DIR, FIXTURES_DIR, HARNESS_DIR, RESULTS_DIR, } from './lib/paths.mjs' import { ENGINES, closeEngine, launchEngine, loadPlaywright, } from './lib/playwright.mjs' import { resultsJson } from './lib/results-json.mjs' import { IMMUTABLE, NO_STORE } from './serve.mjs' const REFERENCE = join(FIXTURES_DIR, 'pdf/r3/demo.fr.logos.pdf') const MODES = ['emulate', 'stop'] const REPLACE_LABEL = 'Remplacer' // fr.ts session.replace.confirm const HOME_LABEL = 'Accueil' // fr.ts common.home const CANVAS = '.svg-canvas [data-anno-id]' // The import's two timers (10 s start, 20 s task) and a margin. const ANSWER_TIMEOUT_MS = 40_000 const LOAD_TIMEOUT_MS = 60_000 const COUNTED = new Set(['chromium', 'firefox']) const today = () => new Date().toISOString().slice(0, 10) const log = (line) => console.error(`[${new Date().toISOString()}] ${line}`) function options() { const { values } = parseArgs({ options: { engines: { type: 'string', default: ENGINES.join(',') }, out: { type: 'string', default: join(RESULTS_DIR, `${today()}-r4-offline-import.json`), }, }, }) const engines = values.engines.split(',').filter(Boolean) const unknown = engines.filter((e) => !ENGINES.includes(e)) if (unknown.length) throw new Error(`unknown engines: ${unknown.join(', ')}`) return { engines, out: values.out } } /** serve.mjs in a child process on a free port; resolves with its URL. */ function startChildServer() { const child = spawn( process.execPath, [join(HARNESS_DIR, 'serve.mjs'), '--port', '0'], { stdio: ['ignore', 'pipe', 'inherit'] }, ) const url = new Promise((done, fail) => { child.once('exit', (code) => fail(new Error(`serve.mjs exited ${code}`))) child.stdout.on('data', (chunk) => { const match = String(chunk).match(/serving apps\/app\/dist on (\S+)/) if (match) done(match[1]) }) }) return { child, url } } /** The Cache-Control lines nginx.conf sets, read back from the server. */ async function cacheHeaders(baseUrl) { const worker = readdirSync(join(DIST_DIR, 'assets')).find((name) => /^import\.worker-.*\.js$/.test(name), ) const read = async (path) => (await fetch(`${baseUrl}${path}`)).headers.get('cache-control') const envJs = await read('/env.js') const workerChunk = await read(`/assets/${worker}`) return { envJs, workerChunk, asNginx: envJs === NO_STORE && workerChunk === IMMUTABLE, } } /** One pick through the button (the replace dialog when a bilan is open). */ async function pickReference(page) { const chooser = page.waitForEvent('filechooser', { timeout: 10_000 }) await page.getByRole('button', { name: PICK_LABEL }).click() const replace = page.getByRole('button', { name: REPLACE_LABEL }) const replaced = await replace .waitFor({ timeout: 2000 }) .then(() => replace.click()) .then(() => true) .catch(() => false) await (await chooser).setFiles(REFERENCE) return replaced } /** The first answer of an import: the editor or the inline line. */ function answerOf(page) { return Promise.race([ tagged('editor', page.waitForURL('**/editor', { timeout: 0 })), tagged('error_text', page.locator(IMPORT_ERROR).waitFor({ timeout: 0 })), timeoutAfter(ANSWER_TIMEOUT_MS), ]) } /** Online import, then the network goes, then the offline import. */ async function offlineRun(page, context, server, mode) { await page.waitForSelector(`button:has-text("${PICK_LABEL}"):enabled`) await pickReference(page) const online = await answerOf(page) if (online.kind !== 'editor') return { online: online.kind } await page.waitForSelector(CANVAS, { timeout: LOAD_TIMEOUT_MS }) if (mode === 'emulate') await context.setOffline(true) else server.child.kill('SIGKILL') await page.getByRole('link', { name: HOME_LABEL }).first().click() const replaced = await pickReference(page) const offline = await answerOf(page) const errorText = await page .locator(IMPORT_ERROR) .textContent({ timeout: 300 }) .catch(() => null) return { online: 'editor', replaced, offline: offline.kind, errorText } } /** One engine and mode: its own server, browser and context. */ async function runOne(pw, engine, mode) { const server = startChildServer() let session = null try { const baseUrl = await server.url const headers = await cacheHeaders(baseUrl) session = await launchEngine(pw, engine) const context = await session.browser.newContext({ locale: 'fr-FR' }) const seed = { draft: null, locale: 'fr', skipDisclaimer: true } const { page, events } = await probedPage(context, seed) await page.goto(`${baseUrl}/`) const run = await offlineRun(page, context, server, mode) return { engine, mode, headers, ...run, pageErrors: events.pageErrors } } finally { if (session) await closeEngine(session) server.child.kill('SIGKILL') } } /** Why a row fails (header comment); empty when as expected. */ function problemsOf(row) { const problems = [] if (!row.headers.asNginx) problems.push('cache headers differ from nginx') if (row.online !== 'editor') problems.push(`online ${row.online}`) if (row.pageErrors.length) problems.push('page errors') if (row.offline === 'timeout') problems.push('no answer offline') if (COUNTED.has(row.engine) && row.offline !== 'editor') { problems.push(`offline ${row.offline}`) } return problems } async function main() { const { engines, out } = options() const build = checkBuild() const { pw, version } = loadPlaywright() const runs = [] for (const engine of engines) { for (const mode of MODES) { log(`${engine} ${mode}`) const row = await runOne(pw, engine, mode) runs.push({ ...row, problems: problemsOf(row) }) log(`${engine} ${mode}: offline ${row.offline} ${row.errorText ?? ''}`) } } const failed = runs.filter((r) => r.problems.length > 0) const result = { date: today(), playwright: version, build, runs } writeFileSync(out, `${resultsJson(result)}\n`) log(`${runs.length} runs, ${failed.length} not as expected → ${out}`) process.exitCode = failed.length ? 1 : 0 } await main()