Best JavaScript code snippet using playwright-internal
proxy-integration-event.js
Source:proxy-integration-event.js
1"use strict";2var __importDefault = (this && this.__importDefault) || function (mod) {3 return (mod && mod.__esModule) ? mod : { "default": mod };4};5Object.defineProperty(exports, "__esModule", { value: true });6exports.Authorizer = exports.Identity = exports.RequestContext = exports.ProxyIntegrationEvent = void 0;7const logger_1 = __importDefault(require("../logger"));8const fakeBaseUrl = "http://localhost";9class ProxyIntegrationEvent {10 constructor(req, stage, resourcePath) {11 const queries = this.parseQuery(req.url);12 this.body = this.parseBody(req.body) || null;13 this.headers = req.headers;14 this.multiValueHeaders = this.parseMultiValueHeaders(req.rawHeaders);15 this.httpMethod = req.method;16 this.isBase64Encoded = false;17 this.path = req.path;18 this.resource = req.path;19 this.pathParameters = this.parsePathParams(req.params);20 this.queryStringParameters = queries ? queries.query : null;21 this.multiValueQueryStringParameters = queries ? queries.multiValueQuery : null;22 this.requestContext = new RequestContext({ stage, httpMethod: req.method, path: this.path, resourcePath, httpVersion: req.httpVersion });23 }24 parseBody(body) {25 try {26 return JSON.stringify(body);27 }28 catch (error) {29 logger_1.default.log("received malformed json body, passing as is", error);30 return body;31 }32 }33 parsePathParams(reqParams) {34 if (!reqParams)35 return null;36 let params = {};37 for (let [key, value] of Object.entries(reqParams)) {38 if (key == "0")39 params["proxy"] = value.substring(1);40 //removes first slash41 else42 params[key] = value;43 }44 return params;45 }46 parseMultiValueHeaders(headers) {47 if (!headers || !headers.length)48 return;49 const multiValueHeaders = {};50 for (let i = 0; i < headers.length; i += 2) {51 const key = headers[i].toLocaleLowerCase();52 const value = headers[i + 1];53 if (multiValueHeaders[key])54 multiValueHeaders[key].push(value);55 else56 multiValueHeaders[key] = [value];57 }58 return multiValueHeaders;59 }60 parseQuery(pathWithQuery) {61 const url = new URL(pathWithQuery, fakeBaseUrl);62 const { searchParams } = url;63 if (Array.from(searchParams).length === 0) {64 return;65 }66 let query = {};67 let multiValueQuery = {};68 for (let [key, value] of searchParams) {69 query[key] = value;70 if (multiValueQuery[key])71 multiValueQuery[key].push(value);72 else73 multiValueQuery[key] = [value];74 }75 return { query, multiValueQuery };76 }77}78exports.ProxyIntegrationEvent = ProxyIntegrationEvent;79class RequestContext {80 constructor(params) {81 this.accountId = "sls-local-accountId";82 this.resourceId = "sls-local-resourceId";83 this.domainName = "sls-local-domainName";84 this.domainPrefix = "sls-local-domainPrefix";85 this.stage = params.stage;86 this.requestId = "sls-local-requestid";87 this.requestTime = new Date().toString();88 this.requestTimeEpoch = new Date().getTime();89 this.extendedRequestId = "sls-local-extendedRequestId";90 this.path = params.path;91 this.resourcePath = `/${params.stage}${params.resourcePath}`;92 this.protocol = `HTTP/${params.httpVersion}`;93 this.httpMethod = params.httpMethod;94 this.apiId = "sls-local-apiId";95 this.identity = new Identity();96 this.authorizer = new Authorizer();97 }98}99exports.RequestContext = RequestContext;100class Identity {101 constructor() {102 this.accessKey = null;103 this.cognitoIdentityPoolId = "sls-local-cognitoIdentityPoolId";104 this.accountId = "sls-local-accountId";105 this.cognitoIdentityId = "sls-local-cognitoIdentityId";106 this.principalOrgId = null;107 this.caller = "sls-local-caller";108 this.apiKey = "sls-local-apikey";109 this.sourceIp = "127.0.0.1";110 this.cognitoAuthenticationType = "sls-local-cognitoAuthenticationtype";111 this.cognitoAuthenticationProvider = "sls-local-cognitoAuthenticationProvider";112 this.userArn = "sls-local-userArn";113 this.userAgent = "sls-local-userAgent";114 this.user = "sls-local-user";115 }116}117exports.Identity = Identity;118class Authorizer {119 constructor() {120 this.principalId = "sls-local-principalId";121 }122}...
LambdaEvent.js
Source:LambdaEvent.js
1import cuid from 'cuid';2import {3 parseMultiValueHeaders, parseMultiValueQueryStringParameters,4 parseQueryStringParameters, formatToClfTime, nullIfEmpty5} from '../Utils';6import Globals from '../Globals';7//8const unflatten = require('unflatten');9//10export default class LambdaEvent {11 constructor(request, functionPath, functionHandler) {12 this.request = request;13 this.functionPath = functionPath;14 this.functionHandler = functionHandler;15 }16 async invoke() {17 return new Promise( async (resolve, reject) => {18 try {19 //Build event and context20 const event = this._buildEvent();21 const context = this._buildContext(event, (err, data) => {22 resolve({err, data});23 });24 //Invoke25 const resp = await (require(`${this.functionPath}`)[this.functionHandler](event, context));26 if (resp) resolve({data: resp});27 } catch (e) { reject(e); } //forward28 });29 }30 /* private */31 _buildEvent() {32 return {33 body: this.request.payload || null, //enforce key34 headers: this.request.raw ? unflatten(this.request.raw.req.headers, 2) : [],35 httpMethod: this.request.method ? this.request.method.toUpperCase() : null,36 isBase64Encoded: false, // TODO37 multiValueHeaders: parseMultiValueHeaders(38 this.request.raw ? this.request.raw.req.headers || [] : [],39 ),40 multiValueQueryStringParameters: parseMultiValueQueryStringParameters(41 this.request.raw ? this.request.raw.req.url : [],42 ),43 path: this.request.path,44 pathParameters: this.request.params ? nullIfEmpty(this.request.params) : null,45 queryStringParameters: this.request.raw ? parseQueryStringParameters(this.request.raw.req.url) : null,46 requestContext: {47 accountId: (process.env.AWS_ACCOUNT_ID || null),48 apiId: 'TODO',49 authorizer: null,50 domainName: 'TODO',51 domainPrefix: 'TODO',52 extendedRequestId: cuid(),53 httpMethod: this.request.method ? this.request.method.toUpperCase() : null,54 identity: {55 accessKey: null,56 accountId: (process.env.AWS_ACCOUNT_ID || null),57 caller: null,58 cognitoAuthenticationProvider: null,59 cognitoAuthenticationType: null,60 cognitoIdentityId: null,61 cognitoIdentityPoolId: null,62 principalOrgId: null,63 sourceIp: this.request.headers ? this.request.headers['x-forwarded-for'] || this.request.info.remoteAddress : null,64 user: null,65 userAgent: this.request.headers ? this.request.headers['user-agent'] : null,66 userArn: null,67 },68 path: this.request.path,69 protocol: 'HTTP/1.1',70 requestId: `${cuid()}-${cuid()}`,71 requestTime: this.request.info ? formatToClfTime(this.request.info.received) : null,72 requestTimeEpoch: this.request.info ? this.request.info.received : null,73 resourceId: 'TODO?',74 resourcePath: Globals.Listener_HTTP_ProxyRoute,75 stage: process.env.STAGE,76 },77 resource: Globals.Listener_HTTP_ProxyRoute,78 stageVariables: null,79 };80 }81 _buildContext(event, callback) {82 return {83 awsRequestId: event.requestContext.requestId,84 callbackWaitsForEmptyEventLoop: true,85 getRemainingTimeInMillis: () => { return 0; }, //TODO86 done: (err, data) => callback(err, data),87 fail: (err) => callback(err),88 succeed: (res) => callback(null, res),89 };90 }...
WebSocketConnectEvent.js
Source:WebSocketConnectEvent.js
1import WebSocketRequestContext from './WebSocketRequestContext.js'2import {3 parseHeaders,4 parseMultiValueHeaders,5 parseMultiValueQueryStringParameters,6 parseQueryStringParameters,7} from '../../../utils/index.js'8export default class WebSocketConnectEvent {9 #connectionId = null10 #httpsProtocol = null11 #rawHeaders = null12 #url = null13 #websocketPort = null14 constructor(connectionId, request, options) {15 const { httpsProtocol, websocketPort } = options16 const { rawHeaders, url } = request17 this.#connectionId = connectionId18 this.#httpsProtocol = httpsProtocol19 this.#rawHeaders = rawHeaders20 this.#url = url21 this.#websocketPort = websocketPort22 }23 create() {24 // const headers = {25 // Host: 'localhost',26 // 'Sec-WebSocket-Extensions': 'permessage-deflate; client_max_window_bits',27 // 'Sec-WebSocket-Key': createUniqueId(),28 // 'Sec-WebSocket-Version': '13',29 // 'X-Amzn-Trace-Id': `Root=${createUniqueId()}`,30 // 'X-Forwarded-For': '127.0.0.1',31 // 'X-Forwarded-Port': String(this.#websocketPort),32 // 'X-Forwarded-Proto': `http${this.#httpsProtocol ? 's' : ''}`,33 // }34 const headers = parseHeaders(this.#rawHeaders)35 const multiValueHeaders = parseMultiValueHeaders(this.#rawHeaders)36 const multiValueQueryStringParameters = parseMultiValueQueryStringParameters(37 this.#url,38 )39 const queryStringParameters = parseQueryStringParameters(this.#url)40 const requestContext = new WebSocketRequestContext(41 'CONNECT',42 '$connect',43 this.#connectionId,44 ).create()45 return {46 headers,47 isBase64Encoded: false,48 multiValueHeaders,49 // NOTE: multiValueQueryStringParameters and queryStringParameters50 // properties are only defined if they have values51 ...(multiValueQueryStringParameters && {52 multiValueQueryStringParameters,53 }),54 ...(queryStringParameters && { queryStringParameters }),55 requestContext,56 }57 }...
WebSocketAuthorizerEvent.js
Source:WebSocketAuthorizerEvent.js
1import WebSocketRequestContext from './WebSocketRequestContext.js'2import {3 parseHeaders,4 parseMultiValueHeaders,5 parseMultiValueQueryStringParameters,6 parseQueryStringParameters,7} from '../../../utils/index.js'8export default class WebSocketAuthorizerEvent {9 #connectionId = null10 #httpsProtocol = null11 #rawHeaders = null12 #url = null13 #websocketPort = null14 #provider = null15 constructor(connectionId, request, provider, options) {16 const { httpsProtocol, websocketPort } = options17 const { rawHeaders, url } = request18 this.#connectionId = connectionId19 this.#httpsProtocol = httpsProtocol20 this.#rawHeaders = rawHeaders21 this.#url = url22 this.#websocketPort = websocketPort23 this.#provider = provider24 }25 create() {26 const headers = parseHeaders(this.#rawHeaders)27 const multiValueHeaders = parseMultiValueHeaders(this.#rawHeaders)28 const multiValueQueryStringParameters =29 parseMultiValueQueryStringParameters(this.#url)30 const queryStringParameters = parseQueryStringParameters(this.#url)31 const requestContext = new WebSocketRequestContext(32 'CONNECT',33 '$connect',34 this.#connectionId,35 ).create()36 return {37 type: 'REQUEST',38 methodArn: `arn:aws:execute-api:${this.#provider.region}:${39 requestContext.accountId40 }:${requestContext.apiId}/${requestContext.stage}/${41 requestContext.routeKey42 }`,43 headers,44 multiValueHeaders,45 // NOTE: multiValueQueryStringParameters and queryStringParameters46 // properties are only defined if they have values47 ...(multiValueQueryStringParameters && {48 multiValueQueryStringParameters,49 }),50 ...(queryStringParameters && { queryStringParameters }),51 requestContext,52 }53 }...
index.js
Source:index.js
1const { isArray } = Array2const { keys } = Object3export { default as createApiKey } from './createApiKey.js'4export { default as createUniqueId } from './createUniqueId.js'5export { default as detectExecutable } from './detectExecutable.js'6export { default as formatToClfTime } from './formatToClfTime.js'7export { default as jsonPath } from './jsonPath.js'8export { default as parseHeaders } from './parseHeaders.js'9export { default as parseMultiValueHeaders } from './parseMultiValueHeaders.js'10export { default as parseMultiValueQueryStringParameters } from './parseMultiValueQueryStringParameters.js'11export { default as parseQueryStringParameters } from './parseQueryStringParameters.js'12export { default as satisfiesVersionRange } from './satisfiesVersionRange.js'13export { default as splitHandlerPathAndName } from './splitHandlerPathAndName.js'14export { default as checkDockerDaemon } from './checkDockerDaemon.js'15// export { default as baseImage } from './baseImage.js'16// Detect the toString encoding from the request headers content-type17// enhance if further content types need to be non utf8 encoded.18export function detectEncoding(request) {19 const contentType = request.headers['content-type']20 return typeof contentType === 'string' &&21 contentType.includes('multipart/form-data')22 ? 'binary'23 : 'utf8'24}25export function nullIfEmpty(obj) {26 return obj && (keys(obj).length > 0 ? obj : null)27}28export function isPlainObject(obj) {29 return typeof obj === 'object' && !isArray(obj) && obj != null30}31export function toPlainOrEmptyObject(obj) {32 return typeof obj === 'object' && !isArray(obj) ? obj : {}...
WebSocketDisconnectEvent.js
Source:WebSocketDisconnectEvent.js
1import WebSocketRequestContext from './WebSocketRequestContext.js'2import { parseHeaders, parseMultiValueHeaders } from '../../../utils/index.js'3export default class WebSocketDisconnectEvent {4 #connectionId = null5 constructor(connectionId) {6 this.#connectionId = connectionId7 }8 create() {9 // TODO FIXME not sure where the headers come from10 const rawHeaders = ['Host', 'localhost', 'x-api-key', '', 'x-restapi', '']11 const headers = parseHeaders(rawHeaders)12 const multiValueHeaders = parseMultiValueHeaders(rawHeaders)13 const requestContext = new WebSocketRequestContext(14 'DISCONNECT',15 '$disconnect',16 this.#connectionId,17 ).create()18 return {19 headers,20 isBase64Encoded: false,21 multiValueHeaders,22 requestContext,23 }24 }...
parseMultiValueHeaders.test.js
Source:parseMultiValueHeaders.test.js
1import parseMultiValueHeaders from '../parseMultiValueHeaders.js'2// TODO need more tests3const tests = [4 {5 description: 'no parameter (empty array)',6 expected: null,7 expectedMulti: null,8 param: [],9 },10]11describe('parseMultiValueHeaders', () => {12 tests.forEach(({ description, expectedMulti, param }) => {13 test(`should return ${description}`, () => {14 const resultMulti = parseMultiValueHeaders(param)15 expect(resultMulti).toEqual(expectedMulti)16 })17 })18})19// export tests for parseHeaders...
parseHeaders.test.js
Source:parseHeaders.test.js
1// uses the same tests as parseMultiValueHeaders2import tests from './parseMultiValueHeaders.test.js'3import parseHeaders from '../parseHeaders.js'4describe('parseQueryStringParameters', () => {5 tests.forEach(({ description, expected, param }) => {6 test(`should return ${description}`, () => {7 const result = parseHeaders(param)8 expect(result).toEqual(expected)9 })10 })...
Using AI Code Generation
1const { parseMultivalueHeaders } = require('playwright-core/lib/utils/utils');2const headers = {3 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36',4 'accept-language': 'en-US,en;q=0.9',5};6const parsedHeaders = parseMultivalueHeaders(headers);7console.log(parsedHeaders);8const { parseHeaders } = require('playwright-core/lib/utils/utils');9const headers = {10 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36',11 'accept-language': 'en-US,en;q=0.9',12};13const parsedHeaders = parseHeaders(headers);14console.log(parsedHeaders);
Using AI Code Generation
1const { parseMultivalueHeaders } = require('playwright-core/lib/utils/utils');2const headers = {3};4const result = parseMultivalueHeaders(headers);5console.log(result);6const context = await browser.newContext();7const cookies = await context.cookies();8console.log(cookies);9const context = await browser.newContext();10const cookies = await context.cookies();11console.log(cookies);12const cookies = await t.getBrowserConsoleMessages();13console.log(cookies);14const context = await browser.newContext();15const cookies = await context.cookies();16console.log(cookies);17const cookies = await t.getBrowserConsoleMessages();18console.log(cookies);
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!!