Best JavaScript code snippet using playwright-internal
gittools.js
Source: gittools.js
1/**2 * Git Tools for the Pylon IDE3 *4 * @license GPLv3 <http://www.gnu.org/licenses/gpl.txt>5 */6"use strict";7var Plugin = require("../pylon.core/plugin");8var util = require("util");9var name = "gittools";10module.exports = function setup(options, imports, register) {11 imports.ide.register(name, GitToolsPlugin, register);12};13var GitToolsPlugin = function(ide) {14 this.ide = ide;15 this.hooks = ["command"];16 this.name = "gittools";17};18util.inherits(GitToolsPlugin, Plugin);19(function() {20 // TODO place these two functions in a separate file21 // Could be useful for others22 this.getGitTopDir = function(dirPath, absoluteFilePath, callback) {23 var _self = this;24 this.getGitTopDirProc(dirPath, function(err, gitRoot) {25 if (err || !gitRoot)26 return callback("Error getting git top dir: " + err +27 " | " + absoluteFilePath + " | " + dirPath);28 gitRoot = gitRoot.replace("\n", "");29 var relativeFilePath = absoluteFilePath.substr(gitRoot.length + 1);30 callback(null, relativeFilePath, gitRoot);31 });32 };33 this.getGitTopDirProc = function(path, callback) {34 // @TODO SECURITY35 var argv = ["rev-parse", "--show-toplevel"];36 this.spawnCommand("git", argv, this.ide.workspaceDir + path,37 function(err) { // Error38 return callback(err);39 },40 function(out) { // Data41 return callback(null, out);42 },43 function(code, err, out) {44 // Exit45 }46 );47 };48 /**49 * Entry point for hooked command from the Plugin arch.50 * Determines if the primary command is "gittools" and then51 * handles the subcommand. Assumes the user is passing a52 * file argument in @message to perform a git operation on53 *54 * @param {object} user55 * @param {object} message User's message to the plugin56 * @param {object} client Client connection to the server57 * @return {boolean} False if message.command != "gittools" so the Plugin58 * architecture knows to keep asking other plugins if they handle59 * message.command60 */61 this.command = function(user, message, client) {62 if (message.command != "gittools" || !message.file)63 return false;64 var _self = this;65 // Cleanup the file path66 if (message.file.indexOf("/workspace/" >= 0))67 message.file = message.file.substr(11);68 // Get the file's parent directory path69 var lastSlash = message.file.lastIndexOf("/");70 var dirPath = "/" + message.file.substr(0, lastSlash);71 // Get the absolute system path to the file (as opposed to the72 // relative file path passed to us by the user)73 var absoluteFilePath = _self.ide.workspaceDir + "/" + message.file;74 // Given the path to the file's parent directory and the75 // absolute file path, determine the top-level directory76 // location of the git repository holding the file77 this.getGitTopDir(dirPath, absoluteFilePath, function(err, relativeFilePath, gitRoot) {78 if (err)79 return _self.sendResult(0, message.command, {80 code: 0,81 argv: message.argv,82 err: err ? err : "No git root found for file",83 out: null84 });85 switch (message.subcommand) {86 case "blame":87 _self.gitBlame(message, relativeFilePath, gitRoot);88 break;89 case "log":90 _self.gitLog(message, relativeFilePath, gitRoot);91 break;92 case "show":93 _self.gitShow(message, relativeFilePath, gitRoot, message.hash);94 break;95 default:96 console.log("Git Tools warning: subcommand `" +97 message.subcommand + "` not found");98 break;99 }100 });101 return true;102 };103 this.gitBlame = function(message, relativeFilePath, gitRoot) {104 var gitCommand = "blame";105 var argv;106 if (message.hash)107 argv = [gitCommand, "-p", message.hash, "--", relativeFilePath];108 else109 argv = [gitCommand, "-p", relativeFilePath];110 var _self = this;111 this.spawnCommand("git", argv, gitRoot,112 function(err) { // Error113 _self.sendResult(0, message.command, {114 code: 0,115 err: err,116 gitcommand: gitCommand,117 file: message.file,118 out: null119 });120 },121 function(out) { }, // Data122 function(code, err, out) { // Exit123 _self.sendResult(0, message.command, {124 code: code,125 err: null,126 gitcommand: gitCommand,127 file: message.file,128 out: out129 });130 }131 );132 };133 this.gitLog = function(message, relativeFilePath, gitRoot) {134 var gitCommand = "log";135 var argv = [gitCommand, "--format=raw", "--reverse", "--", relativeFilePath];136 var _self = this;137 this.spawnCommand("git", argv, gitRoot,138 function(err) { // Error139 _self.sendResult(0, message.command, {140 code: 0,141 err: err,142 gitcommand: gitCommand,143 file: message.file,144 out: null145 });146 },147 function(out) { }, // Data148 function(code, err, out) { // Exit149 _self.sendResult(0, message.command, {150 code: code,151 err: null,152 gitcommand: gitCommand,153 file: message.file,154 out: out155 });156 }157 );158 };159 this.gitShow = function(message, relativeFilePath, gitRoot, hash) {160 var gitCommand = "show";161 var argv = [gitCommand, hash + ":" + relativeFilePath];162 var _self = this;163 this.spawnCommand("git", argv, gitRoot,164 function(err) { // Error165 _self.sendResult(0, message.command, {166 code: 0,167 err: err,168 gitcommand: gitCommand,169 hash: hash,170 file: message.file,171 out: null172 });173 },174 function(out) { }, // Data175 function(code, err, out) { // Exit176 _self.sendResult(0, message.command, {177 code: code,178 err: null,179 gitcommand: gitCommand,180 hash: hash,181 file: message.file,182 out: out183 });184 }185 );186 };187 this.dispose = function(callback) {188 // TODO kill all running processes!189 callback();190 };...
download.test.js
Source: download.test.js
1const {expect, test} = require('@oclif/test');2const td = require('testdouble');3const path = require('path');4describe('download', () => {5 const destination = 'destination';6 const relativeFilePath = '/some/file/path/file.zip'7 const absoluteFilePath = 'file:///some/file/path/file.zip'8 const remoteFilePath = 'http://website.com/files/file.zip'9 const localManifestPath = '/some/manifest/path/manifest.json'10 const remoteManifestPath = '/some/manifest/path/manifest.json'11 const manifestJsonLocalFile = [{12 "@id": absoluteFilePath,13 "@type": "koio:KnowledgeObject"14 }]15 const manifestJsonRemoteFile = [{16 "@id": remoteFilePath,17 "@type": "koio:KnowledgeObject"18 }]19 let downloadOptions = {20 extract: false,21 headers: {accept: ['application/zip', 'application/octet-stream']}22 };23 const fs = td.replace('fs-extra');24 const download = td.replace('download');25 const admzip = td.replace('adm-zip');26 const del = td.replace('del');27 td.when(fs.existsSync(relativeFilePath)).thenResolve(() => {28 })29 td.when(fs.existsSync(localManifestPath)).thenResolve(() => {30 })31 td.when(fs.writeJsonSync(manifestJsonLocalFile)).thenResolve(() => {32 })33 td.when(fs.copySync(relativeFilePath, path.join(destination, path.basename(relativeFilePath)))).thenResolve(() => {34 })35 td.when(download(remoteFilePath, path.join(process.cwd()), downloadOptions)).thenResolve(null);36 td.when(fs.readJsonSync(localManifestPath)).thenResolve(() => {37 return manifestJsonLocalFile38 })39 td.when(fs.readJsonSync(remoteManifestPath)).thenResolve(() => {40 return manifestJsonRemoteFile41 })42 td.when(del(td.matchers.anything())).thenResolve(() => {43 });44 describe('with files', () => {45 test46 .command([`download`, `-d`, `${destination}`, `-f`, `${relativeFilePath}`])47 .it('should create the destination directory if not already there', (context) => {48 td.verify(fs.ensureDirSync(destination))49 });50 test51 .command([`download`, `-f`, `${relativeFilePath}`])52 .it('should use the current directory if destination not set', (context) => {53 td.verify(fs.ensureDirSync(process.cwd()))54 });55 test56 .command([`download`, `-f`, `${relativeFilePath}`])57 .it('should copy the relative file', (context) => {58 td.verify(fs.copySync(relativeFilePath, path.join(process.cwd(), path.basename(relativeFilePath))))59 });60 test61 .command([`download`, `-d`, `${destination}`, `-f`, `${relativeFilePath}`])62 .it('should download the relative file to the destination', (context) => {63 td.verify(fs.copySync(relativeFilePath, path.join(destination, path.basename(relativeFilePath))))64 });65 test66 .command([`download`, `-f`, `${absoluteFilePath}`])67 .it('should copy the absolute file', (context) => {68 td.verify(fs.copySync(relativeFilePath, path.join(process.cwd(), path.basename(relativeFilePath))))69 });70 test71 .command([`download`, `-f`, `${remoteFilePath}`])72 .it('should download the remote file', (context) => {73 td.verify(download(74 remoteFilePath,75 path.join(process.cwd()),76 downloadOptions))77 });78 test79 .command([`download`, `-f`, `${relativeFilePath}`])80 .it('should write the relative file into the final manifest', (context) => {81 td.verify(fs.writeJsonSync(path.join(process.cwd(), 'manifest.json'), manifestJsonLocalFile, {spaces: 4}))82 });83 test84 .command([`download`, `-d`, `${destination}`, `-f`, `${relativeFilePath}`])85 .it('should write the final manifest in the destination', (context) => {86 td.verify(fs.writeJsonSync(path.join(destination, 'manifest.json'), manifestJsonLocalFile, {spaces: 4}))87 });88 test89 .command([`download`, `-f`, `${absoluteFilePath}`])90 .it('should write the absolute file into the final manifest', (context) => {91 td.verify(fs.writeJsonSync(path.join(process.cwd(), 'manifest.json'), manifestJsonLocalFile, {spaces: 4}))92 });93 test94 .command([`download`, `-f`, `${remoteFilePath}`])95 .it('should write the remote file into the final manifest', (context) => {96 td.verify(fs.writeJsonSync(path.join(process.cwd(), 'manifest.json'), manifestJsonRemoteFile, {spaces: 4}))97 });98 test99 .command([`download`, `-d`, `${destination}`,`-f`, `${remoteFilePath}`])100 .it('should delete the temporary directory', (context) => {101 td.verify(del([path.join(destination, 'tmp')]))102 });103 });104 describe('with manifest', () => {105 test106 .command([`download`, `-m`, `${localManifestPath}`])107 .it('should read the local manifest json', (context) => {108 td.verify(fs.readJsonSync(localManifestPath))109 });110 test111 .command([`download`, `-m`, `${localManifestPath}`])112 .it('should copy the local file in the manifest', (context) => {113 td.verify(fs.copySync(relativeFilePath, path.join(process.cwd(), path.basename(relativeFilePath))))114 });115 test116 .command([`download`, `-m`, `${remoteManifestPath}`])117 .it('should read the remote manifest json', (context) => {118 td.verify(fs.readJsonSync(remoteManifestPath))119 });120 test121 .command([`download`, `-m`, `${remoteManifestPath}`])122 .it('should download the remote file from the manifest', (context) => {123 td.verify(download(124 remoteFilePath,125 path.join(process.cwd()),126 downloadOptions))127 });128 test129 .command([`download`, `-m`, `${localManifestPath}`])130 .it('should write the local file from the original manifest into the final manifest', (context) => {131 td.verify(fs.writeJsonSync(path.join(process.cwd(), 'manifest.json'), manifestJsonLocalFile, {spaces: 4}))132 });133 test134 .command([`download`, `-m`, `${remoteManifestPath}`])135 .it('should write the remote file from the original manifest into the final manifest', (context) => {136 td.verify(fs.writeJsonSync(path.join(process.cwd(), 'manifest.json'), manifestJsonRemoteFile, {spaces: 4}))137 });138 test139 .command([`download`, `-d`, `${destination}`,`-m`, `${remoteManifestPath}`])140 .it('should delete the temporary directory', (context) => {141 td.verify(del([path.join(destination, 'tmp')]))142 });143 });...
eject.js
Source: eject.js
1'use strict';2// æ£æµ node çæ¬3require('webpack-launcher-utils/checkNodeVersion')();4// Makes the script crash on unhandled rejections instead of silently5// ignoring them. In the future, promise rejections that are not handled will6// terminate the Node.js process with a non-zero exit code.7// èæ¬æªç¥åå ç»æ¢è¿è¡ï¼éè¦æ示é误8process.on('unhandledRejection', err => {9 throw err;10});11const inquirer = require('react-dev-utils/inquirer');12const chalk = require('chalk');13const fs = require('fs-extra');14const path = require('path');15inquirer16 .prompt({17 type: 'confirm',18 name: 'shouldEject',19 message: 'Are you sure you want to eject? This action is permanent.',20 default: false,21 })22 .then(answer => {23 if (!answer.shouldEject) {24 console.log(chalk.cyan('Close one! Eject aborted.'));25 return;26 }27 const shouldCopyedFileRelativePaths = [28 './.eslintrc.js',29 './.babelrc.js',30 './config/webpack.config.js',31 './config/webpackDevServer.config.js',32 './config/webpackLauncher.config.js',33 './config/webpack.dll.config.js',34 './scripts/start.js',35 './scripts/build.js',36 './scripts/buildDll.js',37 './scripts/serveBuild.js',38 './bin/start.js',39 './bin/build.js',40 './bin/buildDll.js',41 './bin/serveBuild.js',42 ];43 shouldCopyedFileRelativePaths.forEach(relativeFilePath => {44 // æ£æ¥æ件æ¯å¦åå¨ï¼åªè¦å
¶ä¸åå¨ç«å³ä¸æ eject45 const file = path.resolve(relativeFilePath);46 if (fs.existsSync(file)) {47 console.log();48 console.log(chalk.red(`The ejected file ${relativeFilePath} exited! Eject aborted.`));49 console.log();50 console.log(51 chalk.cyan('Make sure that the file not existed in any of the following files:')52 );53 console.log();54 shouldCopyedFileRelativePaths.forEach(relativeFilePath => {55 console.log(` ${relativeFilePath}`);56 });57 process.exit();58 }59 });60 console.log();61 console.log('Ejecting...');62 console.log();63 shouldCopyedFileRelativePaths.forEach(relativeFilePath => {64 if (!!~relativeFilePath.indexOf('./public/')) {65 // public ç´æ¥å¤å¶66 console.log(` Adding ${chalk.cyan(relativeFilePath)}`);67 return;68 }69 // åå§æ件路å¾70 let originalFilePath = path.resolve(__dirname, '../', relativeFilePath);71 // å¤å¶åçè·¯å¾72 const copyedFilePath = path.resolve(relativeFilePath);73 if (relativeFilePath === './.eslintrc.js') {74 originalFilePath = path.resolve(__dirname, '../config/eslint.config.js');75 } else if (relativeFilePath === './.babelrc.js') {76 originalFilePath = path.resolve(__dirname, '../config/babel.config.js');77 } else if (relativeFilePath === './bin/start.js') {78 originalFilePath = path.resolve(__dirname, '../bin/webpack-launcher-start.js');79 } else if (relativeFilePath === './bin/build.js') {80 originalFilePath = path.resolve(__dirname, '../bin/webpack-launcher-build.js');81 } else if (relativeFilePath === './bin/buildDll.js') {82 originalFilePath = path.resolve(__dirname, '../bin/webpack-launcher-build-dll.js');83 } else if (relativeFilePath === './bin/serveBuild.js') {84 originalFilePath = path.resolve(__dirname, '../bin/webpack-launcher-serve-build.js');85 }86 const content = fs87 .readFileSync(originalFilePath, 'utf8')88 // Remove dead code from .js files on eject89 .replace(/\/\/ @remove-on-eject-begin([\s\S]*?)\/\/ @remove-on-eject-end/gm, '')90 .trim();91 console.log(` Adding ${chalk.cyan(relativeFilePath)}`);92 fs.outputFileSync(copyedFilePath, content);93 });94 updateCwdPackageJson();95 console.log();96 console.log('Ejected sucessfully!');97 });98function updateCwdPackageJson() {99 const cwdPacakgeJsonPath = path.resolve('package.json');100 const cwdPacakgeJson = require(cwdPacakgeJsonPath);101 cwdPacakgeJson.scripts.start = 'node ./bin/start.js';102 cwdPacakgeJson.scripts.build = 'node ./bin/build.js';103 cwdPacakgeJson.scripts['build-dll'] = 'node ./bin/buildDll.js';104 cwdPacakgeJson.scripts['serve-build'] = 'node ./bin/serveBuild.js';105 delete cwdPacakgeJson.scripts.eject;106 fs.outputFileSync(cwdPacakgeJsonPath, JSON.stringify(cwdPacakgeJson, null, 2));...
progmem-generator.js
Source: progmem-generator.js
1const { resolve, relative, sep } = require('path');2const { readdirSync, existsSync, unlinkSync, readFileSync, createWriteStream } = require('fs');3var zlib = require('zlib');4var mime = require('mime-types');5const ARDUINO_INCLUDES = "#include <Arduino.h>\n\n";6function getFilesSync(dir, files = []) {7 readdirSync(dir, { withFileTypes: true }).forEach(entry => {8 const entryPath = resolve(dir, entry.name);9 if (entry.isDirectory()) {10 getFilesSync(entryPath, files);11 } else {12 files.push(entryPath);13 }14 })15 return files;16}17function coherseToBuffer(input) {18 return Buffer.isBuffer(input) ? input : Buffer.from(input);19}20function cleanAndOpen(path) {21 if (existsSync(path)) {22 unlinkSync(path);23 }24 return createWriteStream(path, { flags: "w+" });25}26class ProgmemGenerator {27 constructor(options = {}) {28 const { outputPath, bytesPerLine = 20, indent = " ", includes = ARDUINO_INCLUDES } = options;29 this.options = { outputPath, bytesPerLine, indent, includes };30 }31 apply(compiler) {32 compiler.hooks.emit.tapAsync(33 { name: 'ProgmemGenerator' },34 (compilation, callback) => {35 const { outputPath, bytesPerLine, indent, includes } = this.options;36 const fileInfo = [];37 const writeStream = cleanAndOpen(resolve(compilation.options.context, outputPath));38 try {39 const writeIncludes = () => {40 writeStream.write(includes);41 }42 const writeFile = (relativeFilePath, buffer) => {43 const variable = "ESP_REACT_DATA_" + fileInfo.length;44 const mimeType = mime.lookup(relativeFilePath);45 var size = 0;46 writeStream.write("const uint8_t " + variable + "[] PROGMEM = {");47 const zipBuffer = zlib.gzipSync(buffer);48 zipBuffer.forEach((b) => {49 if (!(size % bytesPerLine)) {50 writeStream.write("\n");51 writeStream.write(indent);52 }53 writeStream.write("0x" + ("00" + b.toString(16).toUpperCase()).substr(-2) + ",");54 size++;55 });56 if (size % bytesPerLine) {57 writeStream.write("\n");58 }59 writeStream.write("};\n\n");60 fileInfo.push({61 uri: '/' + relativeFilePath.replace(sep, '/'),62 mimeType,63 variable,64 size65 });66 };67 const writeFiles = () => {68 // process static files69 const buildPath = compilation.options.output.path;70 for (const filePath of getFilesSync(buildPath)) {71 const readStream = readFileSync(filePath);72 const relativeFilePath = relative(buildPath, filePath);73 writeFile(relativeFilePath, readStream);74 }75 // process assets76 const { assets } = compilation;77 Object.keys(assets).forEach((relativeFilePath) => {78 writeFile(relativeFilePath, coherseToBuffer(assets[relativeFilePath].source()));79 });80 }81 const generateWWWClass = () => {82 return `typedef std::function<void(const String& uri, const String& contentType, const uint8_t * content, size_t len)> RouteRegistrationHandler; 83class WWWData {84${indent}public:85${indent.repeat(2)}static void registerRoutes(RouteRegistrationHandler handler) {86${fileInfo.map(file => `${indent.repeat(3)}handler("${file.uri}", "${file.mimeType}", ${file.variable}, ${file.size});`).join('\n')}87${indent.repeat(2)}}88};89`;90 }91 const writeWWWClass = () => {92 writeStream.write(generateWWWClass());93 }94 writeIncludes();95 writeFiles();96 writeWWWClass();97 writeStream.on('finish', () => {98 callback();99 });100 } finally {101 writeStream.end();102 }103 }104 );105 }106}...
directory.js
Source: directory.js
1import * as path from 'path';2import { createReadStream } from 'fs';3import FirstChunkStream from 'first-chunk-stream';4import stripBomStream from 'strip-bom-stream';5import { oneLine } from 'common-tags';6import { IOBase } from 'io/base';7import { walkPromise } from 'io/utils';8import log from 'logger';9export class Directory extends IOBase {10 async getFiles(_walkPromise = walkPromise) {11 // If we have already processed this directory and have data12 // on this instance return that.13 if (Object.keys(this.files).length) {14 log.info(oneLine`Files already exist for directory15 "${this.path}" returning cached data`);16 return this.files;17 }18 const files = await _walkPromise(this.path, {19 shouldIncludePath: (...args) => this.shouldScanFile(...args),20 });21 this.files = files;22 this.entries = Object.keys(files);23 return files;24 }25 async getPath(relativeFilePath) {26 if (!Object.prototype.hasOwnProperty.call(this.files, relativeFilePath)) {27 throw new Error(`Path "${relativeFilePath}" does not exist in this dir.`);28 }29 if (this.files[relativeFilePath].size > this.maxSizeBytes) {30 throw new Error(`File "${relativeFilePath}" is too large. Aborting`);31 }32 const absoluteDirPath = path.resolve(this.path);33 const filePath = path.resolve(path.join(absoluteDirPath, relativeFilePath));34 // This is belt and braces. Should never happen that a file was in35 // the files object and yet doesn't meet these requirements.36 if (37 !filePath.startsWith(absoluteDirPath) ||38 relativeFilePath.startsWith('/')39 ) {40 throw new Error(`Path argument must be relative to ${this.path}`);41 }42 return filePath;43 }44 async getFileAsStream(relativeFilePath, { encoding } = { encoding: 'utf8' }) {45 const filePath = await this.getPath(relativeFilePath);46 const readStream = createReadStream(filePath, {47 autoClose: true,48 encoding,49 flags: 'r',50 });51 return !encoding ? readStream : readStream.pipe(stripBomStream());52 }53 async getFileAsString(_path) {54 const readStream = await this.getFileAsStream(_path);55 return new Promise((resolve, reject) => {56 let content = '';57 readStream.on('readable', () => {58 let chunk;59 // eslint-disable-next-line no-cond-assign60 while ((chunk = readStream.read()) !== null) {61 content += chunk.toString();62 }63 });64 readStream.on('end', () => {65 resolve(content);66 });67 readStream.on('error', reject);68 });69 }70 async getChunkAsBuffer(relativeFilePath, chunkLength) {71 const filePath = await this.getPath(relativeFilePath);72 return new Promise((resolve) => {73 createReadStream(filePath, {74 flags: 'r',75 // This is important because you don't want to encode the76 // bytes if you are doing a binary check.77 encoding: null,78 autoClose: true,79 }).pipe(80 new FirstChunkStream({ chunkLength }, (_, enc) => {81 resolve(enc);82 })83 );84 });85 }...
index.js
Source: index.js
1import { PREVIEW_HOST, PREVIEW_ORIGIN } from '../../constants/preview';2import AWS from 'aws-sdk';3import chalk from 'chalk';4import fs from 'fs-extra';5import glob from 'glob';6import mime from 'mime-types';7import open from 'open';8import path from 'path';9const AWS_REGION = 'us-east-1';10const s3 = new AWS.S3({ region: AWS_REGION });11// Logging12const LOGFILE = path.join(process.cwd(), '.aws.publish.log');13const readLog = () => {14 if (!fs.existsSync(LOGFILE)) fs.writeFileSync(LOGFILE, '{}');15 return JSON.parse(fs.readFileSync(LOGFILE, 'utf-8'), (k, v) => {16 return typeof v === 'string' ? new Date(v) : v;17 });18};19const writeLog = () => fs.writeFileSync(LOGFILE, JSON.stringify(LOG));20const LOG = readLog();21const uploadFile = async(relativeFilePath, URL, DIST_DIR) => {22 const absoluteFilePath = path.resolve(DIST_DIR, relativeFilePath);23 const currentModifiedTime = fs.statSync(absoluteFilePath).mtime;24 const lastModifiedTime = LOG[URL + relativeFilePath];25 if (lastModifiedTime && currentModifiedTime <= lastModifiedTime) {26 console.log(chalk`{green.dim Skip} {yellow.dim ${relativeFilePath}}`);27 return;28 } else {29 console.log(chalk`{green.dim Send} {yellow.dim ${relativeFilePath}}`);30 LOG[URL + relativeFilePath] = currentModifiedTime;31 }32 const fileContent = fs.readFileSync(absoluteFilePath);33 const bucketPath = path.join(URL.replace(PREVIEW_ORIGIN + '/', ''), relativeFilePath);34 const contentType = mime.contentType(path.extname(absoluteFilePath));35 if (!contentType) return;36 const params = {37 Bucket: PREVIEW_HOST,38 Key: bucketPath,39 Body: fileContent,40 CacheControl: 'no-cache',41 ContentType: contentType,42 };43 return new Promise((resolve, reject) => {44 s3.putObject(params, function(err, data) {45 if (err) reject(err);46 resolve();47 });48 });49};50export default {51 async publishToAWS() {52 const URL = this.getPreviewURL();53 const files = glob.sync('**/*', { cwd: this.DIST_DIR, nodir: true });54 await Promise.all(files.map(file => uploadFile(file, URL, this.DIST_DIR)));55 writeLog();56 await open(URL);57 },...
v8-snapshots-util.js
Source: v8-snapshots-util.js
1const path = require('path')2console.log('snapshotResult:', snapshotResult)3if (typeof snapshotResult !== 'undefined') {4 console.log('snapshotResult available!', snapshotResult)5 const Module = require('module')6 const entryPointDirPath = path.resolve(7 global.require.resolve('react'),8 '..',9 '..',10 '..'11 )12 console.log('entryPointDirPath:', entryPointDirPath)13 Module.prototype.require = function (module) {14 const absoluteFilePath = Module._resolveFilename(module, this, false)15 let relativeFilePath = path.relative(entryPointDirPath, absoluteFilePath)16 if (!relativeFilePath.startsWith('./')) {17 relativeFilePath = `./${relativeFilePath}`18 }19 if (process.platform === 'win32') {20 relativeFilePath = relativeFilePath.replace(/\\/g, '/')21 }22 let cachedModule = snapshotResult.customRequire.cache[relativeFilePath]23 if (snapshotResult.customRequire.cache[relativeFilePath]) {24 console.log('Snapshot cache hit:', relativeFilePath)25 }26 if (!cachedModule) {27 console.log('Uncached module:', module, relativeFilePath)28 cachedModule = { exports: Module._load(module, this, false) }29 snapshotResult.customRequire.cache[relativeFilePath] = cachedModule30 }31 return cachedModule.exports32 }33 snapshotResult.setGlobals(34 global,35 process,36 window,37 document,38 console,39 global.require40 )...
clean.relative.path.ts
Source: clean.relative.path.ts
1#!/usr/bin/env node2'use strict';3import {toLower, replace, join, split} from 'lodash';4const cleanRelativePath = (rootFolder: string, absoluteFilePath: string, ext: '.ts' | '.js'): string => {5 let relativeFilePath = toLower(absoluteFilePath) + '/';6 relativeFilePath = replace(relativeFilePath, toLower(rootFolder), '');7 relativeFilePath = replace(relativeFilePath, toLower(ext), '');8 relativeFilePath = replace(relativeFilePath, 'root', '');9 relativeFilePath = join(split(relativeFilePath, '\\'), '/');10 relativeFilePath = join(split(relativeFilePath, '//'), '/');11 return relativeFilePath;12};...
Using AI Code Generation
1const path = require('path');2const {chromium} = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const relativeFilePath = require(path.join(__dirname, '../node_modules/playwright/lib/utils/utils.js')).relativeFilePath;8 console.log(relativeFilePath('test.js'));9 await browser.close();10})();
Using AI Code Generation
1const path = require('path');2const playwright = require('playwright');3(async () => {4 for (const browserType of ['chromium', 'firefox', 'webkit']) {5 const browser = await playwright[browserType].launch();6 const context = await browser.newContext();7 const page = await context.newPage();8 const elementHandle = await page.$('text=Get started');9 const filePath = await elementHandle.evaluate(element => element.ownerDocument.defaultView.relativeFilePath('test.js'));10 console.log(filePath);11 await browser.close();12 }13})();14const path = require('path');15const playwright = require('playwright');16(async () => {17 for (const browserType of ['chromium', 'firefox', 'webkit']) {18 const browser = await playwright[browserType].launch();19 const context = await browser.newContext();20 const page = await context.newPage();21 const elementHandle = await page.$('text=Get started');22 const filePath = await elementHandle.evaluate(element => element.ownerDocument.defaultView.relativeFilePath('src/test.js'));23 console.log(filePath);24 await browser.close();25 }26})();27const path = require('path');28const playwright = require('playwright');29(async () => {30 for (const browserType of ['chromium', 'firefox', 'webkit']) {31 const browser = await playwright[browserType].launch();32 const context = await browser.newContext();33 const page = await context.newPage();34 const elementHandle = await page.$('text=Get started');35 const filePath = await elementHandle.evaluate(element => element.ownerDocument.defaultView.relativeFilePath('src/subfolder/test.js'));36 console.log(filePath);37 await browser.close();38 }39})();
Using AI Code Generation
1const path = require('path');2const playwright = require('playwright');3const { relativeFilePath } = require('playwright/lib/server/utils');4(async () => {5 for (const browserType of ['chromium', 'firefox', 'webkit']) {6 const browser = await playwright[browserType].launch();7 const context = await browser.newContext();8 const page = await context.newPage();9 await page.goto(relativeFilePath(path.join(__dirname, 'index.html')));10 await page.screenshot({ path: `example-${browserType}.png` });11 await browser.close();12 }13})();14{15 "scripts": {16 },17 "dependencies": {18 }19}20{21 "scripts": {22 },23 "dependencies": {24 }25}26{
Using AI Code Generation
1const { relativeFilePath } = require('@playwright/test');2console.log(relativeFilePath('test.js'));3const { relativeFilePath } = require('@playwright/test');4console.log(relativeFilePath('/home/user/test.js'));5const { relativeFilePath } = require('@playwright/test');6console.log(relativeFilePath('/home/user/test.js', '/home/user'));7const { relativeFilePath } = require('@playwright/test');8console.log(relativeFilePath('/home/user/test.js', '/home/user/'));9const { relativeFilePath } = require('@playwright/test');10console.log(relativeFilePath('/home/user/test.js', '/home/user/other'));11const { relativeFilePath } = require('@playwright/test');12console.log(relativeFilePath('/home/user/test.js', '/home/user/other/'));13const { relativeFilePath } = require('@playwright/test');14console.log(relativeFilePath('/home/user/test.js', '/home/user/other/other'));15const { relativeFilePath } = require('@playwright/test');16console.log(relativeFilePath('/home/user/test.js', '/home/user/other/other/'));17const { relativeFilePath } = require('@playwright/test');18console.log(relativeFilePath('/home/user/test.js', '/home/user/other/other/other'));
Using AI Code Generation
1const path = require('path');2const { test, expect } = require('@playwright/test');3test('relativeFilePath', async ({ page }) => {4 const filePath = path.relative(process.cwd(), __filename);5 const relativeFilePath = page.internalModule().relativeFilePath(filePath);6 expect(relativeFilePath).toBe('test.js');7});8Your name to display (optional):
Using AI Code Generation
1const { test, expect } = require('@playwright/test');2const path = require('path');3test('test', async ({ page }) => {4 const filePath = path.resolve(__dirname, 'data/test.csv');5 const relativeFilePath = page.relativeFilePath(filePath);6 console.log(relativeFilePath);7 await page.waitForLoadState('networkidle');8});9 ✓ test (1s)10 1 passed (1s)
Using AI Code Generation
1const { relativeFilePath } = require('@playwright/test');2const path = require('path');3const relativePath = relativeFilePath(path.join(__dirname, 'relativeFilePath.js'));4console.log(relativePath);5const { relativeFilePath } = require('@playwright/test');6const path = require('path');7const relativePath = relativeFilePath(path.join(__dirname, 'relativeFilePath.js'));8console.log(relativePath);9const { relativeFilePath } = require('@playwright/test');10const path = require('path');11const relativePath = relativeFilePath(path.join(__dirname, 'relativeFilePath.js'));12console.log(relativePath);13const { relativeFilePath } = require('@playwright/test');14const path = require('path');15const relativePath = relativeFilePath(path.join(__dirname, 'relativeFilePath.js'));16console.log(relativePath);17const { relativeFilePath } = require('@playwright/test');18const path = require('path');19const relativePath = relativeFilePath(path.join(__dirname, 'relativeFilePath.js'));20console.log(relativePath);21const { relativeFilePath } = require('@playwright/test');22const path = require('path');23const relativePath = relativeFilePath(path.join(__dirname, 'relativeFilePath.js'));24console.log(relativePath);25const { relativeFilePath } = require('@playwright/test');26const path = require('path');27const relativePath = relativeFilePath(path.join(__dirname, 'relativeFilePath.js'));28console.log(relativePath);29const { relativeFilePath } = require('@playwright/test');30const path = require('path');31const relativePath = relativeFilePath(path.join(__dirname, 'relativeFilePath.js'));32console.log(relativePath);
Using AI Code Generation
1const { relativeFilePath } = require('@playwright/test');2console.log(relativeFilePath('test.js'));3const { relativeFilePath } = require('@playwright/test');4console.log(relativeFilePath('/Users/username/Documents/playwright/test.js'));5const { relativeFilePath } = require('@playwright/test');6console.log(relativeFilePath('test.js', '/Users/username/Documents/playwright/test.js'));7const { relativeFilePath } = require('@playwright/test');8console.log(relativeFilePath('/Users/username/Documents/playwright/test.js', '/Users/username/Documents/playwright/test.js'));9const { relativeFilePath } = require('@playwright/test');10console.log(relativeFilePath('test.js', '/Users/username/Documents/playwright/test.js', '/Users/username/Documents/playwright/test.js'));11const { relativeFilePath } = require('@playwright/test');12console.log(relativeFilePath('/Users/username/Documents/playwright/test.js', '/Users/username/Documents/playwright/test.js', '/Users/username/Documents/playwright/test.js'));13const { relativeFilePath } = require('@playwright/test');14console.log(relativeFilePath('/Users/username/Documents/playwright/test.js', '/Users/username/Documents/playwright/test.js', '/Users/username/Documents/playwright/test.js', '/Users/username/Documents/playwright/test.js'));15const { relativeFilePath } = require('@playwright/test');16console.log(relativeFilePath('/Users/
Using AI Code Generation
1const { relativeFilePath } = require('playwright/lib/utils/utils');2const path = require('path');3const filePath = relativeFilePath(__dirname, 'relativeFilePath.txt');4console.log(filePath);5const { relativeFilePath } = require('playwright/lib/utils/utils');6const path = require('path');7const filePath = relativeFilePath(__dirname, 'relativeFilePath.txt');8console.log(filePath);9const { relativeFilePath } = require('playwright/lib/utils/utils');10const path = require('path');11const filePath = relativeFilePath(__dirname, 'relativeFilePath.txt');12console.log(filePath);13const { relativeFilePath } = require('playwright/lib/utils/utils');14const path = require('path');15const filePath = relativeFilePath(__dirname, 'relativeFilePath.txt');16console.log(filePath);17const { relativeFilePath } = require('playwright/lib/utils/utils');18const path = require('path');19const filePath = relativeFilePath(__dirname, 'relativeFilePath.txt');20console.log(filePath);21const { relativeFilePath } = require('playwright/lib/utils/utils');22const path = require('path');23const filePath = relativeFilePath(__dirname, 'relativeFilePath.txt');24console.log(filePath);25const { relativeFilePath } = require('playwright/lib/utils/utils');26const path = require('path');27const filePath = relativeFilePath(__dirname, 'relativeFilePath.txt');28console.log(filePath);29const { relativeFilePath } = require('playwright/lib/utils/utils');30const path = require('path');31const filePath = relativeFilePath(__dirname, 'relativeFilePath.txt');32console.log(filePath);33const { relativeFilePath } = require('playwright/lib/utils/utils');34const path = require('path');35const filePath = relativeFilePath(__dirname, 'relativeFilePath.txt
Jest + Playwright - Test callbacks of event-based DOM library
firefox browser does not start in playwright
Is it possible to get the selector from a locator object in playwright?
How to run a list of test suites in a single file concurrently in jest?
Running Playwright in Azure Function
firefox browser does not start in playwright
This question is quite close to a "need more focus" question. But let's try to give it some focus:
Does Playwright has access to the cPicker object on the page? Does it has access to the window object?
Yes, you can access both cPicker and the window object inside an evaluate call.
Should I trigger the events from the HTML file itself, and in the callbacks, print in the DOM the result, in some dummy-element, and then infer from that dummy element text that the callbacks fired?
Exactly, or you can assign values to a javascript variable:
const cPicker = new ColorPicker({
onClickOutside(e){
},
onInput(color){
window['color'] = color;
},
onChange(color){
window['result'] = color;
}
})
And then
it('Should call all callbacks with correct arguments', async() => {
await page.goto(`http://localhost:5000/tests/visual/basic.html`, {waitUntil:'load'})
// Wait until the next frame
await page.evaluate(() => new Promise(requestAnimationFrame))
// Act
// Assert
const result = await page.evaluate(() => window['color']);
// Check the value
})
Check out the latest blogs from LambdaTest on this topic:
Native apps are developed specifically for one platform. Hence they are fast and deliver superior performance. They can be downloaded from various app stores and are not accessible through browsers.
One of the essential parts when performing automated UI testing, whether using Selenium or another framework, is identifying the correct web elements the tests will interact with. However, if the web elements are not located correctly, you might get NoSuchElementException in Selenium. This would cause a false negative result because we won’t get to the actual functionality check. Instead, our test will fail simply because it failed to interact with the correct element.
Smartphones have changed the way humans interact with technology. Be it travel, fitness, lifestyle, video games, or even services, it’s all just a few touches away (quite literally so). We only need to look at the growing throngs of smartphone or tablet users vs. desktop users to grasp this reality.
As part of one of my consulting efforts, I worked with a mid-sized company that was looking to move toward a more agile manner of developing software. As with any shift in work style, there is some bewilderment and, for some, considerable anxiety. People are being challenged to leave their comfort zones and embrace a continuously changing, dynamic working environment. And, dare I say it, testing may be the most ‘disturbed’ of the software roles in agile development.
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!!