Best JavaScript code snippet using playwright-internal
bf.js
Source:bf.js
1// TODO: show data cells when paused2window.addEventListener("load",function(){3 if(!window.WebAssembly){4 alert("This browser does not support WebAssembly, which is required to use this compiler. Chrome 57+, Firefox 52+ and Opera 44+ are great browsers that do support WebAssembly, and they're free!");5 return;6 }7 if(!window.SharedArrayBuffer){8 alert("This browser does not support experimental Atomics & SharedArrayBuffer. They are required for all combinations of modes other than release non-interactive mode. Experimental support is available in Chrome, Firefox and Opera, and can be enabled in the browser settings.");9 }10 11 var codeEditor=ace.edit(document.getElementById("codeblock").getElementsByClassName("editor")[0]);12 codeEditor.setTheme("ace/theme/chrome");13 codeEditor.setFontSize(16);14 codeEditor.setShowPrintMargin(false);15 16 var inputEditor=ace.edit(document.getElementById("inputblock").getElementsByClassName("editor")[0]);17 inputEditor.setTheme("ace/theme/chrome");18 inputEditor.setFontSize(16);19 inputEditor.setShowPrintMargin(false);20 inputEditor.setHighlightActiveLine(false);21 inputEditor.renderer.setShowGutter(false);22 inputEditor.getSession().setUseWorker(false);23 24 var outputEditor=ace.edit(document.getElementById("outputblock").getElementsByClassName("editor")[0]);25 outputEditor.setTheme("ace/theme/chrome");26 outputEditor.setFontSize(16);27 outputEditor.setShowPrintMargin(false);28 outputEditor.setHighlightActiveLine(false);29 outputEditor.renderer.setShowGutter(false);30 outputEditor.setReadOnly(true);31 outputEditor.getSession().setUseWorker(false);32 33 var interactiveConsole=new InteractiveConsole(document.getElementById("ioblock").getElementsByClassName("combined")[0].getElementsByClassName("terminal")[0]);34 /*interactiveConsole.write("Test 1");35 interactiveConsole.write("Test 2\n");36 interactiveConsole.read(function(e){37 alert(e);38 });*/39 40 // memoryview41 var memoryview=document.getElementById("memoryview");42 var memoryviewmanager=undefined;43 44 // buttons45 var openbutton=document.getElementById("openbutton");46 var downloadbutton=document.getElementById("downloadbutton");47 var compilebutton=document.getElementById("compilebutton");48 var runbutton=document.getElementById("runbutton");49 var stopbutton=document.getElementById("stopbutton");50 var continuebutton=document.getElementById("continuebutton");51 var stepbutton=document.getElementById("stepbutton");52 53 var openbuttonfilepicker=document.getElementById("openbuttonfilepicker");54 55 // shortcuts56 window.addEventListener("keydown",function(e){57 if(e.ctrlKey&&e.key==="o"){ // Ctrl+O58 e.preventDefault();59 openbutton.click();60 }61 else if(e.ctrlKey&&e.key==="s"){ // Ctrl+S62 e.preventDefault();63 downloadbutton.click();64 }65 else if(e.key==="F6"){ // F666 e.preventDefault();67 compilebutton.click();68 }69 else if(e.key==="F5"){ // F570 e.preventDefault();71 runbutton.click();72 }73 else if(e.key==="F4"){ // F874 e.preventDefault();75 stopbutton.click();76 }77 else if(e.key==="F8"){ // F878 e.preventDefault();79 continuebutton.click();80 }81 else if(e.key==="F10"){ // F1082 e.preventDefault();83 stepbutton.click();84 }85 });86 87 openbutton.addEventListener("click",function(){88 openbuttonfilepicker.click();89 });90 91 openbuttonfilepicker.addEventListener("change",function(){92 if(openbuttonfilepicker.files.length===0){93 return;94 }95 var file=openbuttonfilepicker.files[0];96 var filereader=new FileReader();97 filereader.addEventListener("load",function(){98 var codestr=filereader.result;99 codeEditor.setValue(codestr,-1);100 codeEditor.focus();101 });102 filereader.readAsText(file);103 });104 105 downloadbutton.addEventListener("click",function(){106 var el=document.createElement('a');107 el.setAttribute("href","data:text/plain;charset=utf-8,"+encodeURIComponent(codeEditor.getValue()));108 el.setAttribute("download","download.b");109 el.style.display="none";110 document.body.appendChild(el);111 el.click();112 document.body.removeChild(el);113 });114 115 var processHandler=undefined;116 var processHandlerTerminator=undefined; // called when user presses compile or run117 var runTerminator=undefined;118 var codeCompiled=false;119 var isCompiling=false;120 var toRunAfterCompiling=false;121 122 var compilationSpan=document.getElementById("compilationspan");123 var executionSpan=document.getElementById("executionspan");124 125 while(compilationSpan.firstChild)compilationSpan.removeChild(compilationSpan.firstChild);126 compilationSpan.appendChild(document.createTextNode(""));127 while(executionSpan.firstChild)executionSpan.removeChild(executionSpan.firstChild);128 executionSpan.appendChild(document.createTextNode(""));129 130 codeEditor.on("change",function(){131 codeCompiled=false;132 });133 134 var compilemodes_changed=function(){135 executemodes_changed(true);136 if(processHandlerTerminator){137 processHandlerTerminator();138 processHandlerTerminator=undefined;139 }140 compilationSpan.firstChild.nodeValue="";141 codeCompiled=false;142 isCompiling=false;143 };144 145 var executemodes_changed=function(from_compilemode_changed){146 if(runTerminator){147 runTerminator();148 runTerminator=undefined;149 if(!from_compilemode_changed){150 compilemodes_changed();151 return;152 }153 }154 executionSpan.firstChild.nodeValue="";155 if(interactive){156 interactiveConsole.clear();157 }158 else{159 outputEditor.setValue("");160 }161 if(compilemode==="debug"&&interactive==="no"){162 alert("Non-interactive I/O not supported in debug mode.");163 radio_interactive_yes.checked=true;164 radio_interactive_yes.dispatchEvent(new Event("change"));165 }166 }167 168 compilebutton.addEventListener("click",function(){169 codeEditor.setReadOnly(true);170 if(processHandlerTerminator){171 processHandlerTerminator();172 }173 var to_terminate=false;174 processHandlerTerminator=function(){175 to_terminate=true;176 codeEditor.setReadOnly(false);177 if(processHandler){178 processHandler.terminate();179 processHandler=undefined;180 }181 isCompiling=false;182 };183 isCompiling=true;184 processHandler=new JellyBFProcessHandler();185 processHandler.initialize(function(){186 if(!to_terminate){187 executionSpan.firstChild.nodeValue="";188 compilationSpan.firstChild.nodeValue="";189 if(compilemode!=="debug")compilationSpan.firstChild.nodeValue="Compilingâ¦";190 var start_time=Date.now();191 processHandler.compile(codeEditor.getValue(),{debug:(compilemode==="debug")},function(message){192 if(!to_terminate){193 isCompiling=false;194 codeEditor.setReadOnly(false);195 processHandlerTerminator=undefined;196 if(message.success){197 codeCompiled=true;198 var end_time=Date.now();199 console.log("Compiled in "+Math.round(end_time-start_time)+" ms.");200 if(compilemode!=="debug")compilationSpan.firstChild.nodeValue="Compiled in "+Math.round(end_time-start_time)+" ms.";201 if(toRunAfterCompiling){202 toRunAfterCompiling=false;203 runbutton.click();204 }205 }206 else{207 compilationSpan.firstChild.nodeValue="Compilation failed.";208 }209 }210 });211 }212 });213 });214 215 var breakpointBuffer=undefined;216 var globalPauseBuffer=undefined;217 var breakpoints=[];218 219 runbutton.addEventListener("click",function(){220 codeEditor.setReadOnly(true);221 if(!codeCompiled){222 toRunAfterCompiling=true;223 if(!isCompiling){224 compilebutton.click();225 }226 }227 else if(runTerminator){ // this is here because i don't know any way to kill execution without terminating the worker228 runTerminator();229 runTerminator=undefined;230 toRunAfterCompiling=true;231 compilebutton.click();232 }233 else{234 if(runTerminator){235 runTerminator();236 }237 var to_terminate=false;238 runTerminator=function(success){239 to_terminate=true;240 breakpointBuffer=undefined;241 globalPauseBuffer=undefined;242 hide_execution_only_buttons();243 codeEditor.setReadOnly(false);244 if(!success&&processHandler){245 processHandler.terminate();246 processHandler=undefined;247 }248 };249 executionSpan.firstChild.nodeValue="Executingâ¦";250 var start_time=Date.now();251 if(interactive==="no"){252 processHandler.execute(inputEditor.getValue(),{debug:(compilemode==="debug")},function(message){253 if(!to_terminate){254 runTerminator(true);255 runTerminator=undefined;256 if(message.success){257 var end_time=Date.now();258 codeEditor.setReadOnly(false);259 outputEditor.setValue(message.output,1);260 console.log("Executed in "+Math.round(end_time-start_time)+" ms.");261 executionSpan.firstChild.nodeValue="Executed in "+Math.round(end_time-start_time)+" ms.";262 }263 else{264 executionSpan.firstChild.nodeValue="Execution failed.";265 }266 }267 });268 }269 else{270 if(compilemode!=="debug"){271 interactiveConsole.clear();272 interactiveConsole.focus();273 var interactiveObj=processHandler.executeInteractive({debug:(compilemode==="debug")},function(){274 if(!to_terminate){275 interactiveConsole.read(function(text){276 interactiveObj.inputAddedCallback(text);277 });278 }279 },function(outputText){280 if(!to_terminate){281 interactiveConsole.write(outputText);282 }283 },function(message){284 if(!to_terminate){285 runTerminator(true);286 runTerminator=undefined;287 codeEditor.setReadOnly(false);288 if(message.success){289 var end_time=Date.now();290 //outputEditor.setValue(message.output,1);291 console.log("Executed in "+Math.round(end_time-start_time)+" ms.");292 executionSpan.firstChild.nodeValue="Executed in "+Math.round(end_time-start_time)+" ms.";293 }294 else{295 executionSpan.firstChild.nodeValue="Execution failed.";296 }297 }298 });299 show_execution_only_buttons(false);300 }301 else{302 interactiveConsole.clear();303 interactiveConsole.focus();304 breakpointBuffer=new SharedArrayBuffer(codeEditor.getValue().length);305 globalPauseBuffer=new SharedArrayBuffer(1);306 // populate the breakpoints:307 var bp_arr=new Uint8Array(breakpointBuffer);308 var codeEditorDocument=codeEditor.getSession().getDocument();309 breakpoints.forEach(function(bp){310 Atomics.store(bp_arr,codeEditorDocument.positionToIndex(bp.anchor.getPosition()),1);311 });312 313 314 var interactiveObj=processHandler.executeInteractive({debug:(compilemode==="debug"),sourcecode:codeEditor.getValue(),breakpointBuffer:breakpointBuffer,globalPauseBuffer:globalPauseBuffer},function(){315 if(!to_terminate){316 interactiveConsole.read(function(text){317 interactiveObj.inputAddedCallback(text);318 });319 }320 },function(outputText){321 if(!to_terminate){322 interactiveConsole.write(outputText);323 }324 },function(message){325 if(!to_terminate){326 runTerminator(true);327 runTerminator=undefined;328 if(message.success){329 var end_time=Date.now();330 //outputEditor.setValue(message.output,1);331 console.log("Executed in "+Math.round(end_time-start_time)+" ms.");332 executionSpan.firstChild.nodeValue="Executed in "+Math.round(end_time-start_time)+" ms.";333 }334 else if(message.data.type==="parseerror"){335 executionSpan.firstChild.nodeValue="";336 compilationSpan.firstChild.nodeValue="Parsing failed, there may be unmatched brackets.";337 }338 else if(message.data.type==="runtimeerror"){339 executionSpan.firstChild.nodeValue="Runtime error.";340 }341 else{342 executionSpan.firstChild.nodeValue="Execution failed.";343 }344 }345 },function(options){346 if(options.breakpoint){347 console.log("Breakpoint hit.");348 }349 else{350 console.log("Execution paused.");351 }352 draw_execution_paused(options.index,options.memoryuint8array,options.memory_ptr);353 continuehandler=options.resume;354 });355 show_execution_only_buttons(true);356 }357 }358 }359 });360 361 stopbutton.addEventListener("click",function(){362 if(runTerminator)runTerminator();363 console.log("Execution stopped.");364 executionSpan.firstChild.nodeValue="Execution stopped.";365 });366 367 368 var continuehandler=undefined;369 var stephandler=undefined;370 var execution_is_paused=false;371 372 373 continuebutton.addEventListener("click",function(){374 if(runTerminator){ // check if code is currently running375 if(execution_is_paused){376 if(continuehandler&&globalPauseBuffer){377 // turn off the global pauser378 var arr=new Uint8Array(globalPauseBuffer);379 Atomics.store(arr,0,0);380 undraw_execution_paused();381 continuehandler();382 }383 }384 else{385 // turn on the global pauser386 var arr=new Uint8Array(globalPauseBuffer);387 Atomics.store(arr,0,1);388 }389 }390 });391 stepbutton.addEventListener("click",function(){392 if(runTerminator){ // check if code is currently running393 if(execution_is_paused){394 if(continuehandler&&globalPauseBuffer){395 // turn off the global pauser396 var arr=new Uint8Array(globalPauseBuffer);397 Atomics.store(arr,0,1);398 continuehandler();399 }400 }401 }402 });403 404 405 // breakpoints406 codeEditor.on("mousedown",function(e){407 if(e.getButton()===1){408 window.setTimeout(function(){409 var pos=codeEditor.getCursorPosition();410 var session=codeEditor.getSession();411 var document=session.getDocument();412 var Range=ace.require('ace/range').Range;413 var range=new Range();414 range.start=document.createAnchor(pos.row,pos.column);415 range.end=document.createAnchor(pos.row,pos.column+1);416 var fix_valid_range=function(r){417 var endpos=r.end.getPosition();418 var startpos=r.start.getPosition();419 if(endpos.row!==startpos.row)return false;420 if(endpos.column<=startpos.column)return false;421 if(startpos.column+1!==endpos.column){422 r.end.setPosition(startpos.row,startpos.column+1);423 codeEditor.updateSelectionMarkers();424 }425 return true;426 };427 var oldbp_index=breakpoints.findIndex(function(x){428 var x_pos=x.anchor.getPosition();429 return x_pos.row===pos.row&&x_pos.column===pos.column;430 });431 var remove_bp=function(oldbp){432 session.removeMarker(oldbp.id);433 breakpoints.splice(oldbp_index,1);434 if(breakpointBuffer){435 var arr=new Uint8Array(breakpointBuffer);436 Atomics.store(arr,document.positionToIndex(oldbp.anchor.getPosition()),0);437 }438 };439 if(oldbp_index!==-1){440 var oldbp=breakpoints[oldbp_index];441 remove_bp(oldbp);442 }443 else{444 if(fix_valid_range(range)&&"<>+-[].,".includes(document.getTextRange(range))){445 var id=session.addMarker(range,"breakpoint","text",false);446 var oldbp={anchor:range.start,id:id};447 breakpoints.push(oldbp);448 if(breakpointBuffer){449 var arr=new Uint8Array(breakpointBuffer);450 Atomics.store(arr,document.positionToIndex(pos),1);451 }452 var anchor_changed=function(){453 window.setTimeout(function(){454 if(!fix_valid_range(range)){455 remove_bp(oldbp);456 }457 },0);458 };459 range.start.on("change",anchor_changed);460 range.end.on("change",anchor_changed);461 }462 }463 },0);464 }465 });466 var execution_location_marker_id=undefined,execution_location_line_id=undefined;467 var draw_execution_paused=function(index,memoryuint8array,memory_ptr){468 undraw_execution_paused();469 var Range=ace.require('ace/range').Range;470 var pos=codeEditor.getSession().getDocument().indexToPosition(index);471 var range=new Range(pos.row,pos.column,pos.row,pos.column+1);472 execution_location_marker_id=codeEditor.getSession().addMarker(range,"execution-position","text",false);473 var range=new Range(pos.row,0,pos.row,Number.POSITIVE_INFINITY);474 execution_location_line_id=codeEditor.getSession().addMarker(range,"execution-line","fullLine",false);475 codeEditor.scrollToLine(pos.row,true,false,function(){});476 477 var ic_classlist=continuebutton.getElementsByClassName("jelly-icon")[0].classList;478 ic_classlist.remove("jelly-icon-pause");479 ic_classlist.add("jelly-icon-run");480 {481 var nn=continuebutton.getElementsByClassName("button-name")[0];482 while(nn.firstChild)nn.removeChild(nn.firstChild);483 nn.appendChild(document.createTextNode("Continue"));484 }485 execution_is_paused=true;486 stepbutton.classList.remove("displaynone");487 memoryview.classList.remove("displaynone");488 codeEditor.resize();489 memoryviewmanager=new MemoryView(memoryview.getElementsByClassName("memory-cells")[0],memoryuint8array,0,29999,memory_ptr);490 };491 var undraw_execution_paused=function(){492 if(execution_location_marker_id!==undefined)codeEditor.getSession().removeMarker(execution_location_marker_id);493 if(execution_location_line_id!==undefined)codeEditor.getSession().removeMarker(execution_location_line_id);494 495 var ic_classlist=continuebutton.getElementsByClassName("jelly-icon")[0].classList;496 ic_classlist.remove("jelly-icon-run");497 ic_classlist.add("jelly-icon-pause");498 {499 var nn=continuebutton.getElementsByClassName("button-name")[0];500 while(nn.firstChild)nn.removeChild(nn.firstChild);501 nn.appendChild(document.createTextNode("Pause"));502 }503 execution_is_paused=false;504 stepbutton.classList.add("displaynone");505 memoryview.classList.add("displaynone");506 codeEditor.resize();507 if(memoryviewmanager){508 memoryviewmanager.clear();509 memoryviewmanager=undefined;510 }511 };512 513 514 515 // memoryview buttons/functions516 var cast_int_range=function(str,minval,maxval){517 var k=parseInt(str);518 if(k.toString()!==str)return undefined;519 if(k<minval||k>maxval)return undefined;520 return k;521 };522 memoryview.getElementsByClassName("left-arrow")[0].addEventListener("click",function(){523 if(memoryviewmanager)memoryviewmanager.goSmaller();524 });525 memoryview.getElementsByClassName("right-arrow")[0].addEventListener("click",function(){526 if(memoryviewmanager)memoryviewmanager.goLarger();527 });528 Array.prototype.forEach.call(memoryview.getElementsByClassName("goto"),function(el){529 var el_input=el.getElementsByTagName("input")[0];530 el_input.addEventListener("keyup",function(e){531 if(memoryviewmanager&&e.key==="Enter"){532 var str=el_input.value;533 var target=cast_int_range(str,memoryviewmanager.minIndex,memoryviewmanager.maxIndex);534 if(target!==undefined){535 memoryviewmanager.goToIndex(target);536 }537 else{538 alert("Cannot interpret \""+str+"\" as cell index!");539 }540 el_input.value="";541 }542 });543 });544 545 546 547 // options548 var radio_interactive_yes=document.getElementById("radio-interactive-yes");549 var radio_interactive_no=document.getElementById("radio-interactive-no");550 551 var ioblock=document.getElementById("ioblock");552 var separate_ioblock=ioblock.getElementsByClassName("separate")[0];553 var combined_ioblock=ioblock.getElementsByClassName("combined")[0];554 555 radio_interactive_yes.addEventListener("change",function(){556 separate_ioblock.classList.remove("selected");557 combined_ioblock.classList.add("selected");558 interactive="yes";559 localStorage.setItem("option-interactive",interactive);560 executemodes_changed();561 });562 radio_interactive_no.addEventListener("change",function(){563 combined_ioblock.classList.remove("selected");564 separate_ioblock.classList.add("selected");565 interactive="no";566 localStorage.setItem("option-interactive",interactive);567 executemodes_changed();568 });569 570 var interactive=localStorage.getItem("option-interactive");571 if(interactive==="no"||!window.SharedArrayBuffer){572 radio_interactive_no.checked=true;573 radio_interactive_no.dispatchEvent(new Event("change"));574 }575 else{576 radio_interactive_yes.checked=true;577 radio_interactive_yes.dispatchEvent(new Event("change"));578 }579 580 if(!window.SharedArrayBuffer){581 radio_interactive_yes.disabled=true;582 }583 584 var radio_compilemode_debug=document.getElementById("radio-compilemode-debug");585 var radio_compilemode_release=document.getElementById("radio-compilemode-release");586 587 radio_compilemode_debug.addEventListener("change",function(){588 compilemode="debug";589 localStorage.setItem("option-compilemode",compilemode);590 compilemodes_changed();591 });592 radio_compilemode_release.addEventListener("change",function(){593 compilemode="release";594 localStorage.setItem("option-compilemode",compilemode);595 compilemodes_changed();596 });597 598 var compilemode=localStorage.getItem("option-compilemode");599 if(compilemode==="debug"){600 radio_compilemode_debug.checked=true;601 radio_compilemode_debug.dispatchEvent(new Event("change"));602 }603 else{604 radio_compilemode_release.checked=true;605 radio_compilemode_release.dispatchEvent(new Event("change"));606 }607 608 609 // splitters610 Array.prototype.forEach.call(document.getElementById("ioblock").getElementsByClassName("vertical-spacer"),function(el){611 var splitter=new FlexSplitter(el,el.getElementsByClassName("actual-spacer")[0],0.1,0.1);612 splitter.onadjust=function(){613 inputEditor.resize();614 outputEditor.resize();615 };616 });617 Array.prototype.forEach.call(document.getElementsByClassName("horizontal-spacer"),function(el){618 var splitter=new FlexSplitter(el,el.getElementsByClassName("actual-spacer")[0],0.1,0.1);619 splitter.onadjust=function(){620 codeEditor.resize();621 inputEditor.resize();622 outputEditor.resize();623 };624 });625 626 627 628 // buttons629 var show_execution_only_buttons=function(show_debug){630 Array.prototype.forEach.call(document.getElementsByClassName("execution-only"),function(el){if(show_debug||!el.classList.contains("debug-only"))el.classList.remove("displaynone");});631 };632 var hide_execution_only_buttons=function(){633 Array.prototype.forEach.call(document.getElementsByClassName("execution-only"),function(el){el.classList.add("displaynone");});634 undraw_execution_paused();635 };...
EditorContainer.js
Source:EditorContainer.js
1import React, { Component } from 'react';2import ReactDOM from 'react-dom';3import PropTypes from 'prop-types';4import FileSaver from 'file-saver';5import { NotificationStack } from 'react-notification';6import { OrderedSet } from 'immutable';7import SplitPane from 'react-split-pane';8import { throttle } from 'throttle-debounce';9import Editor from '../Components/Editor';10import ToolbarContainer from './ToolbarContainer';11import FooterContainer from './FooterContainer';12import {13 CompileMode,14 CompilerDescriptions,15 formatCode,16 formatSize,17 getCompilerVersion,18 isRequreStdlib,19} from '../Common/Common';20const AutoCompilationDelay = 800; //ms21const MaxPrintingErrors = 8;22const SplitGripWidth = 5;23export default class EditorContainer extends Component {24 static defaultProps = {25 compiler: 'AssemblyScript'26 }27 static propTypes = {28 compiler: PropTypes.string29 }30 constructor(props) {31 super(props);32 this.state = {33 version: '0.0.0',34 compiler: props.compiler,35 compileMode: CompileMode.Auto,36 compilerReady: false,37 // compileFailure: false,38 compileState: 'pending',39 // compileSuccess: false,40 splitPosition: 0.62,41 additionalStatusMessage: '',42 inputEditorWidth: '100%',43 outputEditorWidth: '100%',44 editorsHeight: '750px',45 input: CompilerDescriptions[props.compiler].example.trim(),46 output: {47 text: '',48 binary: null49 },50 outputType: 'text',51 // settings52 validate: true,53 optimize: true,54 longMode: false,55 unsafe: true,56 base64: false,57 annotations: OrderedSet(),58 notifications: OrderedSet(),59 notificationCount: 0,60 inputCursorPosition: [1, 1]61 };62 this._errorCount = 0;63 this._lastTextInput = '';64 this._compileTimerDelay = null;65 this._cachedClientRect = null;66 }67 componentDidMount() {68 this.updateWindowDimensions();69 window.addEventListener("resize", this.updateWindowDimensions);70 this.changeCompiler();71 }72 componentWillUnmount() {73 window.removeEventListener("resize", this.updateWindowDimensions);74 }75 updateWindowDimensions = () => {76 this._cachedClientRect = null;77 this.handleSize();78 }79 _clearCompileTimeout() {80 this._compileTimerDelay && clearTimeout(this._compileTimerDelay);81 this._compileTimerDelay = null;82 }83 updateCompilationWithDelay = (delay = 5000) => {84 this._clearCompileTimeout();85 this._compileTimerDelay = setTimeout(() => {86 this.updateCompilation();87 this._compileTimerDelay = null;88 }, delay);89 }90 updateCompilation = () => {91 if (!this.inputEditor) return;92 //console.clear();93 // clean errors and messages94 this._errorCount = 0;95 this.removeAllNotifications();96 this.removeAllAnnotation();97 this.setState({98 additionalStatusMessage: ''99 });100 const {101 compiler,102 longMode,103 validate,104 optimize,105 unsafe106 } = this.state;107 const inputCode = this.inputEditor.state.value;108 if (this.toolbar && this.toolbar.compileButton) {109 this.toolbar.compileButton.startCompile();110 this.setState({ compileStatus: 'compiling' });111 }112 setImmediate(() => {113 try {114 switch (compiler) {115 case 'AssemblyScript':116 const stdlib = isRequreStdlib(inputCode);117 this.compileByAssemblyScript(inputCode, {118 noMemory: !stdlib,119 longMode,120 validate,121 optimize122 });123 break;124 case 'Speedy.js':125 this.compileBySpeedyJs(inputCode, {126 unsafe,127 optimizationLevel: optimize ? 3 : 0,128 saveWast: true129 });130 break;131 default: console.warn('Compiler not supported');132 }133 } catch (e) {134 this.setState({ compileStatus: 'failure' });135 this._errorCount = 1;136 const message = '<' + compiler + '> internal error: ';137 this.addNotification(message + e.message);138 console.error(message, e);139 this.setState({140 additionalStatusMessage: message + e.message141 });142 } finally {143 if (this.toolbar && this.toolbar.compileButton)144 this.toolbar.compileButton.endCompile();145 }146 });147 }148 compileByAssemblyScript(code, { noMemory, longMode, validate, optimize }) {149 const as = window.assemblyscript;150 const options = as.createOptions();151 as.setTarget(options, +longMode);152 as.setNoTreeShaking(options, false);153 as.setNoAssert(options, false);154 as.setNoMemory(options, noMemory);155 const parser = as.parseFile(code, 'index.ts', null, true);156 const module = as.compile(parser, options);157 const checkDiagnostics = (parser) => {158 let diagnostic, index = 0;159 let hasErrors = false;160 while ((diagnostic = as.nextDiagnostic(parser)) != null) {161 let errorMessage = as.formatDiagnostic(diagnostic, false, true);162 if (index <= MaxPrintingErrors) {163 console.error(errorMessage);164 this.addNotification(errorMessage);165 this.addAnnotation(errorMessage);166 } else {167 errorMessage = 'Too many errors';168 console.error(errorMessage);169 this.addNotification(errorMessage);170 hasErrors = true;171 break;172 }173 if (as.isError(diagnostic)) {174 hasErrors = true;175 }176 index++;177 this._errorCount = index;178 }179 return hasErrors;180 }181 setImmediate(() => {182 if (!module || checkDiagnostics(parser)) {183 this.setState({ compileStatus: 'failure' });184 return;185 }186 // hardcoded for now187 module.runPasses([ "trap-mode-clamp" ]);188 module.setOptimizeLevel(3);189 module.setShrinkLevel(0);190 setImmediate(() => {191 if (validate) {192 if (!module.validate()) {193 let notValid = 'Code validation error';194 console.error(notValid);195 this.addNotification(notValid);196 this._errorCount = 1;197 this.setState({198 compileStatus: 'failure',199 additionalStatusMessage: notValid200 });201 module.dispose();202 return;203 }204 }205 if (optimize)206 module.optimize();207 this._errorCount = 0;208 setImmediate(() => {209 const text = module.toText();210 const {211 output: binary,212 } = module.toBinary();213 this.setState({214 compileStatus: 'success',215 output: { text, binary },216 });217 module.dispose();218 });219 });220 });221 }222 compileBySpeedyJs(code, options) {223 CompilerDescriptions['Speedy.js'].compile(code, options)224 .then(response => {225 if (this.state.compiler !== 'Speedy.js') return;226 if (response.length) {227 const output = response[0];228 if (output.exitStatus !== 0) {229 this.setState({ compileStatus: 'failure' });230 // compiled failure231 const diagnostics = output.diagnostics;232 this._errorCount = diagnostics.length;233 for (let i = 0; i < diagnostics.length; i++) {234 let errorMessage = diagnostics[i];235 if (i <= MaxPrintingErrors) {236 console.error(errorMessage);237 this.addNotification(errorMessage);238 this.addAnnotation(errorMessage);239 } else {240 errorMessage = `Too many errors (${diagnostics.length})`;241 console.error(errorMessage);242 this.addNotification(errorMessage);243 break;244 }245 }246 } else {247 this._errorCount = 0;248 // compiled successfully249 this.setState({250 compileStatus: 'success',251 output: {252 text: output.wast || '',253 binary: new Uint8Array(output.wasm)254 }255 });256 }257 }258 })259 .catch(error => {260 this.setState({ compileStatus: 'failure' });261 this._errorCount = 1;262 const message = '<' + this.state.compiler + '> Service not response';263 this.addNotification(message);264 console.error(message);265 });266 }267 onInputChange = value => {268 // skip compilation if possible269 value = value.trim();270 if (this._lastTextInput !== value) {271 if (this.state.compileMode === CompileMode.Auto)272 this.updateCompilationWithDelay(AutoCompilationDelay);273 this._lastTextInput = value;274 }275 }276 onInputPositionChange = inputCursorPosition => {277 this.setState({ inputCursorPosition });278 }279 onDownloadBinary = () => {280 const { output, compiler } = this.state;281 var blob = new Blob([output.binary], { type: "application/octet-stream" });282 FileSaver.saveAs(blob, `${compiler.toLowerCase()}.module.wasm`);283 }284 changeCompiler = compiler => {285 this._errorCount = 0;286 this._lastTextInput = '';287 this._compileTimerDelay = null;288 compiler = compiler || this.state.compiler;289 const description = CompilerDescriptions[compiler];290 this.setState({291 compiler,292 input: description.example.trim(),293 }, () => {294 if (description.offline) {295 if (!description.loaded && description.scripts && description.scripts.length) {296 if (description.scripts.length > 1) {297 window.$script.order(description.scripts.slice(), () => {298 description.loaded = true;299 this.onScriptLoad();300 });301 } else {302 window.$script(description.scripts[0], () => {303 description.loaded = true;304 this.onScriptLoad();305 });306 }307 } else {308 this.onScriptLoad();309 }310 } else {311 this.onScriptLoad();312 }313 });314 }315 onScriptLoad() {316 this.setState({ compilerReady: true }, () => {317 getCompilerVersion(this.state.compiler, version => this.setState({ version }));318 this.updateCompilation();319 });320 }321 onScriptError = () => {322 console.error('Script not load');323 this.setState({324 compilerReady: false,325 });326 }327 onSplitPositionChange = size => {328 this.handleSize(size);329 }330 onCompileButtonClick = mode => {331 this._clearCompileTimeout();332 if (mode === CompileMode.Auto || mode === CompileMode.Manual)333 this.updateCompilation();334 }335 onSettingsOptionChange = (key, value) => {336 if (!this.state.compilerReady) return;337 this.setState({ [key]: value }, key !== 'base64' ? this.updateCompilation : null);338 }339 handleSize = throttle(8, size => {340 if (this.splitEditor) {341 if (!this._cachedClientRect)342 this._cachedClientRect = ReactDOM.findDOMNode(this.splitEditor).getBoundingClientRect();343 const { width, height } = this._cachedClientRect;344 const pos = (size ? size / width : this.state.splitPosition);345 const primaryWidth = width * pos;346 this.setState({347 inputEditorWidth: Math.ceil(primaryWidth),348 outputEditorWidth: Math.ceil(width - primaryWidth - SplitGripWidth),349 editorsHeight: height - 160,350 splitPosition: pos,351 });352 this.splitEditor.setSize(353 { primary: 'first', size: primaryWidth },354 { draggedSize: primaryWidth }355 );356 }357 })358 addNotification = (message) => {359 // skip notifications for Auto compile mode360 // if (this.state.compileMode === CompileMode.Auto) {361 // return;362 // }363 const {364 notifications,365 notificationCount,366 } = this.state;367 const id = notifications.size + 1;368 const newCount = notificationCount + 1;369 return this.setState({370 notificationCount: newCount,371 notifications: notifications.add({372 id,373 message,374 key: newCount,375 action: 'â',376 dismissAfter: 5000,377 actionStyle: {378 borderRadius: 0,379 paddingLeft: '1.5rem',380 paddingRight: '0.6rem',381 fontSize: '1.8rem',382 color: '#fff',383 },384 onClick: this.removeAllNotifications,385 })386 });387 }388 addAnnotation = (message, type = 'error') => {389 const posRegex = /[{([]\s*(\d+)\s*,\s*(\d+)\s*[\])}]$/;390 const matches = posRegex.exec(message);391 if (matches && matches.length === 3) {392 var row = matches[1] >>> 0;393 // var column = matches[2] >>> 0;394 this.setState(({ annotations }) => ({395 annotations: annotations.add({ row, type, text: message }),396 }));397 }398 }399 removeAllAnnotation = () => {400 this.setState({ annotations: OrderedSet() });401 }402 removeNotification = index => {403 const { notifications } = this.state;404 return this.setState({405 notifications: notifications.filter(n => n.key !== index),406 })407 }408 removeAllNotifications = () => {409 return this.setState({410 notificationCount: 0,411 notifications: OrderedSet(),412 });413 }414 render() {415 const {416 version,417 compiler,418 compilerReady,419 compileStatus,420 notifications,421 annotations,422 additionalStatusMessage,423 splitPosition,424 inputEditorWidth,425 outputEditorWidth,426 editorsHeight,427 input,428 output,429 outputType,430 base64,431 inputCursorPosition,432 } = this.state;433 function notificationStyle(index, style, notification) {434 return {435 zOrder: 999,436 color: '#fff',437 background: '#f00',438 fontSize: '1.5rem',439 padding: '1.2em',440 paddingLeft: '1.8em',441 borderRadius: 0,442 left: '5.3em',443 bottom: `${4.2 + (index * 3.6)}em`444 };445 }446 const errorNotifications = notifications ? (<NotificationStack447 activeBarStyleFactory={ notificationStyle }448 notifications={ notifications.toArray() }449 onDismiss={ notification => this.setState({450 notifications: this.state.notifications.delete(notification)451 }) }452 />) : null;453 const canBinaryDownload = (454 compilerReady &&455 compileStatus === 'success' &&456 output.binary457 );458 let busyState = 'pending';459 if (compilerReady) {460 switch (compileStatus) {461 case 'success': busyState = 'success'; break;462 case 'failure': busyState = 'failure'; break;463 default: break;464 }465 }466 return (467 <div>468 <ToolbarContainer469 ref={ self => this.toolbar = self }470 version={ version }471 compiler={ compiler }472 compileDisabled={ !compilerReady }473 onCompilerChange={ this.changeCompiler }474 onCompileClick={ this.onCompileButtonClick }475 onCompileModeChange={ mode => {476 this._clearCompileTimeout();477 this.setState({ compileMode: mode });478 if (mode === CompileMode.Auto)479 this.updateCompilationWithDelay(AutoCompilationDelay);480 }}481 onSettingsOptionChange={ this.onSettingsOptionChange }482 onOutputSelect={ type => this.setState({ outputType: type }) }483 />484 <SplitPane485 ref={ self => this.splitEditor = self }486 split="vertical"487 minSize={ 200 }488 defaultSize={ splitPosition * 100 + '%' }489 onChange={ this.onSplitPositionChange }490 style={{491 margin: '12px',492 }}493 >494 <Editor495 focus496 id="input"497 ref={ self => this.inputEditor = self }498 width={ inputEditorWidth }499 height={ editorsHeight }500 code={ input }501 annotations={ annotations.toArray() }502 onChange={ this.onInputChange }503 onPositionChange={ this.onInputPositionChange }504 />505 <Editor506 readOnly507 id="output"508 mode={ outputType === 'text' ? 'wast' : 'typescript' }509 ref={ self => this.outputEditor = self }510 width={ outputEditorWidth }511 height={ editorsHeight }512 code={ formatCode(output[outputType], base64) }513 />514 </SplitPane>515 <FooterContainer516 errorCount={ this._errorCount }517 busyState={ busyState }518 binarySize={ output.binary ? formatSize(output.binary.length) : '' }519 onDownloadPressed={ this.onDownloadBinary }520 downloadDisabled={ !canBinaryDownload }521 errorMessage={ additionalStatusMessage }522 cursorPosition={ inputCursorPosition }523 />524 { errorNotifications }525 </div>526 );527 }...
compile.ts
Source:compile.ts
1#!/usr/bin/env node2import fse from "fs-extra";3import minimist from "minimist";4import path from "path";5import {6 ASTKind,7 ASTNodeCallback,8 ASTNodeFormatter,9 ASTReader,10 ASTWriter,11 CACHE_DIR,12 CompilationOutput,13 CompileFailedError,14 compileJson,15 compileJsonData,16 CompileResult,17 CompilerKind,18 CompilerVersions,19 compileSol,20 compileSourceString,21 ContractDefinition,22 DefaultASTWriterMapping,23 FunctionDefinition,24 FunctionVisibility,25 getABIEncoderVersion,26 isExact,27 LatestCompilerVersion,28 PossibleCompilerKinds,29 PrettyFormatter,30 SourceUnit,31 StateVariableVisibility,32 VariableDeclaration,33 XPath34} from "..";35enum CompileMode {36 Auto = "auto",37 Sol = "sol",38 Json = "json"39}40const compileModes = Object.values(CompileMode);41const cli = {42 boolean: [43 "version",44 "help",45 "solidity-versions",46 "stdin",47 "raw",48 "with-sources",49 "tree",50 "source",51 "locate-compiler-cache"52 ],53 number: ["depth"],54 string: [55 "mode",56 "compiler-version",57 "path-remapping",58 "xpath",59 "compiler-settings",60 "compiler-kind"61 ],62 default: {63 depth: Number.MAX_SAFE_INTEGER,64 mode: CompileMode.Auto,65 "compiler-version": "auto",66 "compiler-kind": CompilerKind.WASM67 }68};69(async function () {70 const args = minimist(process.argv.slice(2), cli);71 if (args.version) {72 const { version } = require("../../package.json");73 console.log(version);74 } else if (args["solidity-versions"]) {75 const message = [76 "Latest supported version: " + LatestCompilerVersion,77 "",78 `All supported versions (${CompilerVersions.length} total):`,79 ...CompilerVersions80 ].join("\n");81 console.log(message);82 } else if (args["locate-compiler-cache"]) {83 console.log(CACHE_DIR);84 } else if (args.help || (!args._.length && !args.stdin)) {85 const message = `Compiles Solidity input and prints typed AST.86USAGE:87$ sol-ast-compile <filename>88OPTIONS:89 --help Print help message.90 --version Print package version.91 --solidity-versions Print information about supported Solidity versions.92 --stdin Read input from STDIN instead of files.93 Requires "mode" to be explicitly set to "${CompileMode.Sol}" or "${CompileMode.Json}".94 --mode One of the following input types:95 - ${CompileMode.Sol} (Solidity source)96 - ${CompileMode.Json} (JSON compiler artifact)97 - ${CompileMode.Auto} (try to detect by file extension)98 Default value: ${cli.default.mode}99 --compiler-version Solc version to use:100 - ${LatestCompilerVersion} (exact SemVer version specifier)101 - auto (try to detect suitable compiler version)102 Default value: ${cli.default["compiler-version"]}103 --compiler-kind What type of Solidity compiler to use. Currently supported values are 'wasm' and 'native'.104 Default value: ${cli.default["compiler-kind"]}105 --path-remapping Path remapping input for Solc.106 --compiler-settings Additional settings passed to the solc compiler in the form of a107 JSON string (e.g. '{"optimizer": {"enabled": true, "runs": 200}}').108 Note the double quotes. For more details see https://docs.soliditylang.org/en/latest/using-the-compiler.html#input-description.109 --raw Print raw Solc compilation output.110 --with-sources When used with "raw", adds "source" property with 111 source files content to the compiler artifact.112 --tree Print short tree of parent-child relations in AST.113 --source Print source code, assembled from Solc-generated AST.114 --xpath XPath selector to perform for each source unit.115 --depth Number of children for each of AST node to print.116 Minimum value is 0. Not affects "raw", "tree" and "source".117 Default value: ${cli.default.depth}118 --locate-compiler-cache Print location of cache directory, that is used to store downloaded compilers.119`;120 console.log(message);121 } else {122 const stdin: boolean = args.stdin;123 const mode: CompileMode = args.mode;124 const compilerKind: CompilerKind = args["compiler-kind"];125 if (!PossibleCompilerKinds.has(compilerKind)) {126 throw new Error(127 `Invalid compiler kind "${compilerKind}". Possible values: ${[128 ...PossibleCompilerKinds.values()129 ].join(", ")}.`130 );131 }132 if (!compileModes.includes(mode)) {133 throw new Error(`Invalid mode "${mode}". Possible values: ${compileModes.join(", ")}.`);134 }135 const compilerVersion: string = args["compiler-version"];136 if (!(compilerVersion === "auto" || isExact(compilerVersion))) {137 const message = [138 `Invalid compiler version "${compilerVersion}".`,139 'Possible values: "auto" or exact version string.'140 ].join(" ");141 throw new Error(message);142 }143 const pathRemapping: string[] = args["path-remapping"]144 ? args["path-remapping"].split(";")145 : [];146 let compilerSettings: any = undefined;147 if (args["compiler-settings"]) {148 try {149 compilerSettings = JSON.parse(args["compiler-settings"]);150 } catch (e) {151 throw new Error(152 `Invalid compiler settings '${args["compiler-settings"]}'. Compiler settings must be a valid JSON object.(${e})`153 );154 }155 }156 const compilationOutput: CompilationOutput[] = [CompilationOutput.ALL];157 let result: CompileResult;158 try {159 if (stdin) {160 if (mode === "auto") {161 throw new Error(162 'Mode "auto" is not supported for the input from STDIN. Explicitly specify "mode" as "sol" or "json" instead.'163 );164 }165 const fileName = "stdin";166 const content = await fse.readFile(0, { encoding: "utf-8" });167 result =168 mode === "json"169 ? await compileJsonData(170 fileName,171 JSON.parse(content),172 compilerVersion,173 compilationOutput,174 compilerSettings,175 compilerKind176 )177 : await compileSourceString(178 fileName,179 content,180 compilerVersion,181 pathRemapping,182 compilationOutput,183 compilerSettings,184 compilerKind185 );186 } else {187 const fileNames = args._.map((fileName) => path.resolve(fileName));188 const singleFileName = fileNames[0];189 const iSingleFileName = singleFileName.toLowerCase();190 let isSol: boolean;191 let isJson: boolean;192 if (mode === "auto") {193 isSol = iSingleFileName.endsWith(".sol");194 isJson = iSingleFileName.endsWith(".json");195 } else {196 isSol = mode === "sol";197 isJson = mode === "json";198 }199 if (isSol) {200 result = await compileSol(201 fileNames,202 compilerVersion,203 pathRemapping,204 compilationOutput,205 compilerSettings,206 compilerKind207 );208 } else if (isJson) {209 result = await compileJson(210 singleFileName,211 compilerVersion,212 compilationOutput,213 compilerSettings,214 compilerKind215 );216 } else {217 throw new Error(218 "Unable to auto-detect mode by the file name: " + singleFileName219 );220 }221 }222 } catch (e) {223 if (e instanceof CompileFailedError) {224 console.error("Compile errors encountered:");225 for (const failure of e.failures) {226 console.error(227 failure.compilerVersion228 ? `SolcJS ${failure.compilerVersion}:`229 : "Unknown compiler:"230 );231 for (const error of failure.errors) {232 console.error(error);233 }234 }235 process.exit(1);236 }237 throw e;238 }239 const { data, files } = result;240 if (args.raw) {241 if (args["with-sources"] && files.size > 0) {242 if (!data.sources) {243 data.sources = {};244 }245 for (const [key, value] of files) {246 if (!data.sources[key]) {247 data.sources[key] = {};248 }249 data.sources[key].source = value;250 }251 }252 const output = JSON.stringify(data, undefined, 4);253 console.log(output);254 process.exit(0);255 }256 const separator = "-".repeat(60);257 const depth = args.depth;258 const reader = new ASTReader();259 const units = reader.read(data, ASTKind.Any, files);260 if (args.tree) {261 const INDENT = "| ";262 const encoderVersion = result.compilerVersion263 ? getABIEncoderVersion(units, result.compilerVersion as string)264 : undefined;265 const walker: ASTNodeCallback = (node) => {266 const level = node.getParents().length;267 const indent = INDENT.repeat(level);268 let message = node.type + " #" + node.id;269 if (node instanceof SourceUnit) {270 message += " -> " + node.absolutePath;271 } else if (node instanceof ContractDefinition) {272 message += " -> " + node.kind + " " + node.name;273 const interfaceId = encoderVersion274 ? node.interfaceId(encoderVersion)275 : undefined;276 if (interfaceId !== undefined) {277 message += ` [id: ${interfaceId}]`;278 }279 } else if (node instanceof FunctionDefinition) {280 const signature =281 node.vScope instanceof ContractDefinition &&282 (node.visibility === FunctionVisibility.Public ||283 node.visibility === FunctionVisibility.External) &&284 encoderVersion285 ? node.canonicalSignature(encoderVersion)286 : undefined;287 if (signature && encoderVersion) {288 const selector = node.canonicalSignatureHash(encoderVersion);289 message += ` -> ${signature} [selector: ${selector}]`;290 } else {291 message += ` -> ${node.kind}`;292 }293 } else if (node instanceof VariableDeclaration) {294 if (node.stateVariable) {295 message += ` -> ${node.typeString} ${node.visibility} ${node.name}`;296 if (node.visibility === StateVariableVisibility.Public) {297 const signature = encoderVersion298 ? node.getterCanonicalSignature(encoderVersion)299 : undefined;300 const selector = encoderVersion301 ? node.getterCanonicalSignatureHash(encoderVersion)302 : undefined;303 message += ` [getter: ${signature}, selector: ${selector}]`;304 }305 } else {306 message +=307 node.name === ""308 ? ` -> ${node.typeString}`309 : ` -> ${node.typeString} ${node.name}`;310 }311 }312 console.log(indent + message);313 };314 for (const unit of units) {315 unit.walk(walker);316 console.log();317 }318 process.exit(0);319 }320 if (args.xpath) {321 const selector = args.xpath;322 const formatter = new ASTNodeFormatter();323 for (const unit of units) {324 const xp = new XPath(unit);325 const queryResult = xp.query(selector);326 const output =327 queryResult instanceof Array328 ? queryResult.map((value) => formatter.format(value, depth)).join("\n")329 : formatter.format(queryResult, depth);330 console.log(unit.sourceEntryKey);331 console.log(separator);332 console.log(output);333 }334 process.exit(0);335 }336 if (args.source) {337 let targetCompilerVersion: string;338 if (result.compilerVersion) {339 targetCompilerVersion = result.compilerVersion;340 } else if (compilerVersion !== "auto") {341 targetCompilerVersion = compilerVersion;342 } else {343 targetCompilerVersion = LatestCompilerVersion;344 }345 const formatter = new PrettyFormatter(4, 0);346 const writer = new ASTWriter(DefaultASTWriterMapping, formatter, targetCompilerVersion);347 for (const unit of units) {348 console.log("// " + separator);349 console.log("// " + unit.absolutePath);350 console.log("// " + separator);351 console.log(writer.write(unit));352 }353 process.exit(0);354 }355 for (const unit of units) {356 console.log(unit.print(depth));357 }358 process.exit(0);359 }360})().catch((reason) => {361 console.error(reason);362 process.exit(1);...
gulpfile.js
Source:gulpfile.js
1//æ ¸å¿æ¨¡å2const gulp = require('gulp');3//less4const less = require('gulp-less');5//å缩工å
·6const connect = require('gulp-connect');7//å¼å
¥html8const contentIncluder = require('gulp-content-includer');9//å缩html10const htmlmin = require('gulp-htmlmin');11//å缩js12const uglify = require('gulp-uglify');13//å缩css14const minifycss = require('gulp-minify-css');15//æ件系ç»16const fs = require('fs');17//é¢è²è¾åº18const color = require('gulp-color');19//default config20var config = {21 src: 'src',22 dev: 'dev',23 prod: 'prod',24 ignoredir: ['block'],25 connectjs: false,26 connectcss: false,27 deletedcolor: 'RED',28 addedcolor: 'GREEN',29 changedcolor: 'YELLOW'30}31//é»è®¤æ§è¡å¼å模å¼32gulp.task('default', function() {33 tools.start('dev');34});35//æ§è¡å¼å模å¼36gulp.task('prod', function() {37 tools.start('prod');38});39const tools = {40 start: function(compilemode) {41 var _this = this;42 //读åé
ç½®æ件43 fs.readFile('config.json', function(err, data) {44 var conf = JSON.parse(data.toString());45 for (var f in conf) {46 config[f] = conf[f];47 }48 //å¼å§ç¼è¯49 _this.watchfile(compilemode);50 });51 },52 watchfile: function(compilemode) {53 //ç¼è¯54 var _this = this;55 console.log('gulp starting ' + new Date());56 console.log('Technical support by http://qie.suwis.com');57 tools.walk(config.src, 0, function(path, floor) {58 _this.complie(compilemode, path);59 //å¤æ模å¼å¦ææ¯äº§åæå
åä¸çå¬60 if (compilemode == 'prod') {61 return;62 }63 //å¨æçå¬æ件çåå64 //console.log(path);65 fs.stat(path, function(err, stats) {66 if (err) {67 console.log(err);68 return;69 }70 if (stats.isDirectory()) return;71 //çå¬æ件72 gulp.watch(path, function(evt) {73 evt.path = tools.replaceAll(evt.path, '\\', '/');74 var today = new Date();75 var h = today.getHours();76 var m = today.getMinutes();77 var s = today.getSeconds();78 today = h + ':' + m + ':' + s;79 //ä¿®æ¹oræ·»å 80 if (evt.type == 'changed' || evt.type == 'added') {81 _this.complie(compilemode, evt.path);82 if (evt.type == 'changed') {83 console.log(color('file ' + evt.type + ' path ' + evt.path + ' ' + today, config.changedcolor));84 } else {85 console.log(color('file ' + evt.type + ' path ' + evt.path + ' ' + today, config.addedcolor));86 }87 }88 //å¦ææ¯å é¤åä¸åä»»ä½å¤ç89 if (evt.type == 'deleted') {90 //æ¾å°è¢«å é¤çæ件91 var targetpath = evt.path.substring((evt.path.indexOf(config.src)), evt.path.length);92 targetpath = targetpath.replace(config.src, config.dev);93 console.log(color('file ' + evt.type + ' path ' + evt.path + ' ' + today, config.deletedcolor));94 //åæ¥å é¤æ件95 fs.unlink(targetpath, function(err) {96 if (err) console.log(color(err.error, config.deletedcolor));97 });98 }99 });100 });101 });102 },103 complie: function(compilemode, path) {104 //ç¼è¯105 var _this = this;106 //忽ç¥å¸¸è§ç项ç®æ§å¶æ件107 if (path.indexOf('.svn') >= 0 || path.indexOf('.git') >= 0 || path.indexOf('.project') >= 0) {108 return;109 }110 //忽ç¥èªå®ä¹çæ件夹111 var isignore = false;112 for (var f in config.ignoredir) {113 if (path.indexOf('/' + config.ignoredir[f] + '/') >= 0 || path.indexOf(config.ignoredir[f] + '/') >= 0) {114 isignore = true;115 break;116 }117 }118 if (isignore) return;119 var file = path.substring((path.lastIndexOf('/') + 1), path.length);120 var dir = config.src.substring(config.src.lastIndexOf('/'), config.src.length);121 var targetpath = path.substring((path.indexOf(dir) + 1), path.lastIndexOf('/'));122 if (targetpath.indexOf('/') != -1) {123 targetpath = targetpath.substring((targetpath.indexOf('/') + 1), targetpath.length);124 } else {125 targetpath = '';126 }127 //å¤ææ¯å¦æ¯æ件128 if (file.lastIndexOf('.') == -1) return;129 var suffix = file.substring((file.lastIndexOf('.') + 1), file.length);130 switch (suffix) {131 case 'html':132 _this[compilemode].html(path, targetpath);133 break;134 case 'css':135 _this[compilemode].css(path, targetpath);136 break;137 case 'less':138 _this[compilemode].less(path, targetpath);139 break;140 case 'js':141 _this[compilemode].js(path, targetpath);142 break;143 case 'jpg':144 _this[compilemode].imagemin(path, targetpath);145 break;146 case 'png':147 _this[compilemode].imagemin(path, targetpath);148 break;149 case 'svg':150 _this[compilemode].imagemin(path, targetpath);151 break;152 default:153 if (compilemode == 'dev') {154 gulp.src(path)155 .pipe(gulp.dest(config.dev + '/' + targetpath));156 }157 if (compilemode == 'prod') {158 gulp.src(path)159 .pipe(gulp.dest(config.prod + '/' + targetpath));160 }161 }162 },163 dev: {164 html: function(path, targetpath) {165 gulp.src(path)166 .pipe(contentIncluder({167 includerReg: /<!\-\-include\s+"([^"]+)"\-\->/g168 }))169 .pipe(gulp.dest(config.dev + '/' + targetpath));170 },171 css: function(path, targetpath) {172 gulp.src(path)173 .pipe(gulp.dest(config.dev + '/' + targetpath));174 },175 less: function(path, targetpath) {176 gulp.src(path)177 .pipe(less())178 .pipe(gulp.dest(config.dev + '/' + targetpath));179 },180 js: function(path, targetpath) {181 gulp.src(path)182 .pipe(gulp.dest(config.dev + '/' + targetpath));183 },184 imagemin: function(path, targetpath) {185 gulp.src(path)186 .pipe(gulp.dest(config.dev + '/' + targetpath));187 }188 },189 prod: {190 html: function(path, targetpath) {191 gulp.src(path)192 .pipe(contentIncluder({193 includerReg: /<!\-\-include\s+"([^"]+)"\-\->/g194 }))195 // .pipe(htmlmin({196 // collapseWhitespace: true197 // })) //å缩html198 .pipe(gulp.dest(config.prod + '/' + targetpath));199 },200 css: function(path, targetpath) {201 gulp.src(path)202 .pipe(minifycss()) //å缩css203 .pipe(gulp.dest(config.prod + '/' + targetpath));204 },205 less: function(path, targetpath) {206 gulp.src(path)207 .pipe(less()) //解æless208 .pipe(minifycss()) //å缩css209 .pipe(gulp.dest(config.dev + '/' + targetpath));210 },211 js: function(path, targetpath) {212 gulp.src(path)213 .pipe(uglify()) //å缩js214 .pipe(gulp.dest(config.prod + '/' + targetpath));215 },216 imagemin: function(path, targetpath) {217 gulp.src(path)218 // .pipe(image({219 // pngquant: true,220 // optipng: true,221 // zopflipng: true,222 // jpegRecompress: false,223 // jpegoptim: false,224 // mozjpeg: true,225 // gifsicle: true,226 // svgo: true,227 // concurrent: 10228 // })) //å缩å¾ç229 .pipe(gulp.dest(config.prod + '/' + targetpath));230 }231 },232 walk: function(path, floor, handleFile) {233 var _this = this;234 if (path.indexOf('.svn') == -1 && path.indexOf('.git') == -1) {235 handleFile(path, floor);236 }237 floor++;238 fs.readdir(path, function(err, files) {239 if (err) {240 console.log('read dir error');241 } else {242 files.forEach(function(item) {243 var tmpPath = path + '/' + item;244 fs.stat(tmpPath, function(err1, stats) {245 if (err1) {246 console.log('stat error');247 } else {248 if (stats.isDirectory()) {249 _this.walk(tmpPath, floor, handleFile);250 } else {251 if (tmpPath.indexOf('.svn') >= 0 || tmpPath.indexOf('.git') >= 0) {252 return;253 }254 handleFile(tmpPath, floor);255 }256 }257 })258 });259 }260 });261 },262 replaceAll: function(achar, charA, charB) {263 //æ¿æ¢å
¨é¨264 return achar.replace(/\\/g, charB);265 }...
index.js
Source:index.js
1const fs = require('fs');2const Lab = require('lab');3const lab = exports.lab = Lab.script();4const code = require('code');5const hapi = require('hapi');6const hapiNunjucksHelpers = require('../index.js');7const visionNunjucksPlugin = require('vision-nunjucks');8let server;9lab.beforeEach(() => {10 visionNunjucksPlugin.clearEnvironment();11 server = new hapi.Server({ port: 8000 });12});13lab.afterEach(async () => {14 await server.stop();15});16lab.experiment('helpers', () => {17 lab.test('asset', async() => {18 await server.register(require('vision'));19 server.views({20 engines: {21 njk: require('vision-nunjucks')22 },23 path: `${__dirname}/views`,24 isCached: false,25 compileMode: 'async'26 });27 server.route({28 path: '/asset',29 method: 'get',30 handler(request, h) {31 return h.view('asset');32 }33 });34 await server.register(hapiNunjucksHelpers);35 await server.start();36 const res = await server.inject({37 url: '/asset'38 });39 const expected = fs.readFileSync(`${__dirname}/expected/asset.html`, 'utf8');40 code.expect(res.statusCode).to.equal(200);41 code.expect(res.payload).to.equal(expected);42 });43 lab.test('cdn', async() => {44 visionNunjucksPlugin.clearEnvironment();45 await server.register(require('vision'));46 server.views({47 engines: {48 njk: require('vision-nunjucks')49 },50 path: `${__dirname}/views`,51 isCached: false,52 compileMode: 'async'53 });54 server.route({55 path: '/cdn',56 method: 'get',57 handler(request, h) {58 return h.view('cdn');59 }60 });61 await server.register({62 plugin: hapiNunjucksHelpers,63 options: {64 assets: {65 cdn: 'http://localhost'66 }67 }68 });69 await server.start();70 const res = await server.inject({71 url: '/cdn'72 });73 const expected = fs.readFileSync(`${__dirname}/expected/cdn.html`, 'utf8');74 code.expect(res.statusCode).to.equal(200);75 code.expect(res.payload).to.equal(expected);76 });77 lab.test('copy-block', async() => {78 await server.register(require('vision'));79 server.views({80 engines: {81 njk: require('vision-nunjucks')82 },83 path: `${__dirname}/views`,84 isCached: false,85 compileMode: 'async'86 });87 server.route({88 path: '/copy-block',89 method: 'get',90 handler(request, h) {91 return h.view('copy-block', {92 paragraph: [93 'test1',94 'test2'95 ]96 });97 }98 });99 await server.register(hapiNunjucksHelpers);100 await server.start();101 const res = await server.inject({102 url: '/copy-block'103 });104 const expected = fs.readFileSync(`${__dirname}/expected/copy-block.html`, 'utf8');105 code.expect(res.statusCode).to.equal(200);106 code.expect(res.payload).to.equal(expected);107 });108 lab.test('date', async() => {109 await server.register(require('vision'));110 server.views({111 engines: {112 njk: require('vision-nunjucks')113 },114 path: `${__dirname}/views`,115 isCached: false,116 compileMode: 'async'117 });118 server.route({119 path: '/date',120 method: 'get',121 handler(request, h) {122 return h.view('date');123 }124 });125 await server.register(hapiNunjucksHelpers);126 await server.start();127 const res = await server.inject({128 url: '/date'129 });130 const expected = fs.readFileSync(`${__dirname}/expected/date.html`, 'utf8');131 code.expect(res.statusCode).to.equal(200);132 code.expect(res.payload).to.equal(expected);133 });134 lab.test('exclude', async() => {135 await server.register(require('vision'));136 server.views({137 engines: {138 njk: require('vision-nunjucks')139 },140 path: `${__dirname}/views`,141 isCached: false,142 compileMode: 'async'143 });144 server.route({145 path: '/exclude',146 method: 'get',147 handler(request, h) {148 return h.view('exclude', {149 items: [150 {151 name: 'test 1',152 slug: 'test1'153 },154 {155 name: 'test 2',156 slug: 'test2'157 },158 {159 name: 'test 3',160 slug: 'test3'161 }162 ],163 exclude: [164 {165 name: 'test 2',166 slug: 'test2'167 }168 ]169 });170 }171 });172 await server.register(hapiNunjucksHelpers);173 await server.start();174 const res = await server.inject({175 url: '/exclude'176 });177 const expected = fs.readFileSync(`${__dirname}/expected/exclude.html`, 'utf8');178 code.expect(res.statusCode).to.equal(200);179 code.expect(res.payload).to.equal(expected);180 });181 lab.test('inline', async() => {182 await server.register(require('vision'));183 server.views({184 engines: {185 njk: require('vision-nunjucks')186 },187 path: `${__dirname}/views`,188 isCached: false,189 compileMode: 'async'190 });191 server.route({192 path: '/inline',193 method: 'get',194 handler(request, h) {195 return h.view('inline');196 }197 });198 await server.register(hapiNunjucksHelpers);199 await server.start();200 const res = await server.inject({201 url: '/inline'202 });203 const expected = fs.readFileSync(`${__dirname}/expected/inline.html`, 'utf8');204 code.expect(res.statusCode).to.equal(200);205 code.expect(res.payload.trim()).to.equal(expected.trim());206 });207 lab.test('securify', async() => {208 visionNunjucksPlugin.clearEnvironment();209 await server.register(require('vision'));210 server.views({211 engines: {212 njk: require('vision-nunjucks')213 },214 path: `${__dirname}/views`,215 isCached: false,216 compileMode: 'async'217 });218 server.route({219 path: '/securify',220 method: 'get',221 handler(request, h) {222 return h.view('securify');223 }224 });225 await server.register({226 plugin: hapiNunjucksHelpers,227 options: {228 secureLinks: true229 }230 });231 await server.start();232 const res = await server.inject({233 url: '/securify'234 });235 const expected = fs.readFileSync(`${__dirname}/expected/securify.html`, 'utf8');236 code.expect(res.statusCode).to.equal(200);237 code.expect(res.payload).to.equal(expected);238 });239 lab.test('securify disabled', async() => {240 visionNunjucksPlugin.clearEnvironment();241 await server.register(require('vision'));242 server.views({243 engines: {244 njk: require('vision-nunjucks')245 },246 path: `${__dirname}/views`,247 isCached: false,248 compileMode: 'async'249 });250 server.route({251 path: '/securify-disabled',252 method: 'get',253 handler(request, h) {254 return h.view('securify-disabled');255 }256 });257 await server.register({258 plugin: hapiNunjucksHelpers,259 options: {260 secureLinks: false261 }262 });263 await server.start();264 const res = await server.inject({265 url: '/securify-disabled'266 });267 const expected = fs.readFileSync(`${__dirname}/expected/securify-disabled.html`, 'utf8');268 code.expect(res.statusCode).to.equal(200);269 code.expect(res.payload).to.equal(expected);270 });271 lab.test('slugify', async() => {272 await server.register(require('vision'));273 server.views({274 engines: {275 njk: require('vision-nunjucks')276 },277 path: `${__dirname}/views`,278 isCached: false,279 compileMode: 'async'280 });281 await server.register({282 plugin: hapiNunjucksHelpers,283 options: {284 secureLinks: false285 }286 });287 server.route({288 path: '/slugify',289 method: 'get',290 handler(request, h) {291 return h.view('slugify');292 }293 });294 await server.start();295 const res = await server.inject({296 url: '/slugify'297 });298 const expected = fs.readFileSync(`${__dirname}/expected/slugify.html`, 'utf8');299 code.expect(res.statusCode).to.equal(200);300 code.expect(res.payload).to.equal(expected);301 });302 lab.test('script', async() => {303 await server.register(require('vision'));304 server.views({305 engines: {306 njk: require('vision-nunjucks')307 },308 path: `${__dirname}/views`,309 isCached: false,310 compileMode: 'async'311 });312 server.route({313 path: '/script',314 method: 'get',315 handler(request, h) {316 return h.view('script');317 }318 });319 await server.register({320 plugin: hapiNunjucksHelpers,321 options: {322 assets: {323 cdn: 'http://localhost'324 }325 }326 });327 await server.start();328 const res = await server.inject({329 url: '/script'330 });331 const expected = fs.readFileSync(`${__dirname}/expected/script.html`, 'utf8');332 code.expect(res.statusCode).to.equal(200);333 code.expect(res.payload).to.equal(expected);334 });335 lab.test('style', async() => {336 await server.register(require('vision'));337 server.views({338 engines: {339 njk: require('vision-nunjucks')340 },341 path: `${__dirname}/views`,342 isCached: false,343 compileMode: 'async'344 });345 server.route({346 path: '/style',347 method: 'get',348 handler(request, h) {349 return h.view('style');350 }351 });352 await server.register({353 plugin: hapiNunjucksHelpers,354 options: {355 assets: {356 cdn: 'http://localhost'357 }358 }359 });360 await server.start();361 const res = await server.inject({362 url: '/style'363 });364 const expected = fs.readFileSync(`${__dirname}/expected/style.html`, 'utf8');365 code.expect(res.statusCode).to.equal(200);366 code.expect(res.payload).to.equal(expected);367 });...
CompileButton.js
Source:CompileButton.js
1import React, { Component } from 'react';2import PropTypes from 'prop-types';3import SplitButton from 'react-bootstrap/lib/SplitButton';4import Glyphicon from 'react-bootstrap/lib/Glyphicon';5import OverlayTrigger from 'react-bootstrap/lib/OverlayTrigger';6import MenuItem from 'react-bootstrap/lib/MenuItem';7import tooltip from './Tooltip';8import { CompileMode, CompileModes } from '../Common/Common';9export default class CompileButton extends Component {10 static propTypes = {11 disabled: PropTypes.bool,12 onChange: PropTypes.func,13 onClick: PropTypes.func14 }15 static defaultProps = {16 disabled: true,17 onChange: () => {},18 onClick: () => {}19 }20 constructor(props) {21 super(props);22 this.state = {23 isCompiling: false,24 compileMode: CompileMode.Auto,25 cursor: 'pointer'26 };27 }28 startCompile() {29 this.setState({30 isCompiling: true,31 cursor: 'wait'32 });33 }34 endCompile() {35 this.setState({36 isCompiling: false,37 cursor: 'pointer'38 });39 }40 onCompile = () => {41 const { onClick } = this.props;42 onClick(this.state.compileMode);43 }44 onSelect = compileMode => {45 this.setState({ compileMode });46 this.props.onChange(compileMode);47 }48 render() {49 const { disabled } = this.props;50 const { isCompiling, compileMode, cursor } = this.state;51 const title = (52 <span>53 <Glyphicon54 glyph={ !isCompiling ? 'play' : 'refresh' }55 className={ isCompiling ? 'gly-spin' : '' }56 />{ '\t' + CompileModes[compileMode] }57 </span>58 );59 return (60 <OverlayTrigger61 rootClose62 placement='right'63 trigger={['hover', 'focus']}64 overlay={ tooltip('Compile') }65 >66 <SplitButton67 id='compileButton'68 title={ title }69 disabled={ isCompiling || disabled }70 className='pull-left'71 bsStyle='success'72 bsSize='large'73 style={{74 cursor,75 width: '161px'76 }}77 onClick={ !isCompiling ? this.onCompile : null }78 >79 {80 CompileModes.map((value, index) =>81 <MenuItem82 key={ index }83 eventKey={ index }84 onSelect={ this.onSelect }85 style={{ textAlign: 'center' }}86 >87 <h4>{ value }</h4>88 </MenuItem>89 )90 }91 </SplitButton>92 </OverlayTrigger>93 );94 }...
createUSqlJobProperties.js
Source:createUSqlJobProperties.js
1/*2 * Copyright (c) Microsoft Corporation. All rights reserved.3 * Licensed under the MIT License. See License.txt in the project root for4 * license information.5 *6 * Code generated by Microsoft (R) AutoRest Code Generator.7 * Changes may cause incorrect behavior and will be lost if the code is8 * regenerated.9 */10'use strict';11const models = require('./index');12/**13 * U-SQL job properties used when submitting U-SQL jobs.14 *15 * @extends models['CreateJobProperties']16 */17class CreateUSqlJobProperties extends models['CreateJobProperties'] {18 /**19 * Create a CreateUSqlJobProperties.20 * @member {string} [compileMode] the specific compilation mode for the job21 * used during execution. If this is not specified during submission, the22 * server will determine the optimal compilation mode. Possible values23 * include: 'Semantic', 'Full', 'SingleBox'24 */25 constructor() {26 super();27 }28 /**29 * Defines the metadata of CreateUSqlJobProperties30 *31 * @returns {object} metadata of CreateUSqlJobProperties32 *33 */34 mapper() {35 return {36 required: false,37 serializedName: 'USql',38 type: {39 name: 'Composite',40 className: 'CreateUSqlJobProperties',41 modelProperties: {42 runtimeVersion: {43 required: false,44 serializedName: 'runtimeVersion',45 type: {46 name: 'String'47 }48 },49 script: {50 required: true,51 serializedName: 'script',52 type: {53 name: 'String'54 }55 },56 type: {57 required: true,58 serializedName: 'type',59 type: {60 name: 'String'61 }62 },63 compileMode: {64 required: false,65 serializedName: 'compileMode',66 type: {67 name: 'Enum',68 allowedValues: [ 'Semantic', 'Full', 'SingleBox' ]69 }70 }71 }72 }73 };74 }75}...
hapi-nunjucks.js
Source:hapi-nunjucks.js
1var Path = require("path");2var Nunjucks = require("nunjucks");3// all the exported properties from Nunjucks module are available in the wrapper4Object.keys(Nunjucks).forEach(function(key){5 module.exports[key] = Nunjucks[key];6});7// redefine Nunjucks.compile to be compliant with the Hapi/Vision API8module.exports.compileOriginal = Nunjucks.compile;9module.exports.compile = function(str, compileOptions, next){10 var compileMode = "sync";11 if(next){12 compileMode = "async";13 }14 var compiled = null;15 if(compileMode === "sync"){16 // compileMode is "sync" (the default); The Vision docs say:17 // "the return value is a function [the compiled template] with signature 18 // function(context, options), and the method is allowed to throw errors"19 compiled = function(ctx, runtimeOptions){20 return Nunjucks.render(Path.basename(compileOptions.filename), ctx);21 };22 return compiled; 23 }24 else{25 // compileMode is "async"; The Vision docs say:26 // "next has the signature function(err, compiled), where27 // - compiled should be a function with signature function(context, options, callback)28 // - callback has the signature function(err, rendered) "29 compiled = function(ctx, runtimeOptions, callback){30 Nunjucks.render(Path.basename(compileOptions.filename), ctx, callback);31 return;32 };33 next(null, compiled);34 return; 35 }...
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 for (const browserType of BROWSER) {4 const browser = await playwright[browserType].launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.screenshot({ path: `example-${browserType}.png` });8 await browser.close();9 }10})();11 at CDPSession.send (/Users/username/Downloads/playwright-1.0.0-alpha.3/lib/cjs/pw_protocol/protocol.js:98:19)12 at async ExecutionContext._evaluateInternal (/Users/username/Downloads/playwright-1.0.0-alpha.3/lib/cjs/pw_run
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 const browser = await playwright.chromium.launch({ headless: false });4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.screenshot({ path: 'example.png' });7 await browser.close();8})();9const playwright = require('playwright');10(async () => {11 const browser = await playwright.chromium.launch({ headless: false });12 const context = await browser.newContext();13 const page = await context.newPage();14 await page.screenshot({ path: 'example.png' });15 await browser.close();16})();17const playwright = require('playwright');18(async () => {19 const browser = await playwright.chromium.launch({ headless: false });20 const context = await browser.newContext();21 const page = await context.newPage();22 await page.screenshot({ path: 'example.png' });23 await browser.close();24})();25const playwright = require('playwright');26(async () => {27 const browser = await playwright.chromium.launch({ headless: false });28 const context = await browser.newContext();29 const page = await context.newPage();30 await page.screenshot({ path: 'example.png' });31 await browser.close();32})();33const playwright = require('playwright');34(async () => {35 const browser = await playwright.chromium.launch({ headless: false });36 const context = await browser.newContext();37 const page = await context.newPage();38 await page.screenshot({ path: 'example.png' });39 await browser.close();40})();41const playwright = require('playwright');42(async () => {43 const browser = await playwright.chromium.launch({ headless: false });
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 const browser = await playwright.chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.screenshot({ path: 'example.png' });7 await browser.close();8})();9const playwright = require('playwright');10(async () => {11 const browser = await playwright.chromium.launch();12 const context = await browser.newContext();13 const page = await context.newPage();14 await page.screenshot({ path: 'example.png' });15 await browser.close();16})();17const playwright = require('playwright');18(async () => {19 const browser = await playwright.chromium.launch();20 const context = await browser.newContext();21 const page = await context.newPage();22 await page.screenshot({ path: 'example.png' });23 await browser.close();24})();25const playwright = require('playwright');26(async () => {27 const browser = await playwright.chromium.launch();28 const context = await browser.newContext();29 const page = await context.newPage();30 await page.screenshot({ path: 'example.png' });31 await browser.close();32})();33const playwright = require('playwright');34(async () => {35 const browser = await playwright.chromium.launch();36 const context = await browser.newContext();37 const page = await context.newPage();38 await page.screenshot({ path: 'example.png' });39 await browser.close();40})();41const playwright = require('playwright');42(async () => {43 const browser = await playwright.chromium.launch();44 const context = await browser.newContext();45 const page = await context.newPage();
Using AI Code Generation
1const { chromium } = require('playwright');2const fs = require('fs');3const path = require('path');4(async () => {5 const browser = await chromium.launch();6 const context = await browser.newContext();7 const page = await context.newPage();8 const script = await fs.promises.readFile(path.join(__dirname, 'test.js'), 'utf8');9 await page.compileScript(script);10 await page.evaluate('test()');11 await browser.close();12})();
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 const browser = await playwright.chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const compileMode = await page.compileMode();7 console.log(compileMode);8 await browser.close();9})();10Page.evaluateOnNewDocument()11Page.evaluate()12Page.evaluateHandle()13Page.$eval()14Page.$$eval()15Page.$()16Page.$$()17Page.addInitScript()18Page.exposeFunction()19Page.waitForFunction()20Page.waitForTimeout()21Page.waitForSelector()22Page.waitForXPath()23Page.waitForRequest()24Page.waitForResponse()25Page.title()26Page.close()27Page.bringToFront()28Page.goForward()29Page.goBack()30Page.reload()31Page.setContent()32Page.screenshot()33Page.pdf()34Page.addScriptTag()35Page.addStyleTag()36Page.waitForLoadState()37Page.waitForNavigation()38Page.waitForEvent()39Page.keyboard()40Page.mouse()41Page.touchscreen()42Page.tracing()43Page.selectOption()44Page.accessibility.snapshot()45Page.accessibility.snapshotForTests()46Page.accessibility.describe()47Page.accessibility.describeForTests()48Page.accessibility.queryAXTree()49Page.accessibility.queryAXTreeForTests()50Page.accessibility.queryAXNodes()51Page.accessibility.queryAXNodesForTests()52Page.accessibility.queryAXNode()53Page.accessibility.queryAXNodeForTests()54Page.accessibility.setIgnoreAccessibility()55Page.accessibility.setIgnoreAccessibilityForTests()56Page.accessibility.setIgnoreList()57Page.accessibility.setIgnoreListForTests()58Page.accessibility.setForceList()59Page.accessibility.setForceListForTests()60Page.accessibility.setForceListForTestsForTests()61Page.accessibility.setForceListForTestsForTestsForTests()62Page.accessibility.setForceListForTestsForTestsForTestsForTests()63Page.accessibility.setForceListForTestsForTestsForTestsForTestsForTests()64Page.accessibility.setForceListForTestsForTestsForTestsForTestsForTestsForTests()65Page.accessibility.setForceListForTestsForTestsForTestsForTestsForTestsForTestsForTests()66Page.accessibility.setForceListForTestsForTestsForTestsForTestsForTestsForTestsForTestsForTests()67Page.accessibility.setForceListForTestsForTestsForTestsForTestsForTestsForTestsForTestsForTestsForTests()
Using AI Code Generation
1const { Playwright } = require('@playwright/test');2const fs = require('fs');3const { chromium } = require('playwright');4(async () => {5 const browser = await chromium.launch();6 const context = await browser.newContext();7 const page = await context.newPage();8 await page.screenshot({ path: `example.png` });9 await browser.close();10})();11const { Playwright } = require('@playwright/test');12const fs = require('fs');13const { chromium } = require('playwright');14(async () => {15 const browser = await chromium.launch();16 const context = await browser.newContext();17 const page = await context.newPage();18 await page.screenshot({ path: `example.png` });19 await browser.close();20})();
Using AI Code Generation
1import { chromium } from 'playwright';2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 await context.compileMode();6 const page = await context.newPage();7 await page.screenshot({ path: 'example.png' });8 await browser.close();9})();
Using AI Code Generation
1const playwright = require('playwright');2const { compileMode } = require('playwright/lib/server/compileMode.js');3(async () => {4 const { chromium } = await compileMode('chromium');5 const browser = await chromium.launch({6 });7 const context = await browser.newContext();8 const page = await context.newPage();9 await browser.close();10})();
Using AI Code Generation
1const { compileTypeScript } = require('playwright-core/lib/utils/compileTypescript');2const { writeFile } = require('fs').promises;3const path = require('path');4const { test } = require('playwright-core');5(async () => {6 await test('test', async ({ page }) => {7 const compiledCode = await compileTypeScript(path.join(__dirname, 'test.ts'));8 await writeFile(path.join(__dirname, 'test.js'), compiledCode);9 });10})();
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!!