code
stringlengths
2
1.05M
staticCache(resolve(filePath), { prefix: pf, gzip: true, maxAge: cache && isProd ? 60 * 60 * 24 * 30 : 0 });
var expect = require('chai').expect; var mocha = require('mocha'); var SheknowsStrategy = require('../lib/strategy'); describe('sheknows-passport strategy', function () { describe('constructed', function () { var subject = new SheknowsStrategy({ clientID: 'ABC123', clientSecret: 'keepitsecretkeepitsafe' }, function () {}); it('should be named sheknows', function () { expect(subject.name).to.eql('sheknows'); }); }); describe('constructed with undefined options', function () { it('show throw an error', function () { expect(function () { var strategy = new SheknowsStrategy(undefined, function () {}); }).to.throw(Error); }); }); });
import fs from 'fs'; import path from 'path'; import recast from '@gerhobbelt/recast'; import { transformSync } from '@babel/core'; import '@babel/parser'; import assert$1 from 'assert'; import XRegExp from '@gerhobbelt/xregexp'; import JSON5 from '@gerhobbelt/json5'; // Return TRUE if `src` starts with `searchString`. function startsWith(src, searchString) { return src.substr(0, searchString.length) === searchString; } // tagged template string helper which removes the indentation common to all // non-empty lines: that indentation was added as part of the source code // formatting of this lexer spec file and must be removed to produce what // we were aiming for. // // Each template string starts with an optional empty line, which should be // removed entirely, followed by a first line of error reporting content text, // which should not be indented at all, i.e. the indentation of the first // non-empty line should be treated as the 'common' indentation and thus // should also be removed from all subsequent lines in the same template string. // // See also: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Template_literals function rmCommonWS(strings, ...values) { // As `strings[]` is an array of strings, each potentially consisting // of multiple lines, followed by one(1) value, we have to split each // individual string into lines to keep that bit of information intact. // // We assume clean code style, hence no random mix of tabs and spaces, so every // line MUST have the same indent style as all others, so `length` of indent // should suffice, but the way we coded this is stricter checking as we look // for the *exact* indenting=leading whitespace in each line. var indent_str = null; var src = strings.map(function splitIntoLines(s) { var a = s.split('\n'); indent_str = a.reduce(function analyzeLine(indent_str, line, index) { // only check indentation of parts which follow a NEWLINE: if (index !== 0) { var m = /^(\s*)\S/.exec(line); // only non-empty ~ content-carrying lines matter re common indent calculus: if (m) { if (!indent_str) { indent_str = m[1]; } else if (m[1].length < indent_str.length) { indent_str = m[1]; } } } return indent_str; }, indent_str); return a; }); // Also note: due to the way we format the template strings in our sourcecode, // the last line in the entire template must be empty when it has ANY trailing // whitespace: var a = src[src.length - 1]; a[a.length - 1] = a[a.length - 1].replace(/\s+$/, ''); // Done removing common indentation. // // Process template string partials now, but only when there's // some actual UNindenting to do: if (indent_str) { for (var i = 0, len = src.length; i < len; i++) { var a = src[i]; // only correct indentation at start of line, i.e. only check for // the indent after every NEWLINE ==> start at j=1 rather than j=0 for (var j = 1, linecnt = a.length; j < linecnt; j++) { if (startsWith(a[j], indent_str)) { a[j] = a[j].substr(indent_str.length); } } } } // now merge everything to construct the template result: var rv = []; for (var i = 0, len = values.length; i < len; i++) { rv.push(src[i].join('\n')); rv.push(values[i]); } // the last value is always followed by a last template string partial: rv.push(src[i].join('\n')); var sv = rv.join(''); return sv; } // Convert dashed option keys to Camel Case, e.g. `camelCase('camels-have-one-hump')` => `'camelsHaveOneHump'` /** @public */ function camelCase(s) { // Convert first character to lowercase return s.replace(/^\w/, function (match) { return match.toLowerCase(); }) .replace(/-\w/g, function (match) { var c = match.charAt(1); var rv = c.toUpperCase(); // do not mutate 'a-2' to 'a2': if (c === rv && c.match(/\d/)) { return match; } return rv; }) } // Convert dashed option keys and other inputs to Camel Cased legal JavaScript identifiers /** @public */ function mkIdentifier(s) { s = '' + s; return s // Convert dashed ids to Camel Case (though NOT lowercasing the initial letter though!), // e.g. `camelCase('camels-have-one-hump')` => `'camelsHaveOneHump'` .replace(/-\w/g, function (match) { var c = match.charAt(1); var rv = c.toUpperCase(); // do not mutate 'a-2' to 'a2': if (c === rv && c.match(/\d/)) { return match; } return rv; }) // cleanup: replace any non-suitable character series to a single underscore: .replace(/^[^\w_]/, '_') // do not accept numerics at the leading position, despite those matching regex `\w`: .replace(/^\d/, '_') .replace(/[^\w\d_]/g, '_') // and only accept multiple (double, not triple) underscores at start or end of identifier name: .replace(/^__+/, '#') .replace(/__+$/, '#') .replace(/_+/g, '_') .replace(/#/g, '__'); } // Check if the start of the given input matches a regex expression. // Return the length of the regex expression or -1 if none was found. /** @public */ function scanRegExp(s) { s = '' + s; // code based on Esprima scanner: `Scanner.prototype.scanRegExpBody()` var index = 0; var length = s.length; var ch = s[index]; //assert.assert(ch === '/', 'Regular expression literal must start with a slash'); var str = s[index++]; var classMarker = false; var terminated = false; while (index < length) { ch = s[index++]; str += ch; if (ch === '\\') { ch = s[index++]; // https://tc39.github.io/ecma262/#sec-literals-regular-expression-literals if (isLineTerminator(ch.charCodeAt(0))) { break; // UnterminatedRegExp } str += ch; } else if (isLineTerminator(ch.charCodeAt(0))) { break; // UnterminatedRegExp } else if (classMarker) { if (ch === ']') { classMarker = false; } } else { if (ch === '/') { terminated = true; break; } else if (ch === '[') { classMarker = true; } } } if (!terminated) { return -1; // UnterminatedRegExp } return index; } // https://tc39.github.io/ecma262/#sec-line-terminators function isLineTerminator(cp) { return (cp === 0x0A) || (cp === 0x0D) || (cp === 0x2028) || (cp === 0x2029); } // Check if the given input can be a legal identifier-to-be-camelcased: // use this function to check if the way the identifier is written will // produce a sensible & comparable identifier name using the `mkIdentifier' // API - for humans that transformation should be obvious/trivial in // order to prevent confusion. /** @public */ function isLegalIdentifierInput(s) { s = '' + s; // Convert dashed ids to Camel Case (though NOT lowercasing the initial letter though!), // e.g. `camelCase('camels-have-one-hump')` => `'camelsHaveOneHump'` s = s .replace(/-\w/g, function (match) { var c = match.charAt(1); var rv = c.toUpperCase(); // do not mutate 'a-2' to 'a2': if (c === rv && c.match(/\d/)) { return match; } return rv; }); var alt = mkIdentifier(s); return alt === s; } // properly quote and escape the given input string function dquote(s) { var sq = (s.indexOf('\'') >= 0); var dq = (s.indexOf('"') >= 0); if (sq && dq) { s = s.replace(/"/g, '\\"'); dq = false; } if (dq) { s = '\'' + s + '\''; } else { s = '"' + s + '"'; } return s; } // function chkBugger(src) { src = String(src); if (src.match(/\bcov_\w+/)) { console.error('### ISTANBUL COVERAGE CODE DETECTED ###\n', src); } } // Helper function: pad number with leading zeroes function pad(n, p) { p = p || 2; var rv = '0000' + n; return rv.slice(-p); } // attempt to dump in one of several locations: first winner is *it*! function dumpSourceToFile(sourcecode, errname, err_id, options, ex) { var dumpfile; options = options || {}; try { var dumpPaths = [(options.outfile ? path.dirname(options.outfile) : null), options.inputPath, process.cwd()]; var dumpName = path.basename(options.inputFilename || options.moduleName || (options.outfile ? path.dirname(options.outfile) : null) || options.defaultModuleName || errname) .replace(/\.[a-z]{1,5}$/i, '') // remove extension .y, .yacc, .jison, ...whatever .replace(/[^a-z0-9_]/ig, '_'); // make sure it's legal in the destination filesystem: the least common denominator. if (dumpName === '' || dumpName === '_') { dumpName = '__bugger__'; } err_id = err_id || 'XXX'; var ts = new Date(); var tm = ts.getUTCFullYear() + '_' + pad(ts.getUTCMonth() + 1) + '_' + pad(ts.getUTCDate()) + 'T' + pad(ts.getUTCHours()) + '' + pad(ts.getUTCMinutes()) + '' + pad(ts.getUTCSeconds()) + '.' + pad(ts.getUTCMilliseconds(), 3) + 'Z'; dumpName += '.fatal_' + err_id + '_dump_' + tm + '.js'; for (var i = 0, l = dumpPaths.length; i < l; i++) { if (!dumpPaths[i]) { continue; } try { dumpfile = path.normalize(dumpPaths[i] + '/' + dumpName); fs.writeFileSync(dumpfile, sourcecode, 'utf8'); console.error("****** offending generated " + errname + " source code dumped into file: ", dumpfile); break; // abort loop once a dump action was successful! } catch (ex3) { //console.error("generated " + errname + " source code fatal DUMPING error ATTEMPT: ", i, " = ", ex3.message, " -- while attempting to dump into file: ", dumpfile, "\n", ex3.stack); if (i === l - 1) { throw ex3; } } } } catch (ex2) { console.error("generated " + errname + " source code fatal DUMPING error: ", ex2.message, " -- while attempting to dump into file: ", dumpfile, "\n", ex2.stack); } // augment the exception info, when available: if (ex) { ex.offending_source_code = sourcecode; ex.offending_source_title = errname; ex.offending_source_dumpfile = dumpfile; } } // // `code_execution_rig` is a function which gets executed, while it is fed the `sourcecode` as a parameter. // When the `code_execution_rig` crashes, its failure is caught and (using the `options`) the sourcecode // is dumped to file for later diagnosis. // // Two options drive the internal behaviour: // // - options.dumpSourceCodeOnFailure -- default: FALSE // - options.throwErrorOnCompileFailure -- default: FALSE // // Dumpfile naming and path are determined through these options: // // - options.outfile // - options.inputPath // - options.inputFilename // - options.moduleName // - options.defaultModuleName // function exec_and_diagnose_this_stuff(sourcecode, code_execution_rig, options, title) { options = options || {}; var errname = "" + (title || "exec_test"); var err_id = errname.replace(/[^a-z0-9_]/ig, "_"); if (err_id.length === 0) { err_id = "exec_crash"; } const debug = 0; var p; try { // p = eval(sourcecode); if (typeof code_execution_rig !== 'function') { throw new Error("safe-code-exec-and-diag: code_execution_rig MUST be a JavaScript function"); } chkBugger(sourcecode); p = code_execution_rig.call(this, sourcecode, options, errname, debug); } catch (ex) { if (options.dumpSourceCodeOnFailure) { dumpSourceToFile(sourcecode, errname, err_id, options, ex); } if (options.throwErrorOnCompileFailure) { throw ex; } } return p; } var code_exec = { exec: exec_and_diagnose_this_stuff, dump: dumpSourceToFile }; // assert$1(recast); var types = recast.types; assert$1(types); var namedTypes = types.namedTypes; assert$1(namedTypes); var b = types.builders; assert$1(b); // //assert(astUtils); function parseCodeChunkToAST(src, options) { // src = src // .replace(/@/g, '\uFFDA') // .replace(/#/g, '\uFFDB') // ; var ast = recast.parse(src); return ast; } function compileCodeToES5(src, options) { options = Object.assign({}, { ast: true, code: true, sourceMaps: true, comments: true, filename: 'compileCodeToES5.js', sourceFileName: 'compileCodeToES5.js', sourceRoot: '.', sourceType: 'module', babelrc: false, ignore: [ "node_modules/**/*.js" ], compact: false, retainLines: false, presets: [ ["@babel/preset-env", { targets: { browsers: ["last 2 versions", "safari >= 7"], node: "4.0" } }] ] }, options); return transformSync(src, options); // => { code, map, ast } } function prettyPrintAST(ast, options) { var new_src; var s = recast.prettyPrint(ast, { tabWidth: 2, quote: 'single', arrowParensAlways: true, // Do not reuse whitespace (or anything else, for that matter) // when printing generically. reuseWhitespace: false }); new_src = s.code; new_src = new_src .replace(/\r\n|\n|\r/g, '\n') // platform dependent EOL fixup // // backpatch possible jison variables extant in the prettified code: // .replace(/\uFFDA/g, '@') // .replace(/\uFFDB/g, '#') ; return new_src; } // validate the given JavaScript snippet: does it compile? // // Return either the parsed AST (object) or an error message (string). function checkActionBlock(src, yylloc) { // make sure reasonable line numbers, etc. are reported in any // potential parse errors by pushing the source code down: if (yylloc && yylloc.first_line > 0) { var cnt = yylloc.first_line; var lines = new Array(cnt); src = lines.join('\n') + src; } if (!src.trim()) { return false; } try { var rv = parseCodeChunkToAST(src); return false; } catch (ex) { return ex.message || "code snippet cannot be parsed"; } } // The rough-and-ready preprocessor for any action code block: // this one trims off any surplus whitespace and removes any // trailing semicolons and/or wrapping `{...}` braces, // when such is easily possible *without having to actually // **parse** the `src` code block in order to do this safely*. // // Returns the trimmed sourcecode which was provided via `src`. // // Note: the `startMarker` argument is special in that a lexer/parser // can feed us the delimiter which started the code block here: // when the starting delimiter actually is `{` we can safely // remove the outer `{...}` wrapper (which then *will* be present!), // while otherwise we may *not* do so as complex/specially-crafted // code will fail when it was wrapped in other delimiters, e.g. // action code specs like this one: // // %{ // { // trimActionCode sees this one as outer-starting: WRONG // a: 1 // }; // { // b: 2 // } // trimActionCode sees this one as outer-ending: WRONG // %} // // Of course the example would be 'ludicrous' action code but the // key point here is that users will certainly be able to come up with // convoluted code that is smarter than our simple regex-based // `{...}` trimmer in here! // function trimActionCode(src, startMarker) { var s = src.trim(); // remove outermost set of braces UNLESS there's // a curly brace in there anywhere: in that case // we should leave it up to the sophisticated // code analyzer to simplify the code! // // This is a very rough check as it will also look // inside code comments, which should not have // any influence. // // Nevertheless: this is a *safe* transform as // long as the code doesn't end with a C++-style // comment which happens to contain that closing // curly brace at the end! // // Also DO strip off any trailing optional semicolon, // which might have ended up here due to lexer rules // like this one: // // [a-z]+ -> 'TOKEN'; // // We can safely ditch any trailing semicolon(s) as // our code generator reckons with JavaScript's // ASI rules (Automatic Semicolon Insertion). // // // TODO: make this is real code edit without that // last edge case as a fault condition. if (startMarker === '{') { // code is wrapped in `{...}` for sure: remove the wrapping braces. s = s.replace(/^\{([^]*?)\}$/, '$1').trim(); } else { // code may not be wrapped or otherwise non-simple: only remove // wrapping braces when we can guarantee they're the only ones there, // i.e. only exist as outer wrapping. s = s.replace(/^\{([^}]*)\}$/, '$1').trim(); } s = s.replace(/;+$/, '').trim(); return s; } var parse2AST = { parseCodeChunkToAST, compileCodeToES5, prettyPrintAST, checkActionBlock, trimActionCode, }; function chkBugger$1(src) { src = String(src); if (src.match(/\bcov_\w+/)) { console.error('### ISTANBUL COVERAGE CODE DETECTED ###\n', src); } } /// HELPER FUNCTION: print the function in source code form, properly indented. /** @public */ function printFunctionSourceCode(f) { var src = String(f); chkBugger$1(src); return src; } const funcRe = /^function[\s\r\n]*[^\(]*\(([^\)]*)\)[\s\r\n]*\{([^]*?)\}$/; const arrowFuncRe = /^(?:(?:\(([^\)]*)\))|(?:([^\(\)]+)))[\s\r\n]*=>[\s\r\n]*(?:(?:\{([^]*?)\})|(?:(([^\s\r\n\{)])[^]*?)))$/; /// HELPER FUNCTION: print the function **content** in source code form, properly indented, /// ergo: produce the code for inlining the function. /// /// Also supports ES6's Arrow Functions: /// /// ``` /// function a(x) { return x; } ==> 'return x;' /// function (x) { return x; } ==> 'return x;' /// (x) => { return x; } ==> 'return x;' /// (x) => x; ==> 'return x;' /// (x) => do(1), do(2), x; ==> 'return (do(1), do(2), x);' /// /** @public */ function printFunctionSourceCodeContainer(f) { var action = printFunctionSourceCode(f).trim(); var args; // Also cope with Arrow Functions (and inline those as well?). // See also https://github.com/zaach/jison-lex/issues/23 var m = funcRe.exec(action); if (m) { args = m[1].trim(); action = m[2].trim(); } else { m = arrowFuncRe.exec(action); if (m) { if (m[2]) { // non-bracketed arguments: args = m[2].trim(); } else { // bracketed arguments: may be empty args list! args = m[1].trim(); } if (m[5]) { // non-bracketed version: implicit `return` statement! // // Q: Must we make sure we have extra braces around the return value // to prevent JavaScript from inserting implit EOS (End Of Statement) // markers when parsing this, when there are newlines in the code? // A: No, we don't have to as arrow functions rvalues suffer from this // same problem, hence the arrow function's programmer must already // have formatted the code correctly. action = m[4].trim(); action = 'return ' + action + ';'; } else { action = m[3].trim(); } } else { var e = new Error('Cannot extract code from function'); e.subject = action; throw e; } } return { args: args, code: action, }; } var stringifier = { printFunctionSourceCode, printFunctionSourceCodeContainer, }; // // // function detectIstanbulGlobal() { const gcv = "__coverage__"; const globalvar = new Function('return this')(); var coverage = globalvar[gcv]; return coverage || false; } // // Helper library for safe code execution/compilation // // MIT Licensed // // // This code is intended to help test and diagnose arbitrary regexes, answering questions like this: // // - is this a valid regex, i.e. does it compile? // - does it have captures, and if yes, how many? // //import XRegExp from '@gerhobbelt/xregexp'; // validate the given regex. // // You can specify an (advanced or regular) regex class as a third parameter. // The default assumed is the standard JavaScript `RegExp` class. // // Return FALSE when there's no failure, otherwise return an `Error` info object. function checkRegExp(re_src, re_flags, XRegExp$$1) { var re; // were we fed a RegExp object or a string? if (re_src && typeof re_src.source === 'string' && typeof re_src.flags === 'string' && typeof re_src.toString === 'function' && typeof re_src.test === 'function' && typeof re_src.exec === 'function' ) { // we're looking at a RegExp (or XRegExp) object, so we can trust the `.source` member // and the `.toString()` method to produce something that's compileable by XRegExp // at least... if (!re_flags || re_flags === re_src.flags) { // no change of flags: we assume it's okay as it's already contained // in an RegExp or XRegExp object return false; } } // we DO accept empty regexes: `''` but we DO NOT accept null/undefined if (re_src == null) { return new Error('invalid regular expression source: ' + re_src); } re_src = '' + re_src; if (re_flags == null) { re_flags = undefined; // `new RegExp(..., flags)` will barf a hairball when `flags===null` } else { re_flags = '' + re_flags; } XRegExp$$1 = XRegExp$$1 || RegExp; try { re = new XRegExp$$1(re_src, re_flags); } catch (ex) { return ex; } return false; } // provide some info about the given regex. // // You can specify an (advanced or regular) regex class as a third parameter. // The default assumed is the standard JavaScript `RegExp` class. // // Return FALSE when the input is not a legal regex. function getRegExpInfo(re_src, re_flags, XRegExp$$1) { var re1, re2, m1, m2; // were we fed a RegExp object or a string? if (re_src && typeof re_src.source === 'string' && typeof re_src.flags === 'string' && typeof re_src.toString === 'function' && typeof re_src.test === 'function' && typeof re_src.exec === 'function' ) { // we're looking at a RegExp (or XRegExp) object, so we can trust the `.source` member // and the `.toString()` method to produce something that's compileable by XRegExp // at least... if (!re_flags || re_flags === re_src.flags) { // no change of flags: we assume it's okay as it's already contained // in an RegExp or XRegExp object re_flags = undefined; } } else if (re_src == null) { // we DO NOT accept null/undefined return false; } else { re_src = '' + re_src; if (re_flags == null) { re_flags = undefined; // `new RegExp(..., flags)` will barf a hairball when `flags===null` } else { re_flags = '' + re_flags; } } XRegExp$$1 = XRegExp$$1 || RegExp; try { // A little trick to obtain the captures from a regex: // wrap it and append `(?:)` to ensure it matches // the empty string, then match it against it to // obtain the `match` array. re1 = new XRegExp$$1(re_src, re_flags); re2 = new XRegExp$$1('(?:' + re_src + ')|(?:)', re_flags); m1 = re1.exec(''); m2 = re2.exec(''); return { acceptsEmptyString: !!m1, captureCount: m2.length - 1 }; } catch (ex) { return false; } } var reHelpers = { checkRegExp: checkRegExp, getRegExpInfo: getRegExpInfo }; var cycleref = []; var cyclerefpath = []; var linkref = []; var linkrefpath = []; var path$1 = []; function shallow_copy(src) { if (typeof src === 'object') { if (src instanceof Array) { return src.slice(); } var dst = {}; if (src instanceof Error) { dst.name = src.name; dst.message = src.message; dst.stack = src.stack; } for (var k in src) { if (Object.prototype.hasOwnProperty.call(src, k)) { dst[k] = src[k]; } } return dst; } return src; } function shallow_copy_and_strip_depth(src, parentKey) { if (typeof src === 'object') { var dst; if (src instanceof Array) { dst = src.slice(); for (var i = 0, len = dst.length; i < len; i++) { path$1.push('[' + i + ']'); dst[i] = shallow_copy_and_strip_depth(dst[i], parentKey + '[' + i + ']'); path$1.pop(); } } else { dst = {}; if (src instanceof Error) { dst.name = src.name; dst.message = src.message; dst.stack = src.stack; } for (var k in src) { if (Object.prototype.hasOwnProperty.call(src, k)) { var el = src[k]; if (el && typeof el === 'object') { dst[k] = '[cyclic reference::attribute --> ' + parentKey + '.' + k + ']'; } else { dst[k] = src[k]; } } } } return dst; } return src; } function trim_array_tail(arr) { if (arr instanceof Array) { for (var len = arr.length; len > 0; len--) { if (arr[len - 1] != null) { break; } } arr.length = len; } } function treat_value_stack(v) { if (v instanceof Array) { var idx = cycleref.indexOf(v); if (idx >= 0) { v = '[cyclic reference to parent array --> ' + cyclerefpath[idx] + ']'; } else { idx = linkref.indexOf(v); if (idx >= 0) { v = '[reference to sibling array --> ' + linkrefpath[idx] + ', length = ' + v.length + ']'; } else { cycleref.push(v); cyclerefpath.push(path$1.join('.')); linkref.push(v); linkrefpath.push(path$1.join('.')); v = treat_error_infos_array(v); cycleref.pop(); cyclerefpath.pop(); } } } else if (v) { v = treat_object(v); } return v; } function treat_error_infos_array(arr) { var inf = arr.slice(); trim_array_tail(inf); for (var key = 0, len = inf.length; key < len; key++) { var err = inf[key]; if (err) { path$1.push('[' + key + ']'); err = treat_object(err); if (typeof err === 'object') { if (err.lexer) { err.lexer = '[lexer]'; } if (err.parser) { err.parser = '[parser]'; } trim_array_tail(err.symbol_stack); trim_array_tail(err.state_stack); trim_array_tail(err.location_stack); if (err.value_stack) { path$1.push('value_stack'); err.value_stack = treat_value_stack(err.value_stack); path$1.pop(); } } inf[key] = err; path$1.pop(); } } return inf; } function treat_lexer(l) { // shallow copy object: l = shallow_copy(l); delete l.simpleCaseActionClusters; delete l.rules; delete l.conditions; delete l.__currentRuleSet__; if (l.__error_infos) { path$1.push('__error_infos'); l.__error_infos = treat_value_stack(l.__error_infos); path$1.pop(); } return l; } function treat_parser(p) { // shallow copy object: p = shallow_copy(p); delete p.productions_; delete p.table; delete p.defaultActions; if (p.__error_infos) { path$1.push('__error_infos'); p.__error_infos = treat_value_stack(p.__error_infos); path$1.pop(); } if (p.__error_recovery_infos) { path$1.push('__error_recovery_infos'); p.__error_recovery_infos = treat_value_stack(p.__error_recovery_infos); path$1.pop(); } if (p.lexer) { path$1.push('lexer'); p.lexer = treat_lexer(p.lexer); path$1.pop(); } return p; } function treat_hash(h) { // shallow copy object: h = shallow_copy(h); if (h.parser) { path$1.push('parser'); h.parser = treat_parser(h.parser); path$1.pop(); } if (h.lexer) { path$1.push('lexer'); h.lexer = treat_lexer(h.lexer); path$1.push(); } return h; } function treat_error_report_info(e) { // shallow copy object: e = shallow_copy(e); if (e && e.hash) { path$1.push('hash'); e.hash = treat_hash(e.hash); path$1.pop(); } if (e.parser) { path$1.push('parser'); e.parser = treat_parser(e.parser); path$1.pop(); } if (e.lexer) { path$1.push('lexer'); e.lexer = treat_lexer(e.lexer); path$1.pop(); } if (e.__error_infos) { path$1.push('__error_infos'); e.__error_infos = treat_value_stack(e.__error_infos); path$1.pop(); } if (e.__error_recovery_infos) { path$1.push('__error_recovery_infos'); e.__error_recovery_infos = treat_value_stack(e.__error_recovery_infos); path$1.pop(); } trim_array_tail(e.symbol_stack); trim_array_tail(e.state_stack); trim_array_tail(e.location_stack); if (e.value_stack) { path$1.push('value_stack'); e.value_stack = treat_value_stack(e.value_stack); path$1.pop(); } return e; } function treat_object(e) { if (e && typeof e === 'object') { var idx = cycleref.indexOf(e); if (idx >= 0) { // cyclic reference, most probably an error instance. // we still want it to be READABLE in a way, though: e = shallow_copy_and_strip_depth(e, cyclerefpath[idx]); } else { idx = linkref.indexOf(e); if (idx >= 0) { e = '[reference to sibling --> ' + linkrefpath[idx] + ']'; } else { cycleref.push(e); cyclerefpath.push(path$1.join('.')); linkref.push(e); linkrefpath.push(path$1.join('.')); e = treat_error_report_info(e); cycleref.pop(); cyclerefpath.pop(); } } } return e; } // strip off large chunks from the Error exception object before // it will be fed to a test log or other output. // // Internal use in the unit test rigs. function trimErrorForTestReporting(e) { cycleref.length = 0; cyclerefpath.length = 0; linkref.length = 0; linkrefpath.length = 0; path$1 = ['*']; if (e) { e = treat_object(e); } cycleref.length = 0; cyclerefpath.length = 0; linkref.length = 0; linkrefpath.length = 0; path$1 = ['*']; return e; } var helpers = { rmCommonWS, camelCase, mkIdentifier, isLegalIdentifierInput, scanRegExp, dquote, trimErrorForTestReporting, checkRegExp: reHelpers.checkRegExp, getRegExpInfo: reHelpers.getRegExpInfo, exec: code_exec.exec, dump: code_exec.dump, parseCodeChunkToAST: parse2AST.parseCodeChunkToAST, compileCodeToES5: parse2AST.compileCodeToES5, prettyPrintAST: parse2AST.prettyPrintAST, checkActionBlock: parse2AST.checkActionBlock, trimActionCode: parse2AST.trimActionCode, printFunctionSourceCode: stringifier.printFunctionSourceCode, printFunctionSourceCodeContainer: stringifier.printFunctionSourceCodeContainer, detectIstanbulGlobal, }; // See also: // http://stackoverflow.com/questions/1382107/whats-a-good-way-to-extend-error-in-javascript/#35881508 // but we keep the prototype.constructor and prototype.name assignment lines too for compatibility // with userland code which might access the derived class in a 'classic' way. function JisonParserError(msg, hash) { Object.defineProperty(this, 'name', { enumerable: false, writable: false, value: 'JisonParserError' }); if (msg == null) msg = '???'; Object.defineProperty(this, 'message', { enumerable: false, writable: true, value: msg }); this.hash = hash; var stacktrace; if (hash && hash.exception instanceof Error) { var ex2 = hash.exception; this.message = ex2.message || msg; stacktrace = ex2.stack; } if (!stacktrace) { if (Error.hasOwnProperty('captureStackTrace')) { // V8/Chrome engine Error.captureStackTrace(this, this.constructor); } else { stacktrace = (new Error(msg)).stack; } } if (stacktrace) { Object.defineProperty(this, 'stack', { enumerable: false, writable: false, value: stacktrace }); } } if (typeof Object.setPrototypeOf === 'function') { Object.setPrototypeOf(JisonParserError.prototype, Error.prototype); } else { JisonParserError.prototype = Object.create(Error.prototype); } JisonParserError.prototype.constructor = JisonParserError; JisonParserError.prototype.name = 'JisonParserError'; // helper: reconstruct the productions[] table function bp(s) { var rv = []; var p = s.pop; var r = s.rule; for (var i = 0, l = p.length; i < l; i++) { rv.push([ p[i], r[i] ]); } return rv; } // helper: reconstruct the defaultActions[] table function bda(s) { var rv = {}; var d = s.idx; var g = s.goto; for (var i = 0, l = d.length; i < l; i++) { var j = d[i]; rv[j] = g[i]; } return rv; } // helper: reconstruct the 'goto' table function bt(s) { var rv = []; var d = s.len; var y = s.symbol; var t = s.type; var a = s.state; var m = s.mode; var g = s.goto; for (var i = 0, l = d.length; i < l; i++) { var n = d[i]; var q = {}; for (var j = 0; j < n; j++) { var z = y.shift(); switch (t.shift()) { case 2: q[z] = [ m.shift(), g.shift() ]; break; case 0: q[z] = a.shift(); break; default: // type === 1: accept q[z] = [ 3 ]; } } rv.push(q); } return rv; } // helper: runlength encoding with increment step: code, length: step (default step = 0) // `this` references an array function s(c, l, a) { a = a || 0; for (var i = 0; i < l; i++) { this.push(c); c += a; } } // helper: duplicate sequence from *relative* offset and length. // `this` references an array function c(i, l) { i = this.length - i; for (l += i; i < l; i++) { this.push(this[i]); } } // helper: unpack an array using helpers and data, all passed in an array argument 'a'. function u(a) { var rv = []; for (var i = 0, l = a.length; i < l; i++) { var e = a[i]; // Is this entry a helper function? if (typeof e === 'function') { i++; e.apply(rv, a[i]); } else { rv.push(e); } } return rv; } var parser = { // Code Generator Information Report // --------------------------------- // // Options: // // default action mode: ............. ["classic","merge"] // test-compile action mode: ........ "parser:*,lexer:*" // try..catch: ...................... true // default resolve on conflict: ..... true // on-demand look-ahead: ............ false // error recovery token skip maximum: 3 // yyerror in parse actions is: ..... NOT recoverable, // yyerror in lexer actions and other non-fatal lexer are: // .................................. NOT recoverable, // debug grammar/output: ............ false // has partial LR conflict upgrade: true // rudimentary token-stack support: false // parser table compression mode: ... 2 // export debug tables: ............. false // export *all* tables: ............. false // module type: ..................... es // parser engine type: .............. lalr // output main() in the module: ..... true // has user-specified main(): ....... false // has user-specified require()/import modules for main(): // .................................. false // number of expected conflicts: .... 0 // // // Parser Analysis flags: // // no significant actions (parser is a language matcher only): // .................................. false // uses yyleng: ..................... false // uses yylineno: ................... false // uses yytext: ..................... false // uses yylloc: ..................... false // uses ParseError API: ............. false // uses YYERROR: .................... true // uses YYRECOVERING: ............... false // uses YYERROK: .................... false // uses YYCLEARIN: .................. false // tracks rule values: .............. true // assigns rule values: ............. true // uses location tracking: .......... true // assigns location: ................ true // uses yystack: .................... false // uses yysstack: ................... false // uses yysp: ....................... true // uses yyrulelength: ............... false // uses yyMergeLocationInfo API: .... true // has error recovery: .............. true // has error reporting: ............. true // // --------- END OF REPORT ----------- trace: function no_op_trace() { }, JisonParserError: JisonParserError, yy: {}, options: { type: "lalr", hasPartialLrUpgradeOnConflict: true, errorRecoveryTokenDiscardCount: 3, ebnf: true }, symbols_: { "$": 16, "$accept": 0, "$end": 1, "%%": 19, "(": 8, ")": 9, "*": 11, "+": 10, ",": 17, ".": 14, "/": 13, "/!": 42, "<": 3, "=": 18, ">": 6, "?": 12, "ACTION_BODY": 36, "ACTION_END": 24, "ACTION_START": 26, "ACTION_START_AT_SOL": 23, "ARROW_ACTION_START": 35, "BRACKET_MISSING": 38, "BRACKET_SURPLUS": 39, "CHARACTER_LIT": 51, "CODE": 31, "DUMMY": 27, "DUMMY3": 52, "EOF": 1, "ESCAPED_CHAR": 44, "IMPORT": 30, "INCLUDE": 32, "INCLUDE_PLACEMENT_ERROR": 37, "MACRO_END": 21, "MACRO_NAME": 20, "NAME_BRACE": 45, "OPTIONS": 29, "OPTIONS_END": 22, "OPTION_STRING": 53, "OPTION_VALUE": 54, "RANGE_REGEX": 49, "REGEX_SET": 48, "REGEX_SET_END": 47, "REGEX_SET_START": 46, "REGEX_SPECIAL_CHAR": 43, "SPECIAL_GROUP": 41, "START_EXC": 34, "START_INC": 33, "STRING_LIT": 50, "TRAILING_CODE_CHUNK": 55, "UNKNOWN_DECL": 28, "UNTERMINATED_ACTION_BLOCK": 25, "UNTERMINATED_STRING_ERROR": 40, "^": 15, "action": 72, "any_group_regex": 80, "definition": 60, "definitions": 59, "epilogue": 89, "epilogue_chunk": 91, "epilogue_chunks": 90, "error": 2, "import_keyword": 62, "include_keyword": 64, "include_macro_code": 92, "init": 58, "init_code_keyword": 63, "lex": 56, "literal_string": 84, "name_expansion": 79, "nonempty_regex_list": 76, "option": 86, "option_keyword": 61, "option_list": 85, "option_name": 87, "option_value": 88, "range_regex": 83, "regex": 74, "regex_base": 78, "regex_concat": 77, "regex_list": 75, "regex_set": 81, "regex_set_atom": 82, "rule": 71, "rule_block": 70, "rules": 68, "rules_and_epilogue": 57, "scoped_rules_collective": 69, "start_conditions": 73, "start_conditions_marker": 67, "start_exclusive_keyword": 66, "start_inclusive_keyword": 65, "{": 4, "|": 7, "}": 5 }, terminals_: { 1: "EOF", 2: "error", 3: "<", 4: "{", 5: "}", 6: ">", 7: "|", 8: "(", 9: ")", 10: "+", 11: "*", 12: "?", 13: "/", 14: ".", 15: "^", 16: "$", 17: ",", 18: "=", 19: "%%", 20: "MACRO_NAME", 21: "MACRO_END", 22: "OPTIONS_END", 23: "ACTION_START_AT_SOL", 24: "ACTION_END", 25: "UNTERMINATED_ACTION_BLOCK", 26: "ACTION_START", 27: "DUMMY", 28: "UNKNOWN_DECL", 29: "OPTIONS", 30: "IMPORT", 31: "CODE", 32: "INCLUDE", 33: "START_INC", 34: "START_EXC", 35: "ARROW_ACTION_START", 36: "ACTION_BODY", 37: "INCLUDE_PLACEMENT_ERROR", 38: "BRACKET_MISSING", 39: "BRACKET_SURPLUS", 40: "UNTERMINATED_STRING_ERROR", 41: "SPECIAL_GROUP", 42: "/!", 43: "REGEX_SPECIAL_CHAR", 44: "ESCAPED_CHAR", 45: "NAME_BRACE", 46: "REGEX_SET_START", 47: "REGEX_SET_END", 48: "REGEX_SET", 49: "RANGE_REGEX", 50: "STRING_LIT", 51: "CHARACTER_LIT", 52: "DUMMY3", 53: "OPTION_STRING", 54: "OPTION_VALUE", 55: "TRAILING_CODE_CHUNK" }, terminal_descriptions_: { 45: "macro name in '{...}' curly braces" }, TERROR: 2, EOF: 1, // internals: defined here so the object *structure* doesn't get modified by parse() et al, // thus helping JIT compilers like Chrome V8. originalQuoteName: null, originalParseError: null, cleanupAfterParse: null, constructParseErrorInfo: null, yyMergeLocationInfo: null, __reentrant_call_depth: 0, // INTERNAL USE ONLY __error_infos: [], // INTERNAL USE ONLY: the set of parseErrorInfo objects created since the last cleanup __error_recovery_infos: [], // INTERNAL USE ONLY: the set of parseErrorInfo objects created since the last cleanup // APIs which will be set up depending on user action code analysis: //yyRecovering: 0, //yyErrOk: 0, //yyClearIn: 0, // Helper APIs // ----------- // Helper function which can be overridden by user code later on: put suitable quotes around // literal IDs in a description string. quoteName: function parser_quoteName(id_str) { return '"' + id_str + '"'; }, // Return the name of the given symbol (terminal or non-terminal) as a string, when available. // // Return NULL when the symbol is unknown to the parser. getSymbolName: function parser_getSymbolName(symbol) { if (this.terminals_[symbol]) { return this.terminals_[symbol]; } // Otherwise... this might refer to a RULE token i.e. a non-terminal: see if we can dig that one up. // // An example of this may be where a rule's action code contains a call like this: // // parser.getSymbolName(#$) // // to obtain a human-readable name of the current grammar rule. var s = this.symbols_; for (var key in s) { if (s[key] === symbol) { return key; } } return null; }, // Return a more-or-less human-readable description of the given symbol, when available, // or the symbol itself, serving as its own 'description' for lack of something better to serve up. // // Return NULL when the symbol is unknown to the parser. describeSymbol: function parser_describeSymbol(symbol) { if (symbol !== this.EOF && this.terminal_descriptions_ && this.terminal_descriptions_[symbol]) { return this.terminal_descriptions_[symbol]; } else if (symbol === this.EOF) { return 'end of input'; } var id = this.getSymbolName(symbol); if (id) { return this.quoteName(id); } return null; }, // Produce a (more or less) human-readable list of expected tokens at the point of failure. // // The produced list may contain token or token set descriptions instead of the tokens // themselves to help turning this output into something that easier to read by humans // unless `do_not_describe` parameter is set, in which case a list of the raw, *numeric*, // expected terminals and nonterminals is produced. // // The returned list (array) will not contain any duplicate entries. collect_expected_token_set: function parser_collect_expected_token_set(state, do_not_describe) { var TERROR = this.TERROR; var tokenset = []; var check = {}; // Has this (error?) state been outfitted with a custom expectations description text for human consumption? // If so, use that one instead of the less palatable token set. if (!do_not_describe && this.state_descriptions_ && this.state_descriptions_[state]) { return [ this.state_descriptions_[state] ]; } for (var p in this.table[state]) { p = +p; if (p !== TERROR) { var d = do_not_describe ? p : this.describeSymbol(p); if (d && !check[d]) { tokenset.push(d); check[d] = true; // Mark this token description as already mentioned to prevent outputting duplicate entries. } } } return tokenset; }, productions_: bp({ pop: u([ 56, s, [57, 5], 58, 59, 59, s, [60, 21], s, [61, 8, 1], s, [68, 13], s, [69, 5], 70, 70, s, [71, 5], s, [72, 7], 73, 73, 74, 75, 75, s, [76, 5], 77, 77, s, [78, 18], 79, 80, 80, 81, 81, 82, 82, 83, 84, 84, s, [85, 3], s, [86, 4], 87, 87, 88, 88, s, [89, 3], s, [90, 3], s, [91, 5], 92, 92 ]), rule: u([ 4, 3, 3, 2, 2, 0, 0, 2, 0, 3, 2, 3, 2, c, [4, 3], 1, c, [5, 3], c, [3, 3], 1, 3, 2, 6, 4, 2, s, [1, 8], 2, 2, 4, 2, 3, 4, c, [25, 3], s, [2, 4], 0, 2, 4, c, [53, 4], 0, c, [6, 5], c, [19, 7], 4, 3, 1, 1, c, [66, 3], c, [49, 3], c, [58, 3], s, [3, 3], s, [2, 5], c, [12, 3], s, [1, 7], c, [17, 3], c, [9, 7], c, [8, 3], c, [13, 8], c, [35, 5], c, [13, 5], 3, 2 ]) }), performAction: function parser__PerformAction(yyloc, yystate /* action[1] */, yysp, yyvstack, yylstack) { /* this == yyval */ // the JS engine itself can go and remove these statements when `yy` turns out to be unused in any action code! var yy = this.yy; var yyparser = yy.parser; var yylexer = yy.lexer; const OPTION_DOES_NOT_ACCEPT_VALUE = 0x0001; const OPTION_EXPECTS_ONLY_IDENTIFIER_NAMES = 0x0002; const OPTION_ALSO_ACCEPTS_STAR_AS_IDENTIFIER_NAME = 0x0004; const OPTION_DOES_NOT_ACCEPT_MULTIPLE_OPTIONS = 0x0008; const OPTION_DOES_NOT_ACCEPT_COMMA_SEPARATED_OPTIONS = 0x0010; switch (yystate) { case 0: /*! Production:: $accept : lex $end */ // default action (generated by JISON mode classic/merge :: 1,VT,VA,-,-,LT,LA,-,-): this.$ = yyvstack[yysp - 1]; this._$ = yylstack[yysp - 1]; // END of default action (generated by JISON mode classic/merge :: 1,VT,VA,-,-,LT,LA,-,-) break; case 1: /*! Production:: lex : init definitions rules_and_epilogue EOF */ // default action (generated by JISON mode classic/merge :: 4,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 3, yysp); // END of default action (generated by JISON mode classic/merge :: 4,VT,VA,VU,-,LT,LA,-,-) this.$ = yyvstack[yysp - 1]; for (var key in yyvstack[yysp - 2]) { this.$[key] = yyvstack[yysp - 2][key]; } // if there are any options, add them all, otherwise set options to NULL: // can't check for 'empty object' by `if (yy.options) ...` so we do it this way: for (key in yy.options) { this.$.options = yy.options; break; } if (yy.actionInclude) { var asrc = yy.actionInclude.join('\n\n'); // Only a non-empty action code chunk should actually make it through: if (asrc.trim() !== '') { this.$.actionInclude = asrc; } } delete yy.options; delete yy.actionInclude; return this.$; break; case 2: /*! Production:: rules_and_epilogue : "%%" rules epilogue */ // default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 2, yysp); // END of default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-) if (yyvstack[yysp]) { this.$ = { rules: yyvstack[yysp - 1], moduleInclude: yyvstack[yysp] }; } else { this.$ = { rules: yyvstack[yysp - 1] }; } break; case 3: /*! Production:: rules_and_epilogue : "%%" error epilogue */ // default action (generated by JISON mode classic/merge :: 3,VT,VA,-,-,LT,LA,-,-): this.$ = yyvstack[yysp - 2]; this._$ = yyparser.yyMergeLocationInfo(yysp - 2, yysp); // END of default action (generated by JISON mode classic/merge :: 3,VT,VA,-,-,LT,LA,-,-) yyparser.yyError(rmCommonWS$1` There's probably an error in one or more of your lexer regex rules. The lexer rule spec should have this structure: regex action_code where 'regex' is a lex-style regex expression (see the jison and jison-lex documentation) which is intended to match a chunk of the input to lex, while the 'action_code' block is the JS code which will be invoked when the regex is matched. The 'action_code' block may be any (indented!) set of JS statements, optionally surrounded by '{...}' curly braces or otherwise enclosed in a '%{...%}' block. Erroneous code: ${yylexer.prettyPrintRange(yylstack[yysp - 1])} Technical error report: ${yyvstack[yysp - 1].errStr} `); break; case 4: /*! Production:: rules_and_epilogue : "%%" rules */ // default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 1, yysp); // END of default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-) this.$ = { rules: yyvstack[yysp] }; break; case 5: /*! Production:: rules_and_epilogue : "%%" error */ // default action (generated by JISON mode classic/merge :: 2,VT,VA,-,-,LT,LA,-,-): this.$ = yyvstack[yysp - 1]; this._$ = yyparser.yyMergeLocationInfo(yysp - 1, yysp); // END of default action (generated by JISON mode classic/merge :: 2,VT,VA,-,-,LT,LA,-,-) yyparser.yyError(rmCommonWS$1` There's probably an error in one or more of your lexer regex rules. There's an error in your lexer regex rules section. Maybe you did not correctly separate the lexer sections with a '%%' on an otherwise empty line? Did you correctly delimit every rule's action code block? The lexer spec file should have this structure: definitions %% rules %% // <-- only needed if ... extra_module_code // <-- ... epilogue is present. Erroneous code: ${yylexer.prettyPrintRange(yylstack[yysp])} Technical error report: ${yyvstack[yysp].errStr} `); break; case 6: /*! Production:: rules_and_epilogue : %epsilon */ // default action (generated by JISON mode classic/merge :: 0,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(null, null, null, null, true); // END of default action (generated by JISON mode classic/merge :: 0,VT,VA,VU,-,LT,LA,-,-) this.$ = { rules: [] }; break; case 7: /*! Production:: init : %epsilon */ // default action (generated by JISON mode classic/merge :: 0,VT,VA,-,-,LT,LA,-,-): this.$ = undefined; this._$ = yyparser.yyMergeLocationInfo(null, null, null, null, true); // END of default action (generated by JISON mode classic/merge :: 0,VT,VA,-,-,LT,LA,-,-) yy.actionInclude = []; if (!yy.options) yy.options = {}; yy.__options_flags__ = 0; yy.__options_category_description__ = '???'; // Store the `%s` and `%x` condition states in `yy` to ensure the rules section of the // lex language parser can reach these and use them for validating whether the lexer // rules written by the user actually reference *known* condition states. yy.startConditions = {}; // hash table // The next attribute + API set is a 'lexer/parser hack' in the sense that // it assumes zero look-ahead at some points during the parse // when a parser rule production's action code pushes or pops a value // on/off the context description stack to help the lexer produce // better informing error messages in case of a subsequent lexer // fail. yy.__context_description__ = ['???CONTEXT???']; yy.pushContextDescription = function (str) { yy.__context_description__.push(str); }; yy.popContextDescription = function () { if (yy.__context_description__.length > 1) { yy.__context_description__.pop(); } else { yyparser.yyError('__context_description__ stack depleted! Contact a developer!'); } }; yy.getContextDescription = function () { return yy.__context_description__[yy.__context_description__.length - 1]; }; break; case 8: /*! Production:: definitions : definitions definition */ // default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 1, yysp); // END of default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-) this.$ = yyvstack[yysp - 1]; if (yyvstack[yysp]) { switch (yyvstack[yysp].type) { case 'macro': this.$.macros[yyvstack[yysp].name] = yyvstack[yysp].body; break; case 'names': var condition_defs = yyvstack[yysp].names; for (var i = 0, len = condition_defs.length; i < len; i++) { var name = condition_defs[i][0]; if (name in this.$.startConditions && this.$.startConditions[name] !== condition_defs[i][1]) { yyparser.yyError(rmCommonWS$1` You have specified the lexer condition state '${name}' as both EXCLUSIVE ('%x') and INCLUSIVE ('%s'). Pick one, please, e.g.: %x ${name} %% <${name}>LEXER_RULE_REGEX return 'TOK'; Erroneous code: ${yylexer.prettyPrintRange(yylstack[yysp], yylstack[yysp - 1])} Technical error report: ${yyvstack[yysp].errStr} `); } this.$.startConditions[name] = condition_defs[i][1]; // flag as 'exclusive'/'inclusive' } // and update the `yy.startConditions` hash table as well, so we have a full set // by the time this parser arrives at the lexer rules in the input-to-parse: yy.startConditions = this.$.startConditions; break; case 'unknown': this.$.unknownDecls.push(yyvstack[yysp].body); break; case 'imports': this.$.importDecls.push(yyvstack[yysp].body); break; case 'codeSection': this.$.codeSections.push(yyvstack[yysp].body); break; default: yyparser.yyError(rmCommonWS$1` Encountered an unsupported definition type: ${yyvstack[yysp].type}. Erroneous area: ${yylexer.prettyPrintRange(yylstack[yysp])} `); break; } } break; case 9: /*! Production:: definitions : %epsilon */ // default action (generated by JISON mode classic/merge :: 0,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(null, null, null, null, true); // END of default action (generated by JISON mode classic/merge :: 0,VT,VA,VU,-,LT,LA,-,-) this.$ = { macros: {}, // { hash table } startConditions: {}, // { hash table } codeSections: [], // [ array of {qualifier,include} pairs ] importDecls: [], // [ array of {name,path} pairs ] unknownDecls: [] // [ array of {name,value} pairs ] }; break; case 10: /*! Production:: definition : MACRO_NAME regex MACRO_END */ // default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 2, yysp); // END of default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-) // Note: make sure we don't try re-define/override any XRegExp `\p{...}` or `\P{...}` // macros here: if (XRegExp._getUnicodeProperty(yyvstack[yysp - 2])) { // Work-around so that you can use `\p{ascii}` for a XRegExp slug, a.k.a. // Unicode 'General Category' Property cf. http://unicode.org/reports/tr18/#Categories, // while using `\p{ASCII}` as a *macro expansion* of the `ASCII` // macro: if (yyvstack[yysp - 2].toUpperCase() !== yyvstack[yysp - 2]) { yyparser.yyError(rmCommonWS$1` Cannot use name "${$MACRO_NAME}" as a macro name as it clashes with the same XRegExp "\\p{..}" Unicode \'General Category\' Property name. Use all-uppercase macro names, e.g. name your macro "${$MACRO_NAME.toUpperCase()}" to work around this issue or give your offending macro a different name. Erroneous area: ${yylexer.prettyPrintRange(yylstack[yysp - 2])} `); } } this.$ = { type: 'macro', name: yyvstack[yysp - 2], body: yyvstack[yysp - 1] }; break; case 11: /*! Production:: definition : MACRO_NAME error */ // default action (generated by JISON mode classic/merge :: 2,VT,VA,-,-,LT,LA,-,-): this.$ = yyvstack[yysp - 1]; this._$ = yyparser.yyMergeLocationInfo(yysp - 1, yysp); // END of default action (generated by JISON mode classic/merge :: 2,VT,VA,-,-,LT,LA,-,-) yyparser.yyError(rmCommonWS$1` ill defined macro definition. Erroneous code: ${yylexer.prettyPrintRange(yylstack[yysp], yylstack[yysp - 1])} Technical error report: ${yyvstack[yysp].errStr} `); break; case 12: /*! Production:: definition : start_inclusive_keyword option_list OPTIONS_END */ // default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 2, yysp); // END of default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-) var lst = yyvstack[yysp - 1]; for (var i = 0, len = lst.length; i < len; i++) { lst[i][1] = 0; // flag as 'inclusive' } this.$ = { type: 'names', names: lst // 'inclusive' conditions have value 0, 'exclusive' conditions have value 1 }; break; case 13: /*! Production:: definition : start_inclusive_keyword error */ // default action (generated by JISON mode classic/merge :: 2,VT,VA,-,-,LT,LA,-,-): this.$ = yyvstack[yysp - 1]; this._$ = yyparser.yyMergeLocationInfo(yysp - 1, yysp); // END of default action (generated by JISON mode classic/merge :: 2,VT,VA,-,-,LT,LA,-,-) yyparser.yyError(rmCommonWS$1` ill defined '%s' inclusive lexer condition set specification. Erroneous code: ${yylexer.prettyPrintRange(yylstack[yysp], yylstack[yysp - 1])} Technical error report: ${yyvstack[yysp].errStr} `); break; case 14: /*! Production:: definition : start_exclusive_keyword option_list OPTIONS_END */ // default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 2, yysp); // END of default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-) var lst = yyvstack[yysp - 1]; for (var i = 0, len = lst.length; i < len; i++) { lst[i][1] = 1; // flag as 'exclusive' } this.$ = { type: 'names', names: lst // 'inclusive' conditions have value 0, 'exclusive' conditions have value 1 }; break; case 15: /*! Production:: definition : start_exclusive_keyword error */ // default action (generated by JISON mode classic/merge :: 2,VT,VA,-,-,LT,LA,-,-): this.$ = yyvstack[yysp - 1]; this._$ = yyparser.yyMergeLocationInfo(yysp - 1, yysp); // END of default action (generated by JISON mode classic/merge :: 2,VT,VA,-,-,LT,LA,-,-) yyparser.yyError(rmCommonWS$1` ill defined '%x' exclusive lexer condition set specification. Erroneous code: ${yylexer.prettyPrintRange(yylstack[yysp], yylstack[yysp - 1])} Technical error report: ${yyvstack[yysp].errStr} `); break; case 16: /*! Production:: definition : ACTION_START_AT_SOL action ACTION_END */ // default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 2, yysp); // END of default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-) var srcCode = trimActionCode$1(yyvstack[yysp - 1], yyvstack[yysp - 2]); if (srcCode) { var rv = checkActionBlock$1(srcCode, yylstack[yysp - 1]); if (rv) { yyparser.yyError(rmCommonWS$1` The '%{...%}' lexer setup action code section does not compile: ${rv} Erroneous area: ${yylexer.prettyPrintRange(yylstack[yysp - 1], yylstack[yysp - 2])} `); } yy.actionInclude.push(srcCode); } this.$ = null; break; case 17: /*! Production:: definition : UNTERMINATED_ACTION_BLOCK */ case 131: /*! Production:: epilogue_chunk : UNTERMINATED_ACTION_BLOCK */ // default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-): this._$ = yylstack[yysp]; // END of default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-) // The issue has already been reported by the lexer. No need to repeat // ourselves with another error report from here. this.$ = null; break; case 18: /*! Production:: definition : ACTION_START_AT_SOL error */ // default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 1, yysp); // END of default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-) var start_marker = yyvstack[yysp - 1].trim(); var marker_msg = (start_marker ? ' or similar, such as ' + start_marker : ''); yyparser.yyError(rmCommonWS$1` There's very probably a problem with this '%{...%}' lexer setup action code section. Erroneous area: ${yylexer.prettyPrintRange(yylstack[yysp - 1])} Technical error report: ${yyvstack[yysp].errStr} `); this.$ = null; break; case 19: /*! Production:: definition : ACTION_START include_macro_code ACTION_END */ // default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 2, yysp); // END of default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-) yy.actionInclude.push(yyvstack[yysp - 1]); this.$ = null; break; case 20: /*! Production:: definition : ACTION_START error */ // default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 1, yysp); // END of default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-) var start_marker = yyvstack[yysp - 1].trim(); var marker_msg = (start_marker ? ' or similar, such as ' + start_marker : ''); yyparser.yyError(rmCommonWS$1` The '%{...%}' lexer setup action code section MUST have its action block start marker (\`%{\`${marker_msg}) positioned at the start of a line to be accepted: *indented* action code blocks (such as this one) are always related to an immediately preceding lexer spec item, e.g. a lexer match rule expression (see 'lexer rules'). Erroneous area: ${yylexer.prettyPrintRange(yylstack[yysp - 1])} Technical error report: ${yyvstack[yysp].errStr} `); this.$ = null; break; case 21: /*! Production:: definition : ACTION_START DUMMY */ // default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 1, yysp); // END of default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-) var start_marker = yyvstack[yysp - 1].trim(); var marker_msg = (start_marker ? ' or similar, such as ' + start_marker : ''); yyparser.yyError(rmCommonWS$1` The '%{...%}' lexer setup action code section MUST have its action block start marker (\`%{\`${marker_msg}) positioned at the start of a line to be accepted: *indented* action code blocks (such as this one) are always related to an immediately preceding lexer spec item, e.g. a lexer match rule expression (see 'lexer rules'). Erroneous area: ${yylexer.prettyPrintRange(yylstack[yysp - 1])} `); this.$ = null; break; case 22: /*! Production:: definition : option_keyword option_list OPTIONS_END */ // default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 2, yysp); // END of default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-) var lst = yyvstack[yysp - 1]; for (var i = 0, len = lst.length; i < len; i++) { yy.options[lst[i][0]] = lst[i][1]; } this.$ = null; break; case 23: /*! Production:: definition : option_keyword error */ // default action (generated by JISON mode classic/merge :: 2,VT,VA,-,-,LT,LA,-,-): this.$ = yyvstack[yysp - 1]; this._$ = yyparser.yyMergeLocationInfo(yysp - 1, yysp); // END of default action (generated by JISON mode classic/merge :: 2,VT,VA,-,-,LT,LA,-,-) yyparser.yyError(rmCommonWS$1` ill defined %options line. Erroneous code: ${yylexer.prettyPrintRange(yylstack[yysp], yylstack[yysp - 1])} Technical error report: ${yyvstack[yysp].errStr} `); break; case 24: /*! Production:: definition : UNKNOWN_DECL */ // default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-): this._$ = yylstack[yysp]; // END of default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-) this.$ = { type: 'unknown', body: yyvstack[yysp] }; break; case 25: /*! Production:: definition : import_keyword option_list OPTIONS_END */ // default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 2, yysp); // END of default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-) // check if there are two unvalued options: 'name path' var lst = yyvstack[yysp - 1]; var len = lst.length; var body; if (len === 2 && lst[0][1] === true && lst[1][1] === true) { // `name path`: body = { name: lst[0][0], path: lst[1][0] }; } else if (len <= 2) { yyparser.yyError(rmCommonWS$1` You did not specify a legal qualifier name and/or file path for the '%import' statement, which must have the format: %import qualifier_name file_path Erroneous code: ${yylexer.prettyPrintRange(yylstack[yysp - 1], yylstack[yysp - 2])} `); } else { yyparser.yyError(rmCommonWS$1` You did specify too many attributes for the '%import' statement, which must have the format: %import qualifier_name file_path Erroneous code: ${yylexer.prettyPrintRange(yylstack[yysp - 1], yylstack[yysp - 2])} `); } this.$ = { type: 'imports', body: body }; break; case 26: /*! Production:: definition : import_keyword error */ // default action (generated by JISON mode classic/merge :: 2,VT,VA,-,-,LT,LA,-,-): this.$ = yyvstack[yysp - 1]; this._$ = yyparser.yyMergeLocationInfo(yysp - 1, yysp); // END of default action (generated by JISON mode classic/merge :: 2,VT,VA,-,-,LT,LA,-,-) yyparser.yyError(rmCommonWS$1` %import name or source filename missing maybe? Note: each '%import' must be qualified by a name, e.g. 'required' before the import path itself: %import qualifier_name file_path Erroneous code: ${yylexer.prettyPrintRange(yylstack[yysp], yylstack[yysp - 1])} Technical error report: ${yyvstack[yysp].errStr} `); break; case 27: /*! Production:: definition : init_code_keyword option_list ACTION_START action ACTION_END OPTIONS_END */ // default action (generated by JISON mode classic/merge :: 6,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 5, yysp); // END of default action (generated by JISON mode classic/merge :: 6,VT,VA,VU,-,LT,LA,-,-) // check there's only 1 option which is an identifier var lst = yyvstack[yysp - 4]; var len = lst.length; var name; if (len === 1 && lst[0][1] === true) { // `name`: name = lst[0][0]; } else if (len <= 1) { yyparser.yyError(rmCommonWS$1` You did not specify a legal qualifier name for the '%code' initialization code statement, which must have the format: %code qualifier_name %{...code...%} Erroneous code: ${yylexer.prettyPrintRange(yylstack[yysp - 4], yylstack[yysp - 5])} `); } else { yyparser.yyError(rmCommonWS$1` You did specify too many attributes for the '%code' initialization code statement, which must have the format: %code qualifier_name %{...code...%} Erroneous code: ${yylexer.prettyPrintRange(yylstack[yysp - 4], yylstack[yysp - 5])} `); } var srcCode = trimActionCode$1(yyvstack[yysp - 2], yyvstack[yysp - 3]); var rv = checkActionBlock$1(srcCode, yylstack[yysp - 2]); if (rv) { yyparser.yyError(rmCommonWS$1` The '%code ${name}' initialization code section does not compile: ${rv} Erroneous area: ${yylexer.prettyPrintRange(yylstack[yysp - 2], yylstack[yysp - 5])} `); } this.$ = { type: 'codeSection', body: { qualifier: name, include: srcCode } }; break; case 28: /*! Production:: definition : init_code_keyword option_list ACTION_START error */ // default action (generated by JISON mode classic/merge :: 4,VT,VA,-,-,LT,LA,-,-): this.$ = yyvstack[yysp - 3]; this._$ = yyparser.yyMergeLocationInfo(yysp - 3, yysp); // END of default action (generated by JISON mode classic/merge :: 4,VT,VA,-,-,LT,LA,-,-) break; case 29: /*! Production:: definition : init_code_keyword error */ // default action (generated by JISON mode classic/merge :: 2,VT,VA,-,-,LT,LA,-,-): this.$ = yyvstack[yysp - 1]; this._$ = yyparser.yyMergeLocationInfo(yysp - 1, yysp); // END of default action (generated by JISON mode classic/merge :: 2,VT,VA,-,-,LT,LA,-,-) yyparser.yyError(rmCommonWS$1` Each '%code' initialization code section must be qualified by a name, e.g. 'required' before the action code itself: %code qualifier_name {action code} Erroneous code: ${yylexer.prettyPrintRange(yylstack[yysp], yylstack[yysp - 1])} Technical error report: ${yyvstack[yysp].errStr} `); break; case 30: /*! Production:: definition : error */ // default action (generated by JISON mode classic/merge :: 1,VT,VA,-,-,LT,LA,-,-): this.$ = yyvstack[yysp]; this._$ = yylstack[yysp]; // END of default action (generated by JISON mode classic/merge :: 1,VT,VA,-,-,LT,LA,-,-) yyparser.yyError(rmCommonWS$1` illegal input in the lexer spec definitions section. This might be stuff incorrectly dangling off the previous '${yy.__options_category_description__}' definition statement, so please do check above when the mistake isn't immediately obvious from this error spot itself. Erroneous code: ${yylexer.prettyPrintRange(yylstack[yysp], yylstack[yysp - 2])} Technical error report: ${yyvstack[yysp].errStr} `); break; case 31: /*! Production:: option_keyword : OPTIONS */ // default action (generated by JISON mode classic/merge :: 1,VT,VA,-,-,LT,LA,-,-): this.$ = yyvstack[yysp]; this._$ = yylstack[yysp]; // END of default action (generated by JISON mode classic/merge :: 1,VT,VA,-,-,LT,LA,-,-) yy.__options_flags__ = OPTION_EXPECTS_ONLY_IDENTIFIER_NAMES; yy.__options_category_description__ = yyvstack[yysp]; break; case 32: /*! Production:: import_keyword : IMPORT */ case 34: /*! Production:: include_keyword : INCLUDE */ // default action (generated by JISON mode classic/merge :: 1,VT,VA,-,-,LT,LA,-,-): this.$ = yyvstack[yysp]; this._$ = yylstack[yysp]; // END of default action (generated by JISON mode classic/merge :: 1,VT,VA,-,-,LT,LA,-,-) yy.__options_flags__ = OPTION_DOES_NOT_ACCEPT_VALUE | OPTION_DOES_NOT_ACCEPT_COMMA_SEPARATED_OPTIONS; yy.__options_category_description__ = yyvstack[yysp]; break; case 33: /*! Production:: init_code_keyword : CODE */ // default action (generated by JISON mode classic/merge :: 1,VT,VA,-,-,LT,LA,-,-): this.$ = yyvstack[yysp]; this._$ = yylstack[yysp]; // END of default action (generated by JISON mode classic/merge :: 1,VT,VA,-,-,LT,LA,-,-) yy.__options_flags__ = OPTION_DOES_NOT_ACCEPT_VALUE | OPTION_DOES_NOT_ACCEPT_MULTIPLE_OPTIONS | OPTION_DOES_NOT_ACCEPT_COMMA_SEPARATED_OPTIONS; yy.__options_category_description__ = yyvstack[yysp]; break; case 35: /*! Production:: start_inclusive_keyword : START_INC */ // default action (generated by JISON mode classic/merge :: 1,VT,VA,-,-,LT,LA,-,-): this.$ = yyvstack[yysp]; this._$ = yylstack[yysp]; // END of default action (generated by JISON mode classic/merge :: 1,VT,VA,-,-,LT,LA,-,-) yy.__options_flags__ = OPTION_DOES_NOT_ACCEPT_VALUE | OPTION_EXPECTS_ONLY_IDENTIFIER_NAMES; yy.__options_category_description__ = 'the inclusive lexer start conditions set (%s)'; break; case 36: /*! Production:: start_exclusive_keyword : START_EXC */ // default action (generated by JISON mode classic/merge :: 1,VT,VA,-,-,LT,LA,-,-): this.$ = yyvstack[yysp]; this._$ = yylstack[yysp]; // END of default action (generated by JISON mode classic/merge :: 1,VT,VA,-,-,LT,LA,-,-) yy.__options_flags__ = OPTION_DOES_NOT_ACCEPT_VALUE | OPTION_EXPECTS_ONLY_IDENTIFIER_NAMES; yy.__options_category_description__ = 'the exclusive lexer start conditions set (%x)'; break; case 37: /*! Production:: start_conditions_marker : "<" */ // default action (generated by JISON mode classic/merge :: 1,VT,VA,-,-,LT,LA,-,-): this.$ = yyvstack[yysp]; this._$ = yylstack[yysp]; // END of default action (generated by JISON mode classic/merge :: 1,VT,VA,-,-,LT,LA,-,-) yy.__options_flags__ = OPTION_DOES_NOT_ACCEPT_VALUE | OPTION_EXPECTS_ONLY_IDENTIFIER_NAMES | OPTION_ALSO_ACCEPTS_STAR_AS_IDENTIFIER_NAME; yy.__options_category_description__ = 'the <...> delimited set of lexer start conditions'; break; case 38: /*! Production:: rules : rules scoped_rules_collective */ // default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 1, yysp); // END of default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-) this.$ = yyvstack[yysp - 1].concat(yyvstack[yysp]); break; case 39: /*! Production:: rules : rules rule */ // default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 1, yysp); // END of default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-) this.$ = yyvstack[yysp - 1].concat([yyvstack[yysp]]); break; case 40: /*! Production:: rules : rules ACTION_START_AT_SOL action ACTION_END */ // default action (generated by JISON mode classic/merge :: 4,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 3, yysp); // END of default action (generated by JISON mode classic/merge :: 4,VT,VA,VU,-,LT,LA,-,-) var srcCode = trimActionCode$1(yyvstack[yysp - 1], yyvstack[yysp - 2]); if (srcCode) { var rv = checkActionBlock$1(srcCode, yylstack[yysp - 1]); if (rv) { yyparser.yyError(rmCommonWS$1` The '%{...%}' lexer setup action code section does not compile: ${rv} Erroneous area: ${yylexer.prettyPrintRange(yylstack[yysp - 1], yylstack[yysp - 2])} `); } yy.actionInclude.push(srcCode); } this.$ = yyvstack[yysp - 3]; break; case 41: /*! Production:: rules : rules UNTERMINATED_ACTION_BLOCK */ // default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 1, yysp); // END of default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-) // The issue has already been reported by the lexer. No need to repeat // ourselves with another error report from here. this.$ = yyvstack[yysp - 1]; break; case 42: /*! Production:: rules : rules ACTION_START_AT_SOL error */ // default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 2, yysp); // END of default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-) var start_marker = yyvstack[yysp - 1].trim(); var marker_msg = (start_marker ? ' or similar, such as ' + start_marker : ''); yyparser.yyError(rmCommonWS$1` There's very probably a problem with this '%{...%}' lexer setup action code section. Erroneous area: ${yylexer.prettyPrintRange(yylstack[yysp - 1])} Technical error report: ${yyvstack[yysp].errStr} `); this.$ = yyvstack[yysp - 2]; break; case 43: /*! Production:: rules : rules ACTION_START include_macro_code ACTION_END */ // default action (generated by JISON mode classic/merge :: 4,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 3, yysp); // END of default action (generated by JISON mode classic/merge :: 4,VT,VA,VU,-,LT,LA,-,-) yy.actionInclude.push(yyvstack[yysp - 1]); this.$ = yyvstack[yysp - 3]; break; case 44: /*! Production:: rules : rules ACTION_START error */ // default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 2, yysp); // END of default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-) var start_marker = yyvstack[yysp - 1].trim(); // When the start_marker is not an explicit `%{`, `{` or similar, the error // is more probably due to indenting the rule regex, rather than an error // in writing the action code block: console.error("*** error! marker:", start_marker); if (start_marker.indexOf('{') >= 0) { var marker_msg = (start_marker ? ' or similar, such as ' + start_marker : ''); yyparser.yyError(rmCommonWS$1` The '%{...%}' lexer setup action code section MUST have its action block start marker (\`%{\`${marker_msg}) positioned at the start of a line to be accepted: *indented* action code blocks (such as this one) are always related to an immediately preceding lexer spec item, e.g. a lexer match rule expression (see 'lexer rules'). Erroneous area: ${yylexer.prettyPrintRange(yylstack[yysp - 1])} Technical error report: ${yyvstack[yysp].errStr} `); } else { yyparser.yyError(rmCommonWS$1` There's probably an error in one or more of your lexer regex rules. Did you perhaps indent the rule regex? Note that all rule regexes MUST start at the start of the line, i.e. text column 1. Indented text is perceived as JavaScript action code related to the last lexer rule regex. Erroneous code: ${yylexer.prettyPrintRange(yylstack[yysp])} Technical error report: ${yyvstack[yysp].errStr} `); } this.$ = yyvstack[yysp - 2]; break; case 45: /*! Production:: rules : rules start_inclusive_keyword */ case 46: /*! Production:: rules : rules start_exclusive_keyword */ case 47: /*! Production:: rules : rules option_keyword */ case 48: /*! Production:: rules : rules UNKNOWN_DECL */ case 49: /*! Production:: rules : rules import_keyword */ case 50: /*! Production:: rules : rules init_code_keyword */ // default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 1, yysp); // END of default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-) yyparser.yyError(rmCommonWS$1` \`${yy.__options_category_description__}\` statements must be placed in the top section of the lexer spec file, above the first '%%' separator. You cannot specify any in the second section as has been done here. Erroneous code: ${yylexer.prettyPrintRange(yylstack[yysp])} `); this.$ = yyvstack[yysp - 1]; break; case 51: /*! Production:: rules : %epsilon */ case 58: /*! Production:: rule_block : %epsilon */ // default action (generated by JISON mode classic/merge :: 0,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(null, null, null, null, true); // END of default action (generated by JISON mode classic/merge :: 0,VT,VA,VU,-,LT,LA,-,-) this.$ = []; break; case 52: /*! Production:: scoped_rules_collective : start_conditions rule */ // default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 1, yysp); // END of default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-) if (yyvstack[yysp - 1]) { yyvstack[yysp].unshift(yyvstack[yysp - 1]); } this.$ = [yyvstack[yysp]]; break; case 53: /*! Production:: scoped_rules_collective : start_conditions "{" rule_block "}" */ // default action (generated by JISON mode classic/merge :: 4,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 3, yysp); // END of default action (generated by JISON mode classic/merge :: 4,VT,VA,VU,-,LT,LA,-,-) if (yyvstack[yysp - 3]) { yyvstack[yysp - 1].forEach(function (d) { d.unshift(yyvstack[yysp - 3]); }); } this.$ = yyvstack[yysp - 1]; break; case 54: /*! Production:: scoped_rules_collective : start_conditions "{" error "}" */ // default action (generated by JISON mode classic/merge :: 4,VT,VA,-,-,LT,LA,-,-): this.$ = yyvstack[yysp - 3]; this._$ = yyparser.yyMergeLocationInfo(yysp - 3, yysp); // END of default action (generated by JISON mode classic/merge :: 4,VT,VA,-,-,LT,LA,-,-) yyparser.yyError(rmCommonWS$1` Seems you made a mistake while specifying one of the lexer rules inside the start condition <${yyvstack[yysp - 3].join(',')}> { rules... } block. Erroneous area: ${yylexer.prettyPrintRange(yyparser.mergeLocationInfo((yysp - 3), (yysp)), yylstack[yysp - 3])} Technical error report: ${yyvstack[yysp - 1].errStr} `); break; case 55: /*! Production:: scoped_rules_collective : start_conditions "{" error */ // default action (generated by JISON mode classic/merge :: 3,VT,VA,-,-,LT,LA,-,-): this.$ = yyvstack[yysp - 2]; this._$ = yyparser.yyMergeLocationInfo(yysp - 2, yysp); // END of default action (generated by JISON mode classic/merge :: 3,VT,VA,-,-,LT,LA,-,-) yyparser.yyError(rmCommonWS$1` Seems you did not correctly bracket a lexer rules set inside the start condition <${yyvstack[yysp - 2].join(',')}> { rules... } as a terminating curly brace '}' could not be found. Erroneous area: ${yylexer.prettyPrintRange(yylstack[yysp], yylstack[yysp - 2])} Technical error report: ${yyvstack[yysp].errStr} `); break; case 56: /*! Production:: scoped_rules_collective : start_conditions error "}" */ // default action (generated by JISON mode classic/merge :: 3,VT,VA,-,-,LT,LA,-,-): this.$ = yyvstack[yysp - 2]; this._$ = yyparser.yyMergeLocationInfo(yysp - 2, yysp); // END of default action (generated by JISON mode classic/merge :: 3,VT,VA,-,-,LT,LA,-,-) yyparser.yyError(rmCommonWS$1` Seems you did not correctly bracket a lexer rules set inside the start condition <${yyvstack[yysp - 2].join(',')}> { rules... } as a terminating curly brace '}' could not be found. Erroneous area: ${yylexer.prettyPrintRange(yylstack[yysp - 1], yylstack[yysp - 2])} Technical error report: ${yyvstack[yysp - 1].errStr} `); break; case 57: /*! Production:: rule_block : rule_block rule */ // default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 1, yysp); // END of default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-) this.$ = yyvstack[yysp - 1]; this.$.push(yyvstack[yysp]); break; case 59: /*! Production:: rule : regex ACTION_START action ACTION_END */ // default action (generated by JISON mode classic/merge :: 4,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 3, yysp); // END of default action (generated by JISON mode classic/merge :: 4,VT,VA,VU,-,LT,LA,-,-) var srcCode = trimActionCode$1(yyvstack[yysp - 1], yyvstack[yysp - 2]); var rv = checkActionBlock$1(srcCode, yylstack[yysp - 1]); if (rv) { yyparser.yyError(rmCommonWS$1` The lexer rule's action code section does not compile: ${rv} Erroneous area: ${yylexer.prettyPrintRange(yylstack[yysp - 1], yylstack[yysp - 3])} `); } this.$ = [yyvstack[yysp - 3], srcCode]; break; case 60: /*! Production:: rule : regex ARROW_ACTION_START action ACTION_END */ // default action (generated by JISON mode classic/merge :: 4,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 3, yysp); // END of default action (generated by JISON mode classic/merge :: 4,VT,VA,VU,-,LT,LA,-,-) var srcCode = trimActionCode$1(yyvstack[yysp - 1]); // add braces around ARROW_ACTION_CODE so that the action chunk test/compiler // will uncover any illegal action code following the arrow operator, e.g. // multiple statements separated by semicolon. // // Note/Optimization: // there's no need for braces in the generated expression when we can // already see the given action is an identifier string or something else // that's a sure simple thing for a JavaScript `return` statement to carry. // By doing this, we simplify the token return replacement code replacement // process which will be applied to the parsed lexer before its code // will be generated by JISON. if (/^[^\r\n;\/]+$/.test(srcCode)) { srcCode = 'return ' + srcCode; } else { srcCode = 'return (' + srcCode + '\n)'; } var rv = checkActionBlock$1(srcCode, yylstack[yysp - 1]); if (rv) { yyparser.yyError(rmCommonWS$1` The lexer rule's 'arrow' action code section does not compile: ${rv} # NOTE that the arrow action automatically wraps the action code # in a \`return (...);\` statement to prevent hard-to-diagnose run-time # errors down the line. Erroneous area: ${yylexer.prettyPrintRange(yylstack[yysp - 1], yylstack[yysp - 3])} `); } this.$ = [yyvstack[yysp - 3], srcCode]; break; case 61: /*! Production:: rule : regex ARROW_ACTION_START error */ // default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 2, yysp); // END of default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-) this.$ = [yyvstack[yysp - 2], yyvstack[yysp]]; yyparser.yyError(rmCommonWS$1` A lexer rule action arrow must be followed by a JavaScript expression specifying the lexer token to produce, e.g.: /rule/ -> 'BUGGABOO' // eqv. to \`return 'BUGGABOO';\` Erroneous area: ${yylexer.prettyPrintRange(yylstack[yysp], yylstack[yysp - 2])} Technical error report: ${yyvstack[yysp].errStr} `); break; case 62: /*! Production:: rule : regex ACTION_START error */ // default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 2, yysp); // END of default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-) // TODO: REWRITE this.$ = [yyvstack[yysp - 2], yyvstack[yysp]]; yyparser.yyError(rmCommonWS$1` A lexer rule regex action code must be properly terminated and must contain a JavaScript statement block (or anything that does parse as such), e.g.: /rule/ %{ invokeHooHaw(); return 'TOKEN'; %} NOTE: when you have very simple action code, wrapping it in '%{...}%' or equivalent is not required as long as you keep the code indented, e.g.: /rule/ invokeHooHaw(); return 'TOKEN'; Erroneous area: ${yylexer.prettyPrintRange(yylstack[yysp], yylstack[yysp - 2])} Technical error report: ${yyvstack[yysp].errStr} `); break; case 63: /*! Production:: rule : regex error */ // default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 1, yysp); // END of default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-) this.$ = [yyvstack[yysp - 1], yyvstack[yysp]]; yyparser.yyError(rmCommonWS$1` Lexer rule regex action code declaration error? Erroneous code: ${yylexer.prettyPrintRange(yylstack[yysp], yylstack[yysp - 1])} Technical error report: ${yyvstack[yysp].errStr} `); break; case 64: /*! Production:: action : action ACTION_BODY */ case 81: /*! Production:: regex_concat : regex_concat regex_base */ case 93: /*! Production:: regex_base : regex_base range_regex */ case 104: /*! Production:: regex_set : regex_set regex_set_atom */ case 125: /*! Production:: epilogue_chunks : epilogue_chunks epilogue_chunk */ // default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 1, yysp); // END of default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-) this.$ = yyvstack[yysp - 1] + yyvstack[yysp]; break; case 65: /*! Production:: action : action include_macro_code */ // default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 1, yysp); // END of default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-) this.$ = yyvstack[yysp - 1] + '\n\n' + yyvstack[yysp] + '\n\n'; break; case 66: /*! Production:: action : action INCLUDE_PLACEMENT_ERROR */ // default action (generated by JISON mode classic/merge :: 2,VT,VA,-,-,LT,LA,-,-): this.$ = yyvstack[yysp - 1]; this._$ = yyparser.yyMergeLocationInfo(yysp - 1, yysp); // END of default action (generated by JISON mode classic/merge :: 2,VT,VA,-,-,LT,LA,-,-) yyparser.yyError(rmCommonWS$1` You may place the '%include' instruction only at the start/front of a line. Its use is not permitted at this position: ${yylexer.prettyPrintRange(yylstack[yysp], yylstack[yysp - 3])} `); break; case 67: /*! Production:: action : action BRACKET_MISSING */ // default action (generated by JISON mode classic/merge :: 2,VT,VA,-,-,LT,LA,-,-): this.$ = yyvstack[yysp - 1]; this._$ = yyparser.yyMergeLocationInfo(yysp - 1, yysp); // END of default action (generated by JISON mode classic/merge :: 2,VT,VA,-,-,LT,LA,-,-) yyparser.yyError(rmCommonWS$1` Missing curly braces: seems you did not correctly bracket a lexer rule action block in curly braces: '{ ... }'. Offending action body: ${yylexer.prettyPrintRange(yylstack[yysp], yylstack[yysp - 3])} `); break; case 68: /*! Production:: action : action BRACKET_SURPLUS */ // default action (generated by JISON mode classic/merge :: 2,VT,VA,-,-,LT,LA,-,-): this.$ = yyvstack[yysp - 1]; this._$ = yyparser.yyMergeLocationInfo(yysp - 1, yysp); // END of default action (generated by JISON mode classic/merge :: 2,VT,VA,-,-,LT,LA,-,-) yyparser.yyError(rmCommonWS$1` Too many curly braces: seems you did not correctly bracket a lexer rule action block in curly braces: '{ ... }'. Offending action body: ${yylexer.prettyPrintRange(yylstack[yysp], yylstack[yysp - 3])} `); break; case 69: /*! Production:: action : action UNTERMINATED_STRING_ERROR */ // default action (generated by JISON mode classic/merge :: 2,VT,VA,-,-,LT,LA,-,-): this.$ = yyvstack[yysp - 1]; this._$ = yyparser.yyMergeLocationInfo(yysp - 1, yysp); // END of default action (generated by JISON mode classic/merge :: 2,VT,VA,-,-,LT,LA,-,-) yyparser.yyError(rmCommonWS$1` Unterminated string constant in lexer rule action block. When your action code is as intended, it may help to enclose your rule action block code in a '%{...%}' block. Offending action body: ${yylexer.prettyPrintRange(yylstack[yysp], yylstack[yysp - 3])} `); break; case 70: /*! Production:: action : %epsilon */ case 75: /*! Production:: regex_list : %epsilon */ // default action (generated by JISON mode classic/merge :: 0,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(null, null, null, null, true); // END of default action (generated by JISON mode classic/merge :: 0,VT,VA,VU,-,LT,LA,-,-) this.$ = ''; break; case 71: /*! Production:: start_conditions : start_conditions_marker option_list OPTIONS_END ">" */ // default action (generated by JISON mode classic/merge :: 4,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 3, yysp); // END of default action (generated by JISON mode classic/merge :: 4,VT,VA,VU,-,LT,LA,-,-) // rewrite + accept star '*' as name + check if we allow empty list? this.$ = yyvstack[yysp - 2].map(function (el) { var name = el[0]; // Validate the given condition state: when it isn't known, print an error message // accordingly: if (name !== '*' && name !== 'INITIAL' && !(name in yy.startConditions)) { yyparser.yyError(rmCommonWS$1` You specified an unknown lexer condition state '${name}'. Is this a typo or did you forget to include this one in the '%s' and '%x' inclusive and exclusive condition state sets specifications at the top of the lexer spec? As a rough example, things should look something like this in your lexer spec file: %s ${name} %% <${name}>LEXER_RULE_REGEX return 'TOK'; Erroneous code: ${yylexer.prettyPrintRange(yylstack[yysp - 2], yylstack[yysp - 3], yylstack[yysp])} `); } return name; }); // '<' '*' '>' // { $$ = ['*']; } break; case 72: /*! Production:: start_conditions : start_conditions_marker option_list error */ // default action (generated by JISON mode classic/merge :: 3,VT,VA,-,-,LT,LA,-,-): this.$ = yyvstack[yysp - 2]; this._$ = yyparser.yyMergeLocationInfo(yysp - 2, yysp); // END of default action (generated by JISON mode classic/merge :: 3,VT,VA,-,-,LT,LA,-,-) // rewrite + accept star '*' as name + check if we allow empty list? var lst = yyvstack[yysp - 1].map(function (el) { return el[0]; }); yyparser.yyError(rmCommonWS$1` Seems you did not correctly terminate the start condition set <${lst.join(',')},???> with a terminating '>' Erroneous code: ${yylexer.prettyPrintRange(yylstack[yysp], yylstack[yysp - 2])} Technical error report: ${yyvstack[yysp].errStr} `); break; case 73: /*! Production:: regex : nonempty_regex_list */ // default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-): this._$ = yylstack[yysp]; // END of default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-) // Detect if the regex ends with a pure (Unicode) word; // we *do* consider escaped characters which are 'alphanumeric' // to be equivalent to their non-escaped version, hence these are // all valid 'words' for the 'easy keyword rules' option: // // - hello_kitty // - γεια_σου_γατούλα // - \u03B3\u03B5\u03B9\u03B1_\u03C3\u03BF\u03C5_\u03B3\u03B1\u03C4\u03BF\u03CD\u03BB\u03B1 // // http://stackoverflow.com/questions/7885096/how-do-i-decode-a-string-with-escaped-unicode#12869914 // // As we only check the *tail*, we also accept these as // 'easy keywords': // // - %options // - %foo-bar // - +++a:b:c1 // // Note the dash in that last example: there the code will consider // `bar` to be the keyword, which is fine with us as we're only // interested in the trailing boundary and patching that one for // the `easy_keyword_rules` option. this.$ = yyvstack[yysp]; if (yy.options.easy_keyword_rules) { // We need to 'protect' `eval` here as keywords are allowed // to contain double-quotes and other leading cruft. // `eval` *does* gobble some escapes (such as `\b`) but // we protect against that through a simple replace regex: // we're not interested in the special escapes' exact value // anyway. // It will also catch escaped escapes (`\\`), which are not // word characters either, so no need to worry about // `eval(str)` 'correctly' converting convoluted constructs // like '\\\\\\\\\\b' in here. this.$ = this.$ .replace(/\\\\/g, '.') .replace(/"/g, '.') .replace(/\\c[A-Z]/g, '.') .replace(/\\[^xu0-7]/g, '.'); try { // Convert Unicode escapes and other escapes to their literal characters // BEFORE we go and check whether this item is subject to the // `easy_keyword_rules` option. this.$ = JSON.parse('"' + this.$ + '"'); } catch (ex) { yyparser.warn('easy-keyword-rule FAIL on eval: ', ex); // make the next keyword test fail: this.$ = '.'; } // a 'keyword' starts with an alphanumeric character, // followed by zero or more alphanumerics or digits: var re = new XRegExp('\\w[\\w\\d]*$'); if (XRegExp.match(this.$, re)) { this.$ = yyvstack[yysp] + "\\b"; } else { this.$ = yyvstack[yysp]; } } break; case 74: /*! Production:: regex_list : nonempty_regex_list */ case 80: /*! Production:: nonempty_regex_list : regex_concat */ case 82: /*! Production:: regex_concat : regex_base */ case 101: /*! Production:: name_expansion : NAME_BRACE */ case 108: /*! Production:: range_regex : RANGE_REGEX */ case 127: /*! Production:: epilogue_chunks : epilogue_chunk */ // default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-): this._$ = yylstack[yysp]; // END of default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-) this.$ = yyvstack[yysp]; break; case 76: /*! Production:: nonempty_regex_list : nonempty_regex_list "|" regex_concat */ // default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 2, yysp); // END of default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-) this.$ = yyvstack[yysp - 2] + '|' + yyvstack[yysp]; break; case 77: /*! Production:: nonempty_regex_list : nonempty_regex_list "|" */ // default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 1, yysp); // END of default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-) this.$ = yyvstack[yysp - 1] + '|'; break; case 78: /*! Production:: nonempty_regex_list : "|" regex_concat */ // default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 1, yysp); // END of default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-) this.$ = '|' + yyvstack[yysp]; break; case 79: /*! Production:: nonempty_regex_list : "|" */ // default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-): this._$ = yylstack[yysp]; // END of default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-) this.$ = '|'; break; case 83: /*! Production:: regex_base : "(" regex_list ")" */ // default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 2, yysp); // END of default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-) this.$ = '(' + yyvstack[yysp - 1] + ')'; break; case 84: /*! Production:: regex_base : SPECIAL_GROUP regex_list ")" */ // default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 2, yysp); // END of default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-) this.$ = yyvstack[yysp - 2] + yyvstack[yysp - 1] + ')'; break; case 85: /*! Production:: regex_base : "(" regex_list error */ case 86: /*! Production:: regex_base : SPECIAL_GROUP regex_list error */ // default action (generated by JISON mode classic/merge :: 3,VT,VA,-,-,LT,LA,-,-): this.$ = yyvstack[yysp - 2]; this._$ = yyparser.yyMergeLocationInfo(yysp - 2, yysp); // END of default action (generated by JISON mode classic/merge :: 3,VT,VA,-,-,LT,LA,-,-) yyparser.yyError(rmCommonWS$1` Seems you did not correctly bracket a lex rule regex part in '(...)' braces. Unterminated regex part: ${yylexer.prettyPrintRange(yylstack[yysp], yylstack[yysp - 2])} Technical error report: ${yyvstack[yysp].errStr} `); break; case 87: /*! Production:: regex_base : regex_base "+" */ // default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 1, yysp); // END of default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-) this.$ = yyvstack[yysp - 1] + '+'; break; case 88: /*! Production:: regex_base : regex_base "*" */ // default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 1, yysp); // END of default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-) this.$ = yyvstack[yysp - 1] + '*'; break; case 89: /*! Production:: regex_base : regex_base "?" */ // default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 1, yysp); // END of default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-) this.$ = yyvstack[yysp - 1] + '?'; break; case 90: /*! Production:: regex_base : "/" regex_base */ // default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 1, yysp); // END of default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-) this.$ = '(?=' + yyvstack[yysp] + ')'; break; case 91: /*! Production:: regex_base : "/!" regex_base */ // default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 1, yysp); // END of default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-) this.$ = '(?!' + yyvstack[yysp] + ')'; break; case 92: /*! Production:: regex_base : name_expansion */ case 94: /*! Production:: regex_base : any_group_regex */ case 98: /*! Production:: regex_base : REGEX_SPECIAL_CHAR */ case 99: /*! Production:: regex_base : literal_string */ case 105: /*! Production:: regex_set : regex_set_atom */ case 106: /*! Production:: regex_set_atom : REGEX_SET */ // default action (generated by JISON mode classic/merge :: 1,VT,VA,-,-,LT,LA,-,-): this.$ = yyvstack[yysp]; this._$ = yylstack[yysp]; // END of default action (generated by JISON mode classic/merge :: 1,VT,VA,-,-,LT,LA,-,-) break; case 95: /*! Production:: regex_base : "." */ // default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-): this._$ = yylstack[yysp]; // END of default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-) this.$ = '.'; break; case 96: /*! Production:: regex_base : "^" */ // default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-): this._$ = yylstack[yysp]; // END of default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-) this.$ = '^'; break; case 97: /*! Production:: regex_base : "$" */ // default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-): this._$ = yylstack[yysp]; // END of default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-) this.$ = '$'; break; case 100: /*! Production:: regex_base : ESCAPED_CHAR */ // default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-): this._$ = yylstack[yysp]; // END of default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-) this.$ = encodeRegexLiteralStr(encodeUnicodeCodepoint(yyvstack[yysp])); break; case 102: /*! Production:: any_group_regex : REGEX_SET_START regex_set REGEX_SET_END */ // default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 2, yysp); // END of default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-) this.$ = yyvstack[yysp - 2] + yyvstack[yysp - 1] + yyvstack[yysp]; break; case 103: /*! Production:: any_group_regex : REGEX_SET_START regex_set error */ // default action (generated by JISON mode classic/merge :: 3,VT,VA,-,-,LT,LA,-,-): this.$ = yyvstack[yysp - 2]; this._$ = yyparser.yyMergeLocationInfo(yysp - 2, yysp); // END of default action (generated by JISON mode classic/merge :: 3,VT,VA,-,-,LT,LA,-,-) yyparser.yyError(rmCommonWS$1` Seems you did not correctly bracket a lex rule regex set in '[...]' brackets. Unterminated regex set: ${yylexer.prettyPrintRange(yylstack[yysp], yylstack[yysp - 2])} Technical error report: ${yyvstack[yysp].errStr} `); break; case 107: /*! Production:: regex_set_atom : name_expansion */ // default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-): this._$ = yylstack[yysp]; // END of default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-) if (XRegExp._getUnicodeProperty(yyvstack[yysp].replace(/[{}]/g, '')) && yyvstack[yysp].toUpperCase() !== yyvstack[yysp] ) { // treat this as part of an XRegExp `\p{...}` Unicode 'General Category' Property cf. http://unicode.org/reports/tr18/#Categories this.$ = yyvstack[yysp]; } else { this.$ = yyvstack[yysp]; } //yyparser.log("name expansion for: ", { name: $name_expansion, redux: $name_expansion.replace(/[{}]/g, ''), output: $$ }); break; case 109: /*! Production:: literal_string : STRING_LIT */ // default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-): this._$ = yylstack[yysp]; // END of default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-) var src = yyvstack[yysp]; var s = src.substring(1, src.length - 1); var edge = src[0]; this.$ = encodeRegexLiteralStr(s, edge); break; case 110: /*! Production:: literal_string : CHARACTER_LIT */ // default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-): this._$ = yylstack[yysp]; // END of default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-) var s = yyvstack[yysp]; this.$ = encodeRegexLiteralStr(s); break; case 111: /*! Production:: option_list : option_list "," option */ // default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 2, yysp); // END of default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-) // validate that this is legal behaviour under the given circumstances, i.e. parser context: if (yy.__options_flags__ & OPTION_DOES_NOT_ACCEPT_MULTIPLE_OPTIONS) { yyparser.yyError(rmCommonWS$1` You may only specify one name/argument in a ${yy.__options_category_description__} statement. Erroneous area: ${yylexer.prettyPrintRange(yylexer.deriveLocationInfo(yylstack[yysp - 1], yylstack[yysp]), yylstack[yysp - 4])} `); } if (yy.__options_flags__ & OPTION_DOES_NOT_ACCEPT_COMMA_SEPARATED_OPTIONS) { var optlist = yyvstack[yysp - 2].map(function (opt) { return opt[0]; }); optlist.push(yyvstack[yysp][0]); yyparser.yyError(rmCommonWS$1` You may not separate entries in a ${yy.__options_category_description__} statement using commas. Use whitespace instead, e.g.: ${yyvstack[yysp - 4]} ${optlist.join(' ')} ... Erroneous area: ${yylexer.prettyPrintRange(yylexer.deriveLocationInfo(yylstack[yysp - 1], yylstack[yysp - 2]), yylstack[yysp - 4])} `); } this.$ = yyvstack[yysp - 2]; this.$.push(yyvstack[yysp]); break; case 112: /*! Production:: option_list : option_list option */ // default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 1, yysp); // END of default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-) // validate that this is legal behaviour under the given circumstances, i.e. parser context: if (yy.__options_flags__ & OPTION_DOES_NOT_ACCEPT_MULTIPLE_OPTIONS) { yyparser.yyError(rmCommonWS$1` You may only specify one name/argument in a ${yy.__options_category_description__} statement. Erroneous area: ${yylexer.prettyPrintRange(yylexer.deriveLocationInfo(yylstack[yysp]), yylstack[yysp - 3])} `); } this.$ = yyvstack[yysp - 1]; this.$.push(yyvstack[yysp]); break; case 113: /*! Production:: option_list : option */ // default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-): this._$ = yylstack[yysp]; // END of default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-) this.$ = [yyvstack[yysp]]; break; case 114: /*! Production:: option : option_name */ // default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-): this._$ = yylstack[yysp]; // END of default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-) this.$ = [yyvstack[yysp], true]; break; case 115: /*! Production:: option : option_name "=" option_value */ // default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 2, yysp); // END of default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-) // validate that this is legal behaviour under the given circumstances, i.e. parser context: if (yy.__options_flags__ & OPTION_DOES_NOT_ACCEPT_VALUE) { yyparser.yyError(rmCommonWS$1` The entries in a ${yy.__options_category_description__} statement MUST NOT be assigned values, such as '${$option_name}=${$option_value}'. Erroneous area: ${yylexer.prettyPrintRange(yylexer.deriveLocationInfo(yylstack[yysp], yylstack[yysp - 2]), yylstack[yysp - 4])} `); } this.$ = [yyvstack[yysp - 2], yyvstack[yysp]]; break; case 116: /*! Production:: option : option_name "=" error */ // default action (generated by JISON mode classic/merge :: 3,VT,VA,-,-,LT,LA,-,-): this.$ = yyvstack[yysp - 2]; this._$ = yyparser.yyMergeLocationInfo(yysp - 2, yysp); // END of default action (generated by JISON mode classic/merge :: 3,VT,VA,-,-,LT,LA,-,-) // TODO ... yyparser.yyError(rmCommonWS$1` Internal error: option "${$option}" value assignment failure in a ${yy.__options_category_description__} statement. Erroneous area: ${yylexer.prettyPrintRange(yylstack[yysp], yylstack[yysp - 4])} Technical error report: ${yyvstack[yysp].errStr} `); break; case 117: /*! Production:: option : DUMMY3 error */ // default action (generated by JISON mode classic/merge :: 2,VT,VA,-,-,LT,LA,-,-): this.$ = yyvstack[yysp - 1]; this._$ = yyparser.yyMergeLocationInfo(yysp - 1, yysp); // END of default action (generated by JISON mode classic/merge :: 2,VT,VA,-,-,LT,LA,-,-) var with_value_msg = ' (with optional value assignment)'; if (yy.__options_flags__ & OPTION_DOES_NOT_ACCEPT_VALUE) { with_value_msg = ''; } yyparser.yyError(rmCommonWS$1` Expected a valid option name${with_value_msg} in a ${yy.__options_category_description__} statement. Erroneous area: ${yylexer.prettyPrintRange(yylstack[yysp], yylstack[yysp - 3])} Technical error report: ${yyvstack[yysp].errStr} `); break; case 118: /*! Production:: option_name : option_value */ // default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-): this._$ = yylstack[yysp]; // END of default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-) // validate that this is legal input under the given circumstances, i.e. parser context: if (yy.__options_flags__ & OPTION_EXPECTS_ONLY_IDENTIFIER_NAMES) { this.$ = mkIdentifier$1(yyvstack[yysp]); // check if the transformation is obvious & trivial to humans; // if not, report an error as we don't want confusion due to // typos and/or garbage input here producing something that // is usable from a machine perspective. if (!isLegalIdentifierInput$1(yyvstack[yysp])) { var with_value_msg = ' (with optional value assignment)'; if (yy.__options_flags__ & OPTION_DOES_NOT_ACCEPT_VALUE) { with_value_msg = ''; } yyparser.yyError(rmCommonWS$1` Expected a valid name/argument${with_value_msg} in a ${yy.__options_category_description__} statement. Entries (names) must look like regular programming language identifiers, with the addition that option names MAY contain '-' dashes, e.g. 'example-option-1'. Erroneous area: ${yylexer.prettyPrintRange(yylstack[yysp], yylstack[yysp - 2])} `); } } else { this.$ = yyvstack[yysp]; } break; case 119: /*! Production:: option_name : "*" */ // default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-): this._$ = yylstack[yysp]; // END of default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-) // validate that this is legal input under the given circumstances, i.e. parser context: if (!(yy.__options_flags__ & OPTION_EXPECTS_ONLY_IDENTIFIER_NAMES) || (yy.__options_flags__ & OPTION_ALSO_ACCEPTS_STAR_AS_IDENTIFIER_NAME)) { this.$ = yyvstack[yysp]; } else { var with_value_msg = ' (with optional value assignment)'; if (yy.__options_flags__ & OPTION_DOES_NOT_ACCEPT_VALUE) { with_value_msg = ''; } yyparser.yyError(rmCommonWS$1` Expected a valid name/argument${with_value_msg} in a ${yy.__options_category_description__} statement. Entries (names) must look like regular programming language identifiers, with the addition that option names MAY contain '-' dashes, e.g. 'example-option-1' Erroneous area: ${yylexer.prettyPrintRange(yylstack[yysp], yylstack[yysp - 2])} `); } break; case 120: /*! Production:: option_value : OPTION_STRING */ // default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-): this._$ = yylstack[yysp]; // END of default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-) this.$ = JSON5.parse(yyvstack[yysp]); break; case 121: /*! Production:: option_value : OPTION_VALUE */ // default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-): this._$ = yylstack[yysp]; // END of default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-) this.$ = parseValue(yyvstack[yysp]); break; case 122: /*! Production:: epilogue : "%%" */ // default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-): this._$ = yylstack[yysp]; // END of default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-) this.$ = ''; break; case 123: /*! Production:: epilogue : "%%" epilogue_chunks */ // default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 1, yysp); // END of default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-) var srcCode = trimActionCode$1(yyvstack[yysp]); if (srcCode) { var rv = checkActionBlock$1(srcCode, yylstack[yysp]); if (rv) { yyparser.yyError(rmCommonWS$1` The '%%' lexer epilogue code does not compile: ${rv} Erroneous area: ${yylexer.prettyPrintRange(yylstack[yysp], yylstack[yysp - 1])} `); } } this.$ = srcCode; break; case 124: /*! Production:: epilogue : "%%" error */ // default action (generated by JISON mode classic/merge :: 2,VT,VA,-,-,LT,LA,-,-): this.$ = yyvstack[yysp - 1]; this._$ = yyparser.yyMergeLocationInfo(yysp - 1, yysp); // END of default action (generated by JISON mode classic/merge :: 2,VT,VA,-,-,LT,LA,-,-) yyparser.yyError(rmCommonWS$1` There's an error in your lexer epilogue code block. Erroneous code: ${yylexer.prettyPrintRange(yylstack[yysp], yylstack[yysp - 1])} Technical error report: ${yyvstack[yysp].errStr} `); break; case 126: /*! Production:: epilogue_chunks : epilogue_chunks error */ // default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 1, yysp); // END of default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-) // TODO ... yyparser.yyError(rmCommonWS$1` Module code declaration error? Erroneous code: ${yylexer.prettyPrintRange(yylstack[yysp])} Technical error report: ${yyvstack[yysp].errStr} `); this.$ = ''; break; case 128: /*! Production:: epilogue_chunk : ACTION_START include_macro_code ACTION_END */ // default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 2, yysp); // END of default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-) this.$ = '\n\n' + yyvstack[yysp - 1] + '\n\n'; break; case 129: /*! Production:: epilogue_chunk : ACTION_START_AT_SOL action ACTION_END */ // default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 2, yysp); // END of default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,-,-) var srcCode = trimActionCode$1(yyvstack[yysp - 1], yyvstack[yysp - 2]); if (srcCode) { var rv = checkActionBlock$1(srcCode, yylstack[yysp - 1]); if (rv) { yyparser.yyError(rmCommonWS$1` The '%{...%}' lexer epilogue code chunk does not compile: ${rv} Erroneous area: ${yylexer.prettyPrintRange(yylstack[yysp - 1], yylstack[yysp - 2])} `); } } // Since the epilogue is concatenated as-is (see the `epilogue_chunks` rule above) // we append those protective double newlines right now, as the calling site // won't do it for us: this.$ = '\n\n' + srcCode + '\n\n'; break; case 130: /*! Production:: epilogue_chunk : ACTION_START_AT_SOL error */ // default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-): this._$ = yyparser.yyMergeLocationInfo(yysp - 1, yysp); // END of default action (generated by JISON mode classic/merge :: 2,VT,VA,VU,-,LT,LA,-,-) var start_marker = yyvstack[yysp - 1].trim(); var marker_msg = (start_marker ? ' or similar, such as ' + start_marker : ''); yyparser.yyError(rmCommonWS$1` There's very probably a problem with this '%{...%}' lexer setup action code section. Erroneous area: ${yylexer.prettyPrintRange(yylstack[yysp - 1])} Technical error report: ${yyvstack[yysp].errStr} `); this.$ = ''; break; case 132: /*! Production:: epilogue_chunk : TRAILING_CODE_CHUNK */ // default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-): this._$ = yylstack[yysp]; // END of default action (generated by JISON mode classic/merge :: 1,VT,VA,VU,-,LT,LA,-,-) // these code chunks are very probably incomplete, hence compile-testing // for these should be deferred until we've collected the entire epilogue. this.$ = yyvstack[yysp]; break; case 133: /*! Production:: include_macro_code : include_keyword option_list OPTIONS_END */ // default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,LU,LUbA): this._$ = yyparser.yyMergeLocationInfo(yysp - 2, yysp); // END of default action (generated by JISON mode classic/merge :: 3,VT,VA,VU,-,LT,LA,LU,LUbA) // check if there is only 1 unvalued options: 'path' var lst = yyvstack[yysp - 1]; var len = lst.length; var path$$1; if (len === 1 && lst[0][1] === true) { // `path`: path$$1 = lst[0][0]; } else if (len <= 1) { yyparser.yyError(rmCommonWS$1` You did not specify a legal file path for the '%include' statement, which must have the format: %include file_path Erroneous code: ${yylexer.prettyPrintRange(yylstack[yysp - 1], yylstack[yysp - 2])} Technical error report: ${$error.errStr} `); } else { yyparser.yyError(rmCommonWS$1` You did specify too many attributes for the '%include' statement, which must have the format: %include file_path Erroneous code: ${yylexer.prettyPrintRange(yylstack[yysp - 1], yylstack[yysp - 2])} Technical error report: ${$error.errStr} `); } // **Aside**: And no, we don't support nested '%include'! var fileContent = fs.readFileSync(path$$1, { encoding: 'utf-8' }); var srcCode = trimActionCode$1(fileContent); if (srcCode) { var rv = checkActionBlock$1(srcCode, this._$); if (rv) { yyparser.yyError(rmCommonWS$1` The source code included from file '${path$$1}' does not compile: ${rv} Erroneous area: ${yylexer.prettyPrintRange(this._$)} `); } } this.$ = '\n// Included by Jison: ' + path$$1 + ':\n\n' + srcCode + '\n\n// End Of Include by Jison: ' + path$$1 + '\n\n'; break; case 134: /*! Production:: include_macro_code : include_keyword error */ // default action (generated by JISON mode classic/merge :: 2,VT,VA,-,-,LT,LA,-,-): this.$ = yyvstack[yysp - 1]; this._$ = yyparser.yyMergeLocationInfo(yysp - 1, yysp); // END of default action (generated by JISON mode classic/merge :: 2,VT,VA,-,-,LT,LA,-,-) yyparser.yyError(rmCommonWS$1` %include MUST be followed by a valid file path. Erroneous path: ${yylexer.prettyPrintRange(yylstack[yysp], yylstack[yysp - 1])} Technical error report: ${yyvstack[yysp].errStr} `); break; case 185: // === NO_ACTION[1] :: ensures that anyone (but us) using this new state will fail dramatically! // error recovery reduction action (action generated by jison, // using the user-specified `%code error_recovery_reduction` %{...%} // code chunk below. break; } }, table: bt({ len: u([ 15, 1, 14, 20, 1, 13, 28, 22, s, [9, 3], 13, 5, 9, 13, c, [6, 3], s, [31, 5], 1, 43, 3, 1, 13, 5, 24, 23, 24, 23, 23, 17, 17, s, [23, 8], 25, 5, 23, 23, 9, 13, 8, 9, 1, s, [9, 5], 13, 9, 13, 1, 13, 13, 9, c, [53, 4], c, [11, 4], 26, 26, 9, 26, 4, s, [26, 6], 8, 24, 3, 8, 4, 1, 13, c, [62, 5], s, [23, 3], 2, 3, 2, 24, 24, 6, s, [4, 3], 13, 7, 8, 4, 8, 13, 13, s, [7, 6], 13, 9, 7, c, [62, 3], 9, 26, 1, 26, 7, 1, 6, 3, 9, 6, 6, 26, 17, c, [88, 3], 27, 10, s, [23, 7], 4, s, [8, 3], 7, 9, 13, 26, 26, 6, 6, 1, 9, 6, 23, 27, 26, 9, 27, 9, 27, 1, 16, 1, c, [40, 3], 15, 26, 27, 27, 16, 13 ]), symbol: u([ 1, 2, 19, 20, 23, 25, 26, s, [28, 4, 1], 33, 34, 56, 58, 1, c, [16, 13], 59, c, [14, 13], 57, s, [60, 4, 1], 65, 66, c, [35, 14], 1, 2, 3, 7, 8, s, [13, 4, 1], 19, c, [19, 9], s, [41, 6, 1], 50, 51, 68, 2, c, [26, 6], c, [16, 8], 74, s, [76, 5, 1], 84, 2, 11, 52, 53, 54, s, [85, 4, 1], c, [9, 10], 24, 32, s, [36, 5, 1], 72, c, [90, 13], 2, 27, 32, 64, 92, c, [36, 9], c, [27, 14], c, [67, 17], c, [148, 18], 11, c, [149, 22], c, [48, 3], c, [31, 125], 1, c, [303, 25], c, [349, 5], s, [67, 4, 2], c, [296, 7], 89, 1, 19, 89, 21, c, [247, 14], 7, 21, 26, 35, c, [341, 3], 9, c, [65, 4], c, [11, 3], c, [58, 8], c, [343, 6], c, [24, 18], c, [23, 8], s, [10, 7, 1], c, [26, 9], 49, 50, 51, 83, c, [47, 8], c, [44, 8], s, [75, 6, 1], c, [70, 9], c, [23, 15], c, [456, 13], c, [17, 21], c, [104, 23], c, [23, 181], s, [47, 5, 1], 45, 48, 79, 81, 82, c, [76, 46], 11, 17, 22, c, [483, 3], c, [685, 18], 17, 22, 26, c, [24, 3], c, [8, 3], 18, c, [9, 6], c, [10, 10], c, [9, 26], c, [76, 22], c, [809, 7], 64, 92, c, [22, 14], c, [766, 15], c, [810, 25], c, [85, 22], c, [22, 24], c, [135, 4], c, [859, 17], c, [704, 26], c, [26, 26], c, [992, 10], c, [35, 26], c, [1004, 3], c, [91, 52], c, [26, 105], 2, c, [19, 3], 55, 90, 91, 2, 4, c, [1236, 14], 71, c, [1237, 8], 26, 35, c, [362, 8], c, [8, 4], c, [1316, 14], c, [947, 75], c, [798, 112], 9, 2, 7, 9, c, [5, 4], c, [146, 45], 83, 2, 45, 47, 48, 79, 82, c, [6, 4], c, [4, 8], c, [603, 14], c, [601, 6], c, [793, 9], 53, 54, c, [12, 9], c, [714, 26], c, [580, 7], c, [7, 35], c, [733, 22], c, [29, 20], c, [422, 14], c, [678, 8], c, [869, 10], c, [527, 25], 24, c, [554, 32], 91, c, [514, 3], c, [8, 4], c, [1731, 4], c, [1758, 10], c, [18, 4], c, [6, 7], c, [778, 26], 5, c, [610, 14], 70, 5, c, [65, 9], c, [840, 11], c, [37, 7], c, [63, 19], c, [241, 9], c, [606, 46], c, [23, 116], c, [540, 4], c, [1309, 10], c, [8, 13], c, [466, 14], c, [1264, 15], c, [961, 58], c, [6, 6], 24, c, [87, 11], c, [16, 4], c, [370, 15], c, [980, 8], c, [358, 27], c, [538, 27], c, [573, 10], c, [62, 25], c, [36, 36], 6, c, [1130, 16], 22, c, [575, 38], c, [204, 15], c, [299, 28], c, [222, 27], c, [607, 26], c, [150, 15], c, [408, 13] ]), type: u([ s, [2, 13], 0, 0, 1, c, [16, 14], c, [30, 15], s, [0, 5], s, [2, 41], c, [42, 16], c, [64, 12], c, [9, 18], c, [49, 19], c, [29, 3], c, [36, 17], c, [79, 14], c, [31, 27], s, [2, 177], s, [0, 17], c, [273, 19], c, [58, 27], c, [24, 23], c, [412, 39], c, [477, 24], c, [23, 20], c, [17, 34], s, [2, 198], c, [214, 55], c, [269, 76], c, [76, 23], c, [98, 47], c, [416, 15], c, [557, 25], c, [205, 95], c, [719, 30], c, [579, 164], c, [800, 25], c, [24, 8], c, [778, 41], c, [947, 68], c, [271, 130], c, [24, 28], c, [265, 31], c, [659, 15], c, [971, 139], c, [460, 10], c, [283, 68], c, [1758, 27], c, [357, 48], c, [74, 44], c, [606, 49], c, [888, 175], c, [87, 92], c, [980, 15], c, [178, 89], c, [1845, 209] ]), state: u([ s, [1, 5, 1], 13, 15, 16, 8, 9, s, [24, 4, 2], 31, 36, 37, 42, 48, 50, 51, 53, 57, c, [4, 3], 59, 64, 61, 66, c, [7, 3], 68, c, [4, 3], 70, c, [4, 3], 80, 82, 83, 78, 79, 87, 73, 74, 85, 86, c, [39, 6], 72, 89, 92, c, [7, 4], 93, c, [4, 3], 97, 99, 100, c, [19, 5], 101, c, [7, 6], 102, c, [4, 3], 103, c, [4, 3], 107, 104, 105, 110, 51, 53, c, [3, 3], 64, 116, 122, c, [65, 3], c, [12, 6], c, [3, 3], 127, 64, 129, 131, 133, 138, c, [71, 7], 144, c, [26, 3], 145, c, [73, 9], 97, 97, 107, 152, 153, 51, 53, 154, c, [38, 3], 157, 64, 116, 161, 64, 163, 164, 166, 169, 171, c, [13, 3], c, [29, 4], 64, 116, 64, 116, 179, c, [54, 7], c, [12, 4] ]), mode: u([ s, [2, 27], s, [1, 13], c, [27, 15], c, [53, 38], c, [66, 27], c, [46, 14], c, [67, 23], s, [2, 170], c, [246, 26], c, [315, 22], c, [24, 4], c, [26, 5], c, [235, 10], c, [19, 19], c, [12, 5], c, [62, 17], c, [85, 5], c, [98, 14], s, [1, 38], s, [2, 209], c, [211, 48], c, [263, 30], c, [410, 8], c, [73, 54], c, [714, 21], c, [66, 31], c, [76, 30], c, [187, 43], c, [259, 43], c, [341, 81], c, [874, 136], c, [1123, 24], c, [874, 59], c, [722, 117], c, [1075, 8], c, [145, 23], c, [23, 19], c, [538, 29], c, [29, 12], c, [1028, 92], c, [673, 39], c, [34, 8], c, [1171, 33], c, [75, 28], c, [59, 12], c, [211, 47], c, [46, 16], c, [72, 10], c, [635, 41], c, [577, 23], c, [1708, 176], c, [918, 85], c, [932, 21], c, [845, 53], c, [166, 34], c, [34, 35], c, [1278, 50], s, [2, 129] ]), goto: u([ s, [7, 13], s, [9, 13], 6, 17, 6, 7, 10, 11, 12, 14, 20, 21, 22, 18, 19, 23, s, [8, 13], 51, 25, s, [51, 25], 27, 29, 32, 34, 38, 39, 40, 33, 35, 41, s, [43, 5, 1], 49, 54, 52, 55, 56, 58, c, [5, 4], 60, s, [70, 7], s, [17, 13], 62, 63, 65, 67, c, [29, 4], s, [24, 13], 69, c, [18, 4], 71, c, [5, 4], s, [30, 13], s, [35, 31], s, [36, 31], s, [31, 31], s, [32, 31], s, [33, 31], 1, 4, 88, c, [247, 6], 84, 75, 76, 77, 81, c, [305, 5], c, [257, 8], 5, 84, 90, s, [11, 13], 73, 91, s, [73, 3], 79, 79, 32, 79, c, [47, 4], s, [79, 3], c, [40, 8], 80, 80, 32, 80, c, [19, 4], s, [80, 3], c, [19, 8], s, [82, 4], 94, 95, 96, s, [82, 13], 98, 82, 82, 75, 29, 32, 75, c, [355, 12], c, [16, 16], c, [384, 13], c, [13, 13], s, [92, 23], s, [94, 23], s, [95, 23], s, [96, 23], s, [97, 23], s, [98, 23], s, [99, 23], s, [100, 23], s, [101, 25], 44, 106, s, [109, 23], s, [110, 23], 54, 109, 108, c, [598, 3], s, [13, 13], s, [113, 8], s, [114, 3], 111, s, [114, 5], 112, s, [118, 9], s, [119, 9], s, [120, 9], s, [121, 9], 54, 109, 113, c, [73, 3], s, [15, 13], 114, 65, 115, s, [117, 4, 1], s, [18, 13], 121, s, [20, 13], s, [21, 13], 123, c, [736, 4], s, [34, 5], 54, 109, 124, c, [11, 3], s, [23, 13], 54, 109, 125, c, [19, 3], s, [26, 13], 54, 109, 126, c, [19, 3], s, [29, 13], 2, s, [38, 26], s, [39, 26], 128, s, [70, 7], s, [41, 26], 130, 65, s, [45, 26], s, [46, 26], s, [47, 26], s, [48, 26], s, [49, 26], s, [50, 26], 122, 132, 135, 136, 134, 137, 140, 139, c, [1127, 14], 143, 141, 142, c, [336, 4], s, [37, 4], 3, s, [10, 13], 77, 77, 32, 77, c, [41, 4], s, [77, 3], c, [44, 8], 78, 78, 32, 78, c, [19, 4], s, [78, 3], c, [19, 8], s, [81, 4], c, [874, 3], s, [81, 13], 98, 81, 81, s, [87, 23], s, [88, 23], s, [89, 23], s, [93, 23], s, [108, 23], 147, 146, 74, 91, 74, 149, 148, s, [90, 4], c, [145, 3], s, [90, 13], 98, 90, 90, s, [91, 4], c, [23, 3], s, [91, 13], 98, 91, 91, 151, 44, 150, 106, s, [105, 4], s, [106, 4], s, [107, 4], s, [12, 13], c, [280, 4], s, [112, 8], 155, 55, 56, s, [117, 8], s, [14, 13], s, [16, 13], s, [64, 7], s, [65, 7], s, [66, 7], s, [67, 7], s, [68, 7], s, [69, 7], s, [19, 13], 54, 109, 156, c, [106, 3], s, [134, 7], s, [22, 13], s, [25, 13], 158, s, [70, 7], 159, c, [815, 6], s, [42, 26], 160, s, [44, 26], 123, 162, c, [516, 4], 124, s, [127, 6], 65, 165, s, [70, 7], s, [131, 6], s, [132, 6], s, [52, 26], 167, s, [58, 15], 168, 170, s, [70, 7], 172, s, [70, 7], s, [63, 27], 174, 54, 109, 173, c, [228, 3], 76, 76, 32, 76, c, [577, 4], s, [76, 3], c, [577, 8], s, [83, 23], s, [85, 23], s, [84, 23], s, [86, 23], s, [102, 23], s, [103, 23], s, [104, 4], s, [111, 8], s, [115, 8], s, [116, 8], s, [133, 7], 175, c, [379, 6], s, [28, 13], s, [40, 26], s, [43, 26], s, [125, 6], s, [126, 6], 176, 177, c, [85, 6], s, [130, 6], 178, c, [926, 14], 55, 55, 180, s, [55, 24], s, [56, 26], 181, c, [81, 6], s, [62, 27], 182, c, [34, 6], s, [61, 27], 183, s, [72, 16], 184, s, [128, 6], s, [129, 6], s, [53, 26], s, [57, 15], s, [54, 26], s, [59, 27], s, [60, 27], s, [71, 16], s, [27, 13] ]) }), defaultActions: bda({ idx: u([ 0, 2, 5, 11, 14, s, [17, 7, 1], 27, s, [36, 9, 1], 46, 47, 49, 50, s, [53, 4, 1], 58, 60, 62, s, [63, 5, 2], 72, 73, 74, 76, s, [78, 6, 1], 88, 89, 90, s, [94, 5, 1], s, [105, 4, 1], 110, s, [112, 10, 1], 123, 124, 125, 128, 130, 132, 133, 136, 137, 138, 143, s, [146, 11, 1], s, [158, 5, 1], 165, s, [168, 5, 2], s, [177, 8, 1] ]), goto: u([ 7, 9, 8, 17, 24, 30, 35, 36, 31, 32, 33, 1, 11, 92, s, [94, 8, 1], 109, 110, 13, 113, s, [118, 4, 1], 15, 18, 20, 21, 34, 23, 26, 29, 2, 38, 39, 41, s, [45, 6, 1], 37, 3, 10, 87, 88, 89, 93, 108, 105, 106, 107, 12, 112, 117, 14, 16, s, [64, 6, 1], 19, 134, 22, 25, 42, 44, 124, 127, 131, 132, 52, 63, 83, 85, 84, 86, 102, 103, 104, 111, 115, 116, 133, 28, 40, 43, 125, 126, 130, 56, 62, 61, 72, 128, 129, 53, 57, 54, 59, 60, 71, 27 ]) }), parseError: function parseError(str, hash, ExceptionClass) { if (hash.recoverable) { if (typeof this.trace === 'function') { this.trace(str); } hash.destroy(); // destroy... well, *almost*! } else { if (typeof this.trace === 'function') { this.trace(str); } if (!ExceptionClass) { ExceptionClass = this.JisonParserError; } throw new ExceptionClass(str, hash); } }, parse: function parse(input) { var self = this; var stack = new Array(128); // token stack: stores token which leads to state at the same index (column storage) var sstack = new Array(128); // state stack: stores states (column storage) var vstack = new Array(128); // semantic value stack var lstack = new Array(128); // location stack var table = this.table; var sp = 0; // 'stack pointer': index into the stacks var yyloc; var symbol = 0; var preErrorSymbol = 0; var lastEofErrorStateDepth = Infinity; var recoveringErrorInfo = null; var recovering = 0; // (only used when the grammar contains error recovery rules) var TERROR = this.TERROR; var EOF = this.EOF; var ERROR_RECOVERY_TOKEN_DISCARD_COUNT = (this.options.errorRecoveryTokenDiscardCount | 0) || 3; var NO_ACTION = [0, 185 /* === table.length :: ensures that anyone using this new state will fail dramatically! */]; var lexer; if (this.__lexer__) { lexer = this.__lexer__; } else { lexer = this.__lexer__ = Object.create(this.lexer); } var sharedState_yy = { parseError: undefined, quoteName: undefined, lexer: undefined, parser: undefined, pre_parse: undefined, post_parse: undefined, pre_lex: undefined, post_lex: undefined // WARNING: must be written this way for the code expanders to work correctly in both ES5 and ES6 modes! }; var ASSERT; if (typeof assert !== 'function') { ASSERT = function JisonAssert(cond, msg) { if (!cond) { throw new Error('assertion failed: ' + (msg || '***')); } }; } else { ASSERT = assert; } this.yyGetSharedState = function yyGetSharedState() { return sharedState_yy; }; this.yyGetErrorInfoTrack = function yyGetErrorInfoTrack() { return recoveringErrorInfo; }; // shallow clone objects, straight copy of simple `src` values // e.g. `lexer.yytext` MAY be a complex value object, // rather than a simple string/value. function shallow_copy(src) { if (typeof src === 'object') { var dst = {}; for (var k in src) { if (Object.prototype.hasOwnProperty.call(src, k)) { dst[k] = src[k]; } } return dst; } return src; } function shallow_copy_noclobber(dst, src) { for (var k in src) { if (typeof dst[k] === 'undefined' && Object.prototype.hasOwnProperty.call(src, k)) { dst[k] = src[k]; } } } function copy_yylloc(loc) { var rv = shallow_copy(loc); if (rv && rv.range) { rv.range = rv.range.slice(0); } return rv; } // copy state shallow_copy_noclobber(sharedState_yy, this.yy); sharedState_yy.lexer = lexer; sharedState_yy.parser = this; // *Always* setup `yyError`, `YYRECOVERING`, `yyErrOk` and `yyClearIn` functions as it is paramount // to have *their* closure match ours -- if we only set them up once, // any subsequent `parse()` runs will fail in very obscure ways when // these functions are invoked in the user action code block(s) as // their closure will still refer to the `parse()` instance which set // them up. Hence we MUST set them up at the start of every `parse()` run! if (this.yyError) { this.yyError = function yyError(str /*, ...args */) { var error_rule_depth = (this.options.parserErrorsAreRecoverable ? locateNearestErrorRecoveryRule(state) : -1); var expected = this.collect_expected_token_set(state); var hash = this.constructParseErrorInfo(str, null, expected, (error_rule_depth >= 0)); // append to the old one? if (recoveringErrorInfo) { var esp = recoveringErrorInfo.info_stack_pointer; recoveringErrorInfo.symbol_stack[esp] = symbol; var v = this.shallowCopyErrorInfo(hash); v.yyError = true; v.errorRuleDepth = error_rule_depth; v.recovering = recovering; // v.stackSampleLength = error_rule_depth + EXTRA_STACK_SAMPLE_DEPTH; recoveringErrorInfo.value_stack[esp] = v; recoveringErrorInfo.location_stack[esp] = copy_yylloc(lexer.yylloc); recoveringErrorInfo.state_stack[esp] = newState || NO_ACTION[1]; ++esp; recoveringErrorInfo.info_stack_pointer = esp; } else { recoveringErrorInfo = this.shallowCopyErrorInfo(hash); recoveringErrorInfo.yyError = true; recoveringErrorInfo.errorRuleDepth = error_rule_depth; recoveringErrorInfo.recovering = recovering; } // Add any extra args to the hash under the name `extra_error_attributes`: var args = Array.prototype.slice.call(arguments, 1); if (args.length) { hash.extra_error_attributes = args; } return this.parseError(str, hash, this.JisonParserError); }; } // Does the shared state override the default `parseError` that already comes with this instance? if (typeof sharedState_yy.parseError === 'function') { this.parseError = function parseErrorAlt(str, hash, ExceptionClass) { if (!ExceptionClass) { ExceptionClass = this.JisonParserError; } return sharedState_yy.parseError.call(this, str, hash, ExceptionClass); }; } else { this.parseError = this.originalParseError; } // Does the shared state override the default `quoteName` that already comes with this instance? if (typeof sharedState_yy.quoteName === 'function') { this.quoteName = function quoteNameAlt(id_str) { return sharedState_yy.quoteName.call(this, id_str); }; } else { this.quoteName = this.originalQuoteName; } // set up the cleanup function; make it an API so that external code can re-use this one in case of // calamities or when the `%options no-try-catch` option has been specified for the grammar, in which // case this parse() API method doesn't come with a `finally { ... }` block any more! // // NOTE: as this API uses parse() as a closure, it MUST be set again on every parse() invocation, // or else your `sharedState`, etc. references will be *wrong*! this.cleanupAfterParse = function parser_cleanupAfterParse(resultValue, invoke_post_methods, do_not_nuke_errorinfos) { var rv; if (invoke_post_methods) { var hash; if (sharedState_yy.post_parse || this.post_parse) { // create an error hash info instance: we re-use this API in a **non-error situation** // as this one delivers all parser internals ready for access by userland code. hash = this.constructParseErrorInfo(null /* no error! */, null /* no exception! */, null, false); } if (sharedState_yy.post_parse) { rv = sharedState_yy.post_parse.call(this, sharedState_yy, resultValue, hash); if (typeof rv !== 'undefined') resultValue = rv; } if (this.post_parse) { rv = this.post_parse.call(this, sharedState_yy, resultValue, hash); if (typeof rv !== 'undefined') resultValue = rv; } // cleanup: if (hash && hash.destroy) { hash.destroy(); } } if (this.__reentrant_call_depth > 1) return resultValue; // do not (yet) kill the sharedState when this is a reentrant run. // clean up the lingering lexer structures as well: if (lexer.cleanupAfterLex) { lexer.cleanupAfterLex(do_not_nuke_errorinfos); } // prevent lingering circular references from causing memory leaks: if (sharedState_yy) { sharedState_yy.lexer = undefined; sharedState_yy.parser = undefined; if (lexer.yy === sharedState_yy) { lexer.yy = undefined; } } sharedState_yy = undefined; this.parseError = this.originalParseError; this.quoteName = this.originalQuoteName; // nuke the vstack[] array at least as that one will still reference obsoleted user values. // To be safe, we nuke the other internal stack columns as well... stack.length = 0; // fastest way to nuke an array without overly bothering the GC sstack.length = 0; lstack.length = 0; vstack.length = 0; sp = 0; // nuke the error hash info instances created during this run. // Userland code must COPY any data/references // in the error hash instance(s) it is more permanently interested in. if (!do_not_nuke_errorinfos) { for (var i = this.__error_infos.length - 1; i >= 0; i--) { var el = this.__error_infos[i]; if (el && typeof el.destroy === 'function') { el.destroy(); } } this.__error_infos.length = 0; for (var i = this.__error_recovery_infos.length - 1; i >= 0; i--) { var el = this.__error_recovery_infos[i]; if (el && typeof el.destroy === 'function') { el.destroy(); } } this.__error_recovery_infos.length = 0; // `recoveringErrorInfo` is also part of the `__error_recovery_infos` array, // hence has been destroyed already: no need to do that *twice*. if (recoveringErrorInfo) { recoveringErrorInfo = undefined; } } return resultValue; }; // merge yylloc info into a new yylloc instance. // // `first_index` and `last_index` MAY be UNDEFINED/NULL or these are indexes into the `lstack[]` location stack array. // // `first_yylloc` and `last_yylloc` MAY be UNDEFINED/NULL or explicit (custom or regular) `yylloc` instances, in which // case these override the corresponding first/last indexes. // // `dont_look_back` is an optional flag (default: FALSE), which instructs this merge operation NOT to search // through the parse location stack for a location, which would otherwise be used to construct the new (epsilon!) // yylloc info. // // Note: epsilon rule's yylloc situation is detected by passing both `first_index` and `first_yylloc` as UNDEFINED/NULL. this.yyMergeLocationInfo = function parser_yyMergeLocationInfo(first_index, last_index, first_yylloc, last_yylloc, dont_look_back) { var i1 = first_index | 0, i2 = last_index | 0; var l1 = first_yylloc, l2 = last_yylloc; var rv; // rules: // - first/last yylloc entries override first/last indexes if (!l1) { if (first_index != null) { for (var i = i1; i <= i2; i++) { l1 = lstack[i]; if (l1) { break; } } } } if (!l2) { if (last_index != null) { for (var i = i2; i >= i1; i--) { l2 = lstack[i]; if (l2) { break; } } } } // - detect if an epsilon rule is being processed and act accordingly: if (!l1 && first_index == null) { // epsilon rule span merger. With optional look-ahead in l2. if (!dont_look_back) { for (var i = (i1 || sp) - 1; i >= 0; i--) { l1 = lstack[i]; if (l1) { break; } } } if (!l1) { if (!l2) { // when we still don't have any valid yylloc info, we're looking at an epsilon rule // without look-ahead and no preceding terms and/or `dont_look_back` set: // in that case we ca do nothing but return NULL/UNDEFINED: return undefined; } else { // shallow-copy L2: after all, we MAY be looking // at unconventional yylloc info objects... rv = shallow_copy(l2); if (rv.range) { // shallow copy the yylloc ranges info to prevent us from modifying the original arguments' entries: rv.range = rv.range.slice(0); } return rv; } } else { // shallow-copy L1, then adjust first col/row 1 column past the end. rv = shallow_copy(l1); rv.first_line = rv.last_line; rv.first_column = rv.last_column; if (rv.range) { // shallow copy the yylloc ranges info to prevent us from modifying the original arguments' entries: rv.range = rv.range.slice(0); rv.range[0] = rv.range[1]; } if (l2) { // shallow-mixin L2, then adjust last col/row accordingly. shallow_copy_noclobber(rv, l2); rv.last_line = l2.last_line; rv.last_column = l2.last_column; if (rv.range && l2.range) { rv.range[1] = l2.range[1]; } } return rv; } } if (!l1) { l1 = l2; l2 = null; } if (!l1) { return undefined; } // shallow-copy L1|L2, before we try to adjust the yylloc values: after all, we MAY be looking // at unconventional yylloc info objects... rv = shallow_copy(l1); // first_line: ..., // first_column: ..., // last_line: ..., // last_column: ..., if (rv.range) { // shallow copy the yylloc ranges info to prevent us from modifying the original arguments' entries: rv.range = rv.range.slice(0); } if (l2) { shallow_copy_noclobber(rv, l2); rv.last_line = l2.last_line; rv.last_column = l2.last_column; if (rv.range && l2.range) { rv.range[1] = l2.range[1]; } } return rv; }; // NOTE: as this API uses parse() as a closure, it MUST be set again on every parse() invocation, // or else your `lexer`, `sharedState`, etc. references will be *wrong*! this.constructParseErrorInfo = function parser_constructParseErrorInfo(msg, ex, expected, recoverable) { var pei = { errStr: msg, exception: ex, text: lexer.match, value: lexer.yytext, token: this.describeSymbol(symbol) || symbol, token_id: symbol, line: lexer.yylineno, loc: copy_yylloc(lexer.yylloc), expected: expected, recoverable: recoverable, state: state, action: action, new_state: newState, symbol_stack: stack, state_stack: sstack, value_stack: vstack, location_stack: lstack, stack_pointer: sp, yy: sharedState_yy, lexer: lexer, parser: this, // and make sure the error info doesn't stay due to potential // ref cycle via userland code manipulations. // These would otherwise all be memory leak opportunities! // // Note that only array and object references are nuked as those // constitute the set of elements which can produce a cyclic ref. // The rest of the members is kept intact as they are harmless. destroy: function destructParseErrorInfo() { // remove cyclic references added to error info: // info.yy = null; // info.lexer = null; // info.value = null; // info.value_stack = null; // ... var rec = !!this.recoverable; for (var key in this) { if (this.hasOwnProperty(key) && typeof key === 'object') { this[key] = undefined; } } this.recoverable = rec; } }; // track this instance so we can `destroy()` it once we deem it superfluous and ready for garbage collection! this.__error_infos.push(pei); return pei; }; // clone some parts of the (possibly enhanced!) errorInfo object // to give them some persistence. this.shallowCopyErrorInfo = function parser_shallowCopyErrorInfo(p) { var rv = shallow_copy(p); // remove the large parts which can only cause cyclic references // and are otherwise available from the parser kernel anyway. delete rv.sharedState_yy; delete rv.parser; delete rv.lexer; // lexer.yytext MAY be a complex value object, rather than a simple string/value: rv.value = shallow_copy(rv.value); // yylloc info: rv.loc = copy_yylloc(rv.loc); // the 'expected' set won't be modified, so no need to clone it: //rv.expected = rv.expected.slice(0); //symbol stack is a simple array: rv.symbol_stack = rv.symbol_stack.slice(0); // ditto for state stack: rv.state_stack = rv.state_stack.slice(0); // clone the yylloc's in the location stack?: rv.location_stack = rv.location_stack.map(copy_yylloc); // and the value stack may carry both simple and complex values: // shallow-copy the latter. rv.value_stack = rv.value_stack.map(shallow_copy); // and we don't bother with the sharedState_yy reference: //delete rv.yy; // now we prepare for tracking the COMBINE actions // in the error recovery code path: // // as we want to keep the maximum error info context, we // *scan* the state stack to find the first *empty* slot. // This position will surely be AT OR ABOVE the current // stack pointer, but we want to keep the 'used but discarded' // part of the parse stacks *intact* as those slots carry // error context that may be useful when you want to produce // very detailed error diagnostic reports. // // ### Purpose of each stack pointer: // // - stack_pointer: points at the top of the parse stack // **as it existed at the time of the error // occurrence, i.e. at the time the stack // snapshot was taken and copied into the // errorInfo object.** // - base_pointer: the bottom of the **empty part** of the // stack, i.e. **the start of the rest of // the stack space /above/ the existing // parse stack. This section will be filled // by the error recovery process as it // travels the parse state machine to // arrive at the resolving error recovery rule.** // - info_stack_pointer: // this stack pointer points to the **top of // the error ecovery tracking stack space**, i.e. // this stack pointer takes up the role of // the `stack_pointer` for the error recovery // process. Any mutations in the **parse stack** // are **copy-appended** to this part of the // stack space, keeping the bottom part of the // stack (the 'snapshot' part where the parse // state at the time of error occurrence was kept) // intact. // - root_failure_pointer: // copy of the `stack_pointer`... // for (var i = rv.stack_pointer; typeof rv.state_stack[i] !== 'undefined'; i++) { // empty } rv.base_pointer = i; rv.info_stack_pointer = i; rv.root_failure_pointer = rv.stack_pointer; // track this instance so we can `destroy()` it once we deem it superfluous and ready for garbage collection! this.__error_recovery_infos.push(rv); return rv; }; function stdLex() { var token = lexer.lex(); // if token isn't its numeric value, convert if (typeof token !== 'number') { token = self.symbols_[token] || token; } return token || EOF; } function fastLex() { var token = lexer.fastLex(); // if token isn't its numeric value, convert if (typeof token !== 'number') { token = self.symbols_[token] || token; } return token || EOF; } var lex = stdLex; var state, action, r, t; var yyval = { $: true, _$: undefined, yy: sharedState_yy }; var p; var yyrulelen; var this_production; var newState; var retval = false; // Return the rule stack depth where the nearest error rule can be found. // Return -1 when no error recovery rule was found. function locateNearestErrorRecoveryRule(state) { var stack_probe = sp - 1; var depth = 0; // try to recover from error while (stack_probe >= 0) { // check for error recovery rule in this state var t = table[state][TERROR] || NO_ACTION; if (t[0]) { // We need to make sure we're not cycling forever: // once we hit EOF, even when we `yyerrok()` an error, we must // prevent the core from running forever, // e.g. when parent rules are still expecting certain input to // follow after this, for example when you handle an error inside a set // of braces which are matched by a parent rule in your grammar. // // Hence we require that every error handling/recovery attempt // *after we've hit EOF* has a diminishing state stack: this means // we will ultimately have unwound the state stack entirely and thus // terminate the parse in a controlled fashion even when we have // very complex error/recovery code interplay in the core + user // action code blocks: if (symbol === EOF) { if (lastEofErrorStateDepth > sp - 1 - depth) { lastEofErrorStateDepth = sp - 1 - depth; } else { --stack_probe; // popStack(1): [symbol, action] state = sstack[stack_probe]; ++depth; continue; } } return depth; } if (state === 0 /* $accept rule */ || stack_probe < 1) { return -1; // No suitable error recovery rule available. } --stack_probe; // popStack(1): [symbol, action] state = sstack[stack_probe]; ++depth; } return -1; // No suitable error recovery rule available. } try { this.__reentrant_call_depth++; lexer.setInput(input, sharedState_yy); // NOTE: we *assume* no lexer pre/post handlers are set up *after* // this initial `setInput()` call: hence we can now check and decide // whether we'll go with the standard, slower, lex() API or the // `fast_lex()` one: if (typeof lexer.canIUse === 'function') { var lexerInfo = lexer.canIUse(); if (lexerInfo.fastLex && typeof fastLex === 'function') { lex = fastLex; } } yyloc = lexer.yylloc; lstack[sp] = yyloc; vstack[sp] = null; sstack[sp] = 0; stack[sp] = 0; ++sp; if (this.pre_parse) { this.pre_parse.call(this, sharedState_yy); } if (sharedState_yy.pre_parse) { sharedState_yy.pre_parse.call(this, sharedState_yy); } newState = sstack[sp - 1]; for (;;) { // retrieve state number from top of stack state = newState; // sstack[sp - 1]; // use default actions if available if (this.defaultActions[state]) { action = 2; newState = this.defaultActions[state]; } else { // The single `==` condition below covers both these `===` comparisons in a single // operation: // // if (symbol === null || typeof symbol === 'undefined') ... if (!symbol) { symbol = lex(); } // read action for current state and first input t = (table[state] && table[state][symbol]) || NO_ACTION; newState = t[1]; action = t[0]; // handle parse error if (!action) { // first see if there's any chance at hitting an error recovery rule: var error_rule_depth = locateNearestErrorRecoveryRule(state); var errStr = null; var errSymbolDescr = (this.describeSymbol(symbol) || symbol); var expected = this.collect_expected_token_set(state); if (!recovering) { // Report error if (typeof lexer.yylineno === 'number') { errStr = 'Parse error on line ' + (lexer.yylineno + 1) + ': '; } else { errStr = 'Parse error: '; } if (typeof lexer.showPosition === 'function') { errStr += '\n' + lexer.showPosition(79 - 10, 10) + '\n'; } if (expected.length) { errStr += 'Expecting ' + expected.join(', ') + ', got unexpected ' + errSymbolDescr; } else { errStr += 'Unexpected ' + errSymbolDescr; } p = this.constructParseErrorInfo(errStr, null, expected, (error_rule_depth >= 0)); // DO NOT cleanup the old one before we start the new error info track: // the old one will *linger* on the error stack and stay alive until we // invoke the parser's cleanup API! recoveringErrorInfo = this.shallowCopyErrorInfo(p); r = this.parseError(p.errStr, p, this.JisonParserError); if (typeof r !== 'undefined') { retval = r; break; } // Protect against overly blunt userland `parseError` code which *sets* // the `recoverable` flag without properly checking first: // we always terminate the parse when there's no recovery rule available anyhow! if (!p.recoverable || error_rule_depth < 0) { break; } } var esp = recoveringErrorInfo.info_stack_pointer; // just recovered from another error if (recovering === ERROR_RECOVERY_TOKEN_DISCARD_COUNT && error_rule_depth >= 0) { // SHIFT current lookahead and grab another recoveringErrorInfo.symbol_stack[esp] = symbol; recoveringErrorInfo.value_stack[esp] = shallow_copy(lexer.yytext); recoveringErrorInfo.location_stack[esp] = copy_yylloc(lexer.yylloc); recoveringErrorInfo.state_stack[esp] = newState; // push state ++esp; // Pick up the lexer details for the current symbol as that one is not 'look-ahead' any more: yyloc = lexer.yylloc; preErrorSymbol = 0; symbol = lex(); } // try to recover from error if (error_rule_depth < 0) { ASSERT(recovering > 0, "line 897"); recoveringErrorInfo.info_stack_pointer = esp; // barf a fatal hairball when we're out of look-ahead symbols and none hit a match // while we are still busy recovering from another error: var po = this.__error_infos[this.__error_infos.length - 1]; // Report error if (typeof lexer.yylineno === 'number') { errStr = 'Parsing halted on line ' + (lexer.yylineno + 1) + ' while starting to recover from another error'; } else { errStr = 'Parsing halted while starting to recover from another error'; } if (po) { errStr += ' -- previous error which resulted in this fatal result: ' + po.errStr; } else { errStr += ': '; } if (typeof lexer.showPosition === 'function') { errStr += '\n' + lexer.showPosition(79 - 10, 10) + '\n'; } if (expected.length) { errStr += 'Expecting ' + expected.join(', ') + ', got unexpected ' + errSymbolDescr; } else { errStr += 'Unexpected ' + errSymbolDescr; } p = this.constructParseErrorInfo(errStr, null, expected, false); if (po) { p.extra_error_attributes = po; } r = this.parseError(p.errStr, p, this.JisonParserError); if (typeof r !== 'undefined') { retval = r; } break; } preErrorSymbol = (symbol === TERROR ? 0 : symbol); // save the lookahead token symbol = TERROR; // insert generic error symbol as new lookahead const EXTRA_STACK_SAMPLE_DEPTH = 3; // REDUCE/COMBINE the pushed terms/tokens to a new ERROR token: recoveringErrorInfo.symbol_stack[esp] = preErrorSymbol; if (errStr) { recoveringErrorInfo.value_stack[esp] = { yytext: shallow_copy(lexer.yytext), errorRuleDepth: error_rule_depth, errStr: errStr, errorSymbolDescr: errSymbolDescr, expectedStr: expected, stackSampleLength: error_rule_depth + EXTRA_STACK_SAMPLE_DEPTH }; } else { recoveringErrorInfo.value_stack[esp] = { yytext: shallow_copy(lexer.yytext), errorRuleDepth: error_rule_depth, stackSampleLength: error_rule_depth + EXTRA_STACK_SAMPLE_DEPTH }; } recoveringErrorInfo.location_stack[esp] = copy_yylloc(lexer.yylloc); recoveringErrorInfo.state_stack[esp] = newState || NO_ACTION[1]; ++esp; recoveringErrorInfo.info_stack_pointer = esp; yyval.$ = recoveringErrorInfo; yyval._$ = undefined; yyrulelen = error_rule_depth; r = this.performAction.call(yyval, yyloc, NO_ACTION[1], sp - 1, vstack, lstack); if (typeof r !== 'undefined') { retval = r; break; } // pop off stack sp -= yyrulelen; // and move the top entries + discarded part of the parse stacks onto the error info stack: for (var idx = sp - EXTRA_STACK_SAMPLE_DEPTH, top = idx + yyrulelen; idx < top; idx++, esp++) { recoveringErrorInfo.symbol_stack[esp] = stack[idx]; recoveringErrorInfo.value_stack[esp] = shallow_copy(vstack[idx]); recoveringErrorInfo.location_stack[esp] = copy_yylloc(lstack[idx]); recoveringErrorInfo.state_stack[esp] = sstack[idx]; } recoveringErrorInfo.symbol_stack[esp] = TERROR; recoveringErrorInfo.value_stack[esp] = shallow_copy(yyval.$); recoveringErrorInfo.location_stack[esp] = copy_yylloc(yyval._$); // goto new state = table[STATE][NONTERMINAL] newState = sstack[sp - 1]; if (this.defaultActions[newState]) { recoveringErrorInfo.state_stack[esp] = this.defaultActions[newState]; } else { t = (table[newState] && table[newState][symbol]) || NO_ACTION; recoveringErrorInfo.state_stack[esp] = t[1]; } ++esp; recoveringErrorInfo.info_stack_pointer = esp; // allow N (default: 3) real symbols to be shifted before reporting a new error recovering = ERROR_RECOVERY_TOKEN_DISCARD_COUNT; // Now duplicate the standard parse machine here, at least its initial // couple of rounds until the TERROR symbol is **pushed onto the parse stack**, // as we wish to push something special then! // // Run the state machine in this copy of the parser state machine // until we *either* consume the error symbol (and its related information) // *or* we run into another error while recovering from this one // *or* we execute a `reduce` action which outputs a final parse // result (yes, that MAY happen!). // // We stay in this secondary parse loop until we have completed // the *error recovery phase* as the main parse loop (further below) // is optimized for regular parse operation and DOES NOT cope with // error recovery *at all*. // // We call the secondary parse loop just below the "slow parse loop", // while the main parse loop, which is an almost-duplicate of this one, // yet optimized for regular parse operation, is called the "fast // parse loop". // // Compare this to `bison` & (vanilla) `jison`, both of which have // only a single parse loop, which handles everything. Our goal is // to eke out every drop of performance in the main parse loop... ASSERT(recoveringErrorInfo, "line 1049"); ASSERT(symbol === TERROR, "line 1050"); ASSERT(!action, "line 1051"); var errorSymbolFromParser = true; for (;;) { // retrieve state number from top of stack state = newState; // sstack[sp - 1]; // use default actions if available if (this.defaultActions[state]) { action = 2; newState = this.defaultActions[state]; } else { // The single `==` condition below covers both these `===` comparisons in a single // operation: // // if (symbol === null || typeof symbol === 'undefined') ... if (!symbol) { symbol = lex(); // **Warning: Edge Case**: the *lexer* may produce // TERROR tokens of its own volition: *those* TERROR // tokens should be treated like *regular tokens* // i.e. tokens which have a lexer-provided `yyvalue` // and `yylloc`: errorSymbolFromParser = false; } // read action for current state and first input t = (table[state] && table[state][symbol]) || NO_ACTION; newState = t[1]; action = t[0]; // encountered another parse error? If so, break out to main loop // and take it from there! if (!action) { ASSERT(recoveringErrorInfo, "line 1087"); // Prep state variables so that upon breaking out of // this "slow parse loop" and hitting the `continue;` // statement in the outer "fast parse loop" we redo // the exact same state table lookup as the one above // so that the outer=main loop will also correctly // detect the 'parse error' state (`!action`) we have // just encountered above. newState = state; break; } } switch (action) { // catch misc. parse failures: default: // this shouldn't happen, unless resolve defaults are off // // SILENTLY SIGNAL that the outer "fast parse loop" should // take care of this internal error condition: // prevent useless code duplication now/here. break; // shift: case 1: stack[sp] = symbol; // ### Note/Warning ### // // The *lexer* may also produce TERROR tokens on its own, // so we specifically test for the TERROR we did set up // in the error recovery logic further above! if (symbol === TERROR && errorSymbolFromParser) { // Push a special value onto the stack when we're // shifting the `error` symbol that is related to the // error we're recovering from. ASSERT(recoveringErrorInfo, "line 1131"); vstack[sp] = recoveringErrorInfo; lstack[sp] = this.yyMergeLocationInfo(null, null, recoveringErrorInfo.loc, lexer.yylloc, true); } else { ASSERT(symbol !== 0, "line 1135"); ASSERT(preErrorSymbol === 0, "line 1136"); vstack[sp] = lexer.yytext; lstack[sp] = copy_yylloc(lexer.yylloc); } sstack[sp] = newState; // push state ++sp; symbol = 0; // **Warning: Edge Case**: the *lexer* may have produced // TERROR tokens of its own volition: *those* TERROR // tokens should be treated like *regular tokens* // i.e. tokens which have a lexer-provided `yyvalue` // and `yylloc`: errorSymbolFromParser = false; if (!preErrorSymbol) { // normal execution / no error // Pick up the lexer details for the current symbol as that one is not 'look-ahead' any more: yyloc = lexer.yylloc; if (recovering > 0) { recovering--; } } else { // error just occurred, resume old lookahead f/ before error, *unless* that drops us straight back into error mode: ASSERT(recovering > 0, "line 1163"); symbol = preErrorSymbol; preErrorSymbol = 0; // read action for current state and first input t = (table[newState] && table[newState][symbol]) || NO_ACTION; if (!t[0] || symbol === TERROR) { // forget about that symbol and move forward: this wasn't a 'forgot to insert' error type where // (simple) stuff might have been missing before the token which caused the error we're // recovering from now... // // Also check if the LookAhead symbol isn't the ERROR token we set as part of the error // recovery, for then this we would we idling (cycling) on the error forever. // Yes, this does not take into account the possibility that the *lexer* may have // produced a *new* TERROR token all by itself, but that would be a very peculiar grammar! symbol = 0; } } // once we have pushed the special ERROR token value, // we REMAIN in this inner, "slow parse loop" until // the entire error recovery phase has completed. // // ### Note About Edge Case ### // // Userland action code MAY already have 'reset' the // error recovery phase marker `recovering` to ZERO(0) // while the error symbol hasn't been shifted onto // the stack yet. Hence we only exit this "slow parse loop" // when *both* conditions are met! ASSERT(preErrorSymbol === 0, "line 1194"); if (recovering === 0) { break; } continue; // reduce: case 2: this_production = this.productions_[newState - 1]; // `this.productions_[]` is zero-based indexed while states start from 1 upwards... yyrulelen = this_production[1]; r = this.performAction.call(yyval, yyloc, newState, sp - 1, vstack, lstack); if (typeof r !== 'undefined') { // signal end of error recovery loop AND end of outer parse loop action = 3; sp = -2; // magic number: signal outer "fast parse loop" ACCEPT state that we already have a properly set up `retval` parser return value. retval = r; break; } // pop off stack sp -= yyrulelen; // don't overwrite the `symbol` variable: use a local var to speed things up: var ntsymbol = this_production[0]; // push nonterminal (reduce) stack[sp] = ntsymbol; vstack[sp] = yyval.$; lstack[sp] = yyval._$; // goto new state = table[STATE][NONTERMINAL] newState = table[sstack[sp - 1]][ntsymbol]; sstack[sp] = newState; ++sp; continue; // accept: case 3: retval = true; // Return the `$accept` rule's `$$` result, if available. // // Also note that JISON always adds this top-most `$accept` rule (with implicit, // default, action): // // $accept: <startSymbol> $end // %{ $$ = $1; @$ = @1; %} // // which, combined with the parse kernel's `$accept` state behaviour coded below, // will produce the `$$` value output of the <startSymbol> rule as the parse result, // IFF that result is *not* `undefined`. (See also the parser kernel code.) // // In code: // // %{ // @$ = @1; // if location tracking support is included // if (typeof $1 !== 'undefined') // return $1; // else // return true; // the default parse result if the rule actions don't produce anything // %} sp--; if (sp >= 0 && typeof vstack[sp] !== 'undefined') { retval = vstack[sp]; } sp = -2; // magic number: signal outer "fast parse loop" ACCEPT state that we already have a properly set up `retval` parser return value. break; } // break out of loop: we accept or fail with error break; } // should we also break out of the regular/outer parse loop, // i.e. did the parser already produce a parse result in here?! // *or* did we hit an unsupported parse state, to be handled // in the `switch/default` code further below? ASSERT(action !== 2, "line 1272"); if (!action || action === 1) { continue; } } } switch (action) { // catch misc. parse failures: default: // this shouldn't happen, unless resolve defaults are off if (action instanceof Array) { p = this.constructParseErrorInfo('Parse Error: multiple actions possible at state: ' + state + ', token: ' + symbol, null, null, false); r = this.parseError(p.errStr, p, this.JisonParserError); if (typeof r !== 'undefined') { retval = r; } break; } // Another case of better safe than sorry: in case state transitions come out of another error recovery process // or a buggy LUT (LookUp Table): p = this.constructParseErrorInfo('Parsing halted. No viable error recovery approach available due to internal system failure.', null, null, false); r = this.parseError(p.errStr, p, this.JisonParserError); if (typeof r !== 'undefined') { retval = r; } break; // shift: case 1: stack[sp] = symbol; vstack[sp] = lexer.yytext; lstack[sp] = copy_yylloc(lexer.yylloc); sstack[sp] = newState; // push state ++sp; symbol = 0; ASSERT(preErrorSymbol === 0, "line 1352"); // normal execution / no error ASSERT(recovering === 0, "line 1353"); // normal execution / no error // Pick up the lexer details for the current symbol as that one is not 'look-ahead' any more: yyloc = lexer.yylloc; continue; // reduce: case 2: ASSERT(preErrorSymbol === 0, "line 1364"); // normal execution / no error ASSERT(recovering === 0, "line 1365"); // normal execution / no error this_production = this.productions_[newState - 1]; // `this.productions_[]` is zero-based indexed while states start from 1 upwards... yyrulelen = this_production[1]; r = this.performAction.call(yyval, yyloc, newState, sp - 1, vstack, lstack); if (typeof r !== 'undefined') { retval = r; break; } // pop off stack sp -= yyrulelen; // don't overwrite the `symbol` variable: use a local var to speed things up: var ntsymbol = this_production[0]; // push nonterminal (reduce) stack[sp] = ntsymbol; vstack[sp] = yyval.$; lstack[sp] = yyval._$; // goto new state = table[STATE][NONTERMINAL] newState = table[sstack[sp - 1]][ntsymbol]; sstack[sp] = newState; ++sp; continue; // accept: case 3: if (sp !== -2) { retval = true; // Return the `$accept` rule's `$$` result, if available. // // Also note that JISON always adds this top-most `$accept` rule (with implicit, // default, action): // // $accept: <startSymbol> $end // %{ $$ = $1; @$ = @1; %} // // which, combined with the parse kernel's `$accept` state behaviour coded below, // will produce the `$$` value output of the <startSymbol> rule as the parse result, // IFF that result is *not* `undefined`. (See also the parser kernel code.) // // In code: // // %{ // @$ = @1; // if location tracking support is included // if (typeof $1 !== 'undefined') // return $1; // else // return true; // the default parse result if the rule actions don't produce anything // %} sp--; if (typeof vstack[sp] !== 'undefined') { retval = vstack[sp]; } } break; } // break out of loop: we accept or fail with error break; } } catch (ex) { // report exceptions through the parseError callback too, but keep the exception intact // if it is a known parser or lexer error which has been thrown by parseError() already: if (ex instanceof this.JisonParserError) { throw ex; } else if (lexer && typeof lexer.JisonLexerError === 'function' && ex instanceof lexer.JisonLexerError) { throw ex; } p = this.constructParseErrorInfo('Parsing aborted due to exception.', ex, null, false); retval = false; r = this.parseError(p.errStr, p, this.JisonParserError); if (typeof r !== 'undefined') { retval = r; } } finally { retval = this.cleanupAfterParse(retval, true, true); this.__reentrant_call_depth--; } // /finally return retval; }, yyError: 1 }; parser.originalParseError = parser.parseError; parser.originalQuoteName = parser.quoteName; /* lexer generated by jison-lex 0.6.1-216 */ /* * Returns a Lexer object of the following structure: * * Lexer: { * yy: {} The so-called "shared state" or rather the *source* of it; * the real "shared state" `yy` passed around to * the rule actions, etc. is a direct reference! * * This "shared context" object was passed to the lexer by way of * the `lexer.setInput(str, yy)` API before you may use it. * * This "shared context" object is passed to the lexer action code in `performAction()` * so userland code in the lexer actions may communicate with the outside world * and/or other lexer rules' actions in more or less complex ways. * * } * * Lexer.prototype: { * EOF: 1, * ERROR: 2, * * yy: The overall "shared context" object reference. * * JisonLexerError: function(msg, hash), * * performAction: function lexer__performAction(yy, yyrulenumber, YY_START), * * The function parameters and `this` have the following value/meaning: * - `this` : reference to the `lexer` instance. * `yy_` is an alias for `this` lexer instance reference used internally. * * - `yy` : a reference to the `yy` "shared state" object which was passed to the lexer * by way of the `lexer.setInput(str, yy)` API before. * * Note: * The extra arguments you specified in the `%parse-param` statement in your * **parser** grammar definition file are passed to the lexer via this object * reference as member variables. * * - `yyrulenumber` : index of the matched lexer rule (regex), used internally. * * - `YY_START`: the current lexer "start condition" state. * * parseError: function(str, hash, ExceptionClass), * * constructLexErrorInfo: function(error_message, is_recoverable), * Helper function. * Produces a new errorInfo 'hash object' which can be passed into `parseError()`. * See it's use in this lexer kernel in many places; example usage: * * var infoObj = lexer.constructParseErrorInfo('fail!', true); * var retVal = lexer.parseError(infoObj.errStr, infoObj, lexer.JisonLexerError); * * options: { ... lexer %options ... }, * * lex: function(), * Produce one token of lexed input, which was passed in earlier via the `lexer.setInput()` API. * You MAY use the additional `args...` parameters as per `%parse-param` spec of the **lexer** grammar: * these extra `args...` are added verbatim to the `yy` object reference as member variables. * * WARNING: * Lexer's additional `args...` parameters (via lexer's `%parse-param`) MAY conflict with * any attributes already added to `yy` by the **parser** or the jison run-time; * when such a collision is detected an exception is thrown to prevent the generated run-time * from silently accepting this confusing and potentially hazardous situation! * * cleanupAfterLex: function(do_not_nuke_errorinfos), * Helper function. * * This helper API is invoked when the **parse process** has completed: it is the responsibility * of the **parser** (or the calling userland code) to invoke this method once cleanup is desired. * * This helper may be invoked by user code to ensure the internal lexer gets properly garbage collected. * * setInput: function(input, [yy]), * * * input: function(), * * * unput: function(str), * * * more: function(), * * * reject: function(), * * * less: function(n), * * * pastInput: function(n), * * * upcomingInput: function(n), * * * showPosition: function(), * * * test_match: function(regex_match_array, rule_index), * * * next: function(), * * * begin: function(condition), * * * pushState: function(condition), * * * popState: function(), * * * topState: function(), * * * _currentRules: function(), * * * stateStackSize: function(), * * * performAction: function(yy, yy_, yyrulenumber, YY_START), * * * rules: [...], * * * conditions: {associative list: name ==> set}, * } * * * token location info (`yylloc`): { * first_line: n, * last_line: n, * first_column: n, * last_column: n, * range: [start_number, end_number] * (where the numbers are indexes into the input string, zero-based) * } * * --- * * The `parseError` function receives a 'hash' object with these members for lexer errors: * * { * text: (matched text) * token: (the produced terminal token, if any) * token_id: (the produced terminal token numeric ID, if any) * line: (yylineno) * loc: (yylloc) * recoverable: (boolean: TRUE when the parser MAY have an error recovery rule * available for this particular error) * yy: (object: the current parser internal "shared state" `yy` * as is also available in the rule actions; this can be used, * for instance, for advanced error analysis and reporting) * lexer: (reference to the current lexer instance used by the parser) * } * * while `this` will reference the current lexer instance. * * When `parseError` is invoked by the lexer, the default implementation will * attempt to invoke `yy.parser.parseError()`; when this callback is not provided * it will try to invoke `yy.parseError()` instead. When that callback is also not * provided, a `JisonLexerError` exception will be thrown containing the error * message and `hash`, as constructed by the `constructLexErrorInfo()` API. * * Note that the lexer's `JisonLexerError` error class is passed via the * `ExceptionClass` argument, which is invoked to construct the exception * instance to be thrown, so technically `parseError` will throw the object * produced by the `new ExceptionClass(str, hash)` JavaScript expression. * * --- * * You can specify lexer options by setting / modifying the `.options` object of your Lexer instance. * These options are available: * * (Options are permanent.) * * yy: { * parseError: function(str, hash, ExceptionClass) * optional: overrides the default `parseError` function. * } * * lexer.options: { * pre_lex: function() * optional: is invoked before the lexer is invoked to produce another token. * `this` refers to the Lexer object. * post_lex: function(token) { return token; } * optional: is invoked when the lexer has produced a token `token`; * this function can override the returned token value by returning another. * When it does not return any (truthy) value, the lexer will return * the original `token`. * `this` refers to the Lexer object. * * WARNING: the next set of options are not meant to be changed. They echo the abilities of * the lexer as per when it was compiled! * * ranges: boolean * optional: `true` ==> token location info will include a .range[] member. * flex: boolean * optional: `true` ==> flex-like lexing behaviour where the rules are tested * exhaustively to find the longest match. * backtrack_lexer: boolean * optional: `true` ==> lexer regexes are tested in order and for invoked; * the lexer terminates the scan when a token is returned by the action code. * xregexp: boolean * optional: `true` ==> lexer rule regexes are "extended regex format" requiring the * `XRegExp` library. When this %option has not been specified at compile time, all lexer * rule regexes have been written as standard JavaScript RegExp expressions. * } */ var lexer = function() { /** * See also: * http://stackoverflow.com/questions/1382107/whats-a-good-way-to-extend-error-in-javascript/#35881508 * but we keep the prototype.constructor and prototype.name assignment lines too for compatibility * with userland code which might access the derived class in a 'classic' way. * * @public * @constructor * @nocollapse */ function JisonLexerError(msg, hash) { Object.defineProperty(this, 'name', { enumerable: false, writable: false, value: 'JisonLexerError' }); if (msg == null) msg = '???'; Object.defineProperty(this, 'message', { enumerable: false, writable: true, value: msg }); this.hash = hash; var stacktrace; if (hash && hash.exception instanceof Error) { var ex2 = hash.exception; this.message = ex2.message || msg; stacktrace = ex2.stack; } if (!stacktrace) { if (Error.hasOwnProperty('captureStackTrace')) { // V8 Error.captureStackTrace(this, this.constructor); } else { stacktrace = new Error(msg).stack; } } if (stacktrace) { Object.defineProperty(this, 'stack', { enumerable: false, writable: false, value: stacktrace }); } } if (typeof Object.setPrototypeOf === 'function') { Object.setPrototypeOf(JisonLexerError.prototype, Error.prototype); } else { JisonLexerError.prototype = Object.create(Error.prototype); } JisonLexerError.prototype.constructor = JisonLexerError; JisonLexerError.prototype.name = 'JisonLexerError'; var lexer = { // Code Generator Information Report // --------------------------------- // // Options: // // backtracking: .................... false // location.ranges: ................. true // location line+column tracking: ... true // // // Forwarded Parser Analysis flags: // // uses yyleng: ..................... false // uses yylineno: ................... false // uses yytext: ..................... false // uses yylloc: ..................... false // uses lexer values: ............... true / true // location tracking: ............... true // location assignment: ............. true // // // Lexer Analysis flags: // // uses yyleng: ..................... ??? // uses yylineno: ................... ??? // uses yytext: ..................... ??? // uses yylloc: ..................... ??? // uses ParseError API: ............. ??? // uses yyerror: .................... ??? // uses location tracking & editing: ??? // uses more() API: ................. ??? // uses unput() API: ................ ??? // uses reject() API: ............... ??? // uses less() API: ................. ??? // uses display APIs pastInput(), upcomingInput(), showPosition(): // ............................. ??? // uses describeYYLLOC() API: ....... ??? // // --------- END OF REPORT ----------- EOF: 1, ERROR: 2, // JisonLexerError: JisonLexerError, /// <-- injected by the code generator // options: {}, /// <-- injected by the code generator // yy: ..., /// <-- injected by setInput() __currentRuleSet__: null, /// INTERNAL USE ONLY: internal rule set cache for the current lexer state __error_infos: [], /// INTERNAL USE ONLY: the set of lexErrorInfo objects created since the last cleanup __decompressed: false, /// INTERNAL USE ONLY: mark whether the lexer instance has been 'unfolded' completely and is now ready for use done: false, /// INTERNAL USE ONLY _backtrack: false, /// INTERNAL USE ONLY _input: '', /// INTERNAL USE ONLY _more: false, /// INTERNAL USE ONLY _signaled_error_token: false, /// INTERNAL USE ONLY conditionStack: [], /// INTERNAL USE ONLY; managed via `pushState()`, `popState()`, `topState()` and `stateStackSize()` match: '', /// READ-ONLY EXTERNAL ACCESS - ADVANCED USE ONLY: tracks input which has been matched so far for the lexer token under construction. `match` is identical to `yytext` except that this one still contains the matched input string after `lexer.performAction()` has been invoked, where userland code MAY have changed/replaced the `yytext` value entirely! matched: '', /// READ-ONLY EXTERNAL ACCESS - ADVANCED USE ONLY: tracks entire input which has been matched so far matches: false, /// READ-ONLY EXTERNAL ACCESS - ADVANCED USE ONLY: tracks RE match result for last (successful) match attempt yytext: '', /// ADVANCED USE ONLY: tracks input which has been matched so far for the lexer token under construction; this value is transferred to the parser as the 'token value' when the parser consumes the lexer token produced through a call to the `lex()` API. offset: 0, /// READ-ONLY EXTERNAL ACCESS - ADVANCED USE ONLY: tracks the 'cursor position' in the input string, i.e. the number of characters matched so far. (**WARNING:** this value MAY be negative if you `unput()` more text than you have already lexed. This type of behaviour is generally observed for one kind of 'lexer/parser hack' where custom token-illiciting characters are pushed in front of the input stream to help simulate multiple-START-points in the parser. When this happens, `base_position` will be adjusted to help track the original input's starting point in the `_input` buffer.) base_position: 0, /// READ-ONLY EXTERNAL ACCESS - ADVANCED USE ONLY: index to the original starting point of the input; always ZERO(0) unless `unput()` has pushed content before the input: see the `offset` **WARNING** just above. yyleng: 0, /// READ-ONLY EXTERNAL ACCESS - ADVANCED USE ONLY: length of matched input for the token under construction (`yytext`) yylineno: 0, /// READ-ONLY EXTERNAL ACCESS - ADVANCED USE ONLY: 'line number' at which the token under construction is located yylloc: null, /// READ-ONLY EXTERNAL ACCESS - ADVANCED USE ONLY: tracks location info (lines + columns) for the token under construction CRLF_Re: /\r\n?|\n/, /// READ-ONLY EXTERNAL ACCESS - ADVANCED USE ONLY: regex used to split lines while tracking the lexer cursor position. /** * INTERNAL USE: construct a suitable error info hash object instance for `parseError`. * * @public * @this {RegExpLexer} */ constructLexErrorInfo: function lexer_constructLexErrorInfo(msg, recoverable, show_input_position) { msg = '' + msg; // heuristic to determine if the error message already contains a (partial) source code dump // as produced by either `showPosition()` or `prettyPrintRange()`: if (show_input_position == undefined) { show_input_position = !(msg.indexOf('\n') > 0 && msg.indexOf('^') > 0); } if (this.yylloc && show_input_position) { if (typeof this.prettyPrintRange === 'function') { var pretty_src = this.prettyPrintRange(this.yylloc); if (!/\n\s*$/.test(msg)) { msg += '\n'; } msg += '\n Erroneous area:\n' + this.prettyPrintRange(this.yylloc); } else if (typeof this.showPosition === 'function') { var pos_str = this.showPosition(); if (pos_str) { if (msg.length && msg[msg.length - 1] !== '\n' && pos_str[0] !== '\n') { msg += '\n' + pos_str; } else { msg += pos_str; } } } } /** @constructor */ var pei = { errStr: msg, recoverable: !!recoverable, text: this.match, // This one MAY be empty; userland code should use the `upcomingInput` API to obtain more text which follows the 'lexer cursor position'... token: null, line: this.yylineno, loc: this.yylloc, yy: this.yy, lexer: this, /** * and make sure the error info doesn't stay due to potential * ref cycle via userland code manipulations. * These would otherwise all be memory leak opportunities! * * Note that only array and object references are nuked as those * constitute the set of elements which can produce a cyclic ref. * The rest of the members is kept intact as they are harmless. * * @public * @this {LexErrorInfo} */ destroy: function destructLexErrorInfo() { // remove cyclic references added to error info: // info.yy = null; // info.lexer = null; // ... var rec = !!this.recoverable; for (var key in this) { if (this.hasOwnProperty(key) && typeof key === 'object') { this[key] = undefined; } } this.recoverable = rec; } }; // track this instance so we can `destroy()` it once we deem it superfluous and ready for garbage collection! this.__error_infos.push(pei); return pei; }, /** * handler which is invoked when a lexer error occurs. * * @public * @this {RegExpLexer} */ parseError: function lexer_parseError(str, hash, ExceptionClass) { if (!ExceptionClass) { ExceptionClass = this.JisonLexerError; } if (this.yy) { if (this.yy.parser && typeof this.yy.parser.parseError === 'function') { return this.yy.parser.parseError.call(this, str, hash, ExceptionClass) || this.ERROR; } else if (typeof this.yy.parseError === 'function') { return this.yy.parseError.call(this, str, hash, ExceptionClass) || this.ERROR; } } throw new ExceptionClass(str, hash); }, /** * method which implements `yyerror(str, ...args)` functionality for use inside lexer actions. * * @public * @this {RegExpLexer} */ yyerror: function yyError(str /*, ...args */) { var lineno_msg = ''; if (this.yylloc) { lineno_msg = ' on line ' + (this.yylineno + 1); } var p = this.constructLexErrorInfo( 'Lexical error' + lineno_msg + ': ' + str, this.options.lexerErrorsAreRecoverable ); // Add any extra args to the hash under the name `extra_error_attributes`: var args = Array.prototype.slice.call(arguments, 1); if (args.length) { p.extra_error_attributes = args; } return this.parseError(p.errStr, p, this.JisonLexerError) || this.ERROR; }, /** * final cleanup function for when we have completed lexing the input; * make it an API so that external code can use this one once userland * code has decided it's time to destroy any lingering lexer error * hash object instances and the like: this function helps to clean * up these constructs, which *may* carry cyclic references which would * otherwise prevent the instances from being properly and timely * garbage-collected, i.e. this function helps prevent memory leaks! * * @public * @this {RegExpLexer} */ cleanupAfterLex: function lexer_cleanupAfterLex(do_not_nuke_errorinfos) { // prevent lingering circular references from causing memory leaks: this.setInput('', {}); // nuke the error hash info instances created during this run. // Userland code must COPY any data/references // in the error hash instance(s) it is more permanently interested in. if (!do_not_nuke_errorinfos) { for (var i = this.__error_infos.length - 1; i >= 0; i--) { var el = this.__error_infos[i]; if (el && typeof el.destroy === 'function') { el.destroy(); } } this.__error_infos.length = 0; } return this; }, /** * clear the lexer token context; intended for internal use only * * @public * @this {RegExpLexer} */ clear: function lexer_clear() { this.yytext = ''; this.yyleng = 0; this.match = ''; // - DO NOT reset `this.matched` this.matches = false; this._more = false; this._backtrack = false; var col = (this.yylloc ? this.yylloc.last_column : 0); this.yylloc = { first_line: this.yylineno + 1, first_column: col, last_line: this.yylineno + 1, last_column: col, range: [this.offset, this.offset] }; }, /** * resets the lexer, sets new input * * @public * @this {RegExpLexer} */ setInput: function lexer_setInput(input, yy) { this.yy = yy || this.yy || {}; // also check if we've fully initialized the lexer instance, // including expansion work to be done to go from a loaded // lexer to a usable lexer: if (!this.__decompressed) { // step 1: decompress the regex list: var rules = this.rules; for (var i = 0, len = rules.length; i < len; i++) { var rule_re = rules[i]; // compression: is the RE an xref to another RE slot in the rules[] table? if (typeof rule_re === 'number') { rules[i] = rules[rule_re]; } } // step 2: unfold the conditions[] set to make these ready for use: var conditions = this.conditions; for (var k in conditions) { var spec = conditions[k]; var rule_ids = spec.rules; var len = rule_ids.length; var rule_regexes = new Array(len + 1); // slot 0 is unused; we use a 1-based index approach here to keep the hottest code in `lexer_next()` fast and simple! var rule_new_ids = new Array(len + 1); for (var i = 0; i < len; i++) { var idx = rule_ids[i]; var rule_re = rules[idx]; rule_regexes[i + 1] = rule_re; rule_new_ids[i + 1] = idx; } spec.rules = rule_new_ids; spec.__rule_regexes = rule_regexes; spec.__rule_count = len; } this.__decompressed = true; } this._input = input || ''; this.clear(); this._signaled_error_token = false; this.done = false; this.yylineno = 0; this.matched = ''; this.conditionStack = ['INITIAL']; this.__currentRuleSet__ = null; this.yylloc = { first_line: 1, first_column: 0, last_line: 1, last_column: 0, range: [0, 0] }; this.offset = 0; this.base_position = 0; return this; }, /** * edit the remaining input via user-specified callback. * This can be used to forward-adjust the input-to-parse, * e.g. inserting macro expansions and alike in the * input which has yet to be lexed. * The behaviour of this API contrasts the `unput()` et al * APIs as those act on the *consumed* input, while this * one allows one to manipulate the future, without impacting * the current `yyloc` cursor location or any history. * * Use this API to help implement C-preprocessor-like * `#include` statements, etc. * * The provided callback must be synchronous and is * expected to return the edited input (string). * * The `cpsArg` argument value is passed to the callback * as-is. * * `callback` interface: * `function callback(input, cpsArg)` * * - `input` will carry the remaining-input-to-lex string * from the lexer. * - `cpsArg` is `cpsArg` passed into this API. * * The `this` reference for the callback will be set to * reference this lexer instance so that userland code * in the callback can easily and quickly access any lexer * API. * * When the callback returns a non-string-type falsey value, * we assume the callback did not edit the input and we * will using the input as-is. * * When the callback returns a non-string-type value, it * is converted to a string for lexing via the `"" + retval` * operation. (See also why: http://2ality.com/2012/03/converting-to-string.html * -- that way any returned object's `toValue()` and `toString()` * methods will be invoked in a proper/desirable order.) * * @public * @this {RegExpLexer} */ editRemainingInput: function lexer_editRemainingInput(callback, cpsArg) { var rv = callback.call(this, this._input, cpsArg); if (typeof rv !== 'string') { if (rv) { this._input = '' + rv; } // else: keep `this._input` as is. } else { this._input = rv; } return this; }, /** * consumes and returns one char from the input * * @public * @this {RegExpLexer} */ input: function lexer_input() { if (!this._input) { //this.done = true; -- don't set `done` as we want the lex()/next() API to be able to produce one custom EOF token match after this anyhow. (lexer can match special <<EOF>> tokens and perform user action code for a <<EOF>> match, but only does so *once*) return null; } var ch = this._input[0]; this.yytext += ch; this.yyleng++; this.offset++; this.match += ch; this.matched += ch; // Count the linenumber up when we hit the LF (or a stand-alone CR). // On CRLF, the linenumber is incremented when you fetch the CR or the CRLF combo // and we advance immediately past the LF as well, returning both together as if // it was all a single 'character' only. var slice_len = 1; var lines = false; if (ch === '\n') { lines = true; } else if (ch === '\r') { lines = true; var ch2 = this._input[1]; if (ch2 === '\n') { slice_len++; ch += ch2; this.yytext += ch2; this.yyleng++; this.offset++; this.match += ch2; this.matched += ch2; this.yylloc.range[1]++; } } if (lines) { this.yylineno++; this.yylloc.last_line++; this.yylloc.last_column = 0; } else { this.yylloc.last_column++; } this.yylloc.range[1]++; this._input = this._input.slice(slice_len); return ch; }, /** * unshifts one char (or an entire string) into the input * * @public * @this {RegExpLexer} */ unput: function lexer_unput(ch) { var len = ch.length; var lines = ch.split(this.CRLF_Re); this._input = ch + this._input; this.yytext = this.yytext.substr(0, this.yytext.length - len); this.yyleng = this.yytext.length; this.offset -= len; // **WARNING:** // The `offset` value MAY be negative if you `unput()` more text than you have already lexed. // This type of behaviour is generally observed for one kind of 'lexer/parser hack' // where custom token-illiciting characters are pushed in front of the input stream to help // simulate multiple-START-points in the parser. // When this happens, `base_position` will be adjusted to help track the original input's // starting point in the `_input` buffer. if (-this.offset > this.base_position) { this.base_position = -this.offset; } this.match = this.match.substr(0, this.match.length - len); this.matched = this.matched.substr(0, this.matched.length - len); if (lines.length > 1) { this.yylineno -= lines.length - 1; this.yylloc.last_line = this.yylineno + 1; // Get last entirely matched line into the `pre_lines[]` array's // last index slot; we don't mind when other previously // matched lines end up in the array too. var pre = this.match; var pre_lines = pre.split(this.CRLF_Re); if (pre_lines.length === 1) { pre = this.matched; pre_lines = pre.split(this.CRLF_Re); } this.yylloc.last_column = pre_lines[pre_lines.length - 1].length; } else { this.yylloc.last_column -= len; } this.yylloc.range[1] = this.yylloc.range[0] + this.yyleng; this.done = false; return this; }, /** * return the upcoming input *which has not been lexed yet*. * This can, for example, be used for custom look-ahead inspection code * in your lexer. * * The entire pending input string is returned. * * > ### NOTE ### * > * > When augmenting error reports and alike, you might want to * > look at the `upcomingInput()` API instead, which offers more * > features for limited input extraction and which includes the * > part of the input which has been lexed by the last token a.k.a. * > the *currently lexed* input. * > * * @public * @this {RegExpLexer} */ lookAhead: function lexer_lookAhead() { return this._input || ''; }, /** * cache matched text and append it on next action * * @public * @this {RegExpLexer} */ more: function lexer_more() { this._more = true; return this; }, /** * signal the lexer that this rule fails to match the input, so the * next matching rule (regex) should be tested instead. * * @public * @this {RegExpLexer} */ reject: function lexer_reject() { if (this.options.backtrack_lexer) { this._backtrack = true; } else { // when the `parseError()` call returns, we MUST ensure that the error is registered. // We accomplish this by signaling an 'error' token to be produced for the current // `.lex()` run. var lineno_msg = ''; if (this.yylloc) { lineno_msg = ' on line ' + (this.yylineno + 1); } var p = this.constructLexErrorInfo( 'Lexical error' + lineno_msg + ': You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).', false ); this._signaled_error_token = this.parseError(p.errStr, p, this.JisonLexerError) || this.ERROR; } return this; }, /** * retain first n characters of the match * * @public * @this {RegExpLexer} */ less: function lexer_less(n) { return this.unput(this.match.slice(n)); }, /** * return (part of the) already matched input, i.e. for error * messages. * * Limit the returned string length to `maxSize` (default: 20). * * Limit the returned string to the `maxLines` number of lines of * input (default: 1). * * A negative `maxSize` limit value equals *unlimited*, i.e. * produce the entire input that has already been lexed. * * A negative `maxLines` limit value equals *unlimited*, i.e. limit the result * to the `maxSize` specified number of characters *only*. * * @public * @this {RegExpLexer} */ pastInput: function lexer_pastInput(maxSize, maxLines) { var past = this.matched.substring(0, this.matched.length - this.match.length); if (maxSize < 0) maxSize = past.length; else if (!maxSize) maxSize = 20; if (maxLines < 0) maxLines = past.length; // can't ever have more input lines than this! else if (!maxLines) maxLines = 1; // `substr` anticipation: treat \r\n as a single character and take a little // more than necessary so that we can still properly check against maxSize // after we've transformed and limited the newLines in here: past = past.substr(-maxSize * 2 - 2); // now that we have a significantly reduced string to process, transform the newlines // and chop them, then limit them: var a = past.split(this.CRLF_Re); a = a.slice(-maxLines); past = a.join('\n'); // When, after limiting to maxLines, we still have too much to return, // do add an ellipsis prefix... if (past.length > maxSize) { past = '...' + past.substr(-maxSize); } return past; }, /** * return (part of the) upcoming input *including* the input * matched by the last token (see also the NOTE below). * This can be used to augment error messages, for example. * * Limit the returned string length to `maxSize` (default: 20). * * Limit the returned string to the `maxLines` number of lines of input (default: 1). * * A negative `maxSize` limit value equals *unlimited*, i.e. * produce the entire input that is yet to be lexed. * * A negative `maxLines` limit value equals *unlimited*, i.e. limit the result * to the `maxSize` specified number of characters *only*. * * > ### NOTE ### * > * > *"upcoming input"* is defined as the whole of the both * > the *currently lexed* input, together with any remaining input * > following that. *"currently lexed"* input is the input * > already recognized by the lexer but not yet returned with * > the lexer token. This happens when you are invoking this API * > from inside any lexer rule action code block. * > * > When you want access to the 'upcoming input' in that you want access * > to the input *which has not been lexed yet* for look-ahead * > inspection or likewise purposes, please consider using the * > `lookAhead()` API instead. * > * * @public * @this {RegExpLexer} */ upcomingInput: function lexer_upcomingInput(maxSize, maxLines) { var next = this.match; var source = this._input || ''; if (maxSize < 0) maxSize = next.length + source.length; else if (!maxSize) maxSize = 20; if (maxLines < 0) maxLines = maxSize; // can't ever have more input lines than this! else if (!maxLines) maxLines = 1; // `substring` anticipation: treat \r\n as a single character and take a little // more than necessary so that we can still properly check against maxSize // after we've transformed and limited the newLines in here: if (next.length < maxSize * 2 + 2) { next += source.substring(0, maxSize * 2 + 2 - next.length); // substring is faster on Chrome/V8 } // now that we have a significantly reduced string to process, transform the newlines // and chop them, then limit them: var a = next.split(this.CRLF_Re, maxLines + 1); // stop splitting once we have reached just beyond the reuired number of lines. a = a.slice(0, maxLines); next = a.join('\n'); // When, after limiting to maxLines, we still have too much to return, // do add an ellipsis postfix... if (next.length > maxSize) { next = next.substring(0, maxSize) + '...'; } return next; }, /** * return a string which displays the character position where the * lexing error occurred, i.e. for error messages * * @public * @this {RegExpLexer} */ showPosition: function lexer_showPosition(maxPrefix, maxPostfix) { var pre = this.pastInput(maxPrefix).replace(/\s/g, ' '); var c = new Array(pre.length + 1).join('-'); return pre + this.upcomingInput(maxPostfix).replace(/\s/g, ' ') + '\n' + c + '^'; }, /** * return an YYLLOC info object derived off the given context (actual, preceding, following, current). * Use this method when the given `actual` location is not guaranteed to exist (i.e. when * it MAY be NULL) and you MUST have a valid location info object anyway: * then we take the given context of the `preceding` and `following` locations, IFF those are available, * and reconstruct the `actual` location info from those. * If this fails, the heuristic is to take the `current` location, IFF available. * If this fails as well, we assume the sought location is at/around the current lexer position * and then produce that one as a response. DO NOTE that these heuristic/derived location info * values MAY be inaccurate! * * NOTE: `deriveLocationInfo()` ALWAYS produces a location info object *copy* of `actual`, not just * a *reference* hence all input location objects can be assumed to be 'constant' (function has no side-effects). * * @public * @this {RegExpLexer} */ deriveLocationInfo: function lexer_deriveYYLLOC(actual, preceding, following, current) { var loc = { first_line: 1, first_column: 0, last_line: 1, last_column: 0, range: [0, 0] }; if (actual) { loc.first_line = actual.first_line | 0; loc.last_line = actual.last_line | 0; loc.first_column = actual.first_column | 0; loc.last_column = actual.last_column | 0; if (actual.range) { loc.range[0] = actual.range[0] | 0; loc.range[1] = actual.range[1] | 0; } } if (loc.first_line <= 0 || loc.last_line < loc.first_line) { // plan B: heuristic using preceding and following: if (loc.first_line <= 0 && preceding) { loc.first_line = preceding.last_line | 0; loc.first_column = preceding.last_column | 0; if (preceding.range) { loc.range[0] = actual.range[1] | 0; } } if ((loc.last_line <= 0 || loc.last_line < loc.first_line) && following) { loc.last_line = following.first_line | 0; loc.last_column = following.first_column | 0; if (following.range) { loc.range[1] = actual.range[0] | 0; } } // plan C?: see if the 'current' location is useful/sane too: if (loc.first_line <= 0 && current && (loc.last_line <= 0 || current.last_line <= loc.last_line)) { loc.first_line = current.first_line | 0; loc.first_column = current.first_column | 0; if (current.range) { loc.range[0] = current.range[0] | 0; } } if (loc.last_line <= 0 && current && (loc.first_line <= 0 || current.first_line >= loc.first_line)) { loc.last_line = current.last_line | 0; loc.last_column = current.last_column | 0; if (current.range) { loc.range[1] = current.range[1] | 0; } } } // sanitize: fix last_line BEFORE we fix first_line as we use the 'raw' value of the latter // or plan D heuristics to produce a 'sensible' last_line value: if (loc.last_line <= 0) { if (loc.first_line <= 0) { loc.first_line = this.yylloc.first_line; loc.last_line = this.yylloc.last_line; loc.first_column = this.yylloc.first_column; loc.last_column = this.yylloc.last_column; loc.range[0] = this.yylloc.range[0]; loc.range[1] = this.yylloc.range[1]; } else { loc.last_line = this.yylloc.last_line; loc.last_column = this.yylloc.last_column; loc.range[1] = this.yylloc.range[1]; } } if (loc.first_line <= 0) { loc.first_line = loc.last_line; loc.first_column = 0; // loc.last_column; loc.range[1] = loc.range[0]; } if (loc.first_column < 0) { loc.first_column = 0; } if (loc.last_column < 0) { loc.last_column = (loc.first_column > 0 ? loc.first_column : 80); } return loc; }, /** * return a string which displays the lines & columns of input which are referenced * by the given location info range, plus a few lines of context. * * This function pretty-prints the indicated section of the input, with line numbers * and everything! * * This function is very useful to provide highly readable error reports, while * the location range may be specified in various flexible ways: * * - `loc` is the location info object which references the area which should be * displayed and 'marked up': these lines & columns of text are marked up by `^` * characters below each character in the entire input range. * * - `context_loc` is the *optional* location info object which instructs this * pretty-printer how much *leading* context should be displayed alongside * the area referenced by `loc`. This can help provide context for the displayed * error, etc. * * When this location info is not provided, a default context of 3 lines is * used. * * - `context_loc2` is another *optional* location info object, which serves * a similar purpose to `context_loc`: it specifies the amount of *trailing* * context lines to display in the pretty-print output. * * When this location info is not provided, a default context of 1 line only is * used. * * Special Notes: * * - when the `loc`-indicated range is very large (about 5 lines or more), then * only the first and last few lines of this block are printed while a * `...continued...` message will be printed between them. * * This serves the purpose of not printing a huge amount of text when the `loc` * range happens to be huge: this way a manageable & readable output results * for arbitrary large ranges. * * - this function can display lines of input which whave not yet been lexed. * `prettyPrintRange()` can access the entire input! * * @public * @this {RegExpLexer} */ prettyPrintRange: function lexer_prettyPrintRange(loc, context_loc, context_loc2) { loc = this.deriveLocationInfo(loc, context_loc, context_loc2); const CONTEXT = 3; const CONTEXT_TAIL = 1; const MINIMUM_VISIBLE_NONEMPTY_LINE_COUNT = 2; var input = this.matched + (this._input || ''); var lines = input.split('\n'); var l0 = Math.max(1, (context_loc ? context_loc.first_line : loc.first_line - CONTEXT)); var l1 = Math.max(1, (context_loc2 ? context_loc2.last_line : loc.last_line + CONTEXT_TAIL)); var lineno_display_width = 1 + Math.log10(l1 | 1) | 0; var ws_prefix = new Array(lineno_display_width).join(' '); var nonempty_line_indexes = [[], [], []]; var rv = lines.slice(l0 - 1, l1 + 1).map(function injectLineNumber(line, index) { var lno = index + l0; var lno_pfx = (ws_prefix + lno).substr(-lineno_display_width); var rv = lno_pfx + ': ' + line; var errpfx = new Array(lineno_display_width + 1).join('^'); var offset = 2 + 1; var len = 0; if (lno === loc.first_line) { offset += loc.first_column; len = Math.max( 2, ((lno === loc.last_line ? loc.last_column : line.length)) - loc.first_column + 1 ); } else if (lno === loc.last_line) { len = Math.max(2, loc.last_column + 1); } else if (lno > loc.first_line && lno < loc.last_line) { len = Math.max(2, line.length + 1); } var nli; if (len) { var lead = new Array(offset).join('.'); var mark = new Array(len).join('^'); rv += '\n' + errpfx + lead + mark; nli = 1; } else if (lno < loc.first_line) { nli = 0; } else if (lno > loc.last_line) { nli = 2; } if (line.trim().length > 0) { nonempty_line_indexes[nli].push(index); } rv = rv.replace(/\t/g, ' '); return rv; }); // now make sure we don't print an overly large amount of lead/error/tail area: limit it // to the top and bottom line count: for (var i = 0; i <= 2; i++) { var line_arr = nonempty_line_indexes[i]; if (line_arr.length > 2 * MINIMUM_VISIBLE_NONEMPTY_LINE_COUNT) { var clip_start = line_arr[MINIMUM_VISIBLE_NONEMPTY_LINE_COUNT - 1] + 1; var clip_end = line_arr[line_arr.length - MINIMUM_VISIBLE_NONEMPTY_LINE_COUNT] - 1; var intermediate_line = new Array(lineno_display_width + 1).join(' ') + ' (...continued...)'; if (i === 1) { intermediate_line += '\n' + new Array(lineno_display_width + 1).join('-') + ' (---------------)'; } rv.splice(clip_start, clip_end - clip_start + 1, intermediate_line); } } return rv.join('\n'); }, /** * helper function, used to produce a human readable description as a string, given * the input `yylloc` location object. * * Set `display_range_too` to TRUE to include the string character index position(s) * in the description if the `yylloc.range` is available. * * @public * @this {RegExpLexer} */ describeYYLLOC: function lexer_describe_yylloc(yylloc, display_range_too) { var l1 = yylloc.first_line; var l2 = yylloc.last_line; var c1 = yylloc.first_column; var c2 = yylloc.last_column; var dl = l2 - l1; var dc = c2 - c1; var rv; if (dl === 0) { rv = 'line ' + l1 + ', '; if (dc <= 1) { rv += 'column ' + c1; } else { rv += 'columns ' + c1 + ' .. ' + c2; } } else { rv = 'lines ' + l1 + '(column ' + c1 + ') .. ' + l2 + '(column ' + c2 + ')'; } if (yylloc.range && display_range_too) { var r1 = yylloc.range[0]; var r2 = yylloc.range[1] - 1; if (r2 <= r1) { rv += ' {String Offset: ' + r1 + '}'; } else { rv += ' {String Offset range: ' + r1 + ' .. ' + r2 + '}'; } } return rv; }, /** * test the lexed token: return FALSE when not a match, otherwise return token. * * `match` is supposed to be an array coming out of a regex match, i.e. `match[0]` * contains the actually matched text string. * * Also move the input cursor forward and update the match collectors: * * - `yytext` * - `yyleng` * - `match` * - `matches` * - `yylloc` * - `offset` * * @public * @this {RegExpLexer} */ test_match: function lexer_test_match(match, indexed_rule) { var token, lines, backup, match_str, match_str_len; if (this.options.backtrack_lexer) { // save context backup = { yylineno: this.yylineno, yylloc: { first_line: this.yylloc.first_line, last_line: this.yylloc.last_line, first_column: this.yylloc.first_column, last_column: this.yylloc.last_column, range: this.yylloc.range.slice(0) }, yytext: this.yytext, match: this.match, matches: this.matches, matched: this.matched, yyleng: this.yyleng, offset: this.offset, _more: this._more, _input: this._input, //_signaled_error_token: this._signaled_error_token, yy: this.yy, conditionStack: this.conditionStack.slice(0), done: this.done }; } match_str = match[0]; match_str_len = match_str.length; // if (match_str.indexOf('\n') !== -1 || match_str.indexOf('\r') !== -1) { lines = match_str.split(this.CRLF_Re); if (lines.length > 1) { this.yylineno += lines.length - 1; this.yylloc.last_line = this.yylineno + 1; this.yylloc.last_column = lines[lines.length - 1].length; } else { this.yylloc.last_column += match_str_len; } // } this.yytext += match_str; this.match += match_str; this.matched += match_str; this.matches = match; this.yyleng = this.yytext.length; this.yylloc.range[1] += match_str_len; // previous lex rules MAY have invoked the `more()` API rather than producing a token: // those rules will already have moved this `offset` forward matching their match lengths, // hence we must only add our own match length now: this.offset += match_str_len; this._more = false; this._backtrack = false; this._input = this._input.slice(match_str_len); // calling this method: // // function lexer__performAction(yy, yyrulenumber, YY_START) {...} token = this.performAction.call( this, this.yy, indexed_rule, this.conditionStack[this.conditionStack.length - 1] /* = YY_START */ ); // otherwise, when the action codes are all simple return token statements: //token = this.simpleCaseActionClusters[indexed_rule]; if (this.done && this._input) { this.done = false; } if (token) { return token; } else if (this._backtrack) { // recover context for (var k in backup) { this[k] = backup[k]; } this.__currentRuleSet__ = null; return false; // rule action called reject() implying the next rule should be tested instead. } else if (this._signaled_error_token) { // produce one 'error' token as `.parseError()` in `reject()` // did not guarantee a failure signal by throwing an exception! token = this._signaled_error_token; this._signaled_error_token = false; return token; } return false; }, /** * return next match in input * * @public * @this {RegExpLexer} */ next: function lexer_next() { if (this.done) { this.clear(); return this.EOF; } if (!this._input) { this.done = true; } var token, match, tempMatch, index; if (!this._more) { this.clear(); } var spec = this.__currentRuleSet__; if (!spec) { // Update the ruleset cache as we apparently encountered a state change or just started lexing. // The cache is set up for fast lookup -- we assume a lexer will switch states much less often than it will // invoke the `lex()` token-producing API and related APIs, hence caching the set for direct access helps // speed up those activities a tiny bit. spec = this.__currentRuleSet__ = this._currentRules(); // Check whether a *sane* condition has been pushed before: this makes the lexer robust against // user-programmer bugs such as https://github.com/zaach/jison-lex/issues/19 if (!spec || !spec.rules) { var lineno_msg = ''; if (this.options.trackPosition) { lineno_msg = ' on line ' + (this.yylineno + 1); } var p = this.constructLexErrorInfo( 'Internal lexer engine error' + lineno_msg + ': The lex grammar programmer pushed a non-existing condition name "' + this.topState() + '"; this is a fatal error and should be reported to the application programmer team!', false ); // produce one 'error' token until this situation has been resolved, most probably by parse termination! return this.parseError(p.errStr, p, this.JisonLexerError) || this.ERROR; } } var rule_ids = spec.rules; var regexes = spec.__rule_regexes; var len = spec.__rule_count; // Note: the arrays are 1-based, while `len` itself is a valid index, // hence the non-standard less-or-equal check in the next loop condition! for (var i = 1; i <= len; i++) { tempMatch = this._input.match(regexes[i]); if (tempMatch && (!match || tempMatch[0].length > match[0].length)) { match = tempMatch; index = i; if (this.options.backtrack_lexer) { token = this.test_match(tempMatch, rule_ids[i]); if (token !== false) { return token; } else if (this._backtrack) { match = undefined; continue; // rule action called reject() implying a rule MISmatch. } else { // else: this is a lexer rule which consumes input without producing a token (e.g. whitespace) return false; } } else if (!this.options.flex) { break; } } } if (match) { token = this.test_match(match, rule_ids[index]); if (token !== false) { return token; } // else: this is a lexer rule which consumes input without producing a token (e.g. whitespace) return false; } if (!this._input) { this.done = true; this.clear(); return this.EOF; } else { var lineno_msg = ''; if (this.options.trackPosition) { lineno_msg = ' on line ' + (this.yylineno + 1); } var p = this.constructLexErrorInfo( 'Lexical error' + lineno_msg + ': Unrecognized text.', this.options.lexerErrorsAreRecoverable ); var pendingInput = this._input; var activeCondition = this.topState(); var conditionStackDepth = this.conditionStack.length; token = this.parseError(p.errStr, p, this.JisonLexerError) || this.ERROR; if (token === this.ERROR) { // we can try to recover from a lexer error that `parseError()` did not 'recover' for us // by moving forward at least one character at a time IFF the (user-specified?) `parseError()` // has not consumed/modified any pending input or changed state in the error handler: if (!this.matches && // and make sure the input has been modified/consumed ... pendingInput === this._input && // ...or the lexer state has been modified significantly enough // to merit a non-consuming error handling action right now. activeCondition === this.topState() && conditionStackDepth === this.conditionStack.length) { this.input(); } } return token; } }, /** * return next match that has a token * * @public * @this {RegExpLexer} */ lex: function lexer_lex() { var r; // allow the PRE/POST handlers set/modify the return token for maximum flexibility of the generated lexer: if (typeof this.pre_lex === 'function') { r = this.pre_lex.call(this, 0); } if (typeof this.options.pre_lex === 'function') { // (also account for a userdef function which does not return any value: keep the token as is) r = this.options.pre_lex.call(this, r) || r; } if (this.yy && typeof this.yy.pre_lex === 'function') { // (also account for a userdef function which does not return any value: keep the token as is) r = this.yy.pre_lex.call(this, r) || r; } while (!r) { r = this.next(); } if (this.yy && typeof this.yy.post_lex === 'function') { // (also account for a userdef function which does not return any value: keep the token as is) r = this.yy.post_lex.call(this, r) || r; } if (typeof this.options.post_lex === 'function') { // (also account for a userdef function which does not return any value: keep the token as is) r = this.options.post_lex.call(this, r) || r; } if (typeof this.post_lex === 'function') { // (also account for a userdef function which does not return any value: keep the token as is) r = this.post_lex.call(this, r) || r; } return r; }, /** * return next match that has a token. Identical to the `lex()` API but does not invoke any of the * `pre_lex()` nor any of the `post_lex()` callbacks. * * @public * @this {RegExpLexer} */ fastLex: function lexer_fastLex() { var r; while (!r) { r = this.next(); } return r; }, /** * return info about the lexer state that can help a parser or other lexer API user to use the * most efficient means available. This API is provided to aid run-time performance for larger * systems which employ this lexer. * * @public * @this {RegExpLexer} */ canIUse: function lexer_canIUse() { var rv = { fastLex: !(typeof this.pre_lex === 'function' || typeof this.options.pre_lex === 'function' || this.yy && typeof this.yy.pre_lex === 'function' || this.yy && typeof this.yy.post_lex === 'function' || typeof this.options.post_lex === 'function' || typeof this.post_lex === 'function') && typeof this.fastLex === 'function' }; return rv; }, /** * backwards compatible alias for `pushState()`; * the latter is symmetrical with `popState()` and we advise to use * those APIs in any modern lexer code, rather than `begin()`. * * @public * @this {RegExpLexer} */ begin: function lexer_begin(condition) { return this.pushState(condition); }, /** * activates a new lexer condition state (pushes the new lexer * condition state onto the condition stack) * * @public * @this {RegExpLexer} */ pushState: function lexer_pushState(condition) { this.conditionStack.push(condition); this.__currentRuleSet__ = null; return this; }, /** * pop the previously active lexer condition state off the condition * stack * * @public * @this {RegExpLexer} */ popState: function lexer_popState() { var n = this.conditionStack.length - 1; if (n > 0) { this.__currentRuleSet__ = null; return this.conditionStack.pop(); } else { return this.conditionStack[0]; } }, /** * return the currently active lexer condition state; when an index * argument is provided it produces the N-th previous condition state, * if available * * @public * @this {RegExpLexer} */ topState: function lexer_topState(n) { n = this.conditionStack.length - 1 - Math.abs(n || 0); if (n >= 0) { return this.conditionStack[n]; } else { return 'INITIAL'; } }, /** * (internal) determine the lexer rule set which is active for the * currently active lexer condition state * * @public * @this {RegExpLexer} */ _currentRules: function lexer__currentRules() { var n = this.conditionStack.length - 1; var state; if (n >= 0) { state = this.conditionStack[n]; } else { state = 'INITIAL'; } return this.conditions[state] || this.conditions['INITIAL']; }, /** * return the number of states currently on the stack * * @public * @this {RegExpLexer} */ stateStackSize: function lexer_stateStackSize() { return this.conditionStack.length; }, options: { xregexp: true, ranges: true, trackPosition: true, easy_keyword_rules: true }, JisonLexerError: JisonLexerError, performAction: function lexer__performAction(yy, yyrulenumber, YY_START) { var yy_ = this; switch (yyrulenumber) { case 0: /*! Conditions:: INITIAL macro options rules */ /*! Rule:: \/\/[^\r\n]* */ /* skip single-line comment */ break; case 1: /*! Conditions:: INITIAL macro options rules */ /*! Rule:: \/\*[^]*?\*\/ */ /* skip multi-line comment */ break; case 2: /*! Conditions:: action */ /*! Rule:: %\{([^]*?)%\}(?!\}) */ yy_.yytext = this.matches[1]; yy.include_command_allowed = false; return 36; break; case 3: /*! Conditions:: action */ /*! Rule:: %include\b */ if (yy.include_command_allowed) { // This is an include instruction in place of (part of) an action: this.pushState('options'); return 32; } else { // TODO yy_.yyerror(rmCommonWS` %include statements must occur on a line on their own and cannot occur inside an action code block. Its use is not permitted at this position. Erroneous area: ` + this.prettyPrintRange(yy_.yylloc)); return 37; } break; case 4: /*! Conditions:: action */ /*! Rule:: \/\*[^]*?\*\/ */ //yy.include_command_allowed = false; -- doesn't impact include-allowed state return 36; break; case 5: /*! Conditions:: action */ /*! Rule:: \/\/.* */ yy.include_command_allowed = false; return 36; break; case 6: /*! Conditions:: action */ /*! Rule:: \| */ if (yy.depth === 0) { this.popState(); this.unput(yy_.yytext); // yy_.yytext = ''; --- ommitted as this is the side-effect of .unput(yy_.yytext) already! return 24; } else { return 36; } break; case 7: /*! Conditions:: action */ /*! Rule:: %% */ if (yy.depth === 0) { this.popState(); this.unput(yy_.yytext); // yy_.yytext = ''; --- ommitted as this is the side-effect of .unput(yy_.yytext) already! return 24; } else { return 36; } break; case 8: /*! Conditions:: action */ /*! Rule:: \/(?=\s) */ return 36; // most probably a `/` divide operator. break; case 9: /*! Conditions:: action */ /*! Rule:: \/.* */ yy.include_command_allowed = false; var l = scanRegExp(yy_.yytext); if (l > 0) { this.unput(yy_.yytext.substring(l)); yy_.yytext = yy_.yytext.substring(0, l); } else { // assume it's a division operator: this.unput(yy_.yytext.substring(1)); yy_.yytext = yy_.yytext[0]; } return 36; break; case 10: /*! Conditions:: action */ /*! Rule:: "{DOUBLEQUOTED_STRING_CONTENT}"|'{QUOTED_STRING_CONTENT}'|`{ES2017_STRING_CONTENT}` */ yy.include_command_allowed = false; return 36; break; case 11: /*! Conditions:: action */ /*! Rule:: [^/"'`%\{\}\/{BR}]+ */ yy.include_command_allowed = false; return 36; break; case 12: /*! Conditions:: action */ /*! Rule:: % */ yy.include_command_allowed = false; return 36; break; case 13: /*! Conditions:: action */ /*! Rule:: \{ */ yy.depth++; yy.include_command_allowed = false; return 36; break; case 14: /*! Conditions:: action */ /*! Rule:: \} */ yy.include_command_allowed = false; if (yy.depth <= 0) { yy_.yyerror(rmCommonWS` too many closing curly braces in lexer rule action block. Note: the action code chunk may be too complex for jison to parse easily; we suggest you wrap the action code chunk in '%{...%}' to help jison grok more or less complex action code chunks. Erroneous area: ` + this.prettyPrintRange(yy_.yylloc)); return 39; } else { yy.depth--; } return 36; break; case 15: /*! Conditions:: action */ /*! Rule:: (?:[\s\r\n]*?){BR}+{WS}+ */ yy.include_command_allowed = true; return 36; // keep empty lines as-is inside action code blocks. break; case 17: /*! Conditions:: action */ /*! Rule:: {BR} */ if (yy.depth > 0) { yy.include_command_allowed = true; return 36; // keep empty lines as-is inside action code blocks. } else { // end of action code chunk; allow parent mode to see this mode-terminating linebreak too. this.popState(); this.unput(yy_.yytext); // yy_.yytext = ''; --- ommitted as this is the side-effect of .unput(yy_.yytext) already! return 24; } break; case 18: /*! Conditions:: action */ /*! Rule:: $ */ yy.include_command_allowed = false; if (yy.depth !== 0) { yy_.yyerror(rmCommonWS` missing ${yy.depth} closing curly braces in lexer rule action block. Note: the action code chunk may be too complex for jison to parse easily; we suggest you wrap the action code chunk in '%{...%}' to help jison grok more or less complex action code chunks. Erroneous area: ` + this.prettyPrintRange(yy_.yylloc)); return 38; } this.popState(); yy_.yytext = ''; return 24; break; case 19: /*! Conditions:: INITIAL rules code options */ /*! Rule:: [%\{]\{+ */ { yy.depth = 0; yy.include_command_allowed = false; this.pushState('action'); // keep matched string in local variable as the `unput()` call at the end will also 'unput' `yy_.yytext`, // which for our purposes here is highly undesirable (see trimActionCode() use in the BNF parser spec). var marker = yy_.yytext; // check whether this `%{` marker was located at the start of the line: // if it is, we treat it as a different token to signal the grammar we've // got an action which stands on its own, i.e. is not a rule action, %code // section, etc... //var precedingStr = this.pastInput(1,2).replace(/[\r\n]/g, '\n'); //var precedingStr = this.matched.substr(-this.match.length - 1, 1); var precedingStr = this.matched[this.matched.length - this.match.length - 1]; var atSOL = !precedingStr /* @ Start Of File */ || precedingStr === '\n'; // Make sure we've the proper lexer rule regex active for any possible `%{...%}`, `{{...}}` or what have we here? var endMarker = this.setupDelimitedActionChunkLexerRegex(marker); // Early sanity check for better error reporting: // we'd better make sure that end marker indeed does exist in the // remainder of the input! When it's not, we'll have the `action` // lexer state running past its due date as it'll then go and spit // out a 'too may closing braces' error report at some spot way // beyond the intended end of the action code chunk. // // Writing the wrong end marker is a common user mistake, we can // easily look ahead and check for it now and report a proper hint // to cover this failure mode in a more helpful manner. var remaining = this.lookAhead(); var prevEnd = 0; var endMarkerIndex; for (; ; ) { endMarkerIndex = remaining.indexOf(endMarker, prevEnd); // check for both simple non-existence *and* non-match due to trailing braces, // e.g. in this input: `%{{...%}}}` -- note the 3rd curly closing brace. if (endMarkerIndex >= 0 && remaining[endMarkerIndex + endMarker.length] === '}') { prevEnd = endMarkerIndex + endMarker.length; continue; } if (endMarkerIndex < 0) { yy_.yyerror(rmCommonWS` Incorrectly terminated action code block. We're expecting the '${endMarker}' end marker to go with the given start marker. Regrettably, it does not exist in the remainder of the input. Erroneous area: ` + this.prettyPrintRange(yy_.yylloc)); return 25; } break; } // Allow the start marker to be re-matched by the generated lexer rule regex: this.unput(marker); // Now RESET `yy_.yytext` to what it was originally, i.e. un-unput that lexer variable explicitly: yy_.yytext = marker; // and allow the next lexer round to match and execute the suitable lexer rule(s) to parse this incoming action code block. if (atSOL) { return 23; } return 26; } break; case 20: /*! Conditions:: rules macro INITIAL */ /*! Rule:: -> */ yy.depth = 0; yy.include_command_allowed = false; this.pushState('action'); return 35; break; case 21: /*! Conditions:: rules macro INITIAL */ /*! Rule:: → */ yy.depth = 0; yy.include_command_allowed = false; this.pushState('action'); return 35; break; case 22: /*! Conditions:: rules macro INITIAL */ /*! Rule:: => */ yy.depth = 0; yy.include_command_allowed = false; this.pushState('action'); return 35; break; case 23: /*! Conditions:: rules */ /*! Rule:: {WS}+(?!(?:\{\{|\||%|->|=>|→|{WS}|{BR})) */ { { yy.depth = 0; yy.include_command_allowed = true; //console.error('*** ACTION start @ 355:', yy_.yytext); this.pushState('action'); // Do a bit of magic that's useful for the parser when we // call `trimActionCode()` in there to perform a bit of // rough initial action code chunk cleanup: // when we start the action block -- hence *delimit* the // action block -- with a plain old '{' brace, we can // throw that one and its counterpart out safely without // damaging the action code in any way. // // In order to be able to detect that, we look ahead // now and see whether or rule's regex with the fancy // '/!' postcondition check actually hit a '{', which // is the only action code block starter we cannot // detect explicitly using any of the '%{.*?%}' lexer // rules you've seen further above. // // Thanks to this rule's regex, we DO know that the // first look-ahead character will be a non-whitespace // character, which would either be an action code block // delimiter *or* a comment starter. In the latter case // we just throw up our hands and leave code trimming // and analysis to the more advanced systems which // follow after `trimActionCode()` has passed once we // get to the parser productions which process this // upcoming action code block. var la = this.lookAhead(); if (la[0] === '{') { yy_.yytext = '{'; // hint the parser } return 26; } } break; case 24: /*! Conditions:: rules */ /*! Rule:: %% */ this.popState(); this.pushState('code'); return 19; break; case 25: /*! Conditions:: rules */ /*! Rule:: $ */ this.popState(); this.pushState('code'); return 19; break; case 30: /*! Conditions:: options */ /*! Rule:: %%|\||; */ this.popState(); this.unput(yy_.yytext); return 22; break; case 31: /*! Conditions:: options */ /*! Rule:: %include\b */ yy.depth = 0; yy.include_command_allowed = true; this.pushState('action'); // push the parsed '%include' back into the input-to-parse // to trigger the `<action>` state to re-parse it // and issue the desired follow-up token: 'INCLUDE': this.unput(yy_.yytext); return 26; break; case 32: /*! Conditions:: options */ /*! Rule:: > */ this.popState(); this.unput(yy_.yytext); return 22; break; case 35: /*! Conditions:: options */ /*! Rule:: <{ID}> */ yy_.yytext = this.matches[1]; return 'TOKEN_TYPE'; break; case 37: /*! Conditions:: options */ /*! Rule:: {BR}{WS}+(?=\S) */ /* ignore */ break; case 38: /*! Conditions:: options */ /*! Rule:: {BR} */ this.popState(); this.unput(yy_.yytext); return 22; break; case 39: /*! Conditions:: options */ /*! Rule:: {WS}+ */ /* skip whitespace */ break; case 40: /*! Conditions:: INITIAL */ /*! Rule:: {ID} */ this.pushState('macro'); return 20; break; case 41: /*! Conditions:: macro */ /*! Rule:: {BR}+ */ this.popState(); this.unput(yy_.yytext); return 21; break; case 42: /*! Conditions:: macro */ /*! Rule:: $ */ this.popState(); this.unput(yy_.yytext); return 21; break; case 43: /*! Conditions:: rules macro INITIAL */ /*! Rule:: {BR}+ */ /* skip newlines */ break; case 44: /*! Conditions:: rules macro INITIAL */ /*! Rule:: {WS}+ */ /* skip whitespace */ break; case 48: /*! Conditions:: rules macro INITIAL */ /*! Rule:: {ANY_LITERAL_CHAR}+ */ // accept any non-regex, non-lex, non-string-delim, // non-escape-starter, non-space character as-is return 51; break; case 49: /*! Conditions:: rules macro INITIAL */ /*! Rule:: \[ */ this.pushState('set'); return 46; break; case 64: /*! Conditions:: rules macro INITIAL */ /*! Rule:: < */ this.pushState('options'); return 3; break; case 66: /*! Conditions:: rules macro INITIAL */ /*! Rule:: \/! */ return 42; // treated as `(?!atom)` break; case 67: /*! Conditions:: rules macro INITIAL */ /*! Rule:: \/ */ return 13; // treated as `(?=atom)` break; case 69: /*! Conditions:: rules macro INITIAL */ /*! Rule:: \\(?:([0-7]{1,3})|c([@A-Z])|x([0-9a-fA-F]{2})|u([0-9a-fA-F]{4})|u\{([0-9a-fA-F]{1,8})\}) */ var m = this.matches; yy_.yytext = NaN; if (m[1]) { // [1]: octal char: `\012` --> \x0A var v = parseInt(m[1], 8); yy_.yytext = v; } else if (m[2]) { // [2]: CONTROL char: `\cA` --> \u0001 var v = m[2].charCodeAt(0) - 64; yy_.yytext = v; } else if (m[3]) { // [3]: hex char: `\x41` --> A var v = parseInt(m[3], 16); yy_.yytext = v; } else if (m[4]) { // [4]: unicode/UTS2 char: `\u03c0` --> PI var v = parseInt(m[4], 16); yy_.yytext = v; } else if (m[5]) { // [5]: unicode code point: `\u{00003c0}` --> PI var v = parseInt(m[5], 16); yy_.yytext = v; } return 44; break; case 70: /*! Conditions:: rules macro INITIAL */ /*! Rule:: \\. */ yy_.yytext = yy_.yytext.substring(1); return 51; break; case 73: /*! Conditions:: rules macro INITIAL */ /*! Rule:: %option[s]? */ this.pushState('options'); return 29; break; case 74: /*! Conditions:: rules macro INITIAL */ /*! Rule:: %s\b */ this.pushState('options'); return 33; break; case 75: /*! Conditions:: rules macro INITIAL */ /*! Rule:: %x\b */ this.pushState('options'); return 34; break; case 76: /*! Conditions:: rules macro INITIAL */ /*! Rule:: %code\b */ this.pushState('options'); return 31; break; case 77: /*! Conditions:: rules macro INITIAL */ /*! Rule:: %import\b */ this.pushState('options'); return 30; break; case 80: /*! Conditions:: INITIAL rules code */ /*! Rule:: %include\b */ yy.depth = 0; yy.include_command_allowed = true; this.pushState('action'); // push the parsed '%include' back into the input-to-parse // to trigger the `<action>` state to re-parse it // and issue the desired follow-up token: 'INCLUDE': this.unput(yy_.yytext); return 26; break; case 81: /*! Conditions:: INITIAL rules code */ /*! Rule:: %{NAME}([^\r\n]*) */ /* ignore unrecognized decl */ this.warn(rmCommonWS` ignoring unsupported lexer option ${dquote(yy_.yytext)} while lexing in ${dquote(this.topState())} state. Erroneous area: ` + this.prettyPrintRange(yy_.yylloc)); yy_.yytext = { name: this.matches[1], // {NAME} value: this.matches[2].trim() // optional value/parameters }; return 28; break; case 82: /*! Conditions:: rules macro INITIAL */ /*! Rule:: %% */ this.pushState('rules'); return 19; break; case 90: /*! Conditions:: set */ /*! Rule:: \] */ this.popState(); return 47; break; case 91: /*! Conditions:: code */ /*! Rule:: (?:[^%{BR}][^{BR}]*{BR}+)+ */ return 55; // shortcut to grab a large bite at once when we're sure not to encounter any `%include` in there at start-of-line. break; case 93: /*! Conditions:: code */ /*! Rule:: [^{BR}]+ */ return 55; // the bit of CODE just before EOF... break; case 94: /*! Conditions:: action */ /*! Rule:: " */ yy_.yyerror(rmCommonWS` unterminated string constant in lexer rule action block. Erroneous area: ` + this.prettyPrintRange(yy_.yylloc)); return 40; break; case 95: /*! Conditions:: action */ /*! Rule:: ' */ yy_.yyerror(rmCommonWS` unterminated string constant in lexer rule action block. Erroneous area: ` + this.prettyPrintRange(yy_.yylloc)); return 40; break; case 96: /*! Conditions:: action */ /*! Rule:: ` */ yy_.yyerror(rmCommonWS` unterminated string constant in lexer rule action block. Erroneous area: ` + this.prettyPrintRange(yy_.yylloc)); return 40; break; case 97: /*! Conditions:: options */ /*! Rule:: " */ yy_.yyerror(rmCommonWS` unterminated string constant in %options entry. Erroneous area: ` + this.prettyPrintRange(yy_.yylloc)); return 40; break; case 98: /*! Conditions:: options */ /*! Rule:: ' */ yy_.yyerror(rmCommonWS` unterminated string constant in %options entry. Erroneous area: ` + this.prettyPrintRange(yy_.yylloc)); return 40; break; case 99: /*! Conditions:: options */ /*! Rule:: ` */ yy_.yyerror(rmCommonWS` unterminated string constant in %options entry. Erroneous area: ` + this.prettyPrintRange(yy_.yylloc)); return 40; break; case 100: /*! Conditions:: * */ /*! Rule:: " */ var rules = (this.topState() === 'macro' ? 'macro\'s' : this.topState()); yy_.yyerror(rmCommonWS` unterminated string constant encountered while lexing ${rules}. Erroneous area: ` + this.prettyPrintRange(yy_.yylloc)); return 40; break; case 101: /*! Conditions:: * */ /*! Rule:: ' */ var rules = (this.topState() === 'macro' ? 'macro\'s' : this.topState()); yy_.yyerror(rmCommonWS` unterminated string constant encountered while lexing ${rules}. Erroneous area: ` + this.prettyPrintRange(yy_.yylloc)); return 40; break; case 102: /*! Conditions:: * */ /*! Rule:: ` */ var rules = (this.topState() === 'macro' ? 'macro\'s' : this.topState()); yy_.yyerror(rmCommonWS` unterminated string constant encountered while lexing ${rules}. Erroneous area: ` + this.prettyPrintRange(yy_.yylloc)); return 40; break; case 103: /*! Conditions:: macro rules */ /*! Rule:: . */ /* b0rk on bad characters */ var rules = (this.topState() === 'macro' ? 'macro\'s' : this.topState()); yy_.yyerror(rmCommonWS` unsupported lexer input encountered while lexing ${rules} (i.e. jison lex regexes) in ${dquote(this.topState())} state. NOTE: When you want this input to be interpreted as a LITERAL part of a lex rule regex, you MUST enclose it in double or single quotes. If not, then know that this input is not accepted as a valid regex expression here in jison-lex ${rules}. Erroneous area: ` + this.prettyPrintRange(yy_.yylloc)); return 2; break; case 104: /*! Conditions:: options */ /*! Rule:: . */ yy_.yyerror(rmCommonWS` unsupported lexer input: ${dquote(yy_.yytext)} while lexing in ${dquote(this.topState())} state. If this input was intentional, you might want to put quotes around it; any JavaScript string quoting style is accepted (single quotes, double quotes *or* backtick quotes a la ES6 string templates). Erroneous area: ` + this.prettyPrintRange(yy_.yylloc)); return 2; break; case 105: /*! Conditions:: * */ /*! Rule:: . */ yy_.yyerror(rmCommonWS` unsupported lexer input: ${dquote(yy_.yytext)} while lexing in ${dquote(this.topState())} state. Erroneous area: ` + this.prettyPrintRange(yy_.yylloc)); return 2; break; default: return this.simpleCaseActionClusters[yyrulenumber]; } }, simpleCaseActionClusters: { /*! Conditions:: action */ /*! Rule:: {WS}+ */ 16: 36, /*! Conditions:: options */ /*! Rule:: = */ 26: 18, /*! Conditions:: options */ /*! Rule:: "{DOUBLEQUOTED_STRING_CONTENT}" */ 27: 53, /*! Conditions:: options */ /*! Rule:: '{QUOTED_STRING_CONTENT}' */ 28: 53, /*! Conditions:: options */ /*! Rule:: `{ES2017_STRING_CONTENT}` */ 29: 53, /*! Conditions:: options */ /*! Rule:: , */ 33: 17, /*! Conditions:: options */ /*! Rule:: \* */ 34: 11, /*! Conditions:: options */ /*! Rule:: {ANY_LITERAL_CHAR}+ */ 36: 54, /*! Conditions:: rules macro INITIAL */ /*! Rule:: "{DOUBLEQUOTED_STRING_CONTENT}" */ 45: 50, /*! Conditions:: rules macro INITIAL */ /*! Rule:: '{QUOTED_STRING_CONTENT}' */ 46: 50, /*! Conditions:: rules macro INITIAL */ /*! Rule:: `{ES2017_STRING_CONTENT}` */ 47: 50, /*! Conditions:: rules macro INITIAL */ /*! Rule:: \| */ 50: 7, /*! Conditions:: rules macro INITIAL */ /*! Rule:: \(\?: */ 51: 41, /*! Conditions:: rules macro INITIAL */ /*! Rule:: \(\?= */ 52: 41, /*! Conditions:: rules macro INITIAL */ /*! Rule:: \(\?! */ 53: 41, /*! Conditions:: rules macro INITIAL */ /*! Rule:: \(\?<= */ 54: 41, /*! Conditions:: rules macro INITIAL */ /*! Rule:: \(\?<! */ 55: 41, /*! Conditions:: rules macro INITIAL */ /*! Rule:: \( */ 56: 8, /*! Conditions:: rules macro INITIAL */ /*! Rule:: \) */ 57: 9, /*! Conditions:: rules macro INITIAL */ /*! Rule:: \+ */ 58: 10, /*! Conditions:: rules macro INITIAL */ /*! Rule:: \* */ 59: 11, /*! Conditions:: rules macro INITIAL */ /*! Rule:: \? */ 60: 12, /*! Conditions:: rules macro INITIAL */ /*! Rule:: \^ */ 61: 15, /*! Conditions:: rules macro INITIAL */ /*! Rule:: , */ 62: 17, /*! Conditions:: rules macro INITIAL */ /*! Rule:: <<EOF>> */ 63: 16, /*! Conditions:: rules macro INITIAL */ /*! Rule:: > */ 65: 6, /*! Conditions:: rules macro INITIAL */ /*! Rule:: \\(?:[sSbBwWdDpP]|[rfntv\\*+()${}|[\]\/.^?]) */ 68: 43, /*! Conditions:: rules macro INITIAL */ /*! Rule:: \$ */ 71: 16, /*! Conditions:: rules macro INITIAL */ /*! Rule:: \. */ 72: 14, /*! Conditions:: rules macro INITIAL */ /*! Rule:: %pointer\b */ 78: 'FLEX_POINTER_MODE', /*! Conditions:: rules macro INITIAL */ /*! Rule:: %array\b */ 79: 'FLEX_ARRAY_MODE', /*! Conditions:: rules macro INITIAL */ /*! Rule:: \{\d+(,\s*\d+|,)?\} */ 83: 49, /*! Conditions:: rules macro INITIAL */ /*! Rule:: \{{ID}\} */ 84: 45, /*! Conditions:: set options */ /*! Rule:: \{{ID}\} */ 85: 45, /*! Conditions:: rules macro INITIAL */ /*! Rule:: \{ */ 86: 4, /*! Conditions:: rules macro INITIAL */ /*! Rule:: \} */ 87: 5, /*! Conditions:: set */ /*! Rule:: (?:\\[^{BR}]|[^\]{])+ */ 88: 48, /*! Conditions:: set */ /*! Rule:: \{ */ 89: 48, /*! Conditions:: code */ /*! Rule:: [^{BR}]*{BR}+ */ 92: 55, /*! Conditions:: * */ /*! Rule:: $ */ 106: 1 }, rules: [ /* 0: */ /^(?:\/\/[^\r\n]*)/, /* 1: */ /^(?:\/\*[\s\S]*?\*\/)/, /* 2: */ /^(?:%\{([\s\S]*?)%\}(?!\}))/, /* 3: */ /^(?:%include\b)/, /* 4: */ /^(?:\/\*[\s\S]*?\*\/)/, /* 5: */ /^(?:\/\/.*)/, /* 6: */ /^(?:\|)/, /* 7: */ /^(?:%%)/, /* 8: */ /^(?:\/(?=\s))/, /* 9: */ /^(?:\/.*)/, /* 10: */ /^(?:"((?:\\"|\\[^"]|[^\n\r"\\])*)"|'((?:\\'|\\[^']|[^\n\r'\\])*)'|`((?:\\`|\\[^`]|[^\\`])*)`)/, /* 11: */ /^(?:[^\n\r"%'\/`{}]+)/, /* 12: */ /^(?:%)/, /* 13: */ /^(?:\{)/, /* 14: */ /^(?:\})/, /* 15: */ /^(?:(?:\s*?)(\r\n|\n|\r)+([^\S\n\r])+)/, /* 16: */ /^(?:([^\S\n\r])+)/, /* 17: */ /^(?:(\r\n|\n|\r))/, /* 18: */ /^(?:$)/, /* 19: */ /^(?:[%{]\{+)/, /* 20: */ /^(?:->)/, /* 21: */ /^(?:→)/, /* 22: */ /^(?:=>)/, /* 23: */ /^(?:([^\S\n\r])+(?!(?:\{\{|\||%|->|=>|→|([^\S\n\r])|(\r\n|\n|\r))))/, /* 24: */ /^(?:%%)/, /* 25: */ /^(?:$)/, /* 26: */ /^(?:=)/, /* 27: */ /^(?:"((?:\\"|\\[^"]|[^\n\r"\\])*)")/, /* 28: */ /^(?:'((?:\\'|\\[^']|[^\n\r'\\])*)')/, /* 29: */ /^(?:`((?:\\`|\\[^`]|[^\\`])*)`)/, /* 30: */ /^(?:%%|\||;)/, /* 31: */ /^(?:%include\b)/, /* 32: */ /^(?:>)/, /* 33: */ /^(?:,)/, /* 34: */ /^(?:\*)/, /* 35: */ new XRegExp('^(?:<([\\p{Alphabetic}_](?:[\\p{Alphabetic}\\p{Number}_])*)>)', ''), /* 36: */ /^(?:([^\s!"$%'-,.\/:-?\[-\^`{-}])+)/, /* 37: */ /^(?:(\r\n|\n|\r)([^\S\n\r])+(?=\S))/, /* 38: */ /^(?:(\r\n|\n|\r))/, /* 39: */ /^(?:([^\S\n\r])+)/, /* 40: */ new XRegExp('^(?:([\\p{Alphabetic}_](?:[\\p{Alphabetic}\\p{Number}_])*))', ''), /* 41: */ /^(?:(\r\n|\n|\r)+)/, /* 42: */ /^(?:$)/, /* 43: */ /^(?:(\r\n|\n|\r)+)/, /* 44: */ /^(?:([^\S\n\r])+)/, /* 45: */ /^(?:"((?:\\"|\\[^"]|[^\n\r"\\])*)")/, /* 46: */ /^(?:'((?:\\'|\\[^']|[^\n\r'\\])*)')/, /* 47: */ /^(?:`((?:\\`|\\[^`]|[^\\`])*)`)/, /* 48: */ /^(?:([^\s!"$%'-,.\/:-?\[-\^`{-}])+)/, /* 49: */ /^(?:\[)/, /* 50: */ /^(?:\|)/, /* 51: */ /^(?:\(\?:)/, /* 52: */ /^(?:\(\?=)/, /* 53: */ /^(?:\(\?!)/, /* 54: */ /^(?:\(\?<=)/, /* 55: */ /^(?:\(\?<!)/, /* 56: */ /^(?:\()/, /* 57: */ /^(?:\))/, /* 58: */ /^(?:\+)/, /* 59: */ /^(?:\*)/, /* 60: */ /^(?:\?)/, /* 61: */ /^(?:\^)/, /* 62: */ /^(?:,)/, /* 63: */ /^(?:<<EOF>>)/, /* 64: */ /^(?:<)/, /* 65: */ /^(?:>)/, /* 66: */ /^(?:\/!)/, /* 67: */ /^(?:\/)/, /* 68: */ /^(?:\\(?:[BDPSWbdpsw]|[$(-+.\/?\[-\^fnrtv{-}]))/, /* 69: */ /^(?:\\(?:([0-7]{1,3})|c([@-Z])|x([\dA-Fa-f]{2})|u([\dA-Fa-f]{4})|u\{([\dA-Fa-f]{1,8})\}))/, /* 70: */ /^(?:\\.)/, /* 71: */ /^(?:\$)/, /* 72: */ /^(?:\.)/, /* 73: */ /^(?:%option[s]?)/, /* 74: */ /^(?:%s\b)/, /* 75: */ /^(?:%x\b)/, /* 76: */ /^(?:%code\b)/, /* 77: */ /^(?:%import\b)/, /* 78: */ /^(?:%pointer\b)/, /* 79: */ /^(?:%array\b)/, /* 80: */ /^(?:%include\b)/, /* 81: */ new XRegExp( '^(?:%([\\p{Alphabetic}_](?:[\\p{Alphabetic}\\p{Number}\\-_]*(?:[\\p{Alphabetic}\\p{Number}_]))?)([^\\n\\r]*))', '' ), /* 82: */ /^(?:%%)/, /* 83: */ /^(?:\{\d+(,\s*\d+|,)?\})/, /* 84: */ new XRegExp('^(?:\\{([\\p{Alphabetic}_](?:[\\p{Alphabetic}\\p{Number}_])*)\\})', ''), /* 85: */ new XRegExp('^(?:\\{([\\p{Alphabetic}_](?:[\\p{Alphabetic}\\p{Number}_])*)\\})', ''), /* 86: */ /^(?:\{)/, /* 87: */ /^(?:\})/, /* 88: */ /^(?:(?:\\[^\n\r]|[^\]{])+)/, /* 89: */ /^(?:\{)/, /* 90: */ /^(?:\])/, /* 91: */ /^(?:(?:[^\n\r%][^\n\r]*(\r\n|\n|\r)+)+)/, /* 92: */ /^(?:[^\n\r]*(\r\n|\n|\r)+)/, /* 93: */ /^(?:[^\n\r]+)/, /* 94: */ /^(?:")/, /* 95: */ /^(?:')/, /* 96: */ /^(?:`)/, /* 97: */ /^(?:")/, /* 98: */ /^(?:')/, /* 99: */ /^(?:`)/, /* 100: */ /^(?:")/, /* 101: */ /^(?:')/, /* 102: */ /^(?:`)/, /* 103: */ /^(?:.)/, /* 104: */ /^(?:.)/, /* 105: */ /^(?:.)/, /* 106: */ /^(?:$)/ ], conditions: { 'rules': { rules: [ 0, 1, 19, 20, 21, 22, 23, 24, 25, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 86, 87, 100, 101, 102, 103, 105, 106 ], inclusive: true }, 'macro': { rules: [ 0, 1, 20, 21, 22, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 82, 83, 84, 86, 87, 100, 101, 102, 103, 105, 106 ], inclusive: true }, 'code': { rules: [19, 80, 81, 91, 92, 93, 100, 101, 102, 105, 106], inclusive: false }, 'options': { rules: [ 0, 1, 19, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 85, 97, 98, 99, 100, 101, 102, 104, 105, 106 ], inclusive: false }, 'action': { rules: [ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 94, 95, 96, 100, 101, 102, 105, 106 ], inclusive: false }, 'set': { rules: [85, 88, 89, 90, 100, 101, 102, 105, 106], inclusive: false }, 'INITIAL': { rules: [ 0, 1, 19, 20, 21, 22, 40, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 86, 87, 100, 101, 102, 105, 106 ], inclusive: true } } }; var rmCommonWS = helpers.rmCommonWS; var dquote = helpers.dquote; var scanRegExp = helpers.scanRegExp; // Calculate the end marker to match and produce a // lexer rule to match when the need arrises: lexer.setupDelimitedActionChunkLexerRegex = function lexer__setupDelimitedActionChunkLexerRegex(marker) { // Special: when we encounter `{` as the start of the action code block, // we DO NOT patch the `%{...%}` lexer rule as we will handle `{...}` // elsewhere in the lexer anyway: we cannot use a simple regex like // `/{[^]*?}/` to match an entire action code block after all! var doNotPatch = marker === '{'; var action_end_marker = marker.replace(/\{/g, '}'); if (!doNotPatch) { // Note: this bit comes straight from the lexer kernel! // // Get us the currently active set of lexer rules. // (This is why we push the 'action' lexer condition state above *before* // we commence and work on the ruleset itself.) var spec = this.__currentRuleSet__; if (!spec) { // Update the ruleset cache as we apparently encountered a state change or just started lexing. // The cache is set up for fast lookup -- we assume a lexer will switch states much less often than it will // invoke the `lex()` token-producing API and related APIs, hence caching the set for direct access helps // speed up those activities a tiny bit. spec = this.__currentRuleSet__ = this._currentRules(); } var regexes = spec.__rule_regexes; var len = spec.__rule_count; var rules = spec.rules; var i; var action_chunk_regex; // Must we still locate the rule to patch or have we done // that already during a previous encounter? // // WARNING: our cache/patch must live beyond the current lexer+parser invocation: // our patching must remain detected indefinitely to ensure subsequent invocations // of the parser will still work as expected! // This implies that we CANNOT store anything in the `yy` context as that one // is short-lived: `yy` dies once the current parser.parse() has completed! // Hence we store our patch data in the lexer instance itself: in `spec`. // if (!spec.__action_chunk_rule_idx) { // **WARNING**: *(this bit, like so much else in here, comes straight from the lexer kernel)* // // slot 0 is unused; we use a 1-based index approach here to keep the hottest code in `lexer_next()` fast and simple! var orig_re_str1 = '/^(?:%\\{([^]*?)%\\}(?!\\}))/'; var orig_re_str2 = '/^(?:%\\{([\\s\\S]*?)%\\}(?!\\}))/'; // the XRegExp 'cross-platform' version of the same. // Note: the arrays are 1-based, while `len` itself is a valid index, // hence the non-standard less-or-equal check in the next loop condition! for (i = 1; i <= len; i++) { var rule_re = regexes[i]; var re_str = rule_re.toString(); //console.error('test regexes:', {i, len, re1: re_str, match1: rule_re.toString() === orig_re_str1, match1: rule_re.toString() === orig_re_str2}); if (re_str === orig_re_str1 || re_str === orig_re_str2) { spec.__action_chunk_rule_idx = i; break; } } if (!spec.__action_chunk_rule_idx) { //console.error('ruleset dump:', spec); throw new Error('INTERNAL DEV ERROR: cannot locate %{...%} rule regex!'); } // As we haven't initialized yet, we're sure the rule cache doesn't exist either. // Make it happen: spec.__cached_action_chunk_rule = {}; // set up empty cache } i = spec.__action_chunk_rule_idx; // Must we build the lexer rule or did we already run this variant // through this lexer before? When the latter, fetch the cached version! action_chunk_regex = spec.__cached_action_chunk_rule[marker]; if (!action_chunk_regex) { action_chunk_regex = spec.__cached_action_chunk_rule[marker] = new RegExp( '^(?:' + marker.replace(/\{/g, '\\{') + '([^]*?)' + action_end_marker.replace(/\}/g, '\\}') + '(?!\\}))' ); //console.warn('encode new action block regex:', action_chunk_regex); } //console.error('new ACTION REGEX:', { i, action_chunk_regex }); // and patch the lexer regex table for the current lexer condition state: regexes[i] = action_chunk_regex; } return action_end_marker; }; lexer.warn = function l_warn() { if (this.yy && this.yy.parser && typeof this.yy.parser.warn === 'function') { return this.yy.parser.warn.apply(this, arguments); } else { console.warn.apply(console, arguments); } }; lexer.log = function l_log() { if (this.yy && this.yy.parser && typeof this.yy.parser.log === 'function') { return this.yy.parser.log.apply(this, arguments); } else { console.log.apply(console, arguments); } }; return lexer; }(); parser.lexer = lexer; var rmCommonWS$1 = helpers.rmCommonWS; var checkActionBlock$1 = helpers.checkActionBlock; var mkIdentifier$1 = helpers.mkIdentifier; var isLegalIdentifierInput$1 = helpers.isLegalIdentifierInput; var trimActionCode$1 = helpers.trimActionCode; // see also: // - https://en.wikipedia.org/wiki/C0_and_C1_control_codes // - https://docs.microsoft.com/en-us/dotnet/standard/base-types/character-escapes-in-regular-expressions // - https://kangax.github.io/compat-table/es6/#test-RegExp_y_and_u_flags // - http://2ality.com/2015/07/regexp-es6.html // - http://www.regular-expressions.info/quickstart.html const charCvtTable = { // "\a": "\x07", // "\e": "\x1B", // "\b": "\x08", "\f": "\\f", "\n": "\\n", "\r": "\\r", "\t": "\\t", "\v": "\\v", }; const escCvtTable = { "a": "\\x07", "e": "\\x1B", "b": "\\x08", "f": "\\f", "n": "\\n", "r": "\\r", "t": "\\t", "v": "\\v", }; const codeCvtTable = { 12: "\\f", 10: "\\n", 13: "\\r", 9: "\\t", 11: "\\v", }; // Note about 'b' in the regex below: // when inside a literal string, it's BACKSPACE, otherwise it's // the regex word edge condition `\b`. Here it's BACKSPACE. var codedCharRe = /(?:([sSBwWdDpP])|([*+()${}|[\]\/.^?])|([aberfntv])|([0-7]{1,3})|c([@A-Z])|x([0-9a-fA-F]{2})|u([0-9a-fA-F]{4})|u\{([0-9a-fA-F]{1,8})\}|())/g; function encodeCharCode(v) { if (v < 32) { var rv = codeCvtTable[v]; if (rv) return rv; return '\\u' + ('0000' + v.toString(16)).substr(-4); } else { return String.fromCharCode(v); } } function encodeUnicodeCodepoint(v) { if (v < 32) { var rv = codeCvtTable[v]; if (rv) return rv; return '\\u' + ('0000' + v.toString(16)).substr(-4); } else { return String.fromCodePoint(v); } } function encodeRegexLiteralStr(s, edge) { var rv = ''; //console.warn("encodeRegexLiteralStr INPUT:", {s, edge}); for (var i = 0, l = s.length; i < l; i++) { var c = s[i]; switch (c) { case '\\': i++; if (i < l) { c = s[i]; if (c === edge) { rv += c; continue; } var pos = '\'"`'.indexOf(c); if (pos >= 0) { rv += '\\\\' + c; continue; } if (c === '\\') { rv += '\\\\'; continue; } codedCharRe.lastIndex = i; // we 'fake' the RegExp 'y'=sticky feature cross-platform by using 'g' flag instead // plus an empty capture group at the end of the regex: when that one matches, // we know we did not get a hit. var m = codedCharRe.exec(s); if (m && m[0]) { if (m[1]) { // [1]: regex operators, which occur in a literal string: `\s` --> \\s rv += '\\\\' + m[1]; i += m[1].length - 1; continue; } if (m[2]) { // [2]: regex special characters, which occur in a literal string: `\[` --> \\\[ rv += '\\\\\\' + m[2]; i += m[2].length - 1; continue; } if (m[3]) { // [3]: special escape characters, which occur in a literal string: `\a` --> BELL rv += escCvtTable[m[3]]; i += m[3].length - 1; continue; } if (m[4]) { // [4]: octal char: `\012` --> \x0A var v = parseInt(m[4], 8); rv += encodeCharCode(v); i += m[4].length - 1; continue; } if (m[5]) { // [5]: CONTROL char: `\cA` --> \u0001 var v = m[5].charCodeAt(0) - 64; rv += encodeCharCode(v); i++; continue; } if (m[6]) { // [6]: hex char: `\x41` --> A var v = parseInt(m[6], 16); rv += encodeCharCode(v); i += m[6].length; continue; } if (m[7]) { // [7]: unicode/UTS2 char: `\u03c0` --> PI var v = parseInt(m[7], 16); rv += encodeCharCode(v); i += m[7].length; continue; } if (m[8]) { // [8]: unicode code point: `\u{00003c0}` --> PI var v = parseInt(m[8], 16); rv += encodeUnicodeCodepoint(v); i += m[8].length; continue; } } } // all the rest: simply treat the `\\` escape as a character on its own: rv += '\\\\'; i--; continue; default: // escape regex operators: var pos = ".*+?^${}()|[]/\\".indexOf(c); if (pos >= 0) { rv += '\\' + c; continue; } var cc = charCvtTable[c]; if (cc) { rv += cc; continue; } var cc = c.charCodeAt(0); if (cc < 32) { var rvp = codeCvtTable[v]; if (rvp) { rv += rvp; } else { rv += '\\u' + ('0000' + cc.toString(16)).substr(-4); } } else { rv += c; } continue; } } s = rv; //console.warn("encodeRegexLiteralStr ROUND 3:", {s}); return s; } // convert string value to number or boolean value, when possible // (and when this is more or less obviously the intent) // otherwise produce the string itself as value. function parseValue(v) { if (v === 'false') { return false; } if (v === 'true') { return true; } // http://stackoverflow.com/questions/175739/is-there-a-built-in-way-in-javascript-to-check-if-a-string-is-a-valid-number // Note that the `v` check ensures that we do not convert `undefined`, `null` and `''` (empty string!) if (v && !isNaN(v)) { var rv = +v; if (isFinite(rv)) { return rv; } } return v; } parser.warn = function p_warn() { console.warn.apply(console, arguments); }; parser.log = function p_log() { console.log.apply(console, arguments); }; parser.pre_parse = function p_lex() { if (parser.yydebug) parser.log('pre_parse:', arguments); }; parser.yy.pre_parse = function p_lex() { if (parser.yydebug) parser.log('pre_parse YY:', arguments); }; parser.yy.post_lex = function p_lex() { if (parser.yydebug) parser.log('post_lex:', arguments); }; function Parser() { this.yy = {}; } Parser.prototype = parser; parser.Parser = Parser; function yyparse() { return parser.parse.apply(parser, arguments); } var lexParser = { parser, Parser, parse: yyparse, }; export default lexParser;
// promises/a+ suite. const promisesAplusTests = require("promises-aplus-tests"); const Promise = require("../promise.js"); // needed for aplus process.on("unhandledRejection", (e, v) => {}); describe("Promises/A+ Tests", function () { require("promises-aplus-tests").mocha({ resolved(v) { return Promise.resolve(v); }, rejected(e) { return Promise.reject(e); }, deferred() { let resolve, reject; let promise = new Promise((res, rej) => { resolve = res; reject = rej; }); return { promise, resolve, reject }; } }); });
version https://git-lfs.github.com/spec/v1 oid sha256:ad8098078ed8ad16cea85df9c279ac99ddbbf8d4bbcfab5a4ece55d26d872cc3 size 981493
/** * translate ast to js function code */ 'use strict'; var util = require('./runtime').util; var compilerTools = require('./compiler/tools'); var pushToArray = compilerTools.pushToArray; var wrapByDoubleQuote = compilerTools.wrapByDoubleQuote; // codeTemplates --------------------------- start var TMP_DECLARATION = ['var t;']; for (var i = 0; i < 10; i++) { TMP_DECLARATION.push('var t' + i + ';'); } var TOP_DECLARATION = TMP_DECLARATION.concat(['var tpl = this;\n var root = tpl.root;\n var buffer = tpl.buffer;\n var scope = tpl.scope;\n var runtime = tpl.runtime;\n var name = tpl.name;\n var pos = tpl.pos;\n var data = scope.data;\n var affix = scope.affix;\n var nativeCommands = root.nativeCommands;\n var utils = root.utils;']).join('\n'); var CALL_NATIVE_COMMAND = '{lhs} = {name}Command.call(tpl, scope, {option}, buffer);'; var CALL_CUSTOM_COMMAND = 'buffer = callCommandUtil(tpl, scope, {option}, buffer, {idParts});'; var CALL_FUNCTION = '{lhs} = callFnUtil(tpl, scope, {option}, buffer, {idParts});'; var CALL_DATA_FUNCTION = '{lhs} = callDataFnUtil([{params}], {idParts});'; var CALL_FUNCTION_DEPTH = '{lhs} = callFnUtil(tpl, scope, {option}, buffer, {idParts}, {depth});'; var ASSIGN_STATEMENT = 'var {lhs} = {value};'; var SCOPE_RESOLVE_DEPTH = 'var {lhs} = scope.resolve({idParts},{depth});'; var SCOPE_RESOLVE_LOOSE_DEPTH = 'var {lhs} = scope.resolveLoose({idParts},{depth});'; var FUNC = 'function {functionName}({params}){\n {body}\n}'; var SOURCE_URL = '\n //# sourceURL = {name}.js\n'; var DECLARE_NATIVE_COMMANDS = 'var {name}Command = nativeCommands["{name}"];'; var DECLARE_UTILS = 'var {name}Util = utils["{name}"];'; var BUFFER_WRITE = 'buffer = buffer.write({value});'; var BUFFER_APPEND = 'buffer.data += {value};'; var BUFFER_WRITE_ESCAPED = 'buffer = buffer.writeEscaped({value});'; var RETURN_BUFFER = 'return buffer;'; // codeTemplates ---------------------------- end var XTemplateRuntime = require('./runtime'); var parser = require('./compiler/parser'); parser.yy = require('./compiler/ast'); var nativeCode = []; var substitute = util.substitute; var each = util.each; var nativeCommands = XTemplateRuntime.nativeCommands; var nativeUtils = XTemplateRuntime.utils; each(nativeUtils, function (v, name) { nativeCode.push(substitute(DECLARE_UTILS, { name: name })); }); each(nativeCommands, function (v, name) { nativeCode.push(substitute(DECLARE_NATIVE_COMMANDS, { name: name })); }); nativeCode = nativeCode.join('\n'); var lastLine = 1; function markLine(pos, source) { if (lastLine === pos.line) { return; } lastLine = pos.line; source.push('pos.line = ' + pos.line + ';'); } function resetGlobal() { lastLine = 1; } function getFunctionDeclare(functionName) { return ['function ' + functionName + '(scope, buffer, undefined) {\n var data = scope.data;\n var affix = scope.affix;']; } function guid(self, str) { return str + self.uuid++; } function considerSuffix(n, withSuffix) { var name = n; if (withSuffix && !/\.xtpl$/.test(name)) { name += '.xtpl'; } return name; } function opExpression(e) { var source = []; var type = e.opType; var exp1 = undefined; var exp2 = undefined; var code1Source = undefined; var code2Source = undefined; var code1 = this[e.op1.type](e.op1); var code2 = this[e.op2.type](e.op2); var exp = guid(this, 'exp'); exp1 = code1.exp; exp2 = code2.exp; code1Source = code1.source; code2Source = code2.source; pushToArray(source, code1Source); source.push('var ' + exp + ' = ' + exp1 + ';'); if (type === '&&' || type === '||') { source.push('if(' + (type === '&&' ? '' : '!') + '(' + exp + ')){'); pushToArray(source, code2Source); source.push(exp + ' = ' + exp2 + ';'); source.push('}'); } else { pushToArray(source, code2Source); source.push(exp + ' = (' + exp1 + ') ' + type + ' (' + exp2 + ');'); } return { exp: exp, source: source }; } function genFunction(self, statements) { var functionName = guid(self, 'func'); var source = getFunctionDeclare(functionName); var statement = undefined; for (var i = 0, len = statements.length; i < len; i++) { statement = statements[i]; pushToArray(source, self[statement.type](statement).source); } source.push(RETURN_BUFFER); source.push('}'); // avoid deep closure for performance pushToArray(self.functionDeclares, source); return functionName; } function genConditionFunction(self, condition) { var functionName = guid(self, 'func'); var source = getFunctionDeclare(functionName); var gen = self[condition.type](condition); pushToArray(source, gen.source); source.push('return ' + gen.exp + ';'); source.push('}'); pushToArray(self.functionDeclares, source); return functionName; } function genTopFunction(self, statements) { var catchError = self.config.catchError; var source = [ // 'function run(tpl) {', TOP_DECLARATION, nativeCode, // decrease speed by 10% // for performance catchError ? 'try {' : '']; var statement = undefined; var i = undefined; var len = undefined; for (i = 0, len = statements.length; i < len; i++) { statement = statements[i]; pushToArray(source, self[statement.type](statement, { top: 1 }).source); } source.splice.apply(source, [2, 0].concat(self.functionDeclares).concat('')); source.push(RETURN_BUFFER); // source.push('}'); // source.push('function tryRun(tpl) {'); // source.push('try {'); // source.push('ret = run(this);'); if (catchError) { source.push('} catch(e) {'); source.push('if(!e.xtpl){'); source.push('buffer.error(e);'); source.push('}else{ throw e; }'); source.push('}'); } // source.push('}'); // source.push('return tryRun(this);'); return { params: ['undefined'], source: source.join('\n') }; } function genOptionFromFunction(self, func, escape, fn, elseIfs, inverse) { var source = []; var params = func.params; var hash = func.hash; var funcParams = []; var isSetFunction = func.id.string === 'set'; if (params) { each(params, function (param) { var nextIdNameCode = self[param.type](param); pushToArray(source, nextIdNameCode.source); funcParams.push(nextIdNameCode.exp); }); } var funcHash = []; if (hash) { each(hash.value, function (h) { var v = h[1]; var key = h[0]; var vCode = self[v.type](v); pushToArray(source, vCode.source); if (isSetFunction) { // support {{set(x.y.z=1)}} // https://github.com/xtemplate/xtemplate/issues/54 var resolvedParts = compilerTools.convertIdPartsToRawAccessor(self, source, key.parts).resolvedParts; funcHash.push({ key: resolvedParts, depth: key.depth, value: vCode.exp }); } else { if (key.parts.length !== 1 || typeof key.parts[0] !== 'string') { throw new Error('invalid hash parameter'); } funcHash.push([wrapByDoubleQuote(key.string), vCode.exp]); } }); } var exp = ''; // literal init array, do not use arr.push for performance if (funcParams.length || funcHash.length || escape || fn || inverse || elseIfs) { if (escape) { exp += ',escape:1'; } if (funcParams.length) { exp += ',params:[' + funcParams.join(',') + ']'; } if (funcHash.length) { (function () { var hashStr = []; if (isSetFunction) { util.each(funcHash, function (h) { hashStr.push('{key:[' + h.key.join(',') + '],value:' + h.value + ', depth:' + h.depth + '}'); }); exp += ',hash: [' + hashStr.join(',') + ']'; } else { util.each(funcHash, function (h) { hashStr.push(h[0] + ':' + h[1]); }); exp += ',hash: {' + hashStr.join(',') + '}'; } })(); } if (fn) { exp += ',fn: ' + fn; } if (inverse) { exp += ',inverse: ' + inverse; } if (elseIfs) { exp += ',elseIfs: ' + elseIfs; } exp = '{' + exp.slice(1) + '}'; } return { exp: exp || '{}', funcParams: funcParams, source: source }; } function generateFunction(self, func, block, escape_) { var escape = escape_; var source = []; markLine(func.pos, source); var functionConfigCode = undefined; var idName = undefined; var id = func.id; var idString = id.string; if (idString in nativeCommands) { escape = 0; } var idParts = id.parts; var i = undefined; if (idString === 'elseif') { return { exp: '', source: [] }; } if (block) { var programNode = block.program; var inverse = programNode.inverse; var fnName = undefined; var elseIfsName = undefined; var inverseName = undefined; var elseIfs = []; var elseIf = undefined; var functionValue = undefined; var statement = undefined; var statements = programNode.statements; var thenStatements = []; for (i = 0; i < statements.length; i++) { statement = statements[i]; if (statement.type === 'expressionStatement' && (functionValue = statement.value) && (functionValue = functionValue.parts) && functionValue.length === 1 && (functionValue = functionValue[0]) && functionValue.type === 'function' && functionValue.id.string === 'elseif') { if (elseIf) { elseIfs.push(elseIf); } elseIf = { condition: functionValue.params[0], statements: [] }; } else if (elseIf) { elseIf.statements.push(statement); } else { thenStatements.push(statement); } } if (elseIf) { elseIfs.push(elseIf); } // find elseIfs fnName = genFunction(self, thenStatements); if (inverse) { inverseName = genFunction(self, inverse); } if (elseIfs.length) { var elseIfsVariable = []; for (i = 0; i < elseIfs.length; i++) { var elseIfStatement = elseIfs[i]; var conditionName = genConditionFunction(self, elseIfStatement.condition); elseIfsVariable.push('{test: ' + conditionName + ',fn : ' + genFunction(self, elseIfStatement.statements) + '}'); } elseIfsName = '[' + elseIfsVariable.join(',') + ']'; } functionConfigCode = genOptionFromFunction(self, func, escape, fnName, elseIfsName, inverseName); pushToArray(source, functionConfigCode.source); } var _self$config = self.config; var isModule = _self$config.isModule; var withSuffix = _self$config.withSuffix; if (idString === 'include' || idString === 'parse' || idString === 'extend') { if (!func.params || func.params.length > 2) { throw new Error('include/parse/extend can only has at most two parameter!'); } } if (isModule) { if (idString === 'include' || idString === 'parse') { var _name = considerSuffix(func.params[0].value, withSuffix); func.params[0] = { type: 'raw', value: 're' + 'quire("' + _name + '")' }; } } if (!functionConfigCode) { functionConfigCode = genOptionFromFunction(self, func, escape, null, null, null); pushToArray(source, functionConfigCode.source); } if (!block) { idName = guid(self, 'callRet'); source.push('var ' + idName); } if (idString in nativeCommands) { if (idString === 'extend') { source.push('runtime.extendTpl = ' + functionConfigCode.exp); source.push('buffer = buffer.async(function(newBuffer){runtime.extendTplBuffer = newBuffer;});'); if (isModule) { var _name2 = considerSuffix(func.params[0].value, withSuffix); source.push('runtime.extendTplFn = re' + 'quire("' + _name2 + '");'); } } else if (idString === 'include') { source.push('buffer = root.' + (isModule ? 'includeModule' : 'include') + '(scope,' + functionConfigCode.exp + ',buffer,tpl);'); } else if (idString === 'includeOnce') { source.push('buffer = root.' + (isModule ? 'includeOnceModule' : 'includeOnce') + '(scope,' + functionConfigCode.exp + ',buffer,tpl);'); } else if (idString === 'parse') { source.push('buffer = root.' + (isModule ? 'includeModule' : 'include') + '(new scope.constructor(),' + functionConfigCode.exp + ',buffer,tpl);'); } else { source.push(substitute(CALL_NATIVE_COMMAND, { lhs: block ? 'buffer' : idName, name: idString, option: functionConfigCode.exp })); } } else if (block) { source.push(substitute(CALL_CUSTOM_COMMAND, { option: functionConfigCode.exp, idParts: compilerTools.convertIdPartsToRawAccessor(self, source, idParts).arr })); } else { var resolveParts = compilerTools.convertIdPartsToRawAccessor(self, source, idParts); // {{x.y().q.z()}} // do not need scope resolution, call data function directly if (resolveParts.funcRet) { source.push(substitute(CALL_DATA_FUNCTION, { lhs: idName, params: functionConfigCode.funcParams.join(','), idParts: resolveParts.arr, depth: id.depth })); } else { source.push(substitute(id.depth ? CALL_FUNCTION_DEPTH : CALL_FUNCTION, { lhs: idName, option: functionConfigCode.exp, idParts: resolveParts.arr, depth: id.depth })); } } return { exp: idName, source: source }; } function AstToJSProcessor(config) { this.functionDeclares = []; this.config = config; this.uuid = 0; } AstToJSProcessor.prototype = { constructor: AstToJSProcessor, raw: function raw(_raw) { return { exp: _raw.value }; }, arrayExpression: function arrayExpression(e) { var list = e.list; var len = list.length; var r = undefined; var source = []; var exp = []; for (var i = 0; i < len; i++) { r = this[list[i].type](list[i]); pushToArray(source, r.source); exp.push(r.exp); } return { exp: '[ ' + exp.join(',') + ' ]', source: source }; }, objectExpression: function objectExpression(e) { var obj = e.obj; var len = obj.length; var r = undefined; var source = []; var exp = []; for (var i = 0; i < len; i++) { var item = obj[i]; r = this[item[1].type](item[1]); pushToArray(source, r.source); exp.push(wrapByDoubleQuote(item[0]) + ': ' + r.exp); } return { exp: '{ ' + exp.join(',') + ' }', source: source }; }, conditionalOrExpression: opExpression, conditionalAndExpression: opExpression, relationalExpression: opExpression, equalityExpression: opExpression, additiveExpression: opExpression, multiplicativeExpression: opExpression, unaryExpression: function unaryExpression(e) { var code = this[e.value.type](e.value); return { exp: e.unaryType + '(' + code.exp + ')', source: code.source }; }, string: function string(e) { // same as contentNode.value return { exp: compilerTools.wrapBySingleQuote(compilerTools.escapeString(e.value, 1)), source: [] }; }, number: function number(e) { return { exp: e.value, source: [] }; }, id: function id(idNode) { var source = []; var self = this; var loose = !self.config.strict; markLine(idNode.pos, source); if (compilerTools.isGlobalId(idNode)) { return { exp: idNode.string, source: source }; } var depth = idNode.depth; var idParts = idNode.parts; var idName = guid(self, 'id'); if (depth) { source.push(substitute(loose ? SCOPE_RESOLVE_LOOSE_DEPTH : SCOPE_RESOLVE_DEPTH, { lhs: idName, idParts: compilerTools.convertIdPartsToRawAccessor(self, source, idParts).arr, depth: depth })); return { exp: idName, source: source }; } var part0 = idParts[0]; var remain = undefined; var remainParts = undefined; if (part0 === 'this') { remainParts = idParts.slice(1); source.push(substitute(ASSIGN_STATEMENT, { lhs: idName, value: remainParts.length ? compilerTools.chainedVariableRead(self, source, remainParts, undefined, undefined, loose) : 'data' })); return { exp: idName, source: source }; } else if (part0 === 'root') { remainParts = idParts.slice(1); remain = remainParts.join('.'); if (remain) { remain = '.' + remain; } source.push(substitute(ASSIGN_STATEMENT, { lhs: idName, value: remain ? compilerTools.chainedVariableRead(self, source, remainParts, true, undefined, loose) : 'scope.root.data', idParts: remain })); return { exp: idName, source: source }; } // {{x.y().z}} if (idParts[0].type === 'function') { var resolvedParts = compilerTools.convertIdPartsToRawAccessor(self, source, idParts).resolvedParts; for (var i = 1; i < resolvedParts.length; i++) { resolvedParts[i] = '[' + resolvedParts[i] + ']'; } var value = undefined; if (loose) { value = compilerTools.genStackJudge(resolvedParts.slice(1), resolvedParts[0]); } else { value = resolvedParts[0]; for (var ri = 1; ri < resolvedParts.length; ri++) { value += resolvedParts[ri]; } } source.push(substitute(ASSIGN_STATEMENT, { lhs: idName, value: value })); } else { source.push(substitute(ASSIGN_STATEMENT, { lhs: idName, value: compilerTools.chainedVariableRead(self, source, idParts, false, true, loose) })); } return { exp: idName, source: source }; }, 'function': function _function(func, escape) { return generateFunction(this, func, false, escape); }, blockStatement: function blockStatement(block) { return generateFunction(this, block.func, block); }, expressionStatement: function expressionStatement(_expressionStatement) { var source = []; var escape = _expressionStatement.escape; var code = undefined; var expression = _expressionStatement.value; var type = expression.type; var expressionOrVariable = undefined; code = this[type](expression, escape); pushToArray(source, code.source); expressionOrVariable = code.exp; source.push(substitute(escape ? BUFFER_WRITE_ESCAPED : BUFFER_WRITE, { value: expressionOrVariable })); return { exp: '', source: source }; }, contentStatement: function contentStatement(_contentStatement) { return { exp: '', source: [substitute(BUFFER_APPEND, { value: compilerTools.wrapBySingleQuote(compilerTools.escapeString(_contentStatement.value, 0)) })] }; } }; var anonymousCount = 0; /** * compiler for xtemplate * @class XTemplate.Compiler * @singleton */ var compiler = { /** * get ast of template * @param {String} [name] xtemplate name * @param {String} tplContent * @return {Object} */ parse: function parse(tplContent, name) { if (tplContent) { var ret = undefined; try { ret = parser.parse(tplContent, name); } catch (err) { var e = undefined; if (err instanceof Error) { e = err; } else { e = new Error(err); } var errorStr = 'XTemplate error '; try { e.stack = errorStr + e.stack; e.message = errorStr + e.message; } catch (e2) { // empty } throw e; } return ret; } return { statements: [] }; }, compileToStr: function compileToStr(param) { var func = compiler.compileToJson(param); return substitute(FUNC, { functionName: param.functionName || '', params: func.params.join(','), body: func.source }); }, /** * get template function json format * @param {String} [param.name] xtemplate name * @param {String} param.content * @param {Boolean} [param.isModule] whether generated function is used in module * @param {Boolean} [param.withSuffix] whether generated require name with suffix xtpl * @param {Boolean} [param.catchError] whether to try catch generated function to provide good error message * @param {Boolean} [param.strict] whether to generate strict function * @return {Object} */ compileToJson: function compileToJson(param) { resetGlobal(); var name = param.name = param.name || 'xtemplate' + ++anonymousCount; var content = param.content; var root = compiler.parse(content, name); return genTopFunction(new AstToJSProcessor(param), root.statements); }, /** * get template function * @param {String} tplContent * @param {String} name template file name * @param {Object} config * @return {Function} */ compile: function compile(tplContent, name, config) { var code = compiler.compileToJson(util.merge(config, { content: tplContent, name: name })); var source = code.source; source += substitute(SOURCE_URL, { name: name }); var args = code.params.concat(source); // eval is not ok for eval("(function(){})") ie return Function.apply(null, args); } }; module.exports = compiler; /* todo: need oop, new Source().this() */
/*eslint-env node, mocha*/ /** * @author lattmann / https://github.com/lattmann * @author pmeijer / https://github.com/pmeijer */ describe('storage storageclasses editorstorage', function () { 'use strict'; var testFixture = require('../../../_globals.js'), NodeStorage = testFixture.requirejs('common/storage/nodestorage'), STORAGE_CONSTANTS = testFixture.requirejs('common/storage/constants'), gmeConfig = testFixture.getGmeConfig(), WebGME = testFixture.WebGME, openSocketIo = testFixture.openSocketIo, superagent = testFixture.superagent, Q = testFixture.Q, projectName2Id = testFixture.projectName2Id, expect = testFixture.expect, agent, socket, logger = testFixture.logger.fork('editorstorage.spec'), guestAccount = gmeConfig.authentication.guestAccount, server, gmeAuth, safeStorage, storage, webgmeToken, projectName = 'StorageProject', importResult, originalHash, commitHash1, commitHash2; before(function (done) { var commitObject, commitData; server = WebGME.standaloneServer(gmeConfig); server.start(function (err) { if (err) { done(new Error(err)); return; } testFixture.clearDBAndGetGMEAuth(gmeConfig, [projectName]) .then(function (gmeAuth_) { gmeAuth = gmeAuth_; safeStorage = testFixture.getMongoStorage(logger, gmeConfig, gmeAuth); return safeStorage.openDatabase(); }) .then(function () { return Q.allDone([ testFixture.importProject(safeStorage, { projectSeed: 'seeds/EmptyProject.webgmex', projectName: projectName, gmeConfig: gmeConfig, logger: logger }) ]); }) .then(function (results) { importResult = results[0]; // projectName originalHash = importResult.commitHash; commitObject = importResult.project.createCommitObject([originalHash], importResult.rootHash, 'tester1', 'commit msg 1'); commitData = { projectId: projectName2Id(projectName), commitObject: commitObject, coreObjects: [] }; return safeStorage.makeCommit(commitData); }) .then(function (result) { commitHash1 = result.hash; commitObject = importResult.project.createCommitObject([originalHash], importResult.rootHash, 'tester2', 'commit msg 2'); commitData = { projectId: projectName2Id(projectName), commitObject: commitObject, coreObjects: [] }; return safeStorage.makeCommit(commitData); }) .then(function (result) { commitHash2 = result.hash; }) .then(function () { return Q.allDone([ importResult.project.createBranch('b1', importResult.commitHash), importResult.project.createBranch('b2', importResult.commitHash), importResult.project.createBranch('b3', importResult.commitHash), importResult.project.createBranch('b4', importResult.commitHash), importResult.project.createBranch('b5', importResult.commitHash), importResult.project.createBranch('b6', importResult.commitHash), importResult.project.createBranch('b7', importResult.commitHash), importResult.project.createBranch('b8', importResult.commitHash), importResult.project.createBranch('b9', importResult.commitHash), importResult.project.createBranch('b10', importResult.commitHash), importResult.project.createBranch('b11', importResult.commitHash), ]); }) .then(function () { return Q.allDone([ importResult.project.setBranchHash('b1', commitHash1, importResult.commitHash), importResult.project.setBranchHash('b2', commitHash1, importResult.commitHash), importResult.project.setBranchHash('b3', commitHash1, importResult.commitHash), importResult.project.setBranchHash('b4', commitHash1, importResult.commitHash), importResult.project.setBranchHash('b5', commitHash1, importResult.commitHash) ]); }) .nodeify(done); }); }); after(function (done) { server.stop(function (err) { if (err) { done(new Error(err)); return; } Q.allDone([ gmeAuth.unload(), safeStorage.closeDatabase() ]) .nodeify(done); }); }); beforeEach(function (done) { var wasConnected = false; agent = superagent.agent(); openSocketIo(server, agent, guestAccount, guestAccount) .then(function (result) { socket = result.socket; webgmeToken = result.webgmeToken; storage = NodeStorage.createStorage(null, result.webgmeToken, logger, gmeConfig); storage.open(function (networkState) { if (networkState === STORAGE_CONSTANTS.CONNECTED) { wasConnected = true; done(); } else if (wasConnected === false) { throw new Error('Unexpected network state: ' + networkState); } }); }) .catch(done); }); afterEach(function (done) { storage.close(function (err) { socket.disconnect(); done(err); }); }); function makeCommitPromise(storage, projectId, branchName, parents, rootHash, coreObjects, msg) { var deferred = Q.defer(); storage.makeCommit(projectId, branchName, parents, rootHash, coreObjects, msg, function (err, result) { if (err) { deferred.reject(err); } else { deferred.resolve(result); } } ); return deferred.promise; } it('should closeBranch if it is not open', function (done) { storage.openProject(projectName2Id(projectName)) .then(function () { return storage.closeBranch(projectName2Id(projectName), 'not_open'); }) .nodeify(done); }); it('should closeBranch if project is not open', function (done) { Q.nfcall(storage.closeBranch, projectName2Id(projectName), 'master') .nodeify(done); }); it('should open and close project', function (done) { storage.openProject(projectName2Id(projectName)) .then(function () { return storage.closeProject(projectName2Id(projectName)); }) .then(function () { return storage.closeProject(projectName2Id(projectName)); }) .nodeify(done); }); it('should return error if opening same project twice', function (done) { Q.nfcall(storage.openProject, projectName2Id(projectName)) .then(function () { return Q.nfcall(storage.openProject, projectName2Id(projectName)); }) .then(function () { throw new Error('Should have failed!'); }) .catch(function (err) { expect(err.message).to.include('project is already open'); }) .nodeify(done); }); it('should return error if opening branch with no project open', function (done) { var projectId = projectName2Id(projectName); Q.nfcall(storage.openBranch, projectId, 'master', null, null) .then(function () { throw new Error('Should have failed!'); }) .catch(function (err) { expect(err.message).to.include('project ' + projectId + ' is not opened'); }) .nodeify(done); }); it('should return error if opening branch twice', function (done) { Q.nfcall(storage.openProject, projectName2Id(projectName)) .then(function () { function hashUpdateHandler(data, commitQueue, updateQueue, callback) { callback(null, true); } function branchStatusHandler(/*branchStatus, commitQueue, updateQueue*/) { } return Q.nfcall(storage.openBranch, projectName2Id(projectName), 'master', hashUpdateHandler, branchStatusHandler); }) .then(function () { function hashUpdateHandler(data, commitQueue, updateQueue, callback) { callback(null, true); } function branchStatusHandler(/*branchStatus, commitQueue, updateQueue*/) { } return Q.nfcall(storage.openBranch, projectName2Id(projectName), 'master', hashUpdateHandler, branchStatusHandler); }) .then(function () { throw new Error('Should have failed!'); }) .catch(function (err) { expect(err.message).to.include('Branch is already open'); }) .nodeify(done); }); it('should forkBranch', function (done) { Q.nfcall(storage.openProject, projectName2Id(projectName)) .then(function () { function hashUpdateHandler(data, commitQueue, updateQueue, callback) { callback(null, true); } function branchStatusHandler(/*branchStatus, commitQueue, updateQueue*/) { } return Q.nfcall(storage.openBranch, projectName2Id(projectName), 'master', hashUpdateHandler, branchStatusHandler); }) .then(function () { return Q.ninvoke(storage, 'forkBranch', projectName2Id(projectName), 'master', 'forkName', null); }) .then(function (hash) { expect(hash).to.equal(importResult.commitHash); }) .nodeify(done); }); it('should return error if forking branch of non open project', function (done) { Q.ninvoke(storage, 'forkBranch', projectName2Id(projectName), 'master', 'forkName', null) .then(function () { throw new Error('Should have failed!'); }) .catch(function (err) { expect(err.message).to.include('project ' + projectName2Id(projectName) + ' is not opened.'); }) .nodeify(done); }); it('should return error if forking branch this is not open', function (done) { Q.nfcall(storage.openProject, projectName2Id(projectName)) .then(function () { return Q.ninvoke(storage, 'forkBranch', projectName2Id(projectName), 'master', 'forkName_fail', null); }) .then(function () { throw new Error('Should have failed!'); }) .catch(function (err) { expect(err.message).to.include('branch is not open'); }) .nodeify(done); }); it('should return error if forking branch with unknown commit-hash', function (done) { Q.nfcall(storage.openProject, projectName2Id(projectName)) .then(function () { function hashUpdateHandler(data, commitQueue, updateQueue, callback) { callback(null, true); } function branchStatusHandler(/*branchStatus, commitQueue, updateQueue*/) { } return Q.nfcall(storage.openBranch, projectName2Id(projectName), 'master', hashUpdateHandler, branchStatusHandler); }) .then(function () { return Q.ninvoke(storage, 'forkBranch', projectName2Id(projectName), 'master', 'forkName_fail2', '#un'); }) .then(function () { throw new Error('Should have failed!'); }) .catch(function (err) { expect(err.message).to.include('Could not find specified commitHash'); }) .nodeify(done); }); it('should makeCommit and fork', function (done) { Q.nfcall(storage.openProject, projectName2Id(projectName)) .then(function () { return Q.ninvoke(storage, 'makeCommit', projectName2Id(projectName), null, [importResult.commitHash], importResult.rootHash, {}, 'new commit'); }) .then(function () { function hashUpdateHandler(data, commitQueue, updateQueue, callback) { callback(null, true); } function branchStatusHandler(/*branchStatus, commitQueue, updateQueue*/) { } return Q.nfcall(storage.openBranch, projectName2Id(projectName), 'master', hashUpdateHandler, branchStatusHandler); }) .then(function () { return Q.ninvoke(storage, 'forkBranch', projectName2Id(projectName), 'master', 'commit_and_fork', null); }) .then(function (/*result*/) { // TODO: check commit hash }) .nodeify(done); }); it('should makeCommit', function (done) { Q.nfcall(storage.openProject, projectName2Id(projectName)) .then(function () { return Q.ninvoke(storage, 'makeCommit', projectName2Id(projectName), null, [importResult.commitHash], importResult.rootHash, {}, 'new commit'); }) .then(function (result) { expect(typeof result.hash).to.equal('string'); }) .nodeify(done); }); it('should setBranchHash w/o open branch', function (done) { Q.nfcall(storage.openProject, projectName2Id(projectName)) .then(function () { return Q.ninvoke(storage, 'setBranchHash', projectName2Id(projectName), 'b1', commitHash2, commitHash1); }) .then(function (result) { expect(result.status).to.equal(STORAGE_CONSTANTS.SYNCED); }) .nodeify(done); }); it('should setBranchHash with open branch', function (done) { Q.nfcall(storage.openProject, projectName2Id(projectName)) .then(function () { function hashUpdateHandler(data, commitQueue, updateQueue, callback) { callback(null, true); } function branchStatusHandler(/*branchStatus, commitQueue, updateQueue*/) { } return Q.nfcall(storage.openBranch, projectName2Id(projectName), 'b2', hashUpdateHandler, branchStatusHandler); }) .then(function () { return Q.ninvoke(storage, 'setBranchHash', projectName2Id(projectName), 'b2', commitHash2, commitHash1); }) .then(function (result) { expect(result.status).to.equal(STORAGE_CONSTANTS.SYNCED); }) .nodeify(done); }); it('should makeCommit with no open project', function (done) { Q.ninvoke(storage, 'makeCommit', projectName2Id(projectName), 'b5', [commitHash1], importResult.rootHash, {}, 'commit to non-open project') .then(function (result) { expect(result.status).to.equal(STORAGE_CONSTANTS.SYNCED); }) .nodeify(done); }); it('should persist commits with no open project', function (done) { var projectId = projectName2Id(projectName), commitQueueDump = { webgmeVersion: '2.10.0-beta3', projectId: projectId, branchName: 'master', branchStatus: 'AHEAD_SYNC', commitQueue: [ { rootHash: '#62d07a02c278b90e8ae7ed23ceb188405211c9e5', projectId: projectId, commitObject: { root: '#62d07a02c278b90e8ae7ed23ceb188405211c9e5', parents: [ '#653d24e79d36d5988d62722def123c0d8e67558c' ], updater: [ 'guest' ], time: 1487021619137, message: '[\nsetAttribute(/1,name,"FCO1")\n]', type: 'commit', __v: '1.1.0', _id: '#133dd1308018f8365cb398b5e574e9aced9aaa7d' }, coreObjects: { '#fecc6542f9dba6a548a4e3f5f6c8ce85994b9332': { type: 'patch', base: '#d51484d046f593d83a9e9663346a3c93f80d9018', patch: [ { op: 'replace', path: '/atr/name', value: 'FCO1' } ], _id: '#fecc6542f9dba6a548a4e3f5f6c8ce85994b9332' }, '#62d07a02c278b90e8ae7ed23ceb188405211c9e5': { type: 'patch', base: '#4649fd96b7356499351a6e37abbc6321b95ebc5e', patch: [ { op: 'replace', path: '/1', value: '#fecc6542f9dba6a548a4e3f5f6c8ce85994b9332' } ], _id: '#62d07a02c278b90e8ae7ed23ceb188405211c9e5' } }, changedNodes: { load: {}, unload: {}, update: { '/1': true, '': true }, partialUpdate: {} }, branchName: 'master' }, { rootHash: '#641facf9a9745dc25181bda68eed73e4b023964a', projectId: projectId, commitObject: { root: '#641facf9a9745dc25181bda68eed73e4b023964a', parents: [ '#133dd1308018f8365cb398b5e574e9aced9aaa7d' ], updater: [ 'guest' ], time: 1487021622093, message: '[\nsetRegistry(/1,position,{"x":79,"y":149})\n]', type: 'commit', __v: '1.1.0', _id: '#3fde1479876c769c39c4d545c64e797a5f9f84a5' }, coreObjects: { '#7ac30b6b189e6396445324d4172fbed5674ecc30': { type: 'patch', base: '#fecc6542f9dba6a548a4e3f5f6c8ce85994b9332', patch: [ { op: 'replace', path: '/reg/position', value: { x: 79, y: 149 } } ], _id: '#7ac30b6b189e6396445324d4172fbed5674ecc30' }, '#641facf9a9745dc25181bda68eed73e4b023964a': { type: 'patch', base: '#62d07a02c278b90e8ae7ed23ceb188405211c9e5', patch: [ { op: 'replace', path: '/1', value: '#7ac30b6b189e6396445324d4172fbed5674ecc30' } ], _id: '#641facf9a9745dc25181bda68eed73e4b023964a' } }, changedNodes: { load: {}, unload: {}, update: { '/1': true, '': true }, partialUpdate: {} }, branchName: 'master' } ] }; Q.ninvoke(storage, 'persistCommits', commitQueueDump.commitQueue) .then(function (commitHash) { expect(commitHash).to.equal(commitQueueDump.commitQueue[1].commitObject._id); return Q.ninvoke(storage, 'createBranch', projectName2Id(projectName), 'fromPersistCommits', commitHash); }) .then(function (result) { expect(result.status).to.equal(STORAGE_CONSTANTS.SYNCED); expect(result.hash).to.equal(commitQueueDump.commitQueue[1].commitObject._id); }) .nodeify(done); }); it('should makeCommit with open branch and get canceled', function (done) { Q.nfcall(storage.openProject, projectName2Id(projectName)) .then(function () { function hashUpdateHandler(data, commitQueue, updateQueue, callback) { callback(null, true); } function branchStatusHandler(/*branchStatus, commitQueue, updateQueue*/) { } return Q.nfcall(storage.openBranch, projectName2Id(projectName), 'b3', hashUpdateHandler, branchStatusHandler); }) .then(function () { return importResult.project.setBranchHash('b3', commitHash2, commitHash1); }) .then(function () { return Q.ninvoke(storage, 'makeCommit', projectName2Id(projectName), 'b3', [commitHash1], importResult.rootHash, {}, 'forked commit'); }) .then(function (result) { expect(result.status).to.equal(STORAGE_CONSTANTS.FORKED); }) .nodeify(done); }); it('should makeCommit with open branch and get canceled if not passing same commitHash as own branch', function (done) { Q.nfcall(storage.openProject, projectName2Id(projectName)) .then(function () { function hashUpdateHandler(data, commitQueue, updateQueue, callback) { callback(null, true); } function branchStatusHandler(/*branchStatus, commitQueue, updateQueue*/) { } return Q.nfcall(storage.openBranch, projectName2Id(projectName), 'b4', hashUpdateHandler, branchStatusHandler); }) .then(function () { return Q.ninvoke(storage, 'makeCommit', projectName2Id(projectName), 'b4', [commitHash2], importResult.rootHash, {}, 'forked commit'); }) .then(function (result) { expect(result.status).to.equal(STORAGE_CONSTANTS.CANCELED); }) .nodeify(done); } ); it('should makeCommit in a branch passing a new rootObject', function (done) { var forkName = 'makeCommit_fork_new_root'; Q.nfcall(storage.openProject, projectName2Id(projectName)) .then(function () { function hashUpdateHandler(data, commitQueue, updateQueue, callback) { callback(null, true); } function branchStatusHandler(/*branchStatus, commitQueue, updateQueue*/) { } return Q.nfcall(storage.openBranch, projectName2Id(projectName), 'master', hashUpdateHandler, branchStatusHandler); }) .then(function () { return Q.ninvoke(storage, 'forkBranch', projectName2Id(projectName), 'master', forkName, null); }) .then(function () { function hashUpdateHandler(data, commitQueue, updateQueue, callback) { callback(null, true); } function branchStatusHandler(/*branchStatus, commitQueue, updateQueue*/) { } return Q.ninvoke(storage, 'openBranch', projectName2Id(projectName), forkName, hashUpdateHandler, branchStatusHandler); }) .then(function () { importResult.core.setAttribute(importResult.rootNode, 'name', 'New name'); importResult.core.persist(importResult.rootNode); return makeCommitPromise(storage, projectName2Id(projectName), forkName, [importResult.commitHash], importResult.rootHash, {}, 'new commit'); }) .then(function (result) { expect(typeof result.hash).to.equal('string'); expect(result.status).to.equal(STORAGE_CONSTANTS.SYNCED); }) .nodeify(done); }); it('should makeCommit in a branch referring to an existing rootObject', function (done) { var forkName = 'makeCommit_fork_same_root'; Q.nfcall(storage.openProject, projectName2Id(projectName)) .then(function () { function hashUpdateHandler(data, commitQueue, updateQueue, callback) { callback(null, true); } function branchStatusHandler(/*branchStatus, commitQueue, updateQueue*/) { } return Q.nfcall(storage.openBranch, projectName2Id(projectName), 'master', hashUpdateHandler, branchStatusHandler); }) .then(function () { return Q.ninvoke(storage, 'forkBranch', projectName2Id(projectName), 'master', forkName, null); }) .then(function () { function hashUpdateHandler(data, commitQueue, updateQueue, callback) { callback(null, true); } function branchStatusHandler(/*branchStatus, commitQueue, updateQueue*/) { } return Q.ninvoke(storage, 'openBranch', projectName2Id(projectName), forkName, hashUpdateHandler, branchStatusHandler); }) .then(function () { return makeCommitPromise(storage, projectName2Id(projectName), forkName, [importResult.commitHash], importResult.rootHash, {}, 'new commit'); }) .then(function (result) { expect(typeof result.hash).to.equal('string'); expect(result.status).to.equal(STORAGE_CONSTANTS.SYNCED); }) .nodeify(done); }); it.skip('makeCommit should failed in a branch referring to a non-existing rootObject', function (done) { // We no longer load the root node in these cases. var forkName = 'makeCommit_fork_fail'; Q.nfcall(storage.openProject, projectName2Id(projectName)) .then(function () { function hashUpdateHandler(data, commitQueue, updateQueue, callback) { callback(null, true); } function branchStatusHandler(/*branchStatus, commitQueue, updateQueue*/) { } return Q.nfcall(storage.openBranch, projectName2Id(projectName), 'master', hashUpdateHandler, branchStatusHandler); }) .then(function () { return Q.ninvoke(storage, 'forkBranch', projectName2Id(projectName), 'master', forkName, null); }) .then(function () { function hashUpdateHandler(data, commitQueue, updateQueue, callback) { callback(null, true); } function branchStatusHandler(/*branchStatus, commitQueue, updateQueue*/) { } return Q.ninvoke(storage, 'openBranch', projectName2Id(projectName), forkName, hashUpdateHandler, branchStatusHandler); }) .then(function () { return makeCommitPromise(storage, projectName2Id(projectName), forkName, [importResult.commitHash], '#doesNotExist', {}, 'new commit'); }) .then(function () { done(new Error('Should have failed when makeCommit refers to non-existing root-object.')); }) .catch(function (err) { expect(err.message).to.include('Failed loading referred rootObject'); done(); }) .done(); }); it('should pull changes if another client changes the branch', function (done) { var storageOther, projectOther, newCommitHash, openingBranch = true, updateReceivedDeferred = Q.defer(), forkName = 'pullChanges_fork', coreOther, gmeConfigOther = testFixture.getGmeConfig(); Q.nfcall(storage.openProject, projectName2Id(projectName)) .then(function () { function hashUpdateHandler(data, commitQueue, updateQueue, callback) { callback(null, true); } function branchStatusHandler(/*branchStatus, commitQueue, updateQueue*/) { } return Q.ninvoke(storage, 'openBranch', projectName2Id(projectName), 'master', hashUpdateHandler, branchStatusHandler); }) .then(function () { return Q.ninvoke(storage, 'forkBranch', projectName2Id(projectName), 'master', forkName, null); }) .then(function () { function hashUpdateHandler(data, commitQueue, updateQueue, callback) { // TRICKY: new commit hash will be set later by the storageOther user. We are waiting for the update // from the original storage. // return with a single commit object callback(null, true); if (openingBranch === false) { updateReceivedDeferred.resolve(data.commitData); } } function branchStatusHandler(/*branchStatus, commitQueue, updateQueue*/) { } return Q.ninvoke(storage, 'openBranch', projectName2Id(projectName), forkName, hashUpdateHandler, branchStatusHandler); }) .then(function () { var deferred = Q.defer(); openingBranch = false; storageOther = NodeStorage.createStorage(null, webgmeToken, logger, gmeConfigOther); storageOther.open(function (networkState) { if (networkState === STORAGE_CONSTANTS.CONNECTED) { deferred.resolve(); } else { deferred.reject(new Error('Unexpected network state: ' + networkState)); } }); return deferred.promise; }) .then(function () { return Q.nfcall(storageOther.openProject, projectName2Id(projectName)); }) .then(function (project) { projectOther = project[0]; coreOther = new testFixture.Core(projectOther, { globConf: gmeConfigOther, logger: logger }); function hashUpdateHandler(data, commitQueue, updateQueue, callback) { callback(null, true); } function branchStatusHandler(/*branchStatus, commitQueue, updateQueue*/) { } return Q.ninvoke(storageOther, 'openBranch', projectName2Id(projectName), forkName, hashUpdateHandler, branchStatusHandler); }) .then(function () { return coreOther.loadRoot(importResult.rootHash); }) .then(function (root) { var persisted; coreOther.setAttribute(root, 'name', 'New name'); persisted = coreOther.persist(root); expect(persisted.rootHash).not.to.equal(undefined); expect(persisted.objects[persisted.rootHash]).to.have.keys( ['oldHash', 'newHash', 'oldData', 'newData']); return projectOther.makeCommit(forkName, [importResult.commitHash], persisted.rootHash, persisted.objects, 'new commit'); }) .then(function (result) { newCommitHash = result.hash; return updateReceivedDeferred.promise; }) .then(function (commit) { expect(commit.commitObject._id).to.equal(newCommitHash); expect(commit.changedNodes.update['']).to.equal(true); }) .nodeify(done); }); it('should pull changes if another client changes the branch with patchRoot', function (done) { var storageOther, newCommitHash, openingBranch = true, updateReceivedDeferred = Q.defer(), forkName = 'pullChanges_fork_patchRoot'; Q.nfcall(storage.openProject, projectName2Id(projectName)) .then(function () { function hashUpdateHandler(data, commitQueue, updateQueue, callback) { callback(null, true); } function branchStatusHandler(/*branchStatus, commitQueue, updateQueue*/) { } return Q.ninvoke(storage, 'openBranch', projectName2Id(projectName), 'master', hashUpdateHandler, branchStatusHandler); }) .then(function () { return Q.ninvoke(storage, 'forkBranch', projectName2Id(projectName), 'master', forkName, null); }) .then(function () { function hashUpdateHandler(data, commitQueue, updateQueue, callback) { // TRICKY: new commit hash will be set later by the storageOther user. We are waiting for the update // from the original storage. // return with a single commit object callback(null, true); if (openingBranch === false) { updateReceivedDeferred.resolve(data.commitData); } } function branchStatusHandler(/*branchStatus, commitQueue, updateQueue*/) { } return Q.ninvoke(storage, 'openBranch', projectName2Id(projectName), forkName, hashUpdateHandler, branchStatusHandler); }) .then(function () { var deferred = Q.defer(); openingBranch = false; storageOther = NodeStorage.createStorage(null, null, logger, gmeConfig); storageOther.open(function (networkState) { if (networkState === STORAGE_CONSTANTS.CONNECTED) { deferred.resolve(); } else { deferred.reject(new Error('Unexpected network state: ' + networkState)); } }); return deferred.promise; }) .then(function () { return Q.nfcall(storageOther.openProject, projectName2Id(projectName)); }) .then(function () { function hashUpdateHandler(data, commitQueue, updateQueue, callback) { callback(null, true); } function branchStatusHandler(/*branchStatus, commitQueue, updateQueue*/) { } return Q.ninvoke(storageOther, 'openBranch', projectName2Id(projectName), forkName, hashUpdateHandler, branchStatusHandler); }) .then(function () { return importResult.core.loadRoot(importResult.rootHash); }) .then(function (root) { var persisted; // FIXME: Bogus modification to get makeCommit working. importResult.core.setAttribute(root, 'name', 'New name'); persisted = importResult.core.persist(root); expect(persisted.rootHash).not.to.equal(undefined); expect(persisted.objects[persisted.rootHash]) .to.have.keys(['newHash', 'oldHash', 'newData', 'oldData']); return Q.ninvoke(storageOther, 'makeCommit', projectName2Id(projectName), forkName, [importResult.commitHash], persisted.rootHash, persisted.objects, 'newer commit'); }) .then(function (result) { newCommitHash = result.hash; return updateReceivedDeferred.promise; }) .then(function (commit) { expect(commit.commitObject._id).to.equal(newCommitHash); }) .nodeify(done); }); // SimpleRequest queuing function getSimpleRequestParams(commitHash, branchName) { var params = { command: testFixture.CONSTANTS.SERVER_WORKER_REQUESTS.CHECK_CONSTRAINTS, checkType: 'META', includeChildren: false, nodePaths: ['/1'], projectId: projectName2Id(projectName) }; if (commitHash) { params.commitHash = commitHash; } if (branchName) { params.branchName = branchName; } return params; } it('should not initiate request until queued commit was inserted at server', function (done) { this.timeout(3000); storage.openProject(projectName2Id(projectName)) .then(function () { function hashUpdateHandler(data, commitQueue, updateQueue, callback) { // This is invoked after makeCommit and this point the commit hasn't been sent to the // server. It has been queued so the simple-request should be added if (data.local) { storage.simpleRequest(getSimpleRequestParams(data.commitData.commitObject._id), function (err) { if (err) { done(err); } else { done(); } }); // This is needed to reduce the risk of false positives when requests weren't queued. setTimeout(function () { callback(null, true); }, 1000); } else { // This is the initial load at branch open. callback(null, true); } } return storage.openBranch(projectName2Id(projectName), 'b6', hashUpdateHandler, testFixture.noop); }) .then(function () { // Branch opened and commit-loaded - make a commit to trigger hashUpdateHandler return Q.ninvoke(storage, 'makeCommit', projectName2Id(projectName), 'b6', [originalHash], importResult.rootHash, {}, 'queued commit'); }) .catch(done); }); it('should abort a queued simpleRequest is the branch is closed before the commit was made', function (done) { storage.openProject(projectName2Id(projectName)) .then(function () { function hashUpdateHandler(data, commitQueue, updateQueue, callback) { // This is invoked after makeCommit and this point the commit hasn't been sent to the // server. It has been queued so the simple-request should be added if (data.local) { // 3) Initiate the simpleRequest (will be queued at the commit). storage.simpleRequest(getSimpleRequestParams(data.commitData.commitObject._id), function (err) { try { // 5) The worker-request is aborted since the queued commit was flushed when // the branch was closed. expect(!!err).to.equal(true); expect(err.message).to.include('Queued worker request was aborted'); done(); } catch (e) { done(e); } }); // Abort the commit -> makeCommit returns error callback(null, false); } else { // 1) This is the initial load at branch open. callback(null, true); } } return storage.openBranch(projectName2Id(projectName), 'b7', hashUpdateHandler, testFixture.noop); }) .then(function () { // 2) Branch opened and commit-loaded - make a commit to trigger hashUpdateHandler return Q.ninvoke(storage, 'makeCommit', projectName2Id(projectName), 'b7', [originalHash], importResult.rootHash, {}, 'queued and aborted commit'); }) .catch(function (err) { if (err.message.indexOf('Commit halted') < 0) { done(err); } else { // 4) close the branch storage.closeBranch(projectName2Id(projectName), 'b7').catch(done); } }); }); it('should proceed as normal if referring to a commit that is not queued', function (done) { // This is mainly to increase the coverage. storage.openProject(projectName2Id(projectName)) .then(function () { function hashUpdateHandler(data, commitQueue, updateQueue, callback) { if (data.local) { storage.simpleRequest(getSimpleRequestParams(originalHash), function (err) { if (err) { done(err); } else { done(); } }); callback(null, true); } else { callback(null, true); } } return storage.openBranch(projectName2Id(projectName), 'b8', hashUpdateHandler, testFixture.noop); }) .then(function () { return Q.ninvoke(storage, 'makeCommit', projectName2Id(projectName), 'b8', [originalHash], importResult.rootHash, {}, 'queued commit with no relation to the request'); }) .catch(done); }); it('should queue commit when branchName and commitHash specified', function (done) { storage.openProject(projectName2Id(projectName)) .then(function () { function hashUpdateHandler(data, commitQueue, updateQueue, callback) { var params; if (data.local) { params = getSimpleRequestParams(data.commitData.commitObject._id, 'b9'); storage.simpleRequest(params, function (err) { try { expect(!!err).to.equal(true); expect(err.message).to.include('Queued worker request was aborted'); done(); } catch (e) { done(e); } }); callback(null, false); } else { callback(null, true); } } return storage.openBranch(projectName2Id(projectName), 'b9', hashUpdateHandler, testFixture.noop); }) .then(function () { return Q.ninvoke(storage, 'makeCommit', projectName2Id(projectName), 'b9', [originalHash], importResult.rootHash, {}, 'queued and aborted commit'); }) .catch(function (err) { if (err.message.indexOf('Commit halted') < 0) { done(err); } else { storage.closeBranch(projectName2Id(projectName), 'b9').catch(done); } }); }); it('should queue a plugin execution', function (done) { storage.openProject(projectName2Id(projectName)) .then(function () { function hashUpdateHandler(data, commitQueue, updateQueue, callback) { var params; if (data.local) { params = { command: testFixture.CONSTANTS.SERVER_WORKER_REQUESTS.EXECUTE_PLUGIN, name: 'MinimalWorkingExample', context: { managerConfig: { project: projectName2Id(projectName), activeNode: '', branchName: 'b11' } } }; storage.simpleRequest(params, function (err) { try { expect(!!err).to.equal(true); expect(err.message).to.include('Queued worker request was aborted'); done(); } catch (e) { done(e); } }); callback(null, false); } else { callback(null, true); } } return storage.openBranch(projectName2Id(projectName), 'b11', hashUpdateHandler, testFixture.noop); }) .then(function () { return Q.ninvoke(storage, 'makeCommit', projectName2Id(projectName), 'b11', [originalHash], importResult.rootHash, {}, 'queued and aborted commit'); }) .catch(function (err) { if (err.message.indexOf('Commit halted') < 0) { done(err); } else { storage.closeBranch(projectName2Id(projectName), 'b11').catch(done); } }); }); });
Given three linked lists, say a, b and c, find one node from each list such that the sum of the values of the nodes is equal to a given number. For example, if the three linked lists are 12->6->29, 23->5->8 and 90->20->59, and the given number is 101, the output should be tripel “6 5 90″.In the following solutions, size of all three linked lists is assumed same for simplicity of analysis. The following solutions work for linked lists of different sizes also.A simple method to solve this problem is to run three nested loops. The outermost loop picks an element from list a, the middle loop picks an element from b and the innermost loop picks from c. The innermost loop also checks whether the sum of values of current nodes of a, b and c is equal to given number. The time complexity of this method will be O(n^3).Sorting can be used to reduce the time complexity to O(n*n). Following are the detailed steps. 1) Sort list b in ascending order, and list c in descending order. 2) After the b and c are sorted, one by one pick an element from list a and find the pair by traversing both b and c. See isSumSorted() in the following code. The idea is similar to Quadratic algorithm of 3 sum problem.Following code implements step 2 only. The solution can be easily modified for unsorted lists by adding the merge sort code discussed here. Output: Triplet Found: 15 2 8 Time complexity: The linked lists b and c can be sorted in O(nLogn) time using Merge Sort (See this). The step 2 takes O(n*n) time. So the overall time complexity is O(nlogn) + O(nlogn) + O(n*n) = O(n*n). In this approach, the linked lists b and c are sorted first, so their original order will be lost. If we want to retain the original order of b and c, we can create copy of b and c. This article is compiled by Abhinav Priyadarshi and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
var webpack = require('webpack'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const HTMLWebpackPlugin = require('html-webpack-plugin'); const CleanWebpackPlugin = require('clean-webpack-plugin'); module.exports = { entry: { main: './src/client/main.js', admin: './src/client/admin.js', vendor: [ '@blueprintjs/core', 'axios', 'babel-polyfill', 'core-js', 'history', 'lodash.merge', 'localforage', 'marked', 'react', 'react-animate-on-scroll', 'react-apollo', 'redux-devtools-extension', 'react-dom', 'react-redux', 'react-responsive', 'react-router-dom', 'react-transition-group', 'redux-storage', 'redux', 'redux-logger', 'redux-promise-middleware', 'redux-storage-engine-localforage', 'redux-thunk' ] }, module: { rules: [ { test: /\.js?$/, exclude: /(node_modules)/, use: [ { loader: 'babel-loader', options: { presets: ['react', 'es2015', 'stage-0'], plugins: ['react-html-attrs', 'transform-class-properties', 'transform-decorators-legacy'] } } ] }, { test: /\.scss$/, use: ExtractTextPlugin.extract({ fallback: 'style-loader', use: [ { loader: 'css-loader', options: { minimize: true, sourceMap: true } }, { loader: 'sass-loader', options: { sourceMap: true } } ] }) }, { test: /\.(ico)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'file-loader', options: {name: '[name].[ext]'} }, { test: /\.(woff|woff2|eot|ttf|otf)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'file-loader', options: {name: 'fonts/[name].[ext]'} }, { test: /\.(jpg|gif|png|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'file-loader', options: {name: 'images/[name].[ext]'} } ] }, output: { path: __dirname + '/../public', filename: 'js/[name]-[chunkhash].min.js', publicPath: '/' }, plugins: [ new CleanWebpackPlugin( ['public'], { root: __dirname + '/..' } ), new webpack.DefinePlugin({ 'process.env':{ 'NODE_ENV': JSON.stringify(process.env.NODE_ENV) } }), new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks: Infinity }), new ExtractTextPlugin('css/[name]-[chunkhash].css'), new HTMLWebpackPlugin({ filename: 'index.html', chunks: ['vendor', 'main'], template: 'src/client/assets/index.html' }), new HTMLWebpackPlugin({ filename: 'admin.html', chunks: ['vendor', 'admin'], template: 'src/client/assets/admin.html' }) ], devtool: 'source-map' };
/* * virtual-dom hook for drawing to the canvas element. */ class CanvasHook { constructor(peaks, offset, bits, color) { this.peaks = peaks; // http://stackoverflow.com/questions/6081483/maximum-size-of-a-canvas-element this.offset = offset; this.color = color; this.bits = bits; } static drawFrame(cc, h2, x, minPeak, maxPeak) { const min = Math.abs(minPeak * h2); const max = Math.abs(maxPeak * h2); // draw max cc.fillRect(x, 0, 1, h2 - max); // draw min cc.fillRect(x, h2 + min, 1, h2 - min); } hook(canvas, prop, prev) { // canvas is up to date if (prev !== undefined && (prev.peaks === this.peaks)) { return; } const len = canvas.width; const cc = canvas.getContext('2d'); const h2 = canvas.height / 2; const maxValue = 2 ** (this.bits - 1); cc.clearRect(0, 0, canvas.width, canvas.height); cc.fillStyle = this.color; for (let i = 0; i < len; i += 1) { const minPeak = this.peaks[(i + this.offset) * 2] / maxValue; const maxPeak = this.peaks[((i + this.offset) * 2) + 1] / maxValue; CanvasHook.drawFrame(cc, h2, i, minPeak, maxPeak); } } } export default CanvasHook;
var app = angular.module('js'); app.factory('PlatformSvc', function(conf) { return { host: undefined, isKiso: function() { return !!this.host && (this.host.indexOf('kiso') !== -1 || this.host.indexOf('projects-jd.bz') !== -1 ); }, isJugendsommer: function() { return !!this.host && this.host.indexOf('jugendsommer') !== -1; }, isJDBL: function() { return !!this.host && this.host.indexOf('jd-bozenland') !== -1; }, isJDUL: function() { return !!this.host && this.host.indexOf('jdsummer') !== -1; }, isJSGries: function() { return !!this.host && this.host.indexOf('jungschargries') !== -1; }, isJDWT: function() { return !! this.host && this.host.indexOf('wipptal') !== -1; }, isTest: function() { return !!this.host && this.host.indexOf('localhost') !== -1; }, getTitle: function() { if(this.isKiso()) return 'Kindersommer'; else if(this.isJugendsommer()) return 'Jugendsommer'; else if(this.isJDBL()) return 'Jugenddienst Bozen Land'; else if(this.isJDUL()) return 'Jugenddienst Unterland'; else if(this.isJDWT()) return 'Jugenddienst Wipptal'; else if(this.isJSGries()) return 'Jungschar Gries'; else if(this.isTest()) return 'Test'; else return 'Title'; }, getCities: function() { if(this.isKiso()) return conf.cities_kiso; else if(this.isJugendsommer()) return conf.cities_jdbl; else if(this.isJDBL()) return conf.cities_jdbl; else if(this.isJDUL()) return conf.cities_jdul; else if(this.isJSGries()) return conf.cities_kiso; else return ['test', 'Andere']; }, getDefaultCity: function() { if(this.isKiso()) return 'Bozen'; else if(this.isJugendsommer()) return 'Deutschnofen'; else if(this.isJDBL()) return 'Deutschnofen'; else if(this.isJDUL()) return ''; else if(this.isJSGries()) return 'Bozen'; else return 'Andere'; }, getDefaultSchoolLevel: function() { if(this.isKiso()) return 'Bozen'; else if(this.isJugendsommer()) return 'Deutschnofen'; else if(this.isJDBL()) return 'Deutschnofen'; else if(this.isJDUL()) return ''; else if(this.isJSGries()) return 'Bozen'; else return 'Andere'; } }; });
console.log("Hi Girl Coder, please make sure you join our community at meetup.com/GirlCode. Boys are welcome too!"); $(document).ready(function() { $('.social-button, .social-button-footer').mouseenter(function() { $(this).effect( 'bounce', { times: 1 }, 'slow'); }); }); // slow scroll to content $(document).ready(function() { var fullUrl= $(location).attr('href'); var hashPresent = fullUrl.match('\\?(.*)'); if (hashPresent[0][0] === "?" ) { $('html, body').animate({ scrollTop: $('#' + hashPresent[1]).offset().top -150 }, 1250); return false; } }) $('.scroll').click(function(event){ event.preventDefault(); $('html, body').animate({ scrollTop: $( $.attr(this,'href') ).offset().top -150 }, 1250); return false; }); // fade in and out background image landingspage $(function(){ var t = setInterval(function(){ $('.bg-image').last().fadeOut(2000,function(){ $this = $(this); $parent = $this.parent(); $this.remove().css('display','block'); $parent.prepend($this); }); },3500); }); $(document).ready(function() { $('.contact-cta, .cta-join-container').mouseenter(function(){ $(this).effect( 'bounce', { distance: 10, times: 1 }, 'slow'); }); $('.contact-social-element').children().mouseenter(function() { $(this).children('img').effect( 'bounce', { times: 1 }, 'slow'); }); $('.social-button, .social-button-footer').mouseenter(function() { $(this).effect( 'bounce', { times: 1 }, 'slow'); }); }); // =CONTACT-PAGE MEETUP API REQUEST // =INPUTS var urls = []; // members urls[0] = "https://api.meetup.com/girlcode?photo-host=public&sig_id=196092929&sig=ca1b24075a0729853813027c08cb66ade21c6443"; // upcoming events urls[1] = "https://api.meetup.com/girlcode/events?photo-host=public&page=5&sig_id=196092929&sig=d38879607cf337c44247f12416ef86764e69bef4"; // past events urls[2] = "https://api.meetup.com/girlcode/events?photo-host=public&page=5&sig_id=196092929&status=past&sig=6f8ac70249c033f498e01394ae5e9bb50526571c"; // TEST URL // urls[1] = 'https://api.meetup.com/ocamsterdam/events?photo-host=public&page=5&sig_id=196092929&sig=1f20a3049b0ce2de8d1341dffa1d6c32323f879e'; // capped at 5 upcoming/past events, edit page=5 in url for to increase/decrease. // =REQUESTS for (var i = 0, requests = [], requestsJSON = []; i < urls.length; i++) { requests[i] = new XMLHttpRequest(); requests[i].onreadystatechange = processMeetupData; requests[i].open ("GET", urls[i], false); requests[i].withCredentials = true; requests[i].send(); } // =JSON PARSING function processMeetupData () { if (this.readyState == 4 && this.status == 200) { requestsJSON[i] = JSON.parse(this.responseText); } } // =DATA TO HTML if (document.getElementsByClassName('cta-join-members')[0]) { document.getElementsByClassName('cta-join-members')[0].innerHTML = requestsJSON[0].members; } if (document.getElementsByClassName('calendar-container')[0]) { for (var x = 0, z = 5, y = requestsJSON[2].length - 1, dateString = '', eventLinks = document.getElementsByClassName('event-link'), eventNames = document.getElementsByClassName('event-name'), eventDays = document.getElementsByClassName('event-day'), eventTimes = document.getElementsByClassName('event-time'), eventVenueNames = document.getElementsByClassName('event-venue-name'), // eventGoings = document.getElementsByClassName('event-going'), eventDates = document.getElementsByClassName('event-date'), eventMonths = document.getElementsByClassName('event-month'); x < requestsJSON[1].length, y >= 0; z++, y--, x++) { if(requestsJSON[1][x]) { dateString = String(new Date(requestsJSON[1][x]['time'])); eventNames[x].innerHTML = requestsJSON[1][x]['name']; eventLinks[x].href = requestsJSON[1][x]['link']; eventDays[x].innerHTML = dateString.slice(0,3); eventTimes[x].innerHTML = dateString.slice(16,21); eventVenueNames[x].innerHTML = requestsJSON[1][x]['venue']['name']; // eventGoings[x].innerHTML = requestsJSON[1][x]['yes_rsvp_count'] + ' going'; eventDates[x].innerHTML = dateString.slice(8,10); eventMonths[x].innerHTML = dateString.slice(4,7); document.getElementsByClassName('event-coming-soon')[0].style.display = "none"; } if(requestsJSON[2][y]) { dateString = String(new Date(requestsJSON[2][y]['time'])); eventNames[z].innerHTML = requestsJSON[2][y]['name']; eventLinks[z].href = requestsJSON[2][y]['link']; // eventDays[x].innerHTML = dateString.slice(0,3); eventTimes[z].innerHTML = dateString.slice(16,21); eventVenueNames[z].innerHTML = requestsJSON[2][y]['venue']['name']; // eventGoings[x].innerHTML = requestsJSON[2][y]['yes_rsvp_count'] + ' going'; eventDates[z].innerHTML = dateString.slice(8,10); eventMonths[z].innerHTML = dateString.slice(4,7); } } };
DS.LSSerializer = DS.JSONSerializer.extend({ addBelongsTo: function(data, record, key, association) { data[key] = record.get(key + '.id'); }, addHasMany: function(data, record, key, association) { data[key] = record.get(key).map(function(record) { return record.get('id'); }); }, // extract expects a root key, we don't want to save all these keys to // localStorage so we generate the root keys here extract: function(loader, json, type, record) { this._super(loader, this.rootJSON(json, type), type, record); }, extractMany: function(loader, json, type, records) { this._super(loader, this.rootJSON(json, type, 'pluralize'), type, records); }, rootJSON: function(json, type, pluralize) { var root = this.rootForType(type); if (pluralize == 'pluralize') { root = this.pluralize(root); } var rootedJSON = {}; rootedJSON[root] = json; return rootedJSON; } }); DS.LSAdapter = DS.Adapter.extend(Ember.Evented, { init: function() { this._loadData(); }, generateIdForRecord: function() { return Math.random().toString(32).slice(2).substr(0,5); }, serializer: DS.LSSerializer.create(), find: function(store, type, id) { var namespace = this._namespaceForType(type); this._async(function(){ var copy = Ember.copy(namespace.records[id]); this.didFindRecord(store, type, copy, id); }); }, findMany: function(store, type, ids) { var namespace = this._namespaceForType(type); this._async(function(){ var results = []; for (var i = 0; i < ids.length; i++) { results.push(Ember.copy(namespace.records[ids[i]])); } this.didFindMany(store, type, results); }); }, // Supports queries that look like this: // // { // <property to query>: <value or regex (for strings) to match>, // ... // } // // Every property added to the query is an "AND" query, not "OR" // // Example: // // match records with "complete: true" and the name "foo" or "bar" // // { complete: true, name: /foo|bar/ } findQuery: function(store, type, query, recordArray) { var namespace = this._namespaceForType(type); this._async(function() { var results = this.query(namespace.records, query); this.didFindQuery(store, type, results, recordArray); }); }, query: function(records, query) { var results = []; var id, record, property, test, push; for (id in records) { record = records[id]; for (property in query) { test = query[property]; push = false; if (Object.prototype.toString.call(test) == '[object RegExp]') { push = test.test(record[property]); } else { push = record[property] === test; } } if (push) { results.push(record); } } return results; }, findAll: function(store, type) { var namespace = this._namespaceForType(type); this._async(function() { var results = []; for (var id in namespace.records) { results.push(Ember.copy(namespace.records[id])); } this.didFindAll(store, type, results); }); }, createRecords: function(store, type, records) { var namespace = this._namespaceForType(type); records.forEach(function(record) { this._addRecordToNamespace(namespace, record); }, this); this._async(function() { this._didSaveRecords(store, type, records); }); }, updateRecords: function(store, type, records) { var namespace = this._namespaceForType(type); this._async(function() { records.forEach(function(record) { var id = record.get('id'); namespace.records[id] = record.serialize({includeId:true}); }, this); this._didSaveRecords(store, type, records); }); }, deleteRecords: function(store, type, records) { var namespace = this._namespaceForType(type); this._async(function() { records.forEach(function(record) { var id = record.get('id'); delete namespace.records[id]; }); this._didSaveRecords(store, type, records); }); }, dirtyRecordsForHasManyChange: function(dirtySet, parent, relationship) { dirtySet.add(parent); }, dirtyRecordsForBelongsToChange: function(dirtySet, child, relationship) { dirtySet.add(child); }, // private _getNamespace: function() { return this.namespace || 'DS.LSAdapter'; }, _loadData: function() { var storage = localStorage.getItem(this._getNamespace()); this._data = storage ? JSON.parse(storage) : {}; }, _didSaveRecords: function(store, type, records) { var success = this._saveData(); if (success) { store.didSaveRecords(records); } else { records.forEach(function(record) { store.recordWasError(record); }); this.trigger('QUOTA_EXCEEDED_ERR', records); } }, _saveData: function() { try { localStorage.setItem(this._getNamespace(), JSON.stringify(this._data)); return true; } catch(error) { if (error.name == 'QUOTA_EXCEEDED_ERR') { return false; } else { throw new Error(error); } } }, _namespaceForType: function(type) { var namespace = type.url || type.toString(); return this._data[namespace] || ( this._data[namespace] = {records: {}} ); }, _addRecordToNamespace: function(namespace, record) { var data = record.serialize({includeId: true}); namespace.records[data.id] = data; }, _async: function(callback) { var _this = this; setTimeout(function(){ Ember.run(_this, callback); }, 1); } });
(function (exports) { 'use strict'; //import webeid from './vendor/web-eid/web-eid.js'; //TODO configure rollup so, that import works function guid() { function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); } function getGuid() { var cookiestring=RegExp("guid[^;]+").exec(document.cookie); return unescape(!!cookiestring ? cookiestring.toString().replace(/^[^=]+./,"") : ""); } function parseMessage(message){ try { var r = JSON.parse(message); console.log(r); return r; } catch (e) { return {error:e} } } const autoReconnectInterval = 1000 * 3; const autoReconnectMaxCount = 3; let autoReconnectCounter = 0; var authenticatedWebSocket = function (url) { return new Promise(function (resolve, reject) { var socket = new WebSocket(url) socket.onclose = function (c){ // 1000 CLOSE_NORMAL // 1008 Policy Violation if (c.code !== 1000 && c.code !== 1008) { // server sent unclean close, we try to reconnect if (autoReconnectCounter < autoReconnectMaxCount ) { autoReconnectCounter += 1; console.log('reconnect '+ url + ' in ' + autoReconnectInterval + ' count ' + autoReconnectCounter) setTimeout(function(){ console.log("reconnecting..."); authenticatedWebSocket(url) .then(function (ws) {resolve(ws);}) .catch(function(e) {reject(e)}); },autoReconnectInterval); } else { console.log("reached autoReconnectMaxCount "+autoReconnectMaxCount); reject(new Error('server has disappeared')); } } else { // server sent clean close console.dir(c); reject(new Error('server closed connection')); } } socket.onmessage = function (m) { try { var msg = JSON.parse(m.data); } catch(e) { console.log('Server did not send JSON'); reject(new Error('please contact your sysadmin!')); } if (!msg.nonce){ console.log('Server did not send nonce'); reject(new Error('please contact your sysadmin!')); } else { webeid.authenticate(msg.nonce).then(function (token) { socket.send(JSON.stringify({token: token})); console.log('sent token to server'); socket.onmessage = function (m){ //if server answers, then we are ok console.dir(m); socket.onclose = undefined; socket.onmessage = undefined; resolve(socket); } }, function (reason) { // TODO handle reasons socket.send(JSON.stringify({user : reason.message})); socket.close(); reject(new Error(reason.message)); /* if (reason.message == 'CKR_FUNCTION_CANCELED'){ reject(new Error('user cancel')); } else { // !? try again ... } */ }); } // !msg.nonce } //onmessage }); } // ----- // https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie#Example_5_Do_something_only_once_–_a_general_library function executeOnce () { var argc = arguments.length, bImplGlob = typeof arguments[argc - 1] === "string"; if (bImplGlob) { argc++; } if (argc < 3) { throw new TypeError("executeOnce - not enough arguments"); } var fExec = arguments[0], sKey = arguments[argc - 2]; if (typeof fExec !== "function") { throw new TypeError("executeOnce - first argument must be a function"); } if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { throw new TypeError("executeOnce - invalid identifier"); } if (decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) === "1") { return false; } fExec.apply(argc > 3 ? arguments[1] : null, argc > 4 ? Array.prototype.slice.call(arguments, 2, argc - 2) : []); document.cookie = encodeURIComponent(sKey) + "=1; expires=Fri, 31 Dec 9999 23:59:59 GMT" + (bImplGlob || !arguments[argc - 1] ? "; path=/" : ""); return true; } function hello(logo, html) { function alertCookie (sMsg) { var expiration_date = new Date(); var cookie_string = ''; expiration_date.setFullYear(expiration_date.getFullYear() + 1); // Build the set-cookie string: var uuid = guid(); cookie_string = "guid=" + uuid + "; path=/; expires=" + expiration_date.toUTCString(); // Create or update the cookie: document.cookie = cookie_string; alert(sMsg); } executeOnce(alertCookie, null, "this site uses cookies", "executeOnce"); const CUID = getGuid(); const wsPING_INTERVAL = 30000; function msg(m){ var div = document.createElement("div"); var content = document.createTextNode(m); div.appendChild(content); html.appendChild(div); //return div; } function btn(m,f){ var theButton = document.createElement("button"); theButton.innerHTML = m; theButton.onclick = f; theButton.className = "btn"; return theButton; } function input(m,f){ var div = document.createElement("div"); var bt = btn("<div style='transform: rotate(45deg);'>&#9906;</div>",f) div.appendChild(bt); bt.insertAdjacentHTML('beforebegin','<input "type=text" name="q" className="message-text">'); return div; } msg('looking for web-eid, please wait ...') webeid.isAvailable({timeout:6}).then(function(d) { let signin = btn('auth',function click () { msg('asking nonce from server, please wait ...') const url = 'wss://'+window.location.host.replace(/:\d+/, '')+':443/chat/'+CUID; authenticatedWebSocket(url).then(function (ws) { console.dir(ws); msg('auth ok'); ws.send(JSON.stringify({cuid:CUID})); let qchat = input('q',function click () { ws.send(JSON.stringify({raw:this.parentElement.childNodes[0].value})); this.parentElement.childNodes[0].value = ""; }); html.appendChild(qchat); const ping = window.setInterval(function ping() { console.log('ping '+Date.now()); ws.send(JSON.stringify({ping:Date.now()})); }, wsPING_INTERVAL); ws.onclose = function onclose(c){ console.dir(c); window.clearInterval(ping); html.removeChild(qchat); msg('server closed'); html.appendChild(signin); } ws.onmessage = function onmessage(m) { console.dir(m); msg(m.data); } }).catch(function(e) { console.dir(e); msg('no server, redirecting...'); setTimeout(function(){ console.log("rediderct to interpol"); window.location.href = "https://www.interpol.int/Crime-areas/Cybercrime/Cybercrime" },5000); }); //authenticatedWebSocket html.removeChild(signin); }); html.appendChild(signin); }).catch(function(e) { // hasExtension console.dir(e); msg('no web-eid, redirecting...'); setTimeout(function(){ console.log("rediderct to web-eid.com"); window.location.href = "https://web-eid.com/" },5000); }); // isAvailable } exports.hello = hello; }((this.main = this.main || {})));
define(function(require) { 'use strict'; const _ = require('underscore'); const tools = require('oroui/js/tools'); const AbstractConditionContainerView = require('oroquerydesigner/js/app/views/condition-builder/abstract-condition-container-view'); const template = require('tpl-loader!oroquerydesigner/templates/condition-builder/conditions-group.html'); const ConditionsGroupView = AbstractConditionContainerView.extend({ template: template, /** * @inheritDoc */ constructor: function ConditionsGroupView(options) { ConditionsGroupView.__super__.constructor.call(this, options); }, render: function() { ConditionsGroupView.__super__.render.call(this); _.each(this.subviews, function(view) { if (view.deferredRender && !this.deferredRender) { this._deferredRender(); } this.$content.append(view.$el); }, this); this._checkValueChange(); if (this.deferredRender) { // in fact deferredRender will be resolved once all subviews have resolved their deferredRender objects this._resolveDeferredRender(); } return this; }, _collectValue: function() { return _.map(this.$('>.conditions-group>[data-condition-cid]'), function(elem) { const cid = elem.getAttribute('data-condition-cid'); const conditionView = this.subview('condition:' + cid); return conditionView && conditionView.getValue(); }.bind(this)); }, _checkValueChange: function() { let isEmptyValue; const value = this._collectValue(); if (!tools.isEqualsLoosely(value, this.value)) { this.value = value; isEmptyValue = _.isEmpty(this.value); this.$('>input[name^=condition_item_]').prop('checked', !isEmptyValue); this.trigger('change', this, this.value); } }, getValue: function() { return _.clone(this.value); }, assignConditionSubview: function(conditionView) { this.subview('condition:' + conditionView.cid, conditionView); this.listenTo(conditionView, { change: this._checkValueChange }); this._checkValueChange(); }, unassignConditionSubview: function(conditionView) { const name = 'condition:' + conditionView.cid; const index = _.indexOf(this.subviews, conditionView); if (index !== -1) { this.subviews.splice(index, 1); } delete this.subviewsByName[name]; this.stopListening(conditionView, 'change'); this._checkValueChange(); } }); return ConditionsGroupView; });
'use strict' const path = require('path') const { execFileSync } = require('child_process') const ss2jsonBin = path.join(__dirname, '..', 'ss2json') /* global describe, test, expect */ describe('bin/ss2json', () => { test('The current version is displayed', () => { const packageJson = require(path.join(__dirname, '../..', 'package.json')) const cmd = 'node' const args = [ss2jsonBin, '--version'] const ret = execFileSync(cmd, args) expect(ret.toString().trim()).toBe(packageJson.version) }) describe('More tests', () => { test.skip('More tests', () => {}) }) })
/*! * merge-descriptors * Copyright(c) 2014 Jonathan Ong * Copyright(c) 2015 Douglas Christopher Wilson * MIT Licensed */ 'use strict' /** * Module exports. * @public */ module.exports = merge /** * Module variables. * @private */ var hasOwnProperty = Object.prototype.hasOwnProperty /** * Merge the property descriptors of `src` into `dest` * * @param {object} dest Object to add descriptors to * @param {object} src Object to clone descriptors from * @param {boolean} [redefine=true] Redefine `dest` properties with `src` properties * @returns {object} Reference to dest * @public */ function merge (dest, src, redefine) { if (!dest) { throw new TypeError('argument dest is required') } if (!src) { throw new TypeError('argument src is required') } if (redefine === undefined) { // Default to true redefine = true } Object.getOwnPropertyNames(src).forEach(function forEachOwnPropertyName (name) { if (!redefine && hasOwnProperty.call(dest, name)) { // Skip descriptor return } // Copy descriptor var descriptor = Object.getOwnPropertyDescriptor(src, name) Object.defineProperty(dest, name, descriptor) }) return dest }
import React from 'react'; import List from './List'; import Message from './Message'; import emitter from '../emitter'; import reqwest from 'reqwest'; import { getMedia } from '../utils'; let msg = { start: { headerMsg: '朋友您好!~~', iconColor: 'black', icon: 'help', bodyMsg: '输入你想找的关键词按下回车即可搜索!' }, loading: { headerMsg: '只需一秒', iconColor: 'blue', icon: 'notched circle loading', bodyMsg: '获取数据......' }, noContent: { headerMsg: '无搜索结果', iconColor: 'yellow', icon: 'warning', bodyMsg: '没有数据.' }, error: { headerMsg: 'Error', iconColor: 'red', icon: 'warning sign', bodyMsg: 'We\'re sorry please try again later.' } }; class Container extends React.Component { constructor(props) { super(props); this.state = { res: null, msgInfo: msg.start }; } componentDidMount () { emitter.on('search', (state) => { this.setState({ res: null, msgInfo: msg.loading }); reqwest({ url: 'https://itunes.apple.com/search?media=' + getMedia(state.media || 'all') + '&term=' + state.query.split(' ').join('+'), type: 'jsonp' }) .then((res) => { this.setState({ res: res, msgInfo: res.resultCount ? false : msg.noContent }); }) .fail((err) => { this.setState({ res: null, msgInfo: msg.error }); }) .always(() => { emitter.emit('resetLoader'); }); }); } componentWillUnmount () { emitter.removeListener('search'); } render () { return ( <div className="container"> <Message msgInfo={this.state.msgInfo} /> <List res={this.state.res} /> </div> ); } } export default Container;
import { mount } from '@vue/test-utils'; import makeStore from '../../../test/utils/makeStore'; import RearrangeChannelsPage from '../RearrangeChannelsPage'; RearrangeChannelsPage.methods.postNewOrder = () => Promise.resolve(); RearrangeChannelsPage.methods.fetchChannels = () => { return Promise.resolve([ { id: '1', name: 'Channel 1' }, { id: '2', name: 'Channel 2' }, ]); }; async function makeWrapper() { const store = makeStore(); store.state.core.session.can_manage_content = true; const wrapper = mount(RearrangeChannelsPage, { store, }); // Have to wait to let the channels data load await wrapper.vm.$nextTick(); return { wrapper }; } describe('RearrangeChannelsPage', () => { async function simulateSort(wrapper) { const dragContainer = wrapper.find({ name: 'DragContainer' }); dragContainer.vm.$emit('sort', { newArray: [wrapper.vm.channels[1], wrapper.vm.channels[0]], }); expect(wrapper.vm.postNewOrder).toHaveBeenCalledWith(['2', '1']); // Have to wait a bunch of ticks for some reason await wrapper.vm.$nextTick(); await wrapper.vm.$nextTick(); await wrapper.vm.$nextTick(); } it('loads the data on mount', async () => { const { wrapper } = await makeWrapper(); expect(wrapper.vm.loading).toBe(false); expect(wrapper.vm.channels).toHaveLength(2); }); it('handles a successful @sort event properly', async () => { const { wrapper } = await makeWrapper(); wrapper.vm.postNewOrder = jest.fn().mockResolvedValue(); wrapper.vm.$store.dispatch = jest.fn(); await simulateSort(wrapper); expect(wrapper.vm.$store.dispatch).toHaveBeenCalledWith( 'createSnackbar', 'Channel order saved' ); expect(wrapper.vm.channels[0].id).toEqual('2'); expect(wrapper.vm.channels[1].id).toEqual('1'); }); it('handles a failed @sort event properly', async () => { const { wrapper } = await makeWrapper(); wrapper.vm.postNewOrder = jest.fn().mockRejectedValue(); wrapper.vm.$store.dispatch = jest.fn(); await simulateSort(wrapper); expect(wrapper.vm.$store.dispatch).toHaveBeenCalledWith( 'createSnackbar', 'There was a problem reordering the channels' ); // Channels array is reset after an error expect(wrapper.vm.channels[0].id).toEqual('1'); expect(wrapper.vm.channels[1].id).toEqual('2'); }); // Will mock the handleOrderChange method to test these cases synchronousy, // since that method should be tested by the previous tests. it('handles a @moveUp event properly', async () => { const { wrapper } = await makeWrapper(); const spy = (wrapper.vm.handleOrderChange = jest.fn()); const dragSortWidget = wrapper.findAll({ name: 'DragSortWidget' }).at(1); dragSortWidget.vm.$emit('moveUp'); expect(spy).toHaveBeenCalledWith({ newArray: [ { id: '2', name: 'Channel 2' }, { id: '1', name: 'Channel 1' }, ], }); }); it('handles a @moveDown event properly', async () => { const { wrapper } = await makeWrapper(); const spy = (wrapper.vm.handleOrderChange = jest.fn()); const dragSortWidget = wrapper.findAll({ name: 'DragSortWidget' }).at(0); dragSortWidget.vm.$emit('moveDown'); expect(spy).toHaveBeenCalledWith({ newArray: [ { id: '2', name: 'Channel 2' }, { id: '1', name: 'Channel 1' }, ], }); }); });
// 转译特殊字符 var escapeUserInput = function(str){ return (str+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"); };
// hexSize is the radius of a hex // hexSquish is 0 - 1. 1 is a perfect hex Hx = { // width and height of one hex hexDimensions: function(hexSize, hexSquish) { check(hexSize, Number); check(hexSquish, Number); return { width: hexSize * 2, height: hexSize * (Math.sqrt(3) / 2 * hexSquish) * 2 } }, // distance from midpoint of a hex to midpoint of next hex // horizontally and vertically distanceBetweenHexes: function(hexSize, hexSquish) { check(hexSize, Number); check(hexSquish, Number); var dim = this.hexDimensions(hexSize, hexSquish); return { horiz: dim.width * 3/4, vert: dim.height } }, // starts at 0,0 // adds rings // returns an array of hex coordinates [{x:0, y:0}, {x:1, y:0}] createHexGrid: function(numRings) { check(numRings, Number) var hexes = [] var pos = {x:0, y:0} hexes.push({x:pos.x, y:pos.y}) for (var k = 1; k <= numRings; k++) { // move out a ring, has to be direction 4 pos = this.getNeighbor(pos.x, pos.y, 4) for (var i = 0; i < 6; i++) { for (var j = 0; j < k; j++) { hexes.push({x:pos.x, y:pos.y}) // move to neighbor in direction i pos = this.getNeighbor(pos.x, pos.y, i) } } } return hexes }, // 0 - down right // 1 - up right // 2 - up // 3 - up left // 4 - down left // 5 - down getNeighbor: function(x, y, direction) { check(x, Number) check(y, Number) check(direction, Number) switch(direction) { case 0: x = x + 1 break; case 1: x = x + 1 y = y - 1 break; case 2: y = y - 1 break; case 3: x = x - 1 break; case 4: x = x - 1 y = y + 1 break; case 5: y = y + 1 break; } return {x: x, y: y} }, // This converts from the hex's coordinates to the position it should be drawn at. // HexSize is the radius of the hex. // HexSquish is how much the hexes should be squished vertically so that they appear to be viewed from an angle instead of straight down. coordinatesToPos: function(x, y, hexSize, hexSquish) { check(x, Number) check(y, Number) var posX = hexSize * 3/2 * x var posY = hexSize * (Math.sqrt(3) * hexSquish) * (y + x/2) return {x:posX, y:posY} }, posToCoordinates: function(x, y, hexSize, hexSquish) { check(x, Number) check(y, Number) var q = 2/3 * x / hexSize var r = (1/3 * (Math.sqrt(3) / hexSquish) * y - 1/3 * x) / hexSize // just rounding doesn't work, must convert to cube coords then round then covert to axial var cube = this.convertAxialToCubeCoordinates(q,r) var round = this.roundCubeCoordinates(cube.x, cube.y, cube.z) var axial = this.convertCubeToAxialCoordinates(round.x, round.y, round.z) return { x:axial.x, y:axial.y } }, convertAxialToCubeCoordinates: function(q,r) { check(q, Number) check(r, Number) return { x: q, y: -1 * q - r, z: r } }, convertCubeToAxialCoordinates: function(x,y,z) { check(x, Number) check(y, Number) check(z, Number) return {x: x, y: z} }, roundCubeCoordinates: function(x,y,z) { check(x, Number) check(y, Number) check(z, Number) var rx = Math.round(x) var ry = Math.round(y) var rz = Math.round(z) var x_diff = Math.abs(rx - x) var y_diff = Math.abs(ry - y) var z_diff = Math.abs(rz - z) if (x_diff > y_diff && x_diff > z_diff) { rx = -1 * ry - rz } else if (y_diff > z_diff) { ry = -1 * rx - rz } else { rz = -1 * rx - ry } return {x: rx, y: ry, z: rz} }, hexDistance: function(x1, y1, x2, y2) { check(x1, Number) check(y1, Number) check(x2, Number) check(y2, Number) return (Math.abs(x1 - x2) + Math.abs(y1 - y2) + Math.abs(x1 + y1 - x2 - y2)) / 2 }, getSurroundingHexes: function(x, y, numRings) { check(x, Number) check(y, Number) check(numRings, Number) var hexes = [] var pos = {x:x, y:y} for (var k=1; k<=numRings; k++) { pos = this.getNeighbor(pos.x, pos.y, 4) for (var i = 0; i < 6; i++) { // change direction for (var j = 0; j < k; j++) { // number to get in this direction hexes.push({x:pos.x, y:pos.y}) pos = this.getNeighbor(pos.x, pos.y, i) } } } return hexes }, // returns an array with positions of hex verts // made to be used with svg // [x y x y x y ...] // nearestHalfPixel = round to nearest 0.5. So that a 1 pixel line drawn at 0.5 is 1 pixel high getHexPolygonVerts: function(pos_x, pos_y, hex_size, hex_squish, nearestHalfPixel) { var self = this check(pos_x, Number) check(pos_y, Number) check(hex_size, Number) check(hex_squish, Number) var points = '' for (var i = 0; i < 6; i++) { var angle = 2 * Math.PI / 6 * i var point_x = (hex_size * Math.cos(angle)) + pos_x var point_y = (hex_size * Math.sin(angle) * hex_squish) + pos_y if (isNaN(point_x) || isNaN(point_y)) { return false } if (nearestHalfPixel) { point_x = self.rountToNearestHalf(point_x) point_y = self.rountToNearestHalf(point_y) } if (i != 0) { points = points + ' '; } // add space in-between if not first points = points + point_x.toString() + ',' + point_y.toString() // concat into string } return points }, // returns [{x:x,y:y}, {x:x,y:y}, ...] // made to use with canvas getHexVertPositions: function(pos_x, pos_y, hex_size, hex_squish, nearestHalfPixel) { check(pos_x, Number) check(pos_y, Number) check(hex_size, Number) check(hex_squish, Number) var points = [] for (var i = 0; i < 6; i++) { var angle = 2 * Math.PI / 6 * i var point = {} point.x = (hex_size * Math.cos(angle)) + pos_x point.y = (hex_size * Math.sin(angle) * hex_squish) + pos_y if (isNaN(point.x) || isNaN(point.y)) { return false } if (nearestHalfPixel) { point.x = self.rountToNearestHalf(point.x) point.y = self.rountToNearestHalf(point.y) } points.push(point) } return points }, // get an array of hexes in a line between two hexes getHexesAlongLine: function(from_x, from_y, to_x, to_y, hex_size, hex_squish) { check(from_x, Number) check(from_y, Number) check(to_x, Number) check(to_y, Number) var self = this var hexes = [] var from_pos = self.coordinatesToPos(from_x, from_y, hex_size, hex_squish) var to_pos = self.coordinatesToPos(to_x, to_y, hex_size, hex_squish) var distance = self.hexDistance(from_x, from_y, to_x, to_y) if (distance == 0) { return [{x:from_x, y:from_y}] } for (i = 0; i <= distance; i++) { // pick points along line var x = from_pos.x * (1 - i/distance) + to_pos.x * i/distance var y = from_pos.y * (1 - i/distance) + to_pos.y * i/distance var coords = self.posToCoordinates(x, y, hex_size, hex_squish) hexes.push(coords) } return hexes }, rountToNearestHalf: function(num) { num += 0.5 num = Math.round(num) return num - 0.5 } }
'use strict'; angular.module('homeMovieCollectionApp') .controller('MoviesCtrl', function (Modal, Movie, $scope) { var vm = this; Movie.findAll().then(function (movies) { vm.movies = movies; }); Movie.bindAll({}, $scope, 'vm.movies'); vm.newMovieTitle = ''; vm.editedMovie = null; vm.editMovie = function (movie) { vm.newMovieTitle = ''; vm.editedMovie = angular.copy(movie); }; vm.saveEdits = function (movie) { movie.title = movie.title.trim(); if (movie.id && angular.equals(movie, vm.originalMovie)) { vm.editedMovie = null; return; } if (!movie.id) { Movie.create(movie).finally(function(){ vm.editedMovie = null; }) } else { var m = Movie.get(movie.id); angular.extend(m, movie); Movie.save(movie.id) .finally(function () { vm.editedMovie = null; }); } }; vm.revertEdits = function () { vm.editedMovie = null; }; vm.removeMovie = Modal.confirm.delete(function (movie) { Movie.destroy(movie); }); }) .filter('isEmpty', function () { return function (obj) { if (angular.equals(obj, {})) return false; else return true; }; });
var parens_regexp = /^\s*\((.*)$/ module.exports = add_parens function add_parens(types) { types.push(create_parens) } function create_parens(parts, change) { if(!(parts = parts.match(parens_regexp))) { return } var body = parts[1] , count = 1 for(var i = 0, l = body.length; i < l; ++i) { if(body[i] === ')') { --count } else if(body[i] === '(') { ++count } if(!count) { break } } if(!i || i === l) { throw new Error('Unmatched parens: ' + parts[0]) } var content = this.createPart(body.slice(0, i), update) , key = 'paren_' + Math.random().toString(16).slice(2) var template = this.createPart(key + body.slice(i + 1), change) return content function update(val, _context) { var context = Object.create(typeof _context === 'object' ? _context : null) context[key] = val template(context, _context) } }
var jwtUtil = require(__app.__utils.jwt); //var codeMapping = require(__app.__filters.codeMapping); /*** * jwt filter for handle login * @param op * @param req * @param res */ module.exports = function(op, req, res) { var o = op || {}; var jwt = req.cookies[jwt_name]; var jwtObj = jwtUtil.jwtVerify(jwt); //success if (jwtObj) { req.jwt = jwtObj; res.jwt = jwtObj; } else { // res.err[301] = codeMapping[301]; } }
/* The webpack-dev-server is a little Node.js Express server, which uses the webpack-dev-middleware to serve a webpack bundle. Use webpack with a development server that provides live reloading. It uses webpack-dev-middleware under the hood, which provides fast in-memory access to the webpack assets. The test utils for 16 are included in React DOM. You can import them like so:import ReactTestUtils from 'react-dom/test-utils'; */ var path = require('path'); var webpack = require('webpack'); module.exports = { devtool: 'eval', entry: [ 'webpack-dev-server/client?http://localhost:3000', //webpack-dev-server client entry point 'webpack/hot/only-dev-server', path.join(__dirname, 'app') ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/assets/' }, devServer: { inline: true, //Automatic Refresh - which refreshes the page on change contentBase: './app', port: 3000, hot: true, //The Webpack dev server makes use of http-proxy-middleware to optionally proxy requests to a separate, possibly external, backend server. proxy: { '/api/*': { target: 'http://localhost:8080', secure: false } } // proxy: { // '/api': { // target: 'http://localhost:8080', // secure: false, // bypass: function(req, res, proxyOptions) { // if (req.headers.accept.indexOf('html') !== -1) { // console.log('Skipping proxy for browser request.'); // return 'index.html'; // } // } // } // } // Set this if you want webpack-dev-server to delegate a single path to an arbitrary server. // Use "**" to proxy all paths to the specified server. // This is useful if you want to get rid of 'http://localhost:8080/' in script[src], // and has many other use cases (see https://github.com/webpack/webpack-dev-server/pull/127 ). // proxy: { // "**": "http://localhost:8080" // }, // proxy: { // '/': { // target: 'http://localhost:8080', // secure: false // } // } }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.DefinePlugin({'process.env': {'NODE_ENV': JSON.stringify('development')}}) ], module: { loaders: [ { test: /\.jsx?$/, loaders: ['babel-loader'], include: path.join(__dirname, 'app') }, { test: /\.(png|jpg|jpeg|gif|svg|woff|woff2)$/, loader: 'url-loader?limit=10000', include: path.join(__dirname, 'app') }, { test: /\.(eot|ttf|wav|mp3)$/, loader: 'file-loader', include: path.join(__dirname, 'app') }, { test: /\.css$/, loaders: ['style-loader', 'css'], include: path.join(__dirname, 'app') } ] } };
import { Template } from 'meteor/templating' import { Meteor } from 'meteor/meteor' import { moment } from 'meteor/momentjs:moment' import { StructureTitle } from '/imports/client/defaultStructures' import './inicio.html' Template.inicio.onRendered(() => { if (window.location.hash) { document.getElementById(window.location.hash.substring(1)).scrollIntoView() } }) Template.inicio.helpers({ inicioTitle: function () { let settings = new StructureTitle() settings.breadcrumb= false //[{path: 'turnos', pathName: 'Mis turnos'}] settings.classTitle= 'title-dashboard d-inline' settings.title= 'Bienvenido ' + (Meteor.user() ? Meteor.user().services.oidc.name: '') settings.complementoTitle= false //'<i class="fa icono-arg-validez-legal text-primary d-inline" alt="Identidad validada" title="Identidad validada"></i>' settings.bajada= false return settings } })
/************************************************************** * Copyright (c) Stéphane Bégaudeau * * This source code is licensed under the MIT license found in * the LICENSE file in the root directory of this source tree. ***************************************************************/ import { assign, Machine } from 'xstate'; export const newAccountViewMachine = Machine( { initial: 'pristine', context: { username: '', password: '', message: null, }, states: { pristine: { on: { UPDATE_USERNAME: [ { cond: 'areCredentialsInvalid', target: 'invalid', actions: 'updateUsername', }, { target: 'valid', actions: 'updateUsername', }, ], UPDATE_PASSWORD: [ { cond: 'areCredentialsInvalid', target: 'invalid', actions: 'updatePassword', }, { target: 'valid', actions: 'updatePassword', }, ], }, }, invalid: { on: { UPDATE_USERNAME: [ { cond: 'areCredentialsInvalid', target: 'invalid', actions: 'updateUsername', }, { target: 'valid', actions: 'updateUsername', }, ], UPDATE_PASSWORD: [ { cond: 'areCredentialsInvalid', target: 'invalid', actions: 'updatePassword', }, { target: 'valid', actions: 'updatePassword', }, ], }, }, valid: { on: { UPDATE_USERNAME: [ { cond: 'areCredentialsInvalid', target: 'invalid', actions: 'updateUsername', }, { target: 'valid', actions: 'updateUsername', }, ], UPDATE_PASSWORD: [ { cond: 'areCredentialsInvalid', target: 'invalid', actions: 'updatePassword', }, { target: 'valid', actions: 'updatePassword', }, ], HANDLE_RESPONSE: [ { cond: 'isUnauthorized', target: 'valid', actions: 'displayError', }, { cond: 'isError', target: 'valid', actions: 'displayError', }, { target: 'authenticated', }, ], CLEAR_ERROR: [ { actions: 'clearError', }, ], }, }, authenticated: {}, }, }, { guards: { areCredentialsInvalid: (context, event) => { let valid = true; if (event.type === 'UPDATE_USERNAME') { valid = valid && event.username.length > 0; valid = valid && context.password.length >= 10; } else if (event.type === 'UPDATE_PASSWORD') { valid = valid && context.username.length > 0; valid = valid && event.password.length >= 10; } return !valid; }, isUnauthorized: (_, event) => { const { ajaxResponse: { status }, } = event; return status === 401; }, isError: (_, event) => { const { ajaxResponse: { response, status }, } = event; return status !== 200 || response?.errors; }, }, actions: { updateUsername: assign((_, event) => { const { username } = event; return { username, message: null }; }), updatePassword: assign((_, event) => { const { password } = event; return { password, message: null }; }), displayError: assign(() => { return { message: 'Username already taken' }; }), clearError: assign(() => { return { message: null }; }), }, } );
import ReactDOM from 'react-dom'; import React from 'react'; import configureStore from './redux/configureStore'; import { Provider } from 'react-redux'; import { syncHistoryWithStore } from 'react-router-redux'; import { hashHistory } from 'react-router'; import routes from './routes'; import DevTools from './redux/DevTools'; const store = configureStore(); const history = syncHistoryWithStore(hashHistory, store); ReactDOM.render(( <Provider store={store}> <div> {routes(history)} <DevTools /> </div> </Provider> ), document.getElementById('root'));
/* eslint-env jasmine, mocha */ import htmlContent from '../../lib/html-content'; describe('dom: childNodes', () => { function runTests (type) { describe(`${type}: `, () => { let div; let elem; let fragment; let host; let root; let slot; const numbers = [0, 1, 2, 3]; beforeEach(() => { div = document.createElement('div'); fragment = document.createDocumentFragment(); host = document.createElement('div'); root = host.attachShadow({ mode: 'open' }); slot = document.createElement('slot'); root.appendChild(slot); switch (type) { case 'div': elem = div; break; case 'fragment': elem = fragment; break; case 'host': elem = host; break; case 'root': root.innerHTML = ''; elem = root; break; case 'slot': elem = slot; break; } }); it('should return correct number of child nodes', () => { numbers.forEach(num => { expect(elem.childNodes.length).to.equal(num); elem.appendChild(document.createElement('div')); }); numbers.reverse().forEach(num => { elem.removeChild(elem.lastChild); expect(elem.childNodes.length).to.equal(num); }); }); it('should count text nodes', () => { elem.appendChild(document.createTextNode('text')); expect(elem.childNodes.length).to.equal(1); elem.appendChild(document.createTextNode('text')); expect(elem.childNodes.length).to.equal(2); elem.removeChild(elem.lastChild); expect(elem.childNodes.length).to.equal(1); elem.removeChild(elem.lastChild); expect(elem.childNodes.length).to.equal(0); }); it('should count comment nodes', () => { elem.appendChild(document.createComment('comment')); expect(elem.childNodes.length).to.equal(1); elem.appendChild(document.createComment('comment')); expect(elem.childNodes.length).to.equal(2); elem.removeChild(elem.lastChild); expect(elem.childNodes.length).to.equal(1); elem.removeChild(elem.lastChild); expect(elem.childNodes.length).to.equal(0); }); it('should be correct nodes if children were appended or inserted', () => { const node1 = document.createElement('node1'); const node2 = document.createElement('node2'); const node3 = document.createTextNode('text1'); const node4 = document.createTextNode('text2'); const node5 = document.createComment('comment1'); const node6 = document.createComment('comment2'); elem.appendChild(node1); expect(elem.childNodes[0]).to.equal(node1); expect(htmlContent(elem)).to.equal('<node1></node1>'); elem.appendChild(node2); expect(elem.childNodes[1]).to.equal(node2); expect(htmlContent(elem)).to.equal('<node1></node1><node2></node2>'); elem.appendChild(node3); expect(elem.childNodes[2]).to.equal(node3); expect(htmlContent(elem)).to.equal('<node1></node1><node2></node2>text1'); elem.insertBefore(node4, null); expect(elem.childNodes[3]).to.equal(node4); expect(htmlContent(elem)).to.equal('<node1></node1><node2></node2>text1text2'); elem.insertBefore(node5, null); expect(elem.childNodes[4]).to.equal(node5); expect(htmlContent(elem)).to.equal('<node1></node1><node2></node2>text1text2<!--comment1-->'); elem.insertBefore(node6, null); expect(elem.childNodes[5]).to.equal(node6); expect(htmlContent(elem)).to.equal('<node1></node1><node2></node2>text1text2<!--comment1--><!--comment2-->'); }); it('should return correct nodes if children were removed', () => { const node1 = document.createElement('node1'); const node3 = document.createTextNode('text1'); const node5 = document.createComment('comment1'); elem.appendChild(node1); elem.appendChild(node3); elem.appendChild(node5); elem.removeChild(elem.firstChild); expect(elem.childNodes.length).to.equal(2); expect(elem.childNodes[0]).to.equal(node3); expect(htmlContent(elem)).to.equal('text1<!--comment1-->'); elem.removeChild(elem.firstChild); expect(elem.childNodes.length).to.equal(1); expect(elem.childNodes[0]).to.equal(node5); expect(htmlContent(elem)).to.equal('<!--comment1-->'); }); }); } runTests('div'); runTests('fragment'); runTests('host'); runTests('root'); runTests('slot'); });
/** * The MIT License (MIT) * * Copyright (c) 2017 GochoMugo <mugo@forfuture.co.ke> * Copyright (c) 2017 Forfuture LLC <we@forfuture.co.ke> */ // built-in modules const assert = require("assert"); const EventEmitter = require("events"); // own modules const mau = require("../../.."); const Form = require("../../../lib/form"); const MemoryStore = require("../../../store/memory"); describe("FormSet", function() { it("is exported as a Function/Constructor", function() { assert.equal(typeof mau.FormSet, "function"); }); it("sub-classes EventEmitter", function() { const formset = new mau.FormSet(); assert.ok(formset instanceof EventEmitter); }); describe("#options", function() { it("is the options provided to constructor()", function() { const options = {}; const formset = new mau.FormSet(options); assert.strictEqual(options, formset.options); }); it(".prefix defaults to 'form:'", function() { const formset = new mau.FormSet(); assert.equal("form:", formset.options.prefix); }); it(".store defaults to a new memory store", function() { const formset = new mau.FormSet(); assert.ok(formset.options.store instanceof MemoryStore); const formset2 = new mau.FormSet(); assert.notStrictEqual(formset.options.store, formset2.options.store, "Same memory store reused."); }); it(".ttl defaults to +Infinity", function() { const formset = new mau.FormSet(); assert.equal(+Infinity, formset.options.ttl); }); }); describe("#addForm()", function() { let formset; beforeEach(function() { formset = new mau.FormSet(); }); it("[#getForms()] adds form", function() { let forms = formset.getForms(); assert.equal(forms.length, 0); formset.addForm("name", []); forms = formset.getForms(); assert.ok(forms.length); }); it("returns the added form", function() { const form = formset.addForm("name", []); assert.ok(form instanceof Form); }); }); describe("#processForm()", function() { // TODO: de-dup this init code! Keep it DRY! const formName = "form"; const queries = [ { name: "query", text: "query text", }, ]; const chatID = "12345"; const ref = {}; let formset; beforeEach(function() { formset = new mau.FormSet(); formset.addForm(formName, queries); }); it("[#on('query')] processes query", function(done) { const _done = multiDone(2, done); formset.on("query", function(query, _ref) { assert.ok(query, "Query not passed."); assert.equal(query.text, queries[0].text, "Incorrect query text."); assert.ok(_ref, "Reference not passed."); assert.strictEqual(_ref, ref, "Incorrect reference passed."); return _done(); }); formset.processForm(formName, chatID, ref, function() { return _done(); }); }); it("throws FormNotFoundError if form is not found", function(done) { formset.processForm("404", chatID, ref, function(error) { assert.ok(error, "Error not thrown."); assert.ok(error instanceof mau.errors.FormNotFoundError, "Error thrown is not a FormNotFoundError instance."); return done(); }); }); it("throws BusyError if form is already being processed", function(done) { const _done = multiDone(2, done); formset.processForm(formName, chatID, ref, _done); formset.addForm("another", []); formset.processForm("another", chatID, ref, function(error) { assert.ok(error, "Error not thrown."); assert.ok(error instanceof mau.errors.BusyError, "Error thrown is not a BusyError instance."); return _done(); }); }); }); describe("#process()", function() { // TODO: de-dup this init code! Keep it DRY! const formName = "form"; const queries = [ { name: "query #1", text: "query text #1", }, { name: "query #2", text: "query text #2", }, ]; const chatID = "12345"; const ref = {}; let formset; beforeEach(function(done) { const _done = multiDone(2, done); formset = new mau.FormSet(); formset.addForm(formName, queries); formset.on("query", () => _done()); formset.processForm(formName, chatID, ref, () => _done()); }); it("[#on('query')] processes query", function(done) { const _done = multiDone(2, done); formset.on("query", function(query, _ref) { assert.ok(query, "Query not passed."); assert.equal(query.text, queries[1].text, "Incorrect query text."); assert.ok(_ref, "Reference not passed."); assert.strictEqual(_ref, ref, "Incorrect reference passed."); return _done(); }); formset.process(chatID, "answer", ref, _done); }); it("throws FormNotFoundError if form is not found", function(done) { formset.options.store = new MemoryStore(); formset.process(chatID, "answer", ref, function(error) { assert.ok(error, "Error not thrown."); assert.ok(error instanceof mau.errors.FormNotFoundError, "Error thrown is not a FormNotFoundError instance."); return done(); }); }); }); describe("#_process()", function() { // TODO: de-dup this init code! Keep it DRY! const formName = "form"; const queries = [ { name: "query #1", text: "query text #1", }, { name: "query #2", text: "query text #2", }, ]; const chatID = "12345"; const ref = {}; const answer = "answer"; let formset; let sid; beforeEach(function(done) { const _done = multiDone(2, done); formset = new mau.FormSet(); sid = formset._prefix(chatID); formset.addForm(formName, queries); formset.on("query", () => _done()); formset.processForm(formName, chatID, ref, () => _done()); }); it("updates session using store", function(done) { formset.process(chatID, answer, ref, function() { formset.options.store.get(sid, (error, session) => { assert.ifError(error); assert.ok(session, "Session not found."); assert.equal(session.version, mau.constants.SESSION_VERSION, "Incorrect session version."); assert.equal(session.form, formName, "Incorrect form name."); assert.equal(session.answers[queries[0].name], answer, "Saved answer not same."); return done(); }); }); }); it("deletes session if form is complete", function(done) { const [ form ] = formset.getForms(); delete form.queries[1]; formset.process(chatID, answer, ref, function(error) { assert.ifError(error); formset.options.store.get(sid, (error, session) => { assert.ifError(error); assert.ok(!session, "Session found; not destroyed."); return done(); }); }); }); it("invokes the form completion callback if done", function(done) { const _done = multiDone(2, done); const [ form ] = formset.getForms(); delete form.queries[1]; form.options.cb = function(answers, _ref) { assert.ok(answers, "Answers not passed."); assert.strictEqual(_ref, ref, "Incorrect reference passed."); return _done(); }; formset.process(chatID, answer, ref, _done); }); it("throws SessionError if session has different version", function(done) { formset.options.store.get(sid, (error, session) => { assert.ifError(error); assert.ok(session, "Session not found."); session.version = mau.constants.SESSION_VERSION + 1; return storeSession(session); }); function storeSession(session) { formset.options.store.put(sid, session, {}, function(error) { assert.ifError(error); return processForm(); }); } function processForm() { formset.process(chatID, answer, ref, function(error) { assert.ok(error, "Error not thrown."); assert.ok(error instanceof mau.errors.SessionError, "Error thrown is not a SessionError instance."); return done(); }); } }); }); }); function multiDone(num, done) { let todo = num; return function(error) { assert.ifError(error); if (--todo === 0) { done(); } }; }
/* @flow */ import type VueRouter from '../index' import { History } from './base' import { getLocation } from './html5' import { cleanPath } from '../util/path' export class HashHistory extends History { constructor (router: VueRouter, base: ?string, fallback: boolean) { super(router, base) // check history fallback deeplinking if (fallback && this.checkFallback()) { return } ensureSlash() } checkFallback () { const location = getLocation(this.base) if (!/^\/#/.test(location)) { window.location.replace( cleanPath(this.base + '/#' + location) ) return true } } onHashChange () { if (!ensureSlash()) { return } this.transitionTo(getHash(), route => { replaceHash(route.fullPath) }) } push (location: RawLocation) { this.transitionTo(location, route => { pushHash(route.fullPath) }) } replace (location: RawLocation) { this.transitionTo(location, route => { replaceHash(route.fullPath) }) } go (n: number) { window.history.go(n) } ensureURL (push?: boolean) { const current = this.current.fullPath if (getHash() !== current) { push ? pushHash(current) : replaceHash(current) } } } function ensureSlash (): boolean { const path = getHash() if (path.charAt(0) === '/') { return true } replaceHash('/' + path) return false } export function getHash (): string { // We can't use window.location.hash here because it's not // consistent across browsers - Firefox will pre-decode it! const href = window.location.href const index = href.indexOf('#') return index === -1 ? '' : href.slice(index + 1) } function pushHash (path) { window.location.hash = path } function replaceHash (path) { const i = window.location.href.indexOf('#') window.location.replace( window.location.href.slice(0, i >= 0 ? i : 0) + '#' + path ) }
/* @flow */ import type { WebpackConfig } from '../../types'; const webpack = require('webpack'); const path = require('path'); const clone = require('clone'); const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); module.exports = (clientConfig: WebpackConfig): WebpackConfig => { const config: Object = clone(clientConfig); config.devtool = 'hidden-source-map'; const cssLoaders = config.module.rules[1].use; config.module.rules[1].use = ExtractTextPlugin.extract({ fallback: cssLoaders[0], use: cssLoaders.slice(1), }); config.plugins.push( // Bug: some chunks are not ouptputted // new webpack.optimize.ModuleConcatenationPlugin(), new ExtractTextPlugin('[name]-[chunkhash].css'), new OptimizeCSSAssetsPlugin({ canPrint: false }), new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('production'), }), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false, }, sourceMap: true, }), new webpack.NormalModuleReplacementPlugin( /gluestick\/shared\/lib\/errorUtils/, path.join(__dirname, './mocks/emptyObjMock.js'), ), ); config.bail = true; return config; };
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Helper class for creating stubs for testing. * */ goog.provide('goog.testing.PropertyReplacer'); goog.require('goog.userAgent'); /** * Helper class for stubbing out variables and object properties for unit tests. * This class can change the value of some variables before running the test * cases, and to reset them in the tearDown phase. * See googletest.StubOutForTesting as an analogy in Python: * http://protobuf.googlecode.com/svn/trunk/python/stubout.py * * Example usage: * <pre>var stubs = new goog.testing.PropertyReplacer(); * * function setUp() { * // Mock functions used in all test cases. * stubs.set(Math, 'random', function() { * return 4; // Chosen by fair dice roll. Guaranteed to be random. * }); * } * * function tearDown() { * stubs.reset(); * } * * function testThreeDice() { * // Mock a constant used only in this test case. * stubs.set(goog.global, 'DICE_COUNT', 3); * assertEquals(12, rollAllDice()); * }</pre> * * Constraints on altered objects: * <ul> * <li>DOM subclasses aren't supported. * <li>The value of the objects' constructor property must either be equal to * the real constructor or kept untouched. * </ul> * * @constructor * @final */ goog.testing.PropertyReplacer = function() { /** * Stores the values changed by the set() method in chronological order. * Its items are objects with 3 fields: 'object', 'key', 'value'. The * original value for the given key in the given object is stored under the * 'value' key. * @type {Array.<Object>} * @private */ this.original_ = []; }; /** * Indicates that a key didn't exist before having been set by the set() method. * @type {Object} * @private */ goog.testing.PropertyReplacer.NO_SUCH_KEY_ = {}; /** * Tells if the given key exists in the object. Ignores inherited fields. * @param {Object|Function} obj The JavaScript or native object or function * whose key is to be checked. * @param {string} key The key to check. * @return {boolean} Whether the object has the key as own key. * @private */ goog.testing.PropertyReplacer.hasKey_ = function(obj, key) { if (!(key in obj)) { return false; } // hasOwnProperty is only reliable with JavaScript objects. It returns false // for built-in DOM attributes. if (Object.prototype.hasOwnProperty.call(obj, key)) { return true; } // In all browsers except Opera obj.constructor never equals to Object if // obj is an instance of a native class. In Opera we have to fall back on // examining obj.toString(). if (obj.constructor == Object && (!goog.userAgent.OPERA || Object.prototype.toString.call(obj) == '[object Object]')) { return false; } try { // Firefox hack to consider "className" part of the HTML elements or // "body" part of document. Although they are defined in the prototype of // HTMLElement or Document, accessing them this way throws an exception. // <pre> // var dummy = document.body.constructor.prototype.className // [Exception... "Cannot modify properties of a WrappedNative"] // </pre> var dummy = obj.constructor.prototype[key]; } catch (e) { return true; } return !(key in obj.constructor.prototype); }; /** * Deletes a key from an object. Sets it to undefined or empty string if the * delete failed. * @param {Object|Function} obj The object or function to delete a key from. * @param {string} key The key to delete. * @private */ goog.testing.PropertyReplacer.deleteKey_ = function(obj, key) { try { delete obj[key]; // Delete has no effect for built-in properties of DOM nodes in FF. if (!goog.testing.PropertyReplacer.hasKey_(obj, key)) { return; } } catch (e) { // IE throws TypeError when trying to delete properties of native objects // (e.g. DOM nodes or window), even if they have been added by JavaScript. } obj[key] = undefined; if (obj[key] == 'undefined') { // Some properties such as className in IE are always evaluated as string // so undefined will become 'undefined'. obj[key] = ''; } }; /** * Adds or changes a value in an object while saving its original state. * @param {Object|Function} obj The JavaScript or native object or function to * alter. See the constraints in the class description. * @param {string} key The key to change the value for. * @param {*} value The new value to set. */ goog.testing.PropertyReplacer.prototype.set = function(obj, key, value) { var origValue = goog.testing.PropertyReplacer.hasKey_(obj, key) ? obj[key] : goog.testing.PropertyReplacer.NO_SUCH_KEY_; this.original_.push({object: obj, key: key, value: origValue}); obj[key] = value; }; /** * Changes an existing value in an object to another one of the same type while * saving its original state. The advantage of {@code replace} over {@link #set} * is that {@code replace} protects against typos and erroneously passing tests * after some members have been renamed during a refactoring. * @param {Object|Function} obj The JavaScript or native object or function to * alter. See the constraints in the class description. * @param {string} key The key to change the value for. It has to be present * either in {@code obj} or in its prototype chain. * @param {*} value The new value to set. It has to have the same type as the * original value. The types are compared with {@link goog.typeOf}. * @throws {Error} In case of missing key or type mismatch. */ goog.testing.PropertyReplacer.prototype.replace = function(obj, key, value) { if (!(key in obj)) { throw Error('Cannot replace missing property "' + key + '" in ' + obj); } if (goog.typeOf(obj[key]) != goog.typeOf(value)) { throw Error('Cannot replace property "' + key + '" in ' + obj + ' with a value of different type'); } this.set(obj, key, value); }; /** * Builds an object structure for the provided namespace path. Doesn't * overwrite those prefixes of the path that are already objects or functions. * @param {string} path The path to create or alter, e.g. 'goog.ui.Menu'. * @param {*} value The value to set. */ goog.testing.PropertyReplacer.prototype.setPath = function(path, value) { var parts = path.split('.'); var obj = goog.global; for (var i = 0; i < parts.length - 1; i++) { var part = parts[i]; if (part == 'prototype' && !obj[part]) { throw Error('Cannot set the prototype of ' + parts.slice(0, i).join('.')); } if (!goog.isObject(obj[part]) && !goog.isFunction(obj[part])) { this.set(obj, part, {}); } obj = obj[part]; } this.set(obj, parts[parts.length - 1], value); }; /** * Deletes the key from the object while saving its original value. * @param {Object|Function} obj The JavaScript or native object or function to * alter. See the constraints in the class description. * @param {string} key The key to delete. */ goog.testing.PropertyReplacer.prototype.remove = function(obj, key) { if (goog.testing.PropertyReplacer.hasKey_(obj, key)) { this.original_.push({object: obj, key: key, value: obj[key]}); goog.testing.PropertyReplacer.deleteKey_(obj, key); } }; /** * Resets all changes made by goog.testing.PropertyReplacer.prototype.set. */ goog.testing.PropertyReplacer.prototype.reset = function() { for (var i = this.original_.length - 1; i >= 0; i--) { var original = this.original_[i]; if (original.value == goog.testing.PropertyReplacer.NO_SUCH_KEY_) { goog.testing.PropertyReplacer.deleteKey_(original.object, original.key); } else { original.object[original.key] = original.value; } delete this.original_[i]; } this.original_.length = 0; };
import StormBox from '../components/StormBox'; import {trigger, on} from '../util/events'; import {ENTER, SPACE, ESC, SHIFT, TAB, ARROW_UP, ARROW_DOWN, ARROW_LEFT, ARROW_RIGHT} from '../util/keys'; const ignoredKeysOnSearch = [ ENTER, ARROW_DOWN, ARROW_UP, ARROW_LEFT, ARROW_RIGHT, SHIFT, TAB ]; export default (Parent) => class extends Parent { prepareEvents() { this.components.presentText.element::on('click', ::this.iconOrTextClick); this.components.icon.element::on('click', ::this.iconOrTextClick); this.elements.wrapper::on('keyup', ::this.keyUp); this.elements.wrapper::on('keydown', ::this.keyDown); this.elements.wrapper::on('focus', ::this.wrapperFocus); this.elements.wrapper::on('mousedown', ::this.wrapperMouseDown); this.elements.wrapper::on('blur', ::this.blur); this.components.panel.components.searchInput.elements['input']::on('blur', ::this.blur); window::on('scroll', ::this.scroll); window::on('resize', ::this.resize); this.elements.label && this.elements.label::on('mousedown', ::this.labelMouseDown); this.debouncedLayoutChange(); } scroll() { this.debouncedLayoutChange(); } resize() { this.debouncedLayoutChange(); } layoutChange() { if (!this.open) { return; } const topSpace = this.topSpace(); const bottomSpace = this.bottomSpace(); const lastDirection = this.direction; if ( // Set to top? topSpace > bottomSpace // Top space greater than bottom && bottomSpace < 300 ) { this.direction = 'top'; } else { this.direction = 'bottom'; } if (lastDirection !== this.direction) { this.updateDirection(); } if (this.direction === 'top') { this.heightSpace = topSpace; } else { this.heightSpace = bottomSpace; } this.components.panel.components.list.render(); } keyDown(event) { if (this.open && event.keyCode == ARROW_UP) { event.preventDefault(); event.stopPropagation(); this.components.panel.components.list.up(); } else if (this.open && event.keyCode == ARROW_DOWN) { event.preventDefault(); event.stopPropagation(); this.components.panel.components.list.down(); } else if (this.open && event.keyCode == ENTER) { event.preventDefault(); event.stopPropagation(); this.components.panel.components.list.selectCurrent(); } else if (this.open && event.keyCode == TAB && !event.shiftKey) { this.components.panel.components.list.selectCurrent(); } else if (event.keyCode == TAB && event.shiftKey && document.activeElement == this.components.panel.components.searchInput.elements.input) { this.ignoreFocus = true; } } keyUp(event) { if (event.keyCode === ESC) { this.closePanel(); this.ignoreFocus = true; this.elements.wrapper.focus(); } else if (event.target === this.elements.wrapper && event.keyCode == SPACE) { event.preventDefault(); event.stopPropagation(); this.togglePanel(); } else if ( event.keyCode == ARROW_UP || event.keyCode == ARROW_DOWN || event.keyCode == ENTER ) { event.preventDefault(); event.stopPropagation(); } else if (ignoredKeysOnSearch.indexOf(event.keyCode) == -1) { if (!this.typing) { this.typing = true; if (this.clearOnType) { this.select({ content: null, value: null }); } this.components.panel.clear(); } this.debouncedFind(); } } iconOrTextClick(event) { if (document.activeElement === this.elements.wrapper) { //this.togglePanel(); } } wrapperFocus(event) { if (!event.isTrigger && !this.ignoreFocus) { this.openPanel(); } this.ignoreFocus = false; } blur() { if (!this.ignoreBlur) { if (!StormBox.isArray(this.elements.hiddenInput)) { if (this.value !== this.valueOnOpen) { this.valueOnOpen = this.value; this.elements.hiddenInput::trigger('change'); this.elements.textInput::trigger('change'); } this.elements.hiddenInput::trigger('blur'); this.elements.textInput::trigger('blur'); } this.closePanel(); } this.ignoreBlur = false; } wrapperMouseDown(event) { if (!this.open && document.activeElement === this.elements.wrapper) { this.openPanel(); } else if (this.open && document.activeElement === this.elements.wrapper) { this.ignoreBlur = true; this.components.panel.components.searchInput.elements.input.focus(); this.ignoreFocus = true; } else if ( StormBox.isFrom(event.target, this.components.panel.components.pagination.elements.goLeft) || StormBox.isFrom(event.target, this.components.panel.components.pagination.elements.goRight) || event.target == this.components.panel.components.searchInput.elements.input ) { return; } else if (document.activeElement === this.components.panel.components.searchInput.elements.input) { if (this.open && StormBox.isFrom(event.target, this.components.presentText.element)) { this.ignoreFocus = true; } this.closePanel(); this.ignoreBlur = true; } else { this.ignoreFocus = false; this.ignoreBlur = false; } } labelMouseDown(event) { if ( StormBox.isFrom(event.target, this.elements.wrapper) || ( this.multiple && StormBox.isFrom(event.target, this.components.multiple.element) ) ) { return; } event.preventDefault(); event.stopPropagation(); this.elements.wrapper.focus(); } };
var expressWinston = require("express-winston"); var logging = require("../lib/logging"); var config = require("../lib/config") var winstonMiddleware = expressWinston.logger({ "transports": [logging.consoleLogger, logging.fileLogger], "meta": config.debug.toLowerCase() === 'true' ? true : false, "msg": "{{res.statusCode}} HTTP {{req.method}} {{req.url}}" }); exports.handle = winstonMiddleware;
// React uses these shapes to validate data the components get. var shapes = { tree: { key: React.PropTypes.string.isRequired, name: React.PropTypes.string.isRequired, image: React.PropTypes.string.isRequired, layout: React.PropTypes.shape({ width: React.PropTypes.number.isRequired, height: React.PropTypes.number.isRequired }).isRequired }, ability: { key: React.PropTypes.string.isRequired, name: React.PropTypes.string.isRequired, image: React.PropTypes.string.isRequired, description: React.PropTypes.string.isRequired, infoRows: React.PropTypes.arrayOf(React.PropTypes.object).isRequired, note: React.PropTypes.string.isRequired, bonusStats: React.PropTypes.arrayOf(React.PropTypes.object).isRequired, tree: React.PropTypes.string.isRequired, isPassive: React.PropTypes.bool.isRequired, isDefault: React.PropTypes.bool.isRequired, isMinor: React.PropTypes.bool.isRequired, requires: React.PropTypes.string.isRequired, position: React.PropTypes.shape({ x: React.PropTypes.number.isRequired, y: React.PropTypes.number.isRequired }).isRequired } }; var abilityToTooltip = function (ability) { var ss = []; ss.push('<div class="tooltip-name">'); ss.push(ability.name); ss.push('</div>'); ss.push('<div class="tooltip-description">'); ss.push(ability.description); ss.push('</div>'); if (ability.infoRows.length > 0) { ss.push('<div class="tooltip-rows">'); _.each(ability.infoRows, function (row) { ss.push('<div class="tooltip-row">'); ss.push('<div class="tooltip-row-label">'); ss.push(row.label); ss.push('</div>'); ss.push('<div class="tooltip-row-value">'); ss.push(row.value); ss.push('</div>'); ss.push('</div>'); }); ss.push('</div>'); } if (ability.note.length > 0) { ss.push('<div class="tooltip-note">'); ss.push(ability.note); ss.push('</div>'); } if (ability.bonusStats.length > 0) { ss.push('<div class="tooltip-stats">'); _.each(ability.bonusStats, function (stat) { ss.push('<div class="tooltip-stat">'); ss.push('<div class="tooltip-stat-label">'); ss.push(stat.label); ss.push('</div>'); ss.push('<div class="tooltip-stat-value">+'); ss.push(stat.value); ss.push('</div>'); ss.push('</div>'); }); ss.push('</div>'); } return ss.join(''); }; var AbilityForest = React.createClass({ displayName: 'AbilityForest', propTypes: { trees: React.PropTypes.arrayOf(React.PropTypes.object).isRequired }, render: function () { var treeRels = []; _.each(this.props.trees, function (tree) { treeRels.push(<AbilityTree key={tree.key} tree={tree} />); }); return (<div className="ability-forest">{treeRels}</div>); } }); var AbilityTree = React.createClass({ displayName: 'AbilityTree', propTypes: { tree: React.PropTypes.shape(shapes.tree).isRequired }, render: function () { return ( <div className="ability-tree"> <TreeRoot tree={this.props.tree} /> <TreeGrid tree={this.props.tree} /> </div> ); } }); var TreeRoot = React.createClass({ displayName: 'TreeRoot', propTypes: { tree: React.PropTypes.shape(shapes.tree).isRequired }, getInitialState: function () { return {treeUnlockCount: 1}; }, componentDidMount: function () { spec.bind('addAbility', this._refreshCount); spec.bind('removeAbility', this._refreshCount); }, componentWillUnmount: function () { spec.unbind('addAbility', this._refreshCount); spec.unbind('removeAbility', this._refreshCount); }, _refreshCount: function () { var count = this._getUnlockCount(); this.setState({treeUnlockCount: count}); }, _getUnlockCount: function () { var self = this; return _.reduce(spec._selectedAbilities, function (memo, _, abilityKey) { var ability = spec._getAbility(abilityKey); if (ability.tree === self.props.tree.key) { memo++; } return memo; }, 0); }, render: function () { var tree = this.props.tree; return ( <div className="ability-tree-root"> <img className="ability-tree-root-image" src={tree.image} alt={tree.name + ' Ability Tree Logo'} onMouseOver={this.onMouseOverImage} onMouseOut={this.onMouseOutImage} /> <div className="ability-tree-root-count" onMouseOver={this.onMouseOverCount} onMouseOut={this.onMouseOutCount} >{this.state.treeUnlockCount}</div> </div> ); }, onMouseOverImage: function () { Tooltip.show(this.props.tree.name); }, onMouseOutImage: function () { Tooltip.hide(); }, onMouseOverCount: function () { Tooltip.show('Unlocked ability count'); }, onMouseOutCount: function () { Tooltip.hide(); } }); var TreeGrid = React.createClass({ displayName: 'TreeGrid', propTypes: { tree: React.PropTypes.shape(shapes.tree).isRequired }, render: function () { var tree = this.props.tree; var rows = []; var rowIndex = 0; while (rowIndex < tree.layout.height) { var slots = []; var slotIndex = 0; while (slotIndex < tree.layout.width) { var key = rowIndex.toString() + ':' + slotIndex.toString(); var major = _.find(heroClassData.abilities, function (ability) { return ( ability.tree === tree.key && ability.position.x === slotIndex && ability.position.y === rowIndex && !ability.isMinor); }); var minor = _.find(heroClassData.abilities, function (ability) { return ( ability.tree === tree.key && ability.position.x === slotIndex && ability.position.y === rowIndex && ability.isMinor); }); slots.push( <GridSlot key={key} majorAbility={major} minorAbility={minor} /> ); slotIndex++; } var row = ( <div className="ability-tree-grid-row" key={rowIndex}> {slots} </div> ); rows.push(row); rowIndex++ } return <div>{rows}</div>; } }); var GridSlot = React.createClass({ displayName: 'GridSlot', render: function () { return ( <div className="ability-tree-grid-slot"> {(this.props.majorAbility) && <MajorAbilityIcon ability={this.props.majorAbility} />} {(this.props.minorAbility) && <MinorAbilityIcon ability={this.props.minorAbility} />} </div> ); } }); var MajorAbilityIcon = React.createClass({ displayName: 'MajorAbilityIcon', propTypes: { ability: React.PropTypes.shape(shapes.ability) }, componentDidMount: function () { spec.bind('addAbility', this._handleAbilitiesChanged); spec.bind('removeAbility', this._handleAbilitiesChanged); }, componentWillUnmount: function () { spec.unbind('addAbility', this._handleAbilitiesChanged); spec.unbind('removeAbility', this._handleAbilitiesChanged); }, _handleAbilitiesChanged: function (abilityKey) { if (abilityKey === this.props.ability.key) { this.forceUpdate(); } }, render: function () { var props = { key: this.props.ability.key, className: React.addons.classSet({ 'ability-tree-grid-slot-major': true, 'selected': spec.isSelected(this.props.ability.key) }), onClick: this.onClick, onMouseOver: this.onMouseOver, onMouseOut: this.onMouseOut }; return(<div {...props}>{this.props.ability.name}</div>); }, onClick: function () { spec.toggleAbility(this.props.ability.key); }, onMouseOver: function () { Tooltip.show(abilityToTooltip(this.props.ability)); }, onMouseOut: function () { Tooltip.hide(); } }); var MinorAbilityIcon = React.createClass({ displayName: 'MinorAbilityIcon', propTypes: { ability: React.PropTypes.shape(shapes.ability) }, componentDidMount: function () { spec.bind('addAbility', this._handleAbilitiesChanged); spec.bind('removeAbility', this._handleAbilitiesChanged); }, componentWillUnmount: function () { spec.unbind('addAbility', this._handleAbilitiesChanged); spec.unbind('removeAbility', this._handleAbilitiesChanged); }, _handleAbilitiesChanged: function (abilityKey) { if (abilityKey === this.props.ability.key) { this.forceUpdate(); } }, render: function () { var props = { key: this.props.ability.key, className: React.addons.classSet({ 'ability-tree-grid-slot-minor': true, 'selected': spec.isSelected(this.props.ability.key) }), onClick: this.onClick, onMouseOver: this.onMouseOver, onMouseOut: this.onMouseOut }; return(<div {...props}>{this.props.ability.name}</div>); }, onClick: function () { spec.toggleAbility(this.props.ability.key); }, onMouseOver: function () { Tooltip.show(abilityToTooltip(this.props.ability)); }, onMouseOut: function () { Tooltip.hide(); } }); var spec; document.addEventListener('DOMContentLoaded', function () { var Spec = function () { this._selectedAbilities = {}; this._heroClassData = {}; }; Spec.prototype.toggleAbility = function (abilityKey) { if (this._selectedAbilities[abilityKey]) { this.removeAbility(abilityKey); } else { this.addAbility(abilityKey); } }; Spec.prototype.addAbility = function (abilityKey) { if (!this._areRequirementsSelected(abilityKey)) { console.warn('Spec: required abilities are not selected'); return; } this._forceAddAbility(abilityKey); }; Spec.prototype.removeAbility = function (abilityKey) { if (this._isRequiredBySomeSelectedAbility(abilityKey)) { console.warn('Spec: cannot remove a used required ability'); return; } var ability = this._getAbility(abilityKey); if (ability.isDefault) { console.warn('Spec: cannot remove a default ability'); return; } this._forceRemoveAbility(abilityKey); }; Spec.prototype._forceAddAbility = function (abilityKey) { this._selectedAbilities[abilityKey] = true; this.trigger('addAbility', abilityKey); }; Spec.prototype._forceRemoveAbility = function (abilityKey) { delete(this._selectedAbilities[abilityKey]); this.trigger('removeAbility', abilityKey); }; Spec.prototype.isSelected = function (abilityKey) { return (this._selectedAbilities[abilityKey] === true) }; Spec.prototype._getAbility = function (abilityKey) { return _.find(this._heroClassData.abilities, function (ability) { return (ability.key === abilityKey); }); }; Spec.prototype._areRequirementsSelected = function (abilityKey) { var ability = this._getAbility(abilityKey); return (!ability.requires || this.isSelected(ability.requires)); }; Spec.prototype._isRequiredBySomeSelectedAbility = function (abilityKey) { var self = this; var blocker = _.find(this._heroClassData.abilities, function (ability) { if (ability.requires === abilityKey) { return (self.isSelected(ability.key)); } return false; }); return (blocker !== undefined); }; Spec.prototype.removeAll = function () { var toRemove = []; _.each(this._selectedAbilities, function (value, ability) { toRemove.push(ability); }); var self = this; _.each(toRemove, function (ability) { self._forceRemoveAbility(ability); }); }; Spec.prototype.getLevelRequired = function () { var self = this; return _.reduce(this._selectedAbilities, function (memo, v, abilityKey) { var ability = self._getAbility(abilityKey); if (!ability.isDefault) { memo++; } return memo; }, 1); }; Spec.prototype.saveHeroClassData = function (heroClassData) { this._heroClassData = heroClassData; }; Spec.prototype.resetToDefaults = function () { var self = this; this.removeAll(); _.each(this._heroClassData.abilities, function (ability) { if (ability.isDefault) { self._forceAddAbility(ability.key); } }); }; MicroEvent.mixin(Spec); if (typeof heroClassData !== 'undefined') { spec = new Spec(); spec.saveHeroClassData(heroClassData); spec.resetToDefaults(); console.log(heroClassData); var container = document.querySelector('.js-ability-forest-container'); React.render(<AbilityForest trees={heroClassData.trees}/>, container); } });
/** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ var egret; (function (egret) { var ExternalInterface = (function () { function ExternalInterface() { } /** * 将信息传递给 Egret 外层容器。 * 如果该容器是 HTML 页,则此方法不可用。 * 如果该容器是某个 App 容器,该容器将处理该事件。 * @method egret.ExternalInterface#call * @param functionName {string} * @param value {string} */ ExternalInterface.call = function (functionName, value) { }; /** * 添加外层容器调用侦听,该容器将传递一个字符串给 Egret 容器 * 如果该容器是 HTML 页,则此方法不可用。 * @method egret.ExternalInterface#addCallBack * @param functionName {string} * @param listener {Function} */ ExternalInterface.addCallback = function (functionName, listener) { }; return ExternalInterface; })(); egret.ExternalInterface = ExternalInterface; ExternalInterface.prototype.__class__ = "egret.ExternalInterface"; })(egret || (egret = {}));
var UpdateRetrySettingsSkillRequest_Skills = { "retrySettings": { "loadNonFresh": true, "finalizeWhenExhausted": true, "maximumAttempts": 0, "minimumRetryMinutes": 0, "maximumNumberOfHandledCalls": 0, "restrictedCallingMinutes": 0, "restrictedCallingMaxAttempts": 0, "generalStaleMinutes": 0, "callbackRestMinutes": 0, "releaseAgentSpecificCalls": true, "maximumNumberOfCallbacks": 0, "callbackStaleMinutes": 0 } };
import { connect } from "react-redux"; import MainContent from "../components/MainContent"; import { setLayout } from "../actions"; import { getWebcastIds } from "../selectors"; const mapStateToProps = (state) => ({ webcasts: getWebcastIds(state), hashtagSidebarVisible: state.visibility.hashtagSidebar, chatSidebarVisible: state.visibility.chatSidebar, layoutSet: state.videoGrid.layoutSet, }); const mapDispatchToProps = (dispatch) => ({ setLayout: (layoutId) => dispatch(setLayout(layoutId)), }); export default connect(mapStateToProps, mapDispatchToProps)(MainContent);
/*! jCarousel - v0.3.0-beta.5 - 2013-04-12 * http://sorgalla.com/jcarousel * Copyright (c) 2013 Jan Sorgalla; Licensed MIT */ (function($) { 'use strict'; $.jCarousel.plugin('jcarouselPagination', { _options: { perPage: null, item: function(page) { return '<a href="#' + page + '">' + page + '</a>'; }, event: 'click', method: 'scroll' }, _pages: {}, _items: {}, _currentPage: null, _init: function() { this.onDestroy = $.proxy(function() { this._destroy(); this.carousel() .one('createend.jcarousel', $.proxy(this._create, this)); }, this); this.onReload = $.proxy(this._reload, this); this.onScroll = $.proxy(this._update, this); }, _create: function() { this.carousel() .one('destroy.jcarousel', this.onDestroy) .on('reloadend.jcarousel', this.onReload) .on('scrollend.jcarousel', this.onScroll); this._reload(); }, _destroy: function() { this._clear(); this.carousel() .off('destroy.jcarousel', this.onDestroy) .off('reloadend.jcarousel', this.onReload) .off('scrollend.jcarousel', this.onScroll); }, _reload: function() { var perPage = this.options('perPage'); this._pages = {}; this._items = {}; // Calculate pages if ($.isFunction(perPage)) { perPage = perPage.call(this); } if (perPage == null) { this._pages = this._calculatePages(); } else { var pp = parseInt(perPage, 10) || 0, items = this.carousel().jcarousel('items'), page = 1, i = 0, curr; while (true) { curr = items.eq(i++); if (curr.size() === 0) { break; } if (!this._pages[page]) { this._pages[page] = curr; } else { this._pages[page] = this._pages[page].add(curr); } if (i % pp === 0) { page++; } } } this._clear(); var self = this, carousel = this.carousel().data('jcarousel'), element = this._element, item = this.options('item'); $.each(this._pages, function(page, carouselItems) { var currItem = self._items[page] = $(item.call(self, page, carouselItems)); currItem.on(self.options('event') + '.jcarouselpagination', $.proxy(function() { var target = carouselItems.eq(0); // If circular wrapping enabled, ensure correct scrolling direction if (carousel.circular) { var currentIndex = carousel.index(carousel.target()), newIndex = carousel.index(target); if (parseFloat(page) > parseFloat(self._currentPage)) { if (newIndex < currentIndex) { target = '+=' + (carousel.items().size() - currentIndex + newIndex); } } else { if (newIndex > currentIndex) { target = '-=' + (currentIndex + (carousel.items().size() - newIndex)); } } } carousel[this.options('method')](target); }, self)); element.append(currItem); }); this._update(); }, _update: function() { var target = this.carousel().jcarousel('target'), currentPage; $.each(this._pages, function(page, carouselItems) { carouselItems.each(function() { if (target.is(this)) { currentPage = page; return false; } }); if (currentPage) { return false; } }); if (this._currentPage !== currentPage) { this._trigger('inactive', this._items[this._currentPage]); this._trigger('active', this._items[currentPage]); } this._currentPage = currentPage; }, items: function() { return this._items; }, _clear: function() { this._element.empty(); this._currentPage = null; }, _calculatePages: function() { var carousel = this.carousel().data('jcarousel'), items = carousel.items(), clip = carousel.clipping(), wh = 0, idx = 0, page = 1, pages = {}, curr; while (true) { curr = items.eq(idx++); if (curr.size() === 0) { break; } if (!pages[page]) { pages[page] = curr; } else { pages[page] = pages[page].add(curr); } wh += carousel.dimension(curr); if (wh >= clip) { page++; wh = 0; } } return pages; } }); }(jQuery));
/* * Copyright (c) 2012-2016 André Bargull * Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms. * * <https://github.com/anba/es6draft> */ const { assertSame } = Assert; // 15.4.3.10: CreateOwnDataProperty no longer valid to use // https://bugs.ecmascript.org/show_bug.cgi?id=1883 let a = (new class extends Array{ constructor(...args){ super(...args); this.push(0) } }).slice(0, 1); assertSame(1, a.length); assertSame(0, a[0]);
/*! * Jade - utils * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca> * MIT Licensed */ /** * Convert interpolation in the given string to JavaScript. * * @param {String} str * @return {String} * @api private */ var interpolate = exports.interpolate = function(str){ return str.replace(/(_SLASH_)?([#!]){(.*?)}/g, function(str, escape, flag, code){ code = code .replace(/\\'/g, "'") .replace(/_SLASH_/g, '\\'); return escape ? str.slice(7) : "' + " + ('!' == flag ? '' : 'escape') + "((interp = " + code + ") == null ? '' : interp) + '"; }); }; /** * Escape single quotes in `str`. * * @param {String} str * @return {String} * @api private */ var escape = exports.escape = function(str) { return str.replace(/'/g, "\\'"); }; /** * Interpolate, and escape the given `str`. * * @param {String} str * @return {String} * @api private */ exports.text = function(str){ return interpolate(escape(str)); }; /** * Merge `b` into `a`. * * @param {Object} a * @param {Object} b * @return {Object} * @api public */ exports.merge = function(a, b) { for (var key in b) a[key] = b[key]; return a; };
import { default as React, Component, PropTypes, } from "react"; import { default as propTypesElementOfType, } from "react-prop-types-element-of-type"; import { default as canUseDOM, } from "can-use-dom"; import { default as warning, } from "warning"; import { GoogleMapLoader, GoogleMap, } from "../index"; import { default as makeUrl, urlObjDefinition, getUrlObjChangedKeys, } from "../utils/makeUrl"; export default class ScriptjsLoader extends Component { static propTypes = { ...urlObjDefinition, // PropTypes for ScriptjsLoader loadingElement: PropTypes.node, // ...GoogleMapLoader.propTypes,// Uncomment for 5.0.0 googleMapElement: propTypesElementOfType(GoogleMap).isRequired, }; static defaultProps = { }; state = { isLoaded: false, } shouldUseNewBehavior () { const {containerTagName, containerProps} = this.props.googleMapElement.props; return ( null != this.props.containerElement && undefined === containerTagName && undefined === containerProps ); } componentWillMount () { warning(this.shouldUseNewBehavior(), `"async/ScriptjsLoader" is now rendering "GoogleMapLoader". Migrate to use "GoogleMapLoader" instead. The old behavior will be removed in next major release (5.0.0). See https://github.com/tomchentw/react-google-maps/pull/157 for more details.` ); if (!canUseDOM) { return; } /* * External commonjs require dependency -- begin */ const scriptjs = require("scriptjs"); /* * External commonjs require dependency -- end */ const {protocol, hostname, port, pathname, query} = this.props; const urlObj = {protocol, hostname, port, pathname, query}; const url = makeUrl(urlObj); scriptjs(url, () => this.setState({ isLoaded: true })); } componentWillReceiveProps (nextProps) { if ("production" !== process.env.NODE_ENV) { const changedKeys = getUrlObjChangedKeys(this.props, nextProps); warning(0 === changedKeys.length, `ScriptjsLoader doesn't support mutating url related props after initial render. Changed props: %s`, `[${ changedKeys.join(", ") }]`); } } render () { if (this.state.isLoaded) { const {protocol, hostname, port, pathname, query, loadingElement, ...restProps} = this.props; if (this.shouldUseNewBehavior()) { return ( <GoogleMapLoader {...restProps} /> ); } else {//------------ Deprecated ------------ return this.props.googleMapElement; } } else { return this.props.loadingElement; } } }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const ioc = require(".."); const chai = require("chai"); let should = chai.should(); describe('Ioc', function () { describe('create ioc', function () { it('should crate empty Ioc', function () { let injector = ioc.createContainer(); should.exist(injector.getInstances()); }); it('should add add definitions', function () { let injector = ioc.createContainer(); injector.addDefinitions({ test: { type: function () { } } }); should.exist(injector.getDefinition('test')); }); it('should add duplicate definitions', function () { let injector = ioc.createContainer(); let Test1 = class Test1 { }; let Test2 = class Test1 { }; injector.addDefinitions({ test: { type: Test1 } }); injector.addDefinitions({ test: { type: Test2, override: true } }); injector.initialize(); injector.get('test').should.be.an.instanceOf(Test2); }); }); describe('get simple object', function () { let injector; it('should get object', function () { injector = ioc.createContainer(); class Rectangle { constructor() { } } injector.addDefinitions({ rectangle: { type: Rectangle } }); injector.initialize(); let rectangle = injector.getObject('rectangle'); should.exist(rectangle); }); }); describe('get simple object with linq', function () { it('should get object', function () { class Rectangle { constructor() { } } let injector = ioc.createContainer(); injector.register('rectangle', Rectangle); injector.initialize(); let rectangle = injector.getObject('rectangle'); should.exist(rectangle); }); }); describe('get simple object error', function () { let injector; it('should throw error if object not found', function () { injector = ioc.createContainer(); class Rectangle { constructor() { } } injector.addDefinitions({ rectangle: { type: Rectangle } }); injector.initialize(); (function () { var rectangle = injector.getObject('rectangle2'); }).should.throw("Injector:can't find object definition for objectID:rectangle2"); }); it('should throw error if object not found inner', function () { injector = ioc.createContainer(); class Rectangle { constructor() { } } injector.addDefinitions({ rectangle: { type: Rectangle, inject: [{ name: "test", ref: "test" }] } }); injector.initialize(); (function () { var rectangle = injector.getObject('rectangle'); }).should.throw("Injector:can't find object definition for objectID:test"); }); }); describe('reset ioc', function () { let injector; beforeEach(function () { injector = ioc.createContainer(); class Rectangle { constructor() { } } injector.addDefinitions({ rectangle: { type: Rectangle } }); injector.initialize(); }); it('should reset ioc', function () { should.exist(injector.getDefinition('rectangle')); should.exist(injector.getObject('rectangle')); injector.reset(); should.not.exist(injector.getDefinition('rectangle')); (function () { let rectangle = injector.getObject('rectangle'); }).should.throw(); }); }); describe('add object', function () { let injector; beforeEach(function () { injector = ioc.createContainer(); injector.initialize(); }); it('should add object', function () { function Test() { } injector.addObject('test', new Test()); let test = injector.getObject('test'); should.exist(test); test.should.be.an.instanceOf(Test); }); }); describe('get object by type', function () { let injector; it('should get by type', async function () { injector = ioc.createContainer(); class Rectangle { constructor() { } } class Circle { constructor() { } } injector.addDefinitions({ rectangle: { type: Rectangle, singleton: true } }); injector.addDefinitions({ circle: { type: Circle, singleton: true } }); await injector.initialize(); let objects = injector.getObjectsByType(Rectangle); objects.should.be.instanceof(Array).and.have.lengthOf(1); objects[0].should.be.instanceof(Rectangle); }); }); describe('get object with existing obj', function () { let injector, Rectangle, Circle; beforeEach(function () { injector = ioc.createContainer(); class Rectangle { constructor() { } } class Circle { constructor() { } } injector.addDefinitions({ rectangle: { type: Rectangle, singleton: true } }); injector.addDefinitions({ circle: { type: Circle, singleton: true } }); injector.addObject("test", {}); }); it('should not throw error', function () { (function () { injector.initialize(); }).should.not.throw(); }); }); }); //# sourceMappingURL=ioc.js.map
/* * grunt-texturepacker * https://github.com/saschagehlich/grunt-texturepacker * * Copyright (c) 2014 Sascha Gehlich * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Project configuration. grunt.initConfig({ jshint: { all: [ 'Gruntfile.js', 'tasks/*.js', '<%= nodeunit.tests %>', ], options: { jshintrc: '.jshintrc', }, }, // Before generating any new files, remove any previously-created files. clean: { tests: ['tmp'], }, // Configuration to be run (and then tested). texturepacker: { assets: { src: ["test/fixtures/**/*.png"], options: { scale: 2, scaleMode: 'fast', disableRotation: true, padding: 0, trimMode: '', algorithm: 'Basic', basicSortBy: 'Width', basicOrder: 'Ascending', output: { sheet: { file: 'tmp/assets.png', format: 'png' }, data: { file: 'tmp/assets.json', format: 'json' } } } } }, // Unit tests. nodeunit: { tests: ['test/*_test.js'], }, }); // Actually load this plugin's task(s). grunt.loadTasks('tasks'); // These plugins provide necessary tasks. grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); // Whenever the "test" task is run, first clean the "tmp" dir, then run this // plugin's task(s), then test the result. grunt.registerTask('test', ['clean', 'texturepacker', 'nodeunit']); // By default, lint and run all tests. grunt.registerTask('default', ['jshint', 'test']); };
// This will be replaced
'use strict'; require('ui.router'); require('../logger/logger.module'); require('angular') .module('blocks.exception', ['blocks.logger', 'ui.router']) .factory('exception', require('./exception')) .provider('exceptionHandler', require('./exception-handler.provider')) .config(require('./exception-handler.config'));
import React from 'react' import { Form, TextArea } from 'shengnian-ui-react' const TextAreaExampleTextArea = () => ( <Form> <TextArea placeholder='Tell us more' /> </Form> ) export default TextAreaExampleTextArea
module.exports = function(grunt) { grunt.initConfig({ wiredep: { app: { src: 'index.html' } } }); grunt.loadNpmTasks('grunt-wiredep'); grunt.registerTask('default', ['wiredep']); }
// flow-typed signature: 1dff23447d5e18f5ac2b05aaec7cfb74 // flow-typed version: a453e98ea2/rimraf_v2.x.x/flow_>=v0.25.0 declare module 'rimraf' { declare type Options = { maxBusyTries?: number, emfileWait?: number, glob?: boolean, disableGlob?: boolean, }; declare type Callback = (err: ?Error, path: ?string) => void; declare module.exports: { (f: string, opts?: Options | Callback, callback?: Callback): void, sync(path: string, opts?: Options): void, }; }
/** * @author mrdoob / http://mrdoob.com/ */ import JSZip from 'jszip' import { Menubar } from "./Menubar" Menubar.File = function ( editor ) { var container = new UI.Panel(); container.setClass( 'menu' ); var title = new UI.Panel(); title.setClass( 'title' ); title.setTextContent( 'File' ); container.add( title ); var options = new UI.Panel(); options.setClass( 'options' ); container.add( options ); // New var option = new UI.Row(); option.setClass( 'option' ); option.setTextContent( 'New' ); option.onClick( function () { if ( confirm( 'Any unsaved data will be lost. Are you sure?' ) ) { editor.clear(); } } ); options.add( option ); // options.add( new UI.HorizontalRule() ); // Import var fileInput = document.createElement( 'input' ); fileInput.type = 'file'; fileInput.addEventListener( 'change', function ( event ) { editor.loader.loadFile( fileInput.files[ 0 ] ); } ); var option = new UI.Row(); option.setClass( 'option' ); option.setTextContent( 'Import' ); option.onClick( function () { fileInput.click(); } ); options.add( option ); // options.add( new UI.HorizontalRule() ); // Export Geometry var option = new UI.Row(); option.setClass( 'option' ); option.setTextContent( 'Export Geometry' ); option.onClick( function () { var object = editor.selected; if ( object === null ) { alert( 'No object selected.' ); return; } var geometry = object.geometry; if ( geometry === undefined ) { alert( 'The selected object doesn\'t have geometry.' ); return; } var output = geometry.toJSON(); try { output = JSON.stringify( output, null, '\t' ); output = output.replace( /[\n\t]+([\d\.e\-\[\]]+)/g, '$1' ); } catch ( e ) { output = JSON.stringify( output ); } saveString( output, 'geometry.json' ); } ); options.add( option ); // Export Object var option = new UI.Row(); option.setClass( 'option' ); option.setTextContent( 'Export Object' ); option.onClick( function () { var object = editor.selected; if ( object === null ) { alert( 'No object selected' ); return; } var output = object.toJSON(); try { output = JSON.stringify( output, null, '\t' ); output = output.replace( /[\n\t]+([\d\.e\-\[\]]+)/g, '$1' ); } catch ( e ) { output = JSON.stringify( output ); } saveString( output, 'model.json' ); } ); options.add( option ); // Export Scene var option = new UI.Row(); option.setClass( 'option' ); option.setTextContent( 'Export Scene' ); option.onClick( function () { var output = editor.scene.toJSON(); try { output = JSON.stringify( output, null, '\t' ); output = output.replace( /[\n\t]+([\d\.e\-\[\]]+)/g, '$1' ); } catch ( e ) { output = JSON.stringify( output ); } saveString( output, 'scene.json' ); } ); options.add( option ); // Export OBJ var option = new UI.Row(); option.setClass( 'option' ); option.setTextContent( 'Export OBJ' ); option.onClick( function () { var object = editor.selected; if ( object === null ) { alert( 'No object selected.' ); return; } var exporter = new THREE.OBJExporter(); saveString( exporter.parse( object ), 'model.obj' ); } ); options.add( option ); // Export STL var option = new UI.Row(); option.setClass( 'option' ); option.setTextContent( 'Export STL' ); option.onClick( function () { var exporter = new THREE.STLExporter(); saveString( exporter.parse( editor.scene ), 'model.stl' ); } ); options.add( option ); // options.add( new UI.HorizontalRule() ); // Publish var option = new UI.Row(); option.setClass( 'option' ); option.setTextContent( 'Publish' ); option.onClick( function () { var zip = new JSZip(); // var output = editor.toJSON(); output.metadata.type = 'App'; delete output.history; var vr = output.project.vr; output = JSON.stringify( output, null, '\t' ); output = output.replace( /[\n\t]+([\d\.e\-\[\]]+)/g, '$1' ); zip.file( 'app.json', output ); // var manager = new THREE.LoadingManager( function () { save( zip.generate( { type: 'blob' } ), 'download.zip' ); } ); var loader = new THREE.FileLoader( manager ); loader.load( 'js/libs/app/index.html', function ( content ) { var includes = []; if ( vr ) { includes.push( '<script src="js/VRControls.js"></script>' ); includes.push( '<script src="js/VREffect.js"></script>' ); includes.push( '<script src="js/WebVR.js"></script>' ); } content = content.replace( '<!-- includes -->', includes.join( '\n\t\t' ) ); zip.file( 'index.html', content ); } ); loader.load( 'js/libs/app.js', function ( content ) { zip.file( 'js/app.js', content ); } ); loader.load( '../build/three.min.js', function ( content ) { zip.file( 'js/three.min.js', content ); } ); if ( vr ) { loader.load( '../examples/js/controls/VRControls.js', function ( content ) { zip.file( 'js/VRControls.js', content ); } ); loader.load( '../examples/js/effects/VREffect.js', function ( content ) { zip.file( 'js/VREffect.js', content ); } ); loader.load( '../examples/js/WebVR.js', function ( content ) { zip.file( 'js/WebVR.js', content ); } ); } } ); options.add( option ); /* // Publish (Dropbox) var option = new UI.Row(); option.setClass( 'option' ); option.setTextContent( 'Publish (Dropbox)' ); option.onClick( function () { var parameters = { files: [ { 'url': 'data:text/plain;base64,' + window.btoa( "Hello, World" ), 'filename': 'app/test.txt' } ] }; Dropbox.save( parameters ); } ); options.add( option ); */ // var link = document.createElement( 'a' ); link.style.display = 'none'; document.body.appendChild( link ); // Firefox workaround, see #6594 function save( blob, filename ) { link.href = URL.createObjectURL( blob ); link.download = filename || 'data.json'; link.click(); // URL.revokeObjectURL( url ); breaks Firefox... } function saveString( text, filename ) { save( new Blob( [ text ], { type: 'text/plain' } ), filename ); } return container; };
/** Write me... Straight-up stolen from `Handlebars.registerHelper('outlet', ...);` @method outlet @for Ember.Handlebars.helpers @param {String} property the property on the controller that holds the view for this outlet */ Handlebars.registerHelper('animated-outlet', function(property, options) { var outletSource; if (property && property.data && property.data.isRenderData) { options = property; property = 'main'; } outletSource = options.data.view; while (!(outletSource.get('template.isTop'))){ outletSource = outletSource.get('_parentView'); } options.data.view.set('outletSource', outletSource); options.hash.currentViewBinding = '_view.outletSource._outlets.' + property; //Only this line has been changed return Ember.Handlebars.helpers.view.call(this, Ember.AnimatedContainerView, options); }); /** See animated-outlet */ Handlebars.registerHelper('animatedOutlet', function(property, options) { Ember.warn("The 'animatedOutlet' view helper is deprecated in favor of 'animated-outlet'"); return Ember.Handlebars.helpers['animated-outlet'].apply(this, arguments); });
/*! * multirest * Copyright(c) 2016 Richard Nemec * MIT Licensed */ 'use strict' /** * Module dependencies. * @private */ const debug = require('debug')('multirest'); const request = require('supertest-as-promised'); const Bluebird = require('bluebird'); /** * Module exports. * @public */ module.exports = multirest; /** * Create a new multirest middleware. * * @param {object} [options] * @param {array} [options.concurrency] * @return {function} middleware * @public */ function multirest(app, options) { var opts = options || {}; var concurrency = opts.concurrency || 5; debug('multirest options %j', opts); return function _multirest(req, res, next) { function _invokeMethod(itemReq) { var r = request(app); if (itemReq.method === 'GET') { return r.get(itemReq.url); } else if (itemReq.method === 'POST') { return r.post(itemReq.url).send(itemReq.body); } else if (itemReq.method === 'PUT') { return r.put(itemReq.url).send(itemReq.body); } else if (itemReq.method === 'PATCH') { return r.patch(itemReq.url).send(itemReq.body); } else if (itemReq.method === 'DELETE') { return r.delete(itemReq.url); } } function invokeItemReq(itemReq) { return _invokeMethod(itemReq) .set(req.headers) .then(function(itemRes) { mergeCookies(itemRes, res); return { status: itemRes.status, body: itemRes.body }; }) .catch(function(err) { return { status: 500, body: err.toString() }; }) } try { if (!req.body) { var err = "No body in the multirest request - most likely body parser is not use-d before multirest"; console.error(err); next(err); return; } // our URL to prevent cycling var multirestUrl = req.url; var requests = req.body; if (!Array.isArray(requests)) { var err = "The body in the multirest request must be an array. Likely client request mistake."; console.error(err); next(err); return; } // deal with headers delete req.headers['content-length']; Bluebird.map(requests, invokeItemReq, {concurrency: concurrency}) .then(function(results) {res.json(results);}) .catch(function(err) { console.error(err); next(err); }); } catch (e) { console.error(e); next(e); } } } function mergeCookies(itemRes, res) { try { // get cookies from superagent response structure var cookiesHdr = itemRes.header['set-cookie']; if (cookiesHdr) { // set cookies into express/http response res.setHeader('set-cookie', cookiesHdr); } } catch (e) { console.error(e); throw e; } }
'use strict'; require('node-jsx').install(); var http = require('http'); var path = require('path'); var Hapi = require('hapi'); var Joi = require('joi'); var Boom = require('boom'); var union = require('lodash.union'); var conf = require('./lib/conf'); var auth = require('./lib/auth/auth'); var schema = require('./lib/schema'); var auth_services = require('./lib/auth/services'); var db = require('./lib/db'); var services = require('./lib/services'); var admin = require('./lib/admin'); var apiUserRoutes = require('./lib/api/routes/users'); var apiTopicRoutes = require('./lib/api/routes/topics'); var server = new Hapi.Server(); if (!conf.get('port')) { console.error('\n\'port\' is a required local.json field'); console.error('If you don\'t have a local.json file set up, please copy local.json-dist and fill in your config info before trying again\n'); } server.connection({ host: conf.get('domain'), port: conf.get('port') }); server.views({ engines: { jade: require('jade') }, isCached: process.env.node === 'production', path: path.join(__dirname, '/lib/views'), compileOptions: { pretty: true } }); var routes = [ { method: 'GET', path: '/', handler: services.index }, { method: 'GET', path: '/public/{param*}', handler: { directory: { path: 'public' } } }, { method: 'GET', path: '/logout', handler: auth_services.logout }, { method: 'GET', path: '/admin', handler: admin.index }, { method: 'GET', path: '/admin/users', handler: admin.users }, { method: 'GET', path: '/auth/twitter', handler: auth_services.twitter }, { method: 'GET', path: '/auth/twitter/callback', handler: auth_services.twitter_callback } ]; var options = { cookieOptions: { password: conf.get('cookie'), isSecure: false, clearInvalid: true } }; server.ext('onPreResponse', function (request, reply) { var response = request.response; if (!response.isBoom) { if (['/profile', '/messages', '/chat', '/posts', '/links', '/users', '/deleteaccount', '/post', '/profile/export.json', '/profile/export.csv'].indexOf(request.path) > -1) { if (!request.session.get('session_id')) { return reply.redirect('/'); } } if (request.path.indexOf('/admin') > -1) { if (request.session.get('user_role').name !== 'admin') { return reply.redirect('/'); } } return reply.continue(); } var error = response; var ctx = {}; var message = error.output.payload.message; var statusCode = error.output.statusCode || 500; ctx.code = statusCode; ctx.httpMessage = http.STATUS_CODES[statusCode].toLowerCase(); switch (statusCode) { case 404: ctx.reason = 'page not found'; break; case 403: ctx.reason = 'forbidden'; break; case 500: ctx.reason = 'something went wrong'; break; default: break; } if (process.env.npm_lifecycle_event === 'dev') { console.log(error.stack || error); } if (ctx.reason) { // Use actual message if supplied ctx.reason = message || ctx.reason; return reply.view('error', ctx).code(statusCode); } else { ctx.reason = message.replace(/\s/gi, '+'); reply.redirect(request.path + '?err=' + ctx.reason); } }); if (process.env.NODE_ENV !== 'test') { server.register({ register: require('crumb') }, function (err) { if (err) { throw err; } }); } server.register([{ register: require('yar'), options: options }], function (err) { if (err) { throw new Error(err.message); } }); server.route(union(routes, apiUserRoutes, apiTopicRoutes)); server.start(function (err) { if (err) { throw new Error(err.message); } });
const DrawCard = require('../../drawcard.js'); class TatteredMissive extends DrawCard { setupCardAbilities(ability) { this.action({ title: 'Search top 5 cards', condition: context => context.player.conflictDeck.size() > 0, cost: ability.costs.bowParent(), effect: 'look at the top 5 cards of their conflict deck', gameAction: ability.actions.deckSearch({ amount: 5, reveal: true }) }); } canAttach(card, context) { if(!card.hasTrait('courtier') || card.controller !== context.player) { return false; } return super.canAttach(card, context); } } TatteredMissive.id = 'tattered-missive'; module.exports = TatteredMissive;
'use strict'; angular.module('jsDispatchApp') .factory('Modal', function ($rootScope, $modal) { /** * Opens a modal * @param {Object} scope - an object to be merged with modal's scope * @param {String} modalClass - (optional) class(es) to be applied to the modal * @return {Object} - the instance $modal.open() returns */ function openModal(scope, modalClass) { var modalScope = $rootScope.$new(); scope = scope || {}; modalClass = modalClass || 'modal-default'; angular.extend(modalScope, scope); return $modal.open({ templateUrl: 'components/modal/modal.html', windowClass: modalClass, scope: modalScope }); } // Public API here return { /* Confirmation modals */ confirm: { /** * Create a function to open a delete confirmation modal (ex. ng-click='myModalFn(name, arg1, arg2...)') * @param {Function} del - callback, ran when delete is confirmed * @return {Function} - the function to open the modal (ex. myModalFn) */ delete: function(del) { del = del || angular.noop; /** * Open a delete confirmation modal * @param {String} name - name or info to show on modal * @param {All} - any additional args are passed staight to del callback */ return function() { var args = Array.prototype.slice.call(arguments), name = args.shift(), deleteModal; deleteModal = openModal({ modal: { dismissable: true, title: 'Confirm Delete', html: '<p>Are you sure you want to delete <strong>' + name + '</strong> ?</p>', buttons: [{ classes: 'btn-danger', text: 'Delete', click: function(e) { deleteModal.close(e); } }, { classes: 'btn-default', text: 'Cancel', click: function(e) { deleteModal.dismiss(e); } }] } }, 'modal-danger'); deleteModal.result.then(function(event) { del.apply(event, args); }); }; } } }; });
(function(){ var app = angular.module('weatherApp'); var weatherSvc = function($http){ var getCurrentWeather = function(city){ // this returns the promise from the $http.get() request so it is now thennable return $http.get('http://api.openweathermap.org/data/2.5/weather?q=' + city + '&units=imperial') } var getForecast = function(city){ return $http.get('http://api.openweathermap.org/data/2.5/forecast/daily?q=' + city + '&units=imperial') } // the return is returning a reference to the getCurentWeather function, like a public function return { getCurrent: getCurrentWeather, getForecast: getForecast } } app.factory('weather', weatherSvc); }())
var levelup = require('levelup'); var r = require("restify"); var db = levelup("store") function put(req, res, next) { var body = JSON.parse(req.body) var key = body.key var val = body.value db.put(key, val, function(err) { if (err) {console.log(err)} res.send(JSON.stringify(req.body) + ' inserted'); return next(); }) } function get(req, res, next) { var key = req.params.key db.get(key, function(err, value) { if (err) {console.log(err)} res.send(value); return next(); }) } var server = r.createServer({ name: 'naturalDB', version: require("./package.json").version }); server.use(r.bodyParser()); server.listen(8080); server.get('/get/:key', get); server.post('/put', put); console.log(' add: curl -X POST -d \'{"key": "Anette", "value": "girlfriend"}\' localhost:8080/put') console.log(' get: curl localhost:8080/get/Anette')
var structtesting__1__1internal__1__1__static__assert__type__eq__helper__3__01__t__00__01__t__01__4_8js = [ [ "structtesting_1_1internal_1_1_static_assert_type_eq_helper_3_01_t_00_01_t_01_4", "structtesting__1__1internal__1__1__static__assert__type__eq__helper__3__01__t__00__01__t__01__4_8js.html#ac6183e42c33fb45b46bd5e7ab1557230", null ] ];
'use strict'; /* jasmine specs for controllers go here */ describe('The controller', function(){ var scope = {}; var ctrl = undefined; beforeEach(module('contactApp.controllers')); beforeEach(module('contactApp')); describe('contactlistCtrl', function(){ beforeEach(inject(function($location, $controller, $rootScope){ scope = $rootScope.$new(); ctrl = $controller('contactListCtrl', { $location: location, $scope: scope }); })); it('should exist', function(){ expect(ctrl).toBeDefined(); }); it('should contain contacts on its scope', function(){ expect(scope.contacts).toBeDefined(); }); describe('viewContact method', function(){ it('should redirect to id passed to it', function(){ scope.contacts = { name: 'Bob', address: 'Village Town', number: '12345' }; // pass }); }); describe('editContact method', function(){ //pass }); describe('addContact method', function(){ // pass }); describe('deleteContact method', function(){ it('should delete specified contact along name', function(){ var contactsLength; var info = { name: 'Rob', address: 'Village Town', number: '12345' }; scope.save(info.name, info.address, info.number); contactsLength = scope.contacts.length; scope.deleteContact(info.name); expect(scope.contacts.length).toBe(contactsLength -1); }); }); }); describe('editCtrl', function(){ beforeEach(inject(function($controller, $rootScope){ scope = $rootScope.$new(); ctrl = $controller('contactEditCtrl', { $scope: scope }); })); it('should save a contact on save()', function(){ scope.contact = {name:'Bob', address:'Valley Park', number:'123456'}; expect(scope.save()).toEqual(true); }); }); });
var express = require('express'); var app = express(); // 设置模板引擎 app.set('view engine', 'ejs'); app.get('/', function (req, res) { res.render('form'); }); app.post('/', function (req, res) { // 将数据添加进入数据库 res.send('成功'); }); app.listen(3000, function () { console.log('监听端口号: 3000'); });
'use strict'; import React from 'react'; class Rippler extends React.Component { style; constructor(props) { super(props); } render() { this.style = ({ top : this.props.y-50, left : this.props.x-50}) return ( <div> <div className={this.props.t_w_classes}> <div className={this.props.tr_classes} style={this.style}> </div> </div> </div> ); } componentWillUpdate() { } } export default Rippler; /* <div className={this.t_w_classes}> <div className={'transitioner' + this.tr_classes } style={this.rippleStyle}> </div> </div> */
app.run(function($rootScope) { $rootScope.user = { settings: { tts: { enabled: true, countdown: true, voice: 0 } } }; $rootScope.timers = [ /* { id: String // Unique ID of this timer (used for URL slug) title: String // Human friendly name of the timer profile description: String // UNSUPPORTED Description of the routine routineTime: String // UNSUPPORTED Time the routine should be run for (e.g. '1 week') script: [ // Array of script items { title: String // The display title of the item time: Int // Time in seconds to display say: Bool|String // If true the title will be said via TTS, if a string it will be passed to TTS countdown: Bool // (Default: true), use TTS to announce the countdown { ] } */ { id: 'tennisElbow', title: 'Tennis Elbow Session 1', description: 'Simple Tennis Elbow stretches with the aid of a rubber band. Designed to work with a arm at 90 degrees bend.', routineTime: '1 week', script: [ { title: 'Preperation', time: 5 * 1000, }, { title: 'Right arm stress #1', time: 60 * 1000, }, { title: 'Rest', time: 60 * 1000, say: true }, { title: 'Right arm stress #2', time: 60 * 1000, }, { title: 'Rest', time: 60 * 1000, say: true }, { title: 'Right arm stress #3', time: 60 * 1000, }, { title: 'Rest', time: 60 * 1000, say: true }, { title: 'Right arm stress #4', time: 60 * 1000, }, { title: 'Switch to left arm', time: 10 * 1000, say: true }, { title: 'Left arm stress #1', time: 60 * 1000, }, { title: 'Rest', time: 60 * 1000, say: true }, { title: 'Left arm stress #2', time: 60 * 1000, }, { title: 'Rest', time: 60 * 1000, say: true }, { title: 'Left arm stress #3', time: 60 * 1000, }, { title: 'Rest', time: 60 * 1000, say: true }, { title: 'Left arm stress #4', time: 60 * 1000, }, { title: 'Finished', say: true, countdown: false } ] }, { id: 'tennisElbow1Compressed', title: 'Tennis Elbow Session 1 (Alternating)', description: 'Alternating Tennis Elbow stretches desgigned to reduce the time of the routine. Designed to work with a arm at 90 degrees bend.', routineTime: '1 week', script: [ { title: 'Preperation', time: 5 * 1000, }, { title: 'Right arm stress #1', time: 60 * 1000, }, { title: 'Switch to left arm', time: 10 * 1000, say: true }, { title: 'Left arm stress #1', time: 60 * 1000, }, { title: 'Switch to right arm', time: 10 * 1000, say: true }, { title: 'Right arm stress #2', time: 60 * 1000, }, { title: 'Switch to left arm', time: 10 * 1000, say: true }, { title: 'Left arm stress #2', time: 60 * 1000, }, { title: 'Switch to right arm', time: 10 * 1000, say: true }, { title: 'Right arm stress #3', time: 60 * 1000, }, { title: 'Switch to left arm', time: 10 * 1000, say: true }, { title: 'Left arm stress #3', time: 60 * 1000, }, { title: 'Switch to right arm', time: 10 * 1000, say: true }, { title: 'Right arm stress #4', time: 60 * 1000, }, { title: 'Switch to left arm', time: 10 * 1000, say: true }, { title: 'Left arm stress #4', time: 60 * 1000, }, { title: 'Finished', say: true, countdown: false } ] }, { id: 'tennisElbow2', title: 'Tennis Elbow Session 2', description: 'Straight arm based Tennis Elbow exsorsizes. Stretch arm in \'stopping motion\'.', routineTime: '10 days', script: [ { title: 'Preperation', time: 5 * 1000, }, { title: 'Right arm stress #1', time: 45 * 1000, }, { title: 'Switch to left arm', time: 10 * 1000, say: true }, { title: 'Left arm stress #1', time: 45 * 1000, }, { title: 'Switch to right arm', time: 10 * 1000, say: true }, { title: 'Right arm stress #2', time: 45 * 1000, }, { title: 'Switch to left arm', time: 10 * 1000, say: true }, { title: 'Left arm stress #2', time: 45 * 1000, }, { title: 'Switch to right arm', time: 10 * 1000, say: true }, { title: 'Right arm stress #3', time: 45 * 1000, }, { title: 'Switch to left arm', time: 10 * 1000, say: true }, { title: 'Left arm stress #3', time: 45 * 1000, }, { title: 'Switch to right arm', time: 10 * 1000, say: true }, { title: 'Right arm stress #4', time: 45 * 1000, }, { title: 'Switch to left arm', time: 10 * 1000, say: true }, { title: 'Left arm stress #4', time: 45 * 1000, }, { title: 'Finished', say: true, countdown: false } ] }, { id: 'tennisElbow3', title: 'Tennis Elbow Session 3 (60s)', description: '5kg Weight holding exorcizes, twice a day', routineTime: '14 days', script: [ { title: 'Preperation', time: 5 * 1000, }, { title: 'Right arm weights #1', time: 60 * 1000, }, { title: 'Switch to left arm', time: 5 * 1000, say: true }, { title: 'Left arm weights #1', time: 60 * 1000, }, { title: 'Switch to right arm', time: 5 * 1000, say: true }, { title: 'Right arm weights #2', time: 60 * 1000, }, { title: 'Switch to left arm', time: 5 * 1000, say: true }, { title: 'Left arm weights #2', time: 60 * 1000, }, { title: 'Switch to right arm', time: 5 * 1000, say: true }, { title: 'Right arm weights #3', time: 60 * 1000, }, { title: 'Switch to left arm', time: 5 * 1000, say: true }, { title: 'Left arm weights #3', time: 60 * 1000, }, { title: 'Switch to right arm', time: 5 * 1000, say: true }, { title: 'Right arm weights #4', time: 60 * 1000, }, { title: 'Switch to left arm', time: 5 * 1000, say: true }, { title: 'Left arm weights #4', time: 60 * 1000, }, { title: 'Finished', say: true, countdown: false } ] }, { id: 'tennisElbow3-45s', title: 'Tennis Elbow Session 3 (45s)', description: '5kg Weight holding exorcizes, twice a day with lighter 45 second intervals', routineTime: '14 days', script: [ { title: 'Preperation', time: 5 * 1000, }, { title: 'Right arm weights #1', time: 45 * 1000, }, { title: 'Switch to left arm', time: 5 * 1000, say: true }, { title: 'Left arm weights #1', time: 45 * 1000, }, { title: 'Switch to right arm', time: 5 * 1000, say: true }, { title: 'Right arm weights #2', time: 45 * 1000, }, { title: 'Switch to left arm', time: 5 * 1000, say: true }, { title: 'Left arm weights #2', time: 45 * 1000, }, { title: 'Switch to right arm', time: 5 * 1000, say: true }, { title: 'Right arm weights #3', time: 45 * 1000, }, { title: 'Switch to left arm', time: 5 * 1000, say: true }, { title: 'Left arm weights #3', time: 45 * 1000, }, { title: 'Switch to right arm', time: 5 * 1000, say: true }, { title: 'Right arm weights #4', time: 45 * 1000, }, { title: 'Switch to left arm', time: 5 * 1000, say: true }, { title: 'Left arm weights #4', time: 45 * 1000, }, { title: 'Finished', say: true, countdown: false } ] }, { id: 'tennisElbow3-60s', title: 'Tennis Elbow Session 3 (60s)', description: '5kg Weight holding exorcizes, twice a day with 60 second intervals', routineTime: '14 days', script: [ { title: 'Preperation', time: 5 * 1000, }, { title: 'Right arm weights #1', time: 60 * 1000, }, { title: 'Switch to left arm', time: 5 * 1000, say: true }, { title: 'Left arm weights #1', time: 60 * 1000, }, { title: 'Switch to right arm', time: 5 * 1000, say: true }, { title: 'Right arm weights #2', time: 60 * 1000, }, { title: 'Switch to left arm', time: 5 * 1000, say: true }, { title: 'Left arm weights #2', time: 60 * 1000, }, { title: 'Switch to right arm', time: 5 * 1000, say: true }, { title: 'Right arm weights #3', time: 60 * 1000, }, { title: 'Switch to left arm', time: 5 * 1000, say: true }, { title: 'Left arm weights #3', time: 60 * 1000, }, { title: 'Switch to right arm', time: 5 * 1000, say: true }, { title: 'Right arm weights #4', time: 60 * 1000, }, { title: 'Switch to left arm', time: 5 * 1000, say: true }, { title: 'Left arm weights #4', time: 60 * 1000, }, { title: 'Finished', say: true, countdown: false } ] } ]; });
import { combineReducers } from 'redux' import { routerReducer } from 'react-router-redux' import { reducer as formReducer } from 'redux-form' import { hasErrorReducer, hasResultsReducer, isLoadingReducer } from './statekeys' import contactReducer from './contact' const rootReducer = combineReducers({ isLoading: isLoadingReducer, hasResults: hasResultsReducer, hasErrors: hasErrorReducer, contact: contactReducer, routing: routerReducer, form: formReducer }) export default rootReducer
define(["Pilot", "Ship", "ShipBase", "Team"], function(Pilot, Ship, ShipBase, Team) { "use strict"; function PilotSkillRestriction(pilotSkill) { InputValidator.validateNotNull("pilotSkill", pilotSkill); return ( { name: "Pilot Skill above \"" + pilotSkill + "\".", passes: function(pilotKey) { var pilot = Pilot.properties[pilotKey]; var myPilotSkill = pilot.pilotSkillValue; if (myPilotSkill === undefined && pilot.fore) { myPilotSkill = pilot.fore.pilotSkillValue; } if (myPilotSkill === undefined) { myPilotSkill = pilot.shipTeam.ship.pilotSkillValue; } if (myPilotSkill === undefined && pilot.shipTeam.ship.fore) { myPilotSkill = pilot.shipTeam.ship.fore.pilotSkillValue; } return myPilotSkill > pilotSkill; } }); } function ShipSizeRestriction(shipBaseKey) { InputValidator.validateNotNull("shipBaseKey", shipBaseKey); var props = ShipBase.properties[shipBaseKey]; return ( { name: props.name + " only.", passes: function(pilotKey) { var pilot = Pilot.properties[pilotKey]; var myShipBaseKey = pilot.shipTeam.ship.shipBaseKey; return myShipBaseKey === shipBaseKey; } }); } function ShipRestriction(shipKey) { InputValidator.validateNotNull("shipKey", shipKey); var myShipKey = shipKey; var props = Ship.properties[myShipKey]; if (shipKey.endsWith("fore")) { myShipKey = shipKey.split(".")[0]; props = Ship.properties[myShipKey].fore; } else if (shipKey.endsWith("aft") && !shipKey.endsWith("Craft")) { myShipKey = shipKey.split(".")[0]; props = Ship.properties[myShipKey].aft; } var name = props.name; if (shipKey === Ship.CR90_CORVETTE || shipKey === Ship.GR_75_MEDIUM_TRANSPORT) { name = props.name.split(" ")[0]; } else if (shipKey.startsWith(Ship.RAIDER_CLASS_CORVETTE)) { name = name.replace("(", ""); name = name.replace(")", ""); name += " section"; } return ( { name: name + " only.", passes: function(pilotKey) { var pilot = Pilot.properties[pilotKey]; var myShipKey = pilot.shipTeam.shipKey; return myShipKey === shipKey; } }); } function TeamRestriction(teamKey) { InputValidator.validateNotNull("teamKey", teamKey); var props = Team.properties[teamKey]; return ( { name: props.name + " only.", passes: function(pilotKey) { var pilot = Pilot.properties[pilotKey]; var myTeamKey = pilot.shipTeam.teamKey; return myTeamKey === teamKey; } }); } var UpgradeRestriction = { // Pilot skill lower bound. PILOT_SKILL_ABOVE_1: "pilotSkillAbove1", PILOT_SKILL_ABOVE_2: "pilotSkillAbove2", PILOT_SKILL_ABOVE_3: "pilotSkillAbove3", PILOT_SKILL_ABOVE_4: "pilotSkillAbove4", // Ship specific. A_WING_ONLY: "aWingOnly", AGGRESSOR_ONLY: "aggressorOnly", ARC_170_ONLY: "arc170Only", B_WING_ONLY: "bWingOnly", C_ROC_CRUISER_AND_GR_75_ONLY: "cRocCruiserAndGr75Only", C_ROC_CRUISER_ONLY: "cRocCruiserOnly", CR90_ONLY: "cr90Only", FIRESPRAY_31_ONLY: "firespray31Only", G_1A_STARFIGHTER_ONLY: "g1AStarfighterOnly", GOZANTI_CLASS_CRUISER_ONLY: "gozantiClassCruiserOnly", GR_75_ONLY: "gr75Only", HWK_290_ONLY: "hwk290Only", JUMPMASTER_5000_ONLY: "jumpMaster5000Only", LAMBDA_CLASS_SHUTTLE_ONLY: "lambdaClassShuttleOnly", LANCER_CLASS_PURSUIT_CRAFT_ONLY: "lancerClassPursuitCraftOnly", M3_A_INTERCEPTOR_ONLY: "m3AInterceptorOnly", PROTECTORATE_STARFIGHTER_ONLY: "protectorateStarfighterOnly", RAIDER_CLASS_CORVETTE_AFT_SECTION_ONLY: "raiderClassCorvetteAftSectionOnly", STAR_VIPER_ONLY: "starViperOnly", T_70_X_WING_ONLY: "t70XWingOnly", TIE_ADVANCED_ONLY: "tieAdvancedOnly", TIE_ADVANCED_PROTOTYPE_ONLY: "tieAdvancedPrototypeOnly", TIE_BOMBER_ONLY: "tieBomberOnly", TIE_DEFENDER_ONLY: "tieDefenderOnly", TIE_INTERCEPTOR_ONLY: "tieInterceptorOnly", TIE_PHANTOM_ONLY: "tiePhantomOnly", TIE_SF_ONLY: "tieSfOnly", U_WING_ONLY: "uWingOnly", UPSILON_CLASS_SHUTTLE_ONLY: "upsilonClassShuttleOnly", VCX_100_ONLY: "vcx100Only", VT_49_DECIMATOR_ONLY: "vt49DecimatorOnly", X_WING_ONLY: "xWingOnly", YT_1300_AND_YT_2400_ONLY: "yt1300AndYt2400Only", YT_1300_ONLY: "yt1300Only", YT_2400_ONLY: "yt2400Only", Y_WING_ONLY: "yWingOnly", YV_666_ONLY: "yv666Only", // Ship size. HUGE_SHIP_ONLY: "hugeShipOnly", LARGE_SHIP_ONLY: "largeShipOnly", SMALL_SHIP_ONLY: "smallShipOnly", // Team specific. IMPERIAL_ONLY: "imperialOnly", REBEL_AND_SCUM_ONLY: "rebelAndScumOnly", REBEL_ONLY: "rebelOnly", SCUM_ONLY: "scumOnly", // Miscellaneous. LIMITED: "limited", TIE_ONLY: "tieOnly", properties: { "aWingOnly": new ShipRestriction(Ship.A_WING), "aggressorOnly": new ShipRestriction(Ship.AGGRESSOR), "arc170Only": new ShipRestriction(Ship.ARC_170), "bWingOnly": new ShipRestriction(Ship.B_WING), "cRocCruiserAndGr75Only": { name: "C-ROC Cruiser and GR-75 only.", passes: function(pilotKey) { var pilot = Pilot.properties[pilotKey]; var shipKey = pilot.shipTeam.shipKey; return shipKey === Ship.C_ROC_CRUISER || shipKey === Ship.GR_75_MEDIUM_TRANSPORT; } }, "cRocCruiserOnly": new ShipRestriction(Ship.C_ROC_CRUISER), "cr90Only": new ShipRestriction(Ship.CR90_CORVETTE), "firespray31Only": new ShipRestriction(Ship.FIRESPRAY_31), "g1AStarfighterOnly": new ShipRestriction(Ship.G_1A_STARFIGHTER), "gozantiClassCruiserOnly": new ShipRestriction(Ship.GOZANTI_CLASS_CRUISER), "gr75Only": new ShipRestriction(Ship.GR_75_MEDIUM_TRANSPORT), "hugeShipOnly": { name: "Huge ship only.", passes: function(pilotKey) { var pilot = Pilot.properties[pilotKey]; var shipBaseKey = pilot.shipTeam.ship.shipBaseKey; return ShipBase.isHuge(shipBaseKey); } }, "hwk290Only": new ShipRestriction(Ship.HWK_290), "imperialOnly": new TeamRestriction(Team.IMPERIAL), "jumpMaster5000Only": new ShipRestriction(Ship.JUMPMASTER_5000), "lambdaClassShuttleOnly": new ShipRestriction(Ship.LAMBDA_CLASS_SHUTTLE), "lancerClassPursuitCraftOnly": new ShipRestriction(Ship.LANCER_CLASS_PURSUIT_CRAFT), "largeShipOnly": new ShipSizeRestriction(ShipBase.LARGE), "limited": { name: "Limited.", passes: function(pilotKey) { // FIXME: implement Limited.passes() return true; } }, "m3AInterceptorOnly": new ShipRestriction(Ship.M3_A_INTERCEPTOR), "pilotSkillAbove1": new PilotSkillRestriction(1), "pilotSkillAbove2": new PilotSkillRestriction(2), "pilotSkillAbove3": new PilotSkillRestriction(3), "pilotSkillAbove4": new PilotSkillRestriction(4), "protectorateStarfighterOnly": new ShipRestriction(Ship.PROTECTORATE_STARFIGHTER), "raiderClassCorvetteAftSectionOnly": new ShipRestriction("raiderClassCorvette.aft"), "rebelAndScumOnly": { name: "Rebel and Scum only.", passes: function(pilotKey) { var pilot = Pilot.properties[pilotKey]; var teamKey = pilot.shipTeam.teamKey; return teamKey === Team.REBEL || teamKey === Team.SCUM; } }, "rebelOnly": new TeamRestriction(Team.REBEL), "scumOnly": new TeamRestriction(Team.SCUM), "smallShipOnly": new ShipSizeRestriction(ShipBase.SMALL), "starViperOnly": new ShipRestriction(Ship.STAR_VIPER), "t70XWingOnly": new ShipRestriction(Ship.T_70_X_WING), "tieAdvancedOnly": new ShipRestriction(Ship.TIE_ADVANCED), "tieAdvancedPrototypeOnly": new ShipRestriction(Ship.TIE_ADVANCED_PROTOTYPE), "tieBomberOnly": new ShipRestriction(Ship.TIE_BOMBER), "tieDefenderOnly": new ShipRestriction(Ship.TIE_DEFENDER), "tieInterceptorOnly": new ShipRestriction(Ship.TIE_INTERCEPTOR), "tieOnly": { name: "TIE only.", passes: function(pilotKey) { var pilot = Pilot.properties[pilotKey]; var shipKey = pilot.shipTeam.shipKey; return Ship.properties[shipKey].name.startsWith("TIE"); } }, "tiePhantomOnly": new ShipRestriction(Ship.TIE_PHANTOM), "tieSfOnly": new ShipRestriction(Ship.TIE_SF_FIGHTER), "uWingOnly": new ShipRestriction(Ship.U_WING), "upsilonClassShuttleOnly": new ShipRestriction(Ship.UPSILON_CLASS_SHUTTLE), "vcx100Only": new ShipRestriction(Ship.VCX_100), "vt49DecimatorOnly": new ShipRestriction(Ship.VT_49_DECIMATOR), "xWingOnly": { name: "X-Wing only.", passes: function(pilotKey) { var pilot = Pilot.properties[pilotKey]; var shipKey = pilot.shipTeam.shipKey; return shipKey === Ship.X_WING || shipKey === Ship.T_70_X_WING; } }, "yt1300AndYt2400Only": { name: "YT-1300 and YT-2400 only.", passes: function(pilotKey) { var pilot = Pilot.properties[pilotKey]; var shipKey = pilot.shipTeam.shipKey; return shipKey === Ship.YT_1300 || shipKey === Ship.YT_2400; } }, "yt1300Only": new ShipRestriction(Ship.YT_1300), "yt2400Only": new ShipRestriction(Ship.YT_2400), "yWingOnly": new ShipRestriction(Ship.Y_WING), "yv666Only": new ShipRestriction(Ship.YV_666), }, passes: function(restrictionKeys, pilotKey) { InputValidator.validateNotNull("pilotKey", pilotKey); var answer = true; if (restrictionKeys !== undefined) { answer = restrictionKeys.reduce(function(previousValue, restrictionKey) { if (!UpgradeRestriction.properties[restrictionKey]) { throw "Can't find properties for restrictionKey: " + restrictionKey; } return previousValue && UpgradeRestriction.properties[restrictionKey].passes(pilotKey); }, true); } return answer; }, values: function() { return Object.getOwnPropertyNames(UpgradeRestriction.properties); }, }; if (Object.freeze) { Object.freeze(UpgradeRestriction); } return UpgradeRestriction; });
// All material copyright ESRI, All Rights Reserved, unless otherwise specified. // See https://js.arcgis.com/4.16/esri/copyright.txt for details. //>>built define({"esri/widgets/Search/nls/Search":{widgetLabel:"\u0391\u03bd\u03b1\u03b6\u03ae\u03c4\u03b7\u03c3\u03b7",searchButtonTitle:"\u0391\u03bd\u03b1\u03b6\u03ae\u03c4\u03b7\u03c3\u03b7",clearButtonTitle:"\u0395\u03ba\u03ba\u03b1\u03b8\u03ac\u03c1\u03b9\u03c3\u03b7 \u03b1\u03bd\u03b1\u03b6\u03ae\u03c4\u03b7\u03c3\u03b7\u03c2",placeholder:"\u0391\u03bd\u03b1\u03b6\u03ae\u03c4\u03b7\u03c3\u03b7 \u03b4\u03b9\u03b5\u03cd\u03b8\u03c5\u03bd\u03c3\u03b7\u03c2 \u03ae \u03bc\u03ad\u03c1\u03bf\u03c5\u03c2", searchIn:"\u0391\u03bd\u03b1\u03b6\u03ae\u03c4\u03b7\u03c3\u03b7 \u03c3\u03b5",all:"\u038c\u03bb\u03b5\u03c2",allPlaceholder:"\u0391\u03bd\u03b1\u03b6\u03ae\u03c4\u03b7\u03c3\u03b7 \u03b4\u03b9\u03b5\u03cd\u03b8\u03c5\u03bd\u03c3\u03b7\u03c2 \u03ae \u03bc\u03ad\u03c1\u03bf\u03c5\u03c2",emptyValue:"\u0395\u03b9\u03c3\u03b1\u03b3\u03ac\u03b3\u03b5\u03c4\u03b5 \u03cc\u03c1\u03bf \u03b1\u03bd\u03b1\u03b6\u03ae\u03c4\u03b7\u03c3\u03b7\u03c2.",untitledResult:"\u03a7\u03c9\u03c1\u03af\u03c2 \u03c4\u03af\u03c4\u03bb\u03bf", untitledSource:"\u0391\u03bd\u03ce\u03bd\u03c5\u03bc\u03b7 \u03c0\u03c1\u03bf\u03ad\u03bb\u03b5\u03c5\u03c3\u03b7",noResults:"\u039a\u03b1\u03bd\u03ad\u03bd\u03b1 \u03b1\u03c0\u03bf\u03c4\u03ad\u03bb\u03b5\u03c3\u03bc\u03b1",noResultsFound:"\u0394\u03b5\u03bd \u03b2\u03c1\u03ad\u03b8\u03b7\u03ba\u03b1\u03bd \u03b1\u03c0\u03bf\u03c4\u03b5\u03bb\u03ad\u03c3\u03bc\u03b1\u03c4\u03b1.",noResultsFoundForValue:"\u0394\u03b5\u03bd \u03b2\u03c1\u03ad\u03b8\u03b7\u03ba\u03b1\u03bd \u03b1\u03c0\u03bf\u03c4\u03b5\u03bb\u03ad\u03c3\u03bc\u03b1\u03c4\u03b1 \u03b3\u03b9\u03b1 {value}.", showMoreResults:"\u0395\u03bc\u03c6\u03ac\u03bd\u03b9\u03c3\u03b7 \u03c0\u03b5\u03c1\u03b9\u03c3\u03c3\u03cc\u03c4\u03b5\u03c1\u03c9\u03bd \u03b1\u03c0\u03bf\u03c4\u03b5\u03bb\u03b5\u03c3\u03bc\u03ac\u03c4\u03c9\u03bd",hideMoreResults:"\u0391\u03c0\u03cc\u03ba\u03c1\u03c5\u03c8\u03b7",searchResult:"\u0391\u03bd\u03b1\u03b6\u03ae\u03c4\u03b7\u03c3\u03b7 \u03b1\u03c0\u03bf\u03c4\u03b5\u03bb\u03ad\u03c3\u03bc\u03b1\u03c4\u03bf\u03c2",moreResultsHeader:"\u03a0\u03b5\u03c1\u03b9\u03c3\u03c3\u03cc\u03c4\u03b5\u03c1\u03b1 \u03b1\u03c0\u03bf\u03c4\u03b5\u03bb\u03ad\u03c3\u03bc\u03b1\u03c4\u03b1", useCurrentLocation:"\u03a7\u03c1\u03ae\u03c3\u03b7 \u03c4\u03c1\u03ad\u03c7\u03bf\u03c5\u03c3\u03b1\u03c2 \u03c4\u03bf\u03c0\u03bf\u03b8\u03b5\u03c3\u03af\u03b1\u03c2",_localized:{}},"esri/widgets/Attribution/nls/Attribution":{widgetLabel:"\u0391\u03c0\u03cc\u03b4\u03bf\u03c3\u03b7",_localized:{}},"esri/widgets/Compass/nls/Compass":{widgetLabel:"\u03a0\u03c5\u03be\u03af\u03b4\u03b1",reset:"\u0395\u03c0\u03b1\u03bd\u03b1\u03c6\u03bf\u03c1\u03ac \u03c0\u03c1\u03bf\u03c3\u03b1\u03bd\u03b1\u03c4\u03bf\u03bb\u03b9\u03c3\u03bc\u03bf\u03cd \u03c0\u03c5\u03be\u03af\u03b4\u03b1\u03c2", _localized:{}},"esri/widgets/NavigationToggle/nls/NavigationToggle":{widgetLabel:"\u0395\u03bd\u03b1\u03bb\u03bb\u03b1\u03b3\u03ae \u03c0\u03bb\u03bf\u03ae\u03b3\u03b7\u03c3\u03b7\u03c2",toggle:"\u0395\u03bd\u03b1\u03bb\u03bb\u03b1\u03b3\u03ae \u03c3\u03b5 \u03ba\u03b1\u03c4\u03ac\u03c3\u03c4\u03b1\u03c3\u03b7 \u03bc\u03b5\u03c4\u03b1\u03c4\u03cc\u03c0\u03b9\u03c3\u03b7\u03c2 \u03ae 3D \u03c0\u03b5\u03c1\u03b9\u03c3\u03c4\u03c1\u03bf\u03c6\u03ae\u03c2",_localized:{}},"esri/widgets/Zoom/nls/Zoom":{widgetLabel:"\u0395\u03c3\u03c4\u03af\u03b1\u03c3\u03b7", zoomIn:"\u039c\u03b5\u03b3\u03ad\u03b8\u03c5\u03bd\u03c3\u03b7",zoomOut:"\u03a3\u03bc\u03af\u03ba\u03c1\u03c5\u03bd\u03c3\u03b7",_localized:{}}});
(function($){ $(function(){ var BIN_TOTAL = 128; //HEX_TOTAL = BIN_TOTAL/4, //CHAR_ASCII_START = 64; var $mask = $('#mask'), $range = $('.range'), $ip = $('input[name=ip]'); var $minIp = $('.subnet-min'), $maxIp = $('.subnet-max'); var binToHex = function (bin) { var hex = ''; var binArr = bin.match(/\w{1,4}/g); for( var i=0; i<binArr.length; i++ ) { hex += parseInt(binArr[i], 2).toString(16).toUpperCase(); } return hex; }; var hexToBin = function (hex) { var bin = ''; for(var i=0; i<hex.length; i++){ var b = parseInt(hex[i], 16).toString(2) bin += completeChar(4-b.length, '0') + b; } return bin; }; /* var getConcatBin = function (mask) { var charIndex = keyHexIndex(mask), concatBinNum = mask%4; var concatHex = ip.charAt(charIndex); return hexToBin(concatHex).substr(0, concatBinNum); }; var keyHexIndex = function(mask) { return Math.floor(mask/4); }; var calKeyHex = function( mask, theBin ) { var bin = getConcatBin(mask); return binToHex(bin); }; */ /* var buildIP = function(mask) { var keyIndex = keyHexIndex(mask); var newIpStart = ip.substr(0, keyIndex), placeholderNum = HEX_TOTAL - keyIndex - 1; var minIp = newIpStart + calKeyHex(mask, 0), maxIp = newIpStart + calKeyHex(mask, 1); //var newMinIp = [], newMaxIp = []; minIp += completeChar(placeholderNum, '0'); maxIp += completeChar(placeholderNum, 'F'); for(var i=0; i<HEX_TOTAL/4; i++) { newMinIp.push( minIp.substr(4*i, 4) ); newMaxIp.push( maxIp.substr(4*i, 4) ); } $minIp.text(minIp.split(/\w[4]/).join(':')); $maxIp.text(maxIp.split(/\w[4]/).join(':')); }; var ip = '', getIp = function() { $ip.each(function(){ var inputHex = $(this).val().toUpperCase(); var inputLengthLack = 4 - inputHex.length; ip += completeChar(inputLengthLack, '0') + inputHex; }); }; */ var getRange = function() { var ip = ''; var mask = $mask.val(); var minIp = '', maxIp = '', baseIp = ''; // Get the input IP $ip.each(function(){ var inputHex = $(this).val(); var inputLengthLack = 4 - inputHex.length; ip += completeChar(inputLengthLack, '0') + inputHex; }); // Get the IP baseIp = hexToBin(ip).substr(0, mask); minIp = buildIp(baseIp, '0'); maxIp = buildIp(baseIp, '1'); // Insert the range $minIp.text(minIp); $maxIp.text(maxIp); }; var completeChar = function( num, character ) { return new Array(num+1).join(character); }; var buildIp = function(binaryBaseIp, char) { var completeNum = BIN_TOTAL - binaryBaseIp.length; var binaryIp = binaryBaseIp + completeChar(completeNum, char); var hexIp = binToHex( binaryIp ); return hexIp.match(/\w{4}/g).join(':'); }; // Init mask slider $range.slider({ min: 0, max: BIN_TOTAL, range: 'min', // value: $mask.val(), slide: function (e, ui) { $mask.val(ui.value); $mask.change(); } }); $mask.on('keyup, change',function() { $range.slider('value', $(this).val()); getRange(); }); // Init input $ip.keyup(getRange); getRange(); }); }(jQuery));
/** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Academic Free License (AFL 3.0) * that is bundled with this package in the file LICENSE_AFL.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/afl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magento.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magento.com for more information. * * @category Mage * @package js * @copyright Copyright (c) 2006-2019 Magento, Inc. (http://www.magento.com) * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0) */ (function(){ var eDefer = Function.prototype.defer; Function.prototype.defer = function() { var argLen = arguments.length; if (argLen==0 || (argLen==1 && arguments[0]==1)) { //common for Prototype Ajax requests return this.delay.curry(0.01).apply(this, arguments); } return eDefer.apply(this, arguments); } })();
import parseToRgb from '../parseToRgb' describe('parseToRgb', () => { it('should parse a hex color representation', () => { expect(parseToRgb('#Ff43AE')).toEqual({ blue: 174, green: 67, red: 255, }) }) it('should parse an 8-digit hex color representation', () => { expect(parseToRgb('#Ff43AEFF')).toEqual({ alpha: 1, blue: 174, green: 67, red: 255, }) }) it('should parse an 4-digit hex color representation', () => { expect(parseToRgb('#0f08')).toEqual({ alpha: 0.53, blue: 0, green: 255, red: 0, }) }) it('should parse a reduced hex color representation', () => { expect(parseToRgb('#45a')).toEqual({ blue: 170, green: 85, red: 68, }) }) it('should parse a rgba color representation', () => { expect(parseToRgb('rgba(174,67,255,0.6)')).toEqual({ alpha: 0.6, blue: 255, green: 67, red: 174, }) expect(parseToRgb('rgba( 174 , 67 , 255 , 0.6 )')).toEqual({ alpha: 0.6, blue: 255, green: 67, red: 174, }) }) it('should parse a rgb color representation', () => { expect(parseToRgb('rgb(174,67,255)')).toEqual({ blue: 255, green: 67, red: 174, }) expect(parseToRgb('rgb( 174 , 67 , 255 )')).toEqual({ blue: 255, green: 67, red: 174, }) }) it('should parse a hsl color representation', () => { expect(parseToRgb('hsl(210,10%,4%)')).toEqual({ blue: 11, green: 10, red: 9, }) expect(parseToRgb('hsl( 210 , 10% , 4% )')).toEqual({ blue: 11, green: 10, red: 9, }) }) it('should parse a hsl color representation with decimal values', () => { expect(parseToRgb('hsl(210,16.4%,13.2%)')).toEqual({ blue: 38, green: 33, red: 28, }) expect(parseToRgb('hsl( 210 , 16.4%, 13.2% )')).toEqual({ blue: 38, green: 33, red: 28, }) }) it('should parse a hsla color representation', () => { expect(parseToRgb('hsla(210,10%,40%,0.75)')).toEqual({ alpha: 0.75, blue: 112, green: 102, red: 92, }) expect(parseToRgb('hsla( 210 , 10% , 40% , 0.75 )')).toEqual({ alpha: 0.75, blue: 112, green: 102, red: 92, }) }) it('should parse a hsla color representation with decimal values', () => { expect(parseToRgb('hsla(210,0.5%,0.5%,1.0)')).toEqual({ alpha: 1, blue: 0, green: 0, red: 0, }) expect(parseToRgb('hsla( 210 , 0.5% , 0.5% , 1.0 )')).toEqual({ alpha: 1, blue: 0, green: 0, red: 0, }) }) it('should throw an error if an invalid color string is provided', () => { expect(() => { parseToRgb('(174,67,255)') }).toThrow( "Couldn't parse the color string. Please provide the color as a string in hex, rgb, rgba, hsl or hsla notation.", ) }) it('should throw an error if an invalid color string is provided', () => { expect(() => { parseToRgb(12345) }).toThrow( 'Passed an incorrect argument to a color function, please pass a string representation of a color.', ) }) it('should throw an error if an invalid hsl string is provided', () => { expect(() => { parseToRgb('hsl(210,120%,4%)') }).toThrow( `Couldn't generate valid rgb string from ${'hsl(210,120%,4%)'}, it returned ${'rgb(-2,10,22)'}.`, ) }) it('should throw an error if an unparsable hsla string is provided', () => { expect(() => { parseToRgb('hsla(210,120%,4%,0.7)') }).toThrow( `Couldn't generate valid rgb string from ${'hsla(210,120%,4%,0.7)'}, it returned ${'rgb(-2,10,22)'}.`, ) }) })
function analogize(exposure,gamma,glow,radius) { gl.analogize = gl.analogize || new Shader(null,'\ \ uniform sampler2D texture;\ uniform sampler2D glow_texture;\ varying vec2 texCoord;\ uniform float Glow; \ uniform float Exposure;\ uniform float Gamma;\ void main(void){\ vec3 color = texture2D(glow_texture,vec2(texCoord)).rgb*Glow;\ color += texture2D(texture,texCoord).rgb;\ color=1.0-exp(-Exposure*color);\ color=pow(color, vec3(Gamma,Gamma,Gamma));\ gl_FragColor.rgb = color;\ gl_FragColor.a = 1.0;\ } \ '); // Store a copy of the current texture in the second texture unit this._.extraTexture.ensureFormat(this._.texture); this._.texture.use(); this._.extraTexture.drawTo(function() { Shader.getDefaultShader().drawRect(); }); // Blur the current texture, then use the stored texture to detect edges this._.extraTexture.use(1); this.fastBlur(radius); gl.analogize.textures({ glow_texture: 0, texture: 1 }); simpleShader.call(this, gl.analogize, { Glow: glow, Exposure: exposure, Gamma: gamma }); this._.extraTexture.unuse(1); return this; }
var Gpio = require('onoff').Gpio; var led = new Gpio(17, 'out'); function exit() { led.unexport(); process.exit(); } led.writeSync(0); process.on('SIGINT', exit);
/*! * micromatch <https://github.com/jonschlinkert/micromatch> * * Copyright (c) 2014-2015, Jon Schlinkert. * Licensed under the MIT License. */ 'use strict'; var utils = require('./utils'); var Glob = require('./glob'); /** * Expose `expand` */ module.exports = expand; /** * Expand a glob pattern to resolve braces and * similar patterns before converting to regex. * * @param {String|Array} `pattern` * @param {Array} `files` * @param {Options} `opts` * @return {Array} */ function expand(pattern, options) { if (typeof pattern !== 'string') { throw new TypeError('micromatch.expand(): argument should be a string.'); } var glob = new Glob(pattern, options || {}); var opts = glob.options; // return early if glob pattern matches special patterns if (specialCase(pattern) && opts.safemode) { return new RegExp(utils.escapeRe(pattern), 'g'); } if (opts.nonegate !== true) { opts.negated = glob.negated; } glob._replace('/.', '/\\.'); // parse the glob pattern into tokens glob.parse(); var tok = glob.tokens; tok.is.negated = opts.negated; if (tok.is.dotfile) { glob.options.dot = true; opts.dot = true; } if (!tok.is.glob) { return { pattern: utils.escapePath(glob.pattern), tokens: tok, options: opts }; } // see if it might be a dotfile pattern if (/[{,]\./.test(glob.pattern)) { opts.makeRe = false; opts.dot = true; } // expand braces, e.g `{1..5}` glob.track('before brackets'); if (tok.is.brackets) { glob.brackets(); } glob.track('before braces'); if (tok.is.braces) { glob.braces(); } glob.track('after braces'); glob._replace('[]', '\\[\\]'); glob._replace('(?', '__QMARK_GROUP__'); // windows drives glob._replace(/^(\w):([\\\/]+?)/gi, lookahead + '$1:$2', true); // negate slashes in exclusion ranges if (glob.pattern.indexOf('[^') !== -1) { glob.pattern = negateSlash(glob.pattern); } if (glob.pattern === '**' && opts.globstar !== false) { glob.pattern = globstar(opts); } else { if (/^\*\.\w*$/.test(glob.pattern)) { glob._replace('*', star(opts.dot) + '\\'); glob._replace('__QMARK_GROUP__', '(?'); return glob; } // '/*/*/*' => '(?:/*){3}' glob._replace(/(\/\*)+/g, function (match) { var len = match.length / 2; if (len === 1) { return match; } return '(?:\\/*){' + len + '}'; }); glob.pattern = balance(glob.pattern, '[', ']'); glob.escape(glob.pattern); // if the glob is for one directory deep, we can // simplify the parsing and generated regex if (tok.path.dirname === '' && !tok.is.globstar) { glob.track('before expand filename'); return expandFilename(glob, opts); } // if the pattern has `**` if (tok.is.globstar) { glob._replace(/\*{2,}/g, '**'); glob.pattern = collapse(glob.pattern, '/**'); glob.pattern = optionalGlobstar(glob.pattern); // reduce extraneous globstars glob._replace(/(^|[^\\])\*{2,}([^\\]|$)/g, '$1**$2'); // 'foo/*' glob._replace(/(\w+)\*(?!\/)/g, '(?=.)$1[^/]*?', true); glob._replace('**', globstar(opts), true); } // ends with /* glob._replace(/\/\*$/, '\\/' + stardot(opts), true); // ends with *, no slashes glob._replace(/(?!\/)\*$/, boxQ, true); // has '*' glob._replace('*', stardot(opts), true); glob._replace('?.', '?\\.', true); glob._replace('?:', '?:', true); glob._replace(/\?+/g, function (match) { var len = match.length; if (len === 1) { return box; } return box + '{' + len + '}'; }); // escape '.abc' => '\\.abc' glob._replace(/\.([*\w]+)/g, '\\.$1'); // fix '[^\\\\/]' glob._replace(/\[\^[\\\/]+\]/g, box); // '///' => '\/' glob._replace(/\/+/g, '\\/'); // '\\\\\\' => '\\' glob._replace(/\\{2,}/g, '\\'); } glob._replace('__QMARK_GROUP__', '(?'); glob.unescape(glob.pattern); glob._replace('__UNESC_STAR__', '*'); glob._replace('%~', '?'); glob._replace('%%', '*'); glob._replace('?.', '?\\.'); glob._replace('[^\\/]', '[^/]'); return glob; } /** * Expand the filename part of the glob into a regex * compatible string * * @param {String} glob * @param {Object} tok Tokens * @param {Options} opts * @return {Object} */ function expandFilename(glob, opts) { var tok = glob.tokens; switch (glob.pattern) { case '.': glob.pattern = '\\.'; break; case '.*': glob.pattern = '\\..*'; break; case '*.*': glob.pattern = star(opts.dot) + '\\.[^/]*?'; break; case '*': glob.pattern = star(opts.dot); break; default: if (tok.path.filename === '*' && !tok.path.dirname) { glob.pattern = star(opts.dot) + '\\' + glob.pattern.slice(1); } else { glob._replace(/(?!\()\?/g, '[^/]'); if (tok.path.basename.charAt(0) !== '.') { opts.dot = true; } glob._replace('*', star(opts.dot)); } } if (glob.pattern.charAt(0) === '.') { glob.pattern = '\\' + glob.pattern; } glob._replace('__QMARK_GROUP__', '(?'); glob.unescape(glob.pattern); glob._replace('__UNESC_STAR__', '*'); return glob; } /** * Special cases */ function specialCase(glob) { if (glob === '\\') { return true; } return false; } /** * Collapse repeated character sequences. * * ```js * collapse('a/../../../b', '../'); * //=> 'a/../b' * ``` * * @param {String} `str` * @param {String} `ch` * @return {String} */ function collapse(str, ch, repeat) { var res = str.split(ch); var len = res.length; var isFirst = res[0] === ''; var isLast = res[res.length - 1] === ''; res = res.filter(Boolean); if (isFirst) { res.unshift(''); } if (isLast) { res.push(''); } var diff = len - res.length; if (repeat && diff >= 1) { ch = '(?:' + ch + '){' + (diff + 1) + '}'; } return res.join(ch); } /** * Make globstars optional, as in glob spec: * * ```js * optionalGlobstar('a\/**\/b'); * //=> '(?:a\/b|a\/**\/b)' * ``` * * @param {String} `str` * @return {String} */ function optionalGlobstar(glob) { // globstars preceded and followed by a word character if (/[^\/]\/\*\*\/[^\/]/.test(glob)) { var tmp = glob.split('/**/').join('/'); glob = '(?:' + tmp + '|' + glob + ')'; // leading globstars } else if (/^\*\*\/[^\/]/.test(glob)) { glob = glob.split(/^\*\*\//).join('(^|.+\\/)'); } return glob; } /** * Negate slashes in exclusion ranges, per glob spec: * * ```js * negateSlash('[^foo]'); * //=> '[^\\/foo]' * ``` * * @param {[type]} str [description] * @return {[type]} */ function negateSlash(str) { var re = /\[\^([^\]]*?)\]/g; return str.replace(re, function (match, inner) { if (inner.indexOf('/') === -1) { inner = '\\/' + inner; } return '[^' + inner + ']'; }); } /** * Escape imbalanced braces/bracket */ function balance(str, a, b) { var aarr = str.split(a); var alen = aarr.join('').length; var blen = str.split(b).join('').length; if (alen !== blen) { str = aarr.join('\\' + a); return str.split(b).join('\\' + b); } return str; } /** * Escape utils */ function esc(str) { str = str.split('?').join('%~'); str = str.split('*').join('%%'); return str; } /** * Special patterns to be converted to regex. * Heuristics are used to simplify patterns * and speed up processing. */ var box = '[^/]'; var boxQ = '[^/]*?'; var lookahead = '(?=.)'; var nodot = '(?!\\.)(?=.)'; var ex = {}; ex.dotfileGlob = '(?:^|\\/)(?:\\.{1,2})(?:$|\\/)'; ex.stardot = '(?!' + ex.dotfileGlob + ')(?=.)[^/]*?'; ex.twoStarDot = '(?:(?!' + ex.dotfileGlob + ').)*?'; /** * Create a regex for `*`. If `dot` is true, * or the pattern does not begin with a leading * star, then return the simple regex. */ function star(dotfile) { return dotfile ? boxQ : nodot + boxQ; } function dotstarbase(dotfile) { var re = dotfile ? ex.dotfileGlob : '\\.'; return '(?!' + re + ')' + lookahead; } function globstar(opts) { if (opts.dot) { return ex.twoStarDot; } return '(?:(?!(?:^|\\/)\\.).)*?'; } function stardot(opts) { return dotstarbase(opts && opts.dot) + '[^/]*?'; }
var Colors = require("../util/Colors"); var objects = ["path", "cubes", "mountains", "background"]; var controls, _socket, _peer; var selectedObject = 0; var defaults = [10,10,15,25]; function MobileColorSelecter (socket, peer) { _socket = socket; _peer = peer; controls = createControls(Colors.presets); $("#container").append(controls); var objectNodes = $(".color-swiper"); for (var i = 0; i < objectNodes.length; i++) { $(objectNodes[i]).scrollTop(160 * defaults[i]); } $(".selecter").swipe( {swipe: swipeObject, threshold:0}); $(".color-swiper").swipe( {swipe: swipeColor, threshold:0}); } function swipeObject(event, direction, distance, duration, fingerCount, fingerData){ var object = event.target; var parent = $(object).parent().parent(); var currentPos = parent.scrollTop(); var destination = currentPos; switch(direction){ case "up": destination = currentPos + 161; break; case "down": destination = currentPos - 161; break; } if(destination > (defaults.length-1) * 161){ destination = (defaults.length-1) * 161; } parent.stop().animate({scrollTop: destination}, 200, function(){ currentPos = parent.scrollTop(); var index = Math.floor(currentPos/161); selectedObject = index; }); } function swipeColor(event, direction, distance, duration, fingerCount, fingerData){ var object = event.target; var parent = $(object).parent(); var currentPos = parent.scrollTop(); var destination = currentPos; switch(direction){ case "up": destination = currentPos + 160; break; case "down": destination = currentPos - 160; break; } if(destination > (Colors.presets.length-1) * 160){ parent.scrollTop(0); destination = 0; } if(destination < 0){ parent.scrollTop((Colors.presets.length-1) * 160); destination = (Colors.presets.length-1) * 160; } parent.stop().animate({scrollTop: destination}, 200, function(){ currentPos = parent.scrollTop(); var index = Math.floor(currentPos/160); _socket.emit("color_change", {ontvanger: _peer, change: {object: selectedObject, value: index}}); }); } function createControls(colors){ var prefix = '<div id="mobile-controls"><div id="object-swiper">'; var objectOptions = ''; for (var i = 0; i < objects.length; i++) { objectOptions += '<div class="object-option" val="'+objects[i]+'"><div class="selecter"><p>'+objects[i]+'</p></div><div class="color-swiper">'; for (var j = 0; j < colors.length; j++) { objectOptions += '<div class="color-option" val="'+j+'" style="background-color: '+colors[j]+'">&nbsp;</div>'; } objectOptions += '</div></div>'; } var suffix = '</div></div>'; return $.parseHTML(prefix + objectOptions + suffix); } module.exports = MobileColorSelecter;
var DirectiveContainer = (function(container) { container = container || document.body; var nextInstanceID = 0; var lookup = {}; var instances = {}; var events = {}; var watchers = []; function watchPulse(fn) { watchers.push(fn); return function deregister() { var index = watchers[fn]; watchers.splice(index, 1); }; } function watchFlush() { forEach(watchers, function(watch) { watch(); }); } function directiveBodyTemplate(element) { var propertyCache = {}; return { $events : {}, $watchers : [], on : function(event, fn) { events[event] = events[event] || []; events[event].push(this); this.$events[event] = this.$events[event] || []; this.$events[event].push(fn); }, observe : function(prop, fn) { var deregister = watchPulse(function() { var oldValue = propertyCache[prop]; var newValue = element.getAttribute(prop); if (oldValue !== newValue) { propertyCache[prop] = newValue; fn(newValue, oldValue); } }); this.$watchers.push(deregister); }, destroy : function() { forEach(this.$watchers, function(fn) { fn(); }); triggerOnFn(this, 'destroy'); } }; } function triggerOnFn(instance, event, data) { var listeners = instance.$events[event] || []; forEach(listeners, function(fn) { fn(data); }); } var self; return self = { register : function(selector, bodyFn) { lookup[selector] = lookup[selector] || []; lookup[selector].push(bodyFn); }, list : function() { var result = []; forEach(lookup, function(fns, selector) { forEach(fns, function(bodyFn) { result.push([selector, bodyFn]); }); }); return result; }, scan : function(innerContainer, filterFn) { var innerContainer = innerContainer || container; filterFn = filterFn || function(val) { return true; }; var entries = []; forEach(lookup, function(fns, selector) { forEach(innerContainer.querySelectorAll(selector), function(element) { if (filterFn(element)) { forEach(fns, function(bodyFn) { entries.push([element, bodyFn]); }); } }); }); return entries; }, compile : function(innerContainer) { forEach(self.scan(innerContainer, rejectIfMarkedFn), function(entry) { var element = entry[0]; var bodyFn = entry[1]; var instance = directiveBodyTemplate(element); var instanceID = (nextInstanceID++) + ''; bodyFn.call(instance, element, compileAttrs(element)); instances[instanceID] = instance; markElement(element, instanceID); }); self.checkObservers(); function rejectIfMarkedFn(element) { return !isElementMarked(element); } }, decompile : function(innerContainer) { forEach(self.scan(innerContainer, isElementMarked), function(entry) { var element = entry[0]; var instanceID = element.getAttribute(DIRECTIVE_MARK_KEY); var instance = instances[instanceID]; instance.destroy(); delete instances[instanceID]; markElement(element, undefined); }); }, update : function(newContent) { var replacementContainer = container; if (arguments.length == 2) { replacementContainer = container.querySelector(arguments[0]); newContent = arguments[1]; } self.decompile(replacementContainer); self.trigger(container, 'update'); if (typeof newContent == 'string') { replacementContainer.innerHTML = newContent; } else { replacementContainer.innerHTML = ''; replacementContainer.appendChild(newContent); } self.compile(replacementContainer); }, trigger : function(event, data) { forEach(events[event] || [], function(instance) { triggerOnFn(instance, event, data); }); }, attr : function(element, attr, value) { element.setAttribute(attr, value); self.checkObservers(); }, checkObservers : function() { watchFlush(); } } });
var apiKey = 'AIzaSyBIQzcxjrs9f-jv4iMB8-pGZatxqgRrcz4'; var gapiAuthInfo = { client_id: '1020312901975-rqme2cmcjidsv6cq93o7fo8npqm617v7.apps.googleusercontent.com', scope: 'https://www.googleapis.com/auth/gmail.modify', immediate: false } function gapiAuth() { console.log('Authorizing...'); gapi.auth.authorize(gapiAuthInfo, function(result) { console.log('Authorized, moving on'); var btn = document.getElementById('authorize-button'); if (result && !result.error) { btn.style.visibility = 'hidden'; gapiInitialized(); } else { console.log('auth failed'); btn.style.visibility = ''; btn.onclick = gapiAuth; } }); } function gapiLoaded() { console.log('gapiLoaded'); gapi.client.setApiKey(apiKey); // TODO: Add API key here } function gapiInitialized() { console.log('gapiInitialized'); // TODO: Change to Gmail API gapi.client.load('gmail', 'v1').then(function() { console.log('fetching threads'); var request = gapi.client.gmail.users.threads.list({'userId': 'me'}); request.execute(function(response) { console.log('fetched about ' + response.resultSizeEstimate + ' threads'); var threads = response.threads; for (var i = 0; i < threads.length; i++) { $("#mailbox").add("li").text(threads[i].snippet) }; }); }); } $("#authorize-button").click(gapiAuth);
'use strict'; var should = require('should'), request = require('supertest'), path = require('path'), mongoose = require('mongoose'), User = mongoose.model('User'), Cierreturno = mongoose.model('Cierreturno'), express = require(path.resolve('./config/lib/express')); /** * Globals */ var app, agent, credentials, user, cierreturno; /** * Cierreturno routes tests */ describe('Cierreturno CRUD tests', function () { before(function (done) { // Get application app = express.init(mongoose); agent = request.agent(app); done(); }); beforeEach(function (done) { // Create user credentials credentials = { username: 'username', password: 'M3@n.jsI$Aw3$0m3' }; // Create a new user user = new User({ firstName: 'Full', lastName: 'Name', displayName: 'Full Name', email: 'test@test.com', username: credentials.username, password: credentials.password, provider: 'local' }); // Save a user to the test db and create new Cierreturno user.save(function () { cierreturno = { name: 'Cierreturno name' }; done(); }); }); it('should be able to save a Cierreturno if logged in', function (done) { agent.post('/api/auth/signin') .send(credentials) .expect(200) .end(function (signinErr, signinRes) { // Handle signin error if (signinErr) { return done(signinErr); } // Get the userId var userId = user.id; // Save a new Cierreturno agent.post('/api/cierreturnos') .send(cierreturno) .expect(200) .end(function (cierreturnoSaveErr, cierreturnoSaveRes) { // Handle Cierreturno save error if (cierreturnoSaveErr) { return done(cierreturnoSaveErr); } // Get a list of Cierreturnos agent.get('/api/cierreturnos') .end(function (cierreturnosGetErr, cierreturnosGetRes) { // Handle Cierreturno save error if (cierreturnosGetErr) { return done(cierreturnosGetErr); } // Get Cierreturnos list var cierreturnos = cierreturnosGetRes.body; // Set assertions (cierreturnos[0].user._id).should.equal(userId); (cierreturnos[0].name).should.match('Cierreturno name'); // Call the assertion callback done(); }); }); }); }); it('should not be able to save an Cierreturno if not logged in', function (done) { agent.post('/api/cierreturnos') .send(cierreturno) .expect(403) .end(function (cierreturnoSaveErr, cierreturnoSaveRes) { // Call the assertion callback done(cierreturnoSaveErr); }); }); it('should not be able to save an Cierreturno if no name is provided', function (done) { // Invalidate name field cierreturno.name = ''; agent.post('/api/auth/signin') .send(credentials) .expect(200) .end(function (signinErr, signinRes) { // Handle signin error if (signinErr) { return done(signinErr); } // Get the userId var userId = user.id; // Save a new Cierreturno agent.post('/api/cierreturnos') .send(cierreturno) .expect(400) .end(function (cierreturnoSaveErr, cierreturnoSaveRes) { // Set message assertion (cierreturnoSaveRes.body.message).should.match('Please fill Cierreturno name'); // Handle Cierreturno save error done(cierreturnoSaveErr); }); }); }); it('should be able to update an Cierreturno if signed in', function (done) { agent.post('/api/auth/signin') .send(credentials) .expect(200) .end(function (signinErr, signinRes) { // Handle signin error if (signinErr) { return done(signinErr); } // Get the userId var userId = user.id; // Save a new Cierreturno agent.post('/api/cierreturnos') .send(cierreturno) .expect(200) .end(function (cierreturnoSaveErr, cierreturnoSaveRes) { // Handle Cierreturno save error if (cierreturnoSaveErr) { return done(cierreturnoSaveErr); } // Update Cierreturno name cierreturno.name = 'WHY YOU GOTTA BE SO MEAN?'; // Update an existing Cierreturno agent.put('/api/cierreturnos/' + cierreturnoSaveRes.body._id) .send(cierreturno) .expect(200) .end(function (cierreturnoUpdateErr, cierreturnoUpdateRes) { // Handle Cierreturno update error if (cierreturnoUpdateErr) { return done(cierreturnoUpdateErr); } // Set assertions (cierreturnoUpdateRes.body._id).should.equal(cierreturnoSaveRes.body._id); (cierreturnoUpdateRes.body.name).should.match('WHY YOU GOTTA BE SO MEAN?'); // Call the assertion callback done(); }); }); }); }); it('should be able to get a list of Cierreturnos if not signed in', function (done) { // Create new Cierreturno model instance var cierreturnoObj = new Cierreturno(cierreturno); // Save the cierreturno cierreturnoObj.save(function () { // Request Cierreturnos request(app).get('/api/cierreturnos') .end(function (req, res) { // Set assertion res.body.should.be.instanceof(Array).and.have.lengthOf(1); // Call the assertion callback done(); }); }); }); it('should be able to get a single Cierreturno if not signed in', function (done) { // Create new Cierreturno model instance var cierreturnoObj = new Cierreturno(cierreturno); // Save the Cierreturno cierreturnoObj.save(function () { request(app).get('/api/cierreturnos/' + cierreturnoObj._id) .end(function (req, res) { // Set assertion res.body.should.be.instanceof(Object).and.have.property('name', cierreturno.name); // Call the assertion callback done(); }); }); }); it('should return proper error for single Cierreturno with an invalid Id, if not signed in', function (done) { // test is not a valid mongoose Id request(app).get('/api/cierreturnos/test') .end(function (req, res) { // Set assertion res.body.should.be.instanceof(Object).and.have.property('message', 'Cierreturno is invalid'); // Call the assertion callback done(); }); }); it('should return proper error for single Cierreturno which doesnt exist, if not signed in', function (done) { // This is a valid mongoose Id but a non-existent Cierreturno request(app).get('/api/cierreturnos/559e9cd815f80b4c256a8f41') .end(function (req, res) { // Set assertion res.body.should.be.instanceof(Object).and.have.property('message', 'No Cierreturno with that identifier has been found'); // Call the assertion callback done(); }); }); it('should be able to delete an Cierreturno if signed in', function (done) { agent.post('/api/auth/signin') .send(credentials) .expect(200) .end(function (signinErr, signinRes) { // Handle signin error if (signinErr) { return done(signinErr); } // Get the userId var userId = user.id; // Save a new Cierreturno agent.post('/api/cierreturnos') .send(cierreturno) .expect(200) .end(function (cierreturnoSaveErr, cierreturnoSaveRes) { // Handle Cierreturno save error if (cierreturnoSaveErr) { return done(cierreturnoSaveErr); } // Delete an existing Cierreturno agent.delete('/api/cierreturnos/' + cierreturnoSaveRes.body._id) .send(cierreturno) .expect(200) .end(function (cierreturnoDeleteErr, cierreturnoDeleteRes) { // Handle cierreturno error error if (cierreturnoDeleteErr) { return done(cierreturnoDeleteErr); } // Set assertions (cierreturnoDeleteRes.body._id).should.equal(cierreturnoSaveRes.body._id); // Call the assertion callback done(); }); }); }); }); it('should not be able to delete an Cierreturno if not signed in', function (done) { // Set Cierreturno user cierreturno.user = user; // Create new Cierreturno model instance var cierreturnoObj = new Cierreturno(cierreturno); // Save the Cierreturno cierreturnoObj.save(function () { // Try deleting Cierreturno request(app).delete('/api/cierreturnos/' + cierreturnoObj._id) .expect(403) .end(function (cierreturnoDeleteErr, cierreturnoDeleteRes) { // Set message assertion (cierreturnoDeleteRes.body.message).should.match('User is not authorized'); // Handle Cierreturno error error done(cierreturnoDeleteErr); }); }); }); it('should be able to get a single Cierreturno that has an orphaned user reference', function (done) { // Create orphan user creds var _creds = { username: 'orphan', password: 'M3@n.jsI$Aw3$0m3' }; // Create orphan user var _orphan = new User({ firstName: 'Full', lastName: 'Name', displayName: 'Full Name', email: 'orphan@test.com', username: _creds.username, password: _creds.password, provider: 'local' }); _orphan.save(function (err, orphan) { // Handle save error if (err) { return done(err); } agent.post('/api/auth/signin') .send(_creds) .expect(200) .end(function (signinErr, signinRes) { // Handle signin error if (signinErr) { return done(signinErr); } // Get the userId var orphanId = orphan._id; // Save a new Cierreturno agent.post('/api/cierreturnos') .send(cierreturno) .expect(200) .end(function (cierreturnoSaveErr, cierreturnoSaveRes) { // Handle Cierreturno save error if (cierreturnoSaveErr) { return done(cierreturnoSaveErr); } // Set assertions on new Cierreturno (cierreturnoSaveRes.body.name).should.equal(cierreturno.name); should.exist(cierreturnoSaveRes.body.user); should.equal(cierreturnoSaveRes.body.user._id, orphanId); // force the Cierreturno to have an orphaned user reference orphan.remove(function () { // now signin with valid user agent.post('/api/auth/signin') .send(credentials) .expect(200) .end(function (err, res) { // Handle signin error if (err) { return done(err); } // Get the Cierreturno agent.get('/api/cierreturnos/' + cierreturnoSaveRes.body._id) .expect(200) .end(function (cierreturnoInfoErr, cierreturnoInfoRes) { // Handle Cierreturno error if (cierreturnoInfoErr) { return done(cierreturnoInfoErr); } // Set assertions (cierreturnoInfoRes.body._id).should.equal(cierreturnoSaveRes.body._id); (cierreturnoInfoRes.body.name).should.equal(cierreturno.name); should.equal(cierreturnoInfoRes.body.user, undefined); // Call the assertion callback done(); }); }); }); }); }); }); }); afterEach(function (done) { User.remove().exec(function () { Cierreturno.remove().exec(done); }); }); });
import {mutationWithClientMutationId, cursorForObjectInConnection, fromGlobalId} from 'graphql-relay'; import {GraphQLNonNull, GraphQLString, GraphQLInt} from 'graphql'; import {updateUser, getUsers, tmpUser} from '../loaders/UserLoader'; import {userEdge} from '../connection/UserConnection'; import ViewerType from '../types/ViewerType'; import UserType from '../types/UserType'; export default mutationWithClientMutationId({ name: 'UpdateUser', inputFields: { id: { type: new GraphQLNonNull(GraphQLString) }, name: { type: GraphQLString }, address: { type: GraphQLString }, email: { type: GraphQLString }, age: { type: GraphQLInt } }, outputFields: { // userEdge: { // type: userEdge, // resolve: async (obj) => { // const cursorId = cursorForObjectInConnection(await getUsers(obj), obj); // return { node: obj, cursor: cursorId }; // } // }, viewer: { type: ViewerType, resolve: () => tmpUser }, updatedUser: { type: UserType, resolve: async u => await u } }, mutateAndGetPayload: async ({ id: sentId, name, address, email, age }) => new Promise((resolve, reject) => { const { id } = fromGlobalId(sentId); let update = {id}; if(name)update.name = name; if(address)update.address = address; if(email)update.email = email; if(age)update.age = age; updateUser(update).then(updatedUser => { if(updatedUser) resolve(updatedUser); else reject('User not found') }).catch(e => reject(e.errors.map(e => e.path+': '+e.type))); }) });
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, } from 'react-native'; import App from './app' AppRegistry.registerComponent('CustomLibraryPicker', () => App);
/* Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'justify', 'ko', { block: '양쪽 맞춤', center: '가운데 정렬', left: '왼쪽 정렬', right: '오른쪽 정렬' } );
var Utils = require('./utils') var G15 = (1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0) var G15_MASK = (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1) var G15_BCH = Utils.getBCHDigit(G15) /** * Returns format information with relative error correction bits * * The format information is a 15-bit sequence containing 5 data bits, * with 10 error correction bits calculated using the (15, 5) BCH code. * * @param {Number} errorCorrectionLevel Error correction level * @param {Number} mask Mask pattern * @return {Number} Encoded format information bits */ exports.getEncodedBits = function getEncodedBits (errorCorrectionLevel, mask) { var data = ((errorCorrectionLevel.bit << 3) | mask) var d = data << 10 while (Utils.getBCHDigit(d) - G15_BCH >= 0) { d ^= (G15 << (Utils.getBCHDigit(d) - G15_BCH)) } // xor final data with mask pattern in order to ensure that // no combination of Error Correction Level and data mask pattern // will result in an all-zero data string return ((data << 10) | d) ^ G15_MASK }
//The Character window (CSheet). var WeaponSlot : Transform; //This is where the Weapons are going to go (be parented too). In my case it's the "Melee" gameobject. var HelmetSlot : Transform; private var ArmorSlot : Item[]; //This is the built in Array that stores the Items equipped. You can change this to static if you want to access it from another script. var ArmorSlotName : String[]; //This determines how many slots the character has (Head, Legs, Weapon and so on) and the text on each slot. var buttonPositions : Rect[]; //This list will contain where all buttons, equipped or not will be and SHOULD HAVE THE SAME NUMBER OF cells as the ArmorSlot array. var windowSize : Vector2 = Vector2(375,300); //The size of the character window. var useCustomPosition = false; //Do we want to use the customPosition variable to define where on the screen the Character window will appear. var customPosition : Vector2 = Vector2 (70, 70); //The custom position of the Character window. var cSheetSkin : GUISkin; //This is where you can add a custom GUI skin or use the one included (CSheetSkin) under the Resources folder. var canBeDragged = true; //Can the Character window be dragged? var onOffButton : KeyCode = KeyCode.I; //The key to toggle the Character window on and of. var DebugMode = false; //If this is enabled, debug.logs will print out information when something happens (equipping items etc.). static var csheet = false; //Helps with turning the CharacterSheet on and off. private var windowRect = Rect(100,100,200,300); //Keeping track of our character window. //These are keeping track of components such as equipmentEffects and Audio. private var playersinv; //Refers to the Inventory script. private var equipmentEffectIs = false; private var invAudio : InvAudio; private var invDispKeyIsSame = false; @script AddComponentMenu ("Inventory/Character Sheet") @script RequireComponent(Inventory) //Assign the differnet components to variables and other "behind the scenes" stuff. function Awake () { playersinv = GetComponent(Inventory); if (useCustomPosition == false) { windowRect = Rect(Screen.width-windowSize.x-70,Screen.height-windowSize.y-(162.5+70*2),windowSize.x,windowSize.y); } else { windowRect = Rect(customPosition.x,customPosition.y,windowSize.x,windowSize.y); } invAudio = GetComponent(InvAudio); if (GetComponent(InventoryDisplay).onOffButton == onOffButton) { invDispKeyIsSame = true; } } //Take care of the array lengths. function Start () { ArmorSlot = new Item [ArmorSlotName.length]; if (buttonPositions.Length != ArmorSlotName.Length) { Debug.LogError("The variables on the Character script attached to " + transform.name + " are not set up correctly. There needs to be an equal amount of slots on 'ArmorSlotName' and 'buttonPositions'."); } } //Checking if we already have somthing equipped function CheckSlot(tocheck:int) { var toreturn=false; if(ArmorSlot[tocheck]!=null){ toreturn=true; } return toreturn; } //Using the item. If we assign a slot, we already know where to equip it. function UseItem(i:Item,slot:int,autoequip:boolean) { if(i.isEquipment){ //This is in case we dbl click the item, it will auto equip it. REMEMBER TO MAKE THE ITEM TYPE AND THE SLOT YOU WANT IT TO BE EQUIPPED TO HAVE THE SAME NAME. if(autoequip) { var index=0; //Keeping track of where we are in the list. var equipto=0; //Keeping track of where we want to be. for(var a in ArmorSlotName) //Loop through all the named slots on the armorslots list { if(a==i.itemType) //if the name is the same as the armor type. { equipto=index; //We aim for that slot. } index++; //We move on to the next slot. } EquipItem(i,equipto); } else //If we dont auto equip it then it means we must of tried to equip it to a slot so we make sure the item can be equipped to that slot. { if(i.itemType==ArmorSlotName[slot]) //If types match. { EquipItem(i,slot); //Equip the item to the slot. } } } if (DebugMode) { Debug.Log(i.name + " has been used"); } } //Equip an item to a slot. function EquipItem(i:Item,slot:int) { if(i.itemType == ArmorSlotName[slot]) //If the item can be equipped there: { if(CheckSlot(slot)) //If theres an item equipped to that slot we unequip it first: { UnequipItem(ArmorSlot[slot]); ArmorSlot[slot]=null; } ArmorSlot[slot]=i; //When we find the slot we set it to the item. gameObject.SendMessage ("PlayEquipSound", SendMessageOptions.DontRequireReceiver); //Play sound //We tell the Item to handle EquipmentEffects (if any). if (i.GetComponent(EquipmentEffect) != null) { equipmentEffectIs = true; i.GetComponent(EquipmentEffect).EquipmentEffectToggle(equipmentEffectIs); } //If the item is also a weapon we call the PlaceWeapon function. if (i.isAlsoWeapon == true) { if (i.equippedWeaponVersion != null) { PlaceWeapon(i); } else { Debug.LogError("Remember to assign the equip weapon variable!"); } } if (i.isAlsoHelmet == true) { if (i.equippedHelmetVersion != null) { PlaceHelmet(i); } else { Debug.LogError("Remember to assign the equip weapon variable!"); } } if (DebugMode) { Debug.Log(i.name + " has been equipped"); } playersinv.RemoveItem(i.transform); //We remove the item from the inventory } } //Unequip an item. function UnequipItem(i:Item) { gameObject.SendMessage ("PlayPickUpSound", SendMessageOptions.DontRequireReceiver); //Play sound //We tell the Item to disable EquipmentEffects (if any). if (i.equipmentEffect != null) { equipmentEffectIs = false; i.GetComponent(EquipmentEffect).EquipmentEffectToggle(equipmentEffectIs); } //If it's a weapon we call the RemoveWeapon function. if (i.itemType == "Weapon") { RemoveWeapon(i); } if (DebugMode) { Debug.Log(i.name + " has been unequipped"); } playersinv.AddItem(i.transform); } //Places the weapon in the hand of the Player. function PlaceWeapon (Item) { var Clone = Instantiate (Item.equippedWeaponVersion, WeaponSlot.position, WeaponSlot.rotation); Clone.name = Item.equippedWeaponVersion.name; Clone.transform.parent = WeaponSlot; if (DebugMode) { Debug.Log(Item.name + " has been placed as weapon"); } } function PlaceHelmet (Item) { var Clone = Instantiate (Item.equippedHelmetVersion, HelmetSlot.position, HelmetSlot.rotation); Clone.name = Item.equippedHelmetVersion.name; Clone.transform.parent = HelmetSlot; if (DebugMode) { Debug.Log(Item.name + " has been placed as Helmet"); } } //Removes the weapon from the hand of the Player. function RemoveWeapon (Item) { if (Item.equippedWeaponVersion != null) { Destroy(WeaponSlot.FindChild(""+Item.equippedWeaponVersion.name).gameObject); if (DebugMode) { Debug.Log(Item.name + " has been removed as weapon"); } } } function RemoveHelmet (Item) { if (Item.equippedWeaponVersion != null) { Destroy(HelmetSlot.FindChild(""+Item.equippedWeaponVersion.name).gameObject); if (DebugMode) { Debug.Log(Item.name + " has been removed as Helmet"); } } } function ShowCharacter(){ if (csheet) { csheet = false; if (invDispKeyIsSame != true) { gameObject.SendMessage ("ChangedState", false, SendMessageOptions.DontRequireReceiver); //Play sound gameObject.SendMessage("PauseGame", false, SendMessageOptions.DontRequireReceiver); //StopPauseGame/EnableMouse/ShowMouse } } else { // csheet = true; if (invDispKeyIsSame != true) { gameObject.SendMessage ("ChangedState", true, SendMessageOptions.DontRequireReceiver); //Play sound gameObject.SendMessage("PauseGame", true, SendMessageOptions.DontRequireReceiver); //PauseGame/DisableMouse/HideMouse } } } function Update () { //This will turn the character sheet on and off. if (Input.GetKeyDown(onOffButton)) { if (csheet) { csheet = false; if (invDispKeyIsSame != true) { gameObject.SendMessage ("ChangedState", false, SendMessageOptions.DontRequireReceiver); //Play sound gameObject.SendMessage("PauseGame", false, SendMessageOptions.DontRequireReceiver); //StopPauseGame/EnableMouse/ShowMouse } } else { csheet = true; if (invDispKeyIsSame != true) { gameObject.SendMessage ("ChangedState", true, SendMessageOptions.DontRequireReceiver); //Play sound gameObject.SendMessage("PauseGame", true, SendMessageOptions.DontRequireReceiver); //PauseGame/DisableMouse/HideMouse } } } } //Draw the Character Window function OnGUI() { GUI.skin = cSheetSkin; //Use the cSheetSkin variable. if(csheet) //If the csheet is opened up. { //Make a window that shows what's in the csheet called "Character" and update the position and size variables from the window variables. windowRect=GUI.Window (1, windowRect, DisplayCSheetWindow, "Character"); } } //This will display the character sheet and handle the buttons. function DisplayCSheetWindow(windowID:int) { if (canBeDragged == true) { GUI.DragWindow (Rect (0,0, 10000, 30)); //The window is dragable. } var index=0; for(var a in ArmorSlot) //Loop through the ArmorSlot array. { if(a==null) { if(GUI.Button(buttonPositions[index], ArmorSlotName[index])) //If we click this button (that has no item equipped): { var id=GetComponent(InventoryDisplay); if(id.itemBeingDragged != null) //If we are dragging an item: { EquipItem(id.itemBeingDragged,index); //Equip the Item. id.ClearDraggedItem();//Stop dragging the item. } } } else { if(GUI.Button(buttonPositions[index],ArmorSlot[index].itemIcon)) //If we click this button (that has an item equipped): { var id2=GetComponent(InventoryDisplay); if(id2.itemBeingDragged != null) //If we are dragging an item: { EquipItem(id2.itemBeingDragged,index); //Equip the Item. id2.ClearDraggedItem(); //Stop dragging the item. } else if (playersinv.Contents.length < playersinv.MaxContent) //If there is room in the inventory: { UnequipItem(ArmorSlot[index]); //Unequip the Item. ArmorSlot[index] = null; //Clear the slot. id2.ClearDraggedItem(); //Stop dragging the Item. } else if (DebugMode) { Debug.Log("Could not unequip " + ArmorSlot[index].name + " since the inventory is full"); } } } index++; } }
import React, { Component } from 'react' import Processing from './Processing' import ErrorPage from './ErrorPage' import hello from 'hellojs/dist/hello.all.js' import Graph from './Graph' export class MyContacts extends Component { constructor(props) { super(props) this.state = { status: "processing", contacts: [], msg: '' } } async componentDidMount() { let authResponse = hello('msft').getAuthResponse() try { let myContacts = await Graph.getContacts(authResponse.access_token) this.setState({status: "done", contacts: myContacts }) } catch (e) { sessionStorage.setItem('signIn', "FALSE") this.setState({status: "error", msg: e}) this.props.appState() } } render() { switch (this.state.status) { case 'processing': return <Processing msg="Getting contacts."/> case 'done': return <ContactList contacts={this.state.contacts}/> case 'error': return <ErrorPage msg={this.state.msg}/> default: console.log('Error: Invalid case defined in the render method.') break } } } function ContactList(props) { let rows = [] props.contacts.forEach((e,i) => { rows.push(<tr key={i}><td>{e[0]}</td><td>{e[1]}</td><td>{e[2]}</td><td>{e[3]}</td><td>{e[4]}</td><td>{e[5]}</td></tr>) } ) return <div> <table className="table"> <thead> <tr> <th>Name</th> <th>Email</th> <th>Phone</th> <th>City</th> <th>State</th> </tr> </thead> <tbody> {rows} </tbody> </table> </div> } export default MyContacts
require('babel-register')({ presets: ['env'] }); require('jsdom-global/register'); const _ = require('../../utils.js').default; module.exports = { makeElementFocusable(test) { document.body.innerHTML = '<div></div>'; const element = document.querySelector('div'); // --------------- _.makeElementFocusable(element); // --------------- test.equal(element.tabIndex, 0, 'It should set the tabIndex attribute to zero.'); test.doesNotThrow(() => { _.makeElementFocusable(null); _.makeElementFocusable(undefined); }); test.done(); }, makeElementsFocusable(test) { document.body.innerHTML = `<div></div> <div></div>`; const elements = document.querySelectorAll('div'); // --------------- _.makeElementsFocusable(elements); // --------------- [].forEach.call(elements, (element) => { test.equal(element.tabIndex, 0, 'It should set the tabIndex attribute of all selected elements to zero.'); }); test.doesNotThrow(() => { _.makeElementsFocusable(null); _.makeElementsFocusable(undefined); }); test.done(); }, makeElementNotFocusable(test) { document.body.innerHTML = '<div tabindex="0"></div>'; const element = document.querySelector('div'); // --------------- _.makeElementNotFocusable(element); // --------------- test.equal(element.tabIndex, -1, 'It should set the tabIndex attribute to -1.'); test.doesNotThrow(() => { _.makeElementNotFocusable(null); _.makeElementNotFocusable(undefined); }); test.done(); }, makeElementsNotFocusable(test) { document.body.innerHTML = `<div tabindex='0'></div> <div tabindex='1'></div>`; const elements = document.querySelectorAll('div'); // --------------- _.makeElementsNotFocusable(elements); // --------------- [].forEach.call(elements, (element) => { test.equal(element.tabIndex, -1, 'It should set the tabIndex attribute of all selected elements to -1.'); }); test.doesNotThrow(() => { _.makeElementsNotFocusable(null); _.makeElementsNotFocusable(undefined); }); test.done(); }, getFocusableChilds(test) { document.body.innerHTML = `<div id='parent'> <div tabindex='0'></div> <div tabindex='1'></div> <div></div> </div>`; const parent = document.querySelector('#parent'); // --------------- const childs = _.getFocusableChilds(parent); // --------------- test.equal(childs.length, 2); [].forEach.call(childs, (element) => { test.ok(element.tabIndex >= 0, 'It should return the array of focusable elements.'); }); test.doesNotThrow(() => { _.getFocusableChilds(null); _.getFocusableChilds(undefined); }); test.done(); }, getAllFocusableElements(test) { document.body.innerHTML = `<div> <div tabindex='0'></div> <div tabindex='1'></div> <div></div> </div>`; // --------------- const elements = _.getAllFocusableElements(); // --------------- test.equal(elements.length, 2); [].forEach.call(elements, (element) => { test.ok(element.tabIndex >= 0, 'It should return the array of focusable elements.'); }); test.done(); }, getNextFocusableElement(test) { document.body.innerHTML = `<div> <div id='prev' tabindex='0'></div> <div id='next' tabindex='1'></div> <div></div> </div>`; const element = document.querySelector('#prev'); // --------------- const next1 = _.getNextFocusableElement(element); const next2 = _.getNextFocusableElement(next1); // --------------- test.equal(next1.id, 'next', 'It should return the next focusable element.'); test.equal(next2, null, 'It should return "null" if the selected element is the last focusable element.'); test.doesNotThrow(() => { _.getNextFocusableElement(null); _.getNextFocusableElement(undefined); }); test.done(); }, getPreviousFocusableElement(test) { document.body.innerHTML = `<div> <div id='prev' tabindex='0'></div> <div id='next' tabindex='1'></div> <div></div> </div>`; const element = document.querySelector('#next'); // --------------- const prev1 = _.getPreviousFocusableElement(element); const prev2 = _.getPreviousFocusableElement(prev1); // --------------- test.equal(prev1.id, 'prev', 'It should return the previous focusable element.'); test.equal(prev2, null, 'It should return "null" if the selected element is the first focusable element.'); test.doesNotThrow(() => { _.getPreviousFocusableElement(null); _.getPreviousFocusableElement(undefined); }); test.done(); }, goToNextFocusableElement(test) { document.body.innerHTML = `<div> <div id='prev' tabindex='0'></div> <div id='next' tabindex='1'></div> <div></div> </div>`; const element = document.querySelector('#prev'); element.focus(); // --------------- _.goToNextFocusableElement(element); // --------------- test.equal(document.activeElement.id, 'next', 'It should move the focus to the next focusable element.'); test.doesNotThrow(() => { _.goToNextFocusableElement(element); _.goToNextFocusableElement(null); _.goToNextFocusableElement(undefined); }); test.done(); }, goToPreviousFocusableElement(test) { document.body.innerHTML = `<div> <div id='prev' tabindex='1'></div> <div id='next' tabindex='1'></div> <div></div> </div>`; const element = document.querySelector('#next'); element.focus(); // --------------- _.goToPreviousFocusableElement(element); // --------------- test.equal(document.activeElement.id, 'prev', 'It should move the focus to the previous focusable element.'); test.doesNotThrow(() => { _.goToPreviousFocusableElement(element); _.goToPreviousFocusableElement(null); _.goToPreviousFocusableElement(undefined); }); test.done(); }, makeElementClickable(test) { document.body.innerHTML = `<div></div> <div></div> <div></div>`; const elements = document.querySelectorAll('div'); let isClicked = false; const expectedResultsForMouse = [true, true, false]; const expectedResultsForKeyboard = [true, false, true]; test.expect(11); // --------------- function callback() { test.ok(true, 'It should execute the callback function on the "click" event for the element.'); isClicked = true; } // --------------- _.makeElementClickable(elements[0], callback); _.makeElementClickable(elements[1], callback, { mouse: true, keyboard: false }); _.makeElementClickable(elements[2], callback, { mouse: false, keyboard: true }); // --------------- [0, 1, 2].forEach((i) => { isClicked = false; elements[i].click(); test.equal(isClicked, expectedResultsForMouse[i], 'It should execute the callback function on the "mouse click" event.'); }); [0, 1, 2].forEach((i) => { isClicked = false; elements[i].dispatchEvent( new KeyboardEvent('keydown', { keyCode: 13, which: 13 }) ); test.equal(isClicked, expectedResultsForKeyboard[i], 'It should execute the callback function on the "enter pressed" event.'); }); test.doesNotThrow(() => { _.makeElementClickable(null); _.makeElementClickable(undefined); _.makeElementClickable(elements[0], null); _.makeElementClickable(elements[0], undefined); }); test.done(); }, makeChildElementsClickable(test) { document.body.innerHTML = `<div class='parent'> <div></div> <div></div> </div> <div class='parent'> <div></div> <div></div> </div> <div class='parent'> <div></div> <div></div> </div>`; const parents = document.querySelectorAll('.parent'); const elements = [ parents[0].querySelectorAll('div'), parents[1].querySelectorAll('div'), parents[2].querySelectorAll('div') ]; let isClicked = false; const expectedResultsForMouse = [true, true, false]; const expectedResultsForKeyboard = [true, false, true]; test.expect(29); // --------------- function callback() { let counter = 0; return (index) => { test.ok(true, 'It should set the event listener for the click event for the element.'); test.equal(index, (counter++) % 2, 'It should pass the index of the child element to the callback function.'); isClicked = true; }; } // --------------- _.makeChildElementsClickable(parents[0], elements[0], callback()); _.makeChildElementsClickable(parents[1], elements[1], callback(), { mouse: true, keyboard: false }); _.makeChildElementsClickable(parents[2], elements[2], callback(), { mouse: false, keyboard: true }); // --------------- [0, 1, 2].forEach((testNumber) => { const expectedResult = expectedResultsForMouse[testNumber]; [0, 1].forEach((i) => { isClicked = false; elements[testNumber][i].click(); test.equal(isClicked, expectedResult, 'It should execute the callback function on the "mouse click" event.'); }); }); [0, 1, 2].forEach((testNumber) => { const expectedResult = expectedResultsForKeyboard[testNumber]; [0, 1].forEach((i) => { isClicked = false; elements[testNumber][i].dispatchEvent( new KeyboardEvent('keydown', { keyCode: 13, which: 13 }) ); test.equal(isClicked, expectedResult, 'It should execute the callback function on the "enter pressed" event.'); }); }); test.doesNotThrow(() => { _.makeChildElementsClickable(null); _.makeChildElementsClickable(undefined); _.makeChildElementsClickable(parents, null); _.makeChildElementsClickable(parents, undefined); _.makeChildElementsClickable(parents, elements, null); _.makeChildElementsClickable(parents, elements, undefined); }); test.done(); }, onFocus(test) { document.body.innerHTML = '<div tabindex="0"></div>'; const element = document.querySelector('div'); test.expect(2); // --------------- function callback() { test.ok(true, 'It should execute the callback function on the "focus" event.'); } // --------------- _.onFocus(element, callback); // --------------- element.focus(); test.doesNotThrow(() => { _.onFocus(null); _.onFocus(undefined); _.onFocus(element, null); _.onFocus(element, undefined); }); test.done(); }, onBlur(test) { document.body.innerHTML = '<div tabindex="0"></div>'; const element = document.querySelector('div'); test.expect(2); // --------------- function callback() { test.ok(true, 'It should execute the callback function on the "blur" event.'); } // --------------- _.onBlur(element, callback); // --------------- element.focus(); element.blur(); test.doesNotThrow(() => { _.onBlur(null); _.onBlur(undefined); _.onBlur(element, null); _.onBlur(element, undefined); }); test.done(); }, clearFocus(test) { document.body.innerHTML = '<div></div>'; const element = document.querySelector('div'); test.expect(1); // --------------- element.focus(); _.clearFocus(); // --------------- test.notEqual(element, document.activeElement); test.done(); } };
'use strict' var path = require('path'); var express = require('express'); var fs = require('fs'); var bodyParser = require('body-parser'); var session = require('express-session'); var cookieParser = require('cookie-parser'); var mongoose = require('mongoose'); var app = express(); var port = 3030; var publicDir = path.dirname(require.main.filename) + '/web-project'; app.use(bodyParser.urlencoded({extended : false})); app.use(bodyParser.json()); app.use(cookieParser()); app.use(session({ secret: 'just-relax', resave: false, saveUninitialized: false, cookie: { maxAge: 1000 * 60 * 60 * 24 * 7 } })) app.use(express.static(publicDir)); var db = mongoose.connect('mongodb://blog:yk17148@localhost:27017/blog'); var modelsPath = path.join(__dirname, 'db'); fs.readdirSync(modelsPath).forEach(function (file) { if (/(.*)\.(js$|coffee$)/.test(file)) { require(modelsPath + '/' + file); } }); // 跨域设置 app.all('*', function(req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'X-Requested-With'); res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS'); res.header('X-Powered-By', '3.2.1'); res.header('Content-Type', 'application/json;charset=utf-8'); next(); }) require('./routes')(app); app.get('/api/img/:filename', function(req, res) { var targetPath = path.dirname(require.main.filename) + '/server/uploads/index-images'; var filePath = path.join(targetPath, req.params.filename); fs.exists(filePath, function(exists) { res.sendFile(exists ? filePath : path.join(targetPath, 'default.png')); }) }) app.get('*', function(req,res) { res.sendFile(path.join(publicDir, '/index.html')); }) module.exports = app;
/** * @author alteredq / http://alteredqualia.com/ */ THREE.CrosseyedEffect = function ( renderer ) { var _width, _height; var _cameraL = new THREE.PerspectiveCamera(); _cameraL.target = new THREE.Vector3(); var _cameraR = new THREE.PerspectiveCamera(); _cameraR.target = new THREE.Vector3(); var SCREEN_WIDTH = window.innerWidth; var SCREEN_HEIGHT = window.innerHeight; var HALF_WIDTH = SCREEN_WIDTH / 2; this.separation = 10; renderer.autoClear = false; this.setSize = function ( width, height ) { _width = width / 2; _height = height; renderer.setSize( width, height ); }; this.render = function ( scene, camera ) { _cameraL.fov = camera.fov; _cameraL.aspect = 0.5 * camera.aspect; _cameraL.near = camera.near; _cameraL.far = camera.far; _cameraL.updateProjectionMatrix(); _cameraL.position.copy( camera.position ); _cameraL.target.copy( camera.target ); _cameraL.translateX( this.separation ); _cameraL.lookAt( _cameraL.target ); _cameraR.projectionMatrix = _cameraL.projectionMatrix; _cameraR.position.copy( camera.position ); _cameraR.target.copy( camera.target ); _cameraR.translateX( - this.separation ); _cameraR.lookAt( _cameraR.target ); renderer.clear(); renderer.setViewport( 0, 0, _width, _height ); renderer.render( scene, _cameraL ); renderer.setViewport( _width, 0, _width, _height ); renderer.render( scene, _cameraR, false ); }; };
/* jshint node: true */ 'use strict'; module.exports = { name: require('./package').name };
import Database, {Query} from "../../lib/database.js"; const databaseConfig = require("../../../database.json").testing; const userFixtures = require("../fixtures/users.json"); describe(".select(...columnNames)", () => { let database, columnNames, tableName, fixtures; beforeEach(done => { database = new Database(databaseConfig); columnNames = "*"; tableName = "users"; fixtures = [ // Sorted by id by default userFixtures[1], userFixtures[2], userFixtures[3], userFixtures[4], userFixtures[0] ]; if (databaseConfig.useMocking) { database.mock.select(columnNames).from(tableName).results(fixtures); done(); } else { database.load({ users: fixtures }, done); } }); afterEach(done => { database.close(done); }); it("should return an instance of Query", () => { database.select(columnNames).should.be.instanceOf(Query); }); it("should be able to set the table name", () => { database.select(columnNames).from(tableName).should.be.instanceOf(Query); }); it("should select from the designated table", done => { database.select(columnNames).from(tableName).results((error, rows) => { if (error) { throw error; } rows.should.eql(fixtures); done(); }); }); });
$(document).ready(function () { // 导航栏激活 $('.dropdown').mouseover(function() { $(this).children('.dropdown-menu').css('display', 'block'); $(this).siblings().children('.dropdown-menu').css('display', 'none'); }); $('.dropdown').mouseout(function() { $(this).children('.dropdown-menu').css('display', 'none'); }); // 注册页 $('.register-bg').css('right', '0'); // 侧边客服、微博、微信、咨询 $('.sticker-tel, .sticker-group, .sticker-qq, .sticker-wechat, .sticker-weibo').mouseover(function() { $(this).next().css('right', '56px'); $(this).next().siblings('span').css('right', '-230px'); }); $('.sticker-tel, .sticker-group, .sticker-qq, .sticker-wechat, .sticker-weibo').mouseout(function() { $(this).next().css('right', '-230px'); }); // 返回顶部按钮 var clientHeight = document.documentElement.clientHeight; var toTop = document.getElementById('toTop'); var timer; var isTop =true; window.onscroll = function () { var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; // 判断页面高度,显示“回到顶部”按钮与否 if (scrollTop >= clientHeight) { toTop.style.display = 'block'; } else{ toTop.style.display = 'none'; }; // 滚动过程中结束滚动。清除定时器 if (!isTop) { clearInterval(timer); }; isTop = !isTop;//转换状态 } // 定义事件监听 toTop.onclick = function () { // 设置定时器 timer = setInterval(function () { var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; // 缓动动画效果,速度递减 var speed = Math.floor(-scrollTop / 10); document.documentElement.scrollTop = document.body.scrollTop = scrollTop + speed; isTop = true; // 清除定时器 if (scrollTop === 0) { clearInterval(timer); }; },10); } // 媒体轮播图 var mySwiper = new Swiper ('.swiper-container', { direction : 'horizontal', autoplay : 2000, // 每页的数量和每次翻动的数量 slidesPerView : 5, slidesPerGroup : 5, // 如果需要前进后退按钮 nextButton: '.swiper-button-next', prevButton: '.swiper-button-prev', }) // 表格滚动 $('#project1').mouseover(function() { $('.project-triangle').css('top', '35px'); $('.project-table').css('top', '0'); }); $('#project2').mouseover(function() { $('.project-triangle').css('top', '120px'); $('.project-table').css('top', '-399px'); }); $('#project3').mouseover(function() { $('.project-triangle').css('top', '200px'); $('.project-table').css('top', '-798px'); }); $('#project4').mouseover(function() { $('.project-triangle').css('top', '280px'); $('.project-table').css('top', '-1200px'); }); $('#project5').mouseover(function() { $('.project-triangle').css('top', '360px'); $('.project-table').css('top', '-1600px'); }); // Canvas绘图 var canvas = document.getElementById('canvas1'), // 这里通过gbCanvas获取canvas对象 context = canvas.getContext('2d'); //这里通过canvas获取处理API的上下文context // 定义进度条并转换成圆的占比 var val = $('#canvas1').prev('.progress-val').text(); //定义曲线的相关设置属性 var x = canvas.width/2, y = canvas.height/2, radius = 20, startAngle = 1.5*Math.PI, endAngle = startAngle + val/100*2*Math.PI, counterClockWise = false; context.beginPath(); context.arc( x, //定义圆心x坐标 y, //定义圆心y坐标 radius, //半径 startAngle, //起始角度 endAngle, //结束角度 counterClockWise //是否是逆时针方向 ); context.strokeStyle = '#50cdba'; context.lineWidth = 4; context.stroke(); })
function ConsoleLog(message) { console.log(">> " + message + "\n\n"); document.getElementById("console").innerHTML = ">> " + message + "<br /><br />" + document.getElementById("console").innerHTML; }
import m from 'mithril'; import prop from 'mithril/stream'; import _ from 'underscore'; import h from '../h'; import userVM from '../vms/user-vm'; import ownerMessageContent from './owner-message-content'; import modalBox from './modal-box'; import UserFollowBtn from './user-follow-btn'; const userCard = { oninit: function(vnode) { const userDetails = prop({}), user_id = vnode.attrs.userId; userVM.fetchUser(user_id, true, userDetails); vnode.state = { userDetails, displayModal: h.toggleProp(false, true) }; }, view: function({state}) { const user = state.userDetails(), contactModalC = [ownerMessageContent, state.userDetails], profileImage = userVM.displayImage(user); return m('#user-card', m('.card.card-user.u-radius.u-marginbottom-30[itemprop=\'author\']', [ m('.w-row', [ m('.w-col.w-col-4.w.col-small-4.w-col-tiny-4.w-clearfix', m(`img.thumb.u-round[itemprop='image'][src='${profileImage}'][width='100']`) ), m('.w-col.w-col-8.w-col-small-8.w-col-tiny-8', [ m('.fontsize-small.fontweight-semibold.lineheight-tighter[itemprop=\'name\']', m(`a.link-hidden[href="/users/${user.id}"]`, userVM.displayName(user)) ), m('.fontsize-smallest.lineheight-looser[itemprop=\'address\']', user.address_city ), m('.fontsize-smallest', `${h.pluralize(user.total_published_projects, ' projeto', ' projetos')} criados` ), m('.fontsize-smallest', `apoiou ${h.pluralize(user.total_contributed_projects, ' projeto', ' projetos')}` ) ]) ]), m('.project-author-contacts', [ m('ul.w-list-unstyled.fontsize-smaller.fontweight-semibold', [ (!_.isEmpty(user.facebook_link) ? m('li', [ m(`a.link-hidden[itemprop="url"][href="${user.facebook_link}"][target="_blank"]`, 'Perfil no Facebook') ]) : ''), (!_.isEmpty(user.twitter_username) ? m('li', [ m(`a.link-hidden[itemprop="url"][href="https://twitter.com/${user.twitter_username}"][target="_blank"]`, 'Perfil no Twitter') ]) : ''), _.map(user.links, link => m('li', [ m(`a.link-hidden[itemprop="url"][href="${link.link}"][target="_blank"]`, link.link) ])) ]), ]), (state.displayModal() ? m(modalBox, { displayModal: state.displayModal, content: contactModalC }) : ''), m(UserFollowBtn, { follow_id: user.id, following: user.following_this_user, enabledClass: '.btn.btn-medium.btn-message.u-marginbottom-10', disabledClass: '.btn.btn-medium.btn-message.u-marginbottom-10' }), (!_.isEmpty(user.email) ? m('a.btn.btn-medium.btn-message[href=\'javascript:void(0);\']', { onclick: state.displayModal.toggle }, 'Enviar mensagem') : '') ])); } }; export default userCard;
var acorn = require("acorn/dist/acorn") var walk = require("acorn/dist/walk") var parseType = require("./parsetype") function strip(lines) { for (var head, i = 1; i < lines.length; i++) { var line = lines[i], lineHead = line.match(/^[\s\*]*/)[0] if (lineHead != line) { if (head == null) { head = lineHead } else { var same = 0 while (same < head.length && head.charCodeAt(same) == lineHead.charCodeAt(same)) ++same if (same < head.length) head = head.slice(0, same) } } } if (head != null) { var startIndent = /^\s*/.exec(lines[0])[0] var trailing = /\s*$/.exec(head)[0] var extra = trailing.length - startIndent.length if (extra > 0) head = head.slice(0, head.length - extra) } outer: for (var i = 0; i < lines.length; i++) { var line = lines[i].replace(/\s+$/, "") if (i == 0 && head != null) { for (var j = 0; j < head.length; j++) { var found = line.indexOf(head.slice(j)) if (found == 0) { lines[i] = line.slice(head.length - j) continue outer } } } if (head == null || i == 0) lines[i] = line.replace(/^[\s\*]*/, "") else if (line.length < head.length) lines[i] = "" else lines[i] = line.slice(head.length) } while (lines.length && !lines[lines.length - 1]) lines.pop() while (lines.length && !lines[0]) lines.shift() return lines.join("\n") } exports.stripComment = function(text) { return strip(text.split("\n")) } exports.parse = function(text, options) { var current = null, found = [], filename = options.filename var ast = acorn.parse(text, { ecmaVersion: 6, locations: true, sourceFile: {text: text, name: filename}, sourceType: "module", onComment: function(block, text, start, end, startLoc, endLoc) { if (current && !block && current.endLoc.line == startLoc.line - 1) { current.text.push(text) current.end = end current.endLoc = endLoc } else if (/^\s*[\w\.$]*::/.test(text)) { var obj = {text: text.split("\n"), start: start, end: end, startLoc: startLoc, endLoc: endLoc} found.push(obj) if (!block) current = obj } else { current = null } if (options.onComment) options.onComment(block, text, start, end, startLoc, endLoc) } }) for (var i = 0; i < found.length; i++) { var comment = found[i], loc = comment.startLoc loc.file = filename comment.parsed = parseNestedComments(strip(comment.text), comment.startLoc) } return {ast: ast, comments: found} } function Found() {} exports.findNodeAfter = function(ast, pos, types) { var stack = [] function c(node, _, override) { if (node.end < pos) return if (node.start >= pos && types[node.type]) { stack.push(node) throw new Found } if (!override) stack.push(node) walk.base[override || node.type](node, null, c) if (!override) stack.pop() } try { c(ast) } catch (e) { if (e instanceof Found) return stack throw e } } exports.findNodeAround = function(ast, pos, types) { var stack = [], found function c(node, _, override) { if (node.end <= pos || node.start >= pos) return if (!override) stack.push(node) walk.base[override || node.type](node, null, c) if (types[node.type] && !found) found = stack.slice() if (!override) stack.pop() } c(ast) return found || stack } function parseComment(text, loc) { var match = /^\s*([\w\.$]+)?::\s*(-\s*)?/.exec(text), data, end = match[0].length, name = match[1] if (match[2]) { data = Object.create(null) data.loc = loc } else { var parsed = parseType(text, match[0].length, loc) data = parsed.type end = parsed.end } text = text.slice(end) while (match = /^\s*#([\w$]+)(?:=([^"]\S*|"(?:[^"\\]|\\.)*"))?\s*/.exec(text)) { text = text.slice(match[0].length) var value = match[2] || "true" if (value.charAt(0) == '"') value = JSON.parse(value) data["$" + match[1]] = value } if (/\S/.test(text)) data.description = text return {data: data, name: name, subcomments: []} } function dropIndent(text) { var lines = text.split("\n"), indent = 1e7 for (var i = 0; i < lines.length; i++) if (/\S/.test(lines[i])) indent = Math.min(indent, /^\s*/.exec(lines[i])[0].length) if (indent == 0) return text for (var i = 0; i < lines.length; i++) lines[i] = lines[i].slice(indent) return lines.join("\n") } function parseNestedComments(text, loc) { var line = 0, context = [], top, nextIndent = /^\s*/.exec(text)[0].length for (;;) { var next = /\n( *)[\w\.$]*::/.exec(text) var current = next ? text.slice(0, next.index) : text var parsed = parseComment(dropIndent(current), line ? {line: loc.line + line, column: loc.column, file: loc.file} : loc) if (!top) { top = parsed } else { if (!parsed.name) throw new SyntaxError("Sub-comment without name at " + loc.file + ":" + (loc.line + line)) while (context[context.length - 1].indent >= nextIndent) { context.pop() if (!context.length) throw new SyntaxError("Invalid indentation for sub-field at " + loc.file + ":" + (loc.line + line)) } context[context.length - 1].comment.subcomments.push(parsed) } context.push({indent: nextIndent, comment: parsed}) if (!next) break line += current.split("\n").length + 1 text = text.slice(current.length + 1) nextIndent = next[1].length } return top }
describe('Templates test suite', function () { var Templates = HotSausage.Templates; Templates.extend(function (Templates, _Templates_HS) { }); it('should be added to HS', function () { expect(Templates.isModule()).toBe(true); }); describe('When Templates is loaded', function () { var Clone = Templates.Clone; var instance0, purse, instanceBD, bootstrapBD; it('should have a function at Clone', function () { expect( Clone ).toBeDefined(); expect( typeof Clone ).toBe( "function" ); }); it('should have a template object named Clone', function () { instance0 = Clone(); expect( instance0 ).toBeDefined(); expect( instance0.name() ).toBe( "Clone" ); expect( instance0.template() ).toBe( null ); expect( instance0.isTemplate() ).toBe( true ); }); it('should have a purse', function () { purse = instance0._purse; expect( purse ).toBeDefined(); expect( purse._owner ).toBe( instance0 ); }); it('should have behavior data', function () { instanceBD = instance0._purse.__hsbd; expect( instanceBD ).toBeDefined(); expect( instanceBD.name() ).toBe( "Clone_BD" ); }); it('should have a bootstrap behavior data object', function () { bootstrapBD = instance0._purse.__hsbd._delegateBD; expect( bootstrapBD ).toBeDefined(); expect( bootstrapBD.name() ).toBe("_NULL__BD"); expect( bootstrapBD._templateBD ).toBe( bootstrapBD ); }); }); }); /* var templateInstance0 = (function bootstrap() { var bootstrapInstance = _newObject(); var bootstrapBD = __newBehavioralData(Object.prototype, null); __attachPurse(bootstrapInstance, bootstrapBD); __ensureMethodDictionary(bootstrapBD); bootstrapBD.templateBD = bootstrapBD; bootstrapBD.template = null; bootstrapBD.basicName = "_NULL_"; // This function is very similar to _newTemplate but the // following functions and properties are not needed: // __attachMethod_newInstance(), __copyMethods() // snapshotId, delegateBD, instanceCount, snapshotCount bootstrapBD.name = function () {return __bdBasicName(this) + "-BD";}; return _newTemplate(bootstrapInstance, "Clone"); })(); */
describe('Heading component', () => { it('Should render a Heading component.', () => { }); });
/** * Role repository */ 'use strict'; var locator = require('node-service-locator'); var q = require('q'); var moment = require('moment-timezone'); var BaseRepository = locator.get('base-repository'); var BaseModel = locator.get('base-model'); var RoleModel = locator.get('role-model'); /** * Role repository * * @constructor */ function RoleRepository() { BaseRepository.call(this); } RoleRepository.prototype = new BaseRepository(); RoleRepository.prototype.constructor = RoleRepository; /** * Find a role by ID * * @param {integer} id ID to search by * @return {object} Returns promise resolving to array of models */ RoleRepository.prototype.find = function (id) { var logger = locator.get('logger'); var defer = q.defer(); var db = this.getPostgres(); db.connect(function (err) { if (err) return defer.reject([ 'RoleRepository.find() - pg connect', err ]); db.query( "SELECT * " + " FROM roles " + " WHERE id = $1 ", [ id ], function (err, result) { if (err) { db.end(); return defer.reject([ 'RoleRepository.find() - select', err ]); } db.end(); var roles = []; result.rows.forEach(function (row) { var role = new RoleModel(row); roles.push(role); }); defer.resolve(roles); } ); }); return defer.promise; }; /** * Find roles by handle * * @param {string} handle Handle to search by * @return {object} Returns promise resolving to array of models */ RoleRepository.prototype.findByHandle = function (handle) { var logger = locator.get('logger'); var defer = q.defer(); var db = this.getPostgres(); db.connect(function (err) { if (err) return defer.reject([ 'RoleRepository.findByHandle() - pg connect', err ]); db.query( "SELECT * " + " FROM roles " + " WHERE handle = $1 ", [ handle ], function (err, result) { if (err) { db.end(); return defer.reject([ 'RoleRepository.findByHandle() - select', err ]); } db.end(); var roles = []; result.rows.forEach(function (row) { var role = new RoleModel(row); roles.push(role); }); defer.resolve(roles); } ); }); return defer.promise; }; /** * Find roles by user ID * * @param {integer} userId User ID to search by * @return {object} Return promise resolving to array of models */ RoleRepository.prototype.findByUserId = function (userId) { var logger = locator.get('logger'); var defer = q.defer(); var db = this.getPostgres(); db.connect(function (err) { if (err) return defer.reject([ 'RoleRepository.findByUserId() - pg connect', err ]); db.query( " SELECT r.* " + " FROM roles r " + "INNER JOIN user_roles ur " + " ON ur.role_id = r.id " + " WHERE ur.user_id = $1 ", [ userId ], function (err, result) { if (err) { db.end(); return defer.reject([ 'RoleRepository.findByUserId() - select', err ]); } db.end(); var roles = []; result.rows.forEach(function (row) { var role = new RoleModel(row); roles.push(role); }); defer.resolve(roles); } ); }); return defer.promise; }; /** * Find all the roles * * @return {object} Returns promise resolving to array of models */ RoleRepository.prototype.findAll = function () { var logger = locator.get('logger'); var defer = q.defer(); var db = this.getPostgres(); db.connect(function (err) { if (err) return defer.reject([ 'RoleRepository.findAll() - pg connect', err ]); db.query( " SELECT * " + " FROM roles " + "ORDER BY handle ", function (err, result) { if (err) { db.end(); return defer.reject([ 'RoleRepository.findAll() - select', err ]); } db.end(); var roles = []; result.rows.forEach(function (row) { var role = new RoleModel(row); roles.push(role); }); defer.resolve(roles); } ); }); return defer.promise; }; /** * Save role model * * @param {object} role The role to save * @return {object} Returns promise resolving to role ID or null on failure */ RoleRepository.prototype.save = function (role) { var logger = locator.get('logger'); var defer = q.defer(); var me = this; var db = this.getPostgres(); db.connect(function (err) { if (err) return defer.reject([ 'RoleRepository.save() - pg connect', err ]); var retries = 0; var originalId = role.getId(); function transaction() { if (++retries > BaseRepository.MAX_TRANSACTION_RETRIES) { db.end(); return defer.reject('RoleRepository.save() - maximum transaction retries reached'); } role.setId(originalId); db.query("BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE", [], function (err, result) { if (err) { db.end(); return defer.reject([ 'RoleRepository.save() - begin transaction', err ]); } var query = "SELECT handle " + " FROM roles " + " WHERE handle = $1 "; var params = [ role.getHandle() ]; if (role.getId()) { query += " AND id <> $2 "; params.push(role.getId()); } db.query( query, params, function (err, result) { if (err) { if ((err.sqlState || err.code) == '40001') // serialization failure return me.restartTransaction(db, defer, transaction); db.end(); return defer.reject([ 'RoleRepository.save() - collision check', err ]); } if (result.rows.length) { db.query("ROLLBACK TRANSACTION", [], function (err, result) { if (err) { db.end(); return defer.reject([ 'RoleRepository.save() - rollback transaction', err ]); } db.end(); defer.resolve(null); }); return; } if (role.getId()) { query = "UPDATE roles " + " SET parent_id = $1, " + " handle = $2 " + " WHERE id = $3 "; params = [ role.getParentId(), role.getHandle(), role.getId(), ]; } else { query = " INSERT " + " INTO roles(parent_id, handle) " + " VALUES ($1, $2) " + "RETURNING id "; params = [ role.getParentId(), role.getHandle(), ]; } db.query(query, params, function (err, result) { if (err) { if ((err.sqlState || err.code) == '40001') // serialization failure return me.restartTransaction(db, defer, transaction); db.end(); return defer.reject([ 'RoleRepository.save() - main query', err ]); } var id = result.rows.length && result.rows[0]['id']; if (id) role.setId(id); else id = result.rowCount > 0 ? role.getId() : null; db.query("COMMIT TRANSACTION", [], function (err, result) { if (err) { if ((err.sqlState || err.code) == '40001') // serialization failure return me.restartTransaction(db, defer, transaction); db.end(); return defer.reject([ 'RoleRepository.save() - commit transaction', err ]); } db.end(); if (id) role.dirty(false); defer.resolve(id); }); }); } ); }); } transaction(); }); return defer.promise; }; /** * Delete a role * * @param {object} role Role to delete * @return {object} Returns promise resolving to a number of deleted DB rows */ RoleRepository.prototype.delete = function (role) { var logger = locator.get('logger'); var defer = q.defer(); var db = this.getPostgres(); db.connect(function (err) { if (err) return defer.reject([ 'RoleRepository.delete() - pg connect', err ]); db.query( "DELETE " + " FROM roles " + " WHERE id = $1 ", [ role.getId() ], function (err, result) { if (err) { db.end(); return defer.reject([ 'RoleRepository.delete() - delete', err ]); } db.end(); role.setId(null); role.dirty(false); defer.resolve(result.rowCount); } ); }); return defer.promise; }; /** * Delete all the roles * * @return {object} Returns promise resolving to a number of deleted DB rows */ RoleRepository.prototype.deleteAll = function () { var logger = locator.get('logger'); var defer = q.defer(); var db = this.getPostgres(); db.connect(function (err) { if (err) return defer.reject([ 'RoleRepository.deleteAll() - pg connect', err ]); db.query( "DELETE " + " FROM roles ", function (err, result) { if (err) { db.end(); return defer.reject([ 'RoleRepository.deleteAll() - delete', err ]); } db.end(); defer.resolve(result.rowCount); } ); }); return defer.promise; }; module.exports = RoleRepository;
module.exports = { id: "arm", name: "TR2 Arm", warning: "Made-to-order: Orders take 4-8 weeks to ship", imgs: ["/img/slate-tr2-9"], basePrice: 1999, config: [{ name: "shipping", label: "Shipping", default: 1, items: [{ id: 0, label: "Local Pickup - Springfield, MO", price: 0, enabled: true, }, { id: 1, label: "US Continental Shipping", price: 100, enabled: true, }, { id: 2, label: "Canada Shipping", price: 200, enabled: true, }] }], };
var fs = require('fs'); var mqtt = require('mqtt'); var index = require('./index.js'); var client = mqtt.connect('mqtt://test.mosquitto.org'); var topic = "/CBA/015/n80Freezer"; client.on('connect', function () { console.log(">>> Connected to MQTT hub"); console.log(">>> Subscribed to "+ topic); client.subscribe(topic); }); var deet = null; fs.readFile('logData.txt', 'utf8', function (err,data) { if (err) { console.log("Error reading the file: "+err); } console.log(">>> DATA: "+data.length); console.log(">>> DATA: "+typeof(data)); deet = data.split("\n"); }); var idx = 0; setInterval(function(){ var proc = index.processData(deet[idx]); console.log(">>> Index: " + idx); if (proc.temperature !== NaN){ console.log(">>> Temp: " + proc.temperature); client.publish(topic, "T="+proc.temperature); } idx++; },3000);
var gulp = require('gulp'); var concat = require('gulp-concat'); var minify = require('gulp-minify'); // Concatenate js files var scripts = [ 'ng-oauth-2.js', './providers/*.js' ]; gulp.task('build', ['concatenate', 'minify']); gulp.task('concatenate', function() { return gulp.src(scripts) .pipe(concat('ng-oauth-2.js')) .pipe(gulp.dest('./dist/')); }); gulp.task('minify', function() { return gulp.src(scripts) .pipe(concat('ng-oauth-2.js')) .pipe(minify()) .pipe(gulp.dest('./dist/')); });
/* global require, describe, it */ 'use strict'; // MODULES // var // Expectation library: chai = require( 'chai' ), // Module to be tested: isUint8ClampedArray = require( './../lib' ); // VARIABLES // var expect = chai.expect, assert = chai.assert; // TESTS // describe( 'validate.io-uint8array-clamped', function tests() { it( 'should export a function', function test() { expect( isUint8ClampedArray ).to.be.a( 'function' ); }); it( 'should positively validate', function test() { var arr = new Uint8ClampedArray( 10 ); assert.ok( isUint8ClampedArray( arr ) ); }); it( 'should negatively validate', function test() { var values = [ '5', 5, NaN, null, undefined, true, [], {}, function(){}, new Int8Array( 10 ), new Uint8Array( 10 ), new Int16Array( 10 ), new Uint16Array( 10 ), new Int32Array( 10 ), new Uint32Array( 10 ), new Float32Array( 10 ), new Float64Array( 10 ), new Array( 10 ) ]; for ( var i = 0; i < values.length; i++ ) { assert.notOk( isUint8ClampedArray( values[i] ), values[i] ); } }); });
'use strict'; var path = require('path'); var config = require('config'); var express = require('./lib'); var mongoose = require(path.resolve('./depends/mongoose')); mongoose.connect(function (err, db) { if (err) { throw err; } var app = express.init(); // Start the app by listening on <port> var port = config.provides.express.port; app.listen(port); // Logging initialization console.log('Express started on port ' + port); });
NewTicket.widgets = { layoutBox1: ["wm.Layout", {"horizontalAlign":"left","verticalAlign":"top"}, {}] }