Best JavaScript code snippet using playwright-internal
cli.js
Source:cli.js  
...28run().catch(e => {29  console.error(e);30  process.exit(1);31});;32function getAllMarkdownFiles(dirPath, filePaths = []) {33  for (const entry of fs.readdirSync(dirPath, { withFileTypes: true })) {34    if (entry.isFile() && entry.name.toLowerCase().endsWith('.md'))35      filePaths.push(path.join(dirPath, entry.name));36    else if (entry.isDirectory())37      getAllMarkdownFiles(path.join(dirPath, entry.name), filePaths);38  }39  return filePaths;40}41async function run() {42  // Patch README.md43  const versions = await getBrowserVersions();44  {45    const params = new Map();46    const { chromium, firefox, webkit } = versions;47    params.set('chromium-version', chromium);48    params.set('firefox-version', firefox);49    params.set('webkit-version', webkit);50    params.set('chromium-version-badge', `[](https://www.chromium.org/Home)`);51    params.set('firefox-version-badge', `[](https://www.mozilla.org/en-US/firefox/new/)`);52    params.set('webkit-version-badge', `[](https://webkit.org/)`);53    let content = fs.readFileSync(path.join(PROJECT_DIR, 'README.md')).toString();54    content = content.replace(/<!-- GEN:([^ ]+) -->([^<]*)<!-- GEN:stop -->/ig, (match, p1) => {55      if (!params.has(p1)) {56        console.log(`ERROR: Invalid generate parameter "${p1}" in "${match}"`);57        process.exit(1);58      }59      return `<!-- GEN:${p1} -->${params.get(p1)}<!-- GEN:stop -->`;60    });61    writeAssumeNoop(path.join(PROJECT_DIR, 'README.md'), content, dirtyFiles);62  }63  // Patch docker version in docs64  {65    let playwrightVersion = require(path.join(PROJECT_DIR, 'package.json')).version;66    if (playwrightVersion.endsWith('-next'))67      playwrightVersion = playwrightVersion.substring(0, playwrightVersion.indexOf('-next'));68    const regex = new RegExp("(mcr.microsoft.com/playwright[^: ]*):?([^ ]*)");69    for (const filePath of getAllMarkdownFiles(path.join(PROJECT_DIR, 'docs'))) {70      let content = fs.readFileSync(filePath).toString();71      content = content.replace(new RegExp('(mcr.microsoft.com/playwright[^:]*):([\\w\\d-.]+)', 'ig'), (match, imageName, imageVersion) => {72        return `${imageName}:v${playwrightVersion}-focal`;73      });74      writeAssumeNoop(filePath, content, dirtyFiles);75    }76  }77  // Update device descriptors78  {79    const devicesDescriptorsSourceFile = path.join(PROJECT_DIR, 'packages', 'playwright-core', 'src', 'server', 'deviceDescriptorsSource.json')80    const devicesDescriptors = require(devicesDescriptorsSourceFile)81    for (const deviceName of Object.keys(devicesDescriptors)) {82      switch (devicesDescriptors[deviceName].defaultBrowserType) {83        case 'chromium':84          devicesDescriptors[deviceName].userAgent = devicesDescriptors[deviceName].userAgent.replace(85            /(.*Chrome\/)(.*?)( .*)/,86            `$1${versions.chromium}$3`87          ).replace(88            /(.*Edg\/)(.*?)$/,89            `$1${versions.chromium}`90          )91          break;92        case 'firefox':93          devicesDescriptors[deviceName].userAgent = devicesDescriptors[deviceName].userAgent.replace(94            /^(.*Firefox\/)(.*?)( .*?)?$/,95            `$1${versions.firefox}$3`96          ).replace(/^(.*rv:)(.*)(\).*?)$/, `$1${versions.firefox}$3`)97          break;98        case 'webkit':99          devicesDescriptors[deviceName].userAgent = devicesDescriptors[deviceName].userAgent.replace(100            /(.*Version\/)(.*?)( .*)/,101            `$1${versions.webkit}$3`102          )103          break;104        default:105          break;106      }107    }108    writeAssumeNoop(devicesDescriptorsSourceFile, JSON.stringify(devicesDescriptors, null, 2), dirtyFiles);109  }110  // Validate links111  {112    const langs = ['js', 'java', 'python', 'csharp'];113    const documentationRoot = path.join(PROJECT_DIR, 'docs', 'src');114    for (const lang of langs) {115      try {116        let documentation = parseApi(path.join(documentationRoot, 'api'));117        documentation.filterForLanguage(lang);118        if (lang === 'js') {119          const testDocumentation = parseApi(path.join(documentationRoot, 'test-api'), path.join(documentationRoot, 'api', 'params.md'));120          testDocumentation.filterForLanguage('js');121          const testRerpoterDocumentation = parseApi(path.join(documentationRoot, 'test-reporter-api'));122          testRerpoterDocumentation.filterForLanguage('js');123          documentation = documentation.mergeWith(testDocumentation).mergeWith(testRerpoterDocumentation);124        }125        // This validates member links.126        documentation.setLinkRenderer(() => undefined);127        const relevantMarkdownFiles = new Set([...getAllMarkdownFiles(documentationRoot)128          // filter out language specific files129          .filter(filePath => {130            const matches = filePath.match(/(-(js|python|csharp|java))+?/g);131            // no language specific document132            if (!matches)133              return true;134            // there is a language, lets filter for it135            return matches.includes(`-${lang}`);136          })137          // Standardise naming and remove the filter in the file name138          .map(filePath => filePath.replace(/(-(js|python|csharp|java))+/, ''))139          // Internally (playwright.dev generator) we merge test-api and test-reporter-api into api.140          .map(filePath => filePath.replace(/(\/|\\)(test-api|test-reporter-api)(\/|\\)/, `${path.sep}api${path.sep}`))]);141        for (const filePath of getAllMarkdownFiles(documentationRoot)) {142          if (langs.some(other => other !== lang && filePath.endsWith(`-${other}.md`)))143            continue;144          const data = fs.readFileSync(filePath, 'utf-8');145          const rootNode = md.filterNodesForLanguage(md.parse(data), lang);146          documentation.renderLinksInText(rootNode);147          // Validate links148          {149            md.visitAll(rootNode, node => {150              if (!node.text)151                return;152              for (const [, mdLinkName, mdLink] of node.text.matchAll(/\[([\w\s\d]+)\]\((.*?)\)/g)) {153                const isExternal = mdLink.startsWith('http://') || mdLink.startsWith('https://');154                if (isExternal)155                  continue;...file.js
Source:file.js  
1"use strict";2var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {3    if (k2 === undefined) k2 = k;4    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });5}) : (function(o, m, k, k2) {6    if (k2 === undefined) k2 = k;7    o[k2] = m[k];8}));9var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {10    Object.defineProperty(o, "default", { enumerable: true, value: v });11}) : function(o, v) {12    o["default"] = v;13});14var __importStar = (this && this.__importStar) || function (mod) {15    if (mod && mod.__esModule) return mod;16    var result = {};17    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);18    __setModuleDefault(result, mod);19    return result;20};21var __spreadArray = (this && this.__spreadArray) || function (to, from) {22    for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)23        to[j] = from[i];24    return to;25};26Object.defineProperty(exports, "__esModule", { value: true });27exports.save = exports.getAllMarkdownFiles = exports.buildPath = exports.jsPath = exports.faviconPath = exports.stylesPath = exports.radarPath = exports.relativePath = void 0;28var fs_extra_1 = require("fs-extra");29var path = __importStar(require("path"));30var walk_1 = require("walk");31var relativePath = function () {32    var relativePath = [];33    for (var _i = 0; _i < arguments.length; _i++) {34        relativePath[_i] = arguments[_i];35    }36    return path.resolve.apply(path, relativePath);37};38exports.relativePath = relativePath;39var radarPath = function () {40    var pathInSrc = [];41    for (var _i = 0; _i < arguments.length; _i++) {42        pathInSrc[_i] = arguments[_i];43    }44    return exports.relativePath.apply(void 0, __spreadArray(["radar"], pathInSrc));45};46exports.radarPath = radarPath;47var stylesPath = function () {48    var pathInSrc = [];49    for (var _i = 0; _i < arguments.length; _i++) {50        pathInSrc[_i] = arguments[_i];51    }52    return exports.relativePath.apply(void 0, __spreadArray(["styles"], pathInSrc));53};54exports.stylesPath = stylesPath;55var faviconPath = function () {56    var pathInSrc = [];57    for (var _i = 0; _i < arguments.length; _i++) {58        pathInSrc[_i] = arguments[_i];59    }60    return exports.relativePath.apply(void 0, __spreadArray(["assets/favicon.ico"], pathInSrc));61};62exports.faviconPath = faviconPath;63var jsPath = function () {64    var pathInSrc = [];65    for (var _i = 0; _i < arguments.length; _i++) {66        pathInSrc[_i] = arguments[_i];67    }68    return exports.relativePath.apply(void 0, __spreadArray(["js"], pathInSrc));69};70exports.jsPath = jsPath;71var buildPath = function () {72    var pathInDist = [];73    for (var _i = 0; _i < arguments.length; _i++) {74        pathInDist[_i] = arguments[_i];75    }76    return exports.relativePath.apply(void 0, __spreadArray(["build"], pathInDist));77};78exports.buildPath = buildPath;79var getAllMarkdownFiles = function (folder) {80    return getAllFiles(folder, isMarkdownFile);81};82exports.getAllMarkdownFiles = getAllMarkdownFiles;83var getAllFiles = function (folder, predicate) {84    return new Promise(function (resolve, reject) {85        var walker = walk_1.walk(folder, { followLinks: false });86        var files = [];87        walker.on("file", function (root, fileStat, next) {88            if (predicate(fileStat.name)) {89                files.push(path.resolve(root, fileStat.name));90            }91            next();92        });93        walker.on("errors", function (root, nodeStatsArray, next) {94            nodeStatsArray.forEach(function (n) {95                console.error("[ERROR] " + n.name);96                if (n.error) {97                    console.error(n.error.message || n.error.code + ": " + n.error.path);98                }99            });100            next();101        });102        walker.on("end", function () {103            resolve(files.sort());104        });105    });106};107var isMarkdownFile = function (name) { return name.match(/\.md$/) !== null; };108var save = function (data, fileName) {109    return fs_extra_1.outputFile(exports.buildPath(fileName), data);110};...api.js
Source:api.js  
...18  19  return { ...data }20}21export function getAllPages() {22  const paths = getAllMarkdownFiles(pagesDirectory)23  const pages = paths24    .map(path => getPageBySlug(path))25    .filter(page => devMode || page.published)26  return pages27}28export function getAllPagePaths() {29  const paths = getAllPages().map(page => page.slug.split('/'))30  return paths31}32export function getPageBySlug(slug) {33  const path = join(pagesDirectory, `${slug}.md`)34  const fileContents = fs.readFileSync(path)35  const { data, content } = matter(fileContents)36  // Preload block data37  if (data.blocks) {38    data.blocks = data.blocks.map(block => {39      switch (block.template) {40        case 'projects-block':41          block.projects = (block.limit == -1) ? getAllProjects() : getAllProjects().slice(0, block.limit)42          break;43        case 'articles-block':44          block.articles = (block.limit == -1) ? getAllArticles() : getAllArticles().slice(0, block.limit)45          break;46      }47      return block48    })49  }50  return { slug, content, ...data }51}52export function getAllProjects() {53  const paths = getAllMarkdownFiles(projectsDirectory)54  const projects = paths55    .map(path => {56      const project = getProjectBySlug(path)57      project.created_date = Date.parse(project.created_date)58      return project59    })60    .filter(project => devMode || project.published)61    .sort((a, b) => b.created_date - a.created_date)62  return projects63}64export function getProjectBySlug(slug) {65  const path = join(projectsDirectory, `${slug}.md`)66  const fileContents = fs.readFileSync(path)67  const { data } = matter(fileContents)68  return { ...data }69}70export function getAllArticles() {71  const paths = getAllMarkdownFiles(articlesDirectory)72  const articles = paths73    .map(path => {74      const article = getArticleBySlug(path)75      article.created_date = Date.parse(article.created_date)76      return article77    })78    .filter(article => devMode || article.published)79    .sort((a, b) => b.created_date - a.created_date)80  81  return articles82}83export function getAllArticlePaths() {84  const paths = getAllArticles().map(article => article.slug.split('/'))85  return paths...generate-directory.js
Source:generate-directory.js  
...17    });18    fs.writeFileSync(`./src/assets/blogs/${dir}`, JSON.stringify(directory));19}20function getNewFiles(directory) {21    const files = getAllMarkdownFiles();22    return files.filter(x => !directory.files.includes(x));23}24function getMetadataFromFile(filename) {25    const path = './public/blog/' + filename;26    const file = fs.readFileSync(path, 'utf8');27    const indexOfTags = file.indexOf(':tags') + 5;28    const indexOfEndOfTags = file.indexOf('\n', indexOfTags);29    const indexOfDesc = file.indexOf(':desc') + 5;30    const indexOfEndOfDesc = file.indexOf('\n', indexOfDesc);31    const tags = file.substring(indexOfTags, indexOfEndOfTags)32        .trim()33        .split(', ');34    const desc = file.substring(indexOfDesc, indexOfEndOfDesc).trim();35    return { tags: tags, desc: desc };36}37function getAllMarkdownFiles() {38    const files = fs.readdirSync('./public/blog/');39    return files.filter(file => file.substring(file.length - 3) == ".md");40}41function addNewFileToDirectory(directory, filename) {42    const metadata = getMetadataFromFile(filename);43    directory.files.push({ name: filename, desc: metadata.desc, tags: metadata.tags });44    const index = directory.files.length - 1;45    metadata.tags.forEach(tag => {46        directory.tags[tag] ? directory.tags[tag].push(index) : directory.tags[tag] = [index];47    });...build-markdown.js
Source:build-markdown.js  
...8    fileNames = fs.readdirSync(startingPath)9    for (fileName of fileNames) {10        filePath = path.join(startingPath, fileName)11        if (fs.lstatSync(filePath).isDirectory()){12            getAllMarkdownFiles(filePath, acc)13        } else if( filePath.endsWith('.md')){14            acc.push(filePath)15        }16    }17    return acc18}19const filePaths = getAllMarkdownFiles(markdownDir)20let posts = filePaths.map((filePath) => matter(fs.readFileSync(filePath)))...util.js
Source:util.js  
1import fs from 'fs'2import { join } from 'path'3export function getAllMarkdownFiles(directory, filelist = [], base = null) {4  const files = fs.readdirSync(directory)5  files.forEach(filename => {6    const path = join(directory, filename)7    8    if (fs.lstatSync(path).isDirectory()) {9      getAllMarkdownFiles(path, filelist, base ? base : `${directory}/`)10    } else if (/\.md$/.test(path)) {11      if (base) {12        filelist.push(join(directory.replace(base, ''), filename.replace(/\.md$/, '')))13      } else {14        filelist.push(filename.replace(/\.md$/, ''))15      }16    }17  })18  19  return filelist...getCollection.js
Source:getCollection.js  
...3const { parseMarkdown } = require('../utils/parseMarkdown')4const { getAllMarkdownFiles } = require('./getAllMarkdownFiles')5export default async function getCollection (config, collectionType) {6  const { sourceDir } = config7  let collectionFiles = getAllMarkdownFiles(sourceDir, collectionType)8  return Promise.all(collectionFiles.map(async (fileName) => {9    const content = await jetpack.readAsync(path.join(sourceDir, collectionType, fileName))10    return parseMarkdown(fileName, content)11  }))12}...getAllMarkdownFiles.js
Source:getAllMarkdownFiles.js  
1const jetpack = require('fs-jetpack');2function getAllMarkdownFiles (contentSrcDir, directory) {3  const contentDir = jetpack.cwd(`${contentSrcDir}/${directory}`);4  return contentDir.find({5    matching: ['*.md']6  });7}...LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!
