Best JavaScript code snippet using puppeteer
jsdocparser.js
Source:jsdocparser.js
...121};122// TODO: merge with processFragment?123var processObject = function(fragment) {124 var lines = fragment.split('\n');125 var obj = parseMember(lines.shift());126 currentObj = obj;127 processMetadata(obj, lines);128 obj.overloads = []; // Parameter overloads if Obj is a Function129 obj.constructors = []; // Constructor overloads if Obj is a Constructor Function130 obj.members = []; // Obj members131 obj.instanceMembers = []; // Instance members 132 obj.instanceEvents = []; // Instance events 133 obj.prototypeMembers = []; // Prototype members134 return obj;135};136var processInstanceMember = function(obj, frag) {137 frag = frag.replace(/^instance\.?/, '');138 var member = parseMember(frag);139 obj.instanceMembers.push(member);140 member.source = 'instance';141 return member;142};143var processInstanceEvent = function(obj, frag) {144 frag = frag.replace(/^event\./, '');145 var member = parseMember(frag);146 member.onname = member.onname || 'on' + member.name;147 obj.instanceEvents.push(member);148 member.source = 'event';149 return member;150};151var processPrototypeMember = function(obj, frag) {152 frag = frag.replace(/^prototype\./, '');153 var member = parseMember(frag);154 obj.prototypeMembers.push(member);155 member.source = 'prototype';156 return member;157};158var processConstructor = function(obj, frag) {159 frag = frag.replace(/^new /, '');160 var member = parseMember(frag);161 obj.constructors.push(member);162 member.isConstructor = true;163 return member;164};165var processOverload = function(obj, frag) {166 var member = parseMember(frag);167 obj.overloads.push(member);168 return member;169};170var processMember = function(obj, frag) {171 var member = parseMember(frag);172 obj.members.push(member);173 return member;174};175var processFragment = function(obj, desc) {176 var lines = desc.trim().split('\n');177 var first = lines.shift();178 var trailingBackslash = /\\\s*$/;179 while (trailingBackslash.test(first)) {180 first = first.replace(trailingBackslash, ' ');181 first += lines.shift();182 }183 if (first === '' && lines.length === 0) {184 return;185 }186 var member;187 if (/^instance(\.|\[)/.test(first)) {188 member = processInstanceMember(obj, first);189 }190 else if (/^event\./.test(first)) {191 member = processInstanceEvent(obj, first);192 }193 else if (/^prototype\./.test(first)) {194 member = processPrototypeMember(obj, first);195 }196 else if (/^new /.test(first)) {197 member = processConstructor(obj, first);198 }199 else if (new RegExp('^'+obj.name).test(first)) {200 member = processOverload(obj, first);201 }202 else if (/^Details:\s*$/.test(first)) {203 obj.details = processMarkup(obj, lines.join('\n').trim());204 return;205 }206 else {207 member = processMember(obj, first);208 }209 if (member) {210 processMetadata(member, lines);211 }212};213var processMetadata = function(member, lines) {214 var metadataProcessors = {215 description: processMarkup,216 };217 // Process 'Label:' lines 218 var prop = 'description';219 for (var i = 0; lines.length > 0 && i <= lines.length; i++) {220 var res;221 if (i === lines.length || (res = /^(\w+):\s*$/.exec(lines[i]))) {222 var value = lines.splice(0, i).join('\n').trim();223 if (prop in metadataProcessors) {224 value = metadataProcessors[prop](member, value);225 }226 member[prop] = value;227 lines.shift(); // pull off this line ('ReadOnly:')228 prop = res ? res[1].toLowerCase() : ''; // set the property value229 i = 0;230 }231 }232};233var createHtml = function(html) {234 html = replaceLinks(html);235 html = replaceCode(html);236 return html;237};238var createTag = function(html, obj, tag) {239 html = replaceLinks(html);240 html = replaceCode(html);241 return '<' + tag + '>' + html + '</' + tag + '>';242};243var createHtmlExample = function(code, obj) {244 obj.hasExample = true;245 return template.render('htmlexample', { code: code, objectName: currentObj.name, propertyName: obj.name });246};247var createExample = function(code, obj) {248 obj.hasExample = true;249 return template.render('example', { code: code, objectName: currentObj.name, propertyName: obj.name });250};251var tags = {252 'html': createHtml,253 'h3': createTag,254 'p': createTag,255 'em': createTag,256 'code': createTag,257 'htmlexample': createHtmlExample,258 'example': createExample,259};260var processMarkup = function(obj, desc) {261 var res = '';262 var parts;263 var rest = desc;264 var regexp = RegExp('([\\s\\S]*?)\\<(' + Object.keys(tags).join('|') + ')\\>([\\s\\S]*?)\\<\\/\\2\\>([\\s\\S]*)', 'm');265 while (parts = rest.match(regexp)) {266 var before = parts[1];267 var tag = parts[2];268 var content = parts[3];269 var converter = tags[tag];270 res += linkify(before);271 res += converter(content, obj, tag); 272 rest = parts[4];273 }274 res += linkify(rest);275 return res;276};277var htmlEscape = function(str) {278 str = str.replace(/&/g, '&');279 str = str.replace(/</g, '<');280 str = str.replace(/>/g, '>');281 return str;282};283var replaceLinks = function(str) {284 return str.replace(/%%(.*?)(?:\|(.*?))%%/g, function(str, p1, p2) {285 p2 = p2 || p1;286 return "<a href='" + p1 + "'>" + p2 + "</a>";287 });288};289var replaceCode = function(str) {290 return str.replace(/\*\*(.*?)\*\*/gm, function(str, p1) {291 return "<code>" + p1 + "</code>";292 });293};294var linkify = function(description) {295 var res = description;296 res = res.replace(/\n/g, ' ');297 res = htmlEscape(res);298 res = replaceLinks(res);299 res = replaceCode(res);300 return res;301};302var parseMember = function(member) {303 member = member.trim();304 if (member === '...') {305 return { name: '...'};306 }307 if (!member.match(/:/)) {308 var res;309 // See if member has a <type>310 if (res = member.match(/\s*(\w*)\s*\<(.*)\>/)) {311 name = res[1];312 return { name: name,313 templates: parseParamList(res[2]) };314 }315 return member;316 }317 var split = -1;318 var depth = 0;319 var defaultValueSplit = -1; 320 var inComment = false;321 var parenStack = [];322 var parens = [['(', ')'],323 ['{', '}'],324 ['[', ']'],325 ['<', '>']];326 for (var i = 0; i < member.length; i++) {327 if (inComment) {328 if (member[i] === '*' && member[i + 1] === '/') {329 inComment = false;330 }331 continue;332 }333 // See if the character is one of the parens334 for (var j = 0; j < parens.length; j++) {335 var pair = parens[j];336 // If it is a left paren, push it on the stack337 if (member[i] === pair[0]) {338 parenStack.push(member[i]);339 }340 else if (member[i] === pair[1]) {341 // If it is a right paren, see if it matches the top paren of on the stack342 if (!parenStack.length) {343 throw Error('empty paren stack');344 }345 if (parenStack[parenStack.length - 1] !== pair[0]) {346 throw Error('Mismatched parens. Expected: \'' + pair[0] + '\' but got \'' + parenStack[parenStack.length - 1] + '\'. (processing ' + member + ')');347 }348 parenStack.pop();349 }350 }351 if (member[i] === '/' && member[i + 1] === '*') inComment = true;352 if (member[i] === '=' && parenStack.length === 0) {353 defaultValueSplit = i;354 }355 if (member[i] === ':' && parenStack.length === 0) {356 split = i;357 break;358 }359 }360 var name;361 var defaultValue; 362 if (defaultValueSplit !== -1) {363 name = member.substring(0, defaultValueSplit).trim();364 defaultValue = member.substring(defaultValueSplit + 1, split).trim();365 }366 else if (split === -1) {367 var res = member.match(/\{(.*)\}/);368 if (!res) throw Error('parse error for member: ' + member);369 return { type: 'Object',370 properties: parseParamList(res[1])};371 }372 else {373 if (split === -1) throw Error('parse error');374 name = member.substring(0, split).trim();375 }376 var type = member.substring(split + 1).trim();377 var description;378 var res;379 if (type.length > 2 && type.lastIndexOf('*/') === type.length - 2) {380 var commentStartIndex = type.lastIndexOf('/*');381 description = processMarkup(currentObj, type.substring(commentStartIndex + 2, type.length - 2).trim());382 type = type.substring(0, commentStartIndex).trim();383 }384 // Process Indexer [Symbol]385 if (res = name.match(/^\s*\[\s*(\w*\.\w*)\s*\]/)) {386 return { parameters: [{ name: res[1] }],387 type: 'Indexer',388 returnType: parseMember(type),389 description: description };390 }391 // Process Indexer392 if (res = name.match(/^\s*\[(.*)\]/)) {393 return { parameters: parseParamList(res[1]),394 type: 'Indexer',395 returnType: parseMember(type),396 description: description };397 }398 // Process method399 if (res = name.match(/^\s*(\w*)\s*\((.*)\)/)) {400 name = res[1];401 return { name: name,402 parameters: parseParamList(res[2]),403 type: 'Function',404 returnType: parseMember(type),405 defaultValue: defaultValue,406 description: description };407 }408 if (res = type.match(/\s*\{(.*)\}/)) {409 return { name: name,410 type: 'Object',411 properties: parseParamList(res[1]),412 description: description };413 }414 return { name: name,415 type: parseMember(type),416 defaultValue: defaultValue,417 description: description };418};419//jsdoc.parseMember('a(b : c, [..., [f : g]]) : h');420var parseParamList = function(params) {421 var split = -1;422 var paramsList = [];423 var depth = 0;424 var optionalDepth = 0;425 var inQuote = false;426 var inComment = false;427 for (var i = 0; i < params.length; i++) {428 if (inComment) {429 if (params[i] === '*' && params[i + 1] === '/') inComment = false;430 continue;431 }432 if (params[i] === '(') depth++;433 if (params[i] === ')') depth--;434 if (params[i] === '{') depth++;435 if (params[i] === '}') depth--;436 if (params[i] === '<') depth++;437 if (params[i] === '>') depth--;438 if (params[i] === '/' && params[i + 1] === '*') inComment = true;439 if (params[i] === '\'') inQuote=!inQuote; 440 if (params[i] === '[') {441 optionalDepth++;442 split = i;443 }444 //if (params[i] === ']') optionalDepth--;445 if ((params[i] === ',' || params[i] === ']') && depth === 0 && !inQuote) {446 var param = params.substring(split + 1, i);447 448 // if there are no 'word' characters, ignore this substring. 449 // This can happen if you have ],450 if (param.match(/\w/) || param.match(/\.\.\./)) {451 paramsList.push({param: param, optionalDepth: optionalDepth});452 }453 split = i;454 }455 if (params[i] === ']') optionalDepth--;456 }457 // Add the last one458 var param = params.substring(split + 1);459 if (param.match(/\w/) || param.match(/\.\.\./)) {460 paramsList.push({param: param, optionalDepth: optionalDepth});461 }462 463 params = paramsList.map(function(m) { 464 m.param = m.param.replace(/\[/g, '');465 m.param = m.param.replace(/\]/g, '');466 var member = parseMember(m.param);467 if (typeof member !== 'string') {468 // When parsing templates (like Array<String>), the param may not have a469 // name and be of type string, which can't have properties set on it.470 member.optionalDepth = m.optionalDepth;471 }472 return member; 473 });474 // Group the params475 var grouped = [[]];476 while (params.length) {477 var param = params.shift();478 if (param.optionalDepth > grouped.length - 1) {479 grouped.unshift([]);480 }...
parseObject-test.js
Source:parseObject-test.js
1const R = require('ramda');2const { Fury } = require('@apielements/core');3const { expect } = require('../chai');4const parseObject = require('../../../lib/parser/parseObject');5const { minim: namespace } = new Fury();6const Context = require('../../../lib/context');7describe('#parseObject', () => {8 let name;9 let context;10 let object;11 beforeEach(() => {12 name = 'Example Object';13 context = new Context(namespace);14 object = new namespace.elements.Object({15 name: 'Doe',16 message: 'Hello',17 });18 object.attributes.set('sourceMap', [19 new namespace.elements.SourceMap([[0, 10]]),20 ]);21 });22 it('provides warning when given element is non-object', () => {23 const element = new namespace.elements.String();24 const parseMember = member => member;25 const parseResult = parseObject(context, name, parseMember)(element);26 expect(parseResult).to.contain.warning("'Example Object' is not an object");27 });28 it('can parse an object when the transform returns a member element', () => {29 const parseMember = member => member;30 const parseResult = parseObject(context, name, parseMember)(object);31 expect(parseResult.length).to.equal(1);32 expect(parseResult.get(0)).to.be.instanceof(namespace.elements.Object);33 expect(parseResult.get(0).length).to.equal(2);34 expect(parseResult.get(0).get('name').toValue()).to.equal('Doe');35 expect(parseResult.get(0).get('message').toValue()).to.equal('Hello');36 });37 it('can parse an object when the transform returns a value to be wrapped in a member', () => {38 const parseMember = member => member.value;39 const parseResult = parseObject(context, name, parseMember)(object);40 expect(parseResult.length).to.equal(1);41 expect(parseResult.get(0)).to.be.instanceof(namespace.elements.Object);42 expect(parseResult.get(0).length).to.equal(2);43 expect(parseResult.get(0).get('name').toValue()).to.equal('Doe');44 expect(parseResult.get(0).get('message').toValue()).to.equal('Hello');45 });46 it('can parse an object when the transform returns a parse result', () => {47 const parseMember = member => new namespace.elements.ParseResult([member]);48 const parseResult = parseObject(context, name, parseMember)(object);49 expect(parseResult.length).to.equal(1);50 expect(parseResult.get(0)).to.be.instanceof(namespace.elements.Object);51 expect(parseResult.get(0).length).to.equal(2);52 expect(parseResult.get(0).get('name').toValue()).to.equal('Doe');53 expect(parseResult.get(0).get('message').toValue()).to.equal('Hello');54 });55 it('can parse an object when the transform returns a parse result containing a value to be wrapped in a member', () => {56 const parseMember = member => new namespace.elements.ParseResult([member.value]);57 const parseResult = parseObject(context, name, parseMember)(object);58 expect(parseResult.length).to.equal(1);59 expect(parseResult.get(0)).to.be.instanceof(namespace.elements.Object);60 expect(parseResult.get(0).length).to.equal(2);61 expect(parseResult.get(0).get('name').toValue()).to.equal('Doe');62 expect(parseResult.get(0).get('message').toValue()).to.equal('Hello');63 });64 it('can parse an object when the transform returns a parse result including a warning annotation', () => {65 const parseMember = (member) => {66 const warning = new namespace.elements.Annotation(67 `${member.key.toValue()} warning`,68 { classes: ['warning'] }69 );70 return new namespace.elements.ParseResult([member, warning]);71 };72 const parseResult = parseObject(context, name, parseMember)(object);73 expect(parseResult.length).to.equal(3);74 expect(parseResult.get(0)).to.be.instanceof(namespace.elements.Object);75 expect(parseResult.get(0).length).to.equal(2);76 expect(parseResult.get(0).get('name').toValue()).to.equal('Doe');77 expect(parseResult.get(0).get('message').toValue()).to.equal('Hello');78 expect(parseResult.warnings.length).to.equal(2);79 expect(parseResult.warnings.get(0).toValue()).to.equal('name warning');80 expect(parseResult.warnings.get(1).toValue()).to.equal('message warning');81 });82 it('discards any members when the transform returns a parse result which includes an error', () => {83 const parseMember = (member) => {84 const warning = new namespace.elements.Annotation(85 `${member.key.toValue()} error`,86 { classes: ['error'] }87 );88 return new namespace.elements.ParseResult([member, warning]);89 };90 const parseResult = parseObject(context, name, parseMember)(object);91 expect(parseResult.length).to.equal(2);92 expect(parseResult.errors.get(0).toValue()).to.equal('name error');93 expect(parseResult.errors.get(1).toValue()).to.equal('message error');94 });95 it('discards any members when the transform returns a parse result which includes a warning and no value', () => {96 const parseMember = (member) => {97 const warning = new namespace.elements.Annotation(98 `${member.key.toValue()} warning`,99 { classes: ['warning'] }100 );101 return new namespace.elements.ParseResult([warning]);102 };103 const parseResult = parseObject(context, name, parseMember)(object);104 expect(parseResult.length).to.equal(3);105 expect(parseResult.get(0)).to.be.instanceof(namespace.elements.Object);106 expect(parseResult.get(0).isEmpty).to.be.true;107 expect(parseResult.warnings.get(0).toValue()).to.equal('name warning');108 expect(parseResult.warnings.get(1).toValue()).to.equal('message warning');109 });110 describe('required keys', () => {111 it('validates that the object contains any required keys', () => {112 const parseResult = parseObject(context, name, R.T, ['name', 'required1', 'required2'])(object);113 expect(parseResult.length).to.equal(2);114 expect(parseResult.errors.toValue()).to.deep.equal([115 "'Example Object' is missing required property 'required1'",116 "'Example Object' is missing required property 'required2'",117 ]);118 // assert errors can be frozen (we're testing that the source map119 // for object was cloned instead of referenced)120 parseResult.freeze();121 expect(parseResult.errors.get(0)).to.have.sourceMap([[0, 10]]);122 expect(parseResult.errors.get(1)).to.have.sourceMap([[0, 10]]);123 });124 it('fails object parsing when member parse cannot parse required key', () => {125 const parseMember = (member) => {126 const warning = new namespace.elements.Annotation(127 `${member.key.toValue()} warning`,128 { classes: ['warning'] }129 );130 return new namespace.elements.ParseResult([warning]);131 };132 const parseResult = parseObject(context, name, parseMember, ['name'])(object);133 expect(parseResult.length).to.equal(2);134 expect(parseResult.annotations.toValue()).to.deep.equal([135 'name warning',136 'message warning',137 ]);138 });139 it('can parse object with required keys', () => {140 const parseResult = parseObject(context, name, R.T, ['name'])(object);141 expect(parseResult.length).to.equal(1);142 expect(parseResult.get(0)).to.be.instanceof(namespace.elements.Object);143 });144 });...
svgDraw.spec.js
Source:svgDraw.spec.js
2describe('class member Renderer, ', function () {3 describe('when parsing text to build method display string', function () {4 it('should handle simple method declaration', function () {5 const str = 'foo()';6 let actual = svgDraw.parseMember(str);7 expect(actual.displayText).toBe('foo()');8 expect(actual.cssStyle).toBe('');9 });10 it('should handle public visibility', function () {11 const str = '+foo()';12 let actual = svgDraw.parseMember(str);13 expect(actual.displayText).toBe('+foo()');14 expect(actual.cssStyle).toBe('');15 });16 it('should handle private visibility', function () {17 const str = '-foo()';18 let actual = svgDraw.parseMember(str);19 expect(actual.displayText).toBe('-foo()');20 expect(actual.cssStyle).toBe('');21 });22 it('should handle protected visibility', function () {23 const str = '#foo()';24 let actual = svgDraw.parseMember(str);25 expect(actual.displayText).toBe('#foo()');26 expect(actual.cssStyle).toBe('');27 });28 it('should handle package/internal visibility', function () {29 const str = '~foo()';30 let actual = svgDraw.parseMember(str);31 expect(actual.displayText).toBe('~foo()');32 expect(actual.cssStyle).toBe('');33 });34 it('should ignore unknown character for visibility', function () {35 const str = '!foo()';36 let actual = svgDraw.parseMember(str);37 expect(actual.displayText).toBe('foo()');38 expect(actual.cssStyle).toBe('');39 });40 it('should handle abstract method classifier', function () {41 const str = 'foo()*';42 let actual = svgDraw.parseMember(str);43 expect(actual.displayText).toBe('foo()');44 expect(actual.cssStyle).toBe('font-style:italic;');45 });46 it('should handle static method classifier', function () {47 const str = 'foo()$';48 let actual = svgDraw.parseMember(str);49 expect(actual.displayText).toBe('foo()');50 expect(actual.cssStyle).toBe('text-decoration:underline;');51 });52 it('should ignore unknown character for classifier', function () {53 const str = 'foo()!';54 let actual = svgDraw.parseMember(str);55 expect(actual.displayText).toBe('foo()');56 expect(actual.cssStyle).toBe('');57 });58 it('should handle simple method declaration with parameters', function () {59 const str = 'foo(int id)';60 let actual = svgDraw.parseMember(str);61 expect(actual.displayText).toBe('foo(int id)');62 expect(actual.cssStyle).toBe('');63 });64 it('should handle simple method declaration with multiple parameters', function () {65 const str = 'foo(int id, object thing)';66 let actual = svgDraw.parseMember(str);67 expect(actual.displayText).toBe('foo(int id, object thing)');68 expect(actual.cssStyle).toBe('');69 });70 it('should handle simple method declaration with single item in parameters', function () {71 const str = 'foo(id)';72 let actual = svgDraw.parseMember(str);73 expect(actual.displayText).toBe('foo(id)');74 expect(actual.cssStyle).toBe('');75 });76 it('should handle simple method declaration with single item in parameters with extra spaces', function () {77 const str = ' foo ( id) ';78 let actual = svgDraw.parseMember(str);79 expect(actual.displayText).toBe('foo(id)');80 expect(actual.cssStyle).toBe('');81 });82 it('should handle method declaration with return value', function () {83 const str = 'foo(id) int';84 let actual = svgDraw.parseMember(str);85 expect(actual.displayText).toBe('foo(id) : int');86 expect(actual.cssStyle).toBe('');87 });88 it('should handle method declaration with generic return value', function () {89 const str = 'foo(id) List~int~';90 let actual = svgDraw.parseMember(str);91 expect(actual.displayText).toBe('foo(id) : List<int>');92 expect(actual.cssStyle).toBe('');93 });94 it('should handle method declaration with generic parameter', function () {95 const str = 'foo(List~int~)';96 let actual = svgDraw.parseMember(str);97 expect(actual.displayText).toBe('foo(List<int>)');98 expect(actual.cssStyle).toBe('');99 });100 it('should handle method declaration with all possible markup', function () {101 const str = '+foo ( List~int~ ids )* List~Item~';102 let actual = svgDraw.parseMember(str);103 expect(actual.displayText).toBe('+foo(List<int> ids) : List<Item>');104 expect(actual.cssStyle).toBe('font-style:italic;');105 });106 });107 describe('when parsing text to build field display string', function () {108 it('should handle simple field declaration', function () {109 const str = 'int[] ids';110 let actual = svgDraw.parseMember(str);111 expect(actual.displayText).toBe('int[] ids');112 expect(actual.cssStyle).toBe('');113 });114 it('should handle field declaration with generic type', function () {115 const str = 'List~int~ ids';116 let actual = svgDraw.parseMember(str);117 expect(actual.displayText).toBe('List<int> ids');118 expect(actual.cssStyle).toBe('');119 });120 it('should handle static field classifier', function () {121 const str = 'String foo$';122 let actual = svgDraw.parseMember(str);123 expect(actual.displayText).toBe('String foo');124 expect(actual.cssStyle).toBe('text-decoration:underline;');125 });126 });...
parser.js
Source:parser.js
...49 if (xmlName == '$') {50 ALY.util.each.call(this, value, function (attrName, attrValue) {51 if (rules[attrName]) {52 var rule = rules[attrName];53 data[rule.name || xmlName] = this.parseMember([attrValue], rule);54 }55 });56 } else {57 var rule = rules[xmlName] || {};58 data[rule.name || xmlName] = this.parseMember(value, rule);59 }60 });61 return data;62 },63 parseMap: function parseMap(map, rules) {64 var data = {};65 var keyRules = rules.keys || {};66 var valueRules = rules.members || {};67 var keyName = keyRules.name || 'key';68 var valueName = valueRules.name || 'value';69 if (!rules.flattened) {70 map = map[0].entry;71 }72 ALY.util.arrayEach.call(this, map, function (entry) {73 var value = this.parseMember(entry[valueName], valueRules);74 data[entry[keyName][0]] = value;75 });76 return data;77 },78 parseList: function parseList(list, rules) {79 var data = [];80 var memberRules = rules.members || {};81 var memberName = memberRules.name || 'member';82 if (rules.flattened) {83 ALY.util.arrayEach.call(this, list, function (value) {84 data.push(this.parseMember([value], memberRules));85 });86 } else {87 ALY.util.arrayEach.call(this, list, function (member) {88 ALY.util.arrayEach.call(this, member[memberName], function (value) {89 data.push(this.parseMember([value], memberRules));90 });91 });92 }93 return data;94 },95 parseMember: function parseMember(values, rules) {96 /*jshint maxcomplexity:20*/97 if (values[0] === null) {98 if (rules.type === 'structure') return {};99 if (rules.type === 'list') return [];100 if (rules.type === 'map') return {};101 return null;102 }103 if (values[0]['$'] && values[0]['$'].encoding == 'base64') {104 return ALY.util.base64.decode(values[0]['_']);105 }106 if (!rules.type) {107 if (typeof values[0] === 'string') {108 rules.type = 'string';109 } else if (values[0]['_']) {...
collect-inputs-outputs.js
Source:collect-inputs-outputs.js
...16 if (doc.members[i].decorators && doc.members[i].decorators.length) {17 decoratorLoop:18 for (var ii in doc.members[i].decorators) {19 if (doc.members[i].decorators[ii].name == 'Input') {20 inputs.push(parseMember(doc.members[i]));21 continue memberLoop;22 }23 if (doc.members[i].decorators[ii].name == 'Output') {24 outputs.push(parseMember(doc.members[i]));25 continue memberLoop;26 }27 }28 // not an input or output, must be a plain member29 members.push(doc.members[i]);30 } else {31 members.push(doc.members[i]);32 };33 }34 // update doc with pruned members list and add inputs and outputs35 doc.members = members;36 doc.inputs = inputs;37 doc.outputs = outputs;38 }39 function parseMember(member) {40 member.type = member.content.substring(41 member.content.indexOf('{') + 1,42 member.content.indexOf('}')43 );44 member.description = member.content.substring(45 member.content.indexOf('}') + 1,46 member.content.length47 );48 return member;49 }50 });51 }52 };53};
actionChecker.js
Source:actionChecker.js
...15 throw new AppError(16 'Missing Permissions',17 `I require \`${permission}\` permission to perform that action.`,18 );19 const member = await parseMember(user.id, guild).catch(() => {});20 if (!member) {21 if (options.outsideGuild) return true;22 throw new AppError('Member Not Found', `That member is not in this server.`);23 }24 const botPermission = getHighestRole(botMember.roles.cache).rawPosition;25 const memberPermission = getHighestRole(member.roles.cache).rawPosition;26 if (memberPermission >= botPermission)27 throw new AppError(28 'Invalid Member',29 "That member's role position is greater or higher than mine!",30 );31 if (guild.ownerID === member.id)32 throw new AppError(33 'Invalid Member',...
validateModeration.js
Source:validateModeration.js
...10 */11exports.validateModeration = async (moderator, recipient, guild) => {12 if (moderator.id === recipient.id)13 throw new AppError('Stop That', 'Cannot use this command on yourself.');14 const recipientMember = await parseMember(recipient.id, guild).catch(() => {});15 if (!recipientMember) return;16 const moderatorMember = await parseMember(moderator.id, guild);17 const highestModRole = getHighestRole(moderatorMember.roles.cache);18 const highestRecipientRole = getHighestRole(recipientMember.roles.cache);19 if (highestModRole.rawPosition <= highestRecipientRole.rawPosition)20 throw new AppError(21 'Invalid Recipient',22 'Cannot use this command on a member with an equal or higher role position.',23 );24 return true;...
Using AI Code Generation
1const puppeteer = require('puppeteer');2const fs = require('fs');3(async () => {4 const browser = await puppeteer.launch();5 const page = await browser.newPage();6 await page.screenshot({path: 'google.png'});7 await browser.close();8})();9const puppeteer = require('puppeteer');10const fs = require('fs');11(async () => {12 const browser = await puppeteer.launch();13 const page = await browser.newPage();14 await page.screenshot({path: 'google.png'});15 await browser.close();16})();
Using AI Code Generation
1const puppeteer = require('puppeteer');2const fs = require('fs');3const { parseMember } = require('./parseMember.js');4(async () => {5 const browser = await puppeteer.launch();6 const page = await browser.newPage();7 const html = await page.content();8 const member = parseMember(html);9 fs.writeFileSync('member.json', JSON.stringify(member, null, 2));10 await browser.close();11})();12const { JSDOM } = require('jsdom');13const parseMember = html => {14 const dom = new JSDOM(html);15 const { document } = dom.window;16 const name = document.querySelector('.pv-top-card-section__name').textContent;17 const headline = document.querySelector('.pv-top-card-section__headline').textContent;18 const location = document.querySelector('.pv-top-card-section__location').textContent;19 const connections = document.querySelector('.pv-top-card-section__connections').textContent;20 const about = document.querySelector('.pv-about__summary-text').textContent;21 const experience = [...document.querySelectorAll('.pv-position-entity')].map(el => {22 const title = el.querySelector('.pv-entity__summary-info-v2 h3').textContent;23 const company = el.querySelector('.pv-entity__summary-info-v2 .pv-entity__secondary-title').textContent;24 const dateRange = el.querySelector('.pv-entity__date-range span:last-child').textContent;25 const location = el.querySelector('.pv-entity__location span:last-child').textContent;26 const description = el.querySelector('.pv-entity__description').textContent;27 return { title, company, dateRange, location, description };28 });29 const education = [...document.querySelectorAll('.pv-education-entity')].map(el => {30 const school = el.querySelector('.pv-entity__school-name').textContent;31 const degree = el.querySelector('.pv-entity__degree-name span:last-child').textContent;32 const fieldOfStudy = el.querySelector('.pv-entity__fos span:last-child').textContent;33 const dateRange = el.querySelector('.pv-entity__dates span:last-child').textContent;34 return { school, degree, fieldOfStudy, dateRange };35 });36 const skills = [...document.querySelectorAll('.pv-skill-entity')].map(el => {37 const name = el.querySelector('.pv-skill-entity__skill-name
Using AI Code Generation
1const puppeteerPool = require('puppeteer-pool');2const pool = puppeteerPool.default({3 puppeteerArgs: {4 }5});6async function parseMember() {7 try {8 const browser = await pool.use();9 const page = await browser.newPage();10 await page.screenshot({path: 'google.png'});11 await page.close();12 } catch (err) {13 console.error(err);14 }15}16parseMember();17const puppeteerPool = require('puppeteer-pool');18const pool = puppeteerPool.default({19 puppeteerArgs: {20 }21});22async function parseMember() {23 try {24 const browser = await pool.use();25 const page = await browser.newPage();26 await page.screenshot({path: 'google.png'});27 await page.close();28 } catch (err) {29 console.error(err);30 }31}32parseMember();33const puppeteerPool = require('puppeteer-pool');34const pool = puppeteerPool.default({35 puppeteerArgs: {
Using AI Code Generation
1const puppeteer = require('puppeteer');2const fs = require('fs');3(async () => {4 const browser = await puppeteer.launch({5 });6 const page = await browser.newPage();7 await page.goto(url, { waitUntil: 'networkidle2' });8 const result = await page.evaluate(() => {9 const tds = Array.from(document.querySelectorAll('table tr td'));10 return tds.map(td => td.innerHTML);11 });12 fs.writeFile('test.json', JSON.stringify(result), function(err) {13 if (err) throw err;14 console.log('Saved!');15 });16 await browser.close();17})();
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!