Best JavaScript code snippet using ladle
index.js
Source:index.js
1// Copyright (c) 2016-present, salesforce.com, inc. All rights reserved2// Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license3/* global describe, it */4'use strict'5const { expect } = require('chai')6const createQuery = require('../lib')7const { getAST } = require('./helpers')8const getType = (n) => n.type9const getValue = (n) => n.value10describe('#createQuery(ast, options)', () => {11 describe('ast', () => {12 it('throws an error if no AST is provided', () => {13 expect(() => {14 createQuery()15 }).to.throw(/object/)16 })17 })18 describe('options', () => {19 it('throws an error if hasChildren is not a function', () => {20 expect(() => {21 createQuery({}, {22 hasChildren: true23 })24 }).to.throw(/hasChildren/)25 })26 it('throws an error if getChildren is not a function', () => {27 expect(() => {28 createQuery({}, {29 getChildren: true30 })31 }).to.throw(/getChildren/)32 })33 it('throws an error if getType is not a function', () => {34 expect(() => {35 createQuery({}, {36 getType: true37 })38 }).to.throw(/getType/)39 })40 it('throws an error if toJSON is not a function', () => {41 expect(() => {42 createQuery({}, {43 toJSON: true44 })45 }).to.throw(/toJSON/)46 })47 it('throws an error if toString is not a function', () => {48 expect(() => {49 createQuery({}, {50 toString: true51 })52 }).to.throw(/toString/)53 })54 })55})56describe('$', () => {57 describe('#get', () => {58 it('returns the the nodes as JSON', () => {59 const { $ } = getAST(`60 $border: 1px 2px 3px;61 `)62 const numbers = $('number').get()63 expect(Array.isArray(numbers)).to.be.true // eslint-disable-line64 expect(numbers).to.have.length(3)65 expect(numbers.map(getValue)).to.deep.equal(['1', '2', '3'])66 })67 it('returns a single node as JSON', () => {68 const { $ } = getAST(`69 $border: 1px 2px 3px;70 `)71 const numbers = $().find('number').get(1)72 expect(numbers.value).to.deep.equal('2')73 })74 })75 describe('#length', () => {76 it('returns length of the current selection', () => {77 const { $ } = getAST(`78 $border: 1px 2px 3px;79 `)80 const numbers = $('number')81 expect(numbers.length()).to.equal(3)82 })83 })84 describe('#index', () => {85 it('returns the index of the first item in the selection based on its siblings', () => {86 const { $ } = getAST(`87 .r { color: $_r; }88 .g { color: #{$_g}; }89 .b { color: $_b; }90 `)91 const index = $('rule')92 .eq(1)93 .index()94 // This is matching against siblings (whitespace included)95 expect(index).to.equal(3)96 })97 it('returns the index of the first item in the selection that matches the selector', () => {98 const { $ } = getAST(`99 $background: #fff #ccc #000;100 `)101 const $node = $()102 const $gray = $node.find('value').first().children().eq(3)103 const index = $gray.index('color_hex')104 expect(index).to.equal(1)105 })106 })107 describe('#after', () => {108 it('inserts a node after', () => {109 const { $ } = getAST(`110 .r { color: $_r; }111 .g { color: $_g; }112 .b { color: $_b; }113 `)114 $('rule')115 .eq(1)116 .after(117 getAST('.z { color: $_z; }').ast.value[0]118 )119 expect($().find('class').value()).to.equal('rgzb')120 })121 })122 describe('#before', () => {123 it('inserts a node after', () => {124 const { $ } = getAST(`125 .r { color: $_r; }126 .g { color: $_g; }127 .b { color: $_b; }128 `)129 $('rule')130 .eq(0)131 .before(132 getAST('.z { color: $_z; }').ast.value[0]133 )134 expect($().find('class').value()).to.equal('zrgb')135 })136 })137 describe('#remove', () => {138 it('removes a node', () => {139 const { $ } = getAST(`140 .r { color: $_r; }141 .g { color: $_g; }142 .b { color: $_b; }143 `)144 const rulesBefore = $('rule').get()145 $('rule').eq(1).remove()146 const rulesAfter = $('rule').get()147 expect(rulesAfter).to.deep.equal([rulesBefore[0], rulesBefore[2]])148 })149 })150 describe('#map', () => {151 it('works', () => {152 const { $ } = getAST(`153 $border: 1px 2px 3px;154 `)155 const numbers = $('number').map((n) => {156 return $(n).value()157 })158 expect(numbers).to.deep.equal(['1', '2', '3'])159 })160 })161 describe('#reduce', () => {162 it('works', () => {163 const { $ } = getAST(`164 $border: 1px 2px 3px;165 `)166 const numbers = $('number').reduce((acc, n) => {167 return acc + $(n).value()168 }, '')169 expect(numbers).to.deep.equal('123')170 })171 })172 describe('#concat', () => {173 it('works', () => {174 const { $ } = getAST(`175 $border: 1px 2px 3px;176 `)177 const numbersA = $('number').eq(0)178 const numbersB = $('number').eq(1)179 expect(numbersA.concat(numbersB).value()).to.deep.equal('12')180 })181 })182 describe('#replace', () => {183 it('removes a node', () => {184 const { $ } = getAST(`185 $border: 1px 2px 3px;186 `)187 $('number').first().replace((n) => {188 return { type: 'number', value: '8' }189 })190 expect($().find('number').first().value()).to.equal('8')191 })192 })193 describe('#children', () => {194 it('returns direct children of a node', () => {195 const { $ } = getAST(`196 $border: 1px 2px 3px;197 `)198 const children = $()199 .find('value')200 .children()201 expect(children.length()).to.equal(9)202 })203 it('returns direct children of multiple nodes', () => {204 const { $ } = getAST(`205 $borderA: 1px 2px 3px;206 $borderB: 4px 5px 6px;207 `)208 const children = $()209 .find('value')210 .children()211 expect(children.length()).to.equal(18)212 })213 it('returns direct children of multiple nodes filterd by a selector', () => {214 const { $ } = getAST(`215 $borderA: 1px 2px 3px;216 $borderB: 4px 5px 6px;217 `)218 const children = $()219 .find('value')220 .children('number')221 expect(children.length()).to.equal(6)222 })223 })224 describe('#closest', () => {225 it('works', () => {226 const { $ } = getAST(`227 .r { color: $_r; }228 `)229 const blocks = $()230 .find('variable')231 .closest('block')232 .get()233 const block = $().find('block').get(0)234 expect(blocks).to.deep.equal([block])235 })236 })237 describe('#eq', () => {238 it('selects the node at the specified index', () => {239 const { $ } = getAST(`240 .r { color: $_r; }241 .g { color: $_g; }242 .b { color: $_b; }243 `)244 const className = $()245 .find('rule')246 .eq(1)247 .find('class')248 .value()249 expect(className).to.equal('g')250 })251 })252 describe('#find', () => {253 it('selects all nodes matching a type', () => {254 const { $ } = getAST(`255 .r { color: $_r; }256 `)257 const variables = $()258 .find('variable')259 .get()260 expect(variables.map(getValue)).to.deep.equal(['_r'])261 })262 it('selects based on the previous selection', () => {263 const { $ } = getAST(`264 $hello: world;265 .b { color: $_b; }266 .g { color: $_g; }267 `)268 const variables = $()269 .find('rule')270 .find('variable')271 .get()272 expect(variables.map(getValue)).to.deep.equal(['_b', '_g'])273 })274 })275 describe('#filter', () => {276 it('filters a selection', () => {277 const { $ } = getAST(`278 .r { color: $_r; }279 .g { color: $_g; }280 .b { color: $_b; }281 `)282 const className = $()283 .find('class')284 .filter((n) => $(n).value() === 'g')285 .value()286 expect(className).to.equal('g')287 })288 it('filters a selection inverse', () => {289 const { $ } = getAST(`290 .r { color: $_r; }291 .g { color: $_g; }292 .b { color: $_b; }293 `)294 const notSpaces = $()295 .children()296 .filter((n) => n.node.type !== 'space')297 expect(notSpaces.length()).to.equal(3)298 })299 })300 describe('#first', () => {301 it('selects the first item in a selection', () => {302 const { $ } = getAST(`303 .r { color: $_r; }304 .g { color: $_g; }305 .b { color: $_b; }306 `)307 const actual = $()308 .find('class')309 .first()310 expect(actual.get()).to.have.length(1)311 expect(actual.value()).to.equal('r')312 })313 })314 describe('#has', () => {315 it('filters a selection to those that have a descendant that match the selector', () => {316 const { $ } = getAST(`317 .r { color: $_r; }318 .g { color: #{$_g}; }319 .b { color: $_b; }320 `)321 const rules = $()322 .find('rule')323 const rulesInterpolation = $()324 .find('rule')325 .has('interpolation')326 expect(rulesInterpolation.length()).to.equal(1)327 expect(rulesInterpolation.get(0)).to.deep.equal(rules.get(1))328 })329 })330 describe('#hasParent', () => {331 it('filters a selection to those that have a descendant that match the selector', () => {332 const { $ } = getAST(`333 .r { color: $_r; }334 .g { color: #{$_g}; }335 .b { color: $_b; }336 `)337 const variables = $()338 .find('variable')339 const variablesInterpolation = variables.hasParent('interpolation')340 expect(variablesInterpolation.length()).to.equal(1)341 expect(variablesInterpolation.get(0)).to.deep.equal(variables.get(1))342 })343 })344 describe('#hasParents', () => {345 it('filters a selection to those that have a descendant that match the selector', () => {346 const { $ } = getAST(`347 .r { color: $_r; }348 .g { color: #{$_g}; }349 .b { color: $_b; }350 `)351 const variables = $()352 .find('variable')353 const variablesInsideG = variables.hasParents((n) => {354 return n.node.type === 'rule' && $(n).has((n) => {355 return n.node.type === 'class' && $(n).value() === 'g'356 }).length()357 })358 expect(variablesInsideG.length()).to.equal(1)359 expect(variablesInsideG.get(0)).to.deep.equal(variables.get(1))360 })361 })362 describe('#last', () => {363 it('selects the last item in a selection', () => {364 const { $ } = getAST(`365 .r { color: $_r; }366 .g { color: $_g; }367 .b { color: $_b; }368 `)369 const classes = $()370 .find('class')371 .last()372 expect(classes.get()).to.have.length(1)373 expect(classes.value()).to.equal('b')374 })375 })376 describe('#next', () => {377 it('selects the next sibling for each item in the selection', () => {378 const { $ } = getAST(`379 .r { color: $_r; }380 .g { color: $_g; }381 .b { color: $_b; }382 `)383 const node = $()384 .find('rule')385 .eq(1) // .g386 .next() // space387 .next() // .b388 expect(node.find('class').value()).to.equal('b')389 })390 it('optionally filters selection', () => {391 const { $ } = getAST(`392 .r { color: $_r; }393 .g { color: $_g; }394 .b { color: $_b; }395 `)396 const node = $()397 .find('rule')398 .eq(1)399 .next('rule')400 // a "space" node is the next node401 expect(node.length()).to.equal(0)402 })403 })404 describe('#nextAll', () => {405 it('selects the next sibling for each item in the selection', () => {406 const { $ } = getAST(`407 .r { color: $_r; }408 .g { color: $_g; }409 .b { color: $_b; }410 `)411 const nodes = $()412 .find('rule')413 .eq(1)414 .nextAll()415 .get()416 expect(nodes.map(getType)).to.deep.equal(['space', 'rule', 'space'])417 })418 it('optionally filters selection', () => {419 const { $ } = getAST(`420 .r { color: $_r; }421 .g { color: $_g; }422 .b { color: $_b; }423 `)424 const nodes = $()425 .find('rule')426 .eq(0)427 .nextAll('rule')428 .find('class')429 expect(nodes.map((n) => $(n).value())).to.deep.equal(['g', 'b'])430 })431 })432 describe('#parent', () => {433 it('works', () => {434 const { $ } = getAST(`435 @mixin myMixin ($a) {}436 .r { color: $_r; }437 .g { color: $_g; }438 .b { color: $_b; }439 `)440 const parents = $()441 .find('variable')442 .parent()443 .get()444 expect(parents.map(getType)).to.deep.equal([445 'arguments', 'value', 'value', 'value'446 ])447 })448 it('optionally filters selection', () => {449 const { $ } = getAST(`450 @mixin myMixin ($a) {}451 .r { color: $_r; }452 .g { color: $_g; }453 .b { color: $_b; }454 `)455 const parents = $()456 .find('variable')457 .parent('arguments')458 .get()459 expect(parents.map(getType)).to.deep.equal(['arguments'])460 })461 })462 describe('#parents', () => {463 it('works', () => {464 const { $ } = getAST(`465 .r { color: $_r; }466 `)467 const parents = $()468 .find('variable')469 .parents()470 .get()471 expect(parents.map(getType)).to.deep.equal([472 'value', 'declaration', 'block', 'rule', 'stylesheet'473 ])474 })475 it('optionally filters selection', () => {476 const { $ } = getAST(`477 .r { color: $_r; }478 `)479 const parents = $()480 .find('variable')481 .parents('rule')482 .get()483 expect(parents.map(getType)).to.deep.equal(['rule'])484 })485 })486 describe('#parentsUntil', () => {487 it('works', () => {488 const { $ } = getAST(`489 .r { color: $_r; }490 `)491 const parents = $()492 .find('variable')493 .parentsUntil('rule')494 .get()495 expect(parents.map(getType)).to.deep.equal([496 'value', 'declaration', 'block'497 ])498 })499 })500 describe('#prev', () => {501 it('selects the previous sibling for each item in the selection', () => {502 const { $ } = getAST(`503 .r { color: $_r; }504 .g { color: $_g; }505 .b { color: $_b; }506 `)507 const node = $()508 .find('rule')509 .eq(1) // .g510 .prev() // space511 .prev() // .r512 expect(node.find('class').value()).to.equal('r')513 })514 it('optionally filters selection', () => {515 const { $ } = getAST(`516 .r { color: $_r; }517 .g { color: $_g; }518 .b { color: $_b; }519 `)520 const node = $()521 .find('rule')522 .eq(1)523 .prev('rule')524 // a "space" node is the prev node525 expect(node.length()).to.equal(0)526 })527 })528 describe('#prevAll', () => {529 it('selects the previous sibling for each item in the selection', () => {530 const { $ } = getAST(`531 .r { color: $_r; }532 .g { color: $_g; }533 .b { color: $_b; }534 `)535 const nodes = $()536 .find('rule')537 .eq(1)538 .prevAll()539 .get()540 expect(nodes.map(getType)).to.deep.equal(['space', 'rule', 'space'])541 })542 it('optionally filters selection', () => {543 const { $ } = getAST(`544 .r { color: $_r; }545 .g { color: $_g; }546 .b { color: $_b; }547 `)548 const classNames = $()549 .find('rule')550 .eq(2)551 .prevAll('rule')552 .find('class')553 .value()554 expect(classNames).to.deep.equal('gr')555 })556 })557 describe('#value', () => {558 it('reduces all nodes with a string value', () => {559 const { $ } = getAST(`560 .r { .g { .b {} } }561 .c .m .y .k { }562 `)563 const value = $()564 .find('class')565 .value()566 expect(value).to.deep.equal('rgbcmyk')567 })568 it('reduces all nodes with a string value (interpolation)', () => {569 const { $ } = getAST(`570 .r-#{g}-#{b} { color: $red; }571 `)572 const value = $()573 .find('class')574 .value()575 expect(value).to.deep.equal('r-g-b')576 })577 })...
dependencyTests.js
Source:dependencyTests.js
1/*******************************************************************************2 * @license3 * Copyright (c) 2015, 2016 IBM Corporation and others.4 * All rights reserved. This program and the accompanying materials are made 5 * available under the terms of the Eclipse Public License v1.0 6 * (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution 7 * License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html). 8 * 9 * Contributors: IBM Corporation - initial API and implementation10 ******************************************************************************/11/*eslint-env amd, mocha, node*/12/* eslint-disable missing-nls */13define([14 'chai/chai',15 'javascript/astManager',16 'orion/Deferred',17 'mocha/mocha' //must stay last, not a module18], function(chai, ASTManager, Deferred) {19 var assert = chai.assert;20 return /* @callback */ function(worker) {21 var astManager = new ASTManager.ASTManager();22 23 /**24 * @description Sets up the test25 * @param {Object} options The options the set up with26 * @returns {Object} The object with the initialized values27 */28 function setup(options) {29 var buffer = typeof options.buffer === 'undefined' ? '' : options.buffer,30 contentType = options.contenttype ? options.contenttype : 'application/javascript',31 file = 'dep_analysis_test_script.js';32 33 var editorContext = {34 /*override*/35 getText: function() {36 return new Deferred().resolve(buffer);37 },38 39 getFileMetadata: function() {40 var o = Object.create(null);41 o.contentType = Object.create(null);42 o.contentType.id = contentType;43 o.location = file;44 return new Deferred().resolve(o);45 }46 };47 astManager.onModelChanging({file: {location: file}});48 return {49 editorContext: editorContext50 };51 }52 53 /**54 * @description Checks the deps from the AST against the given list55 * @param {object} ast The AST56 * @param {Array.<string>} expected The array of expected values57 */58 function assertDeps(ast, expected) {59 assert(ast, 'An AST was not produced');60 assert(expected, 'You must provide an expected array of dependencies');61 assert(ast.dependencies, 'There were no dependencies in the produced AST');62 var len = ast.dependencies.length;63 assert.equal(len, expected.length, 'The number of computed dependencies and expected ones differs');64 for(var i = 0; i < len; i++) {65 var dep = ast.dependencies[i];66 if(typeof expected[i] === 'object') {67 assert.equal(dep.value, expected[i].value, 'The name of the dependent does not match');68 assert.equal(dep.env, expected[i].env, 'The name of the dependent env does not match');69 } else {70 assert.equal(dep.value, expected[i], 'The name of the dependent does not match');71 }72 }73 }74 /**75 * @description Checks the envs from the AST against the given list76 * @param {object} ast The AST77 * @param {Array.<string>} expected The array of expected values78 */79 function assertEnvs(ast, expected) {80 assert(ast, 'An AST was not produced');81 assert(expected, 'You must provide an expected array of envs');82 assert(ast.environments, 'There were no envs in the produced AST');83 for(var i = 0, len = expected.length; i < len; i++) {84 assert(ast.environments[expected[i]], 'There is no computed env \''+expected[i]+'\'.');85 }86 }87 describe('Environment Analysis Tests', function() {88 it("commonjs - define(func)", function() {89 var _s = setup({buffer: 'define(function(require) {var foo = require(\'somelib\');});'});90 return astManager.getAST(_s.editorContext).then(function(ast) {91 assertDeps(ast, [{value: 'somelib', env: 'commonjs'}]);92 assertEnvs(ast, ['amd', 'node']);93 });94 });95 it("amd - object expression", function() {96 var _s = setup({buffer: 'define({one: 1});'});97 return astManager.getAST(_s.editorContext).then(function(ast) {98 assertDeps(ast, []);99 assertEnvs(ast, ['amd']);100 });101 });102 it("node - simple", function() {103 var _s = setup({buffer: 'var _n = require(\'somelib\')'});104 return astManager.getAST(_s.editorContext).then(function(ast) {105 assertDeps(ast, ['somelib']);106 assertEnvs(ast, ['node']);107 });108 });109 });110 describe('Dependency Analysis Tests', function() {111 describe('Node Require', function(){112 it("require module", function() {113 var _s = setup({buffer: 'var foo = require("a");'});114 return astManager.getAST(_s.editorContext).then(function(ast) {115 assertDeps(ast, ['a']);116 });117 });118 it("multiple require modules", function() {119 var _s = setup({buffer: 'var foo = require("a");\nvar foo2 = require("b");'});120 return astManager.getAST(_s.editorContext).then(function(ast) {121 assertDeps(ast, ['a', 'b']);122 });123 });124 });125 describe('ES Module Import', function(){126 it("import * from module", function() {127 var _s = setup({buffer: 'import * from "a";'});128 return astManager.getAST(_s.editorContext).then(function(ast) {129 assertDeps(ast, ['a']);130 });131 });132 it("import defaultMember from module", function() {133 var _s = setup({buffer: 'import defaultMember from "a";'});134 return astManager.getAST(_s.editorContext).then(function(ast) {135 assertDeps(ast, ['a']);136 });137 });138 it("import { foo } from module", function() {139 var _s = setup({buffer: 'import {foo} from "a";'});140 return astManager.getAST(_s.editorContext).then(function(ast) {141 assertDeps(ast, ['a']);142 });143 });144 it("import { foo as difFoo } from module", function() {145 var _s = setup({buffer: 'import {foo as difFoo} from "a";'});146 return astManager.getAST(_s.editorContext).then(function(ast) {147 assertDeps(ast, ['a']);148 });149 });150 it("import multiple members from module", function() {151 var _s = setup({buffer: 'import { foobar, foo as difFoo} from "a";'});152 return astManager.getAST(_s.editorContext).then(function(ast) {153 assertDeps(ast, ['a']);154 });155 });156 it("import module only", function() {157 var _s = setup({buffer: 'import "a";'});158 return astManager.getAST(_s.editorContext).then(function(ast) {159 assertDeps(ast, ['a']);160 });161 });162 }); 163 describe('RequireJS', function(){164 it("Collect deps define 1", function() {165 var _s = setup({buffer: 'define("foo", ["a"], function(A){});'});166 return astManager.getAST(_s.editorContext).then(function(ast) {167 assertDeps(ast, ['a']);168 });169 });170 it("Collect deps define 2", function() {171 var _s = setup({buffer: 'define(["a"], function(A){});'});172 return astManager.getAST(_s.editorContext).then(function(ast) {173 assertDeps(ast, ['a']);174 });175 });176 it("Collect deps define 3", function() {177 var _s = setup({buffer: 'define(["a", "b", "C"], function(A){});'});178 return astManager.getAST(_s.editorContext).then(function(ast) {179 assertDeps(ast, ['a', 'b', 'C']);180 });181 });182 it("Collect deps importScripts 1", function() {183 var _s = setup({buffer: 'importScripts("a.js");'});184 return astManager.getAST(_s.editorContext).then(function(ast) {185 assertDeps(ast, ['a.js']);186 });187 });188 it("Collect deps importScripts 2", function() {189 var _s = setup({buffer: 'importScripts("a.js", "b.js");'});190 return astManager.getAST(_s.editorContext).then(function(ast) {191 assertDeps(ast, ['a.js', 'b.js']);192 });193 });194 it("Collect deps Worker", function() {195 var _s = setup({buffer: 'var myworker = new Worker("a.js")'});196 return astManager.getAST(_s.editorContext).then(function(ast) {197 assertDeps(ast, ['a.js']);198 });199 });200 it("Collect deps require 1", function() {201 var _s = setup({buffer: 'var _r = require("a")'});202 return astManager.getAST(_s.editorContext).then(function(ast) {203 assertDeps(ast, ['a']);204 });205 });206 it("Collect deps require 1", function() {207 var _s = setup({buffer: 'var _r = require("a");'}); //node + requirejs208 return astManager.getAST(_s.editorContext).then(function(ast) {209 assertDeps(ast, ['a']);210 });211 });212 it("Collect deps require 2", function() {213 var _s = setup({buffer: 'var _r = require(["a"], function(){});'}); //requirejs214 return astManager.getAST(_s.editorContext).then(function(ast) {215 assertDeps(ast, ['a']);216 });217 });218 it("Collect deps require 3", function() {219 var _s = setup({buffer: 'var _r = require(["a", "b", "c"], function(){});'}); //requirejs220 return astManager.getAST(_s.editorContext).then(function(ast) {221 assertDeps(ast, ['a', 'b', 'c']);222 });223 });224 it("Collect deps require 4", function() {225 var _s = setup({buffer: 'var _r = require({paths:{"a": "a/b"}}, ["a", "b", "c"], function(){});'}); //requirejs226 return astManager.getAST(_s.editorContext).then(function(ast) {227 assertDeps(ast, ['a', 'b', 'c']);228 });229 });230 it("Collect deps require 5", function() {231 var _s = setup({buffer: 'var _r = require();'}); //requirejs232 return astManager.getAST(_s.editorContext).then(function(ast) {233 assertDeps(ast, []);234 });235 });236 it("Collect deps requirejs 1", function() {237 var _s = setup({buffer: 'var _r = requirejs(["a", "b", "c"], function(){});'}); //requirejs238 return astManager.getAST(_s.editorContext).then(function(ast) {239 assertDeps(ast, ['a', 'b', 'c']);240 });241 });242 /**243 * @see https://bugs.eclipse.org/bugs/show_bug.cgi?id=476370244 * @since 10.0245 */246 it("Collect deps requirejs + require", function() {247 var _s = setup({buffer: '(function(root, mod) {if (typeof exports == "object" && typeof module == "object") return mod(exports, require("./infer"), require("./signal"), require("esprima"), require("acorn/dist/walk")); if (typeof define == "function" && define.amd) return define(["exports", "./infer", "./signal", "esprima", "acorn/dist/walk"], mod); mod(root.tern || (root.tern = {}), tern, tern.signal, acorn, acorn.walk);})(this, function(exports, infer, signal, acorn, walk) {})'}); //requirejs248 return astManager.getAST(_s.editorContext).then(function(ast) {249 assertDeps(ast, ['./infer', './signal', 'esprima', 'acorn/dist/walk', 'exports']);250 });251 });252 });253 });254 };...
parser-specs.js
Source:parser-specs.js
...4 'use strict';5 describe('when parsing', function() {6 it('simple metric expression', function() {7 var parser = new Parser('metric.test.*.asd.count');8 var rootNode = parser.getAst();9 expect(rootNode.type).to.be('metric');10 expect(rootNode.segments.length).to.be(5);11 expect(rootNode.segments[0].value).to.be('metric');12 });13 it('simple metric expression with numbers in segments', function() {14 var parser = new Parser('metric.10.15_20.5');15 var rootNode = parser.getAst();16 expect(rootNode.type).to.be('metric');17 expect(rootNode.segments.length).to.be(4);18 expect(rootNode.segments[1].value).to.be('10');19 expect(rootNode.segments[2].value).to.be('15_20');20 expect(rootNode.segments[3].value).to.be('5');21 });22 it('simple metric expression with curly braces', function() {23 var parser = new Parser('metric.se1-{count, max}');24 var rootNode = parser.getAst();25 expect(rootNode.type).to.be('metric');26 expect(rootNode.segments.length).to.be(2);27 expect(rootNode.segments[1].value).to.be('se1-{count,max}');28 });29 it('simple metric expression with curly braces at start of segment and with post chars', function() {30 var parser = new Parser('metric.{count, max}-something.count');31 var rootNode = parser.getAst();32 expect(rootNode.type).to.be('metric');33 expect(rootNode.segments.length).to.be(3);34 expect(rootNode.segments[1].value).to.be('{count,max}-something');35 });36 it('simple function', function() {37 var parser = new Parser('sum(test)');38 var rootNode = parser.getAst();39 expect(rootNode.type).to.be('function');40 expect(rootNode.params.length).to.be(1);41 });42 it('simple function2', function() {43 var parser = new Parser('offset(test.metric, -100)');44 var rootNode = parser.getAst();45 expect(rootNode.type).to.be('function');46 expect(rootNode.params[0].type).to.be('metric');47 expect(rootNode.params[1].type).to.be('number');48 });49 it('simple function with string arg', function() {50 var parser = new Parser("randomWalk('test')");51 var rootNode = parser.getAst();52 expect(rootNode.type).to.be('function');53 expect(rootNode.params.length).to.be(1);54 expect(rootNode.params[0].type).to.be('string');55 });56 it('function with multiple args', function() {57 var parser = new Parser("sum(test, 1, 'test')");58 var rootNode = parser.getAst();59 expect(rootNode.type).to.be('function');60 expect(rootNode.params.length).to.be(3);61 expect(rootNode.params[0].type).to.be('metric');62 expect(rootNode.params[1].type).to.be('number');63 expect(rootNode.params[2].type).to.be('string');64 });65 it('function with nested function', function() {66 var parser = new Parser("sum(scaleToSeconds(test, 1))");67 var rootNode = parser.getAst();68 expect(rootNode.type).to.be('function');69 expect(rootNode.params.length).to.be(1);70 expect(rootNode.params[0].type).to.be('function');71 expect(rootNode.params[0].name).to.be('scaleToSeconds');72 expect(rootNode.params[0].params.length).to.be(2);73 expect(rootNode.params[0].params[0].type).to.be('metric');74 expect(rootNode.params[0].params[1].type).to.be('number');75 });76 it('function with multiple series', function() {77 var parser = new Parser("sum(test.test.*.count, test.timers.*.count)");78 var rootNode = parser.getAst();79 expect(rootNode.type).to.be('function');80 expect(rootNode.params.length).to.be(2);81 expect(rootNode.params[0].type).to.be('metric');82 expect(rootNode.params[1].type).to.be('metric');83 });84 it('function with templated series', function() {85 var parser = new Parser("sum(test.[[server]].count)");86 var rootNode = parser.getAst();87 expect(rootNode.message).to.be(undefined);88 expect(rootNode.params[0].type).to.be('metric');89 expect(rootNode.params[0].segments[1].type).to.be('segment');90 expect(rootNode.params[0].segments[1].value).to.be('[[server]]');91 });92 it('invalid metric expression', function() {93 var parser = new Parser('metric.test.*.asd.');94 var rootNode = parser.getAst();95 expect(rootNode.message).to.be('Expected metric identifier instead found end of string');96 expect(rootNode.pos).to.be(19);97 });98 it('invalid function expression missing closing paranthesis', function() {99 var parser = new Parser('sum(test');100 var rootNode = parser.getAst();101 expect(rootNode.message).to.be('Expected closing paranthesis instead found end of string');102 expect(rootNode.pos).to.be(9);103 });104 it('unclosed string in function', function() {105 var parser = new Parser("sum('test)");106 var rootNode = parser.getAst();107 expect(rootNode.message).to.be('Unclosed string parameter');108 expect(rootNode.pos).to.be(11);109 });110 it('handle issue #69', function() {111 var parser = new Parser('cactiStyle(offset(scale(net.192-168-1-1.192-168-1-9.ping_value.*,0.001),-100))');112 var rootNode = parser.getAst();113 expect(rootNode.type).to.be('function');114 });115 it('handle float function arguments', function() {116 var parser = new Parser('scale(test, 0.002)');117 var rootNode = parser.getAst();118 expect(rootNode.type).to.be('function');119 expect(rootNode.params[1].type).to.be('number');120 expect(rootNode.params[1].value).to.be(0.002);121 });122 it('handle curly brace pattern at start', function() {123 var parser = new Parser('{apps}.test');124 var rootNode = parser.getAst();125 expect(rootNode.type).to.be('metric');126 expect(rootNode.segments[0].value).to.be('{apps}');127 expect(rootNode.segments[1].value).to.be('test');128 });129 it('series parameters', function() {130 var parser = new Parser('asPercent(#A, #B)');131 var rootNode = parser.getAst();132 expect(rootNode.type).to.be('function');133 expect(rootNode.params[0].type).to.be('series-ref');134 expect(rootNode.params[0].value).to.be('#A');135 expect(rootNode.params[1].value).to.be('#B');136 });137 });...
ast-get.test.js
Source:ast-get.test.js
1import tape from 'tape';2import astToJson from './util-ast-to-json';3import getAST from '../src/ast-get';4tape('getAST()', t => {5 t.deepEqual(astToJson(...getAST('a @href')), {6 ctx: 'a',7 attr: 'href'8 });9 t.deepEqual(astToJson(...getAST('a @href => url')), {10 ctx: 'a',11 alias: 'url',12 attr: 'href'13 });14 t.deepEqual(astToJson(...getAST('a { @href }')), {15 ctx: 'a',16 children: [17 {18 ctx: '',19 alias: 'href',20 attr: 'href'21 }22 ]23 });24 t.deepEqual(astToJson(...getAST('a { @href, @.textContent }')), {25 ctx: 'a',26 children: [27 {28 ctx: '',29 alias: 'href',30 attr: 'href'31 },32 {33 ctx: '',34 alias: '.textContent',35 attr: '.textContent'36 }37 ]38 });39 t.deepEqual(astToJson(...getAST('a { @href => url }')), {40 ctx: 'a',41 children: [42 {43 ctx: '',44 alias: 'url',45 attr: 'href'46 }47 ]48 });49 t.deepEqual(50 astToJson(...getAST('a { @href >> url, @.textContent => text }')),51 {52 ctx: 'a',53 children: [54 {55 ctx: '',56 attr: 'href',57 alias: 'url'58 },59 {60 ctx: '',61 attr: '.textContent',62 alias: 'text'63 }64 ]65 }66 );67 t.deepEqual(68 astToJson(69 ...getAST(`dt { 70 a { @href, @.textContent },71 :scope + dd @.textContent72 }`)73 ),74 {75 ctx: 'dt',76 children: [77 {78 ctx: 'a',79 children: [80 {81 ctx: '',82 alias: 'href',83 attr: 'href'84 },85 {86 ctx: '',87 alias: '.textContent',88 attr: '.textContent'89 }90 ]91 },92 {93 ctx: ':scope + dd',94 attr: '.textContent'95 }96 ]97 }98 );99 t.end();100});101tape('commas and CSS semantics', t => {102 t.deepEqual(103 astToJson(...getAST('h2, h3')),104 {105 ctx: ':root',106 first: true,107 children: [{ ctx: 'h2' }, { ctx: 'h3' }]108 },109 'commas'110 );111 t.deepEqual(112 astToJson(...getAST('{ h2, h3 }')),113 {114 ctx: ':root',115 children: [{ ctx: 'h2' }, { ctx: 'h3' }]116 },117 'commas w/ group'118 );119 t.deepEqual(120 astToJson(...getAST(':is(h2, h3)')),121 {122 ctx: ':matches(h2,h3)'123 },124 ':is()'125 );126 t.end();127});128tape('Syntax errors', t => {129 t.throws(() => {130 getAST('a { @href }}');131 }, /Unexpected \}/);132 t.throws(() => {133 getAST('li { @title, a { @href }');134 }, /Missing \}/);135 t.throws(() => {136 getAST('a:is(a, b))');137 }, /Unexpected \)/);138 t.throws(() => {139 getAST('li:not(a, b');140 }, /Missing \)/);141 t.throws(() => {142 getAST('a @{href}');143 }, /after \@/);144 t.throws(() => {145 getAST('a >>{href}');146 }, /after \>\>/);147 t.end();148});149tape('^ (first)', t => {150 t.deepEqual(151 astToJson(...getAST('a[href^="#"]')),152 {153 ctx: 'a[href^="#"]'154 },155 'ignore ^ unless first token'156 );157 t.deepEqual(158 astToJson(...getAST('a { ^ span }')),159 {160 ctx: 'a',161 children: [162 {163 ctx: 'span',164 first: true165 }166 ]167 },168 'identify ^ as first'169 );170 t.end();171});172tape('attribute wildcard', t => {173 t.deepEqual(astToJson(...getAST('a @*')), { ctx: 'a', attr: '*' });174 t.deepEqual(175 astToJson(...getAST('a { @* => . }')),176 { ctx: 'a', children: [{ ctx: '', attr: '*', alias: '.' }] },177 'spread via alias'178 );179 t.deepEqual(180 astToJson(...getAST('a { ...@* }')),181 { ctx: 'a', children: [{ ctx: '', attr: '*', alias: '.' }] },182 'spread via ellipsis'183 );184 t.end();...
test-ast.js
Source:test-ast.js
1import test from 'ava';2import { getAst } from '../assertions';3test('does not include the lang directive in the AST', t => {4 t.snapshot(5 getAst(`6 'lang sweet.js';7 `),8 );9});10test('does include the use strict directive in the AST', t => {11 t.snapshot(12 getAst(`13 'use strict';14 `),15 );16});17test('includes export in AST', t => {18 t.snapshot(19 getAst(`20 export { b }21 `),22 );23});24test('includes export with renaming in AST', t => {25 t.snapshot(26 getAst(`27 export { b as c}28 `),29 );30});31test('includes export declaration in AST', t => {32 t.snapshot(33 getAst(`34 export var x = 1;35 `),36 );37});38test('includes support for async function declarations', t => {39 t.snapshot(40 getAst(`41 async function f() {}42 `),43 );44});45test('includes support for async function expressions', t => {46 t.snapshot(47 getAst(`48 let f = async function f() {}49 `),50 );51});52test('includes support for exporting async functions', t => {53 t.snapshot(54 getAst(`55 export async function f() {}56 `),57 );58});59test('includes support for exporting default async functions', t => {60 t.snapshot(61 getAst(`62 export default async function f() {}63 `),64 );65});66test('includes no-line-terminator requirement for async functions', t => {67 t.snapshot(68 getAst(`69 async 70 function f() {}71 `),72 );73});74test('includes no-line-terminator requirement for async function expressions', t => {75 t.snapshot(76 getAst(`77 let f = async 78 function f() {}79 `),80 );81});82test('includes support for async arrow functions', t => {83 t.snapshot(84 getAst(`85 let f = async () => {}86 `),87 );88});89test('includes support for async method definitions', t => {90 t.snapshot(91 getAst(`92 class C {93 async f() {}94 }95 `),96 );97});98test('handles properties named async', t => {99 t.snapshot(100 getAst(`101 let o = {102 async: true103 }104 `),105 );106});107test('includes support for await', t => {108 t.snapshot(109 getAst(`110 async function f () {111 await g();112 }113 `),114 );...
component-properties.test.js
Source:component-properties.test.js
...5const glob = require('glob');6const files = glob.sync(path.join(process.cwd(), 'tests/data/**/*component.ts'));7files.forEach(file => {8 test('#get should not return $inject property', t => {9 const ast = getAst(file);10 const result = properties.get(ast);11 t.false(/\$inject/.test(result), file);12 });13 test('#get should not return $onInit property', t => {14 const ast = getAst(file);15 const result = properties.get(ast);16 t.false(/[public|private] \$onInit/.test(result), file);17 });18 test('#get should not return $onChanges property', t => {19 const ast = getAst(file);20 const result = properties.get(ast);21 t.false(/[public|private] \$onChanges/.test(result), file);22 });23 test('#get should not return $onDestroy property', t => {24 const ast = getAst(file);25 const result = properties.get(ast);26 t.false(/[public|private] \$onDestroy/.test(result), file);27 });28 test('#get should not return the constructor', t => {29 const ast = getAst(file);30 const result = properties.get(ast);31 t.false(/constructor/.test(result), file);32 }); ...
mangle-pray
Source:mangle-pray
...21 out.push(manglePray(el));22 });23 return out;24}25var getAst = exports.getAst = function getAst(fname) {26 var code = fs.readFileSync(fname, 'utf-8');27 return uglifyjs.parser.parse(code);28}29function main() {30 var fname = process.argv[2];31 var ast = manglePray(getAst(fname));32 process.stdout.write(uglifyjs.uglify.gen_code(ast));33}...
example.js
Source:example.js
...39 // params: "body[**type=BlockStatement].path.original"40 }41 }42};43// console.log(JSON.stringify(getAst(code)))44export default {45 ast: getAst(code),46 rules,47 code,48 getAst...
Using AI Code Generation
1const ladle = require('ladle');2const ast = ladle.getAst('test.js');3const ladle = require('ladle');4const ast = ladle.getAst('test.js');5ladle.getAst(path);6ladle.getAstOfAllFiles(path);7ladle.getAstOfAllFilesRecursively(path);8ladle.getAstOfAllFilesWithExtension(path, extension);
Using AI Code Generation
1var ladle = require('ladle');2var ast = ladle.getAst('var a = 5;');3console.log(ast);4var ladle = require('ladle');5var ast = ladle.getAst('var a = 5;');6console.log(ast);7var ladle = require('ladle');8var ast = ladle.getAst('var a = 5;');9console.log(ast);10var ladle = require('ladle');11var ast = ladle.getAst('var a = 5;');12console.log(ast);13var ladle = require('ladle');14var ast = ladle.getAst('var a = 5;');15console.log(ast);16var ladle = require('ladle');17var ast = ladle.getAst('var a = 5;');18console.log(ast);19var ladle = require('
Using AI Code Generation
1var ladle = require("ladle");2var ast = ladle.getAst("test.js");3console.log(ast);4var ladle = require("ladle");5var ast = ladle.getAst("test.js");6console.log(ast);7var ladle = require("ladle");8var ast = ladle.getAst("test.js");9console.log(ast);10var ladle = require("ladle");11var ast = ladle.getAst("test.js");12console.log(ast);13var ladle = require("ladle");14var ast = ladle.getAst("test.js");15console.log(ast);16var ladle = require("ladle");17var ast = ladle.getAst("test.js");18console.log(ast);19var ladle = require("ladle");20var ast = ladle.getAst("test.js");21console.log(ast);22var ladle = require("ladle");23var ast = ladle.getAst("test.js");24console.log(ast);25var ladle = require("ladle");26var ast = ladle.getAst("test.js");27console.log(ast);28var ladle = require("ladle");29var ast = ladle.getAst("test.js");30console.log(ast);
Using AI Code Generation
1const ladle = require("ladle");2const ast = ladle.getAst("let a = 1;");3console.log(ast);4const ladle = require("ladle");5const ast = ladle.getAst("let a = 1;");6console.log(ast);7const ladle = require("ladle");8const ast = ladle.getAst("let a = 1;");9console.log(ast);10const ladle = require("ladle");11const ast = ladle.getAst("let a = 1;");12console.log(ast);13const ladle = require("ladle");14const ast = ladle.getAst("let a = 1;");15console.log(ast);16const ladle = require("ladle");17const ast = ladle.getAst("let a = 1;");18console.log(ast);19const ladle = require("ladle");20const ast = ladle.getAst("let a = 1;");21console.log(ast);
Using AI Code Generation
1var ladle = require('ladle');2var ast = ladle.getAst('test.js');3console.log(ast);4var ladle = require('ladle');5var ast = ladle.getAstSync('test.js');6console.log(ast);7var ladle = require('ladle');8ladle.getAstAsync('test.js', function(err, ast) {9 console.log(ast);10});11var ladle = require('ladle');12var ast = ladle.getAstFromCode('var a = 1;');13console.log(ast);14var ladle = require('ladle');15ladle.getAstFromCodeAsync('var a = 1;', function(err, ast) {16 console.log(ast);17});18var ladle = require('ladle');19var ast = ladle.getAstFromCodeSync('var a = 1;');20console.log(ast);21var ladle = require('ladle');22ladle.getAstFromCodeAsync('var a = 1;', function(err, ast) {
Using AI Code Generation
1var ladle = require('ladle');2var ast = ladle.getAst('path/to/file.js');3### `getAst(file, callback)`4var ladle = require('ladle');5ladle.getAst('path/to/file.js', function(ast) {6 console.log(ast);7});8### `getAstSync(file)`9var ladle = require('ladle');10var ast = ladle.getAstSync('path/to/file.js');11### `getAstFromFile(file, callback)`12var ladle = require('ladle');13ladle.getAstFromFile('path/to/file.js', function(ast) {14 console.log(ast);15});16### `getAstSyncFromFile(file)`17var ladle = require('ladle');18var ast = ladle.getAstSyncFromFile('path/to/file.js');19### `getAstFromString(string, callback)`20var ladle = require('ladle');21ladle.getAstFromString('var a = 10;', function(ast) {22 console.log(ast);23});
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!!