Best JavaScript code snippet using playwright-internal
MudScriptTranspiler.js
Source:MudScriptTranspiler.js
...282 * @param {NodeType} e The current node283 * @param {number} depth The stack depth284 * @returns {string} The element as source code.285 */286function parseElement(op, e, depth) {287 let ret = '';288 if (e) {289 if (e.start > op.pos) {290 ret += op.source.slice(op.pos, e.start);291 op.pos = e.start;292 }293 switch (e.type) {294 case 'ArrayExpression':295 e.elements.forEach(_ => ret += parseElement(op, _, depth + 1));296 break;297298 case 'ArrayPattern':299 e.elements.forEach(_ => ret += parseElement(op, _, depth + 1));300 break;301302 case 'ArrowFunctionExpression':303 {304 let funcName = e.async ?305 `async ${op.getCallerId() || '(anonymous)'}(() => {})` :306 `${op.getCallerId() || '(anonymous)'}(() => {})`;307 e.params.forEach(_ => ret += parseElement(op, _, depth + 1));308 ret += op.readUntil(e.body.start);309 if (e.body.type === 'BlockStatement') {310 ret += `{ let __mec = __bfc(${op.thisParameter}, false, '${funcName}', __FILE__, ${e.async}); try `;311 ret += parseElement(op, e.body);312 ret += ` finally { __efc(__mec, '${funcName}'); } }`;313 }314 else if (e.body.type === 'MemberExpression') {315 ret += `{ let __mec = __bfc(${op.thisParameter}, false, '${funcName}', __FILE__, ${e.async}); try { return `;316 ret += parseElement(op, e.body);317 ret += `; } finally { __efc(__mec, '${funcName}'); } }`;318 }319 else {320 ret += `{ let __mec = __bfc(${op.thisParameter}, false, '${funcName}', __FILE__, ${e.async}); try { return (`;321 ret += parseElement(op, e.body);322 ret += `); } finally { __efc(__mec, '${funcName}'); } }`;323 }324 }325 break; 326327 case 'AssignmentExpression':328 ret += parseElement(op, e.left, depth + 1);329 ret += parseElement(op, e.right, depth + 1);330 break;331332 case 'AssignmentPattern':333 ret += parseElement(op, e.left, depth + 1);334 ret += parseElement(op, e.right, depth + 1);335 break;336337 case 'AwaitExpression':338 {339 // Step 1: Suspend context,340 // Step 2: Make the async call,341 // Step 3: Restore the context and continue... sounds simple enough...342343 // ret += `await __mec.awaitAsync('${e.idType || ''}', `;344 // ret += parseElement(op, e.argument, depth + 1).slice(5);345 // ret += ')';346347348 //ret += '(async () => { let __err, __ctx = __mec.asyncBegin(); try { ';349 //ret += '__ctx.asyncResult = ' + parseElement(op, e.argument, depth + 1) ;350 //ret += '.catch(e => { _err = e; }); if(__err) throw __err; return __ctx.asncResult; ';351 //ret += ' } finally { __ctx.asyncRestore(); } })()';352353 ret += parseElement(op, e.argument, depth + 1);354 //ret += '.always(() => __ctx.restore())';355 }356 break;357358 case 'BinaryExpression':359 ret += parseElement(op, e.left, depth + 1);360 ret += parseElement(op, e.right, depth + 1);361 break;362363 case 'BlockStatement':364 e.body.forEach(_ => ret += parseElement(op, _, depth + 1));365 break;366367 case 'BreakStatement':368 ret += op.source.slice(e.start, e.end);369 op.pos = e.end;370 break;371372 case 'CallExpression':373 {374 let writeCallee = true,375 isCallout = false,376 object = false,377 propName = false,378 callee = false;379380 if (e.callee.type === 'MemberExpression') {381 object = parseElement(op, e.callee.object, depth + 1);382 propName = parseElement(op, e.callee.property, depth + 1);383 callee = object + propName;384 op.addCallerId(propName.slice(1));385 }386 else if (e.callee.type === 'Identifier') {387 propName = callee = parseElement(op, e.callee, depth + 1);388 if (SettersGetters.indexOf(propName) > -1) {389 let parts = (op.thisMethod || '').split(/\s+/), prop = parts.pop();390391 if (!op.thisClass)392 throw new Error(`The ${propName} operator can only be used inside a class.`);393394 else if (parts.indexOf('get') === -1 && parts.indexOf('set') === -1)395 throw new Error(`The ${propName} operator cannot be used within non getter/setter '${op.thismethod || op.method || 'unknown'}'`);396397 // set.call(this, ... args)398 ret += propName;399 ret += `.call(this, ${op.thisClass}, '${prop}'`400 if (e.arguments.length > 0) {401 ret += ', ';402 op.readUntil(e.arguments[0].start);403 e.arguments.forEach(_ => ret += parseElement(op, _, depth + 1));404 }405 op.readUntil(e.end);406 ret += ')';407 isCallout = true;408 writeCallee = false;409 }410 else if (propName === '$include') {411 let fileSpec = e.arguments.map(a => {412 if (a.type !== 'Literal')413 throw new Error(`Illegal include statement; Cannot include type ${a.type} (must be Literal)`);414 return a.value;415 });416417 if (fileSpec.length === 0)418 throw new Error('Illegal include statement; Must specify at least one file.');419420 ret += `/* included ${fileSpec.join(', ')} */`;421 op.include(fileSpec);422 writeCallee = false;423 isCallout = true;424 op.pos = e.end;425 }426 else if (propName === 'create' || propName === 'createAsync') {427 ret += callee;428 ret += `('${op.filename}'`;429 if (e.arguments.length) {430 ret += ', ';431 let foobar = op.readUntil('(');432 }433 writeCallee = false;434 }435 else436 op.addCallerId(propName);437 }438 else if (e.callee.type === 'Super') {439 propName = callee = parseElement(op, e.callee, depth + 1);440 op.addCallerId(propName);441 }442 else if (e.callee.type === 'FunctionExpression') {443 propName = callee = parseElement(op, e.callee, depth + 1);444 op.addCallerId('function()');445 }446 else if (e.callee.type === 'ArrowFunctionExpression') {447 propName = callee = parseElement(op, e.callee, depth + 1);448 op.addCallerId('() => {}');449 }450 else if (e.callee.type === 'CallExpression') {451 ret += parseElement(op, e.callee.callee, depth + 1);452 e.callee.arguments.forEach(_ => ret += parseElement(op, _, depth + 1));453 writeCallee = false;454 ret += '';455 }456 else {457 throw new Error(`Unexpected callee type ${e.callee.type}`);458 }459 if (op.allowLiteralCallouts) {460 if (e.callee && e.callee.type === 'MemberExpression') {461 let objectType = e.callee.object.type;462 if (objectType === 'Literal' || objectType === 'MemberExpression') {463 let isString = false;464 try {465 isString = typeof eval(object) === 'string';466 }467 catch (e) { /* do nothing */ }468469 if (typeof String.prototype[propName] !== 'function') {470 let args = '';471 ret += `typeof ${object} === 'string' && typeof String.prototype${propName} !== 'function' && unwrap(efuns.loadObjectSync(${object}), o => o${propName}`;472 e.arguments.forEach(_ => args += parseElement(op, _, depth + 1));473 args += op.source.slice(op.pos, e.end);474 ret += `${args}) || (() => ${object}${propName}${args})()`; // Close out the wrap475 isCallout = true;476 op.pos = e.end;477 } else {478 ret += object;479 ret += propName;480 }481 writeCallee = false;482 }483 }484 }485 if (writeCallee)486 ret += callee;487 if (!isCallout)488 e.arguments.forEach(_ => ret += parseElement(op, _, depth + 1));489 }490 break;491492 case 'CatchClause':493 ret += parseElement(op, e.param, depth + 1);494 addRuntimeAssert(e, `__cat(${e.param.name}); `);495 ret += parseElement(op, e.body, depth + 1);496 break;497498 case 'ClassBody':499 e.body.forEach(_ => ret += parseElement(op, _, depth + 1));500 op.thisClass = false;501 break;502503 case 'ClassDeclaration':504 op.thisClass = e.id.name;505 ret += parseElement(op, e.id, depth + 1);506 if (e.superClass)507 ret += parseElement(op, e.superClass, depth + 1);508 else if (op.injectedSuperClass)509 ret += ` extends ${op.injectedSuperClass}`;510 ret += parseElement(op, e.body, depth + 1);511 ret += ` ${e.id.name}.prototype.baseName = '${op.getBaseName(e.id.name)}'; __dmt("${op.filename}", ${e.id.name}); `;512 break;513514 case 'ConditionalExpression':515 ret += parseElement(op, e.test, depth + 1);516 ret += parseElement(op, e.consequent, depth + 1);517 ret += parseElement(op, e.alternate, depth + 1);518 break;519520 case 'ContinueStatement':521 ret += op.source.slice(e.start, e.end);522 op.pos = e.end;523 break;524525 case 'DebuggerStatement':526 // TODO: Add config check to see if debugger is allowed...527 ret += op.source.slice(e.start, e.end);528 op.pos = e.end;529 break;530531 case 'DoWhileStatement':532 addRuntimeAssert(e, '__ala(); ');533 ret += parseElement(op, e.body, depth + 1);534 ret += parseElement(op, e.test, depth + 1);535 break;536537 case 'EmptyStatement':538 ret += op.source.slice(op.pos, e.end);539 break;540541 case 'ExpressionStatement':542 ret += parseElement(op, e.expression, depth + 1);543 break;544545 case 'ForInStatement':546 ret += parseElement(op, e.left, depth + 1);547 ret += parseElement(op, e.right, depth + 1);548 addRuntimeAssert(e, '__ala(); ');549 ret += parseElement(op, e.body, depth + 1);550 break;551552 case 'ForStatement':553 ret += parseElement(op, e.init, depth + 1);554 ret += parseElement(op, e.test, depth + 1);555 ret += parseElement(op, e.update, depth + 1);556 addRuntimeAssert(e, '__ala(); ');557 ret += parseElement(op, e.body, depth + 1);558 break;559560 case 'FunctionDeclaration':561 {562 let functionName = e.id.name; 563 if (IllegalIdentifiers.indexOf(functionName) > -1)564 throw new Error(`Illegal function name: ${functionName}`);565 else if (SettersGetters.indexOf(functionName) > -1)566 throw new Error(`Illegal function name: ${functionName}`);567 ret += parseElement(op, e.id, depth + 1);568 e.params.forEach(_ => ret += parseElement(op, _, depth + 1));569 if (op.thisClass) {570 addRuntimeAssert(e,571 `let __mec = __bfc(${op.thisParameter}, 'public', '${e.id.name}', __FILE__, false); try { `,572 ` } finally { __efc(__mec, '${e.id.name}'); }`);573 }574 else575 addRuntimeAssert(e,576 `let __mec = __bfc(this, 'public', '${e.id.name}', __FILE__, false); try { `,577 ` } finally { __efc(__mec, '${e.id.name}'); }`);578 ret += parseElement(op, e.body, depth + 1, e.id);579 }580 break;581582 case 'FunctionExpression':583 {584 ret += parseElement(op, e.id, depth + 1);585 e.params.forEach(_ => ret += parseElement(op, _, depth + 1));586 if (op.thisClass && op.thisMethod) {587 if (op.method === 'constructor' && op.thisClass) {588 addRuntimeAssert(e,589 `let __mec = __bfc(${op.thisParameter}, '${op.thisAccess}', '${op.thisMethod}', __FILE__, false, ${op.thisClass}); try { `,590 ` } finally { __efc(__mec, '${op.method}'); }`, true);591 }592 else {593 addRuntimeAssert(e,594 `let __mec = __bfc(${op.thisParameter}, '${op.thisAccess}', '${op.thisMethod}', __FILE__, false); try { `,595 ` } finally { __efc(__mec, '${op.method}'); }`, false);596 }597 }598 ret += parseElement(op, e.body, depth + 1);599 }600 break;601602 case 'Identifier':603 let identifier = op.source.slice(e.start, e.end);604605 if (IllegalIdentifiers.indexOf(identifier) > -1)606 throw new Error(`Illegal identifier: ${identifier}`);607 else if (identifier in op.symbols && identifier in op.symbols.__proto__ === false) {608 let symbolValue = op.symbols[identifier];609 if (typeof symbolValue === 'string') {610 ret += `'${op.symbols[identifier]}'`;611 }612 else if (typeof symbolValue === 'function') {613 ret += symbolValue.toString();614 }615 else if (efuns.isPOO(symbolValue)) {616 ret += JSON.stingify(symbolValue);617 }618 }619 else620 ret += identifier;621 op.pos = e.end;622 break;623624 case 'IfStatement':625 ret += parseElement(op, e.test, depth + 1);626 ret += parseElement(op, e.consequent, depth + 1);627 // BUG: Wow alternates were not being processed at all.628 if (e.alternate) ret += parseElement(op, e.alternate);629 break;630631 case 'JSXAttribute':632 if (!op.allowJsx)633 throw new Error(`JSX is not enabled for ${this.extension} files`);634 op.pos = e.end;635 ret += parseElement(op, e.name, depth + 1);636 ret += ':';637 op.pos = e.value.start;638 ret += parseElement(op, e.value, depth + 1);639 break;640641 case 'JSXClosingElement':642 if (!op.allowJsx)643 throw new Error(`JSX is not enabled for ${this.extension} files`);644 ret += ')';645 op.pos = e.end;646 break;647648 case 'JSXElement':649 if (!op.allowJsx)650 throw new Error(`JSX is not enabled for ${op.context.extension} files`);651 if (op.jsxDepth === 0) {652 var jsxInX = op.source.slice(0, e.start).lastIndexOf('\n') + 1;653 op.jsxIndent = ' '.repeat(e.start - jsxInX);654 }655 ret += 'createElement(';656 op.pos = e.start;657 ret += parseElement(op, e.openingElement, depth + 1);658 if (e.children.length > 0) {659 e.children.forEach((_, i) => {660 if(i === 1) op.jsxDepth++;661 let t = parseElement(op, _, depth + 1);662 if (t.length) {663 ret += ', ' + (_.type === 'JSXElement' ? '' : '') + t;664 }665 });666 }667 op.pos = e.end;668 ret += e.closingElement ? parseElement(op, e.closingElement) : ')';669 op.jsxDepth--;670 break;671672 case 'JSXIdentifier':673 if (!op.allowJsx)674 throw new Error(`JSX is not enabled for ${this.extension} files`);675 if (e.name.match(/^[a-z]+/)) {676 ret += `"${e.name}"`;677 }678 else {679 ret += e.name;680 }681 op.pos = e.end;682 break;683684 case 'JSXExpressionContainer':685 if (!op.allowJsx)686 throw new Error(`JSX is not enabled for ${this.extension} files`);687 op.pos = e.expression.start;688 ret += parseElement(op, e.expression, depth + 1);689 op.pos = e.end;690 break;691692 case 'JSXOpeningElement':693 if (!op.allowJsx)694 throw new Error(`JSX is not enabled for ${this.extension} files`);695 op.pos = e.end;696 ret += parseElement(op, e.name, depth + 1);697 ret += ', {';698 e.attributes.forEach((_, i) => {699 ret += (i > 0 ? ', ' : '') + parseElement(op, _, depth + 1);700 });701 ret += '}';702 op.pos = e.end;703 break;704705 case 'JSXText':706 if (!op.allowJsx)707 throw new Error(`JSX is not enabled for ${this.extension} files`);708 ret += e.value.trim().length === 0 ? ret : `"${e.raw.replace(/([\r\n]+)/g, "\\$1")}"`;709 op.pos = e.end;710 break;711712 case 'Literal':713 let literal = op.source.slice(e.start, e.end);714 ret += literal;715 op.pos = e.end;716 break;717718 case 'LogicalExpression':719 ret += parseElement(op, e.left, depth + 1);720 ret += parseElement(op, e.right, depth + 1);721 break;722723 case 'MemberExpression':724 {725 ret += parseElement(op, e.object, depth + 1);726 ret += parseElement(op, e.property, depth + 1);727 }728 break;729730 case 'MethodDefinition':731 if (e.access) {732 op.pos = e.access.end;733 op.eatWhitespace();734 }735 let methodName = op.setMethod(parseElement(op, e.key, depth + 1), e.accessKind, e.static);736 ret += methodName;737 ret += parseElement(op, e.value, depth + 1, methodName);738 op.setMethod();739 break;740741 case 'NewExpression':742 {743 let callee = op.source.slice(e.callee.start, e.callee.end);744 op.pos = e.callee.end;745 ret += `__pcc(${op.thisParameter}, ${callee}, __FILE__, '${op.method}', ct => new ct`;746 e.arguments.forEach(_ => ret += parseElement(op, _, depth + 1));747 if (op.pos !== e.end) {748 if (op.pos > e.end) throw new Error('Oops?');749 ret += op.source.slice(op.pos, e.end);750 op.pos = e.end;751 }752 ret += ')';753 }754 break;755756 case 'ObjectExpression':757 e.properties.forEach(_ => ret += parseElement(op, _, depth + 1));758 break;759760 case 'ObjectPattern':761 e.properties.forEach(_ => ret += parseElement(op, _, depth + 1));762 break;763764 case 'Property':765 ret += parseElement(op, e.key, depth + 1);766 if (e.key.start !== e.value.start)767 ret += parseElement(op, e.value, depth + 1);768 break;769770 case 'RestElement':771 ret += parseElement(op, e.argument, depth + 1);772 op.pos = e.end;773 break;774775 case 'ReturnStatement':776 ret += parseElement(op, e.argument, depth + 1);777 break;778779 case 'RuntimeAssertion':780 ret += e.text;781 break;782783 case 'SwitchCase':784 ret += parseElement(op, e.test, depth + 1);785 e.consequent.forEach(_ => ret += parseElement(op, _, depth + 1));786 break;787788 case 'SequenceExpression':789 e.expressions.forEach(_ => ret += parseElement(op, _, depth + 1));790 break;791792 case 'SpreadElement':793 ret += parseElement(op, e.argument, depth + 1);794 break;795796 case 'Super':797 ret += op.source.slice(e.start, e.end);798 op.pos = e.end;799 break;800801 case 'SwitchStatement':802 ret += parseElement(op, e.discriminant, depth + 1);803 e.cases.forEach(_ => ret += parseElement(op, _, depth + 1));804 break;805806 case 'TemplateElement':807 ret += op.source.slice(e.start, e.end);808 op.pos = e.end;809 break;810811 case 'TemplateLiteral':812 {813 let items = []814 .concat(e.quasis.slice(0), e.expressions.slice(0))815 .sort((a, b) => a.start < b.start ? -1 : a.start === b.start ? 0 : 1);816 items.forEach(_ => ret += parseElement(op, _, depth + 1));817 }818 break;819820 case 'ThisExpression':821 ret += op.source.slice(e.start, e.end);822 op.pos = e.end;823 break;824825 case 'ThrowStatement':826 ret += parseElement(op, e.argument, depth + 1);827 break;828829 case 'TryStatement':830 ret += parseElement(op, e.block, depth + 1);831 ret += parseElement(op, e.handler, depth + 1);832 ret += parseElement(op, e.finalizer, depth + 1);833 break;834835 case 'UnaryExpression':836 ret += parseElement(op, e.argument, depth + 1);837 break;838839 case 'UpdateExpression':840 ret += op.source.slice(e.start, e.end);841 op.pos = e.end;842 break;843844 case 'VariableDeclarator':845 ret += parseElement(op, e.id, depth + 1);846 if (e.init) {847 e.init.idType = e.id.type;848 ret += parseElement(op, e.init, depth + 1);849 }850 break;851852 case 'VariableDeclaration':853 e.declarations.forEach(_ => ret += parseElement(op, _, depth + 1));854 break;855856 case 'WhileStatement':857 ret += parseElement(op, e.test, depth + 1);858 addRuntimeAssert(e, '__ala(); ');859 ret += parseElement(op, e.body, depth + 1);860 break;861862 case 'WithStatement':863 ret += parseElement(op, e.object, depth + 1);864 ret += parseElement(op, e.body, depth + 1);865 break;866867 default:868 throw new Error(`Unknown type: ${e.type}`);869 }870 if (op.pos !== e.end) {871 if (op.pos > e.end) throw new Error('Oops?');872873 // this should be done by each type so we are sure we aren't missing something874 ret += op.readUntil(e.end);875 }876 }877 return ret;878}879880class MudScriptTranspiler extends PipelineComponent {881 constructor(config) {882 super(config);883884 this.acornOptions = Object.assign({}, config.acornOptions);885 this.acornOptions.onComment = (block, text, start, end) => {886 /* TODO: do autodoc stuff */887 let len = end - start;888 };889890 this.allowJsx = typeof config.allowJsx === 'boolean' ? config.allowJsx : true;891 this.allowLiteralCallouts = typeof config.allowLiteralCallouts === 'boolean' ? config.allowLiteralCallouts : true;892 this.extension = config.extension || '.js';893 this.parser = acorn.Parser894 .extend(jsx())895 .extend(modifiers(config));896897 }898899 run(context) {900 let op = new JSXTranspilerOp({901 acornOptions: Object.assign({}, this.acornOptions, context.acornOptions),902 allowJsx: this.allowJsx,903 allowLiteralCallouts: this.allowLiteralCallouts,904 filename: context.basename,905 context,906 source: context.content907 });908 try {909 if (this.enabled) {910 op.ast = this.parser.parse(op.source, op.acornOptions);911 op.output += `__rmt("${op.filename}");`912 op.ast.body.forEach(n => op.output += parseElement(op, n, 0));913 op.output += op.readUntil(op.max);914 op.output += op.appendText;915 return context.update(PipeContext.CTX_RUNNING, op.finish());916 }917 }918 catch (x) {919 console.log(`MudScriptTranspiler.run compiling ${context.basename}`, x.message);920 throw x;921 }922 }923924 async runAsync(context) {925 let op = new JSXTranspilerOp({926 acornOptions: Object.assign({}, this.acornOptions, context.acornOptions),927 allowJsx: this.allowJsx,928 allowLiteralCallouts: this.allowLiteralCallouts,929 filename: context.basename,930 context,931 source: context.content932 });933 try {934 if (this.enabled) {935 let source = op.source = 'await (async (x) => { ' + op.source + ' })(42)';936 op.ast = this.parser.parse(source, op.acornOptions);937 op.output += `__rmt("${op.filename}");`938 op.ast.body.forEach(n => op.output += parseElement(op, n, 0));939 op.output += op.readUntil(op.max);940 op.output += op.appendText;941 return context.update(PipeContext.CTX_RUNNING, op.finish());942 }943 }944 catch (x) {945 console.log(`MudScriptTranspiler.run compiling ${context.basename}`, x.message);946 throw x;947 }948 }949}950
...
douban_parse.js
Source:douban_parse.js
...18 }19 var parseAuthor = function(source, target) {20 target.author = {}21 if (!source.author || !source.author[0]) return;22 parseElement(source.author[0], target.author, 'name');23 parseLinks(source.author[0], target.author);24 }25 var parseLinks = function(source, target) {26 target.link = {};27 if (source.link)28 for (var i = 0; i < source.link.length; ++i)29 target.link[source.link[i]['@rel']] = source.link[i]['@href'];30 }31 var parseId = function(source, target) {32 if (source.id) {33 target.id = source.id.$t;34 var tmp = target.id.split('/').slice(-1);35 if (tmp.length > 0) target.nid = tmp[0]36 }37 }38 var parseOpenSearch = function(source, target) {39 parseElement(source, target, 'opensearch:startIndex', 'startIndex');40 target.startIndex = parseInt(target.startIndex)41 parseElement(source, target, 'opensearch:itemPerPage', 'itemPerPage');42 target.itemPerPage = parseInt(target.itemPerPage)43 parseElement(source, target, 'opensearch:totalResults', 'totalResults');44 target.totalResults = parseInt(target.totalResults)45 }46 var parseFeed = function(results, feed, entryParser) {47 parseOpenSearch(results, feed)48 parseElement(results, feed, 'title')49 feed.entries = []50 for (var i = 0; i < results.entry.length; ++i)51 feed.entries.push(entryParser(results.entry[i]));52 }53 api_obj.parseUser = function(re) {54 var user = {};55 parseId(re, user)56 parseElement(re, user, 'title');57 if (user.title) user.name = user.title58 parseElement(re, user, 'content');59 parseElement(re, user, 'db:location', 'location');60 parseLinks(re, user)61 return user;62 }63 api_obj.parseUsers = function(results) {64 var feed = {};65 parseFeed(results, feed, api_obj.parseUser)66 return feed;67 }68 api_obj.parseSubject = function(re) {69 var subject = {};70 parseId(re, subject)71 parseAuthor(re, subject)72 parseElement(re, subject, 'title');73 parseElement(re, subject, 'summary');74 parseRating(re, subject);75 parseLinks(re, subject)76 if (re.category) subject.category = re.category['@term'].match('2007#([a-z]+)')[1];77 subject.tag = [];78 if (re['db:tag'])79 for (var j = 0; j < re['db:tag'].length; ++j)80 subject.tag.push({81 count: parseInt(re['db:tag'][j]['@count']),82 name: re['db:tag'][j]['@name']83 });84 subject.attribute = {};85 if (re['db:attribute'])86 for (var j = 0; j < re['db:attribute'].length; ++j) {87 if (subject.attribute[re['db:attribute'][j]['@name']] == null)88 subject.attribute[re['db:attribute'][j]['@name']] = [];89 subject.attribute[re['db:attribute'][j]['@name']].push(re['db:attribute'][j]['$t']);90 if (re['db:attribute'][j]['@name'] == 'aka' && re['db:attribute'][j]['@lang'] == 'zh_CN')91 subject.title_cn = re['db:attribute'][j]['$t']92 }93 return subject;94 }95 api_obj.parseSubjects = function(results) {96 var feed = {};97 parseFeed(results, feed, api_obj.parseSubject)98 return feed;99 }100 api_obj.parseReview = function(re) {101 var review = {};102 parseId(re, review)103 parseAuthor(re, review)104 parseElement(re, review, 'title');105 parseElement(re, review, 'summary');106 parseElement(re, review, 'published');107 parseElement(re, review, 'updated')108 parseRating(re, review);109 parseLinks(re, review)110 if (re['db:subject']) review.subject = api_obj.parseSubject(re['db:subject'])111 return review;112 }113 api_obj.parseReviews = function(results) {114 var feed = {}115 parseAuthor(results, feed)116 if (results['db:subject']) feed.subject = api_obj.parseSubject(results['db:subject'])117 parseFeed(results, feed, api_obj.parseReview)118 return feed;119 }120 api_obj.parseCollection = function(re) {121 var collection = {};122 parseId(re, collection)123 parseElement(re, collection, 'title');124 parseElement(re, collection, 'summary');125 parseElement(re, collection, 'updated')126 parseElement(re, collection, 'db:status', 'status')127 parseRating(re, collection);128 parseLinks(re, collection)129 collection.tag = [];130 if (re['db:tag'])131 for (var j = 0; j < re['db:tag'].length; ++j)132 collection.tag.push({133 name: re['db:tag'][j]['@name']134 });135 if (re['db:subject']) collection.subject = api_obj.parseSubject(re['db:subject'])136 return collection;137 }138 api_obj.parseMultiCollection = function(results) {139 var feed = {}140 parseAuthor(results, feed)141 parseFeed(results, feed, api_obj.parseCollection)142 return feed;143 }144 api_obj.parseTag = function(re) {145 var tag = {};146 parseElement(re, tag, 'id');147 if (tag.title) tag.name = tag.title148 parseElement(re, tag, 'title');149 parseElement(re, tag, 'count')150 return tag;151 }152 api_obj.parseTags = function(results) {153 var feed = {}154 parseFeed(results, feed, api_obj.parseTag)155 return feed156 }...
page_tab.js
Source:page_tab.js
...40 //ç¨äºçæå³ä¸è§ç导èªåæ¢æé®41 //if(locator.get_scope() === 'all'){ //表示å½åå±äºallçå®ä½å42 //å³ä¾§43 if(locator.get_domain_url() !== undefined){44 this.element_navigator_second.appendChild(parseElement(locator.get_domain_url()));45 }46 if (locator.get_student_url() !== undefined){47 this.element_navigator_second.appendChild(parseElement(locator.get_student_url()));48 }49 if(locator.get_teacher_url() !== undefined){50 this.element_navigator_second.appendChild(parseElement(locator.get_teacher_url()));51 }52 if(locator.get_admin_url() !== undefined){53 this.element_navigator_second.appendChild(parseElement(locator.get_admin_url()));54 }55 //}56 this.element_navigator_first.innerHTML = '';57 //左侧58 if (adminType !== 0){59 this.element_navigator_first.appendChild(parseElement(locator.get_all_url()));60 }61 if(locator.get_college_url() !== undefined){62 if (adminType !== 0){63 this.element_navigator_first.appendChild(parseElement(`<span>/</span>`));64 }65 this.element_navigator_first.appendChild(parseElement(locator.get_college_url()));66 } else if(locator.get_scope() === 'all' && data !== undefined){ //说ææäºçº§ç®å½çåºç°67 this.element_navigator_first.appendChild(parseElement(`<span>/</span>`));68 this.element_navigator_first.appendChild(parseElement(`<label>69 <select class="select-one">70 <option value="0">请éæ©</option>71 ${data.reduce((total, item) => {72 return total + `<option value=${item.id}>${item.name}</option>`73}, '')}74 </select>75</label>`));76 let checkbox = this.element_navigator_first.querySelector('.select-one');77 checkbox.addEventListener('change', (event)=>{78 if(checkbox.value !== 0){79 locator.collegeId = checkbox.value;80 window.location.href = locator.get_college_scoped();81 }82 //console.log(checkbox.value);83 });84 }85 if(locator.get_profession_url() !== undefined){86 this.element_navigator_first.appendChild(parseElement(`<span>/</span>`));87 this.element_navigator_first.appendChild(parseElement(locator.get_profession_url()));88 } else if(locator.get_scope() === 'college' && data !== undefined){89 this.element_navigator_first.appendChild(parseElement(`<span>/</span>`));90 this.element_navigator_first.appendChild(parseElement(`<label>91 <select class="select-one">92 <option value="0">请éæ©</option>93 ${data.reduce((total, item) => {94 return total + `<option value=${item.id}>${item.name}</option>`95 }, '')}96 </select>97</label>`));98 let checkbox = this.element_navigator_first.querySelector('.select-one');99 checkbox.addEventListener('change', (event)=>{100 if(checkbox.value !== 0){101 locator.professionId = checkbox.value;102 window.location.href = locator.get_profession_scoped();103 }104 //console.log(checkbox.value);105 });106 }107 if(locator.get_xclass_url() !== undefined){108 this.element_navigator_first.appendChild(parseElement(`<span>/</span>`));109 this.element_navigator_first.appendChild(parseElement(locator.get_xclass_url()));110 }else if(locator.get_scope() === 'profession' && data !== undefined){111 this.element_navigator_first.appendChild(parseElement(`<span>/</span>`));112 this.element_navigator_first.appendChild(parseElement(`<label>113 <select class="select-one">114 <option value="0">请éæ©</option>115 ${data.reduce((total, item) => {116 return total + `<option value=${item.id}>${item.name}</option>`117 }, '')}118 </select>119</label>`));120 let checkbox = this.element_navigator_first.querySelector('.select-one');121 checkbox.addEventListener('change', (event)=>{122 if(checkbox.value !== 0){123 locator.xclassId = checkbox.value;124 window.location.href = locator.get_xclass_scoped();125 }126 //console.log(checkbox.value);...
api-parser.js
Source:api-parser.js
...18}19var parseAuthor = function(source, target) {20 target.author={}21 if (!source.author || !source.author[0]) return;22 parseElement(source.author[0], target.author, 'name');23 parseLinks(source.author[0], target.author);24}25var parseLinks = function(source, target) {26 target.link = {};27 if (source.link)28 for (var i=0; i<source.link.length; ++i)29 target.link[source.link[i]['@rel']] = source.link[i]['@href'];30}31var parseId = function(source, target) {32 if (source.id) {33 target.id=source.id.$t;34 var tmp = target.id.split('/').slice(-1);35 if (tmp.length > 0) target.nid = tmp[0]36 }37}38var parseOpenSearch = function(source, target){39 parseElement(source, target, 'opensearch:startIndex', 'startIndex');40 target.startIndex = parseInt(target.startIndex)41 parseElement(source, target, 'opensearch:itemPerPage', 'itemPerPage');42 target.itemPerPage = parseInt(target.itemPerPage)43 parseElement(source, target, 'opensearch:totalResults', 'totalResults');44 target.totalResults = parseInt(target.totalResults)45}46var parseFeed = function(results, feed, entryParser){47 parseOpenSearch(results, feed)48 parseElement(results, feed, 'title')49 feed.entries = []50 for (var i=0; i<results.entry.length; ++i)51 feed.entries.push(entryParser(results.entry[i]));52}53api_obj.parseUser = function(re) {54 var user = {};55 parseId(re, user)56 parseElement(re, user, 'title');57 if (user.title) user.name = user.title58 parseElement(re, user, 'content');59 parseElement(re, user, 'db:location', 'location');60 parseLinks(re, user)61 return user;62}63api_obj.parseUsers = function(results){64 var feed = {};65 parseFeed(results, feed, api_obj.parseUser)66 return feed;67}68api_obj.parseSubject = function(re) {69 var subject = {};70 parseId(re, subject)71 parseAuthor(re, subject)72 parseElement(re, subject, 'title');73 parseElement(re, subject, 'summary');74 parseRating(re, subject);75 parseLinks(re, subject)76 if (re.category) subject.category = re.category['@term'].match('2007#([a-z]+)')[1];77 subject.tag = [];78 if (re['db:tag'])79 for (var j=0; j<re['db:tag'].length; ++j)80 subject.tag.push({count:parseInt(re['db:tag'][j]['@count']), name:re['db:tag'][j]['@name']});81 subject.attribute = {};82 if (re['db:attribute'])83 for (var j=0; j<re['db:attribute'].length; ++j) {84 if (subject.attribute[re['db:attribute'][j]['@name']] == null)85 subject.attribute[re['db:attribute'][j]['@name']] = [];86 subject.attribute[re['db:attribute'][j]['@name']].push(re['db:attribute'][j]['$t']);87 if (re['db:attribute'][j]['@name'] == 'aka' && re['db:attribute'][j]['@lang'] == 'zh_CN')88 subject.title_cn = re['db:attribute'][j]['$t']89 }90 return subject;91}92api_obj.parseSubjects = function(results){93 var feed = {};94 parseFeed(results, feed, api_obj.parseSubject)95 return feed;96}97api_obj.parseReview = function(re) {98 var review = {};99 parseId(re, review)100 parseAuthor(re, review)101 parseElement(re, review, 'title');102 parseElement(re, review, 'summary');103 parseElement(re, review, 'published');104 parseElement(re, review, 'updated')105 parseRating(re, review);106 parseLinks(re, review)107 if (re['db:subject']) review.subject = api_obj.parseSubject(re['db:subject'])108 return review;109}110api_obj.parseReviews = function(results){111 var feed = {}112 parseAuthor(results, feed)113 if (results['db:subject']) feed.subject = api_obj.parseSubject(results['db:subject'])114 parseFeed(results, feed, api_obj.parseReview)115 return feed;116}117api_obj.parseCollection = function(re) {118 var collection = {};119 parseId(re, collection)120 parseElement(re, collection, 'title');121 parseElement(re, collection, 'summary');122 parseElement(re, collection, 'updated')123 parseElement(re, collection, 'db:status', 'status')124 parseRating(re, collection);125 parseLinks(re, collection)126 collection.tag = [];127 if (re['db:tag'])128 for (var j=0; j<re['db:tag'].length; ++j)129 collection.tag.push({name:re['db:tag'][j]['@name']});130 if (re['db:subject']) collection.subject = api_obj.parseSubject(re['db:subject'])131 return collection;132}133api_obj.parseMultiCollection = function(results) {134 var feed = {}135 parseAuthor(results, feed)136 parseFeed(results, feed, api_obj.parseCollection)137 return feed;138}139api_obj.parseTag = function(re){140 var tag = {};141 parseElement(re, tag, 'id');142 if (tag.title) tag.name = tag.title143 parseElement(re, tag, 'title');144 parseElement(re, tag, 'count')145 return tag;146}147api_obj.parseTags = function(results){148 var feed = {}149 parseFeed(results, feed, api_obj.parseTag)150 return feed151}...
page_navigator.js
Source:page_navigator.js
...11 this.element_page_navigator.innerHTML = ''; //å
æ¸
空ææçä¸è¥¿12 let index = locator.pageIndex;13 // 第ä¸è¡14 if(index === 0){15 this.element_page_navigator.appendChild(parseElement(`<span class='disabled'>åä¸é¡µ</span>`))16 } else {17 this.element_page_navigator.appendChild(parseElement(`<span><a href='${this.get_url(index - 1)}'>åä¸é¡µ</a></span>`))18 }19 // ä¸é´çå
ç´ 20 let start_index = index - 2 < 0 ? 0: index - 2;21 if(index - 2 > 0){22 this.element_page_navigator.appendChild(parseElement(`<span>...</span>`))23 }24 let end_index = start_index + 5 > this.pageCount? this.pageCount: start_index + 5;25 for(let i = start_index; i < end_index; ++i){26 if(i === index){//å½åè¡27 this.element_page_navigator.appendChild(parseElement(`<span><a class='selected' href='${this.get_url(i)}'>${i + 1}</a></span>`));28 } else {29 this.element_page_navigator.appendChild(parseElement(`<span><a href='${this.get_url(i)}'>${i + 1}</a></span>`));30 }31 }32 if(start_index + 5 < this.pageCount){33 this.element_page_navigator.appendChild(parseElement(`<span>...</span>`))34 }35 if(index === this.pageCount - 1){36 this.element_page_navigator.appendChild(parseElement(`<span class='disabled'>åä¸é¡µ</span>`))37 }38 }39 get_url(pageIndex){40 return get_url(`/admin/user?type=${locator.type}&pageIndex=${pageIndex}&scope=${locator.scope}&tag=${locator.type}`);41 }...
get-default-internals.js
Source:get-default-internals.js
1module.exports = function getDefaultInternals (cardscript) {2 const internals = {3 dialogControl: {},4 currentCardListData: {},5 cardListParents: {}6 }7 const cardListPath = []8 cardscript.body.forEach(parseElement)9 function parseElement (element) {10 switch (element.type) {11 case 'CardList':12 internals.dialogControl[element.id] = false13 internals.currentCardListData[element.id] = {}14 if (cardListPath.length === 0) {15 internals.cardListParents[element.id] = null16 cardListPath.push(element.id)17 } else {18 internals.cardListParents[element.id] = cardListPath[cardListPath.length - 1]19 cardListPath.push(element.id)20 }21 element.card.body.forEach(parseElement)22 cardListPath.pop()23 break24 case 'ColumnSet':25 element.columns.forEach(parseElement)26 break27 case 'FactSet':28 if (Array.isArray(element.facts)) {29 element.facts.forEach(parseElement)30 }31 break32 case 'Collapsible':33 element.card.body.forEach(parseElement)34 break35 case 'TabSet':36 element.tabs.forEach(parseElement)37 break38 case 'Stepper':39 element.steps.forEach(parseElement)40 break41 case 'Tab':42 case 'Step':43 case 'Column':44 case 'Container':45 element.items.forEach(parseElement)46 }47 }48 return internals...
util.test.js
Source:util.test.js
...21test('Util parseElement', (t) => {22 t.plan(10);23 // eslint-disable-next-line no-empty-function24 const noop = () => { };25 t.equal(Util.parseElement(null), null);26 t.equal(Util.parseElement(undefined), null);27 t.equal(Util.parseElement('Hello {0}').constructor, StringTag);28 t.equal(Util.parseElement(['Hello {0}']).constructor, ArrayTag);29 t.equal(Util.parseElement({ test: 'Hello {0}' }).constructor, BlockTag);30 t.equal(Util.parseElement(false).constructor, ValueTag);31 t.equal(Util.parseElement(noop).constructor, ValueTag);32 t.equal(Util.parseElement(0).constructor, ValueTag);33 t.equal(Util.parseElement(Util).constructor, ValueTag);34 t.equal(Util.parseElement(Symbol('test')).constructor, ValueTag);...
index.js
Source:index.js
1module.exports = function (cardscript) {2 const graphs = {}3 function parseElement (element) {4 switch (element.type) {5 case 'Collapsible':6 element.card.body.forEach(parseElement)7 break8 case 'ColumnSet':9 element.columns.forEach(parseElement)10 break11 case 'CardList':12 element.card.body.forEach(parseElement)13 break14 case 'Input.ApiLookup':15 if (element.parametersCard) element.parametersCard.body.forEach(parseElement)16 break17 case 'TabSet':18 element.tabs.forEach(parseElement)19 break20 case 'Steppers':21 element.steps.forEach(parseElement)22 break23 case 'Tab':24 case 'Step':25 case 'Container':26 case 'Column':27 element.items.forEach(parseElement)28 break29 case 'Graph':30 graphs[element.id] = {31 options: element.stats32 }33 }34 }35 if (cardscript && cardscript.body) {36 cardscript.body.forEach(parseElement)37 }38 return graphs...
Using AI Code Generation
1const { parseElement } = require('playwright/lib/client/selectorEngine');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const page = await browser.newPage();6 const element = await parseElement(page, 'css=div[role="main"]');7 await element.screenshot({ path: 'main.png' });8 await browser.close();9})();10### `parseSelector(selector)`11const { parseSelector } = require('playwright/lib/client/selectorEngine');12const selector = parseSelector('css=div[role="main"]');13### `parseElement(page, selector)`14const { parseElement } = require('playwright/lib/client/selectorEngine');15const { chromium } = require('playwright');16(async () => {17 const browser = await chromium.launch();18 const page = await browser.newPage();19 const element = await parseElement(page, 'css=div[role="main"]');20 await element.screenshot({ path: 'main.png' });21 await browser.close();22})();23const { chromium } = require('playwright');24const { parseElement } = require('playwright/lib/client/selectorEngine');25(async () => {26 const browser = await chromium.launch();27 const page = await browser.newPage();28 const element = await parseElement(page, 'css=div[role="main"]');29 await element.screenshot({ path: 'main.png' });30 await browser.close();31})();32const { selectors } = require('playwright/lib/client/
Using AI Code Generation
1const { parseElement } = require('playwright/lib/server/frames');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const element = await page.$('input[name=q]');8 const parsedElement = parseElement(element);9 console.log(parsedElement);10 await browser.close();11})();
Using AI Code Generation
1const { parseSelector } = require('playwright/lib/server/selectors/selectorEngine');2const { parseSelector } = require('playwright/lib/server/selectors/selectorEngine');3const selector = parseSelector('css=div#foo');4console.log(selector);5const { createEngine } = require('playwright/lib/server/selectors/selectorEngine');6const { createEngine } = require('playwright/lib/server/selectors/selectorEngine');7const engine = createEngine({8 query(root, selector) {9 return root.querySelectorAll(selector);10 },11 queryOne(root, selector) {12 return root.querySelector(selector);13 },14});15const { createEngine } = require('playwright/lib/server/selectors/selectorEngine');16const { createEngine } = require('playwright/lib/server/selectors/selectorEngine');17const engine = createEngine({18 { name: 'foo', title: 'Foo', type: 'text' },19 { name: 'bar', title: 'Bar', type: 'number' },20 query(root, selector, options) {21 return root.querySelectorAll(selector);22 },23 queryOne(root, selector, options) {24 return root.querySelector(selector);25 },26});27const { createEngine } = require('playwright/lib/server/selectors/selectorEngine');28const { registerEngine } = require('playwright/lib/server/selectors/selectorEngine');29const { registerEngine } = require('playwright/lib/server/selectors/selectorEngine');30const engine = createEngine({31 query(root, selector) {32 return root.querySelectorAll(selector);33 },34 queryOne(root, selector) {35 return root.querySelector(selector);36 },37});38registerEngine('my-engine', engine);
Using AI Code Generation
1const { parseElement } = require('playwright/lib/server/dom.js');2const element = parseElement(document.querySelector('div'));3console.log(element);4{5 {6 importedDocument: null,7 }8 importedDocument: null,9}10const { parseElement } = require('playwright/lib/server/dom.js');11const element = parseElement(document.querySelector('div'));12console.log(element.nodeName);13const { parseElement } = require('playwright/lib/server/dom.js');14const element = parseElement(document.querySelector('div'));15console.log(element.attributes);16 { name: 'id', value: 'test' },17 { name: 'class', value: 'test' }
Using AI Code Generation
1const { parseElement } = require('playwright/lib/client/selectorEngine');2const element = parseElement('css=div');3console.log(element);4### parseElement(selector: string, root?: ElementHandle): ElementHandle5const { parseElement } = require('playwright/lib/client/selectorEngine');6const element = parseElement('css=div');7console.log(element);8Agreement. You (or your employer) retain the copyright
Using AI Code Generation
1const { parseSelector } = require('@playwright/test/lib/server/frames');2const { parseSelector: parseSelector2 } = require('@playwright/test/lib/server/selectors/selectorEngine');3const { parseSelector: parseSelector3 } = require('@playwright/test/lib/server/selectors/selectorImpl');4const { parseSelector: parseSelector4 } = require('@playwright/test/lib/server/selectors/selectorParser');5const { parseSelector: parseSelector5 } = require('@playwright/test/lib/server/selectors/selectorType');6const { parseSelector: parseSelector6 } = require('@playwright/test/lib/server/selectors/selectorTypes');7const { parseSelector: parseSelector7 } = require('@playwright/test/lib/server/selectors/selectorValidator');8const { parseSelector: parseSelector8 } = require('@playwright/test/lib/server/selectors/selectorVersion');9const { parseSelector: parseSelector9 } = require('@playwright/test/lib/server/selectors/selectorVersions');10const { parseSelector: parseSelector10 } = require('@playwright/test/lib/server/selectors/selectors');11const { parseSelector: parseSelector11 } = require('@playwright/test/lib/server/selectors/types');12const selector = 'css=div';13const selector2 = 'text=Click me';14const selector4 = 'css=div >> text=Click me';15const selector5 = 'css=div >> text=Click me >> css=div >> text=Click me';16const selector6 = 'css=div >> text=Click me >> css=div >> text=Click me >> css=div >> text=Click me';17const parsedSelector = parseSelector(selector);18const parsedSelector2 = parseSelector2(selector);19const parsedSelector3 = parseSelector3(selector);20const parsedSelector4 = parseSelector4(selector);21const parsedSelector5 = parseSelector5(selector);22const parsedSelector6 = parseSelector6(selector);23const parsedSelector7 = parseSelector7(selector);24const parsedSelector8 = parseSelector8(selector);25const parsedSelector9 = parseSelector9(selector);26const parsedSelector10 = parseSelector10(selector);27const parsedSelector11 = parseSelector11(selector);28const parsedSelector12 = parseSelector(selector2);29const parsedSelector13 = parseSelector2(selector2);30const parsedSelector14 = parseSelector3(selector2);31const parsedSelector15 = parseSelector4(selector2);
Using AI Code Generation
1const { parseElement } = require('playwright/lib/client/selectorEngine');2const elementHandle = parseElement('css=div#myDiv');3console.log(elementHandle);4ElementHandle {5 _context: BrowserContext {6 _options: {7 },8 _browser: Browser {9 },10 _timeoutSettings: TimeoutSettings { _defaultTimeout: 30000 },11 _pageBindings: Map(0) {},12 _browserSession: BrowserSession {13 _downloadUUIDToPath: Map(0) {},14 _downloadURLs: Map(0) {},15 _downloadURLToUUID: Map(0) {},16 _downloadURLToIsPaused: Map(0) {},
Using AI Code Generation
1const { parseElement } = require("@playwright/test/lib/utils/selectorParser");2const element = parseElement("css=div.test");3console.log(element);4const { parseElement } = require("@playwright/test-selector-parser");5const element = parseElement("css=div.test");6console.log(element);
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!