How to use OpenParenToken method in Playwright Internal

Best JavaScript code snippet using playwright-internal

cssTokenizer.js

Source:cssTokenizer.js Github

copy

Full Screen

...163 return new DelimToken(code);164 }165 }166 else if(code == 0x27) return consumeAStringToken();167 else if(code == 0x28) return new OpenParenToken();168 else if(code == 0x29) return new CloseParenToken();169 else if(code == 0x2a) {170 if(next() == 0x3d) {171 consume();172 return new SubstringMatchToken();173 } else {174 return new DelimToken(code);175 }176 }177 else if(code == 0x2b) {178 if(startsWithANumber()) {179 reconsume();180 return consumeANumericToken();181 } else {182 return new DelimToken(code);183 }184 }185 else if(code == 0x2c) return new CommaToken();186 else if(code == 0x2d) {187 if(startsWithANumber()) {188 reconsume();189 return consumeANumericToken();190 } else if(next(1) == 0x2d && next(2) == 0x3e) {191 consume(2);192 return new CDCToken();193 } else if(startsWithAnIdentifier()) {194 reconsume();195 return consumeAnIdentlikeToken();196 } else {197 return new DelimToken(code);198 }199 }200 else if(code == 0x2e) {201 if(startsWithANumber()) {202 reconsume();203 return consumeANumericToken();204 } else {205 return new DelimToken(code);206 }207 }208 else if(code == 0x3a) return new ColonToken;209 else if(code == 0x3b) return new SemicolonToken;210 else if(code == 0x3c) {211 if(next(1) == 0x21 && next(2) == 0x2d && next(3) == 0x2d) {212 consume(3);213 return new CDOToken();214 } else {215 return new DelimToken(code);216 }217 }218 else if(code == 0x40) {219 if(wouldStartAnIdentifier(next(1), next(2), next(3))) {220 return new AtKeywordToken(consumeAName());221 } else {222 return new DelimToken(code);223 }224 }225 else if(code == 0x5b) return new OpenSquareToken();226 else if(code == 0x5c) {227 if(startsWithAValidEscape()) {228 reconsume();229 return consumeAnIdentlikeToken();230 } else {231 parseerror();232 return new DelimToken(code);233 }234 }235 else if(code == 0x5d) return new CloseSquareToken();236 else if(code == 0x5e) {237 if(next() == 0x3d) {238 consume();239 return new PrefixMatchToken();240 } else {241 return new DelimToken(code);242 }243 }244 else if(code == 0x7b) return new OpenCurlyToken();245 else if(code == 0x7c) {246 if(next() == 0x3d) {247 consume();248 return new DashMatchToken();249 } else if(next() == 0x7c) {250 consume();251 return new ColumnToken();252 } else {253 return new DelimToken(code);254 }255 }256 else if(code == 0x7d) return new CloseCurlyToken();257 else if(code == 0x7e) {258 if(next() == 0x3d) {259 consume();260 return new IncludeMatchToken();261 } else {262 return new DelimToken(code);263 }264 }265 else if(digit(code)) {266 reconsume();267 return consumeANumericToken();268 }269 else if(namestartchar(code)) {270 reconsume();271 return consumeAnIdentlikeToken();272 }273 else if(eof()) return new EOFToken();274 else return new DelimToken(code);275 };276 var consumeComments = function() {277 while(next(1) == 0x2f && next(2) == 0x2a) {278 consume(2);279 while(true) {280 consume();281 if(code == 0x2a && next() == 0x2f) {282 consume();283 break;284 } else if(eof()) {285 parseerror();286 return;287 }288 }289 }290 };291 var consumeANumericToken = function() {292 var num = consumeANumber();293 if(wouldStartAnIdentifier(next(1), next(2), next(3))) {294 var token = new DimensionToken();295 token.value = num.value;296 token.repr = num.repr;297 token.type = num.type;298 token.unit = consumeAName();299 return token;300 } else if(next() == 0x25) {301 consume();302 var token = new PercentageToken();303 token.value = num.value;304 token.repr = num.repr;305 return token;306 } else {307 var token = new NumberToken();308 token.value = num.value;309 token.repr = num.repr;310 token.type = num.type;311 return token;312 }313 };314 var consumeAnIdentlikeToken = function() {315 var str = consumeAName();316 if(str.toLowerCase() == "url" && next() == 0x28) {317 consume();318 while(whitespace(next(1)) && whitespace(next(2))) consume();319 if(next() == 0x22 || next() == 0x27) {320 return new FunctionToken(str);321 } else if(whitespace(next()) && (next(2) == 0x22 || next(2) == 0x27)) {322 return new FunctionToken(str);323 } else {324 return consumeAURLToken();325 }326 } else if(next() == 0x28) {327 consume();328 return new FunctionToken(str);329 } else {330 return new IdentToken(str);331 }332 };333 var consumeAStringToken = function(endingCodePoint) {334 if(endingCodePoint === undefined) endingCodePoint = code;335 var string = "";336 while(consume()) {337 if(code == endingCodePoint || eof()) {338 return new StringToken(string);339 } else if(newline(code)) {340 parseerror();341 reconsume();342 return new BadStringToken();343 } else if(code == 0x5c) {344 if(eof(next())) {345 donothing();346 } else if(newline(next())) {347 consume();348 } else {349 string += stringFromCode(consumeEscape())350 }351 } else {352 string += stringFromCode(code);353 }354 }355 };356 var consumeAURLToken = function() {357 var token = new URLToken("");358 while(whitespace(next())) consume();359 if(eof(next())) return token;360 while(consume()) {361 if(code == 0x29 || eof()) {362 return token;363 } else if(whitespace(code)) {364 while(whitespace(next())) consume();365 if(next() == 0x29 || eof(next())) {366 consume();367 return token;368 } else {369 consumeTheRemnantsOfABadURL();370 return new BadURLToken();371 }372 } else if(code == 0x22 || code == 0x27 || code == 0x28 || nonprintable(code)) {373 parseerror();374 consumeTheRemnantsOfABadURL();375 return new BadURLToken();376 } else if(code == 0x5c) {377 if(startsWithAValidEscape()) {378 token.value += stringFromCode(consumeEscape());379 } else {380 parseerror();381 consumeTheRemnantsOfABadURL();382 return new BadURLToken();383 }384 } else {385 token.value += stringFromCode(code);386 }387 }388 };389 var consumeEscape = function() {390 // Assume the the current character is the \391 // and the next code point is not a newline.392 consume();393 if(hexdigit(code)) {394 // Consume 1-6 hex digits395 var digits = [code];396 for(var total = 0; total < 5; total++) {397 if(hexdigit(next())) {398 consume();399 digits.push(code);400 } else {401 break;402 }403 }404 if(whitespace(next())) consume();405 var value = parseInt(digits.map(function(x){return String.fromCharCode(x);}).join(''), 16);406 if( value > maximumallowedcodepoint ) value = 0xfffd;407 return value;408 } else if(eof()) {409 return 0xfffd;410 } else {411 return code;412 }413 };414 var areAValidEscape = function(c1, c2) {415 if(c1 != 0x5c) return false;416 if(newline(c2)) return false;417 return true;418 };419 var startsWithAValidEscape = function() {420 return areAValidEscape(code, next());421 };422 var wouldStartAnIdentifier = function(c1, c2, c3) {423 if(c1 == 0x2d) {424 return namestartchar(c2) || c2 == 0x2d || areAValidEscape(c2, c3);425 } else if(namestartchar(c1)) {426 return true;427 } else if(c1 == 0x5c) {428 return areAValidEscape(c1, c2);429 } else {430 return false;431 }432 };433 var startsWithAnIdentifier = function() {434 return wouldStartAnIdentifier(code, next(1), next(2));435 };436 var wouldStartANumber = function(c1, c2, c3) {437 if(c1 == 0x2b || c1 == 0x2d) {438 if(digit(c2)) return true;439 if(c2 == 0x2e && digit(c3)) return true;440 return false;441 } else if(c1 == 0x2e) {442 if(digit(c2)) return true;443 return false;444 } else if(digit(c1)) {445 return true;446 } else {447 return false;448 }449 };450 var startsWithANumber = function() {451 return wouldStartANumber(code, next(1), next(2));452 };453 var consumeAName = function() {454 var result = "";455 while(consume()) {456 if(namechar(code)) {457 result += stringFromCode(code);458 } else if(startsWithAValidEscape()) {459 result += stringFromCode(consumeEscape());460 } else {461 reconsume();462 return result;463 }464 }465 };466 var consumeANumber = function() {467 var repr = [];468 var type = "integer";469 if(next() == 0x2b || next() == 0x2d) {470 consume();471 repr += stringFromCode(code);472 }473 while(digit(next())) {474 consume();475 repr += stringFromCode(code);476 }477 if(next(1) == 0x2e && digit(next(2))) {478 consume();479 repr += stringFromCode(code);480 consume();481 repr += stringFromCode(code);482 type = "number";483 while(digit(next())) {484 consume();485 repr += stringFromCode(code);486 }487 }488 var c1 = next(1), c2 = next(2), c3 = next(3);489 if((c1 == 0x45 || c1 == 0x65) && digit(c2)) {490 consume();491 repr += stringFromCode(code);492 consume();493 repr += stringFromCode(code);494 type = "number";495 while(digit(next())) {496 consume();497 repr += stringFromCode(code);498 }499 } else if((c1 == 0x45 || c1 == 0x65) && (c2 == 0x2b || c2 == 0x2d) && digit(c3)) {500 consume();501 repr += stringFromCode(code);502 consume();503 repr += stringFromCode(code);504 consume();505 repr += stringFromCode(code);506 type = "number";507 while(digit(next())) {508 consume();509 repr += stringFromCode(code);510 }511 }512 var value = convertAStringToANumber(repr);513 return {type:type, value:value, repr:repr};514 };515 var convertAStringToANumber = function(string) {516 // CSS's number rules are identical to JS, afaik.517 return +string;518 };519 var consumeTheRemnantsOfABadURL = function() {520 while(consume()) {521 if(code == 0x29 || eof()) {522 return;523 } else if(startsWithAValidEscape()) {524 consumeEscape();525 donothing();526 } else {527 donothing();528 }529 }530 };531 var iterationCount = 0;532 while(!eof(next())) {533 tokens.push(consumeAToken());534 iterationCount++;535 if(iterationCount > str.length*2) return "I'm infinite-looping!";536 }537 return tokens;538}539function CSSParserToken() { throw "Abstract Base Class"; }540CSSParserToken.prototype.toJSON = function() {541 return {token: this.tokenType};542}543CSSParserToken.prototype.toString = function() { return this.tokenType; }544CSSParserToken.prototype.toSource = function() { return ''+this; }545function BadStringToken() { return this; }546BadStringToken.prototype = Object.create(CSSParserToken.prototype);547BadStringToken.prototype.tokenType = "BADSTRING";548function BadURLToken() { return this; }549BadURLToken.prototype = Object.create(CSSParserToken.prototype);550BadURLToken.prototype.tokenType = "BADURL";551function WhitespaceToken() { return this; }552WhitespaceToken.prototype = Object.create(CSSParserToken.prototype);553WhitespaceToken.prototype.tokenType = "WHITESPACE";554WhitespaceToken.prototype.toString = function() { return "WS"; }555WhitespaceToken.prototype.toSource = function() { return " "; }556function CDOToken() { return this; }557CDOToken.prototype = Object.create(CSSParserToken.prototype);558CDOToken.prototype.tokenType = "CDO";559CDOToken.prototype.toSource = function() { return "<!--"; }560function CDCToken() { return this; }561CDCToken.prototype = Object.create(CSSParserToken.prototype);562CDCToken.prototype.tokenType = "CDC";563CDCToken.prototype.toSource = function() { return "-->"; }564function ColonToken() { return this; }565ColonToken.prototype = Object.create(CSSParserToken.prototype);566ColonToken.prototype.tokenType = ":";567function SemicolonToken() { return this; }568SemicolonToken.prototype = Object.create(CSSParserToken.prototype);569SemicolonToken.prototype.tokenType = ";";570function CommaToken() { return this; }571CommaToken.prototype = Object.create(CSSParserToken.prototype);572CommaToken.prototype.tokenType = ",";573function GroupingToken() { throw "Abstract Base Class"; }574GroupingToken.prototype = Object.create(CSSParserToken.prototype);575function OpenCurlyToken() { this.value = "{"; this.mirror = "}"; return this; }576OpenCurlyToken.prototype = Object.create(GroupingToken.prototype);577OpenCurlyToken.prototype.tokenType = "{";578function CloseCurlyToken() { this.value = "}"; this.mirror = "{"; return this; }579CloseCurlyToken.prototype = Object.create(GroupingToken.prototype);580CloseCurlyToken.prototype.tokenType = "}";581function OpenSquareToken() { this.value = "["; this.mirror = "]"; return this; }582OpenSquareToken.prototype = Object.create(GroupingToken.prototype);583OpenSquareToken.prototype.tokenType = "[";584function CloseSquareToken() { this.value = "]"; this.mirror = "["; return this; }585CloseSquareToken.prototype = Object.create(GroupingToken.prototype);586CloseSquareToken.prototype.tokenType = "]";587function OpenParenToken() { this.value = "("; this.mirror = ")"; return this; }588OpenParenToken.prototype = Object.create(GroupingToken.prototype);589OpenParenToken.prototype.tokenType = "(";590function CloseParenToken() { this.value = ")"; this.mirror = "("; return this; }591CloseParenToken.prototype = Object.create(GroupingToken.prototype);592CloseParenToken.prototype.tokenType = ")";593function IncludeMatchToken() { return this; }594IncludeMatchToken.prototype = Object.create(CSSParserToken.prototype);595IncludeMatchToken.prototype.tokenType = "~=";596function DashMatchToken() { return this; }597DashMatchToken.prototype = Object.create(CSSParserToken.prototype);598DashMatchToken.prototype.tokenType = "|=";599function PrefixMatchToken() { return this; }600PrefixMatchToken.prototype = Object.create(CSSParserToken.prototype);601PrefixMatchToken.prototype.tokenType = "^=";...

Full Screen

Full Screen

ts-component.ts

Source:ts-component.ts Github

copy

Full Screen

1#!/usr/bin/env node2import fs from 'fs';3import path from 'path';4import * as ts from 'typescript';5import yargs from 'yargs';6import { hideBin } from 'yargs/helpers';7import { scanAsync } from 'ts-scan';8import { scanAllChildren, AstInfo } from 'ts-parser';9import * as CSV from 'libs/csv-parser';10import { CSVItem } from 'libs/csv-parser';11enum AttentionKind {12 none,13 arrow,14 arrowVariable,15 export,16 paren,17 function,18 functionCall,19 variable,20 component,21 comment,22 property,23 object,24 objectProperty,25 block,26}27interface AstNode extends AstInfo {28 identifier?: AstNode;29 returnStatement?: AstNode;30 children?: AstNode[];31 attention?: AttentionKind;32 note?: string;33 syntax: {34 export: boolean;35 };36}37const initAstNode = (n: AstNode) => {38 n.syntax = { export: false };39};40interface AstRegExp {41 exp: RegExp | RegExp[] | [any, RegExp][];42 options?: any[];43 match?: (option: any, reg?: AstRegExp) => void;44}45const indent = (level: number) => new Array(level).fill(' ').join('');46class AstStack extends Array<AstNode> {47 replace(ast: AstNode) {48 this.pop();49 this.push(ast);50 }51 last(offset: number = 0) {52 return this[this.length - 1 + offset];53 }54 indexFromLast(kind: string | string[], hook?: (index: number) => void) {55 for (let i = this.length - 2; i >= 0; i--) {56 if (Array.isArray(kind)) {57 for (let j = 0; j < kind.length; j++) {58 if (this[i].kind === kind[j]) {59 if (hook) hook(i);60 return i;61 }62 }63 } else {64 if (this[i].kind === kind) {65 if (hook) hook(i);66 return i;67 }68 }69 }70 return -1;71 }72 findFromLast(kind: string | string[], hook?: (node: AstNode) => void) {73 return this.indexFromLast(kind, (index: number) => {74 if (hook) hook(this[index]);75 });76 }77 match(regs: AstRegExp[] | AstRegExp) {78 const path = this.astPath;79 const test = (reg: AstRegExp, exp: RegExp | RegExp[] | [any, RegExp][]) => {80 // exp が配列の場合81 if (Array.isArray(exp)) {82 return exp.some((e, i) => {83 if (Array.isArray(e)) {84 const result = e[1].test(path);85 if (result && reg.match) reg.match(e[0], reg);86 return result;87 } else {88 const result = e.test(path);89 if (result && reg.match) reg.match(reg.options?.[i], reg);90 return result;91 }92 });93 }94 // exp が単体の場合95 const result = exp.test(path);96 if (result && reg.match) reg.match(reg.options?.[0], reg);97 return result;98 };99 // regs が配列の場合100 if (Array.isArray(regs)) {101 return regs.some((reg, i) => {102 return test(reg, reg.exp);103 });104 }105 // regs が単体の場合106 return test(regs, regs.exp);107 }108 get astPath() {109 return this.map((v) => v.kind).join('/');110 }111}112function getText(node: AstNode | undefined, kind = AttentionKind.none): string {113 if (node) {114 if (115 node.attention === AttentionKind.arrowVariable116 // node.attention === AttentionKind.variable ||117 // node.attention === AttentionKind.function118 ) {119 return getText(node.identifier, node.attention);120 }121 const kindStr =122 AttentionKind[kind === AttentionKind.none ? node.attention || 0 : kind];123 const textStr =124 node.attention === AttentionKind.comment ||125 node.attention === AttentionKind.export126 ? node.text127 : node.text.replace(/[ \n]/g, '');128 return `${node.line} ${kindStr}: ${textStr} #${node.note || ''}, !${129 node.syntax.export ? 'export' : 'intarnal'130 }`;131 }132 return '';133}134class ExportCSV {135 level: number = 0;136 getCsv(node: AstNode | undefined, kind = AttentionKind.none): CSVItem[] {137 if (node) {138 if (139 node.attention === AttentionKind.arrowVariable140 // node.attention === AttentionKind.variable ||141 // node.attention === AttentionKind.function142 ) {143 return this.getCsv(node.identifier, node.attention);144 }145 const kindStr =146 AttentionKind[kind === AttentionKind.none ? node.attention || 0 : kind];147 const textStr = (node: AstNode) => {148 const note = node.note || '';149 const r =150 node.attention === AttentionKind.comment ||151 node.attention === AttentionKind.export152 ? node.text153 : node.text.replace(/[ \n]/g, '');154 if (note.indexOf('fragment') < 0) {155 if (note === 'jsx-close') {156 return `</${r}>`;157 }158 if (note.indexOf('jsx-self') === 0) {159 return `<${r} />`;160 }161 if (note.indexOf('jsx-open') === 0) {162 return `<${r}>`;163 }164 }165 return r;166 };167 const getIndentCell = (level: number) => {168 return new Array(level < 0 ? 0 : level).fill(' ').join('');169 };170 const note = node.note || '';171 if (note.indexOf('open') >= 0) this.level++;172 const returnStatement = node.returnStatement;173 const returnComponent = returnStatement ? textStr(returnStatement) : '';174 const getCsvCol = () => {175 if (kindStr === 'paren' || kindStr === 'block' || kindStr === 'arrow') {176 return [];177 } else {178 return [179 { value: `` },180 { value: `${node.line}` },181 {182 value: `${kindStr}${returnComponent !== '' ? '-component' : ''}`,183 },184 { value: `${getIndentCell(this.level)}${textStr(node)}` },185 { value: node.syntax.export ? 'export' : '' },186 { value: note },187 ];188 }189 };190 const retval = getCsvCol();191 if (note.indexOf('close') >= 0) this.level--;192 return retval;193 }194 return [];195 }196}197class Parser {198 _ptr = 0;199 _info: AstNode[];200 constructor(info: AstNode[]) {201 this._info = info;202 }203 prev() {204 return this._info[--this._ptr];205 }206 next() {207 return this._info[this._ptr++];208 }209 last(d: number = 0) {210 return this._info[this._ptr - 1 + d];211 }212 isEnd() {213 return this._ptr >= this._info.length;214 }215 stack: AstStack = new AstStack();216 debugLog = (m: AstNode) => {217 const isJsxElement = (node: AstNode) =>218 node.kind === 'JsxOpeningElement' ||219 node.kind === 'JsxClosingElement' ||220 node.kind === 'JsxOpeningFragment' ||221 node.kind === 'JsxClosingFragment' ||222 node.kind === 'JsxSelfClosingElement';223 const isComment = (node: AstNode) =>224 node.kind === 'MultiLineCommentTrivia' ||225 node.kind === 'SingleLineCommentTrivia';226 const isArrow = (node: AstNode) => node.kind === 'CloseParenToken';227 const printLog = (node: AstNode) => {228 if (node.kind === 'Identifier' || node.kind === 'ImportKeyword') {229 console.log(`${indent(node.level)}${node.kind} - ${node.text}`);230 } else {231 console.log(`${indent(node.level)}${node.kind}`);232 }233 };234 printLog(m);235 if (236 m.kind.search(/Declaration$/) >= 0 ||237 m.kind === 'Identifier' ||238 m.kind === 'ExportKeyword' ||239 isArrow(m) ||240 isJsxElement(m) ||241 isComment(m)242 ) {243 console.log(this.stack.astPath, m.text);244 }245 };246 pushAttention = (node: AstNode, attention: AttentionKind) => {247 node.attention = attention;248 this.attentions.push(node);249 };250 replaceAttention = (node: AstNode, attention: AttentionKind) => {251 node.attention = attention;252 this.attentions.pop();253 this.attentions.push(node);254 };255 attentions: AstNode[] = [];256 traverse = (_node: AstNode) => {257 this.stack.push(_node);258 let node = _node;259 let next = _node;260 const isExport = (offset: number, kind?: string) => {261 const node = this.stack.last(offset);262 if (node && node.syntax.export === true) {263 if (kind) {264 if (node.kind === kind) return node;265 } else {266 return node;267 }268 }269 return null;270 };271 while (!this.isEnd()) {272 this.stack.match([273 // 変数を特定274 {275 exp: /VariableDeclaration\/Identifier$/,276 match: () => {277 const ast = this.stack.last();278 if (isExport(-4, 'VariableStatement')) {279 ast.syntax.export = true;280 }281 this.pushAttention(ast, AttentionKind.variable);282 this.stack.findFromLast(283 ['VariableDeclaration'],284 (node: AstNode) => {285 node.identifier = ast;286 }287 );288 },289 },290 //291 // 関数名を特定292 {293 exp: /FunctionDeclaration\/Identifier$/,294 match: () => {295 const ast = this.stack.last();296 if (isExport(-1)) {297 ast.syntax.export = true;298 }299 this.pushAttention(ast, AttentionKind.function);300 this.stack.findFromLast(301 ['FunctionDeclaration'],302 (node: AstNode) => {303 node.identifier = ast;304 }305 );306 },307 },308 // 関数呼び出し309 {310 exp: /CallExpression\/Identifier$/,311 match: () => {312 const ast = this.stack.last();313 this.pushAttention(ast, AttentionKind.functionCall);314 },315 },316 // コンポーネントが戻り値になっている関数を特定317 {318 exp: [319 [320 'jsx-open-return',321 /ReturnStatement\/ParenthesizedExpression\/JsxElement\/JsxOpeningElement\/Identifier$/,322 ],323 [324 'jsx-self-return',325 /ReturnStatement\/ParenthesizedExpression\/JsxSelfClosingElement\/Identifier$/,326 ],327 [328 'jsx-open-return-fragment',329 /ReturnStatement\/ParenthesizedExpression\/JsxFragment\/JsxOpeningFragment$/,330 ],331 [332 'jsx-open-return',333 /ReturnStatement\/JsxElement\/JsxOpeningElement\/Identifier$/,334 ],335 [336 'jsx-self-return',337 /ReturnStatement\/JsxSelfClosingElement\/Identifier$/,338 ],339 [340 'jsx-open-return-fragment',341 /ReturnStatement\/JsxFragment\/JsxOpeningFragment$/,342 ],343 [344 'jsx-open-return',345 /ReturnStatement\/JsxSelfClosingElement\/Identifier$/,346 ],347 ],348 match: (option) => {349 const ast = this.stack.last();350 ast.note = option;351 this.pushAttention(ast, AttentionKind.component);352 this.stack.findFromLast(353 ['FunctionDeclaration', 'VariableDeclaration'],354 (node: AstNode) => {355 if (node.identifier) {356 node.identifier.returnStatement = ast;357 }358 }359 );360 },361 },362 // コンポーネントが戻り値になっているアロー関数を特定363 {364 exp: [365 [366 [-4, 'jsx-open-return'],367 /VariableDeclaration\/ArrowFunction\/ParenthesizedExpression\/JsxElement\/JsxOpeningElement$/,368 ],369 [370 [-4, 'jsx-self-return'],371 /VariableDeclaration\/ArrowFunction\/ParenthesizedExpression\/JsxElement\/JsxSelfClosingElement$/,372 ],373 [374 [-4, 'jsx-open-return-fragment'],375 /VariableDeclaration\/ArrowFunction\/ParenthesizedExpression\/JsxFragment\/JsxOpeningFragment$/,376 ],377 [378 [-3, 'jsx-open-return'],379 /VariableDeclaration\/ArrowFunction\/JsxElement\/JsxOpeningElement$/,380 ],381 [382 [-3, 'jsx-self-return'],383 /VariableDeclaration\/ArrowFunction\/JsxElement\/JsxSelfClosingElement$/,384 ],385 [386 [-3, 'jsx-open-return-fragment'],387 /VariableDeclaration\/ArrowFunction\/JsxFragment\/JsxOpeningFragment$/,388 ],389 [390 [-2, 'jsx-open-return'],391 /VariableDeclaration\/ArrowFunction\/JsxOpeningElement$/,392 ],393 [394 [-2, 'jsx-self-return'],395 /VariableDeclaration\/ArrowFunction\/JsxSelfClosingElement$/,396 ],397 [398 [-2, 'jsx-open-return-fragment'],399 /VariableDeclaration\/ArrowFunction\/JsxOpeningFragment$/,400 ],401 ],402 match: (option) => {403 const ast = this.stack.last();404 ast.note = option[1];405 if (option[1].indexOf('fragment') >= 0) {406 this.pushAttention(ast, AttentionKind.component);407 }408 const node = this.stack.last(option[0]);409 if (node.identifier) {410 node.identifier.returnStatement = ast;411 }412 },413 },414 // 関数で使用しているコンポーネント415 {416 exp: [417 /JsxOpeningElement\/Identifier$/,418 /JsxOpeningElement\/PropertyAccessExpression\/Identifier$/,419 /JsxOpeningElement\/PropertyAccessExpression\/DotToken$/,420 /JsxSelfClosingElement\/Identifier$/,421 /JsxSelfClosingElement\/PropertyAccessExpression\/Identifier$/,422 /JsxClosingElement\/Identifier$/,423 /JsxClosingElement\/PropertyAccessExpression\/Identifier$/,424 /JsxFragment\/JsxClosingFragment$/,425 ],426 options: [427 'jsx-open',428 'jsx-open-prop',429 'jsx-dot-prop',430 'jsx-self',431 'jsx-self-prop',432 'jsx-close',433 'jsx-close-prop',434 'jsx-close-fragment',435 ],436 match: (option) => {437 const ast = this.stack.last();438 ast.note = option;439 if (option.indexOf('prop') >= 0) {440 this.stack.findFromLast(441 ['PropertyAccessExpression'],442 (node: AstNode) => {443 node.text += ast.text;444 }445 );446 } else {447 this.stack.findFromLast(448 ['FunctionDeclaration', 'VariableDeclaration'],449 (node: AstNode) => {450 if (!node.children) node.children = [];451 node.children?.push(ast);452 this.pushAttention(ast, AttentionKind.component);453 }454 );455 }456 },457 },458 // プロパティ459 {460 exp: [461 ['jsx-open', /JsxOpeningElement\/PropertyAccessExpression$/],462 ['jsx-close', /JsxClosingElement\/PropertyAccessExpression$/],463 ['prop', /PropertyAccessExpression$/],464 ['word', /PropertyAccessExpression\/Identifier$/],465 ['word', /PropertyAccessExpression\/DotToken$/],466 ],467 match: (option) => {468 const ast = this.stack.last();469 if (option === 'word') {470 this.stack.findFromLast(471 ['PropertyAccessExpression'],472 (node: AstNode) => {473 node.text += ast.text;474 }475 );476 } else {477 ast.text = '';478 this.stack.match({479 exp: [/PropertyAccessExpression\/PropertyAccessExpression$/],480 match: (option) => {481 const node = this.stack.last(-1);482 if (!node.children) node.children = [];483 node.children?.push(ast);484 },485 });486 if (option.indexOf('jsx') >= 0) {487 ast.note = option;488 this.pushAttention(ast, AttentionKind.component);489 } else {490 this.pushAttention(ast, AttentionKind.property);491 }492 }493 },494 },495 // アロー関数496 {497 exp: [498 ['open', /ArrowFunction\/OpenParenToken$/],499 ['close', /ArrowFunction\/CloseParenToken$/],500 ['open', /CallExpression\/OpenParenToken$/],501 ['close', /CallExpression\/CloseParenToken$/],502 ['arrow', /ArrowFunction\/EqualsGreaterThanToken$/],503 ['open', /ArrowFunction\/OpenParenToken\/Block\/OpenBraceToken$/],504 ['close', /ArrowFunction\/OpenParenToken\/Block\/CloseBraceToken$/],505 ['open', /ArrowFunction\/(.+?)Expression\/OpenParenToken$/],506 ['close', /ArrowFunction\/(.+?)Expression\/CloseParenToken$/],507 ],508 match: (option) => {509 const ast = this.stack.last();510 this.stack.match({511 exp: [512 [-2, /VariableDeclaration\/ArrowFunction\/OpenParenToken$/],513 [514 -3,515 /VariableDeclaration\/ArrowFunction\/ParenthesizedExpression\/OpenBraceToken$/,516 ],517 ],518 match: (option) => {519 const variableAst = this.stack.last(option);520 if (isExport(option - 3)) {521 if (variableAst.identifier)522 variableAst.identifier.syntax.export = true;523 }524 variableAst.attention = AttentionKind.arrowVariable;525 },526 });527 ast.note = option;528 if (option === 'arrow') {529 this.pushAttention(ast, AttentionKind.arrow);530 } else {531 this.pushAttention(ast, AttentionKind.paren);532 }533 },534 },535 // オブジェクト536 {537 exp: [538 ['object-open', /ObjectLiteralExpression\/OpenBraceToken$/],539 ['object-close', /ObjectLiteralExpression\/CloseBraceToken$/],540 ],541 match: (option) => {542 const ast = this.stack.last();543 ast.note = option;544 this.pushAttention(ast, AttentionKind.object);545 },546 },547 // オブジェクトプロパティ548 {549 exp: [/PropertyAssignment\/Identifier$/],550 match: (option) => {551 const ast = this.stack.last();552 ast.note = 'object-prop';553 this.pushAttention(ast, AttentionKind.objectProperty);554 },555 },556 // エキスポート557 {558 exp: [559 [-3, /SyntaxList\/ExportKeyword$/],560 [-2, /SyntaxList\/ExportAssignment\/ExportKeyword$/],561 ],562 match: (option) => {563 const ast = this.stack.last();564 {565 const ast = this.stack.last(option);566 this.stack567 .slice(option)568 .forEach((node) => (node.syntax.export = true));569 }570 node.syntax = { export: true };571 ast.note = 'export';572 // this.pushAttention(ast, AttentionKind.export);573 },574 },575 // ブロック576 {577 exp: [578 ['open', /Block\/OpenBraceToken$/],579 ['close', /Block\/CloseBraceToken$/],580 ],581 match: (option) => {582 const ast = this.stack.last();583 ast.note = option;584 this.pushAttention(ast, AttentionKind.block);585 },586 },587 // コメント588 {589 exp: [/SingleLineCommentTrivia$/, /MultiLineCommentTrivia$/],590 match: () => {591 const ast = this.stack.last();592 this.pushAttention(ast, AttentionKind.comment);593 },594 },595 ]);596 // this.debugLog(node);597 next = this.next();598 if (next.level < node.level) {599 this.stack.splice(next.level + 1);600 this.prev();601 break;602 }603 if (node.level < next.level) {604 this.traverse(next);605 next = this.next();606 }607 this.stack.pop();608 this.stack.push(next);609 node = next;610 }611 };612}613async function main(argv: string[]) {614 const arg = yargs(hideBin(argv))615 .detectLocale(false)616 .scriptName('ts-component')617 .usage('$0 [options] <source>', 'Extract react component.')618 .option('base', {619 type: 'string',620 default: '',621 describe: 'Set base directory',622 demandOption: true,623 })624 .option('mode', {625 choices: ['log', 'csv'],626 default: 'csv',627 describe: 'Select output format',628 })629 .option('source', { type: 'string', demandOption: true })630 .help()631 .parseSync();632 const baseDir = `${arg.base}`;633 const srcPath = `${arg.source}`;634 const importedFiles = await scanAsync(srcPath, baseDir);635 const result = new Set(importedFiles.map((file) => file.source));636 new Array(...result).forEach((sourcePath) => {637 const sourcePathWithBase = path.join(baseDir, sourcePath);638 const sourceCode = fs.readFileSync(sourcePathWithBase, 'utf-8').trim();639 const sourceFile = ts.createSourceFile(640 sourcePath,641 sourceCode,642 ts.ScriptTarget.ES5,643 true644 );645 const lineInfo: AstNode[] = [];646 scanAllChildren(lineInfo, sourceFile, -1);647 lineInfo.forEach((n) => initAstNode(n));648 const parser = new Parser(lineInfo);649 const topNode = parser.next();650 parser.traverse(topNode);651 const attentions = parser.attentions.sort((a, b) => a.line - b.line);652 if (arg.mode === 'csv') {653 console.log(`${sourcePath}, ${sourcePathWithBase}`);654 const csvExport = new ExportCSV();655 const csvData = attentions656 .map((c) => csvExport.getCsv(c, 0))657 .filter((v) => v.length > 0);658 console.log(CSV.stringify(csvData));659 console.log('');660 } else {661 console.log(`# ${sourcePath}, ${sourcePathWithBase}, ---------`);662 console.log('');663 console.log('## imports');664 const imports = importedFiles665 .filter((file) => file.source === sourcePath)666 .map((file) => file.imports)667 .flat();668 console.log(imports);669 console.log('## attentions');670 console.log(671 JSON.stringify(672 attentions.map((c) => `${getText(c)}`),673 null,674 ' '675 )676 );677 }678 });679}680if (require.main === module) {681 main(process.argv);...

Full Screen

Full Screen

spaces.js

Source:spaces.js Github

copy

Full Screen

1/**2 * @fileoverview A task to automatically adjust spaces as needed.3 * @author Nicholas C. Zakas4 */5//-----------------------------------------------------------------------------6// Helpers7//-----------------------------------------------------------------------------8function findNextCommaOrSemicolon(layout, start) {9 return layout.findNext(part => part.type === "Punctuator", start);10}11function normalizePunctuatorSpacing(layout) {12 let token = findNextCommaOrSemicolon(layout);13 while (token) {14 switch (token.value) {15 case ",":16 case ";":17 layout.noSpaceBefore(token);18 layout.spaceAfter(token);19 break;20 21 case ".":22 layout.noSpaces(token);23 break;24 default:25 if (token.value.includes("=")) {26 layout.spaceBefore(token);27 layout.spaceAfter(token);28 }29 }30 token = findNextCommaOrSemicolon(layout, token);31 }32}33function spaceKeywordAndBrace(node, bodyKey, layout) {34 const firstToken = layout.firstToken(node);35 layout.spaceAfter(firstToken);36 const braceToken = layout.firstToken(node[bodyKey]);37 if (braceToken.value === "{") {38 layout.spaceBefore(braceToken);39 }40}41//-----------------------------------------------------------------------------42// Task43//-----------------------------------------------------------------------------44export default function(context) {45 const layout = context.layout;46 // first, adjust all commas47 normalizePunctuatorSpacing(layout);48 return {49 ArrayExpression(node) {50 51 const { firstToken, lastToken } = layout.boundaryTokens(node);52 layout.noSpaceAfter(firstToken);53 54 // no spacing work for multiline55 if (!layout.isMultiLine(node)) {56 57 layout.noSpaceBefore(lastToken);58 if (node.elements.length) {59 node.elements.forEach((element, index) => {60 if (index > 0) {61 layout.spaceBefore(element);62 }63 layout.noSpaceAfter(element);64 });65 }66 }67 },68 ArrayPattern(node) {69 this.ArrayExpression(node);70 },71 ArrowFunctionExpression(node) {72 73 let openParenToken, closeParenToken;74 const firstToken = layout.firstToken(node);75 76 if (node.async) {77 layout.spaceAfter(firstToken);78 }79 80 if (node.params.length === 0) {81 82 openParenToken = node.async83 ? layout.findNext("(", firstToken)84 : firstToken;85 86 closeParenToken = layout.findNext(")", openParenToken);87 } else if (node.params.length === 1) {88 89 if (node.async) {90 layout.spaceAfter(firstToken);91 openParenToken = layout.findPrevious(part => {92 return part === firstToken || part.value === "(";93 }, node.params[0]);94 95 if (openParenToken.value !== "(") {96 openParenToken = null;97 } else {98 closeParenToken = layout.findNext(")", node.params[0]);99 }100 101 } else {102 if (firstToken.value === "(") {103 openParenToken = firstToken;104 closeParenToken = layout.findNext(")", node.params[0]);105 }106 }107 108 } else {109 110 openParenToken = node.async111 ? layout.findNext("(", firstToken)112 : firstToken;113 114 closeParenToken = layout.findNext(")", node.params[node.params.length - 1]);115 }116 117 if (openParenToken) {118 // have to do both in case there's a comment inside119 layout.noSpaceAfter(openParenToken);120 layout.noSpaceBefore(closeParenToken);121 }122 },123 AwaitExpression(node) {124 const firstToken = layout.firstToken(node);125 layout.spaceAfter(firstToken);126 },127 BinaryExpression(node) {128 const firstToken = layout.firstToken(node);129 const operatorToken = layout.findNext(node.operator, firstToken);130 layout.spaces(operatorToken);131 },132 BlockStatement(node) {133 const { firstToken, lastToken } = layout.boundaryTokens(node);134 if (layout.isSameLine(firstToken, lastToken)) {135 if (node.body.length) {136 layout.spaceAfter(firstToken);137 layout.spaceBefore(lastToken);138 } else {139 layout.noSpaceAfter(firstToken);140 layout.noSpaceBefore(lastToken);141 }142 }143 },144 ConditionalExpression(node) {145 const questionMark = layout.findPrevious("?", node.consequent);146 const colon = layout.findNext(":", node.consequent);147 148 layout.spaceBefore(questionMark);149 layout.spaces(questionMark);150 layout.spaces(colon);151 },152 DoWhileStatement(node) {153 spaceKeywordAndBrace(node, "body", layout);154 const whileToken = layout.findPrevious("while", node.test);155 layout.spaces(whileToken);156 },157 ExportNamedDeclaration(node) {158 const firstToken = layout.firstToken(node);159 layout.spaceAfter(firstToken);160 if (node.specifiers.length) {161 // adjust spaces around braces162 layout.spaceAfter(layout.findNext("{", firstToken));163 layout.spaceBefore(layout.findNext("}", firstToken));164 }165 },166 ForStatement(node) {167 spaceKeywordAndBrace(node, "body", layout);168 },169 ForInStatement(node) {170 this.ForStatement(node);171 },172 ForOfStatement(node) {173 this.ForStatement(node);174 },175 FunctionDeclaration(node, parent) {176 this.FunctionExpression(node, parent);177 },178 FunctionExpression(node, parent) {179 // ESTree quirk: concise methods don't have "function" keyword180 const isConcise =181 (parent.type === "Property" && parent.method) ||182 (parent.type === "MethodDefinition");183 let token = layout.firstToken(node);184 let id, openParen;185 if (!isConcise) {186 187 // "async" keyword188 if (token.value === "async") {189 layout.spaceAfter(token);190 token = layout.nextToken(token);191 }192 // "function" keyword193 layout.spaceAfter(token);194 token = layout.nextToken(token);195 // "*" punctuator196 if (token.value === "*") {197 layout.noSpaceAfter(token);198 token = layout.nextToken(token);199 }200 // function name201 if (token.type === "Identifier") {202 layout.noSpaceAfter(token);203 token = layout.nextToken(token);204 }205 206 if (token.value === "(") {207 openParen = token;208 } else {209 throw new Error(`Unexpected token "${token.value}".`);210 }211 } else {212 let idStart = layout.firstToken(parent.key);213 id = idStart;214 if (parent.computed) {215 const leftBracket = layout.previousToken(idStart);216 layout.noSpaceAfter(leftBracket);217 const rightBracket = layout.nextToken(idStart);218 layout.noSpaceBefore(rightBracket);219 idStart = leftBracket;220 id = rightBracket;221 }222 if (parent.generator) {223 const star = layout.previousToken(idStart);224 layout.noSpaceAfter(star);225 }226 openParen = token;227 }228 if (id) {229 layout.noSpaceAfter(id);230 }231 232 layout.noSpaces(openParen);233 const openBrace = layout.firstToken(node.body);234 layout.spaceBefore(openBrace);235 236 const closeParen = layout.findPrevious(")", openBrace);237 layout.noSpaceBefore(closeParen);238 },239 240 IfStatement(node) {241 spaceKeywordAndBrace(node, "consequent", layout);242 if (node.alternate) {243 const elseToken = layout.findPrevious("else", node.alternate);244 layout.spaces(elseToken);245 }246 },247 ImportDeclaration(node) {248 const firstToken = layout.firstToken(node);249 layout.spaceAfter(firstToken);250 const fromToken = layout.findPrevious("from", node.source);251 layout.spaces(fromToken);252 if (node.specifiers.some(node => node.type === "ImportSpecifier")) {253 // adjust spaces around braces254 layout.spaceAfter(layout.findNext("{", firstToken));255 layout.spaceBefore(layout.findNext("}", firstToken));256 }257 },258 LogicalExpression(node) {259 this.BinaryExpression(node);260 },261 MethodDefinition(node) {262 this.FunctionExpression(node.value, node);263 },264 ObjectExpression(node) {265 const { firstToken, lastToken } = layout.boundaryTokens(node);266 layout.spaceAfter(firstToken);267 if (!layout.isMultiLine(node)) {268 269 if (node.properties.length) {270 271 node.properties.forEach((property, index) => {272 273 if (index > 0) {274 layout.spaceBefore(property);275 }276 layout.noSpaceAfter(property);277 });278 }279 }280 281 layout.spaceBefore(lastToken);282 },283 ObjectPattern(node) {284 this.ObjectExpression(node);285 },286 Property(node) {287 // ensure there's a space after the colon in properties288 if (!node.shorthand && !node.method) {289 layout.spaceBefore(node.value);290 291 // also be sure to check spacing of computed properties292 if (node.computed) {293 const firstToken = layout.firstToken(node.key);294 const openBracket = layout.findPrevious("[", firstToken);295 const closeBracket = layout.findNext("]", firstToken);296 297 layout.noSpaceAfter(openBracket);298 layout.noSpaceBefore(closeBracket);299 layout.noSpaceAfter(closeBracket);300 } else {301 layout.noSpaceAfter(node.key);302 }303 }304 if (node.method) {305 layout.spaceBefore(node.value.body);306 }307 },308 ReturnStatement(node) {309 if (node.argument) {310 layout.spaceBefore(node.argument);311 } else {312 layout.noSpaceAfter(node);313 }314 },315 SwitchStatement(node) {316 const firstToken = layout.firstToken(node);317 layout.spaceAfter(firstToken);318 const braceToken = layout.findNext("{", node.discriminant);319 layout.spaceBefore(braceToken);320 },321 SwitchCase(node) {322 const colon = layout.findPrevious(":", node.consequent[0]);323 layout.noSpaceBefore(colon);324 layout.spaceAfter(colon);325 },326 TemplateLiteral(node) {327 const [firstQuasi, ...quasis] = node.quasis;328 if (quasis.length) {329 layout.noSpaceAfter(firstQuasi);330 331 quasis.forEach(quasi => {332 layout.noSpaceBefore(quasi);333 layout.noSpaceAfter(quasi);334 });335 }336 },337 ThrowStatement(node) {338 const firstToken = layout.firstToken(node);339 layout.spaceAfter(firstToken);340 },341 TryStatement(node) {342 spaceKeywordAndBrace(node, "block", layout);343 const catchToken = layout.firstToken(node.handler);344 layout.spaces(catchToken);345 const catchBraceToken = layout.firstToken(node.handler.body);346 layout.spaceBefore(catchBraceToken);347 if (node.finalizer) {348 const finallyBraceToken = layout.firstToken(node.finalizer);349 const finallyToken = layout.findPrevious("finally", finallyBraceToken);350 layout.spaces(finallyToken);351 }352 },353 UpdateExpression(node) {354 if (node.prefix) {355 const operatorToken = layout.firstToken(node);356 // "typeof" is also an operator and requires a space no matter what357 if (operatorToken.type === "Punctuator") {358 layout.noSpaceAfter(operatorToken);359 } else {360 layout.spaceAfter(operatorToken);361 }362 } else {363 const operatorToken = layout.lastToken(node);364 layout.noSpaceBefore(operatorToken);365 }366 },367 UnaryExpression(node) {368 this.UpdateExpression(node);369 },370 VariableDeclaration(node) {371 const firstToken = layout.firstToken(node);372 layout.spaceAfter(firstToken);373 },374 375 WhileStatement(node) {376 spaceKeywordAndBrace(node, "body", layout);377 },378 YieldExpression(node) {379 const firstToken = layout.firstToken(node);380 layout.spaceAfter(firstToken);381 },382 383 };...

Full Screen

Full Screen

spaceBeforeFunctionParenRule.js

Source:spaceBeforeFunctionParenRule.js Github

copy

Full Screen

1/**2 * @license3 * Copyright 2016 Palantir Technologies, Inc.4 *5 * Licensed under the Apache License, Version 2.0 (the "License");6 * you may not use this file except in compliance with the License.7 * You may obtain a copy of the License at8 *9 * http://www.apache.org/licenses/LICENSE-2.010 *11 * Unless required by applicable law or agreed to in writing, software12 * distributed under the License is distributed on an "AS IS" BASIS,13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.14 * See the License for the specific language governing permissions and15 * limitations under the License.16 */17"use strict";18var __extends = (this && this.__extends) || (function () {19 var extendStatics = Object.setPrototypeOf ||20 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||21 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };22 return function (d, b) {23 extendStatics(d, b);24 function __() { this.constructor = d; }25 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());26 };27})();28Object.defineProperty(exports, "__esModule", { value: true });29var ts = require("typescript");30var Lint = require("../index");31var ALWAYS_OR_NEVER = {32 enum: ["always", "never"],33 type: "string",34};35var Rule = (function (_super) {36 __extends(Rule, _super);37 function Rule() {38 return _super !== null && _super.apply(this, arguments) || this;39 }40 Rule.prototype.apply = function (sourceFile) {41 return this.applyWithWalker(new FunctionWalker(sourceFile, this.getOptions()));42 };43 return Rule;44}(Lint.Rules.AbstractRule));45Rule.metadata = {46 description: "Require or disallow a space before function parenthesis",47 hasFix: true,48 optionExamples: [49 "true",50 "[true, \"always\"]",51 "[true, \"never\"]",52 "[true, {\"anonymous\": \"always\", \"named\": \"never\", \"asyncArrow\": \"always\"}]",53 ],54 options: {55 properties: {56 anonymous: ALWAYS_OR_NEVER,57 asyncArrow: ALWAYS_OR_NEVER,58 constructor: ALWAYS_OR_NEVER,59 method: ALWAYS_OR_NEVER,60 named: ALWAYS_OR_NEVER,61 },62 type: "object",63 },64 optionsDescription: (_a = ["\n One argument which is an object which may contain the keys `anonymous`, `named`, and `asyncArrow`\n These should be set to either `\"always\"` or `\"never\"`.\n\n * `\"anonymous\"` checks before the opening paren in anonymous functions\n * `\"named\"` checks before the opening paren in named functions\n * `\"asyncArrow\"` checks before the opening paren in async arrow functions\n * `\"method\"` checks before the opening paren in class methods\n * `\"constructor\"` checks before the opening paren in class constructors\n "], _a.raw = ["\n One argument which is an object which may contain the keys \\`anonymous\\`, \\`named\\`, and \\`asyncArrow\\`\n These should be set to either \\`\"always\"\\` or \\`\"never\"\\`.\n\n * \\`\"anonymous\"\\` checks before the opening paren in anonymous functions\n * \\`\"named\"\\` checks before the opening paren in named functions\n * \\`\"asyncArrow\"\\` checks before the opening paren in async arrow functions\n * \\`\"method\"\\` checks before the opening paren in class methods\n * \\`\"constructor\"\\` checks before the opening paren in class constructors\n "], Lint.Utils.dedent(_a)),65 ruleName: "space-before-function-paren",66 type: "style",67 typescriptOnly: false,68};69Rule.INVALID_WHITESPACE_ERROR = "Spaces before function parens are disallowed";70Rule.MISSING_WHITESPACE_ERROR = "Missing whitespace before function parens";71exports.Rule = Rule;72var FunctionWalker = (function (_super) {73 __extends(FunctionWalker, _super);74 function FunctionWalker(sourceFile, options) {75 var _this = _super.call(this, sourceFile, options) || this;76 // assign constructor now to avoid typescript assuming its a function type77 _this.cachedOptions = { constructor: undefined };78 _this.scanner = ts.createScanner(ts.ScriptTarget.ES5, false, ts.LanguageVariant.Standard, sourceFile.text);79 _this.cacheOptions();80 return _this;81 }82 FunctionWalker.prototype.visitArrowFunction = function (node) {83 var option = this.getOption("asyncArrow");84 var syntaxList = Lint.childOfKind(node, ts.SyntaxKind.SyntaxList);85 var isAsyncArrow = syntaxList.getStart() === node.getStart() && syntaxList.getText() === "async";86 var openParen = isAsyncArrow ? Lint.childOfKind(node, ts.SyntaxKind.OpenParenToken) : undefined;87 this.evaluateRuleAt(openParen, option);88 _super.prototype.visitArrowFunction.call(this, node);89 };90 FunctionWalker.prototype.visitConstructorDeclaration = function (node) {91 var option = this.getOption("constructor");92 var openParen = Lint.childOfKind(node, ts.SyntaxKind.OpenParenToken);93 this.evaluateRuleAt(openParen, option);94 _super.prototype.visitConstructorDeclaration.call(this, node);95 };96 FunctionWalker.prototype.visitFunctionDeclaration = function (node) {97 this.visitFunction(node);98 _super.prototype.visitFunctionDeclaration.call(this, node);99 };100 FunctionWalker.prototype.visitFunctionExpression = function (node) {101 this.visitFunction(node);102 _super.prototype.visitFunctionExpression.call(this, node);103 };104 FunctionWalker.prototype.visitMethodDeclaration = function (node) {105 this.visitMethod(node);106 _super.prototype.visitMethodDeclaration.call(this, node);107 };108 FunctionWalker.prototype.visitMethodSignature = function (node) {109 this.visitMethod(node);110 _super.prototype.visitMethodSignature.call(this, node);111 };112 FunctionWalker.prototype.cacheOptions = function () {113 var _this = this;114 var allOptions = this.getOptions();115 var options = allOptions[0];116 var optionNames = ["anonymous", "asyncArrow", "constructor", "method", "named"];117 optionNames.forEach(function (optionName) {118 switch (options) {119 case undefined:120 case "always":121 _this.cachedOptions[optionName] = "always";122 break;123 case "never":124 _this.cachedOptions[optionName] = "never";125 break;126 default:127 _this.cachedOptions[optionName] = options[optionName];128 }129 });130 };131 FunctionWalker.prototype.getOption = function (optionName) {132 return this.cachedOptions[optionName];133 };134 FunctionWalker.prototype.evaluateRuleAt = function (openParen, option) {135 if (openParen === undefined || option === undefined) {136 return;137 }138 var hasSpace = this.isSpaceAt(openParen.getStart() - 1);139 if (hasSpace && option === "never") {140 var pos = openParen.getStart() - 1;141 var fix = new Lint.Fix(Rule.metadata.ruleName, [this.deleteText(pos, 1)]);142 this.addFailureAt(pos, 1, Rule.INVALID_WHITESPACE_ERROR, fix);143 }144 else if (!hasSpace && option === "always") {145 var pos = openParen.getStart();146 var fix = new Lint.Fix(Rule.metadata.ruleName, [this.appendText(pos, " ")]);147 this.addFailureAt(pos, 1, Rule.MISSING_WHITESPACE_ERROR, fix);148 }149 };150 FunctionWalker.prototype.isSpaceAt = function (textPos) {151 this.scanner.setTextPos(textPos);152 var prevTokenKind = this.scanner.scan();153 return prevTokenKind === ts.SyntaxKind.WhitespaceTrivia;154 };155 FunctionWalker.prototype.visitFunction = function (node) {156 var identifier = Lint.childOfKind(node, ts.SyntaxKind.Identifier);157 var hasIdentifier = identifier !== undefined && (identifier.getEnd() !== identifier.getStart());158 var optionName = hasIdentifier ? "named" : "anonymous";159 var option = this.getOption(optionName);160 var openParen = Lint.childOfKind(node, ts.SyntaxKind.OpenParenToken);161 this.evaluateRuleAt(openParen, option);162 };163 FunctionWalker.prototype.visitMethod = function (node) {164 var option = this.getOption("method");165 var openParen = Lint.childOfKind(node, ts.SyntaxKind.OpenParenToken);166 this.evaluateRuleAt(openParen, option);167 };168 return FunctionWalker;169}(Lint.RuleWalker));...

Full Screen

Full Screen

objectLiteralShorthandRule.js

Source:objectLiteralShorthandRule.js Github

copy

Full Screen

1"use strict";2/**3 * @license4 * Copyright 2016 Palantir Technologies, Inc.5 *6 * Licensed under the Apache License, Version 2.0 (the "License");7 * you may not use this file except in compliance with the License.8 * You may obtain a copy of the License at9 *10 * http://www.apache.org/licenses/LICENSE-2.011 *12 * Unless required by applicable law or agreed to in writing, software13 * distributed under the License is distributed on an "AS IS" BASIS,14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.15 * See the License for the specific language governing permissions and16 * limitations under the License.17 */18Object.defineProperty(exports, "__esModule", { value: true });19var tslib_1 = require("tslib");20var tsutils_1 = require("tsutils");21var ts = require("typescript");22var Lint = require("..");23var OPTION_NEVER = "never";24var Rule = /** @class */ (function (_super) {25 tslib_1.__extends(Rule, _super);26 function Rule() {27 return _super !== null && _super.apply(this, arguments) || this;28 }29 Rule.prototype.apply = function (sourceFile) {30 return this.applyWithFunction(sourceFile, this.ruleArguments.indexOf(OPTION_NEVER) === -131 ? enforceShorthandWalker32 : disallowShorthandWalker);33 };34 /* tslint:disable:object-literal-sort-keys */35 Rule.metadata = {36 ruleName: "object-literal-shorthand",37 description: "Enforces/disallows use of ES6 object literal shorthand.",38 hasFix: true,39 optionsDescription: Lint.Utils.dedent(templateObject_1 || (templateObject_1 = tslib_1.__makeTemplateObject(["\n If the 'never' option is provided, any shorthand object literal syntax will cause a failure."], ["\n If the \\'never\\' option is provided, any shorthand object literal syntax will cause a failure."]))),40 options: {41 type: "string",42 enum: [OPTION_NEVER],43 },44 optionExamples: [true, [true, OPTION_NEVER]],45 type: "style",46 typescriptOnly: false,47 };48 /* tslint:enable:object-literal-sort-keys */49 Rule.LONGHAND_PROPERTY = "Expected property shorthand in object literal ";50 Rule.LONGHAND_METHOD = "Expected method shorthand in object literal ";51 Rule.SHORTHAND_ASSIGNMENT = "Shorthand property assignments have been disallowed.";52 return Rule;53}(Lint.Rules.AbstractRule));54exports.Rule = Rule;55function disallowShorthandWalker(ctx) {56 return ts.forEachChild(ctx.sourceFile, function cb(node) {57 if (tsutils_1.isShorthandPropertyAssignment(node)) {58 ctx.addFailureAtNode(node.name, Rule.SHORTHAND_ASSIGNMENT, Lint.Replacement.appendText(node.getStart(ctx.sourceFile), node.name.text + ": "));59 }60 else if (tsutils_1.isMethodDeclaration(node) && node.parent.kind === ts.SyntaxKind.ObjectLiteralExpression) {61 ctx.addFailureAtNode(node.name, Rule.SHORTHAND_ASSIGNMENT, fixShorthandMethodDeclaration(node, ctx.sourceFile));62 }63 return ts.forEachChild(node, cb);64 });65}66function enforceShorthandWalker(ctx) {67 return ts.forEachChild(ctx.sourceFile, function cb(node) {68 if (tsutils_1.isPropertyAssignment(node)) {69 if (node.name.kind === ts.SyntaxKind.Identifier &&70 tsutils_1.isIdentifier(node.initializer) &&71 node.name.text === node.initializer.text) {72 ctx.addFailureAtNode(node, Rule.LONGHAND_PROPERTY + "('{" + node.name.text + "}').", Lint.Replacement.deleteFromTo(node.name.end, node.end));73 }74 else if (tsutils_1.isFunctionExpression(node.initializer) &&75 // allow named function expressions76 node.initializer.name === undefined) {77 var _a = handleLonghandMethod(node.name, node.initializer, ctx.sourceFile), name = _a[0], fix = _a[1];78 ctx.addFailure(node.getStart(ctx.sourceFile), tsutils_1.getChildOfKind(node.initializer, ts.SyntaxKind.OpenParenToken, ctx.sourceFile).pos, Rule.LONGHAND_METHOD + "('{" + name + "() {...}}').", fix);79 }80 }81 return ts.forEachChild(node, cb);82 });83}84function fixShorthandMethodDeclaration(node, sourceFile) {85 var isGenerator = node.asteriskToken !== undefined;86 var isAsync = tsutils_1.hasModifier(node.modifiers, ts.SyntaxKind.AsyncKeyword);87 return Lint.Replacement.replaceFromTo(node.getStart(sourceFile), node.name.end, node.name.getText(sourceFile) + ":" + (isAsync ? " async" : "") + " function" + (isGenerator ? "*" : ""));88}89function handleLonghandMethod(name, initializer, sourceFile) {90 var nameStart = name.getStart(sourceFile);91 var fix = Lint.Replacement.deleteFromTo(name.end, tsutils_1.getChildOfKind(initializer, ts.SyntaxKind.OpenParenToken).pos);92 var prefix = "";93 if (initializer.asteriskToken !== undefined) {94 prefix = "*";95 }96 if (tsutils_1.hasModifier(initializer.modifiers, ts.SyntaxKind.AsyncKeyword)) {97 prefix = "async " + prefix;98 }99 if (prefix !== "") {100 fix = [fix, Lint.Replacement.appendText(nameStart, prefix)];101 }102 return [prefix + sourceFile.text.substring(nameStart, name.end), fix];103}...

Full Screen

Full Screen

utils.js

Source:utils.js Github

copy

Full Screen

1/** @typedef {import("eslint").Rule.RuleContext} RuleContext */2/** @typedef {import("eslint").Rule.RuleModule} RuleModule */3/** @typedef {import("eslint").Rule.Node} Node */4/** @typedef {import("eslint").AST.Token} Token */5/** @typedef {import("eslint").SourceCode} SourceCode */6/**7 * @typedef {object} PreRequiredData8 * @property {RuleContext} context9 * @property {SourceCode} code10 * @property {boolean} insertSpaces11 * @property {Node} parensData12 */13/**14 * @param {PreRequiredData} preRequiredData15 * @param {Token} a16 * @param {Token} b17 * @param {"open" | "close"} openOrClose18 */19function validateSpacesInCtx( preRequiredData, a, b, openOrClose ) {20 const { context, code, insertSpaces } = preRequiredData21 const undesirableErr = `undesirableSpace${openOrClose === `open` ? `Start` : `End`}`22 const missingErr = `missingSpace${openOrClose === `open` ? `Start` : `End`}`23 if (code.isSpaceBetween( a, b )) {24 if (!insertSpaces) {25 context.report({26 loc: {27 start: a.loc.end,28 end: b.loc.start,29 },30 messageId: undesirableErr,31 fix: fixer => fixer.removeRange([ a.range[ 1 ], b.range[ 0 ] ]),32 })33 } else {34 if (a.loc.end.column < b.loc.start.column - 1) {35 context.report({36 loc: {37 start: { line:a.loc.end.line, column:a.loc.end.column + 1 },38 end: b.loc.start,39 },40 messageId: undesirableErr,41 fix: fixer => fixer.removeRange([ a.range[ 1 ] + 1, b.range[ 0 ] ]),42 })43 }44 }45 } else if (insertSpaces) {46 context.report({47 loc: openOrClose === `open` ? a.loc : b.loc,48 messageId: missingErr,49 fix: fixer => fixer.insertTextAfterRange( a.range, ` ` ),50 })51 }52}53/**54 * @param {PreRequiredData} preRequiredData55 * @param {Token[]} tokens56 * @param {Node} parensData57 * @param {number} firstTokenIndex58 */59function checkSpaces( preRequiredData, tokens, parensData, firstTokenIndex ) {60 if (!parensData) return61 const { context } = preRequiredData62 const openParenToken = tokens[ firstTokenIndex ]63 const tokenAfterOpen = tokens[ firstTokenIndex + 1 ]64 if (!openParenToken || openParenToken.value !== `(`) return65 if (tokenAfterOpen.value === `)`) {66 if (openParenToken.range[ 1 ] != tokenAfterOpen.range[ 0 ]) context.report({67 loc: {68 start: openParenToken.loc.end,69 end: tokenAfterOpen.loc.start,70 },71 messageId: `undesirableSpaceInParens`,72 fix: fixer => fixer.removeRange([73 openParenToken.range[ 1 ],74 tokenAfterOpen.range[ 0 ],75 ]),76 })77 return78 }79 const paramASTTypes = [ `ObjectExpression`, `ObjectPattern`, `ArrayExpression`, `ArrayPattern` ]80 if (Array.isArray( parensData )) {81 if (parensData.length == 1 && paramASTTypes.includes( parensData[ 0 ].type )) {82 preRequiredData.insertSpaces = false83 }84 }85 // if (Array.isArray( parensData ) && parensData.length == 1 && paramASTTypes.includes( parensData[ 0 ].type )) {86 // preRequiredData.insertSpaces = false87 // }88 let a, b89 a = openParenToken90 b = tokenAfterOpen91 validateSpacesInCtx( preRequiredData, a, b, `open` )92 b = Array.isArray( parensData ) ? parensData[ parensData.length - 1 ] : parensData93 b = context.getTokenAfter( b, { filter:token => token.value === `)` } )94 a = context.getTokenBefore( b )95 validateSpacesInCtx( preRequiredData, a, b, `close` )96}97function findTokenIndex( tokenValue, tokens, startFrom = 0, maxSearchIndex = (startFrom + 5) ) {98 const max = tokens.length > maxSearchIndex99 ? maxSearchIndex100 : tokens.length101 for (let i = startFrom; i < max; ++i) {102 if (tokens[ i ].value != tokenValue) continue103 return i104 }105}106module.exports = {107 messagesForParens: {108 missingSpaceStart: `Missing space after parens open`,109 missingSpaceEnd: `Missing space before parens close`,110 undesirableSpaceStart: `Undesirable space after parens open`,111 undesirableSpaceEnd: `Undesirable space before parens close`,112 undesirableSpaceInParens: `Undesirable space between parens without params`,113 },114 messagesForSemi: {115 missingSpaceAfterFirstSemi: `Missing spaces (2 or more) after first loop semicolon`,116 missingSpaceAfterSecondSemi: `Missing spaces (2 or more) after second loop semicolon`,117 },118 validateSpacesInCtx,119 checkSpaces,120 findTokenIndex,...

Full Screen

Full Screen

lexer.js

Source:lexer.js Github

copy

Full Screen

1/**2 * Token 类型枚举3 */4 const SyntaxKind = {5 Unknown: 'Unknown',6 EndOfFileToken: 'EndOfFileToken',7 ConstKeyword: 'ConstKeyword',8 LetKeyword: 'LetKeyword',9 Identifier: 'Identifier',10 ColonToken: 'ColonToken',11 StringLiteral: 'StringLiteral',12 NumericLiteral: 'NumericLiteral',13 SemicolonToken: 'SemicolonToken',14 EqualsToken: 'EqualsToken',15 DotToken: 'DotToken',16 OpenParenToken: 'OpenParenToken',17 CloseParenToken: 'CloseParenToken'18}19/**20 * 关键字映射21 */22const textToKeyword = {23 const: SyntaxKind.ConstKeyword,24 let: SyntaxKind.LetKeyword,25}26class Lexer {27 constructor(text) {28 // 源代码29 this.text = text30 // 指针位置31 this.pos = 032 // 当前符号类型33 this.token = SyntaxKind.Unknown34 // 当前符号值35 this.tokenValue = null36 }37 scan() {38 // while 循环表示指针不断向下读取的过程39 while (true) {40 // 原文本全部读取完毕时,输出『结束符号』41 if (this.pos >= this.text.length) {42 return this.token = SyntaxKind.EndOfFileToken43 }44 const ch = this.text[this.pos]45 switch (ch) {46 case ' ':47 case '\n':48 this.pos++49 continue50 case ':':51 this.pos++52 this.tokenValue = ':'53 return this.token = SyntaxKind.ColonToken54 case '':55 this.pos++56 this.tokenValue = ''57 return this.token = SyntaxKind.SemicolonToken58 case '=':59 this.pos++60 this.tokenValue = '='61 return this.token = SyntaxKind.EqualsToken62 case '"':63 case '\'':64 this.tokenValue = this.scanString()65 return this.token = SyntaxKind.StringLiteral66 case '1':67 case '2':68 case '3':69 case '4':70 case '5':71 case '6':72 case '7':73 case '8':74 case '9':75 this.tokenValue = this.scanNumericLiteral()76 return this.token = SyntaxKind.NumericLiteral77 default:78 return this.token = this.scanIdentifier(ch)79 }80 }81 }82 scanNumericLiteral() {83 const start = this.pos84 while (0 <= this.text[this.pos] && this.text[this.pos] <= 9) {85 this.pos++86 }87 return this.tokenValue = Number(this.text.substring(start, this.pos))88 }89 scanString() {90 const quote = this.text[this.pos]91 this.pos++92 const start = this.pos93 while (this.text[this.pos] !== quote) {94 this.pos++95 }96 this.tokenValue = this.text.substring(start, this.pos)97 this.pos++98 return this.tokenValue99 }100 scanIdentifier() {101 const start = this.pos102 while (true) {103 const ch = this.text[this.pos]104 if (!(('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || ch === '_')) {105 break106 }107 this.pos++108 }109 this.tokenValue = this.text.substring(start, this.pos)110 if (!this.tokenValue) {111 throw new Error('Lexer error')112 }113 // 当前的标识符是否是关键字114 const keyword = textToKeyword[this.tokenValue]115 if (keyword) {116 return keyword117 }118 return this.token = SyntaxKind.Identifier119 }120 getToken() {121 return this.token122 }123 getTokenValue() {124 return this.tokenValue125 }126}127exports.SyntaxKind = SyntaxKind...

Full Screen

Full Screen

prefer-object-rule.js

Source:prefer-object-rule.js Github

copy

Full Screen

1/**2 * @author Brad Zacher <https://github.com/bradzacher>3 */4'use strict';5const utils = require('../utils');6// ------------------------------------------------------------------------------7// Rule Definition8// ------------------------------------------------------------------------------9/** @type {import('eslint').Rule.RuleModule} */10module.exports = {11 meta: {12 type: 'suggestion',13 docs: {14 description: 'disallow rule exports where the export is a function',15 category: 'Rules',16 recommended: true,17 url: 'https://github.com/not-an-aardvark/eslint-plugin-eslint-plugin/tree/HEAD/docs/rules/prefer-object-rule.md',18 },19 fixable: 'code',20 schema: [],21 messages: {22 preferObject: 'Rules should be declared using the object style.',23 },24 },25 create(context) {26 // ----------------------------------------------------------------------27 // Public28 // ----------------------------------------------------------------------29 const sourceCode = context.getSourceCode();30 const ruleInfo = utils.getRuleInfo(sourceCode);31 return {32 Program() {33 if (!ruleInfo || ruleInfo.isNewStyle) {34 return;35 }36 context.report({37 node: ruleInfo.create,38 messageId: 'preferObject',39 *fix(fixer) {40 // note - we intentionally don't worry about formatting here, as otherwise we have41 // to indent the function correctly42 if (43 ruleInfo.create.type === 'FunctionExpression' ||44 ruleInfo.create.type === 'FunctionDeclaration'45 ) {46 const openParenToken = sourceCode.getFirstToken(47 ruleInfo.create,48 (token) => token.type === 'Punctuator' && token.value === '('49 );50 /* istanbul ignore if */51 if (!openParenToken) {52 // this shouldn't happen, but guarding against crashes just in case53 return null;54 }55 yield fixer.replaceTextRange(56 [ruleInfo.create.range[0], openParenToken.range[0]],57 '{create'58 );59 yield fixer.insertTextAfter(ruleInfo.create, '}');60 } else if (ruleInfo.create.type === 'ArrowFunctionExpression') {61 yield fixer.insertTextBefore(ruleInfo.create, '{create: ');62 yield fixer.insertTextAfter(ruleInfo.create, '}');63 }64 },65 });66 },67 };68 },...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { openBrowser, goto, closeBrowser } = require('taiko');2(async () => {3 try {4 await openBrowser();5 await openParenToken();6 await closeBrowser();7 } catch (e) {8 console.error(e);9 } finally {10 }11})();12const { openBrowser, goto, closeBrowser } = require('taiko');13(async () => {14 try {15 await openBrowser();16 await closeParenToken();17 await closeBrowser();18 } catch (e) {19 console.error(e);20 } finally {21 }22})();23const { openBrowser, goto, closeBrowser } = require('taiko');24(async () => {25 try {26 await openBrowser();27 await openCurlyToken();28 await closeBrowser();29 } catch (e) {30 console.error(e);31 } finally {32 }33})();34const { openBrowser, goto, closeBrowser } = require('taiko');35(async () => {36 try {37 await openBrowser();38 await closeCurlyToken();39 await closeBrowser();40 } catch (e) {41 console.error(e);42 } finally {43 }44})();45const { openBrowser, goto, closeBrowser } = require('taiko');46(async () => {47 try {48 await openBrowser();49 await openSquareToken();50 await closeBrowser();51 } catch (e) {52 console.error(e);53 } finally {54 }55})();56const { openBrowser, goto, closeBrowser } = require('taiko');57(async () => {58 try {59 await openBrowser();60 await closeSquareToken();61 await closeBrowser();62 } catch (e) {63 console.error(e);64 } finally {65 }66})();67const { openBrowser, goto, close

Full Screen

Using AI Code Generation

copy

Full Screen

1const { OpenParenToken } = require('@playwright/test/lib/locators/locators');2const { test } = require('@playwright/test');3test('test', async ({ page }) => {4 await page.click(OpenParenToken('Sign in'));5});6const { OpenParenToken } = require('@playwright/test/lib/locators/locators');7const { test } = require('@playwright/test');8test('test', async ({ page }) => {9 await page.click(OpenParenToken('Sign in'));10});11const { OpenParenToken } = require('@playwright/test/lib/locators/locators');12const { test } = require('@playwright/test');13test('test', async ({ page }) => {14 await page.click(OpenParenToken('Sign in'));15});16const { OpenParenToken } = require('@playwright/test/lib/locators/locators');17const { test } = require('@playwright/test');18test('test', async ({ page }) => {19 await page.click(OpenParenToken('Sign in'));20});21const { OpenParenToken } = require('@playwright/test/lib/locators/locators');22const { test } = require('@playwright/test');23test('test', async ({ page }) => {24 await page.click(OpenParenToken('Sign in'));25});26const { OpenParenToken } = require('@playwright/test/lib/locators/locators');27const { test } = require('@playwright/test');28test('test', async ({ page }) => {29 await page.click(OpenParenToken('Sign in'));30});31const { OpenParenToken } = require('@playwright/test/lib/locators/locators');32const { test

Full Screen

Using AI Code Generation

copy

Full Screen

1const { Playwright } = require('playwright');2const { OpenParenToken } = Playwright.internal.grammars.typescript;3const { Playwright } = require('playwright');4const { OpenParenToken } = Playwright.internal.grammars.typescript;5const { Playwright } = require('playwright');6const { OpenParenToken } = Playwright.internal.grammars.typescript;7const { Playwright } = require('playwright');8const { OpenParenToken } = Playwright.internal.grammars.typescript;9const { Playwright } = require('playwright');10const { OpenParenToken } = Playwright.internal.grammars.typescript;11const { Playwright } = require('playwright');12const { OpenParenToken } = Playwright.internal.grammars.typescript;13const { Playwright } = require('playwright');14const { OpenParenToken } = Playwright.internal.grammars.typescript;15const { Playwright } = require('playwright');16const { OpenParenToken } = Playwright.internal.grammars.typescript;17const { Playwright } = require('playwright');18const { OpenParenToken } = Playwright.internal.grammars.typescript;19const { Playwright } = require('playwright');20const { OpenParenToken } = Playwright.internal.grammars.typescript;21const { Playwright } = require('playwright');22const { OpenParenToken } = Playwright.internal.grammars.typescript;23const { Playwright } = require('playwright');24const { OpenParenToken } = Playwright.internal.grammars.typescript;25const { Playwright }

Full Screen

Using AI Code Generation

copy

Full Screen

1const { OpenParenToken } = require('playwright/lib/protocol/types');2const { Playwright } = require('playwright/lib/server/playwright');3const { BrowserType } = require('playwright/lib/server/browserType');4const { Browser } = require('playwright/lib/server/browser');5const { Page } = require('playwright/lib/server/page');6const { OpenParenToken } = require('playwright/lib/protocol/types');7const { Playwright } = require('playwright/lib/server/playwright');8const { BrowserType } = require('playwright/lib/server/browserType');9const { Browser } = require('playwright/lib/server/browser');10const { Page } = require('playwright/lib/server/page');11const { OpenParenToken } = require('playwright/lib/protocol/types');12const { Playwright } = require('playwright/lib/server/playwright');13const { BrowserType } = require('playwright/lib/server/browserType');14const { Browser } = require('playwright/lib/server/browser');15const { Page } = require('playwright/lib/server/page');16const { OpenParenToken } = require('playwright/lib/protocol/types');17const { Playwright } = require('playwright/lib/server/playwright');18const { BrowserType } = require('playwright/lib/server/browserType');19const { Browser } = require('playwright/lib/server/browser');20const { Page } = require('playwright/lib/server/page');21const { OpenParenToken } = require('playwright/lib/protocol/types');22const { Playwright } = require('playwright/lib/server/playwright');23const { BrowserType } = require('playwright/lib/server/browserType');24const { Browser } = require('playwright/lib/server/browser');25const { Page } = require('playwright/lib/server/page');26const { OpenParenToken } = require('playwright/lib/protocol/types');27const { Playwright } = require('playwright/lib/server/playwright');28const { BrowserType } = require('playwright/lib/server/browserType');29const { Browser } = require('playwright/lib/server/browser');30const { Page } = require('play

Full Screen

Using AI Code Generation

copy

Full Screen

1const playwright = require('playwright');2const { OpenParenToken } = require('playwright/lib/server/inspector/protocol/protocol.js');3(async () => {4 for (const browserType of ['chromium']) {5 const browser = await playwright[browserType].launch();6 const context = await browser.newContext();7 const page = await context.newPage();8 await page.screenshot({ path: `example-${browserType}.png` });9 await browser.close();10 }11})();12const { OpenParenToken } = require('playwright/lib/server/inspector/protocol/protocol.js');13SyntaxError: Cannot use import statement outside a module14const playwright = require('playwright');15const { OpenParenToken } = require('playwright/lib/server/inspector/protocol/protocol.js');16(async () => {17 for (const browserType of ['chromium']) {18 const browser = await playwright[browserType].launch();19 const context = await browser.newContext();20 const page = await context.newPage();21 await page.screenshot({ path: `example-${browserType}.png` });22 await browser.close();23 }24})();25const { OpenParenToken } = require('playwright/lib/server/inspector/protocol/protocol.js');26SyntaxError: Cannot use import statement outside a module

Full Screen

Using AI Code Generation

copy

Full Screen

1const { Playwright } = require('playwright');2const playwright = new Playwright();3const { OpenParenToken } = playwright._internal;4console.log(OpenParenToken);5const { Playwright } = require('playwright');6const playwright = new Playwright();7const { OpenParenToken } = playwright._internal;8console.log(OpenParenToken);9const { Playwright } = require('playwright');10const playwright = new Playwright();11const { OpenParenToken } = playwright._internal;12console.log(OpenParenToken);13const { Playwright } = require('playwright');14const playwright = new Playwright();15const { OpenParenToken } = playwright._internal;16console.log(OpenParenToken);17const { Playwright } = require('playwright');18const playwright = new Playwright();19const { OpenParenToken } = playwright._internal;20console.log(OpenParenToken);21const { Playwright } = require('playwright');22const playwright = new Playwright();23const { OpenParenToken } = playwright._internal;24console.log(OpenParenToken);25const { Playwright } = require('playwright');26const playwright = new Playwright();27const { OpenParenToken } = playwright._internal;28console.log(OpenParenToken);29const { Playwright } = require('playwright');30const playwright = new Playwright();31const { OpenParenToken } = playwright._internal;32console.log(OpenParenToken);33const { Playwright } = require('playwright');34const playwright = new Playwright();35const { OpenParenToken } = playwright._internal;36console.log(OpenParenToken);37const { Playwright } = require('playwright');38const playwright = new Playwright();39const { OpenParenToken } = playwright._internal;40console.log(OpenParenToken);

Full Screen

Using AI Code Generation

copy

Full Screen

1const { OpenParenToken } = require('playwright/lib/server/frames');2const openParenToken = new OpenParenToken();3const page = await context.newPage();4await page.goto(url);5await page.evaluate(openParenToken);6const { OpenParenToken } = require('playwright');7const openParenToken = new OpenParenToken();8const page = await context.newPage();9await page.goto(url);10await page.evaluate(openParenToken);11const { OpenParenToken } = require('playwright/lib/server/frames');12const openParenToken = new OpenParenToken();13const page = await context.newPage();14await page.goto(url);15await page.evaluate(openParenToken);

Full Screen

Using AI Code Generation

copy

Full Screen

1const { openBrowser, goto, openBrowserArgs, closeBrowser, write, screenshot, openTab, closeTab, openPage, closePage } = require('taiko');2(async () => {3 try {4 await openBrowser(openBrowserArgs({ headless: false }));5 await write("Taiko", into(textBox("Search")));6 await screenshot({ path: 'screenshot.png' });7 await closePage();8 await closeTab();9 await closeBrowser();10 } catch (error) {11 console.error(error);12 } finally {13 }14})();15const { openBrowser, goto, openBrowserArgs, closeBrowser, write, screenshot, openTab, closeTab, openPage, closePage } = require('taiko');16(async () => {17 try {18 await openBrowser(openBrowserArgs({ headless: false }));19 await write("Taiko", into(textBox("Search")));20 await screenshot({ path: 'screenshot.png' });21 await closePage();22 await closeTab();23 await closeBrowser();24 } catch (error) {25 console.error(error);26 } finally {27 }28})();29const { openBrowser, goto, openBrowserArgs, closeBrowser, write, screenshot, openTab, closeTab, openPage, closePage } = require('taiko');30(async () => {31 try {32 await openBrowser(openBrowserArgs({ headless: false }));33 await write("Taiko", into(textBox("Search")));34 await screenshot({ path: 'screenshot.png' });35 await closePage();36 await closeTab();37 await closeBrowser();38 } catch (error) {39 console.error(error);40 } finally {41 }42})();43const { openBrowser, goto, openBrowserArgs, closeBrowser, write, screenshot

Full Screen

Using AI Code Generation

copy

Full Screen

1const { Playwright } = require('playwright');2const playwright = new Playwright();3const { chromium } = playwright;4const { OpenParenToken } = chromium._internalApi;5const { Page } = require('playwright');6const { ElementHandle } = require('playwright');7const { JSHandle } = require('playwright');8const { JSHandleDispatcher } = require('playwright/lib/server/domDispatcher');9const { JSHandleDispatcherImpl } = require('playwright/lib/server/domDispatcher');10const { Playwright } = require('playwright');11const playwright = new Playwright();12const { chromium } = playwright;13const { OpenParenToken } = chromium._internalApi;14const { Page } = require('playwright');15const { ElementHandle } = require('playwright');16const { JSHandle } = require('playwright');17const { JSHandleDispatcher } = require('playwright/lib/server/domDispatcher');18const { JSHandleDispatcherImpl } = require('playwright/lib/server/domDispatcher');19const { Playwright } = require('playwright');20const playwright = new Playwright();21const { chromium } = playwright;22const { OpenParenToken } = chromium._internalApi;23const { Page } = require('playwright');24const { ElementHandle } = require('playwright');25const { JSHandle } = require('playwright');26const { JSHandleDispatcher } = require('playwright/lib/server/domDispatcher');27const { JSHandleDispatcherImpl } = require('playwright/lib/server/domDispatcher');28const { Playwright } = require('playwright');29const playwright = new Playwright();30const { chromium } = playwright;31const { OpenParenToken } = chromium._internalApi;32const { Page } = require('playwright');33const { ElementHandle } = require('playwright');34const { JSHandle } = require('playwright');35const { JSHandleDispatcher } = require('playwright/lib/server/domDispatcher');36const { JSHandleDispatcherImpl } = require('playwright/lib/server/domDispatcher');37const { Playwright } = require('playwright');38const playwright = new Playwright();39const { chromium } = playwright;40const { OpenParenToken } = chromium

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2const { InternalAPI } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const openParenToken = await InternalAPI.openParenToken(page, 4, 4);8 const closeParenToken = openParenToken.findMatchingCloseParen();9 await page.selectText(closeParenToken.lineNumber, closeParenToken.columnNumber, openParenToken.lineNumber, openParenToken.columnNumber);10 await browser.close();11})();

Full Screen

Playwright tutorial

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.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Internal automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful