How to use verifySourceMapForBabel method of compiler Package

Best K6 code snippet using compiler.verifySourceMapForBabel

compiler.go

Source:compiler.go Github

copy

Full Screen

...139 filename, maxSrcLenForBabelSourceMap)140 }141 // check that babel will likely be able to parse the inputSrcMap142 if sourceMapEnabled && len(inputSrcMap) != 0 {143 if err = verifySourceMapForBabel(inputSrcMap); err != nil {144 sourceMapEnabled = false145 inputSrcMap = nil146 c.logger.WithError(err).Warnf(147 "The source for `%s` needs to be transpiled by Babel, but its source map will"+148 " not be accepted by Babel, so it was disabled", filename)149 }150 }151 code, srcMap, err = c.babel.transformImpl(c.logger, src, filename, sourceMapEnabled, inputSrcMap)152 return153}154// Options are options to the compiler155type Options struct {156 CompatibilityMode lib.CompatibilityMode157 SourceMapLoader func(string) ([]byte, error)158 Strict bool159}160// compilationState is helper struct to keep the state of a compilation161type compilationState struct {162 // set when we couldn't load external source map so we can try parsing without loading it163 couldntLoadSourceMap bool164 // srcMap is the current full sourceMap that has been generated read so far165 srcMap []byte166 srcMapError error167 main bool168 compiler *Compiler169}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, err225 }226 // the compatibility mode "decreases" here as we shouldn't transform twice227 return c.compileImpl(code, filename, main, lib.CompatibilityModeBase, state.srcMap)228 }229 return nil, code, err230 }231 pgm, err := goja.CompileAST(ast, c.Options.Strict)232 return pgm, code, err233}234type babel struct {235 vm *goja.Runtime236 this goja.Value237 transform goja.Callable238 m sync.Mutex239}240func newBabel() (*babel, error) {241 onceBabelCode.Do(func() {242 globalBabelCode, globalBabelCodeErr = goja.Compile("<internal/k6/compiler/lib/babel.min.js>", babelSrc, false)243 })244 if globalBabelCodeErr != nil {245 return nil, globalBabelCodeErr246 }247 vm := goja.New()248 _, err := vm.RunProgram(globalBabelCode)249 if err != nil {250 return nil, err251 }252 this := vm.Get("Babel")253 bObj := this.ToObject(vm)254 result := &babel{vm: vm, this: this}255 if err = vm.ExportTo(bObj.Get("transform"), &result.transform); err != nil {256 return nil, err257 }258 return result, err259}260// increaseMappingsByOne increases the lines in the sourcemap by line so that it fixes the case where we need to wrap a261// required file in a function to support/emulate commonjs262func (c *compilationState) increaseMappingsByOne(sourceMap []byte) ([]byte, error) {263 var err error264 m := make(map[string]interface{})265 if err = json.Unmarshal(sourceMap, &m); err != nil {266 return nil, err267 }268 mappings, ok := m["mappings"]269 if !ok {270 // no mappings, no idea what this will do, but just return it as technically we can have sourcemap with sections271 // TODO implement incrementing of `offset` in the sections? to support that case as well272 // see https://sourcemaps.info/spec.html#h.n05z8dfyl3yh273 //274 // TODO (kind of alternatively) drop the newline in the "commonjs" wrapping and have only the first line wrong275 // and drop this whole function276 return sourceMap, nil277 }278 if str, ok := mappings.(string); ok {279 // ';' is the separator between lines so just adding 1 will make all mappings be for the line after which they were280 // originally281 m["mappings"] = ";" + str282 } else {283 // we have mappings but it's not a string - this is some kind of error284 // we still won't abort the test but just not load the sourcemap285 c.couldntLoadSourceMap = true286 return nil, errors.New(`missing "mappings" in sourcemap`)287 }288 return json.Marshal(m)289}290// transformImpl the given code into ES5, while synchronizing to ensure only a single291// bundle instance / Goja VM is in use at a time.292func (b *babel) transformImpl(293 logger logrus.FieldLogger, src, filename string, sourceMapsEnabled bool, inputSrcMap []byte,294) (string, []byte, error) {295 b.m.Lock()296 defer b.m.Unlock()297 opts := make(map[string]interface{})298 for k, v := range DefaultOpts {299 opts[k] = v300 }301 if sourceMapsEnabled {302 // given that the source map should provide accurate lines(and columns), this option isn't needed303 // it also happens to make very long and awkward lines, especially around import/exports and definitely a lot304 // less readable overall. Hopefully it also has some performance improvement not trying to keep the same lines305 opts["retainLines"] = false306 opts["sourceMaps"] = true307 if inputSrcMap != nil {308 srcMap := new(map[string]interface{})309 if err := json.Unmarshal(inputSrcMap, &srcMap); err != nil {310 return "", nil, err311 }312 opts["inputSourceMap"] = srcMap313 }314 }315 opts["filename"] = filename316 startTime := time.Now()317 v, err := b.transform(b.this, b.vm.ToValue(src), b.vm.ToValue(opts))318 if err != nil {319 return "", nil, err320 }321 logger.WithField("t", time.Since(startTime)).Debug("Babel: Transformed")322 vO := v.ToObject(b.vm)323 var code string324 if err = b.vm.ExportTo(vO.Get("code"), &code); err != nil {325 return code, nil, err326 }327 if !sourceMapsEnabled {328 return code, nil, nil329 }330 // this is to make goja try to load a sourcemap.331 // it is a special url as it should never leak outside of this code332 // additionally the alternative support from babel is to embed *the whole* sourcemap at the end333 code += "\n//# sourceMappingURL=" + sourceMapURLFromBabel334 stringify, err := b.vm.RunString("(function(m) { return JSON.stringify(m)})")335 if err != nil {336 return code, nil, err337 }338 c, _ := goja.AssertFunction(stringify)339 mapAsJSON, err := c(goja.Undefined(), vO.Get("map"))340 if err != nil {341 return code, nil, err342 }343 return code, []byte(mapAsJSON.String()), nil344}345// Pool is a pool of compilers so it can be used easier in parallel tests as they have their own babel.346type Pool struct {347 c chan *Compiler348}349// NewPool creates a Pool that will be using the provided logger and will preallocate (in parallel)350// the count of compilers each with their own babel.351func NewPool(logger logrus.FieldLogger, count int) *Pool {352 c := &Pool{353 c: make(chan *Compiler, count),354 }355 go func() {356 for i := 0; i < count; i++ {357 go func() {358 co := New(logger)359 err := co.initializeBabel()360 if err != nil {361 panic(err)362 }363 c.Put(co)364 }()365 }366 }()367 return c368}369// Get a compiler from the pool.370func (c *Pool) Get() *Compiler {371 return <-c.c372}373// Put a compiler back in the pool.374func (c *Pool) Put(co *Compiler) {375 c.c <- co376}377func verifySourceMapForBabel(srcMap []byte) error {378 // this function exists to do what babel checks in sourcemap before we give it to it.379 m := make(map[string]json.RawMessage)380 err := json.Unmarshal(srcMap, &m)381 if err != nil {382 return fmt.Errorf("source map is not valid json: %w", err)383 }384 // there are no checks on it's value in babel385 // we technically only support v3 though386 if _, ok := m["version"]; !ok {387 return fmt.Errorf("source map missing required 'version' field")388 }389 // This actually gets checked by the go implementation so it's not really necessary390 if _, ok := m["mappings"]; !ok {391 return fmt.Errorf("source map missing required 'mappings' field")...

