Best K6 code snippet using compiler.sourceMapLoader
compiler.go
Source:compiler.go
...170// Compile the program in the given CompatibilityMode, wrapping it between pre and post code171func (c *Compiler) Compile(src, filename string, main bool) (*goja.Program, string, error) {172 return c.compileImpl(src, filename, main, c.Options.CompatibilityMode, nil)173}174// sourceMapLoader is to be used with goja's WithSourceMapLoader175// it not only gets the file from disk in the simple case, but also returns it if the map was generated from babel176// additioanlly it fixes off by one error in commonjs dependencies due to having to wrap them in a function.177func (c *compilationState) sourceMapLoader(path string) ([]byte, error) {178 if path == sourceMapURLFromBabel {179 if !c.main {180 return c.increaseMappingsByOne(c.srcMap)181 }182 return c.srcMap, nil183 }184 c.srcMap, c.srcMapError = c.compiler.Options.SourceMapLoader(path)185 if c.srcMapError != nil {186 c.couldntLoadSourceMap = true187 return nil, c.srcMapError188 }189 _, c.srcMapError = sourcemap.Parse(path, c.srcMap)190 if c.srcMapError != nil {191 c.couldntLoadSourceMap = true192 c.srcMap = nil193 return nil, c.srcMapError194 }195 if !c.main {196 return c.increaseMappingsByOne(c.srcMap)197 }198 return c.srcMap, nil199}200func (c *Compiler) compileImpl(201 src, filename string, main bool, compatibilityMode lib.CompatibilityMode, srcMap []byte,202) (*goja.Program, string, error) {203 code := src204 state := compilationState{srcMap: srcMap, compiler: c, main: main}205 if !main { // the lines in the sourcemap (if available) will be fixed by increaseMappingsByOne206 code = "(function(module, exports){\n" + code + "\n})\n"207 }208 opts := parser.WithDisableSourceMaps209 if c.Options.SourceMapLoader != nil {210 opts = parser.WithSourceMapLoader(state.sourceMapLoader)211 }212 ast, err := parser.ParseFile(nil, filename, code, 0, opts)213 if state.couldntLoadSourceMap {214 state.couldntLoadSourceMap = false // reset215 // we probably don't want to abort scripts which have source maps but they can't be found,216 // this also will be a breaking change, so if we couldn't we retry with it disabled217 c.logger.WithError(state.srcMapError).Warnf("Couldn't load source map for %s", filename)218 ast, err = parser.ParseFile(nil, filename, code, 0, parser.WithDisableSourceMaps)219 }220 if err != nil {221 if compatibilityMode == lib.CompatibilityModeExtended {222 code, state.srcMap, err = c.Transform(src, filename, state.srcMap)223 if err != nil {224 return nil, code, err...
compiler_test.go
Source:compiler_test.go
1/*2 *3 * k6 - a next-generation load testing tool4 * Copyright (C) 2017 Load Impact5 *6 * This program is free software: you can redistribute it and/or modify7 * it under the terms of the GNU Affero General Public License as8 * published by the Free Software Foundation, either version 3 of the9 * License, or (at your option) any later version.10 *11 * This program is distributed in the hope that it will be useful,12 * but WITHOUT ANY WARRANTY; without even the implied warranty of13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the14 * GNU Affero General Public License for more details.15 *16 * You should have received a copy of the GNU Affero General Public License17 * along with this program. If not, see <http://www.gnu.org/licenses/>.18 *19 */20package compiler21import (22 "errors"23 "io/ioutil"24 "strings"25 "testing"26 "github.com/dop251/goja"27 "github.com/sirupsen/logrus"28 "github.com/stretchr/testify/assert"29 "github.com/stretchr/testify/require"30 "go.k6.io/k6/lib"31 "go.k6.io/k6/lib/testutils"32)33func TestTransform(t *testing.T) {34 t.Parallel()35 t.Run("blank", func(t *testing.T) {36 t.Parallel()37 c := New(testutils.NewLogger(t))38 src, _, err := c.Transform("", "test.js", nil)39 assert.NoError(t, err)40 assert.Equal(t, `"use strict";`, src)41 })42 t.Run("double-arrow", func(t *testing.T) {43 t.Parallel()44 c := New(testutils.NewLogger(t))45 src, _, err := c.Transform("()=> true", "test.js", nil)46 assert.NoError(t, err)47 assert.Equal(t, `"use strict";() => true;`, src)48 })49 t.Run("longer", func(t *testing.T) {50 t.Parallel()51 c := New(testutils.NewLogger(t))52 src, _, err := c.Transform(strings.Join([]string{53 `function add(a, b) {`,54 ` return a + b;`,55 `};`,56 ``,57 `let res = add(1, 2);`,58 }, "\n"), "test.js", nil)59 assert.NoError(t, err)60 assert.Equal(t, strings.Join([]string{61 `"use strict";function add(a, b) {`,62 ` return a + b;`,63 `};`,64 ``,65 `let res = add(1, 2);`,66 }, "\n"), src)67 })68 t.Run("double-arrow with sourceMap", func(t *testing.T) {69 t.Parallel()70 c := New(testutils.NewLogger(t))71 c.Options.SourceMapLoader = func(string) ([]byte, error) { return nil, errors.New("shouldn't be called") }72 src, _, err := c.Transform("()=> true", "test.js", nil)73 assert.NoError(t, err)74 assert.Equal(t, `"use strict";75() => true;76//# sourceMappingURL=k6://internal-should-not-leak/file.map`, src)77 })78}79func TestCompile(t *testing.T) {80 t.Parallel()81 t.Run("ES5", func(t *testing.T) {82 t.Parallel()83 c := New(testutils.NewLogger(t))84 src := `1+(function() { return 2; })()`85 pgm, code, err := c.Compile(src, "script.js", true)86 require.NoError(t, err)87 assert.Equal(t, src, code)88 v, err := goja.New().RunProgram(pgm)89 if assert.NoError(t, err) {90 assert.Equal(t, int64(3), v.Export())91 }92 })93 t.Run("ES5 Wrap", func(t *testing.T) {94 t.Parallel()95 c := New(testutils.NewLogger(t))96 src := `exports.d=1+(function() { return 2; })()`97 pgm, code, err := c.Compile(src, "script.js", false)98 require.NoError(t, err)99 assert.Equal(t, "(function(module, exports){\nexports.d=1+(function() { return 2; })()\n})\n", code)100 rt := goja.New()101 v, err := rt.RunProgram(pgm)102 if assert.NoError(t, err) {103 fn, ok := goja.AssertFunction(v)104 if assert.True(t, ok, "not a function") {105 exp := make(map[string]goja.Value)106 _, err := fn(goja.Undefined(), goja.Undefined(), rt.ToValue(exp))107 if assert.NoError(t, err) {108 assert.Equal(t, int64(3), exp["d"].Export())109 }110 }111 }112 })113 t.Run("ES5 Invalid", func(t *testing.T) {114 t.Parallel()115 c := New(testutils.NewLogger(t))116 src := `1+(function() { return 2; )()`117 c.Options.CompatibilityMode = lib.CompatibilityModeExtended118 _, _, err := c.Compile(src, "script.js", false)119 assert.IsType(t, &goja.Exception{}, err)120 assert.Contains(t, err.Error(), `SyntaxError: script.js: Unexpected token (1:26)121> 1 | 1+(function() { return 2; )()`)122 })123 t.Run("ES6", func(t *testing.T) {124 t.Parallel()125 c := New(testutils.NewLogger(t))126 c.Options.CompatibilityMode = lib.CompatibilityModeExtended127 pgm, code, err := c.Compile(`3**2`, "script.js", true)128 require.NoError(t, err)129 assert.Equal(t, `"use strict";Math.pow(3, 2);`, code)130 v, err := goja.New().RunProgram(pgm)131 if assert.NoError(t, err) {132 assert.Equal(t, int64(9), v.Export())133 }134 })135 t.Run("Wrap", func(t *testing.T) {136 t.Parallel()137 c := New(testutils.NewLogger(t))138 c.Options.CompatibilityMode = lib.CompatibilityModeExtended139 pgm, code, err := c.Compile(`exports.fn(3**2)`, "script.js", false)140 require.NoError(t, err)141 assert.Equal(t, "(function(module, exports){\n\"use strict\";exports.fn(Math.pow(3, 2));\n})\n", code)142 rt := goja.New()143 v, err := rt.RunProgram(pgm)144 if assert.NoError(t, err) {145 fn, ok := goja.AssertFunction(v)146 if assert.True(t, ok, "not a function") {147 exp := make(map[string]goja.Value)148 var out interface{}149 exp["fn"] = rt.ToValue(func(v goja.Value) {150 out = v.Export()151 })152 _, err := fn(goja.Undefined(), goja.Undefined(), rt.ToValue(exp))153 assert.NoError(t, err)154 assert.Equal(t, int64(9), out)155 }156 }157 })158 t.Run("Invalid", func(t *testing.T) {159 t.Parallel()160 c := New(testutils.NewLogger(t))161 c.Options.CompatibilityMode = lib.CompatibilityModeExtended162 _, _, err := c.Compile(`1+(=>2)()`, "script.js", true)163 assert.IsType(t, &goja.Exception{}, err)164 assert.Contains(t, err.Error(), `SyntaxError: script.js: Unexpected token (1:3)165> 1 | 1+(=>2)()`)166 })167}168func TestCorruptSourceMap(t *testing.T) {169 t.Parallel()170 corruptSourceMap := []byte(`{"mappings": 12}`) // 12 is a number not a string171 logger := logrus.New()172 logger.SetLevel(logrus.DebugLevel)173 logger.Out = ioutil.Discard174 hook := testutils.SimpleLogrusHook{175 HookedLevels: []logrus.Level{logrus.InfoLevel, logrus.WarnLevel},176 }177 logger.AddHook(&hook)178 compiler := New(logger)179 compiler.Options = Options{180 Strict: true,181 SourceMapLoader: func(string) ([]byte, error) {182 return corruptSourceMap, nil183 },184 }185 _, _, err := compiler.Compile("var s = 5;\n//# sourceMappingURL=somefile", "somefile", false)186 require.NoError(t, err)187 entries := hook.Drain()188 require.Len(t, entries, 1)189 msg, err := entries[0].String() // we need this in order to get the field error190 require.NoError(t, err)191 require.Contains(t, msg, `Couldn't load source map for somefile`)192 require.Contains(t, msg, `json: cannot unmarshal number into Go struct field v3.mappings of type string`)193}194func TestCorruptSourceMapOnlyForBabel(t *testing.T) {195 t.Parallel()196 // this a valid source map for the go implementation but babel doesn't like it197 corruptSourceMap := []byte(`{"mappings": ";"}`)198 logger := logrus.New()199 logger.SetLevel(logrus.DebugLevel)200 logger.Out = ioutil.Discard201 hook := testutils.SimpleLogrusHook{202 HookedLevels: []logrus.Level{logrus.InfoLevel, logrus.WarnLevel},203 }204 logger.AddHook(&hook)205 compiler := New(logger)206 compiler.Options = Options{207 CompatibilityMode: lib.CompatibilityModeExtended,208 Strict: true,209 SourceMapLoader: func(string) ([]byte, error) {210 return corruptSourceMap, nil211 },212 }213 _, _, err := compiler.Compile("class s {};\n//# sourceMappingURL=somefile", "somefile", false)214 require.NoError(t, err)215 entries := hook.Drain()216 require.Len(t, entries, 1)217 msg, err := entries[0].String() // we need this in order to get the field error218 require.NoError(t, err)219 require.Contains(t, msg, `needs to be transpiled by Babel, but its source map will not be accepted by Babel`)220 require.Contains(t, msg, `source map missing required 'version' field`)221}222func TestMinimalSourceMap(t *testing.T) {223 t.Parallel()224 // this is the minimal sourcemap valid for both go and babel implementations225 corruptSourceMap := []byte(`{"version":3,"mappings":";","sources":[]}`)226 logger := logrus.New()227 logger.SetLevel(logrus.DebugLevel)228 logger.Out = ioutil.Discard229 hook := testutils.SimpleLogrusHook{230 HookedLevels: []logrus.Level{logrus.InfoLevel, logrus.WarnLevel},231 }232 logger.AddHook(&hook)233 compiler := New(logger)234 compiler.Options = Options{235 CompatibilityMode: lib.CompatibilityModeExtended,236 Strict: true,237 SourceMapLoader: func(string) ([]byte, error) {238 return corruptSourceMap, nil239 },240 }241 _, _, err := compiler.Compile("class s {};\n//# sourceMappingURL=somefile", "somefile", false)242 require.NoError(t, err)243 require.Empty(t, hook.Drain())244}...
sourceMapLoader
Using AI Code Generation
1import (2func main() {3 db := memorydb.New()4 statedb, _ := state.New(common.Hash{}, state.NewDatabase(db))5 block := types.NewBlock(&types.Header{}, nil, nil, nil)6 env := core.NewEVMBlockContext(block.Header(), nil, nil)7 context := core.NewEVMContext(msg, block.Header(), nil, nil)8 evm := vm.NewEVM(env, context, statedb, params.TestChainConfig, vm.Config{})9 rt := runtime.New(evm, statedb, params.TestChainConfig, evm.ChainConfig(), vm.Config{}, nil)10 compiler := vm.NewCompiler(evm.ChainConfig(), rt, nil)11 sourceMap, err := compiler.SourceMap("0x1234567890123456789012345678901234567890")12 if err != nil {13 fmt.Println(err)14 }15 fmt.Println(sourceMap)16}17{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":13,"14":14,"15":15,"16":16,"17":17,"18":18,"19":19,"20":20,"21":21,"22":22,"23":23,"24":24,"25":25,"26":26,"27":27,"28":28,"29":29,"30":30,"31":31,"32":32,"33":33,"34":34,"35":35,"36":36,"37":37,"
sourceMapLoader
Using AI Code Generation
1import "fmt"2import "github.com/ethereum/go-ethereum/core/vm"3func main() {4 var sourceMapLoader func(path string) (string, error)5 sourceMapLoader = func(path string) (string, error) {6 }7 compiler := vm.NewEVMCompiler(sourceMapLoader)8 fmt.Println(compiler)9}10import "fmt"11import "github.com/ethereum/go-ethereum/core/vm"12func main() {13 var sourceMapLoader func(path string) (string, error)14 sourceMapLoader = func(path string) (string, error) {15 }16 compiler := vm.NewEVMCompiler(sourceMapLoader)17 fmt.Println(compiler)18}
sourceMapLoader
Using AI Code Generation
1import java.io.*;2import java.util.*;3import org.openjdk.nashorn.api.scripting.*;4import javax.script.*;5public class 1 {6 public static void main(String[] args) throws Exception {7 ScriptEngineManager sem = new ScriptEngineManager();8 ScriptEngine engine = sem.getEngineByName("nashorn");9 try {10 engine.eval("function add(a, b) { return a + b; }");11 System.out.println("add(3, 4) = " + engine.eval("add(3, 4)"));12 System.out.println("add(3, 4) = " + engine.eval("add(3, 4)"));13 } catch (ScriptException e) {14 e.printStackTrace();15 }16 }17}18add(3, 4) = 719add(3, 4) = 720function add(a, b) {21 return a + b;22}23import java.io.*;24import java.util.*;25import org.openjdk.nashorn.api.scripting.*;26import javax.script.*;27public class 2 {28 public static void main(String[] args) throws Exception {29 ScriptEngineManager sem = new ScriptEngineManager();30 ScriptEngine engine = sem.getEngineByName("nashorn");31 try {32 engine.eval("function add(a, b) { return a + b; }");33 System.out.println("add(3, 4) = " + engine.eval("add(3, 4)"));34 System.out.println("add(3, 4) = " + engine.eval("add(3, 4)"));35 } catch (ScriptException e) {36 e.printStackTrace();37 }38 }39}40add(3, 4) = 741add(3, 4) = 7
sourceMapLoader
Using AI Code Generation
1import "fmt"2import "github.com/robertkrimen/otto"3func main() {4 vm := otto.New()5 vm.Run(`6 var vm = this;7 var sourceMapLoader = vm.require("source-map-support").install({8 });9 sourceMapLoader.loadSourceMap("1.js.map");10 vm.Run(`11 function f() {12 throw new Error("Whoops!");13 }14 f();15 if err := vm.Get("err"); err != nil {16 fmt.Println("Error:", err)17 }18}19{
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!