UNPKG

creevey

Version:

Cross-browser screenshot testing tool for Storybook with fancy UI Runner

201 lines 8.03 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.downloadBinary = exports.isInsideDocker = exports.skipOptionKeys = exports.configExt = exports.LOCALHOST_REGEXP = exports.isShuttingDown = void 0; exports.shouldSkip = shouldSkip; exports.shouldSkipByOption = shouldSkipByOption; exports.shutdownWorkers = shutdownWorkers; exports.gracefullyKill = gracefullyKill; exports.shutdown = shutdown; exports.shutdownWithError = shutdownWithError; exports.getCreeveyCache = getCreeveyCache; exports.runSequence = runSequence; exports.testsToImages = testsToImages; exports.readDirRecursive = readDirRecursive; exports.tryToLoadTestsData = tryToLoadTestsData; exports.loadThroughTSX = loadThroughTSX; exports.waitOnUrl = waitOnUrl; const fs_1 = __importDefault(require("fs")); const https_1 = __importDefault(require("https")); const http_1 = __importDefault(require("http")); const cluster_1 = __importDefault(require("cluster")); const path_1 = require("path"); const url_1 = require("url"); const module_1 = require("module"); const find_cache_dir_1 = __importDefault(require("find-cache-dir")); const api_1 = require("tsx/esm/api"); const api_2 = require("tsx/cjs/api"); const types_js_1 = require("../types.js"); const messages_js_1 = require("./messages.js"); const importMetaUrl = (0, url_1.pathToFileURL)(__filename).href; exports.isShuttingDown = { current: false }; exports.LOCALHOST_REGEXP = /(localhost|127\.0\.0\.1)/i; exports.configExt = ['.js', '.mjs', '.ts', '.cjs', '.mts', '.cts']; exports.skipOptionKeys = ['in', 'kinds', 'stories', 'tests', 'reason']; function matchBy(pattern, value) { return ((typeof pattern == 'string' && pattern == value) || (Array.isArray(pattern) && pattern.includes(value)) || (pattern instanceof RegExp && pattern.test(value)) || !(0, types_js_1.isDefined)(pattern)); } function shouldSkip(browser, meta, skipOptions, test) { if (typeof skipOptions != 'object') { return skipOptions; } for (const skipKey in skipOptions) { const reason = shouldSkipByOption(browser, meta, skipOptions[skipKey], skipKey, test); if (reason) return reason; } return false; } function shouldSkipByOption(browser, meta, skipOption, reason, test) { if (Array.isArray(skipOption)) { for (const skip of skipOption) { const result = shouldSkipByOption(browser, meta, skip, reason, test); if (result) return result; } return false; } const { in: browsers, kinds, stories, tests } = skipOption; const { title, name } = meta; const skipByBrowser = matchBy(browsers, browser); const skipByKind = matchBy(kinds, title); const skipByStory = matchBy(stories, name); const skipByTest = !(0, types_js_1.isDefined)(test) || matchBy(tests, test); return skipByBrowser && skipByKind && skipByStory && skipByTest && reason; } async function shutdownWorkers() { exports.isShuttingDown.current = true; await Promise.all(Object.values(cluster_1.default.workers ?? {}) .filter(types_js_1.isDefined) .filter((worker) => worker.isConnected()) .map((worker) => new Promise((resolve) => { const timeout = setTimeout(() => { worker.kill(); }, 10000); worker.on('exit', () => { clearTimeout(timeout); resolve(); }); (0, messages_js_1.sendShutdownMessage)(worker); }))); (0, messages_js_1.emitShutdownMessage)(); } function gracefullyKill(worker) { worker.isShuttingDown = true; const timeout = setTimeout(() => { worker.kill(); }, 10000); worker.on('exit', () => { clearTimeout(timeout); }); (0, messages_js_1.sendShutdownMessage)(worker); } function shutdown() { process.exit(); } function shutdownWithError() { process.exit(1); } function getCreeveyCache() { return (0, find_cache_dir_1.default)({ name: 'creevey', cwd: (0, path_1.dirname)((0, url_1.fileURLToPath)(importMetaUrl)) }); } async function runSequence(seq, predicate) { for (const fn of seq) { if (predicate()) await fn(); } } function testsToImages(tests) { return new Set([].concat(...tests .filter(types_js_1.isDefined) .map(({ browser, testName, storyPath, results }) => Object.keys(results?.slice(-1)[0]?.images ?? {}).map((image) => `${[...storyPath, testName, browser, browser == image ? undefined : image] .filter(types_js_1.isDefined) .join('/')}.png`)))); } // https://tuhrig.de/how-to-know-you-are-inside-a-docker-container/ exports.isInsideDocker = fs_1.default.existsSync('/proc/1/cgroup') && fs_1.default.readFileSync('/proc/1/cgroup', 'utf-8').includes('docker'); const downloadBinary = (downloadUrl, destination) => new Promise((resolve, reject) => https_1.default.get(downloadUrl, (response) => { if (response.statusCode == 302) { const { location } = response.headers; if (!location) { reject(new Error(`Couldn't download selenoid. Status code: ${response.statusCode ?? 'UNKNOWN'}`)); return; } resolve((0, exports.downloadBinary)(location, destination)); return; } if (response.statusCode != 200) { reject(new Error(`Couldn't download selenoid. Status code: ${response.statusCode ?? 'UNKNOWN'}`)); return; } const fileStream = fs_1.default.createWriteStream(destination); response.pipe(fileStream); fileStream.on('finish', () => { fileStream.close(); resolve(); }); fileStream.on('error', (error) => { fs_1.default.unlink(destination, types_js_1.noop); reject(error); }); })); exports.downloadBinary = downloadBinary; function readDirRecursive(dirPath) { return [].concat(...fs_1.default .readdirSync(dirPath, { withFileTypes: true }) .map((dirent) => dirent.isDirectory() ? readDirRecursive(`${dirPath}/${dirent.name}`) : [`${dirPath}/${dirent.name}`])); } const _require = (0, module_1.createRequire)(importMetaUrl); function tryToLoadTestsData(filename) { try { return _require(filename); } catch { /* noop */ } } const [nodeVersion] = process.versions.node.split('.').map(Number); async function loadThroughTSX(callback) { const unregister = nodeVersion > 18 ? (0, api_1.register)() : (0, api_2.register)(); const result = await callback((modulePath) => nodeVersion > 18 ? import(modulePath) : // eslint-disable-next-line @typescript-eslint/no-require-imports Promise.resolve(require(modulePath))); // NOTE: `unregister` type is `(() => Promise<void>) | (() => void)` // eslint-disable-next-line @typescript-eslint/await-thenable, @typescript-eslint/no-confusing-void-expression await unregister(); return result; } function waitOnUrl(waitUrl, timeout, delay) { const urls = [waitUrl]; if (!exports.LOCALHOST_REGEXP.test(waitUrl)) { const parsedUrl = new URL(waitUrl); parsedUrl.host = 'localhost'; urls.push(parsedUrl.toString()); } const startTime = Date.now(); return Promise.race(urls.map((url) => new Promise((resolve, reject) => { const interval = setInterval(() => { http_1.default .get(url, (response) => { if (response.statusCode === 200) { clearInterval(interval); resolve(); } }) .on('error', () => { // Ignore HTTP errors }); if (Date.now() - startTime > timeout) { clearInterval(interval); reject(new Error(`${url} didn't respond within ${timeout / 1000} seconds`)); } }, delay); }))); } //# sourceMappingURL=utils.js.map