Full Screen

Full Screen

verifySourceMapForBabel

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 privateKey, err := crypto.GenerateKey()4 if err != nil {5 fmt.Println("Error in generating private key")6 }7 account := crypto.PubkeyToAddress(privateKey.PublicKey)8 tx := types.NewTransaction(0, common.HexToAddress("0x0"), big.NewInt(0), 100000, big.NewInt(0), nil)9 signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, privateKey)10 if err != nil {11 fmt.Println("Error in signing the transaction")12 }13 encodedTx, err := rlp.EncodeToBytes(signedTx)14 if err != nil {15 fmt.Println("Error in encoding the transaction to RLP")16 }17 compiler := native.NewCompiler()18 sourceMap, err := compiler.VerifySourceMapForBabel(encodedTx, account)19 if err != nil {20 fmt.Println("Error in generating the source map")21 }22 fmt.Println("Source Map:")23 fmt.Println(sourceMap)

Full Screen

Full Screen

verifySourceMapForBabel

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 var src string = "package main" + "\n" + "func main() {" + "\n" + "fmt.Println(\"Hello World\")" + "\n" + "}"4 var sourceMap, err = compiler.VerifySourceMapForBabel(src, path)5 if err != nil {6 fmt.Println(err)7 }8 fmt.Println(sourceMap)9}

Full Screen

Full Screen

verifySourceMapForBabel

Using AI Code Generation

copy

Full Screen

1func main() {2 compiler := compiler.NewCompiler()3 sourceMap := sourceMap.NewSourceMap()4 sourceMap1 := sourceMap.NewSourceMap()5 sourceMap.SetSourceMapPath("sourceMap.json")6 sourceMap1.SetSourceMapPath("sourceMap1.json")7 sourceMap2 := sourceMap.NewSourceMap()8 sourceMap2.SetSourceMapPath("sourceMap2.json")9 sourceMap3 := sourceMap.NewSourceMap()10 sourceMap3.SetSourceMapPath("sourceMap3.json")11 sourceMap4 := sourceMap.NewSourceMap()12 sourceMap4.SetSourceMapPath("sourceMap4.json")13 sourceMap5 := sourceMap.NewSourceMap()14 sourceMap5.SetSourceMapPath("sourceMap5.json")15 sourceMap6 := sourceMap.NewSourceMap()16 sourceMap6.SetSourceMapPath("sourceMap6.json")17 sourceMap7 := sourceMap.NewSourceMap()18 sourceMap7.SetSourceMapPath("sourceMap7.json")19 sourceMap8 := sourceMap.NewSourceMap()20 sourceMap8.SetSourceMapPath("sourceMap8.json")21 sourceMap9 := sourceMap.NewSourceMap()22 sourceMap9.SetSourceMapPath("sourceMap9.json")23 sourceMap10 := sourceMap.NewSourceMap()24 sourceMap10.SetSourceMapPath("sourceMap10.json")25 sourceMap11 := sourceMap.NewSourceMap()26 sourceMap11.SetSourceMapPath("

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful