Best JavaScript code snippet using taiko
ios.js
Source:ios.js  
1!function(root, factory) {2    "function" == typeof define && define.amd ? define([ "exports" ], factory) : factory("undefined" != typeof exports ? exports : root);3}(this, function(exports) {4    function parse(tokens) {5        function consumeAPrimitive() {6            switch (token.tokenType) {7              case "(":8              case "[":9              case "{":10                return consumeASimpleBlock();11              case "FUNCTION":12                return consumeAFunc();13              default:14                return token;15            }16        }17        function consumeASimpleBlock() {18            for (var endingTokenType = {19                "(": ")",20                "[": "]",21                "{": "}"22            }[token.tokenType], block = new SimpleBlock(token.tokenType); ;) switch (consume(), 23            token.tokenType) {24              case "EOF":25              case endingTokenType:26                return block;27              default:28                block.append(consumeAPrimitive());29            }30        }31        function consumeAFunc() {32            for (var func = new Func(token.value), arg = new FuncArg(); ;) switch (consume(), 33            token.tokenType) {34              case "EOF":35              case ")":36                return func.append(arg), func;37              case "DELIM":38                "," == token.value ? (func.append(arg), arg = new FuncArg()) : arg.append(token);39                break;40              default:41                arg.append(consumeAPrimitive());42            }43        }44        for (var token, mode = "top-level", i = -1, stylesheet = new Stylesheet(), stack = [ stylesheet ], rule = stack[0], consume = function(advance) {45            return void 0 === advance && (advance = 1), i += advance, token = i < tokens.length ? tokens[i] : new EOFToken(), 46            !0;47        }, reprocess = function() {48            return i--, !0;49        }, next = function() {50            return tokens[i + 1];51        }, switchto = function(newmode) {52            return void 0 === newmode ? "" !== rule.fillType ? mode = rule.fillType : "STYLESHEET" == rule.type ? mode = "top-level" : (console.log("Unknown rule-type while switching to current rule's content mode: ", rule), 53            mode = "") : mode = newmode, !0;54        }, push = function(newRule) {55            return rule = newRule, stack.push(rule), !0;56        }, parseerror = function(msg) {57            return console.log("Parse error at token " + i + ": " + token + ".\n" + msg), !0;58        }, pop = function() {59            var oldrule = stack.pop();60            return rule = stack[stack.length - 1], rule.append(oldrule), !0;61        }, discard = function() {62            return stack.pop(), rule = stack[stack.length - 1], !0;63        }, finish = function() {64            for (;stack.length > 1; ) pop();65        }; ;) if (consume(), "DELIM" !== token.tokenType || "\r" !== token.value) switch (mode) {66          case "top-level":67            switch (token.tokenType) {68              case "CDO":69              case "CDC":70              case "WHITESPACE":71                break;72              case "AT-KEYWORD":73                push(new AtRule(token.value)) && switchto("at-rule");74                break;75              case "{":76                parseerror("Attempt to open a curly-block at top-level.") && consumeAPrimitive();77                break;78              case "EOF":79                return finish(), stylesheet;80              default:81                push(new StyleRule()) && switchto("selector") && reprocess();82            }83            break;84          case "at-rule":85            switch (token.tokenType) {86              case ";":87                pop() && switchto();88                break;89              case "{":90                "" !== rule.fillType ? switchto(rule.fillType) : parseerror("Attempt to open a curly-block in a statement-type at-rule.") && discard() && switchto("next-block") && reprocess();91                break;92              case "EOF":93                return finish(), stylesheet;94              default:95                rule.appendPrelude(consumeAPrimitive());96            }97            break;98          case "rule":99            switch (token.tokenType) {100              case "WHITESPACE":101                break;102              case "}":103                pop() && switchto();104                break;105              case "AT-KEYWORD":106                push(new AtRule(token.value)) && switchto("at-rule");107                break;108              case "EOF":109                return finish(), stylesheet;110              default:111                push(new StyleRule()) && switchto("selector") && reprocess();112            }113            break;114          case "selector":115            switch (token.tokenType) {116              case "{":117                switchto("declaration");118                break;119              case "EOF":120                return discard() && finish(), stylesheet;121              default:122                rule.appendSelector(consumeAPrimitive());123            }124            break;125          case "declaration":126            switch (token.tokenType) {127              case "WHITESPACE":128              case ";":129                break;130              case "}":131                pop() && switchto();132                break;133              case "AT-RULE":134                push(new AtRule(token.value)) && switchto("at-rule");135                break;136              case "IDENT":137                push(new Declaration(token.value)) && switchto("after-declaration-name");138                break;139              case "EOF":140                return finish(), stylesheet;141              default:142                parseerror() && discard() && switchto("next-declaration");143            }144            break;145          case "after-declaration-name":146            switch (token.tokenType) {147              case "WHITESPACE":148                break;149              case ":":150                switchto("declaration-value");151                break;152              case ";":153                parseerror("Incomplete declaration - semicolon after property name.") && discard() && switchto();154                break;155              case "EOF":156                return discard() && finish(), stylesheet;157              default:158                parseerror("Invalid declaration - additional token after property name") && discard() && switchto("next-declaration");159            }160            break;161          case "declaration-value":162            switch (token.tokenType) {163              case "DELIM":164                "!" == token.value && "IDENTIFIER" == next().tokenType && "important" == next().value.toLowerCase() ? (consume(), 165                rule.important = !0, switchto("declaration-end")) : rule.append(token);166                break;167              case ";":168                pop() && switchto();169                break;170              case "}":171                pop() && pop() && switchto();172                break;173              case "EOF":174                return finish(), stylesheet;175              default:176                rule.append(consumeAPrimitive());177            }178            break;179          case "declaration-end":180            switch (token.tokenType) {181              case "WHITESPACE":182                break;183              case ";":184                pop() && switchto();185                break;186              case "}":187                pop() && pop() && switchto();188                break;189              case "EOF":190                return finish(), stylesheet;191              default:192                parseerror("Invalid declaration - additional token after !important.") && discard() && switchto("next-declaration");193            }194            break;195          case "next-block":196            switch (token.tokenType) {197              case "{":198                consumeAPrimitive() && switchto();199                break;200              case "EOF":201                return finish(), stylesheet;202              default:203                consumeAPrimitive();204            }205            break;206          case "next-declaration":207            switch (token.tokenType) {208              case ";":209                switchto("declaration");210                break;211              case "}":212                switchto("declaration") && reprocess();213                break;214              case "EOF":215                return finish(), stylesheet;216              default:217                consumeAPrimitive();218            }219            break;220          default:221            return void console.log("Unknown parsing mode: " + mode);222        }223    }224    function CSSParserRule() {225        return this;226    }227    function Stylesheet() {228        return this.value = [], this;229    }230    function AtRule(name) {231        return this.name = name, this.prelude = [], this.value = [], name in AtRule.registry && (this.fillType = AtRule.registry[name]), 232        this;233    }234    function StyleRule() {235        return this.selector = [], this.value = [], this;236    }237    function Declaration(name) {238        return this.name = name, this.value = [], this;239    }240    function SimpleBlock(type) {241        return this.name = type, this.value = [], this;242    }243    function Func(name) {244        return this.name = name, this.value = [], this;245    }246    function FuncArg() {247        return this.value = [], this;248    }249    CSSParserRule.prototype.fillType = "", CSSParserRule.prototype.toString = function(indent) {250        return JSON.stringify(this.toJSON(), null, indent);251    }, CSSParserRule.prototype.append = function(val) {252        return this.value.push(val), this;253    }, Stylesheet.prototype = new CSSParserRule(), Stylesheet.prototype.type = "STYLESHEET", 254    Stylesheet.prototype.toJSON = function() {255        return {256            type: "stylesheet",257            value: this.value.map(function(e) {258                return e.toJSON();259            })260        };261    }, AtRule.prototype = new CSSParserRule(), AtRule.prototype.type = "AT-RULE", AtRule.prototype.appendPrelude = function(val) {262        return this.prelude.push(val), this;263    }, AtRule.prototype.toJSON = function() {264        return {265            type: "at",266            name: this.name,267            prelude: this.prelude.map(function(e) {268                return e.toJSON();269            }),270            value: this.value.map(function(e) {271                return e.toJSON();272            })273        };274    }, AtRule.registry = {275        "import": "",276        media: "rule",277        "font-face": "declaration",278        page: "declaration",279        keyframes: "rule",280        namespace: "",281        "counter-style": "declaration",282        supports: "rule",283        document: "rule",284        "font-feature-values": "declaration",285        viewport: "",286        "region-style": "rule"287    }, StyleRule.prototype = new CSSParserRule(), StyleRule.prototype.type = "STYLE-RULE", 288    StyleRule.prototype.fillType = "declaration", StyleRule.prototype.appendSelector = function(val) {289        return this.selector.push(val), this;290    }, StyleRule.prototype.toJSON = function() {291        return {292            type: "selector",293            selector: this.selector.map(function(e) {294                return e.toJSON();295            }),296            value: this.value.map(function(e) {297                return e.toJSON();298            })299        };300    }, Declaration.prototype = new CSSParserRule(), Declaration.prototype.type = "DECLARATION", 301    Declaration.prototype.toJSON = function() {302        return {303            type: "declaration",304            name: this.name,305            value: this.value.map(function(e) {306                return e.toJSON();307            })308        };309    }, SimpleBlock.prototype = new CSSParserRule(), SimpleBlock.prototype.type = "BLOCK", 310    SimpleBlock.prototype.toJSON = function() {311        return {312            type: "block",313            name: this.name,314            value: this.value.map(function(e) {315                return e.toJSON();316            })317        };318    }, Func.prototype = new CSSParserRule(), Func.prototype.type = "FUNCTION", Func.prototype.toJSON = function() {319        return {320            type: "func",321            name: this.name,322            value: this.value.map(function(e) {323                return e.toJSON();324            })325        };326    }, FuncArg.prototype = new CSSParserRule(), FuncArg.prototype.type = "FUNCTION-ARG", 327    FuncArg.prototype.toJSON = function() {328        return this.value.map(function(e) {329            return e.toJSON();330        });331    }, exports.parse = parse;332}), function(root, factory) {333    "function" == typeof define && define.amd ? define([ "exports" ], factory) : factory("undefined" != typeof exports ? exports : root);334}(this, function(exports) {335    function digit(code) {336        return between(code, 48, 57);337    }338    function hexdigit(code) {339        return digit(code) || between(code, 65, 70) || between(code, 97, 102);340    }341    function uppercaseletter(code) {342        return between(code, 65, 90);343    }344    function lowercaseletter(code) {345        return between(code, 97, 122);346    }347    function letter(code) {348        return uppercaseletter(code) || lowercaseletter(code);349    }350    function nonascii(code) {351        return code >= 160;352    }353    function namestartchar(code) {354        return letter(code) || nonascii(code) || 95 == code;355    }356    function namechar(code) {357        return namestartchar(code) || digit(code) || 45 == code;358    }359    function nonprintable(code) {360        return between(code, 0, 8) || between(code, 14, 31) || between(code, 127, 159);361    }362    function newline(code) {363        return 10 == code || 12 == code;364    }365    function whitespace(code) {366        return newline(code) || 9 == code || 32 == code;367    }368    function badescape(code) {369        return newline(code) || isNaN(code);370    }371    function tokenize(str, options) {372        void 0 == options && (options = {373            transformFunctionWhitespace: !1,374            scientificNotation: !1375        });376        for (var code, currtoken, i = -1, tokens = [], state = "data", line = 0, column = 0, lastLineLength = 0, incrLineno = function() {377            line += 1, lastLineLength = column, column = 0;378        }, locStart = {379            line: line,380            column: column381        }, next = function(num) {382            return void 0 === num && (num = 1), str.charCodeAt(i + num);383        }, consume = function(num) {384            return void 0 === num && (num = 1), i += num, code = str.charCodeAt(i), newline(code) ? incrLineno() : column += num, 385            !0;386        }, reconsume = function() {387            return i -= 1, newline(code) ? (line -= 1, column = lastLineLength) : column -= 1, 388            locStart.line = line, locStart.column = column, !0;389        }, eof = function() {390            return i >= str.length;391        }, donothing = function() {}, emit = function(token) {392            return token ? token.finish() : token = currtoken.finish(), options.loc === !0 && (token.loc = {}, 393            token.loc.start = {394                line: locStart.line,395                column: locStart.column396            }, locStart = {397                line: line,398                column: column399            }, token.loc.end = locStart), tokens.push(token), currtoken = void 0, !0;400        }, create = function(token) {401            return currtoken = token, !0;402        }, parseerror = function() {403            return console.log("Parse error at index " + i + ", processing codepoint 0x" + code.toString(16) + " in state " + state + "."), 404            !0;405        }, catchfire = function(msg) {406            return console.log("MAJOR SPEC ERROR: " + msg), !0;407        }, switchto = function(newstate) {408            return state = newstate, !0;409        }, consumeEscape = function() {410            if (consume(), hexdigit(code)) {411                for (var digits = [], total = 0; 6 > total && hexdigit(code); total++) digits.push(code), 412                consume();413                var value = parseInt(digits.map(String.fromCharCode).join(""), 16);414                return value > maximumallowedcodepoint && (value = 65533), whitespace(code) || reconsume(), 415                value;416            }417            return code;418        }; ;) {419            if (i > 2 * str.length) return "I'm infinite-looping!";420            switch (consume(), state) {421              case "data":422                if (whitespace(code)) for (emit(new WhitespaceToken()); whitespace(next()); ) consume(); else if (34 == code) switchto("double-quote-string"); else if (35 == code) switchto("hash"); else if (39 == code) switchto("single-quote-string"); else if (40 == code) emit(new OpenParenToken()); else if (41 == code) emit(new CloseParenToken()); else if (43 == code) digit(next()) || 46 == next() && digit(next(2)) ? switchto("number") && reconsume() : emit(new DelimToken(code)); else if (45 == code) 45 == next(1) && 62 == next(2) ? consume(2) && emit(new CDCToken()) : digit(next()) || 46 == next(1) && digit(next(2)) ? switchto("number") && reconsume() : switchto("ident") && reconsume(); else if (46 == code) digit(next()) ? switchto("number") && reconsume() : emit(new DelimToken(code)); else if (47 == code) 42 == next() ? consume() && switchto("comment") : emit(new DelimToken(code)); else if (58 == code) emit(new ColonToken()); else if (59 == code) emit(new SemicolonToken()); else if (60 == code) 33 == next(1) && 45 == next(2) && 45 == next(3) ? consume(3) && emit(new CDOToken()) : emit(new DelimToken(code)); else if (64 == code) switchto("at-keyword"); else if (91 == code) emit(new OpenSquareToken()); else if (92 == code) badescape(next()) ? parseerror() && emit(new DelimToken(code)) : switchto("ident") && reconsume(); else if (93 == code) emit(new CloseSquareToken()); else if (123 == code) emit(new OpenCurlyToken()); else if (125 == code) emit(new CloseCurlyToken()); else if (digit(code)) switchto("number") && reconsume(); else if (85 == code || 117 == code) 43 == next(1) && hexdigit(next(2)) ? consume() && switchto("unicode-range") : switchto("ident") && reconsume(); else if (namestartchar(code)) switchto("ident") && reconsume(); else {423                    if (eof()) return emit(new EOFToken()), tokens;424                    emit(new DelimToken(code));425                }426                break;427              case "double-quote-string":428                void 0 == currtoken && create(new StringToken()), 34 == code ? emit() && switchto("data") : eof() ? parseerror() && emit() && switchto("data") && reconsume() : newline(code) ? parseerror() && emit(new BadStringToken()) && switchto("data") && reconsume() : 92 == code ? badescape(next()) ? parseerror() && emit(new BadStringToken()) && switchto("data") : newline(next()) ? consume() : currtoken.append(consumeEscape()) : currtoken.append(code);429                break;430              case "single-quote-string":431                void 0 == currtoken && create(new StringToken()), 39 == code ? emit() && switchto("data") : eof() ? parseerror() && emit() && switchto("data") : newline(code) ? parseerror() && emit(new BadStringToken()) && switchto("data") && reconsume() : 92 == code ? badescape(next()) ? parseerror() && emit(new BadStringToken()) && switchto("data") : newline(next()) ? consume() : currtoken.append(consumeEscape()) : currtoken.append(code);432                break;433              case "hash":434                namechar(code) ? create(new HashToken(code)) && switchto("hash-rest") : 92 == code ? badescape(next()) ? parseerror() && emit(new DelimToken(35)) && switchto("data") && reconsume() : create(new HashToken(consumeEscape())) && switchto("hash-rest") : emit(new DelimToken(35)) && switchto("data") && reconsume();435                break;436              case "hash-rest":437                namechar(code) ? currtoken.append(code) : 92 == code ? badescape(next()) ? parseerror() && emit() && switchto("data") && reconsume() : currtoken.append(consumeEscape()) : emit() && switchto("data") && reconsume();438                break;439              case "comment":440                42 == code ? 47 == next() ? consume() && switchto("data") : donothing() : eof() ? parseerror() && switchto("data") && reconsume() : donothing();441                break;442              case "at-keyword":443                45 == code ? namestartchar(next()) ? create(new AtKeywordToken(45)) && switchto("at-keyword-rest") : 92 != next(1) || badescape(next(2)) ? parseerror() && emit(new DelimToken(64)) && switchto("data") && reconsume() : create(new AtKeywordtoken(45)) && switchto("at-keyword-rest") : namestartchar(code) ? create(new AtKeywordToken(code)) && switchto("at-keyword-rest") : 92 == code ? badescape(next()) ? parseerror() && emit(new DelimToken(35)) && switchto("data") && reconsume() : create(new AtKeywordToken(consumeEscape())) && switchto("at-keyword-rest") : emit(new DelimToken(64)) && switchto("data") && reconsume();444                break;445              case "at-keyword-rest":446                namechar(code) ? currtoken.append(code) : 92 == code ? badescape(next()) ? parseerror() && emit() && switchto("data") && reconsume() : currtoken.append(consumeEscape()) : emit() && switchto("data") && reconsume();447                break;448              case "ident":449                45 == code ? namestartchar(next()) ? create(new IdentifierToken(code)) && switchto("ident-rest") : 92 != next(1) || badescape(next(2)) ? emit(new DelimToken(45)) && switchto("data") : create(new IdentifierToken(code)) && switchto("ident-rest") : namestartchar(code) ? create(new IdentifierToken(code)) && switchto("ident-rest") : 92 == code ? badescape(next()) ? parseerror() && switchto("data") && reconsume() : create(new IdentifierToken(consumeEscape())) && switchto("ident-rest") : catchfire("Hit the generic 'else' clause in ident state.") && switchto("data") && reconsume();450                break;451              case "ident-rest":452                namechar(code) ? currtoken.append(code) : 92 == code ? badescape(next()) ? parseerror() && emit() && switchto("data") && reconsume() : currtoken.append(consumeEscape()) : 40 == code ? currtoken.ASCIImatch("url") ? switchto("url") : emit(new FunctionToken(currtoken)) && switchto("data") : whitespace(code) && options.transformFunctionWhitespace ? switchto("transform-function-whitespace") && reconsume() : emit() && switchto("data") && reconsume();453                break;454              case "transform-function-whitespace":455                whitespace(next()) ? donothing() : 40 == code ? emit(new FunctionToken(currtoken)) && switchto("data") : emit() && switchto("data") && reconsume();456                break;457              case "number":458                create(new NumberToken()), 45 == code ? digit(next()) ? consume() && currtoken.append([ 45, code ]) && switchto("number-rest") : 46 == next(1) && digit(next(2)) ? consume(2) && currtoken.append([ 45, 46, code ]) && switchto("number-fraction") : switchto("data") && reconsume() : 43 == code ? digit(next()) ? consume() && currtoken.append([ 43, code ]) && switchto("number-rest") : 46 == next(1) && digit(next(2)) ? consume(2) && currtoken.append([ 43, 46, code ]) && switchto("number-fraction") : switchto("data") && reconsume() : digit(code) ? currtoken.append(code) && switchto("number-rest") : 46 == code && digit(next()) ? consume() && currtoken.append([ 46, code ]) && switchto("number-fraction") : switchto("data") && reconsume();459                break;460              case "number-rest":461                digit(code) ? currtoken.append(code) : 46 == code ? digit(next()) ? consume() && currtoken.append([ 46, code ]) && switchto("number-fraction") : emit() && switchto("data") && reconsume() : 37 == code ? emit(new PercentageToken(currtoken)) && switchto("data") : 69 == code || 101 == code ? digit(next()) ? consume() && currtoken.append([ 37, code ]) && switchto("sci-notation") : 43 != next(1) && 45 != next(1) || !digit(next(2)) ? create(new DimensionToken(currtoken, code)) && switchto("dimension") : currtoken.append([ 37, next(1), next(2) ]) && consume(2) && switchto("sci-notation") : 45 == code ? namestartchar(next()) ? consume() && create(new DimensionToken(currtoken, [ 45, code ])) && switchto("dimension") : 92 == next(1) && badescape(next(2)) ? parseerror() && emit() && switchto("data") && reconsume() : 92 == next(1) ? consume() && create(new DimensionToken(currtoken, [ 45, consumeEscape() ])) && switchto("dimension") : emit() && switchto("data") && reconsume() : namestartchar(code) ? create(new DimensionToken(currtoken, code)) && switchto("dimension") : 92 == code ? badescape(next) ? parseerror() && emit() && switchto("data") && reconsume() : create(new DimensionToken(currtoken, consumeEscape)) && switchto("dimension") : emit() && switchto("data") && reconsume();462                break;463              case "number-fraction":464                currtoken.type = "number", digit(code) ? currtoken.append(code) : 37 == code ? emit(new PercentageToken(currtoken)) && switchto("data") : 69 == code || 101 == code ? digit(next()) ? consume() && currtoken.append([ 101, code ]) && switchto("sci-notation") : 43 != next(1) && 45 != next(1) || !digit(next(2)) ? create(new DimensionToken(currtoken, code)) && switchto("dimension") : currtoken.append([ 101, next(1), next(2) ]) && consume(2) && switchto("sci-notation") : 45 == code ? namestartchar(next()) ? consume() && create(new DimensionToken(currtoken, [ 45, code ])) && switchto("dimension") : 92 == next(1) && badescape(next(2)) ? parseerror() && emit() && switchto("data") && reconsume() : 92 == next(1) ? consume() && create(new DimensionToken(currtoken, [ 45, consumeEscape() ])) && switchto("dimension") : emit() && switchto("data") && reconsume() : namestartchar(code) ? create(new DimensionToken(currtoken, code)) && switchto("dimension") : 92 == code ? badescape(next) ? parseerror() && emit() && switchto("data") && reconsume() : create(new DimensionToken(currtoken, consumeEscape())) && switchto("dimension") : emit() && switchto("data") && reconsume();465                break;466              case "dimension":467                namechar(code) ? currtoken.append(code) : 92 == code ? badescape(next()) ? parseerror() && emit() && switchto("data") && reconsume() : currtoken.append(consumeEscape()) : emit() && switchto("data") && reconsume();468                break;469              case "sci-notation":470                currtoken.type = "number", digit(code) ? currtoken.append(code) : emit() && switchto("data") && reconsume();471                break;472              case "url":473                eof() ? parseerror() && emit(new BadURLToken()) && switchto("data") : 34 == code ? switchto("url-double-quote") : 39 == code ? switchto("url-single-quote") : 41 == code ? emit(new URLToken()) && switchto("data") : whitespace(code) ? donothing() : switchto("url-unquoted") && reconsume();474                break;475              case "url-double-quote":476                currtoken instanceof URLToken || create(new URLToken()), eof() ? parseerror() && emit(new BadURLToken()) && switchto("data") : 34 == code ? switchto("url-end") : newline(code) ? parseerror() && switchto("bad-url") : 92 == code ? newline(next()) ? consume() : badescape(next()) ? parseerror() && emit(new BadURLToken()) && switchto("data") && reconsume() : currtoken.append(consumeEscape()) : currtoken.append(code);477                break;478              case "url-single-quote":479                currtoken instanceof URLToken || create(new URLToken()), eof() ? parseerror() && emit(new BadURLToken()) && switchto("data") : 39 == code ? switchto("url-end") : newline(code) ? parseerror() && switchto("bad-url") : 92 == code ? newline(next()) ? consume() : badescape(next()) ? parseerror() && emit(new BadURLToken()) && switchto("data") && reconsume() : currtoken.append(consumeEscape()) : currtoken.append(code);480                break;481              case "url-end":482                eof() ? parseerror() && emit(new BadURLToken()) && switchto("data") : whitespace(code) ? donothing() : 41 == code ? emit() && switchto("data") : parseerror() && switchto("bad-url") && reconsume();483                break;484              case "url-unquoted":485                currtoken instanceof URLToken || create(new URLToken()), eof() ? parseerror() && emit(new BadURLToken()) && switchto("data") : whitespace(code) ? switchto("url-end") : 41 == code ? emit() && switchto("data") : 34 == code || 39 == code || 40 == code || nonprintable(code) ? parseerror() && switchto("bad-url") : 92 == code ? badescape(next()) ? parseerror() && switchto("bad-url") : currtoken.append(consumeEscape()) : currtoken.append(code);486                break;487              case "bad-url":488                eof() ? parseerror() && emit(new BadURLToken()) && switchto("data") : 41 == code ? emit(new BadURLToken()) && switchto("data") : 92 == code ? badescape(next()) ? donothing() : consumeEscape() : donothing();489                break;490              case "unicode-range":491                for (var start = [ code ], end = [ code ], total = 1; 6 > total && hexdigit(next()); total++) consume(), 492                start.push(code), end.push(code);493                if (63 == next()) {494                    for (;6 > total && 63 == next(); total++) consume(), start.push("0".charCodeAt(0)), 495                    end.push("f".charCodeAt(0));496                    emit(new UnicodeRangeToken(start, end)) && switchto("data");497                } else if (45 == next(1) && hexdigit(next(2))) {498                    consume(), consume(), end = [ code ];499                    for (var total = 1; 6 > total && hexdigit(next()); total++) consume(), end.push(code);500                    emit(new UnicodeRangeToken(start, end)) && switchto("data");501                } else emit(new UnicodeRangeToken(start)) && switchto("data");502                break;503              default:504                catchfire("Unknown state '" + state + "'");505            }506        }507    }508    function stringFromCodeArray(arr) {509        return String.fromCharCode.apply(null, arr.filter(function(e) {510            return e;511        }));512    }513    function CSSParserToken() {514        return this;515    }516    function BadStringToken() {517        return this;518    }519    function BadURLToken() {520        return this;521    }522    function WhitespaceToken() {523        return this;524    }525    function CDOToken() {526        return this;527    }528    function CDCToken() {529        return this;530    }531    function ColonToken() {532        return this;533    }534    function SemicolonToken() {535        return this;536    }537    function OpenCurlyToken() {538        return this;539    }540    function CloseCurlyToken() {541        return this;542    }543    function OpenSquareToken() {544        return this;545    }546    function CloseSquareToken() {547        return this;548    }549    function OpenParenToken() {550        return this;551    }552    function CloseParenToken() {553        return this;554    }555    function EOFToken() {556        return this;557    }558    function DelimToken(code) {559        return this.value = String.fromCharCode(code), this;560    }561    function StringValuedToken() {562        return this;563    }564    function IdentifierToken(val) {565        this.value = [], this.append(val);566    }567    function FunctionToken(val) {568        this.value = val.finish().value;569    }570    function AtKeywordToken(val) {571        this.value = [], this.append(val);572    }573    function HashToken(val) {574        this.value = [], this.append(val);575    }576    function StringToken(val) {577        this.value = [], this.append(val);578    }579    function URLToken(val) {580        this.value = [], this.append(val);581    }582    function NumberToken(val) {583        this.value = [], this.append(val), this.type = "integer";584    }585    function PercentageToken(val) {586        val.finish(), this.value = val.value, this.repr = val.repr;587    }588    function DimensionToken(val, unit) {589        val.finish(), this.num = val.value, this.unit = [], this.repr = val.repr, this.append(unit);590    }591    function UnicodeRangeToken(start, end) {592        return start = parseInt(stringFromCodeArray(start), 16), end = void 0 === end ? start + 1 : parseInt(stringFromCodeArray(end), 16), 593        start > maximumallowedcodepoint && (end = start), start > end && (end = start), 594        end > maximumallowedcodepoint && (end = maximumallowedcodepoint), this.start = start, 595        this.end = end, this;596    }597    var between = function(num, first, last) {598        return num >= first && last >= num;599    }, maximumallowedcodepoint = 1114111;600    CSSParserToken.prototype.finish = function() {601        return this;602    }, CSSParserToken.prototype.toString = function() {603        return this.tokenType;604    }, CSSParserToken.prototype.toSourceString = CSSParserToken.prototype.toString, 605    CSSParserToken.prototype.toJSON = function() {606        return this.toString();607    }, BadStringToken.prototype = new CSSParserToken(), BadStringToken.prototype.tokenType = "BADSTRING", 608    BadURLToken.prototype = new CSSParserToken(), BadURLToken.prototype.tokenType = "BADURL", 609    WhitespaceToken.prototype = new CSSParserToken(), WhitespaceToken.prototype.tokenType = "WHITESPACE", 610    WhitespaceToken.prototype.toString = function() {611        return "WS";612    }, WhitespaceToken.prototype.toSourceString = function() {613        return " ";614    }, CDOToken.prototype = new CSSParserToken(), CDOToken.prototype.tokenType = "CDO", 615    CDCToken.prototype = new CSSParserToken(), CDCToken.prototype.tokenType = "CDC", 616    ColonToken.prototype = new CSSParserToken(), ColonToken.prototype.tokenType = ":", 617    SemicolonToken.prototype = new CSSParserToken(), SemicolonToken.prototype.tokenType = ";", 618    OpenCurlyToken.prototype = new CSSParserToken(), OpenCurlyToken.prototype.tokenType = "{", 619    CloseCurlyToken.prototype = new CSSParserToken(), CloseCurlyToken.prototype.tokenType = "}", 620    OpenSquareToken.prototype = new CSSParserToken(), OpenSquareToken.prototype.tokenType = "[", 621    CloseSquareToken.prototype = new CSSParserToken(), CloseSquareToken.prototype.tokenType = "]", 622    OpenParenToken.prototype = new CSSParserToken(), OpenParenToken.prototype.tokenType = "(", 623    CloseParenToken.prototype = new CSSParserToken(), CloseParenToken.prototype.tokenType = ")", 624    EOFToken.prototype = new CSSParserToken(), EOFToken.prototype.tokenType = "EOF", 625    DelimToken.prototype = new CSSParserToken(), DelimToken.prototype.tokenType = "DELIM", 626    DelimToken.prototype.toString = function() {627        return "DELIM(" + this.value + ")";628    }, DelimToken.prototype.toSourceString = function() {629        return this.value;630    }, StringValuedToken.prototype = new CSSParserToken(), StringValuedToken.prototype.append = function(val) {631        if (val instanceof Array) for (var i = 0; i < val.length; i++) this.value.push(val[i]); else this.value.push(val);632        return !0;633    }, StringValuedToken.prototype.finish = function() {634        return this.value = this.valueAsString(), this;635    }, StringValuedToken.prototype.ASCIImatch = function(str) {636        return this.valueAsString().toLowerCase() == str.toLowerCase();637    }, StringValuedToken.prototype.valueAsString = function() {638        return "string" == typeof this.value ? this.value : stringFromCodeArray(this.value);639    }, StringValuedToken.prototype.valueAsCodes = function() {640        if ("string" == typeof this.value) {641            for (var ret = [], i = 0; i < this.value.length; i++) ret.push(this.value.charCodeAt(i));642            return ret;643        }644        return this.value.filter(function(e) {645            return e;646        });647    }, IdentifierToken.prototype = new StringValuedToken(), IdentifierToken.prototype.tokenType = "IDENT", 648    IdentifierToken.prototype.toString = function() {649        return "IDENT(" + this.value + ")";650    }, IdentifierToken.prototype.toSourceString = function() {651        return this.value;652    }, FunctionToken.prototype = new StringValuedToken(), FunctionToken.prototype.tokenType = "FUNCTION", 653    FunctionToken.prototype.toString = function() {654        return "FUNCTION(" + this.value + ")";655    }, FunctionToken.prototype.toSourceString = function() {656        return this.value;657    }, AtKeywordToken.prototype = new StringValuedToken(), AtKeywordToken.prototype.tokenType = "AT-KEYWORD", 658    AtKeywordToken.prototype.toString = function() {659        return "AT(" + this.value + ")";660    }, AtKeywordToken.prototype.toSourceString = function() {661        return "@" + this.value;662    }, HashToken.prototype = new StringValuedToken(), HashToken.prototype.tokenType = "HASH", 663    HashToken.prototype.toString = function() {664        return "HASH(" + this.value + ")";665    }, HashToken.prototype.toSourceString = function() {666        return "#" + this.value;667    }, StringToken.prototype = new StringValuedToken(), StringToken.prototype.tokenType = "STRING", 668    StringToken.prototype.toString = function() {669        return '"' + this.value + '"';670    }, StringToken.prototype.toSourceString = StringToken.prototype.toString, URLToken.prototype = new StringValuedToken(), 671    URLToken.prototype.tokenType = "URL", URLToken.prototype.toString = function() {672        return "URL(" + this.value + ")";673    }, URLToken.prototype.toSourceString = function() {674        return "url('" + this.value + "')";675    }, NumberToken.prototype = new StringValuedToken(), NumberToken.prototype.tokenType = "NUMBER", 676    NumberToken.prototype.toString = function() {677        return "integer" == this.type ? "INT(" + this.value + ")" : "NUMBER(" + this.value + ")";678    }, NumberToken.prototype.toSourceString = function() {679        return "integer" == this.type ? this.value : this.value;680    }, NumberToken.prototype.finish = function() {681        return this.repr = this.valueAsString(), this.value = 1 * this.repr, Math.abs(this.value) % 1 != 0 && (this.type = "number"), 682        this;683    }, PercentageToken.prototype = new CSSParserToken(), PercentageToken.prototype.tokenType = "PERCENTAGE", 684    PercentageToken.prototype.toString = function() {685        return "PERCENTAGE(" + this.value + ")";686    }, PercentageToken.prototype.toSourceString = function() {687        return this.value + "%";688    }, DimensionToken.prototype = new CSSParserToken(), DimensionToken.prototype.tokenType = "DIMENSION", 689    DimensionToken.prototype.toString = function() {690        return "DIM(" + this.num + "," + this.unit + ")";691    }, DimensionToken.prototype.toSourceString = function() {692        return this.num + this.unit;693    }, DimensionToken.prototype.append = function(val) {694        if (val instanceof Array) for (var i = 0; i < val.length; i++) this.unit.push(val[i]); else this.unit.push(val);695        return !0;696    }, DimensionToken.prototype.finish = function() {697        return this.unit = stringFromCodeArray(this.unit), this.repr += this.unit, this;698    }, UnicodeRangeToken.prototype = new CSSParserToken(), UnicodeRangeToken.prototype.tokenType = "UNICODE-RANGE", 699    UnicodeRangeToken.prototype.toString = function() {700        return this.start + 1 == this.end ? "UNICODE-RANGE(" + this.start.toString(16).toUpperCase() + ")" : this.start < this.end ? "UNICODE-RANGE(" + this.start.toString(16).toUpperCase() + "-" + this.end.toString(16).toUpperCase() + ")" : "UNICODE-RANGE()";701    }, UnicodeRangeToken.prototype.toSourceString = function() {702        return this.start + 1 == this.end ? "UNICODE-RANGE(" + this.start.toString(16).toUpperCase() + ")" : this.start < this.end ? "UNICODE-RANGE(" + this.start.toString(16).toUpperCase() + "-" + this.end.toString(16).toUpperCase() + ")" : "UNICODE-RANGE()";703    }, UnicodeRangeToken.prototype.contains = function(code) {704        return code >= this.start && code < this.end;705    }, exports.tokenize = tokenize;706}), function() {707    var XMLHttpFactories, ajax, createXMLHTTPObject, getViewportSize, initLayoutEngine;708    XMLHttpFactories = [ function() {709        return new XMLHttpRequest();710    }, function() {711        return new ActiveXObject("Msxml2.XMLHTTP");712    }, function() {713        return new ActiveXObject("Msxml3.XMLHTTP");714    }, function() {715        return new ActiveXObject("Microsoft.XMLHTTP");716    } ], createXMLHTTPObject = function() {717        var e, i, xmlhttp;718        for (xmlhttp = !1, i = 0; i < XMLHttpFactories.length; ) {719            try {720                xmlhttp = XMLHttpFactories[i++]();721            } catch (_error) {722                e = _error;723                continue;724            }725            break;726        }727        return xmlhttp;728    }, ajax = function(url, onload) {729        var xmlhttp;730        xmlhttp = createXMLHTTPObject(), xmlhttp.onreadystatechange = function() {731            if (4 === xmlhttp.readyState) {732                if (200 !== xmlhttp.status) throw "Error!";733                onload(xmlhttp.responseText);734            }735        }, xmlhttp.open("GET", url, !0), xmlhttp.send();736    }, getViewportSize = function() {737        var x, y;738        return x = 0, y = 0, window.innerHeight ? (x = window.innerWidth, y = window.innerHeight) : document.documentElement && document.documentElement.clientHeight ? (x = document.documentElement.clientWidth, 739        y = document.documentElement.clientHeight) : document.body && (x = document.body.clientWidth, 740        y = document.body.clientHeight), {741            width: x,742            height: y743        };744    }, (initLayoutEngine = function() {745        var analyzeStyleRule, analyzeStylesheet, head, i, innerSheetCount, links, onresize, outerSheetCount, sheets, styleElement, _i, _len;746        for (analyzeStyleRule = function(rule) {747            var declaration, declarations, hasDimension, token, _i, _j, _len, _len1, _ref, _ref1;748            for (declarations = [], _ref = rule.value, _i = 0, _len = _ref.length; _len > _i; _i++) {749                for (declaration = _ref[_i], hasDimension = !1, _ref1 = declaration.value, _j = 0, 750                _len1 = _ref1.length; _len1 > _j; _j++) token = _ref1[_j], "DIMENSION" !== token.tokenType || "vmin" !== token.unit && "vh" !== token.unit && "vw" !== token.unit || (hasDimension = !0);751                hasDimension && declarations.push(declaration);752            }753            return rule.value = declarations, declarations;754        }, analyzeStylesheet = function(sheet) {755            var atRules, decs, rule, rules, _i, _len, _ref;756            for (rules = [], _ref = sheet.value, _i = 0, _len = _ref.length; _len > _i; _i++) switch (rule = _ref[_i], 757            rule.type) {758              case "STYLE-RULE":759                decs = analyzeStyleRule(rule), 0 !== decs.length && rules.push(rule);760                break;761              case "AT-RULE":762                atRules = analyzeStylesheet(rule), 0 !== atRules.length && rules.push(rule);763            }764            return sheet.value = rules, rules;765        }, onresize = function() {766            var css, dims, generateRuleCode, generateSheetCode, map, sheet, url, vpAspectRatio, vpDims;767            vpDims = getViewportSize(), dims = {768                vh: vpDims.height / 100,769                vw: vpDims.width / 100770            }, dims.vmin = Math.min(dims.vh, dims.vw), vpAspectRatio = vpDims.width / vpDims.height, 771            map = function(a, f) {772                var a1, e, _i, _len;773                if (null != a.map) return a.map(f);774                for (a1 = [], _i = 0, _len = a.length; _len > _i; _i++) e = a[_i], a1.push(f(e));775                return a1;776            }, generateRuleCode = function(rule) {777                var declaration, declarations, ruleCss, token, _i, _j, _len, _len1, _ref, _ref1;778                for (declarations = [], ruleCss = map(rule.selector, function(o) {779                    return null != o.toSourceString ? o.toSourceString() : "";780                }).join(""), ruleCss += "{", _ref = rule.value, _i = 0, _len = _ref.length; _len > _i; _i++) {781                    for (declaration = _ref[_i], ruleCss += declaration.name, ruleCss += ":", _ref1 = declaration.value, 782                    _j = 0, _len1 = _ref1.length; _len1 > _j; _j++) token = _ref1[_j], ruleCss += "DIMENSION" !== token.tokenType || "vmin" !== token.unit && "vh" !== token.unit && "vw" !== token.unit ? token.toSourceString() : "" + Math.floor(token.num * dims[token.unit]) + "px";783                    ruleCss += ";";784                }785                return ruleCss += "}\r";786            }, generateSheetCode = function(sheet) {787                var mar, nums, prelude, rule, sheetCss, source, t, t1, _i, _j, _k, _l, _len, _len1, _len2, _len3, _ref, _ref1, _ref2, _ref3;788                for (sheetCss = "", _ref = sheet.value, _i = 0, _len = _ref.length; _len > _i; _i++) switch (rule = _ref[_i], 789                rule.type) {790                  case "STYLE-RULE":791                    sheetCss += generateRuleCode(rule);792                    break;793                  case "AT-RULE":794                    if ("media" === rule.name) {795                        for (prelude = "", mar = !1, nums = [], _ref1 = rule.prelude, _j = 0, _len1 = _ref1.length; _len1 > _j; _j++) if (t = _ref1[_j], 796                        "(" === t.name) {797                            for (prelude += "(", _ref2 = t.value, _k = 0, _len2 = _ref2.length; _len2 > _k; _k++) t1 = _ref2[_k], 798                            source = null != t1.toSourceString ? t1.toSourceString() : "", "IDENT" === t1.tokenType && "max-aspect-ratio" === source && (mar = !0), 799                            "NUMBER" === t1.tokenType && nums.push(parseInt(source)), prelude += source;800                            prelude += ")";801                        } else prelude += t.toSourceString();802                        vpAspectRatio < nums[0] / nums[1] && (sheetCss += generateSheetCode(rule));803                    } else {804                        for (prelude = "", _ref3 = rule.prelude, _l = 0, _len3 = _ref3.length; _len3 > _l; _l++) t = _ref3[_l], 805                        "(" === t.name ? (prelude += "(", prelude += map(t.value, function(o) {806                            return null != o.toSourceString ? o.toSourceString() : "";807                        }).join(""), prelude += ")") : prelude += t.toSourceString();808                        sheetCss += "@" + rule.name + " " + prelude + " {", sheetCss += generateSheetCode(rule), 809                        sheetCss += "}\n";810                    }811                }812                return sheetCss;813            }, css = "";814            for (url in sheets) sheet = sheets[url], css += generateSheetCode(sheet);815            return null != styleElement.styleSheet ? styleElement.styleSheet.cssText = css : styleElement.innerHTML = css;816        }, sheets = {}, styleElement = document.createElement("style"), head = document.getElementsByTagName("head")[0], 817        head.appendChild(styleElement), links = document.getElementsByTagName("link"), innerSheetCount = 0, 818        outerSheetCount = 0, _i = 0, _len = links.length; _len > _i; _i++) i = links[_i], 819        "stylesheet" === i.rel && (innerSheetCount++, ajax(i.href, function(cssText) {820            var sheet, tokenlist;821            tokenlist = tokenize(cssText), sheet = parse(tokenlist), analyzeStylesheet(sheet), 822            sheets[i.href] = sheet, outerSheetCount++, outerSheetCount === innerSheetCount && window.onresize();823        }));824        window.onresize = onresize;825    })();...tokenizer.js
Source:tokenizer.js  
1(function (root, factory) {2    // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,3    // Rhino, and plain browser loading.4    if (typeof define === 'function' && define.amd) {5        define(['exports'], factory);6    } else if (typeof exports !== 'undefined') {7        factory(exports);8    } else {9        factory(root);10    }11}(this, function (exports) {12var between = function (num, first, last) { return num >= first && num <= last; }13function digit(code) { return between(code, 0x30,0x39); }14function hexdigit(code) { return digit(code) || between(code, 0x41,0x46) || between(code, 0x61,0x66); }15function uppercaseletter(code) { return between(code, 0x41,0x5a); }16function lowercaseletter(code) { return between(code, 0x61,0x7a); }17function letter(code) { return uppercaseletter(code) || lowercaseletter(code); }18function nonascii(code) { return code >= 0xa0; }19function namestartchar(code) { return letter(code) || nonascii(code) || code == 0x5f; }20function namechar(code) { return namestartchar(code) || digit(code) || code == 0x2d; }21function nonprintable(code) { return between(code, 0,8) || between(code, 0xe,0x1f) || between(code, 0x7f,0x9f); }22function newline(code) { return code == 0xa || code == 0xc; }23function whitespace(code) { return newline(code) || code == 9 || code == 0x20; }24function badescape(code) { return newline(code) || isNaN(code); }25// Note: I'm not yet acting smart enough to actually handle astral characters.26var maximumallowedcodepoint = 0x10ffff;27function tokenize(str, options) {28	if(options == undefined) options = {transformFunctionWhitespace:false, scientificNotation:false};29	var i = -1;30	var tokens = [];31	var state = "data";32	var code;33	var currtoken;34	// Line number information.35	var line = 0;36	var column = 0;37	// The only use of lastLineLength is in reconsume().38	var lastLineLength = 0;39	var incrLineno = function() {40		line += 1;41		lastLineLength = column;42		column = 0;43	};44	var locStart = {line:line, column:column};45	var next = function(num) { if(num === undefined) num = 1; return str.charCodeAt(i+num); };46	var consume = function(num) {47		if(num === undefined)48			num = 1;49		i += num;50		code = str.charCodeAt(i);51		if (newline(code)) incrLineno();52		else column += num;53		//console.log('Consume '+i+' '+String.fromCharCode(code) + ' 0x' + code.toString(16));54		return true;55	};56	var reconsume = function() {57		i -= 1;58		if (newline(code)) {59			line -= 1;60			column = lastLineLength;61		} else {62			column -= 1;63		}64		locStart.line = line;65		locStart.column = column;66		return true;67	};68	var eof = function() { return i >= str.length; };69	var donothing = function() {};70	var emit = function(token) {71		if(token) {72			token.finish();73		} else {74			token = currtoken.finish();75		}76		if (options.loc === true) {77			token.loc = {};78			token.loc.start = {line:locStart.line, column:locStart.column};79			locStart = {line: line, column: column};80			token.loc.end = locStart;81		}82		tokens.push(token);83		//console.log('Emitting ' + token);84		currtoken = undefined;85		return true;86	};87	var create = function(token) { currtoken = token; return true; };88	var parseerror = function() { console.log("Parse error at index " + i + ", processing codepoint 0x" + code.toString(16) + " in state " + state + ".");return true; };89	var catchfire = function(msg) { console.log("MAJOR SPEC ERROR: " + msg); return true;}90	var switchto = function(newstate) {91		state = newstate;92		//console.log('Switching to ' + state);93		return true;94	};95	var consumeEscape = function() {96		// Assume the the current character is the \97		consume();98		if(hexdigit(code)) {99			// Consume 1-6 hex digits100			var digits = [];101			for(var total = 0; total < 6; total++) {102				if(hexdigit(code)) {103					digits.push(code);104					consume();105				} else { break; }106			}107			if(digits.map != null) {108				var value = parseInt(digits.map(String.fromCharCode).join(''), 16);109			} else {110				d1 = [];111				_len = digits.length;112				for (_i = 0; _i < _len; _i++) { d1.push(String.fromCharCode(digits[_i])); }113				var value = parseInt(d1.join(''), 16);114			}115			if( value > maximumallowedcodepoint ) value = 0xfffd;116			// If the current char is whitespace, cool, we'll just eat it.117			// Otherwise, put it back.118			if(!whitespace(code)) reconsume();119			return value;120		} else {121			return code;122		}123	};124	for(;;) {125		if(i > str.length*2) return "I'm infinite-looping!";126		consume();127		switch(state) {128		case "data":129			if(whitespace(code)) {130				emit(new WhitespaceToken);131				while(whitespace(next())) consume();132			}133			else if(code == 0x22) switchto("double-quote-string");134			else if(code == 0x23) switchto("hash");135			else if(code == 0x27) switchto("single-quote-string");136			else if(code == 0x28) emit(new OpenParenToken);137			else if(code == 0x29) emit(new CloseParenToken);138			else if(code == 0x2b) {139				if(digit(next()) || (next() == 0x2e && digit(next(2)))) switchto("number") && reconsume();140				else emit(new DelimToken(code));141			}142			else if(code == 0x2d) {143				if(next(1) == 0x2d && next(2) == 0x3e) consume(2) && emit(new CDCToken);144				else if(digit(next()) || (next(1) == 0x2e && digit(next(2)))) switchto("number") && reconsume();145				else switchto('ident') && reconsume();146			}147			else if(code == 0x2e) {148				if(digit(next())) switchto("number") && reconsume();149				else emit(new DelimToken(code));150			}151			else if(code == 0x2f) {152				if(next() == 0x2a) consume() && switchto("comment");153				else emit(new DelimToken(code));154			}155			else if(code == 0x3a) emit(new ColonToken);156			else if(code == 0x3b) emit(new SemicolonToken);157			else if(code == 0x3c) {158				if(next(1) == 0x21 && next(2) == 0x2d && next(3) == 0x2d) consume(3) && emit(new CDOToken);159				else emit(new DelimToken(code));160			}161			else if(code == 0x40) switchto("at-keyword");162			else if(code == 0x5b) emit(new OpenSquareToken);163			else if(code == 0x5c) {164				if(badescape(next())) parseerror() && emit(new DelimToken(code));165				else switchto('ident') && reconsume();166			}167			else if(code == 0x5d) emit(new CloseSquareToken);168			else if(code == 0x7b) emit(new OpenCurlyToken);169			else if(code == 0x7d) emit(new CloseCurlyToken);170			else if(digit(code)) switchto("number") && reconsume();171			else if(code == 0x55 || code == 0x75) {172				if(next(1) == 0x2b && hexdigit(next(2))) consume() && switchto("unicode-range");173				else switchto('ident') && reconsume();174			}175			else if(namestartchar(code)) switchto('ident') && reconsume();176			else if(eof()) { emit(new EOFToken); return tokens; }177			else emit(new DelimToken(code));178			break;179		case "double-quote-string":180			if(currtoken == undefined) create(new StringToken);181			if(code == 0x22) emit() && switchto("data");182			else if(eof()) parseerror() && emit() && switchto("data") && reconsume();183			else if(newline(code)) parseerror() && emit(new BadStringToken) && switchto("data") && reconsume();184			else if(code == 0x5c) {185				if(badescape(next())) parseerror() && emit(new BadStringToken) && switchto("data");186				else if(newline(next())) consume();187				else currtoken.append(consumeEscape());188			}189			else currtoken.append(code);190			break;191		case "single-quote-string":192			if(currtoken == undefined) create(new StringToken);193			if(code == 0x27) emit() && switchto("data");194			else if(eof()) parseerror() && emit() && switchto("data");195			else if(newline(code)) parseerror() && emit(new BadStringToken) && switchto("data") && reconsume();196			else if(code == 0x5c) {197				if(badescape(next())) parseerror() && emit(new BadStringToken) && switchto("data");198				else if(newline(next())) consume();199				else currtoken.append(consumeEscape());200			}201			else currtoken.append(code);202			break;203		case "hash":204			if(namechar(code)) create(new HashToken(code)) && switchto("hash-rest");205			else if(code == 0x5c) {206				if(badescape(next())) parseerror() && emit(new DelimToken(0x23)) && switchto("data") && reconsume();207				else create(new HashToken(consumeEscape())) && switchto('hash-rest');208			}209			else emit(new DelimToken(0x23)) && switchto('data') && reconsume();210			break;211		case "hash-rest":212			if(namechar(code)) currtoken.append(code);213			else if(code == 0x5c) {214				if(badescape(next())) parseerror() && emit() && switchto("data") && reconsume();215				else currtoken.append(consumeEscape());216			}217			else emit() && switchto('data') && reconsume();218			break;219		case "comment":220			if(code == 0x2a) {221				if(next() == 0x2f) consume() && switchto('data');222				else donothing();223			}224			else if(eof()) parseerror() && switchto('data') && reconsume();225			else donothing();226			break;227		case "at-keyword":228			if(code == 0x2d) {229				if(namestartchar(next())) create(new AtKeywordToken(0x2d)) && switchto('at-keyword-rest');230				else if(next(1) == 0x5c && !badescape(next(2))) create(new AtKeywordtoken(0x2d)) && switchto('at-keyword-rest');231				else parseerror() && emit(new DelimToken(0x40)) && switchto('data') && reconsume();232			}233			else if(namestartchar(code)) create(new AtKeywordToken(code)) && switchto('at-keyword-rest');234			else if(code == 0x5c) {235				if(badescape(next())) parseerror() && emit(new DelimToken(0x23)) && switchto("data") && reconsume();236				else create(new AtKeywordToken(consumeEscape())) && switchto('at-keyword-rest');237			}238			else emit(new DelimToken(0x40)) && switchto('data') && reconsume();239			break;240		case "at-keyword-rest":241			if(namechar(code)) currtoken.append(code);242			else if(code == 0x5c) {243				if(badescape(next())) parseerror() && emit() && switchto("data") && reconsume();244				else currtoken.append(consumeEscape());245			}246			else emit() && switchto('data') && reconsume();247			break;248		case "ident":249			if(code == 0x2d) {250				if(namestartchar(next())) create(new IdentifierToken(code)) && switchto('ident-rest');251				else if(next(1) == 0x5c && !badescape(next(2))) create(new IdentifierToken(code)) && switchto('ident-rest');252				else emit(new DelimToken(0x2d)) && switchto('data');253			}254			else if(namestartchar(code)) create(new IdentifierToken(code)) && switchto('ident-rest');255			else if(code == 0x5c) {256				if(badescape(next())) parseerror() && switchto("data") && reconsume();257				else create(new IdentifierToken(consumeEscape())) && switchto('ident-rest');258			}259			else catchfire("Hit the generic 'else' clause in ident state.") && switchto('data') && reconsume();260			break;261		case "ident-rest":262			if(namechar(code)) currtoken.append(code);263			else if(code == 0x5c) {264				if(badescape(next())) parseerror() && emit() && switchto("data") && reconsume();265				else currtoken.append(consumeEscape());266			}267			else if(code == 0x28) {268				if(currtoken.ASCIImatch('url')) switchto('url');269				else emit(new FunctionToken(currtoken)) && switchto('data');270			} 271			else if(whitespace(code) && options.transformFunctionWhitespace) switchto('transform-function-whitespace') && reconsume();272			else emit() && switchto('data') && reconsume();273			break;274		case "transform-function-whitespace":275			if(whitespace(next())) donothing();276			else if(code == 0x28) emit(new FunctionToken(currtoken)) && switchto('data');277			else emit() && switchto('data') && reconsume();278			break;279		case "number":280			create(new NumberToken());281			if(code == 0x2d) {282				if(digit(next())) consume() && currtoken.append([0x2d,code]) && switchto('number-rest');283				else if(next(1) == 0x2e && digit(next(2))) consume(2) && currtoken.append([0x2d,0x2e,code]) && switchto('number-fraction');284				else switchto('data') && reconsume();285			}286			else if(code == 0x2b) {287				if(digit(next())) consume() && currtoken.append([0x2b,code]) && switchto('number-rest');288				else if(next(1) == 0x2e && digit(next(2))) consume(2) && currtoken.append([0x2b,0x2e,code]) && switchto('number-fraction');289				else switchto('data') && reconsume();290			}291			else if(digit(code)) currtoken.append(code) && switchto('number-rest');292			else if(code == 0x2e) {293				if(digit(next())) consume() && currtoken.append([0x2e,code]) && switchto('number-fraction');294				else switchto('data') && reconsume();295			}296			else switchto('data') && reconsume();297			break;298		case "number-rest":299			if(digit(code)) currtoken.append(code);300			else if(code == 0x2e) {301				if(digit(next())) consume() && currtoken.append([0x2e,code]) && switchto('number-fraction');302				else emit() && switchto('data') && reconsume();303			}304			else if(code == 0x25) emit(new PercentageToken(currtoken)) && switchto('data');305			else if(code == 0x45 || code == 0x65) {306				if(digit(next())) consume() && currtoken.append([0x25,code]) && switchto('sci-notation');307				else if((next(1) == 0x2b || next(1) == 0x2d) && digit(next(2))) currtoken.append([0x25,next(1),next(2)]) && consume(2) && switchto('sci-notation');308				else create(new DimensionToken(currtoken,code)) && switchto('dimension');309			}310			else if(code == 0x2d) {311				if(namestartchar(next())) consume() && create(new DimensionToken(currtoken,[0x2d,code])) && switchto('dimension');312				else if(next(1) == 0x5c && badescape(next(2))) parseerror() && emit() && switchto('data') && reconsume();313				else if(next(1) == 0x5c) consume() && create(new DimensionToken(currtoken, [0x2d,consumeEscape()])) && switchto('dimension');314				else emit() && switchto('data') && reconsume();315			}316			else if(namestartchar(code)) create(new DimensionToken(currtoken, code)) && switchto('dimension');317			else if(code == 0x5c) {318				if(badescape(next)) parseerror() && emit() && switchto('data') && reconsume();319				else create(new DimensionToken(currtoken,consumeEscape)) && switchto('dimension');320			}321			else emit() && switchto('data') && reconsume();322			break;323		case "number-fraction":324			currtoken.type = "number";325			if(digit(code)) currtoken.append(code);326			else if(code == 0x25) emit(new PercentageToken(currtoken)) && switchto('data');327			else if(code == 0x45 || code == 0x65) {328				if(digit(next())) consume() && currtoken.append([0x65,code]) && switchto('sci-notation');329				else if((next(1) == 0x2b || next(1) == 0x2d) && digit(next(2))) currtoken.append([0x65,next(1),next(2)]) && consume(2) && switchto('sci-notation');330				else create(new DimensionToken(currtoken,code)) && switchto('dimension');331			}332			else if(code == 0x2d) {333				if(namestartchar(next())) consume() && create(new DimensionToken(currtoken,[0x2d,code])) && switchto('dimension');334				else if(next(1) == 0x5c && badescape(next(2))) parseerror() && emit() && switchto('data') && reconsume();335				else if(next(1) == 0x5c) consume() && create(new DimensionToken(currtoken, [0x2d,consumeEscape()])) && switchto('dimension');336				else emit() && switchto('data') && reconsume();337			}338			else if(namestartchar(code)) create(new DimensionToken(currtoken, code)) && switchto('dimension');339			else if(code == 0x5c) {340				if(badescape(next)) parseerror() && emit() && switchto('data') && reconsume();341				else create(new DimensionToken(currtoken,consumeEscape())) && switchto('dimension');342			}343			else emit() && switchto('data') && reconsume();344			break;345		case "dimension":346			if(namechar(code)) currtoken.append(code);347			else if(code == 0x5c) {348				if(badescape(next())) parseerror() && emit() && switchto('data') && reconsume();349				else currtoken.append(consumeEscape());350			}351			else emit() && switchto('data') && reconsume();352			break;353		case "sci-notation":354			currtoken.type = "number";355			if(digit(code)) currtoken.append(code);356			else emit() && switchto('data') && reconsume();357			break;358		case "url":359			if(eof()) parseerror() && emit(new BadURLToken) && switchto('data');360			else if(code == 0x22) switchto('url-double-quote');361			else if(code == 0x27) switchto('url-single-quote');362			else if(code == 0x29) emit(new URLToken) && switchto('data');363			else if(whitespace(code)) donothing();364			else switchto('url-unquoted') && reconsume();365			break;366		case "url-double-quote":367			if(! (currtoken instanceof URLToken)) create(new URLToken);368			if(eof()) parseerror() && emit(new BadURLToken) && switchto('data');369			else if(code == 0x22) switchto('url-end');370			else if(newline(code)) parseerror() && switchto('bad-url');371			else if(code == 0x5c) {372				if(newline(next())) consume();373				else if(badescape(next())) parseerror() && emit(new BadURLToken) && switchto('data') && reconsume();374				else currtoken.append(consumeEscape());375			}376			else currtoken.append(code);377			break;378		case "url-single-quote":379			if(! (currtoken instanceof URLToken)) create(new URLToken);380			if(eof()) parseerror() && emit(new BadURLToken) && switchto('data');381			else if(code == 0x27) switchto('url-end');382			else if(newline(code)) parseerror() && switchto('bad-url');383			else if(code == 0x5c) {384				if(newline(next())) consume();385				else if(badescape(next())) parseerror() && emit(new BadURLToken) && switchto('data') && reconsume();386				else currtoken.append(consumeEscape());387			}388			else currtoken.append(code);389			break;390		case "url-end":391			if(eof()) parseerror() && emit(new BadURLToken) && switchto('data');392			else if(whitespace(code)) donothing();393			else if(code == 0x29) emit() && switchto('data');394			else parseerror() && switchto('bad-url') && reconsume();395			break;396		case "url-unquoted":397			if(! (currtoken instanceof URLToken)) create(new URLToken);398			if(eof()) parseerror() && emit(new BadURLToken) && switchto('data');399			else if(whitespace(code)) switchto('url-end');400			else if(code == 0x29) emit() && switchto('data');401			else if(code == 0x22 || code == 0x27 || code == 0x28 || nonprintable(code)) parseerror() && switchto('bad-url');402			else if(code == 0x5c) {403				if(badescape(next())) parseerror() && switchto('bad-url');404				else currtoken.append(consumeEscape());405			}406			else currtoken.append(code);407			break;408		case "bad-url":409			if(eof()) parseerror() && emit(new BadURLToken) && switchto('data');410			else if(code == 0x29) emit(new BadURLToken) && switchto('data');411			else if(code == 0x5c) {412				if(badescape(next())) donothing();413				else consumeEscape();414			}415			else donothing();416			break;417		case "unicode-range":418			// We already know that the current code is a hexdigit.419			var start = [code], end = [code];420			for(var total = 1; total < 6; total++) {421				if(hexdigit(next())) {422					consume();423					start.push(code);424					end.push(code);425				}426				else break;427			}428			if(next() == 0x3f) {429				for(;total < 6; total++) {430					if(next() == 0x3f) {431						consume();432						start.push("0".charCodeAt(0));433						end.push("f".charCodeAt(0));434					}435					else break;436				}437				emit(new UnicodeRangeToken(start,end)) && switchto('data');438			}439			else if(next(1) == 0x2d && hexdigit(next(2))) {440				consume();441				consume();442				end = [code];443				for(var total = 1; total < 6; total++) {444					if(hexdigit(next())) {445						consume();446						end.push(code);447					}448					else break;449				}450				emit(new UnicodeRangeToken(start,end)) && switchto('data');451			}452			else emit(new UnicodeRangeToken(start)) && switchto('data');453			break;454		default:455			catchfire("Unknown state '" + state + "'");456		}457	}458}459function stringFromCodeArray(arr) {460	return String.fromCharCode.apply(null,arr.filter(function(e){return e;}));461}462function CSSParserToken(options) { return this; }463CSSParserToken.prototype.finish = function() { return this; }464CSSParserToken.prototype.toString = function() { return this.tokenType; }465CSSParserToken.prototype.toSourceString = CSSParserToken.prototype.toString;466CSSParserToken.prototype.toJSON = function() { return this.toString(); }467function BadStringToken() { return this; }468BadStringToken.prototype = new CSSParserToken;469BadStringToken.prototype.tokenType = "BADSTRING";470function BadURLToken() { return this; }471BadURLToken.prototype = new CSSParserToken;472BadURLToken.prototype.tokenType = "BADURL";473function WhitespaceToken() { return this; }474WhitespaceToken.prototype = new CSSParserToken;475WhitespaceToken.prototype.tokenType = "WHITESPACE";476WhitespaceToken.prototype.toString = function() { return "WS"; }477WhitespaceToken.prototype.toSourceString = function() { return " "; }478function CDOToken() { return this; }479CDOToken.prototype = new CSSParserToken;480CDOToken.prototype.tokenType = "CDO";481function CDCToken() { return this; }482CDCToken.prototype = new CSSParserToken;483CDCToken.prototype.tokenType = "CDC";484function ColonToken() { return this; }485ColonToken.prototype = new CSSParserToken;486ColonToken.prototype.tokenType = ":";487function SemicolonToken() { return this; }488SemicolonToken.prototype = new CSSParserToken;489SemicolonToken.prototype.tokenType = ";";490function OpenCurlyToken() { return this; }491OpenCurlyToken.prototype = new CSSParserToken;492OpenCurlyToken.prototype.tokenType = "{";493function CloseCurlyToken() { return this; }494CloseCurlyToken.prototype = new CSSParserToken;495CloseCurlyToken.prototype.tokenType = "}";496function OpenSquareToken() { return this; }497OpenSquareToken.prototype = new CSSParserToken;498OpenSquareToken.prototype.tokenType = "[";499function CloseSquareToken() { return this; }500CloseSquareToken.prototype = new CSSParserToken;501CloseSquareToken.prototype.tokenType = "]";502function OpenParenToken() { return this; }503OpenParenToken.prototype = new CSSParserToken;504OpenParenToken.prototype.tokenType = "(";505function CloseParenToken() { return this; }506CloseParenToken.prototype = new CSSParserToken;507CloseParenToken.prototype.tokenType = ")";508function EOFToken() { return this; }509EOFToken.prototype = new CSSParserToken;510EOFToken.prototype.tokenType = "EOF";511function DelimToken(code) {512	this.value = String.fromCharCode(code);513	return this;514}515DelimToken.prototype = new CSSParserToken;516DelimToken.prototype.tokenType = "DELIM";517DelimToken.prototype.toString = function() { return "DELIM("+this.value+")"; }518DelimToken.prototype.toSourceString = function() { return this.value; }519function StringValuedToken() { return this; }520StringValuedToken.prototype = new CSSParserToken;521StringValuedToken.prototype.append = function(val) {522	if(val instanceof Array) {523		for(var i = 0; i < val.length; i++) {524			this.value.push(val[i]);525		}526	} else {527		this.value.push(val);528	}529	return true;530}531StringValuedToken.prototype.finish = function() {532	this.value = this.valueAsString();533	return this;534}535StringValuedToken.prototype.ASCIImatch = function(str) {536	return this.valueAsString().toLowerCase() == str.toLowerCase();537}538StringValuedToken.prototype.valueAsString = function() {539	if(typeof this.value == 'string') return this.value;540	return stringFromCodeArray(this.value);541}542StringValuedToken.prototype.valueAsCodes = function() {543	if(typeof this.value == 'string') {544		var ret = [];545		for(var i = 0; i < this.value.length; i++)546			ret.push(this.value.charCodeAt(i));547		return ret;548	}549	return this.value.filter(function(e){return e;});550}551function IdentifierToken(val) {552	this.value = [];553	this.append(val);554}555IdentifierToken.prototype = new StringValuedToken;556IdentifierToken.prototype.tokenType = "IDENT";557IdentifierToken.prototype.toString = function() { return "IDENT("+this.value+")"; }558IdentifierToken.prototype.toSourceString = function() { return this.value; }559function FunctionToken(val) {560	// These are always constructed by passing an IdentifierToken561	this.value = val.finish().value;562}563FunctionToken.prototype = new StringValuedToken;564FunctionToken.prototype.tokenType = "FUNCTION";565FunctionToken.prototype.toString = function() { return "FUNCTION("+this.value+")"; }566FunctionToken.prototype.toSourceString = function() { return this.value; }567function AtKeywordToken(val) {568	this.value = [];569	this.append(val);570}571AtKeywordToken.prototype = new StringValuedToken;572AtKeywordToken.prototype.tokenType = "AT-KEYWORD";573AtKeywordToken.prototype.toString = function() { return "AT("+this.value+")"; }574AtKeywordToken.prototype.toSourceString = function() { return "@"+this.value; }575function HashToken(val) {576	this.value = [];577	this.append(val);578}579HashToken.prototype = new StringValuedToken;580HashToken.prototype.tokenType = "HASH";581HashToken.prototype.toString = function() { return "HASH("+this.value+")"; }582HashToken.prototype.toSourceString = function() { return "#"+this.value; }583function StringToken(val) {584	this.value = [];585	this.append(val);586}587StringToken.prototype = new StringValuedToken;588StringToken.prototype.tokenType = "STRING";589StringToken.prototype.toString = function() { return "\""+this.value+"\""; }590StringToken.prototype.toSourceString = StringToken.prototype.toString;591function URLToken(val) {592	this.value = [];593	this.append(val);594}595URLToken.prototype = new StringValuedToken;596URLToken.prototype.tokenType = "URL";597URLToken.prototype.toString = function() { return "URL("+this.value+")"; }598URLToken.prototype.toSourceString = function() { return "url('"+this.value+"')"; }599function NumberToken(val) {600	this.value = [];601	this.append(val);602	this.type = "integer";603}604NumberToken.prototype = new StringValuedToken;605NumberToken.prototype.tokenType = "NUMBER";606NumberToken.prototype.toString = function() {607	if(this.type == "integer")608		return "INT("+this.value+")";609	return "NUMBER("+this.value+")";610}611NumberToken.prototype.toSourceString = function() {612 	if(this.type == "integer")613		return this.value;614	return this.value;615}616NumberToken.prototype.finish = function() {617	this.repr = this.valueAsString();618	this.value = this.repr * 1;619	if(Math.abs(this.value) % 1 != 0) this.type = "number";620	return this;621}622function PercentageToken(val) {623	// These are always created by passing a NumberToken as val624	val.finish();625	this.value = val.value;626	this.repr = val.repr;627}628PercentageToken.prototype = new CSSParserToken;629PercentageToken.prototype.tokenType = "PERCENTAGE";630PercentageToken.prototype.toString = function() { return "PERCENTAGE("+this.value+")"; }631PercentageToken.prototype.toSourceString = function() { return this.value+'%'; }632function DimensionToken(val,unit) {633	// These are always created by passing a NumberToken as the val634	val.finish();635	this.num = val.value;636	this.unit = [];637	this.repr = val.repr;638	this.append(unit);639}640DimensionToken.prototype = new CSSParserToken;641DimensionToken.prototype.tokenType = "DIMENSION";642DimensionToken.prototype.toString = function() { return "DIM("+this.num+","+this.unit+")"; }643DimensionToken.prototype.toSourceString = function() { return this.num+this.unit; }644DimensionToken.prototype.append = function(val) {645	if(val instanceof Array) {646		for(var i = 0; i < val.length; i++) {647			this.unit.push(val[i]);648		}649	} else {650		this.unit.push(val);651	}652	return true;653}654DimensionToken.prototype.finish = function() {655	this.unit = stringFromCodeArray(this.unit);656	this.repr += this.unit;657	return this;658}659function UnicodeRangeToken(start,end) {660	// start and end are array of char codes, completely finished661	start = parseInt(stringFromCodeArray(start),16);662	if(end === undefined) end = start + 1;663	else end = parseInt(stringFromCodeArray(end),16);664	if(start > maximumallowedcodepoint) end = start;665	if(end < start) end = start;666	if(end > maximumallowedcodepoint) end = maximumallowedcodepoint;667	this.start = start;668	this.end = end;669	return this;670}671UnicodeRangeToken.prototype = new CSSParserToken;672UnicodeRangeToken.prototype.tokenType = "UNICODE-RANGE";673UnicodeRangeToken.prototype.toString = function() {674	if(this.start+1 == this.end)675		return "UNICODE-RANGE("+this.start.toString(16).toUpperCase()+")";676	if(this.start < this.end)677		return "UNICODE-RANGE("+this.start.toString(16).toUpperCase()+"-"+this.end.toString(16).toUpperCase()+")";678	return "UNICODE-RANGE()";679}680UnicodeRangeToken.prototype.toSourceString = function() {681	if(this.start+1 == this.end)682		return "UNICODE-RANGE("+this.start.toString(16).toUpperCase()+")";683	if(this.start < this.end)684		return "UNICODE-RANGE("+this.start.toString(16).toUpperCase()+"-"+this.end.toString(16).toUpperCase()+")";685	return "UNICODE-RANGE()";686}687UnicodeRangeToken.prototype.contains = function(code) {688	return code >= this.start && code < this.end;689}690// Exportation.691// TODO: also export the various tokens objects?692exports.tokenize = tokenize;...css-tokenizer.js
Source:css-tokenizer.js  
1/**2 * This file is taken from the below mentioned url and is under CC0 license.3 * https://github.com/tabatkins/css-parser/blob/master/tokenizer.js4 * Please retain this comment while updating this file from upstream.5 */6(function (root, factory) {7    // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,8    // Rhino, and plain browser loading.9    if (typeof define === 'function' && define.amd) {10        define(['exports'], factory);11    } else if (typeof exports !== 'undefined') {12        factory(exports);13    } else {14        factory(root);15    }16}(this, function (exports) {17var between = function (num, first, last) { return num >= first && num <= last; }18function digit(code) { return between(code, 0x30,0x39); }19function hexdigit(code) { return digit(code) || between(code, 0x41,0x46) || between(code, 0x61,0x66); }20function uppercaseletter(code) { return between(code, 0x41,0x5a); }21function lowercaseletter(code) { return between(code, 0x61,0x7a); }22function letter(code) { return uppercaseletter(code) || lowercaseletter(code); }23function nonascii(code) { return code >= 0xa0; }24function namestartchar(code) { return letter(code) || nonascii(code) || code == 0x5f; }25function namechar(code) { return namestartchar(code) || digit(code) || code == 0x2d; }26function nonprintable(code) { return between(code, 0,8) || between(code, 0xe,0x1f) || between(code, 0x7f,0x9f); }27function newline(code) { return code == 0xa || code == 0xc; }28function whitespace(code) { return newline(code) || code == 9 || code == 0x20; }29function badescape(code) { return newline(code) || isNaN(code); }30// Note: I'm not yet acting smart enough to actually handle astral characters.31var maximumallowedcodepoint = 0x10ffff;32function tokenize(str, options) {33  if(options == undefined) options = {transformFunctionWhitespace:false, scientificNotation:false};34  var i = -1;35  var tokens = [];36  var state = "data";37  var code;38  var currtoken;39  // Line number information.40  var line = 0;41  var column = 0;42  // The only use of lastLineLength is in reconsume().43  var lastLineLength = 0;44  var incrLineno = function() {45    line += 1;46    lastLineLength = column;47    column = 0;48  };49  var locStart = {line:line, column:column};50  var next = function(num) { if(num === undefined) num = 1; return str.charCodeAt(i+num); };51  var consume = function(num) {52    if(num === undefined)53      num = 1;54    i += num;55    code = str.charCodeAt(i);56    if (newline(code)) incrLineno();57    else column += num;58    //console.log('Consume '+i+' '+String.fromCharCode(code) + ' 0x' + code.toString(16));59    return true;60  };61  var reconsume = function() {62    i -= 1;63    if (newline(code)) {64      line -= 1;65      column = lastLineLength;66    } else {67      column -= 1;68    }69    locStart.line = line;70    locStart.column = column;71    return true;72  };73  var eof = function() { return i >= str.length; };74  var donothing = function() {};75  var emit = function(token) {76    if(token) {77      token.finish();78    } else {79      token = currtoken.finish();80    }81    if (options.loc === true) {82      token.loc = {};83      token.loc.start = {line:locStart.line, column:locStart.column};84      locStart = {line: line, column: column};85      token.loc.end = locStart;86    }87    tokens.push(token);88    //console.log('Emitting ' + token);89    currtoken = undefined;90    return true;91  };92  var create = function(token) { currtoken = token; return true; };93  var parseerror = function() { console.log("Parse error at index " + i + ", processing codepoint 0x" + code.toString(16) + " in state " + state + ".");return true; };94  var switchto = function(newstate) {95    state = newstate;96    //console.log('Switching to ' + state);97    return true;98  };99  var consumeEscape = function() {100    // Assume the the current character is the \101    consume();102    if(hexdigit(code)) {103      // Consume 1-6 hex digits104      var digits = [];105      for(var total = 0; total < 6; total++) {106        if(hexdigit(code)) {107          digits.push(code);108          consume();109        } else { break; }110      }111      var value = parseInt(digits.map(String.fromCharCode).join(''), 16);112      if( value > maximumallowedcodepoint ) value = 0xfffd;113      // If the current char is whitespace, cool, we'll just eat it.114      // Otherwise, put it back.115      if(!whitespace(code)) reconsume();116      return value;117    } else {118      return code;119    }120  };121  for(;;) {122    if(i > str.length*2) return "I'm infinite-looping!";123    consume();124    switch(state) {125    case "data":126      if(whitespace(code)) {127        emit(new WhitespaceToken);128        while(whitespace(next())) consume();129      }130      else if(code == 0x22) switchto("double-quote-string");131      else if(code == 0x23) switchto("hash");132      else if(code == 0x27) switchto("single-quote-string");133      else if(code == 0x28) emit(new OpenParenToken);134      else if(code == 0x29) emit(new CloseParenToken);135      else if(code == 0x2b) {136        if(digit(next()) || (next() == 0x2e && digit(next(2)))) switchto("number") && reconsume();137        else emit(new DelimToken(code));138      }139      else if(code == 0x2d) {140        if(next(1) == 0x2d && next(2) == 0x3e) consume(2) && emit(new CDCToken);141        else if(digit(next()) || (next(1) == 0x2e && digit(next(2)))) switchto("number") && reconsume();142        else if(namestartchar(next())) switchto("identifier") && reconsume();143        else emit(new DelimToken(code));144      }145      else if(code == 0x2e) {146        if(digit(next())) switchto("number") && reconsume();147        else emit(new DelimToken(code));148      }149      else if(code == 0x2f) {150        if(next() == 0x2a) switchto("comment");151        else emit(new DelimToken(code));152      }153      else if(code == 0x3a) emit(new ColonToken);154      else if(code == 0x3b) emit(new SemicolonToken);155      else if(code == 0x3c) {156        if(next(1) == 0x21 && next(2) == 0x2d && next(3) == 0x2d) consume(3) && emit(new CDOToken);157        else emit(new DelimToken(code));158      }159      else if(code == 0x40) switchto("at-keyword");160      else if(code == 0x5b) emit(new OpenSquareToken);161      else if(code == 0x5c) {162        if(badescape(next())) parseerror() && emit(new DelimToken(code));163        else switchto("identifier") && reconsume();164      }165      else if(code == 0x5d) emit(new CloseSquareToken);166      else if(code == 0x7b) emit(new OpenCurlyToken);167      else if(code == 0x7d) emit(new CloseCurlyToken);168      else if(digit(code)) switchto("number") && reconsume();169      else if(code == 0x55 || code == 0x75) {170        if(next(1) == 0x2b && hexdigit(next(2))) consume() && switchto("unicode-range");171        else if((next(1) == 0x52 || next(1) == 0x72) && (next(2) == 0x4c || next(2) == 0x6c) && (next(3) == 0x28)) consume(3) && switchto("url");172        else switchto("identifier") && reconsume();173      }174      else if(namestartchar(code)) switchto("identifier") && reconsume();175      else if(eof()) { emit(new EOFToken); return tokens; }176      else emit(new DelimToken(code));177      break;178    case "double-quote-string":179      if(currtoken == undefined) create(new StringToken);180      if(code == 0x22) emit() && switchto("data");181      else if(eof()) parseerror() && emit() && switchto("data");182      else if(newline(code)) parseerror() && emit(new BadStringToken) && switchto("data") && reconsume();183      else if(code == 0x5c) {184        if(badescape(next())) parseerror() && emit(new BadStringToken) && switchto("data");185        else if(newline(next())) consume();186        else currtoken.append(consumeEscape());187      }188      else currtoken.append(code);189      break;190    case "single-quote-string":191      if(currtoken == undefined) create(new StringToken);192      if(code == 0x27) emit() && switchto("data");193      else if(eof()) parseerror() && emit() && switchto("data");194      else if(newline(code)) parseerror() && emit(new BadStringToken) && switchto("data") && reconsume();195      else if(code == 0x5c) {196        if(badescape(next())) parseerror() && emit(new BadStringToken) && switchto("data");197        else if(newline(next())) consume();198        else currtoken.append(consumeEscape());199      }200      else currtoken.append(code);201      break;202    case "hash":203      if(namechar(code)) create(new HashToken(code)) && switchto("hash-rest");204      else if(code == 0x5c) {205        if(badescape(next())) parseerror() && emit(new DelimToken(0x23)) && switchto("data") && reconsume();206        else create(new HashToken(consumeEscape())) && switchto('hash-rest');207      }208      else emit(new DelimToken(0x23)) && switchto('data') && reconsume();209      break;210    case "hash-rest":211      if(namechar(code)) currtoken.append(code);212      else if(code == 0x5c) {213        if(badescape(next())) parseerror() && emit(new DelimToken(0x23)) && switchto("data") && reconsume();214        else currtoken.append(consumeEscape());215      }216      else emit() && switchto('data') && reconsume();217      break;218    case "comment":219      if(code == 0x2a) {220        if(next() == 0x2f) consume() && switchto('data');221        else donothing();222      }223      else if(eof()) parseerror() && switchto('data') && reconsume();224      else donothing();225      break;226    case "at-keyword":227      if(code == 0x2d) {228        if(namestartchar(next())) consume() && create(new AtKeywordToken([0x40,code])) && switchto('at-keyword-rest');229        else emit(new DelimToken(0x40)) && switchto('data') && reconsume();230      }231      else if(namestartchar(code)) create(new AtKeywordToken(code)) && switchto('at-keyword-rest');232      else if(code == 0x5c) {233        if(badescape(next())) parseerror() && emit(new DelimToken(0x23)) && switchto("data") && reconsume();234        else create(new AtKeywordToken(consumeEscape())) && switchto('at-keyword-rest');235      }236      else emit(new DelimToken(0x40)) && switchto('data') && reconsume();237      break;238    case "at-keyword-rest":239      if(namechar(code)) currtoken.append(code);240      else if(code == 0x5c) {241        if(badescape(next())) parseerror() && emit() && switchto("data") && reconsume();242        else currtoken.append(consumeEscape());243      }244      else emit() && switchto('data') && reconsume();245      break;246    case "identifier":247      if(code == 0x2d) {248        if(namestartchar(next())) create(new IdentifierToken(code)) && switchto('identifier-rest');249        else switchto('data') && reconsume();250      }251      else if(namestartchar(code)) create(new IdentifierToken(code)) && switchto('identifier-rest');252      else if(code == 0x5c) {253        if(badescape(next())) parseerror() && switchto("data") && reconsume();254        else create(new IdentifierToken(consumeEscape())) && switchto('identifier-rest');255      }256      else switchto('data') && reconsume();257      break;258    case "identifier-rest":259      if(namechar(code)) currtoken.append(code);260      else if(code == 0x5c) {261        if(badescape(next())) parseerror() && emit() && switchto("data") && reconsume();262        else currtoken.append(consumeEscape());263      }264      else if(code == 0x28) emit(new FunctionToken(currtoken)) && switchto('data');265      else if(whitespace(code) && options.transformFunctionWhitespace) switchto('transform-function-whitespace');266      else emit() && switchto('data') && reconsume();267      break;268    case "transform-function-whitespace":269      if(whitespace(code)) donothing();270      else if(code == 0x28) emit(new FunctionToken(currtoken)) && switchto('data');271      else emit() && switchto('data') && reconsume();272      break;273    case "number":274      create(new NumberToken());275      if(code == 0x2d) {276        if(digit(next())) consume() && currtoken.append([0x2d,code]) && switchto('number-rest');277        else if(next(1) == 0x2e && digit(next(2))) consume(2) && currtoken.append([0x2d,0x2e,code]) && switchto('number-fraction');278        else switchto('data') && reconsume();279      }280      else if(code == 0x2b) {281        if(digit(next())) consume() && currtoken.append([0x2b,code]) && switchto('number-rest');282        else if(next(1) == 0x2e && digit(next(2))) consume(2) && currtoken.append([0x2b,0x2e,code]) && switchto('number-fraction');283        else switchto('data') && reconsume();284      }285      else if(digit(code)) currtoken.append(code) && switchto('number-rest');286      else if(code == 0x2e) {287        if(digit(next())) consume() && currtoken.append([0x2e,code]) && switchto('number-fraction');288        else switchto('data') && reconsume();289      }290      else switchto('data') && reconsume();291      break;292    case "number-rest":293      if(digit(code)) currtoken.append(code);294      else if(code == 0x2e) {295        if(digit(next())) consume() && currtoken.append([0x2e,code]) && switchto('number-fraction');296        else emit() && switchto('data') && reconsume();297      }298      else if(code == 0x25) emit(new PercentageToken(currtoken)) && switchto('data') && reconsume();299      else if(code == 0x45 || code == 0x65) {300        if(!options.scientificNotation) create(new DimensionToken(currtoken,code)) && switchto('dimension');301        else if(digit(next())) consume() && currtoken.append([0x25,code]) && switchto('sci-notation');302        else if((next(1) == 0x2b || next(1) == 0x2d) && digit(next(2))) currtoken.append([0x25,next(1),next(2)]) && consume(2) && switchto('sci-notation');303        else create(new DimensionToken(currtoken,code)) && switchto('dimension');304      }305      else if(code == 0x2d) {306        if(namestartchar(next())) consume() && create(new DimensionToken(currtoken,[0x2d,code])) && switchto('dimension');307        else if(next(1) == 0x5c && badescape(next(2))) parseerror() && emit() && switchto('data') && reconsume();308        else if(next(1) == 0x5c) consume() && create(new DimensionToken(currtoken, [0x2d,consumeEscape()])) && switchto('dimension');309        else emit() && switchto('data') && reconsume();310      }311      else if(namestartchar(code)) create(new DimensionToken(currtoken, code)) && switchto('dimension');312      else if(code == 0x5c) {313        if(badescape(next)) emit() && switchto('data') && reconsume();314        else create(new DimensionToken(currtoken,consumeEscape)) && switchto('dimension');315      }316      else emit() && switchto('data') && reconsume();317      break;318    case "number-fraction":319      currtoken.type = "number";320      if(digit(code)) currtoken.append(code);321      else if(code == 0x2e) emit() && switchto('data') && reconsume();322      else if(code == 0x25) emit(new PercentageToken(currtoken)) && switchto('data') && reconsume();323      else if(code == 0x45 || code == 0x65) {324        if(!options.scientificNotation) create(new DimensionToken(currtoken,code)) && switchto('dimension');325        else if(digit(next())) consume() && currtoken.append([0x25,code]) && switchto('sci-notation');326        else if((next(1) == 0x2b || next(1) == 0x2d) && digit(next(2))) currtoken.append([0x25,next(1),next(2)]) && consume(2) && switchto('sci-notation');327        else create(new DimensionToken(currtoken,code)) && switchto('dimension');328      }329      else if(code == 0x2d) {330        if(namestartchar(next())) consume() && create(new DimensionToken(currtoken,[0x2d,code])) && switchto('dimension');331        else if(next(1) == 0x5c && badescape(next(2))) parseerror() && emit() && switchto('data') && reconsume();332        else if(next(1) == 0x5c) consume() && create(new DimensionToken(currtoken, [0x2d,consumeEscape()])) && switchto('dimension');333        else emit() && switchto('data') && reconsume();334      }335      else if(namestartchar(code)) create(new DimensionToken(currtoken, code)) && switchto('dimension');336      else if(code == 0x5c) {337        if(badescape(next)) emit() && switchto('data') && reconsume();338        else create(new DimensionToken(currtoken,consumeEscape)) && switchto('dimension');339      }340      else emit() && switchto('data') && reconsume();341      break;342    case "dimension":343      if(namechar(code)) currtoken.append(code);344      else if(code == 0x5c) {345        if(badescape(next())) parseerror() && emit() && switchto('data') && reconsume();346        else currtoken.append(consumeEscape());347      }348      else emit() && switchto('data') && reconsume();349      break;350    case "sci-notation":351      if(digit(code)) currtoken.append(code);352      else emit() && switchto('data') && reconsume();353      break;354    case "url":355      if(code == 0x22) switchto('url-double-quote');356      else if(code == 0x27) switchto('url-single-quote');357      else if(code == 0x29) emit(new URLToken) && switchto('data');358      else if(whitespace(code)) donothing();359      else switchto('url-unquoted') && reconsume();360      break;361    case "url-double-quote":362      if(currtoken == undefined) create(new URLToken);363      if(code == 0x22) switchto('url-end');364      else if(newline(code)) parseerror() && switchto('bad-url');365      else if(code == 0x5c) {366        if(newline(next())) consume();367        else if(badescape(next())) parseerror() && emit(new BadURLToken) && switchto('data') && reconsume();368        else currtoken.append(consumeEscape());369      }370      else currtoken.append(code);371      break;372    case "url-single-quote":373      if(currtoken == undefined) create(new URLToken);374      if(code == 0x27) switchto('url-end');375      else if(newline(code)) parseerror() && switchto('bad-url');376      else if(code == 0x5c) {377        if(newline(next())) consume();378        else if(badescape(next())) parseerror() && emit(new BadURLToken) && switchto('data') && reconsume();379        else currtoken.append(consumeEscape());380      }381      else currtoken.append(code);382      break;383    case "url-end":384      if(whitespace(code)) donothing();385      else if(code == 0x29) emit() && switchto('data');386      else parseerror() && switchto('bad-url') && reconsume();387      break;388    case "url-unquoted":389      if(currtoken == undefined) create(new URLToken);390      if(whitespace(code)) switchto('url-end');391      else if(code == 0x29) emit() && switchto('data');392      else if(code == 0x22 || code == 0x27 || code == 0x28 || nonprintable(code)) parseerror() && switchto('bad-url');393      else if(code == 0x5c) {394        if(badescape(next())) parseerror() && switchto('bad-url');395        else currtoken.append(consumeEscape());396      }397      else currtoken.append(code);398      break;399    case "bad-url":400      if(code == 0x29) emit(new BadURLToken) && switchto('data');401      else if(code == 0x5c) {402        if(badescape(next())) donothing();403        else consumeEscape()404      }405      else donothing();406      break;407    case "unicode-range":408      // We already know that the current code is a hexdigit.409      var start = [code], end = [code];410      for(var total = 1; total < 6; total++) {411        if(hexdigit(next())) {412          consume();413          start.push(code);414          end.push(code);415        }416        else break;417      }418      if(next() == 0x3f) {419        for(;total < 6; total++) {420          if(next() == 0x3f) {421            consume();422            start.push("0".charCodeAt(0));423            end.push("f".charCodeAt(0));424          }425          else break;426        }427        emit(new UnicodeRangeToken(start,end)) && switchto('data');428      }429      else if(next(1) == 0x2d && hexdigit(next(2))) {430        consume();431        consume();432        end = [code];433        for(var total = 1; total < 6; total++) {434          if(hexdigit(next())) {435            consume();436            end.push(code);437          }438          else break;439        }440        emit(new UnicodeRangeToken(start,end)) && switchto('data');441      }442      else emit(new UnicodeRangeToken(start)) && switchto('data');443      break;444    default:445      console.log("Unknown state '" + state + "'");446    }447  }448}449function stringFromCodeArray(arr) {450  return String.fromCharCode.apply(null,arr.filter(function(e){return e;}));451}452function CSSParserToken(options) { return this; }453CSSParserToken.prototype.finish = function() { return this; }454CSSParserToken.prototype.toString = function() { return this.tokenType; }455CSSParserToken.prototype.toJSON = function() { return this.toString(); }456function BadStringToken() { return this; }457BadStringToken.prototype = new CSSParserToken;458BadStringToken.prototype.tokenType = "BADSTRING";459function BadURLToken() { return this; }460BadURLToken.prototype = new CSSParserToken;461BadURLToken.prototype.tokenType = "BADURL";462function WhitespaceToken() { return this; }463WhitespaceToken.prototype = new CSSParserToken;464WhitespaceToken.prototype.tokenType = "WHITESPACE";465WhitespaceToken.prototype.toString = function() { return "WS"; }466function CDOToken() { return this; }467CDOToken.prototype = new CSSParserToken;468CDOToken.prototype.tokenType = "CDO";469function CDCToken() { return this; }470CDCToken.prototype = new CSSParserToken;471CDCToken.prototype.tokenType = "CDC";472function ColonToken() { return this; }473ColonToken.prototype = new CSSParserToken;474ColonToken.prototype.tokenType = ":";475function SemicolonToken() { return this; }476SemicolonToken.prototype = new CSSParserToken;477SemicolonToken.prototype.tokenType = ";";478function OpenCurlyToken() { return this; }479OpenCurlyToken.prototype = new CSSParserToken;480OpenCurlyToken.prototype.tokenType = "{";481function CloseCurlyToken() { return this; }482CloseCurlyToken.prototype = new CSSParserToken;483CloseCurlyToken.prototype.tokenType = "}";484function OpenSquareToken() { return this; }485OpenSquareToken.prototype = new CSSParserToken;486OpenSquareToken.prototype.tokenType = "[";487function CloseSquareToken() { return this; }488CloseSquareToken.prototype = new CSSParserToken;489CloseSquareToken.prototype.tokenType = "]";490function OpenParenToken() { return this; }491OpenParenToken.prototype = new CSSParserToken;492OpenParenToken.prototype.tokenType = "(";493function CloseParenToken() { return this; }494CloseParenToken.prototype = new CSSParserToken;495CloseParenToken.prototype.tokenType = ")";496function EOFToken() { return this; }497EOFToken.prototype = new CSSParserToken;498EOFToken.prototype.tokenType = "EOF";499function DelimToken(code) {500  this.value = String.fromCharCode(code);501  return this;502}503DelimToken.prototype = new CSSParserToken;504DelimToken.prototype.tokenType = "DELIM";505DelimToken.prototype.toString = function() { return "DELIM("+this.value+")"; }506function StringValuedToken() { return this; }507StringValuedToken.prototype = new CSSParserToken;508StringValuedToken.prototype.append = function(val) {509  if(val instanceof Array) {510    for(var i = 0; i < val.length; i++) {511      this.value.push(val[i]);512    }513  } else {514    this.value.push(val);515  }516  return true;517}518StringValuedToken.prototype.finish = function() {519  this.value = stringFromCodeArray(this.value);520  return this;521}522function IdentifierToken(val) {523  this.value = [];524  this.append(val);525}526IdentifierToken.prototype = new StringValuedToken;527IdentifierToken.prototype.tokenType = "IDENT";528IdentifierToken.prototype.toString = function() { return "IDENT("+this.value+")"; }529function FunctionToken(val) {530  // These are always constructed by passing an IdentifierToken531  this.value = val.finish().value;532}533FunctionToken.prototype = new CSSParserToken;534FunctionToken.prototype.tokenType = "FUNCTION";535FunctionToken.prototype.toString = function() { return "FUNCTION("+this.value+")"; }536function AtKeywordToken(val) {537  this.value = [];538  this.append(val);539}540AtKeywordToken.prototype = new StringValuedToken;541AtKeywordToken.prototype.tokenType = "AT-KEYWORD";542AtKeywordToken.prototype.toString = function() { return "AT("+this.value+")"; }543function HashToken(val) {544  this.value = [];545  this.append(val);546}547HashToken.prototype = new StringValuedToken;548HashToken.prototype.tokenType = "HASH";549HashToken.prototype.toString = function() { return "HASH("+this.value+")"; }550function StringToken(val) {551  this.value = [];552  this.append(val);553}554StringToken.prototype = new StringValuedToken;555StringToken.prototype.tokenType = "STRING";556StringToken.prototype.toString = function() { return "\""+this.value+"\""; }557function URLToken(val) {558  this.value = [];559  this.append(val);560}561URLToken.prototype = new StringValuedToken;562URLToken.prototype.tokenType = "URL";563URLToken.prototype.toString = function() { return "URL("+this.value+")"; }564function NumberToken(val) {565  this.value = [];566  this.append(val);567  this.type = "integer";568}569NumberToken.prototype = new StringValuedToken;570NumberToken.prototype.tokenType = "NUMBER";571NumberToken.prototype.toString = function() {572  if(this.type == "integer")573    return "INT("+this.value+")";574  return "NUMBER("+this.value+")";575}576NumberToken.prototype.finish = function() {577  this.repr = stringFromCodeArray(this.value);578  this.value = this.repr * 1;579  if(Math.abs(this.value) % 1 != 0) this.type = "number";580  return this;581}582function PercentageToken(val) {583  // These are always created by passing a NumberToken as val584  val.finish();585  this.value = val.value;586  this.repr = val.repr;587}588PercentageToken.prototype = new CSSParserToken;589PercentageToken.prototype.tokenType = "PERCENTAGE";590PercentageToken.prototype.toString = function() { return "PERCENTAGE("+this.value+")"; }591function DimensionToken(val,unit) {592  // These are always created by passing a NumberToken as the val593  val.finish();594  this.num = val.value;595  this.unit = [];596  this.repr = val.repr;597  this.append(unit);598}599DimensionToken.prototype = new CSSParserToken;600DimensionToken.prototype.tokenType = "DIMENSION";601DimensionToken.prototype.toString = function() { return "DIM("+this.num+","+this.unit+")"; }602DimensionToken.prototype.append = function(val) {603  if(val instanceof Array) {604    for(var i = 0; i < val.length; i++) {605      this.unit.push(val[i]);606    }607  } else {608    this.unit.push(val);609  }610  return true;611}612DimensionToken.prototype.finish = function() {613  this.unit = stringFromCodeArray(this.unit);614  this.repr += this.unit;615  return this;616}617function UnicodeRangeToken(start,end) {618  // start and end are array of char codes, completely finished619  start = parseInt(stringFromCodeArray(start),16);620  if(end === undefined) end = start + 1;621  else end = parseInt(stringFromCodeArray(end),16);622  if(start > maximumallowedcodepoint) end = start;623  if(end < start) end = start;624  if(end > maximumallowedcodepoint) end = maximumallowedcodepoint;625  this.start = start;626  this.end = end;627  return this;628}629UnicodeRangeToken.prototype = new CSSParserToken;630UnicodeRangeToken.prototype.tokenType = "UNICODE-RANGE";631UnicodeRangeToken.prototype.toString = function() {632  if(this.start+1 == this.end)633    return "UNICODE-RANGE("+this.start.toString(16).toUpperCase()+")";634  if(this.start < this.end)635    return "UNICODE-RANGE("+this.start.toString(16).toUpperCase()+"-"+this.end.toString(16).toUpperCase()+")";636  return "UNICODE-RANGE()";637}638UnicodeRangeToken.prototype.contains = function(code) {639  return code >= this.start && code < this.end;640}641// Exportation.642// TODO: also export the various tokens objects?643module.exports = tokenize;...Using AI Code Generation
1const { openBrowser, goto, switchTo, closeBrowser } = require('taiko');2(async () => {3    try {4        await openBrowser();5        await closeBrowser();6    } catch (e) {7        console.error(e);8    } finally {9    }10})();11const { openBrowser, goto, switchToFrame, closeBrowser } = require('taiko');12(async () => {13    try {14        await openBrowser();15        await switchToFrame("iframeResult");16        await closeBrowser();17    } catch (e) {18        console.error(e);19    } finally {20    }21})();22const { openBrowser, goto, switchToParentFrame, closeBrowser } = require('taiko');23(async () => {24    try {25        await openBrowser();26        await switchToParentFrame();27        await closeBrowser();28    } catch (e) {29        console.error(e);30    } finally {31    }32})();33const { openBrowser, goto, tap, closeBrowser } = require('taiko');34(async () => {35    try {36        await openBrowser();37        await tap("Try it");38        await closeBrowser();39    } catch (e) {40        console.error(e);41    } finally {42    }43})();44const { openBrowser, goto, text, closeBrowser } = require('taUsing AI Code Generation
1const { openBrowser, goto, switchTo, closeBrowser } = require('taiko');2(async () => {3    try {4        await openBrowser();5        await switchTo("iframe");6        await click("Try it");7        await switchTo();8        await click("HTML Tutorial");9    } catch (e) {10        console.error(e);11    } finally {12        await closeBrowser();13    }14})();15const { openBrowser, goto, switchTo, closeBrowser } = require('taiko');16(async () => {17    try {18        await openBrowser();19        await switchTo("iframe");20        await click("Try it");21        await switchTo();22        await click("HTML Tutorial");23    } catch (e) {24        console.error(e);25    } finally {26        await closeBrowser();27    }28})();29const { openBrowser, goto, switchTo, closeBrowser } = require('taiko');30(async () => {31    try {32        await openBrowser();33        await switchTo("iframe");34        await click("Try it");35        await switchTo();36        await click("HTML Tutorial");37    } catch (e) {38        console.error(e);39    } finally {40        await closeBrowser();41    }42})();43const { openBrowser, goto, switchTo, closeBrowser } = require('taiko');44(async () => {45    try {46        await openBrowser();47        await switchTo("iframe");48        await click("Try it");49        await switchTo();50        await click("HTML Tutorial");51    } catch (e) {52        console.error(e);53    } finally {54        await closeBrowser();55    }56})();57const { openBrowser, goto, switchTo,Using AI Code Generation
1const { openBrowser, goto, switchTo, closeBrowser } = require('taiko');2(async () => {3    try {4        await openBrowser();5        await closeBrowser();6    } catch (e) {7        console.error(e);8    } finally {9    }10})();11const { openBrowser, goto, switchToFrame, closeBrowser } = require('taiko');12(async () => {13    try {14        await openBrowser();15        await closeBrowser();16    } catch (e) {17        console.error(e);18    } finally {19    }20})();21const { openBrowser, goto, switchToParentFrame, closeBrowser } = require('taiko');22(async () => {23    try {24        await openBrowser();25        await switchToParentFrame();26        await closeBrowser();27    } catch (e) {28        console.error(e);29    } finally {30    }31})();32const { openBrowser, goto, switchToPreviousTab, closeBrowser } = require('taiko');33(async () => {34    try {35        await openBrowser();36        await switchToPreviousTab();37        await closeBrowser();38    } catch (e) {39        console.error(e);40    } finally {41    }42})();Using AI Code Generation
1const { openBrowser, goto, switchTo, closeBrowser } = require('taiko');2(async () => {3    try {4        await openBrowser();5        await goto("google.com");6        await closeBrowser();7    } catch (e) {8        console.error(e);9    } finally {10    }11})();12const puppeteer = require('puppeteer');13(async () => {14    const browser = await puppeteer.launch({headless:false});15    const page = await browser.newPage();16    const newPagePromise = new Promise(x => browser.once('targetcreated', target => x(target.page())));17    await Promise.all([18    ]);19    await browser.close();20})();21const { remote } = require('webdriverio');22(async () => {23    const browser = await remote({24        capabilities: {25        }26    })27    await browser.closeWindow()28    await browser.deleteSession()29})();30const { chromium } = require('playwright');31(async () => {32    const browser = await chromium.launch({headless: false});33    const context = await browser.newContext();34    const page = await context.newPage();35    await page.close();36    await context.close();37    await browser.close();38})();39module.exports = {40    'Demo test Google' : function (browser) {41        .waitForElementVisible('body', 1000)42        .assert.title('Google')43        .assert.visible('input[type=text]')44        .setValue('inputUsing AI Code Generation
1const { openBrowser, goto, switchTo, closeBrowser, setConfig } = require('taiko');2(async () => {3    try {4        setConfig({5        });6        await openBrowser();Using AI Code Generation
1const { openBrowser, goto, switchTo, closeBrowser, write, button, link, text } = require('taiko');2(async () => {3    try {4        await openBrowser({headless:false});5        await write("Taiko",into(textBox({placeholder:"Search"})));6        await click(button({type:"submit"}));7        await click(link("Taiko - A Node.js library to automate web ..."));8        await click(link("Documentation"));9        await click(link("API Reference"));10        await click(link("switchTo"));11        await click(button("Run in REPL"));12        await click(link("Console"));13        await click(link("Console"));14        await press("Enter");15        await click(link("Documentation"));16        await click(link("API Reference"));17        await click(link("switchTo"));18        await click(button("Run in REPL"));19        await click(link("Console"));20        await click(link("Console"));21        await press("Enter");22        await click(link("Documentation"));23        await click(link("API Reference"));24        await click(link("switchTo"));25        await click(button("Run in REPL"));26        await click(link("Console"));27        await click(link("Console"));28        await press("Enter");29        await click(link("Documentation"));30        await click(link("API Reference"));31        await click(link("switchTo"));32        await click(button("Run in REPL"));33        await click(link("Console"));Using AI Code Generation
1const {switchTo} = require('taiko');2await write("Taiko");3await press("Enter");4await write("Taiko");5await press("Enter");6await write("Taiko");7await press("Enter");8await write("Taiko");9await press("Enter");10await write("Taiko");11await press("Enter");12await write("Taiko");13await press("Enter");14await write("Taiko");15await press("Enter");16await write("Taiko");17await press("Enter");18await write("Taiko");19await press("Enter");20await write("Taiko");21await press("Enter");22await write("Taiko");23await press("Enter");24await write("Taiko");25await press("Enter");Using AI Code Generation
1const { openBrowser, closeBrowser, goto, switchTo, write, click, button, textBox, dropDown, link, toRightOf, image, toLeftOf, text, waitFor, listItem, fileField } = require('taiko');2(async () => {3    try {4        await openBrowser({ headless: false });5        await write("Taiko", into(textBox(toRightOf("Google Search"))));6        await click("Google Search");7        await click("Taiko - Test Automation Framework");8        await click("Get Started");9        await click("Install Taiko");10        await click("Install");11        await click("Download");12        await click("Download");13        await click("Download");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!!
