Best JavaScript code snippet using playwright-internal
utils.js
Source:utils.js
...506 const lines = text.split('\n');507 const maxLength = Math.max(...lines.map(line => line.length));508 return ['â' + 'â'.repeat(maxLength + padding * 2) + 'â', ...lines.map(line => 'â' + ' '.repeat(padding) + line + ' '.repeat(maxLength - line.length + padding) + 'â'), 'â' + 'â'.repeat(maxLength + padding * 2) + 'â'].join('\n');509}510function isFilePayload(value) {511 return typeof value === 'object' && value['name'] && value['mimeType'] && value['buffer'];512}513function streamToString(stream) {514 return new Promise((resolve, reject) => {515 const chunks = [];516 stream.on('data', chunk => chunks.push(Buffer.from(chunk)));517 stream.on('error', reject);518 stream.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));519 });520}521async function transformCommandsForRoot(commands) {522 const isRoot = process.getuid() === 0;523 if (isRoot) return {524 command: 'sh',...
fetch.js
Source:fetch.js
1"use strict";2Object.defineProperty(exports, "__esModule", {3 value: true4});5exports.APIResponse = exports.APIRequestContext = exports.APIRequest = void 0;6var _fs = _interopRequireDefault(require("fs"));7var _path = _interopRequireDefault(require("path"));8var util = _interopRequireWildcard(require("util"));9var _errors = require("../utils/errors");10var _utils = require("../utils/utils");11var _channelOwner = require("./channelOwner");12var network = _interopRequireWildcard(require("./network"));13var _clientInstrumentation = require("./clientInstrumentation");14let _util$inspect$custom;15function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }16function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }17function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }18class APIRequest {19 // Instrumentation.20 constructor(playwright) {21 this._playwright = void 0;22 this._contexts = new Set();23 this._onDidCreateContext = void 0;24 this._onWillCloseContext = void 0;25 this._playwright = playwright;26 }27 async newContext(options = {}) {28 var _this$_onDidCreateCon;29 const storageState = typeof options.storageState === 'string' ? JSON.parse(await _fs.default.promises.readFile(options.storageState, 'utf8')) : options.storageState;30 const context = APIRequestContext.from((await this._playwright._channel.newRequest({ ...options,31 extraHTTPHeaders: options.extraHTTPHeaders ? (0, _utils.headersObjectToArray)(options.extraHTTPHeaders) : undefined,32 storageState33 })).request);34 this._contexts.add(context);35 await ((_this$_onDidCreateCon = this._onDidCreateContext) === null || _this$_onDidCreateCon === void 0 ? void 0 : _this$_onDidCreateCon.call(this, context));36 return context;37 }38}39exports.APIRequest = APIRequest;40class APIRequestContext extends _channelOwner.ChannelOwner {41 static from(channel) {42 return channel._object;43 }44 constructor(parent, type, guid, initializer) {45 super(parent, type, guid, initializer, (0, _clientInstrumentation.createInstrumentation)());46 this._request = void 0;47 if (parent instanceof APIRequest) this._request = parent;48 }49 async dispose() {50 var _this$_request, _this$_request$_onWil, _this$_request2;51 await ((_this$_request = this._request) === null || _this$_request === void 0 ? void 0 : (_this$_request$_onWil = _this$_request._onWillCloseContext) === null || _this$_request$_onWil === void 0 ? void 0 : _this$_request$_onWil.call(_this$_request, this));52 await this._channel.dispose();53 (_this$_request2 = this._request) === null || _this$_request2 === void 0 ? void 0 : _this$_request2._contexts.delete(this);54 }55 async delete(url, options) {56 return this.fetch(url, { ...options,57 method: 'DELETE'58 });59 }60 async head(url, options) {61 return this.fetch(url, { ...options,62 method: 'HEAD'63 });64 }65 async get(url, options) {66 return this.fetch(url, { ...options,67 method: 'GET'68 });69 }70 async patch(url, options) {71 return this.fetch(url, { ...options,72 method: 'PATCH'73 });74 }75 async post(url, options) {76 return this.fetch(url, { ...options,77 method: 'POST'78 });79 }80 async put(url, options) {81 return this.fetch(url, { ...options,82 method: 'PUT'83 });84 }85 async fetch(urlOrRequest, options = {}) {86 return this._wrapApiCall(async () => {87 const request = urlOrRequest instanceof network.Request ? urlOrRequest : undefined;88 (0, _utils.assert)(request || typeof urlOrRequest === 'string', 'First argument must be either URL string or Request');89 (0, _utils.assert)((options.data === undefined ? 0 : 1) + (options.form === undefined ? 0 : 1) + (options.multipart === undefined ? 0 : 1) <= 1, `Only one of 'data', 'form' or 'multipart' can be specified`);90 const url = request ? request.url() : urlOrRequest;91 const params = (0, _utils.objectToArray)(options.params);92 const method = options.method || (request === null || request === void 0 ? void 0 : request.method()); // Cannot call allHeaders() here as the request may be paused inside route handler.93 const headersObj = options.headers || (request === null || request === void 0 ? void 0 : request.headers());94 const headers = headersObj ? (0, _utils.headersObjectToArray)(headersObj) : undefined;95 let jsonData;96 let formData;97 let multipartData;98 let postDataBuffer;99 if (options.data !== undefined) {100 if ((0, _utils.isString)(options.data)) {101 if (isJsonContentType(headers)) jsonData = options.data;else postDataBuffer = Buffer.from(options.data, 'utf8');102 } else if (Buffer.isBuffer(options.data)) {103 postDataBuffer = options.data;104 } else if (typeof options.data === 'object' || typeof options.data === 'number' || typeof options.data === 'boolean') {105 jsonData = options.data;106 } else {107 throw new Error(`Unexpected 'data' type`);108 }109 } else if (options.form) {110 formData = (0, _utils.objectToArray)(options.form);111 } else if (options.multipart) {112 multipartData = []; // Convert file-like values to ServerFilePayload structs.113 for (const [name, value] of Object.entries(options.multipart)) {114 if ((0, _utils.isFilePayload)(value)) {115 const payload = value;116 if (!Buffer.isBuffer(payload.buffer)) throw new Error(`Unexpected buffer type of 'data.${name}'`);117 multipartData.push({118 name,119 file: filePayloadToJson(payload)120 });121 } else if (value instanceof _fs.default.ReadStream) {122 multipartData.push({123 name,124 file: await readStreamToJson(value)125 });126 } else {127 multipartData.push({128 name,129 value: String(value)130 });131 }132 }133 }134 if (postDataBuffer === undefined && jsonData === undefined && formData === undefined && multipartData === undefined) postDataBuffer = (request === null || request === void 0 ? void 0 : request.postDataBuffer()) || undefined;135 const postData = postDataBuffer ? postDataBuffer.toString('base64') : undefined;136 const result = await this._channel.fetch({137 url,138 params,139 method,140 headers,141 postData,142 jsonData,143 formData,144 multipartData,145 timeout: options.timeout,146 failOnStatusCode: options.failOnStatusCode,147 ignoreHTTPSErrors: options.ignoreHTTPSErrors148 });149 return new APIResponse(this, result.response);150 });151 }152 async storageState(options = {}) {153 const state = await this._channel.storageState();154 if (options.path) {155 await (0, _utils.mkdirIfNeeded)(options.path);156 await _fs.default.promises.writeFile(options.path, JSON.stringify(state, undefined, 2), 'utf8');157 }158 return state;159 }160}161exports.APIRequestContext = APIRequestContext;162_util$inspect$custom = util.inspect.custom;163class APIResponse {164 constructor(context, initializer) {165 this._initializer = void 0;166 this._headers = void 0;167 this._request = void 0;168 this._request = context;169 this._initializer = initializer;170 this._headers = new network.RawHeaders(this._initializer.headers);171 }172 ok() {173 return this._initializer.status >= 200 && this._initializer.status <= 299;174 }175 url() {176 return this._initializer.url;177 }178 status() {179 return this._initializer.status;180 }181 statusText() {182 return this._initializer.statusText;183 }184 headers() {185 return this._headers.headers();186 }187 headersArray() {188 return this._headers.headersArray();189 }190 async body() {191 try {192 const result = await this._request._channel.fetchResponseBody({193 fetchUid: this._fetchUid()194 });195 if (result.binary === undefined) throw new Error('Response has been disposed');196 return Buffer.from(result.binary, 'base64');197 } catch (e) {198 if (e.message.includes(_errors.kBrowserOrContextClosedError)) throw new Error('Response has been disposed');199 throw e;200 }201 }202 async text() {203 const content = await this.body();204 return content.toString('utf8');205 }206 async json() {207 const content = await this.text();208 return JSON.parse(content);209 }210 async dispose() {211 await this._request._channel.disposeAPIResponse({212 fetchUid: this._fetchUid()213 });214 }215 [_util$inspect$custom]() {216 const headers = this.headersArray().map(({217 name,218 value219 }) => ` ${name}: ${value}`);220 return `APIResponse: ${this.status()} ${this.statusText()}\n${headers.join('\n')}`;221 }222 _fetchUid() {223 return this._initializer.fetchUid;224 }225 async _fetchLog() {226 const {227 log228 } = await this._request._channel.fetchLog({229 fetchUid: this._fetchUid()230 });231 return log;232 }233}234exports.APIResponse = APIResponse;235function filePayloadToJson(payload) {236 return {237 name: payload.name,238 mimeType: payload.mimeType,239 buffer: payload.buffer.toString('base64')240 };241}242async function readStreamToJson(stream) {243 const buffer = await new Promise((resolve, reject) => {244 const chunks = [];245 stream.on('data', chunk => chunks.push(chunk));246 stream.on('end', () => resolve(Buffer.concat(chunks)));247 stream.on('error', err => reject(err));248 });249 const streamPath = Buffer.isBuffer(stream.path) ? stream.path.toString('utf8') : stream.path;250 return {251 name: _path.default.basename(streamPath),252 buffer: buffer.toString('base64')253 };254}255function isJsonContentType(headers) {256 if (!headers) return false;257 for (const {258 name,259 value260 } of headers) {261 if (name.toLocaleLowerCase() === 'content-type') return value === 'application/json';262 }263 return false;...
index.js
Source:index.js
...190 const lines = text.split('\n');191 const maxLength = Math.max(...lines.map(line => line.length));192 return ['â' + 'â'.repeat(maxLength + padding * 2) + 'â', ...lines.map(line => 'â' + ' '.repeat(padding) + line + ' '.repeat(maxLength - line.length + padding) + 'â'), 'â' + 'â'.repeat(maxLength + padding * 2) + 'â'].join('\n');193}194function isFilePayload(value) {195 return typeof value === 'object' && value['name'] && value['mimeType'] && value['buffer'];196}197function streamToString(stream) {198 return new Promise((resolve, reject) => {199 const chunks = [];200 stream.on('data', chunk => chunks.push(Buffer.from(chunk)));201 stream.on('error', reject);202 stream.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));203 });...
Using AI Code Generation
1const fs = require('fs');2const path = require('path');3const { webkit } = require('playwright-internal');4(async () => {5 const browser = await webkit.launch();6 const context = await browser.newContext();7 const page = await context.newPage();8 const filePayload = await page.evaluate(async () => {9 const file = await window.__playwright__internal__isFilePayload(new File(['foo'], 'foo.txt'));10 return file;11 });12 console.log(filePayload);13 await browser.close();14})();15{16}
Using AI Code Generation
1const path = require('path');2const { isFilePayload } = require(path.join(process.cwd(), 'node_modules', 'playwright', 'lib', 'server', 'utils', 'utils.js'));3const { chromium } = require('playwright');4const fs = require('fs');5(async () => {6 const browser = await chromium.launch();7 const context = await browser.newContext();8 const page = await context.newPage();9 const file = fs.readFileSync('file.txt');10 console.log(isFilePayload(file));11 await browser.close();12})();13const path = require('path');14const { isFilePayload } = require(path.join(process.cwd(), 'node_modules', 'playwright', 'lib', 'server', 'utils', 'utils.js'));15const { chromium } = require('playwright');16const fs = require('fs');17(async () => {18 const browser = await chromium.launch();19 const context = await browser.newContext();20 const page = await context.newPage();21 const file = fs.readFileSync('file.txt');22 console.log(isFilePayload(file));23 await browser.close();24})();25Your name to display (optional):26Your name to display (optional):27const path = require('path');28const { isBinaryFile } = require(path.join(process.cwd(), 'node_modules', 'playwright', 'lib', 'server', 'utils', 'utils.js'));29const { chromium } = require('playwright');30const fs = require('fs');31(async () => {32 const browser = await chromium.launch();33 const context = await browser.newContext();34 const page = await context.newPage();35 const file = fs.readFileSync('file.txt');36 console.log(isBinaryFile(file));37 await browser.close();38})();39Your name to display (optional):40const path = require('path');41const { isBinaryFile } =
Using AI Code Generation
1const { isFilePayload } = require('@playwright/test/lib/utils/utils');2const { test, expect } = require('@playwright/test');3test('isFilePayload test', async ({ page }) => {4 const filePayload = isFilePayload('test.js');5 expect(filePayload).toBeTruthy();6});7PASS test.js (1s)8 ✓ isFilePayload test (1s)9 1 test passed (1s)
Using AI Code Generation
1const { isFilePayload } = require("playwright/lib/utils/utils");2const filePayload = await page.evaluateHandle(() => document.querySelector("input[type=file]").files[0]);3const isFile = await isFilePayload(filePayload);4const { isFilePayload } = require("playwright");5const filePayload = await page.evaluateHandle(() => document.querySelector("input[type=file]").files[0]);6const isFile = await isFilePayload(filePayload);
Using AI Code Generation
1const { isFilePayload } = require('playwright/lib/utils/utils');2const fs = require('fs');3const file = fs.readFileSync('./test.png');4const filePayload = { name: 'test.png', mimeType: 'image/png', buffer: file };5console.log(isFilePayload(filePayload));6console.log(isFilePayload(file));7import { isFilePayload } from 'playwright/lib/utils/utils';8import fs from 'fs';9const file = fs.readFileSync('./test.png');10const filePayload = { name: 'test.png', mimeType: 'image/png', buffer: file };11console.log(isFilePayload(filePayload));12console.log(isFilePayload(file));13const { isFilePayload } = require('playwright/lib/utils/utils');14const fs = require('fs');15const file = fs.readFileSync('./test.png');16const filePayload = { name: 'test.png', mimeType: 'image/png', buffer: file };17console.log(isFilePayload(filePayload));18console.log(isFilePayload(file));19import { isFilePayload } from 'playwright/lib/utils/utils';20import fs from 'fs';21const file = fs.readFileSync('./test.png');22const filePayload = { name: 'test.png', mimeType: 'image/png', buffer: file };23console.log(isFilePayload(filePayload));24console.log(isFilePayload(file));25const { isFilePayload } = require('playwright/lib/utils/utils');26const fs = require('fs');27const file = fs.readFileSync('./test.png');28const filePayload = { name: 'test.png', mimeType: 'image/png', buffer: file };29console.log(isFilePayload(filePayload));30console.log(isFilePayload(file));31import { isFilePayload } from 'playwright/lib/utils/utils';32import fs from 'fs';33const file = fs.readFileSync('./test.png');34const filePayload = { name: 'test.png', mimeType: 'image/png', buffer: file };35console.log(isFilePayload(filePayload));36console.log(isFilePayload(file));37const { isFilePayload } = require('playwright/lib/utils/utils');38const fs = require('fs');39const file = fs.readFileSync('./test.png');40const filePayload = { name: 'test.png', mimeType: 'image/png', buffer: file };41console.log(isFilePayload(filePayload
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!!