Best JavaScript code snippet using playwright-internal
api_parser.js
Source:api_parser.js
...67 extendsName = member.text.substring('extends: ['.length, member.text.indexOf(']'));68 continue;69 }70 }71 const clazz = new Documentation.Class(extractLangs(node), name, [], extendsName, extractComments(node));72 this.classes.set(clazz.name, clazz);73 }74 /**75 * @param {MarkdownNode} spec76 */77 parseMember(spec) {78 const match = spec.text.match(/(event|method|property|async method): ([^.]+)\.(.*)/);79 if (!match)80 throw new Error('Invalid member: ' + spec.text);81 const name = match[3];82 let returnType = null;83 for (const item of spec.children || []) {84 if (item.type === 'li' && item.liType === 'default')85 returnType = this.parseType(item);86 }87 if (!returnType)88 returnType = new Documentation.Type('void');89 let member;90 if (match[1] === 'event')91 member = Documentation.Member.createEvent(extractLangs(spec), name, returnType, extractComments(spec));92 if (match[1] === 'property')93 member = Documentation.Member.createProperty(extractLangs(spec), name, returnType, extractComments(spec));94 if (match[1] === 'method' || match[1] === 'async method') {95 member = Documentation.Member.createMethod(extractLangs(spec), name, [], returnType, extractComments(spec));96 if (match[1] === 'async method')97 member.async = true;98 }99 const clazz = this.classes.get(match[2]);100 const existingMember = clazz.membersArray.find(m => m.name === name && m.kind === member.kind);101 if (existingMember && isTypeOverride(existingMember, member)) {102 for (const lang of member.langs.only) {103 existingMember.langs.types = existingMember.langs.types || {};104 existingMember.langs.types[lang] = returnType;105 }106 } else {107 clazz.membersArray.push(member);108 }109 }110 /**111 * @param {MarkdownNode} spec112 */113 parseArgument(spec) {114 const match = spec.text.match(/(param|option): (.*)/);115 if (!match)116 throw `Something went wrong with matching ${spec.text}`;117 // For "test.describe.only.title":118 // - className is "test"119 // - methodName is "describe.only"120 // - argument name is "title"121 const parts = match[2].split('.');122 const className = parts[0];123 const name = parts[parts.length - 1];124 const methodName = parts.slice(1, parts.length - 1).join('.');125 const clazz = this.classes.get(className);126 if (!clazz)127 throw new Error('Invalid class ' + className);128 const method = clazz.membersArray.find(m => m.kind === 'method' && m.name === methodName);129 if (!method)130 throw new Error(`Invalid method ${className}.${methodName} when parsing: ${match[0]}`);131 if (!name)132 throw new Error('Invalid member name ' + spec.text);133 if (match[1] === 'param') {134 const arg = this.parseProperty(spec);135 arg.name = name;136 const existingArg = method.argsArray.find(m => m.name === arg.name);137 if (existingArg && isTypeOverride(existingArg, arg)) {138 if (!arg.langs || !arg.langs.only)139 throw new Error('Override does not have lang: ' + spec.text);140 for (const lang of arg.langs.only) {141 existingArg.langs.overrides = existingArg.langs.overrides || {};142 existingArg.langs.overrides[lang] = arg;143 }144 } else {145 method.argsArray.push(arg);146 }147 } else {148 let options = method.argsArray.find(o => o.name === 'options');149 if (!options) {150 const type = new Documentation.Type('Object', []);151 options = Documentation.Member.createProperty({}, 'options', type, undefined, false);152 method.argsArray.push(options);153 }154 const p = this.parseProperty(spec);155 p.required = false;156 options.type.properties.push(p);157 }158 }159 /**160 * @param {MarkdownNode} spec161 */162 parseProperty(spec) {163 const param = childrenWithoutProperties(spec)[0];164 const text = param.text;165 const name = text.substring(0, text.indexOf('<')).replace(/\`/g, '').trim();166 const comments = extractComments(spec);167 return Documentation.Member.createProperty(extractLangs(spec), name, this.parseType(param), comments, guessRequired(md.render(comments)));168 }169 /**170 * @param {MarkdownNode=} spec171 * @return {Documentation.Type}172 */173 parseType(spec) {174 const arg = parseVariable(spec.text);175 const properties = [];176 for (const child of spec.children || []) {177 const { name, text } = parseVariable(child.text);178 const comments = /** @type {MarkdownNode[]} */ ([{ type: 'text', text }]);179 properties.push(Documentation.Member.createProperty({}, name, this.parseType(child), comments, guessRequired(text)));180 }181 return Documentation.Type.parse(arg.type, properties);182 }183}184/**185 * @param {string} line186 * @returns {{ name: string, type: string, text: string }}187 */188function parseVariable(line) {189 let match = line.match(/^`([^`]+)` (.*)/);190 if (!match)191 match = line.match(/^(returns): (.*)/);192 if (!match)193 match = line.match(/^(type): (.*)/);194 if (!match)195 match = line.match(/^(argument): (.*)/);196 if (!match)197 throw new Error('Invalid argument: ' + line);198 const name = match[1];199 const remainder = match[2];200 if (!remainder.startsWith('<'))201 throw new Error(`Bad argument: "${name}" in "${line}"`);202 let depth = 0;203 for (let i = 0; i < remainder.length; ++i) {204 const c = remainder.charAt(i);205 if (c === '<')206 ++depth;207 if (c === '>')208 --depth;209 if (depth === 0)210 return { name, type: remainder.substring(1, i), text: remainder.substring(i + 2) };211 }212 throw new Error('Should not be reached');213}214/**215 * @param {MarkdownNode[]} body216 * @param {MarkdownNode[]} params217 */218function applyTemplates(body, params) {219 const paramsMap = new Map();220 for (const node of params)221 paramsMap.set('%%-' + node.text + '-%%', node);222 const visit = (node, parent) => {223 if (node.text && node.text.includes('-inline- = %%')) {224 const [name, key] = node.text.split('-inline- = ');225 const list = paramsMap.get(key);226 const newChildren = [];227 if (!list)228 throw new Error('Bad template: ' + key);229 for (const prop of list.children) {230 const template = paramsMap.get(prop.text);231 if (!template)232 throw new Error('Bad template: ' + prop.text);233 const children = childrenWithoutProperties(template);234 const { name: argName } = parseVariable(children[0].text);235 newChildren.push({236 type: node.type,237 text: name + argName,238 children: template.children.map(c => md.clone(c))239 });240 }241 const nodeIndex = parent.children.indexOf(node);242 parent.children = [...parent.children.slice(0, nodeIndex), ...newChildren, ...parent.children.slice(nodeIndex + 1)];243 } else if (node.text && node.text.includes(' = %%')) {244 const [name, key] = node.text.split(' = ');245 node.text = name;246 const template = paramsMap.get(key);247 if (!template)248 throw new Error('Bad template: ' + key);249 node.children.push(...template.children.map(c => md.clone(c)));250 }251 for (const child of node.children || [])252 visit(child, node);253 if (node.children)254 node.children = node.children.filter(child => !child.text || !child.text.includes('-inline- = %%'));255 };256 for (const node of body)257 visit(node, null);258 return body;259}260/**261 * @param {MarkdownNode} item262 * @returns {MarkdownNode[]}263 */264function extractComments(item) {265 return (item.children || []).filter(c => {266 if (c.type.startsWith('h'))267 return false;268 if (c.type === 'li' && c.liType === 'default')269 return false;270 if (c.type === 'li' && c.text.startsWith('langs:'))271 return false;272 return true;273 });274}275/**276 * @param {string} comment277 */278function guessRequired(comment) {279 let required = true;280 if (comment.toLowerCase().includes('defaults to '))281 required = false;282 if (comment.startsWith('Optional'))283 required = false;284 if (comment.endsWith('Optional.'))285 required = false;286 if (comment.toLowerCase().includes('if set'))287 required = false;288 if (comment.toLowerCase().includes('if applicable'))289 required = false;290 if (comment.toLowerCase().includes('if available'))291 required = false;292 return required;293}294/**295 * @param {string} apiDir296 * @param {string=} paramsPath297 */298function parseApi(apiDir, paramsPath) {299 return new ApiParser(apiDir, paramsPath).documentation;300}301/**302 * @param {MarkdownNode} spec303 * @returns {import('./documentation').Langs}304 */305function extractLangs(spec) {306 for (const child of spec.children) {307 if (child.type !== 'li' || child.liType !== 'bullet' || !child.text.startsWith('langs:'))308 continue;309 const only = child.text.substring('langs:'.length).trim();310 /** @type {Object<string, string>} */311 const aliases = {};312 for (const p of child.children || []) {313 const match = p.text.match(/alias-(\w+)[\s]*:(.*)/);314 if (match)315 aliases[match[1].trim()] = match[2].trim();316 }317 return {318 only: only ? only.split(',').map(l => l.trim()) : undefined,319 aliases,...
i18n.js
Source:i18n.js
...14 var locales2paths = {};15 // Puts the paths of all locale files contained in a given directory16 // into `locales2paths` (files from various dirs are grouped by lang code)17 // (only json files with valid language code as name)18 function extractLangs(dir) {19 if(!existsSync(dir)) return;20 var stat = fs.lstatSync(dir);21 if (!stat.isDirectory() || stat.isSymbolicLink()) return;22 fs.readdirSync(dir).forEach(function(file) {23 file = path.resolve(dir, file);24 stat = fs.lstatSync(file);25 if (stat.isDirectory() || stat.isSymbolicLink()) return;26 var ext = path.extname(file)27 , locale = path.basename(file, ext).toLowerCase();28 if ((ext == '.json') && languages.isValid(locale)) {29 if(!locales2paths[locale]) locales2paths[locale] = [];30 locales2paths[locale].push(file);31 }32 });33 }34 //add core supported languages first35 extractLangs(npm.root+"/ep_etherpad-lite/locales");36 37 //add plugins languages (if any)38 for(var pluginName in plugins) extractLangs(path.join(npm.root, pluginName, 'locales'));39 // Build a locale index (merge all locale data)40 var locales = {}41 _.each (locales2paths, function(files, langcode) {42 locales[langcode]={};43 files.forEach(function(file) {44 var fileContents = JSON.parse(fs.readFileSync(file,'utf8'));45 _.extend(locales[langcode], fileContents);46 });47 });48 return locales;49}50// returns a hash of all available languages availables with nativeName and direction51// e.g. { es: {nativeName: "español", direction: "ltr"}, ... }52function getAvailableLangs(locales) {...
Using AI Code Generation
1const { extractLangs } = require('playwright-core/lib/server/i18n');2console.log(extractLangs('en,fr,de'));3console.log(extractLangs('en,fr,de', 'en'));4const { extractLangs } = require('playwright-core/lib/server/i18n');5console.log(extractLangs('en,fr,de'));6console.log(extractLangs('en,fr,de', 'en'));7const { extractLangs } = require('playwright-core/lib/server/i18n');8console.log(extractLangs('en,fr,de'));9console.log(extractLangs('en,fr,de', 'en'));10const { extractLangs } = require('playwright-core/lib/server/i18n');11console.log(extractLangs('en,fr,de'));12console.log(extractLangs('en,fr,de', 'en'));13const { extractLangs } = require('playwright-core/lib/server/i18n');14console.log(extractLangs('en,fr,de'));15console.log(extractLangs('en,fr,de', 'en'));16const { extractLangs } = require('playwright-core/lib/server/i18n');17console.log(extractLangs('en,fr,de'));18console.log(extractLangs('en,fr,de', 'en'));
Using AI Code Generation
1const { extractLangs } = require('playwright/lib/server/common/supplements.js');2const langs = extractLangs('en-US');3console.log(langs);4const { extractLangs } = require('playwright/lib/server/common/supplements.js');5const langs = extractLangs('en-US');6const context = await browser.newContext({ acceptLanguages: langs });7const page = await context.newPage();
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!!