Best JavaScript code snippet using playwright-internal
mafiachecker.js
Source:mafiachecker.js
...40 lists.push("roles"+i);41 ++i;42 }43 checkAttributes(raw, ["name", "sides", "roles", "roles1"], ["villageCantLoseRoles", "author", "summary", "border", "killmsg", "killusermsg", "votemsg", "lynchmsg", "drawmsg", "minplayers", "noplur", "nolynch", "votesniping", "checkNoVoters", "quickOnDeadRoles", "ticks", "silentVote", "delayedConversionMsg", "nonPeak", "changelog", "changelog2", "threadlink", "altname", "tips", "closedSetup", "variables", "spawnPacks"].concat(lists), "Your theme");44 if (checkType(raw.name, ["string"], "'theme.name'")) {45 if (raw.name[raw.name.length - 1] == " ") {46 addFatalError("Your theme has an extra whitespace at the end of its name, which will make it impossible to update.");47 }48 if (raw.name.indexOf(" ") >= 0) {49 addFatalError("Your theme has a double whitespace on its name, which will make it impossible to update.");50 }51 }52 checkType(raw.sides, ["array"], "'theme.sides'");53 checkType(raw.roles, ["array"], "'theme.roles'");54 55 if (checkType(raw.author, ["string", "array"], "'theme.author'")) {56 if (Array.isArray(raw.author)) {57 for (i in raw.author) {58 if (!checkType(raw.author[i], ["string"], "All names in 'theme.author'")) {59 break;60 }61 }62 }63 }64 65 checkType(raw.summary, ["string"], "'theme.summary'");66 checkType(raw.border, ["string"], "'theme.border'");67 checkType(raw.killmsg, ["string"], "'theme.killmsg'");68 checkType(raw.killusermsg, ["string"], "'theme.killusermsg'");69 checkType(raw.votemsg, ["string"], "'theme.votemsg'");70 checkType(raw.lynchmsg, ["string"], "'theme.lynchmsg'");71 checkType(raw.drawmsg, ["string"], "'theme.drawmsg'");72 checkType(raw.minplayers, ["number"], "'theme.minplayers'");73 checkType(raw.threadlink, ["string"], "'theme.threadlink'");74 checkType(raw.altname, ["string"], "'theme.altname'");75 checkType(raw.variables, ["object"], "'theme.variables'");76 checkValidValue(raw.nolynch, [true, false], "theme.nolynch");77 checkValidValue(raw.noplur, [true, false], "theme.noplur");78 checkValidValue(raw.votesniping, [true, false], "theme.votesniping");79 checkValidValue(raw.silentVote, [true, false], "theme.silentVote");80 checkValidValue(raw.checkNoVoters, [true, false], "theme.checkNoVoters");81 checkValidValue(raw.quickOnDeadRoles, [true, false], "theme.quickOnDeadRoles");82 checkValidValue(raw.delayedConversionMsg, [true, false], "theme.delayedConversionMsg");83 checkValidValue(raw.nonPeak, [true, false], "theme.nonPeak");84 checkValidValue(raw.closedSetup, [true, false], "theme.closedSetup");85 86 if (checkType(raw.changelog, ["object", "array"], "'theme.changelog'")) {87 for (i in raw.changelog) {88 if (!checkType(raw.changelog[i], ["string"], "All values for 'theme.changelog'")) {89 break;90 }91 }92 }93 if (checkType(raw.tips, ["object", "array"], "'theme.tips'")) {94 for (i in raw.tips) {95 if (!checkType(raw.tips[i], ["string"], "All values for 'theme.tips'")) {96 break;97 }98 }99 }100 101 if (checkType(raw.ticks, ["object"], "'theme.ticks'")) {102 checkAttributes(raw.ticks, [], ["night", "night1", "standby"], "theme.ticks");103 checkType(raw.ticks.night, ["number"], "'theme.ticks.night'");104 checkType(raw.ticks.night1, ["number"], "'theme.ticks.night1'");105 checkType(raw.ticks.standby, ["number"], "'theme.ticks.standby'");106 }107 theme.sideTranslations = {};108 theme.roles = {};109 // Init from the theme110 for (i in raw.sides) {111 theme.addSide(raw.sides[i]);112 }113 for (i in raw.roles) {114 theme.addRole(raw.roles[i]);115 }116 i = 1;117 var roleList, e;118 while ("roles"+i in raw) {119 roleList = raw["roles" + i];120 if (checkType(roleList, ["array"], "'theme.roles" + i + "'")) {121 for (e = 0; e < roleList.length; ++e) {122 if (typeof roleList[e] == "object") {123 for (var c in roleList[e]) {124 checkValidRole(c, "theme.roles" + i);125 }126 } else {127 if (roleList[e].indexOf("pack:") === 0) {128 if (!("spawnPacks" in raw)) {129 addFatalError("Your theme use spawnPacks. but no 'spawnPack' object was found in your theme.");130 } else if (!(roleList[e].substr(5) in raw.spawnPacks)) {131 addFatalError("Invalid spawnPack '" + roleList[e].substr(5) + "' found on theme.roles" + i + ".");132 }133 } else {134 checkValidRole(roleList[e], "theme.roles" + i);135 }136 }137 }138 }139 ++i;140 }141 if (!raw.roles1) {142 addFatalError("This theme has no roles1, it can not be played.");143 }144 145 if (checkType(raw.spawnPacks, ["object"], "'theme.spawnPacks'")) {146 var pack, p;147 for (e in raw.spawnPacks) {148 pack = raw.spawnPacks[e];149 checkAttributes(pack, ["roles"], ["chance"], "theme.spawnPacks." + e);150 151 if (checkType(pack.roles, ["array"], "'theme.spawnPacks." + e + ".roles'")) {152 for (i in pack.roles) {153 if (checkType(pack.roles[i], ["array"], "All values for 'theme.spawnPacks." + e + ".roles'")) {154 if (pack.roles[i].length === 0) {155 addFatalError("spawnPack '" + e + ".roles." + i + "' must have at least 1 role.");156 } else {157 for (p in pack.roles[i]) {158 checkValidRole(pack.roles[i][p], "theme.spawnPacks." + e + ".roles." + p);159 }160 }161 }162 }163 }164 if (checkType(pack.chance, ["array"], "'theme.spawnPacks." + e + ".chance'")) {165 for (i in pack.chance) {166 if (!checkType(pack.chance[i], ["number"], "All values for 'theme.spawnPacks." + e + ".chance'")) {167 break;168 }169 }170 }171 172 if (pack.roles && pack.chance && pack.roles.length !== pack.chance.length) {173 addFatalError("spawnPack '" + e + "' must have the same number of lists and values under 'roles' and 'chance'.");174 }175 }176 }177 178 if ("villageCantLoseRoles" in raw) {179 var cantLose = raw.villageCantLoseRoles;180 if (checkType(cantLose, ["array"], "'theme.villageCantLoseRoles'")) {181 for (e = 0; e < cantLose.length; ++e) {182 checkValidRole(cantLose[e], "theme.villageCantLoseRoles");183 }184 }185 }186 theme.addActions();187 theme.checkActions();188 } catch (err) {189 addFatalError("Couldn't check the entire code. The following error has occured: " + err + (err.lineNumber ? " on line: " + err.lineNumber : ""));190 }191 192 return {fatal: fatalErrors, minor: minorErrors};193 };194 this.update = function () {195 var POglobal = SESSION.global();196 var index, source;197 for (var i = 0; i < POglobal.plugins.length; ++i) {198 if ("mafiachecker.js" == POglobal.plugins[i].source) {199 source = POglobal.plugins[i].source;200 index = i;201 }202 }203 if (index !== undefined) {204 updateModule(source, function (module) {205 POglobal.plugins[index] = module;206 module.source = source;207 module.init();208 });209 }210 };211 212 function Theme(){}213 Theme.prototype.addSide = function(obj) {214 var yourSide = (obj.side) ? 'Your side "' + obj.side + '"' : 'One of your sides';215 checkAttributes(obj, ["side", "translation"], ["winmsg", "hide"], yourSide);216 if (obj.side in this.sideTranslations) {217 addFatalError("Your theme has a repeated side \"" + obj.side + "\".");218 }219 this.sideTranslations[obj.side] = obj.translation;220 221 checkType(obj.side, ["string"], yourSide + "'s 'side' attribute");222 checkType(obj.translation, ["string"], yourSide + "'s 'translation' attribute");223 checkType(obj.winmsg, ["string"], yourSide + "'s 'winmsg' attribute");224 225 if (obj.side) {226 this.correctSides.push(obj.side);227 this.lowerCaseSides.push(obj.side.toLowerCase());228 }229 };230 Theme.prototype.addRole = function(obj) {231 var yourRole = (obj.role) ? 'your role "' + obj.role + '"' : 'one of your roles';232 checkAttributes(obj, ["role", "translation", "side", "help"], ["actions", "help2", "info", "infoName", "winningSides", "winIfDeadRoles", "hide", "startupmsg", "players"], cap(yourRole));233 if (!obj.actions) {234 obj.actions = {};235 }236 if (obj.role in this.roles) {237 addFatalError("Your theme has a repeated role '" + obj.role + "'.");238 }239 this.roles[obj.role] = obj;240 checkType(obj.role, ["string"], yourRole + "'s 'role' attribute");241 checkType(obj.translation, ["string"], yourRole + "'s 'translation' attribute");242 checkType(obj.help, ["string"], yourRole + "'s 'help' attribute");243 checkType(obj.help2, ["string"], yourRole + "'s 'help2' attribute");244 checkType(obj.info, ["string"], yourRole + "'s 'info' attribute");245 checkType(obj.infoName, ["string"], yourRole + "'s 'infoName' attribute");246 checkType(obj.startupmsg, ["string"], yourRole + "'s 'startupmsg' attribute");247 checkType(obj.players, ["string", "number", "array", "boolean"], yourRole + "'s 'players' attribute");248 checkValidValue(obj.hide, [true, false, "role", "side", "both"], yourRole + "'s 'hide' attribute");249 250 if (checkType(obj.side, ["string", "object"], yourRole + "'s 'side' attribute")) {251 if (typeof obj.side == "string") {252 checkValidSide(obj.side, yourRole + "'s 'side' attribute");253 } else if (typeof obj.side == "object") {254 if (checkType(obj.side.random, ["object"], yourRole + "'s 'side.random' attribute")) {255 for (var e in obj.side.random) {256 checkValidSide(e, yourRole + "'s 'side' attribute");257 checkType(obj.side.random[e], ["number"], yourRole + "'s 'side.random.'" + e);258 }259 } else {260 addFatalError(cap(yourRole) + " has an invalid Object as its side");261 }262 }263 }264 if (obj.role) {265 this.correctRoles.push(obj.role);266 this.lowerCaseRoles.push(obj.role.toLowerCase());267 }268 };269 Theme.prototype.addActions = function() {270 var r, e, i, o, role, action, command, yourRole, c, commonMandatory, commonOptional, commandList, requiredAtt, mode, extraModes, possibleStandbyActions, act, comm;271 for (r in this.roles) {272 role = this.roles[r];273 yourRole = "<b>" + role.role + "</b>";274 if (checkType(role.winningSides, ["array", "string"], "'" + yourRole + ".winningSides'")) {275 if (Array.isArray(role.winningSides)) {276 for (e in role.winningSides) {277 checkValidSide(role.winningSides[e], yourRole + ".winningSides");278 }279 } else {280 if (role.winningSides !== "*") {281 addFatalError("Role " + yourRole + ".winningSides must be either an Array of sides or \"*\".");282 }283 }284 }285 if (checkType(role.winIfDeadRoles, ["array"], "'" + yourRole + ".winIfDeadRoles'")) {286 for (e in role.winIfDeadRoles) {287 checkValidRole(role.winIfDeadRoles[e], yourRole + ".winIfDeadRoles");288 }289 }290 291 if (checkType(role.actions, ["object"], "'" + yourRole + ".actions")) {292 act = "Role " + yourRole + ".actions";293 checkAttributes(role.actions, [], ["night", "standby", "hax", "standbyHax", "onDeath", "onDeadRoles", "initialCondition", "avoidHax", "avoidStandbyHax", "daykill", "daykillrevengemsg", "daykillevademsg", "daykillmissmsg", "revealexposermsg", "expose", "exposerevengemsg", "exposeevademsg", "exposemissmsg", "vote", "voteshield", "voteMultiplier", "startup", "onlist", "onteam", "lynch", "teamTalk", "noVote", "noVoteMsg", "preventTeamvote", "updateTeam", "teamUtilities", "updateCharges"].concat(possibleNightActions), act);294 if (checkType(role.actions.night, ["object"], act + ".night")) {295 for (e in role.actions.night) {296 action = role.actions.night[e];297 comm = act + ".night." + e;298 if (checkType(action, ["object"], comm)) {299 command = e;300 commonMandatory = ["target", "common", "priority"];301 commonOptional = ["broadcast", "command", "limit", "msg", "failChance", "charges", "recharge", "initialrecharge", "broadcastmsg", "chargesmsg", "clearCharges", "addCharges", "suicideChance", "suicidemsg", "restrict", "cancel", "pierce", "pierceChance", "noFollow", "haxMultiplier", "userMustBeVisited", "targetMustBeVisited", "userMustVisit", "targetMustVisit", "bypass", "hide"];302 commandList = [];303 if ("command" in action) {304 if (Array.isArray(action.command)) {305 commandList = action.command;306 } else if (typeof action.command == "object") {307 for (c in action.command) {308 commandList.push(c);309 }310 } else if (typeof action.command == "string") {311 commandList.push(action.command);312 }313 } else {314 commandList.push(command);315 }316 if (commandList.indexOf("kill") !== -1)317 commonOptional = commonOptional.concat(["msg", "killmsg"]);318 if (commandList.indexOf("inspect") !== -1)319 commonOptional = commonOptional.concat(["Sight"]);320 if (commandList.indexOf("distract") !== -1)321 commonOptional = commonOptional.concat(["distractmsg", "teammsg"]);322 if (commandList.indexOf("protect") !== -1)323 commonOptional = commonOptional.concat(["protectmsg"]);324 if (commandList.indexOf("safeguard") !== -1)325 commonOptional = commonOptional.concat(["safeguardmsg"]);326 if (commandList.indexOf("poison") !== -1)327 commonOptional = commonOptional.concat(["count", "poisonDeadMessage", "poisonmsg", "poisontarmsg"]);328 if (commandList.indexOf("stalk") !== -1) {329 commonOptional = commonOptional.concat(["stalkmsg", "novisitmsg"]);330 }331 if (commandList.indexOf("watch") !== -1) {332 commonOptional = commonOptional.concat(["watchmsg", "watchFirst", "watchLast"]);333 }334 if (commandList.indexOf("convert") !== -1) {335 commonMandatory = commonMandatory.concat(["newRole"]);336 commonOptional = commonOptional.concat(["canConvert", "convertmsg", "usermsg", "tarmsg", "convertfailmsg", "silent", "silentConvert", "unlimitedSelfConvert"]);337 }338 if (commandList.indexOf("massconvert") !== -1) {339 commonMandatory = commonMandatory.concat(["convertRoles"]);340 commonOptional = commonOptional.concat(["silentMassConvert", "massconvertmsg", "singlemassconvertmsg", "silent"]);341 }342 if (commandList.indexOf("copy") !== -1) {343 commonMandatory = commonMandatory.concat(["copyAs"]);344 commonOptional = commonOptional.concat(["canCopy", "copymsg", "copyfailmsg", "usermsg", "silent", "silentCopy"]);345 }346 if (commandList.indexOf("curse") !== -1) {347 commonMandatory = commonMandatory.concat(["cursedRole"]);348 commonOptional = commonOptional.concat(["curseCount", "canCurse", "curseConvertMessage", "cursemsg", "cursefailmsg", "silent", "silentCurse"]);349 }350 if (commandList.indexOf("detox") !== -1) {351 commonOptional = commonOptional.concat(["msg", "targetmsg", "detoxmsg", "detoxfailmsg", "silent"]);352 }353 if (commandList.indexOf("dispel") !== -1) {354 commonOptional = commonOptional.concat(["msg", "targetmsg", "dispelmsg", "dispelfailmsg", "silent"]);355 }356 if (commandList.indexOf("shield") !== -1) {357 commonOptional = commonOptional.concat(["shieldActions", "shieldmsg"]);358 }359 if (commandList.indexOf("guard") !== -1) {360 commonMandatory = commonMandatory.concat(["guardActions"]);361 commonOptional = commonOptional.concat(["guardmsg"]);362 }363 if (commandList.indexOf("dummy") !== -1) {364 commonOptional = commonOptional.concat(["dummyusermsg", "dummytargetmsg", "dummybroadcastmsg"]);365 }366 if (commandList.indexOf("dummy2") !== -1) {367 commonOptional = commonOptional.concat(["dummy2usermsg", "dummy2targetmsg", "dummy2broadcastmsg"]);368 }369 if (commandList.indexOf("dummy3") !== -1) {370 commonOptional = commonOptional.concat(["dummy3usermsg", "dummy3targetmsg", "dummy3broadcastmsg"]);371 }372 if (commandList.indexOf("dummy4") !== -1) {373 commonOptional = commonOptional.concat(["dummy4usermsg", "dummy4targetmsg", "dummy4broadcastmsg"]);374 }375 if (commandList.indexOf("dummy5") !== -1) {376 commonOptional = commonOptional.concat(["dummy5usermsg", "dummy5targetmsg", "dummy5broadcastmsg"]);377 }378 if (commandList.indexOf("dummy6") !== -1) {379 commonOptional = commonOptional.concat(["dummy6usermsg", "dummy6targetmsg", "dummy6broadcastmsg"]);380 }381 if (commandList.indexOf("dummy7") !== -1) {382 commonOptional = commonOptional.concat(["dummy7usermsg", "dummy7targetmsg", "dummy7broadcastmsg"]);383 }384 if (commandList.indexOf("dummy8") !== -1) {385 commonOptional = commonOptional.concat(["dummy8usermsg", "dummy8targetmsg", "dummy8broadcastmsg"]);386 }387 if (commandList.indexOf("dummy9") !== -1) {388 commonOptional = commonOptional.concat(["dummy9usermsg", "dummy9targetmsg", "dummy9broadcastmsg"]);389 }390 if (commandList.indexOf("dummy10") !== -1) {391 commonOptional = commonOptional.concat(["dummy10usermsg", "dummy10targetmsg", "dummy10broadcastmsg"]);392 }393 394 commonNightActions(act, action, e);395 checkAttributes(action, commonMandatory, commonOptional, comm);396 for (c in commandList) {397 command = commandList[c];398 if (command == "kill") {399 checkType(action.msg, ["string"], comm + ".msg");400 checkType(action.killmsg, ["string"], comm + ".killmsg");401 } else if (command == "inspect") {402 if (checkType(action.Sight, ["string", "object"], comm + ".Sight")) {403 if (typeof action.Sight == "string") {404 checkValidValue(action.Sight, ["Team"], comm + ".Sight");405 } else if (typeof action.Sight == "object") {406 for (i in action.Sight) {407 if (i !== "true") {408 checkValidRole(i, comm + ".Sight");409 }410 checkType(action.Sight[i], ["number"], comm + ".Sight." + i);411 }412 }413 }414 } else if (command == "distract") {415 checkType(action.distractmsg, ["string"], comm + ".distractmsg");416 checkType(action.teammsg, ["string"], comm + ".teammsg");417 } else if (command == "protect") {418 checkType(action.protectmsg, ["string"], comm + ".protectmsg");419 } else if (command == "safeguard") {420 checkType(action.safeguardmsg, ["string"], comm + ".safeguardmsg");421 } else if (command == "poison") {422 checkType(action.count, ["number"], comm + ".count");423 checkType(action.poisonDeadMessage, ["string"], comm + ".poisonDeadMessage");424 checkType(action.poisontarmsg, ["string"], comm + ".poisontarmsg");425 checkType(action.poisonmsg, ["string"], comm + ".poisonmsg");426 } else if (command == "stalk") {427 checkType(action.stalkmsg, ["string"], comm + ".stalkmsg");428 checkType(action.novisitmsg, ["string"], comm + ".novisitmsg");429 } else if (command == "watch") {430 checkType(action.watchmsg, ["string"], comm + ".watchmsg");431 checkType(action.watchFirst, ["number"], comm + ".watchFirst");432 checkType(action.watchLast, ["number"], comm + ".watchLast");433 } else if (command == "convert") {434 checkValidValue(action.silent, [true, false], comm + ".silent");435 checkValidValue(action.silentConvert, [true, false], comm + ".silentConvert");436 checkValidValue(action.unlimitedSelfConvert, [true, false], comm + ".unlimitedSelfConvert");437 438 if (checkType(action.newRole, ["string", "object"], comm + ".newRole")) {439 if (typeof action.newRole == "string") {440 checkValidRole(action.newRole, comm + ".newRole");441 } else if (typeof action.newRole == "object") {442 if ("random" in action.newRole && typeof action.newRole.random == "object") {443 for (i in action.newRole.random) {444 checkValidRole(i, comm + ".newRole.random");445 checkType(action.newRole.random[i], ["number"], comm + ".newRole.random." + i);446 }447 } else {448 for (i in action.newRole) {449 checkValidRole(i, comm + ".newRole");450 if (checkType(action.newRole[i], ["array"], comm + ".newRole." + i)) {451 for (o in action.newRole[i]) {452 checkValidRole(action.newRole[i][o], comm + ".newRole." + i);453 }454 }455 }456 }457 }458 }459 if (checkType(action.canConvert, ["string", "array"], comm + ".canConvert")) {460 if (typeof action.canConvert == "string") {461 checkValidValue(action.canConvert, ["*"], comm + ".canConvert");462 } else {463 for (i in action.canConvert) {464 checkValidRole(action.canConvert[i], comm + ".canConvert");465 }466 }467 }468 checkType(action.convertmsg, ["string"], comm + ".convertmsg");469 checkType(action.usermsg, ["string"], comm + ".usermsg");470 checkType(action.tarmsg, ["string"], comm + ".tarmsg");471 checkType(action.convertfailmsg, ["string"], comm + ".convertfailmsg");472 } else if (command == "massconvert") {473 if (checkType(action.convertRoles, ["object"], comm + ".convertRoles")) {474 for (i in action.convertRoles) {475 checkValidRole(i, comm + ".convertRoles");476 checkValidRole(action.convertRoles[i], comm + ".convertRoles." + i);477 }478 }479 480 checkType(action.massconvertmsg, ["string"], comm + ".massconvertmsg");481 checkType(action.singlemassconvertmsg, ["string"], comm + ".singlemassconvertmsg");482 checkType(action.silentMassConvert, ["boolean"], comm + ".silentMassConvert");483 checkType(action.silent, ["boolean"], comm + ".silent");484 } else if (command == "copy") {485 checkValidValue(action.silent, [true, false], comm + ".silent");486 checkValidValue(action.silentCopy, [true, false], comm + ".silentCopy");487 488 if (checkType(action.copyAs, ["string", "object"], comm + ".copyAs")) {489 if (typeof action.copyAs == "string") {490 if (!isRole(action.copyAs) && action.copyAs !== "*") {491 addFatalError(comm + ".copyAs must be a role or \"*\"." );492 }493 } else if (typeof action.copyAs == "object") {494 for (i in action.copyAs) {495 checkValidRole(i, comm + ".copyAs." + i);496 if (checkType(action.copyAs[i], ["array"], comm + ".copyAs." + i)) {497 for (o in action.copyAs[i]) {498 checkValidRole(action.copyAs[i][o], comm + ".copyAs." + i);499 }500 }501 }502 }503 }504 if (checkType(action.canCopy, ["string", "array"], comm + ".canCopy")) {505 if (typeof action.canCopy == "string") {506 checkValidValue(action.canCopy, ["*"], comm + ".canCopy");507 } else {508 for (i in action.canCopy) {509 checkValidRole(action.canCopy[i], comm + ".canCopy");510 }511 }512 }513 checkType(action.copymsg, ["string"], comm + ".copymsg");514 checkType(action.copyfailmsg, ["string"], comm + ".copyfailmsg");515 checkType(action.usermsg, ["string"], comm + ".usermsg");516 } else if (command == "curse") {517 checkValidValue(action.silent, [true, false], comm + ".silent");518 checkValidValue(action.silentCurse, [true, false], comm + ".silentCurse");519 520 if (checkType(action.cursedRole, ["string", "object"], comm + ".cursedRole")) {521 if (typeof action.cursedRole == "string") {522 checkValidRole(action.cursedRole, comm + ".cursedRole");523 } else {524 for (i in action.cursedRole) {525 checkValidRole(i, comm + ".cursedRole");526 if (checkType(action.cursedRole[i], ["array"], comm + ".cursedRole." + i)) {527 for (o in action.cursedRole[i]) {528 checkValidRole(action.cursedRole[i][o], comm + ".cursedRole." + i);529 }530 }531 }532 }533 }534 if (checkType(action.canCurse, ["string", "array"], comm + ".canCurse")) {535 if (typeof action.canCurse == "string") {536 checkValidValue(action.canCurse, ["*"], comm + ".canCurse");537 } else {538 for (i in action.canCurse) {539 checkValidRole(action.canCurse[i], comm + ".canCurse");540 }541 }542 }543 checkType(action.curseCount, ["number"], comm + ".curseCount");544 checkType(action.curseConvertMessage, ["string"], comm + ".curseConvertMessage");545 checkType(action.cursefailmsg, ["string"], comm + ".cursefailmsg");546 checkType(action.cursemsg, ["string"], comm + ".cursemsg");547 } else if (command == "detox") {548 checkType(action.msg, ["string"], comm + ".msg");549 checkType(action.targetmsg, ["string"], comm + ".targetmsg");550 checkType(action.detoxmsg, ["string"], comm + ".detoxmsg");551 checkType(action.detoxfailmsg, ["string"], comm + ".detoxfailmsg");552 } else if (command == "dispel") {553 checkType(action.msg, ["string"], comm + ".msg");554 checkType(action.targetmsg, ["string"], comm + ".targetmsg");555 checkType(action.dispelmsg, ["string"], comm + ".dispelmsg");556 checkType(action.dispelfailmsg, ["string"], comm + ".dispelfailmsg");557 } else if (command == "shield") {558 if (checkType(action.shieldActions, ["string", "array"], comm + ".shieldActions")) {559 if (typeof action.shieldActions === "string") {560 checkValidValue(action.shieldActions, ["*"], comm + ".shieldActions");561 }562 }563 checkType(action.shieldmsg, ["string"], comm + ".shieldmsg");564 } else if (command == "guard") {565 checkType(action.guardActions, ["array"], comm + ".guardActions");566 checkType(action.guardmsg, ["string"], comm + ".guardmsg");567 } else if (command == "dummy" || command == "dummy2" || command == "dummy3") {568 checkType(action[command + "usermsg"], ["string"], comm + "." + command + "usermsg");569 checkType(action[command + "targetmsg"], ["string"], comm + "." + command + "targetmsg");570 checkType(action[command + "broadcastmsg"], ["string"], comm + "." + command + "broadcastmsg");571 }572 }573 }574 }575 }576 if (checkType(role.actions.standby, ["object"], act + ".standby")) {577 for (e in role.actions.standby) {578 action = role.actions.standby[e];579 comm = act + ".standby." + e;580 if (checkType(action, ["object"], comm)) {581 possibleStandbyActions = ["kill", "reveal", "expose"];582 command = e;583 if (checkType(action.command, ["string"], comm + ".command")) {584 command = action.command;585 }586 if (command == "kill") {587 checkAttributes(action, ["target", "killmsg"], ["command", "limit", "msg", "revealChance", "revealmsg", "recharge", "initialrecharge", "charges", "chargesmsg", "clearCharges", "addCharges"], comm);588 589 checkValidValue(action.target, ["Any", "Self", "AnyButTeam", "AnyButRole", "AnyButSelf"], comm + ".target");590 checkType(action.limit, ["number"], comm + ".limit");591 checkType(action.msg, ["string"], comm + ".msg");592 checkType(action.killmsg, ["string"], comm + ".killmsg");593 checkType(action.revealChance, ["number"], comm + ".revealChance");594 checkType(action.revealmsg, ["string"], comm + ".revealmsg");595 checkType(action.recharge, ["number"], comm + ".recharge");596 checkType(action.initialrecharge, ["number"], comm + ".initialrecharge");597 checkType(action.charges, ["number"], comm + ".charges");598 checkType(action.chargesmsg, ["string"], comm + ".chargesmsg");599 checkType(action.clearCharges, ["boolean"], comm + ".clearCharges");600 checkType(action.addCharges, ["number"], comm + ".addCharges");601 } else if (command == "expose") {602 checkAttributes(action, ["target"], ["command", "limit", "msg", "exposemsg", "revealChance", "revealmsg", "recharge", "initialrecharge", "exposedtargetmsg", "charges", "chargesmsg", "clearCharges", "addCharges"], comm);603 604 checkValidValue(action.target, ["Any", "Self", "AnyButTeam", "AnyButRole", "AnyButSelf"], comm + ".target");605 checkType(action.limit, ["number"], comm + ".limit");606 checkType(action.msg, ["string"], comm + ".msg");607 checkType(action.exposemsg, ["string"], comm + ".exposemsg");608 checkType(action.exposedtargetmsg, ["string"], comm + ".exposedtargetmsg");609 checkType(action.revealChance, ["number"], comm + ".revealChance");610 checkType(action.revealmsg, ["string"], comm + ".revealmsg");611 checkType(action.recharge, ["number"], comm + ".recharge");612 checkType(action.initialrecharge, ["number"], comm + ".initialrecharge");613 checkType(action.charges, ["number"], comm + ".charges");614 checkType(action.chargesmsg, ["string"], comm + ".chargesmsg");615 checkType(action.clearCharges, ["boolean"], comm + ".clearCharges");616 checkType(action.addCharges, ["number"], comm + ".addCharges");617 } else if (command == "reveal") {618 checkAttributes(action, [], ["command", "limit", "msg", "revealmsg", "recharge", "initialrecharge", "charges", "chargesmsg", "clearCharges", "addCharges"], comm);619 620 checkType(action.limit, ["number"], comm + ".limit");621 checkType(action.msg, ["string"], comm + ".msg");622 checkType(action.revealmsg, ["string"], comm + ".revealmsg");623 checkType(action.recharge, ["number"], comm + ".recharge");624 checkType(action.initialrecharge, ["number"], comm + ".initialrecharge");625 checkType(action.charges, ["number"], comm + ".charges");626 checkType(action.chargesmsg, ["string"], comm + ".chargesmsg");627 checkType(action.clearCharges, ["boolean"], comm + ".clearCharges");628 checkType(action.addCharges, ["number"], comm + ".addCharges");629 } else {630 addMinorError("Role " + yourRole + "'s standby action \"" + e + "\" is not a valid action (Valid standby actions are " + possibleStandbyActions.join(", ") + ")");631 }632 }633 }634 }635 if (checkType(role.actions.hax, ["object"], act + ".hax")) {636 for (e in role.actions.hax) {637 comm = act + ".hax." + e;638 checkAttributes(role.actions.hax[e], [], ["revealTeam", "revealPlayer", "revealRole", "revealTarget"], comm);639 if (checkType(role.actions.hax[e], ["object"], comm)) {640 checkType(role.actions.hax[e].revealTeam, ["number"], comm + ".revealTeam");641 checkType(role.actions.hax[e].revealPlayer, ["number"], comm + ".revealPlayer");642 checkType(role.actions.hax[e].revealRole, ["number"], comm + ".revealRole");643 checkType(role.actions.hax[e].revealTarget, ["number"], comm + ".revealTarget");644 }645 }646 }647 if (checkType(role.actions.standbyHax, ["object"], act + ".standbyHax")) {648 for (e in role.actions.standbyHax) {649 comm = act + ".standbyHax." + e;650 checkAttributes(role.actions.standbyHax[e], [], ["revealTeam", "revealPlayer", "revealRole"], comm);651 if (checkType(role.actions.standbyHax[e], ["object"], comm)) {652 checkType(role.actions.standbyHax[e].revealTeam, ["number"], comm + ".revealTeam");653 checkType(role.actions.standbyHax[e].revealPlayer, ["number"], comm + ".revealPlayer");654 checkType(role.actions.standbyHax[e].revealRole, ["number"], comm + ".revealRole");655 }656 }657 }658 if (checkType(role.actions.onDeath, ["object"], act + ".onDeath")) {659 action = role.actions.onDeath;660 comm = act + ".onDeath";661 this.checkOnDeath(action, comm, ["onslay"]);662 }663 if (checkType(role.actions.onDeadRoles, ["object"], act + ".onDeadRoles")) {664 action = role.actions.onDeadRoles;665 comm = act + ".onDeadRoles";666 667 checkAttributes(action, ["convertTo"], ["convertmsg", "silentConvert"], comm);668 669 checkType(action.convertmsg, ["string"], comm + ".convertmsg");670 checkType(action.silentConvert, ["boolean"], comm + ".silentConvert");671 672 if (checkType(action.convertTo, ["object"], comm + ".convertTo")) {673 for (e in action.convertTo) {674 checkValidRole(e, comm + ".convertTo");675 if (checkType(action.convertTo[e], ["array"], comm + ".convertTo." + e)) {676 for (c in action.convertTo[e]) {677 checkValidRole(action.convertTo[e][c], comm + ".convertTo." + e);678 }679 }680 }681 }682 683 }684 if (checkType(role.actions.vote, ["number", "array"], act + ".vote")) {685 if (Array.isArray(role.actions.vote)) {686 for (e in role.actions.vote) {687 if (!checkType(role.actions.vote[e], ["number"], "All values for " + act + ".vote")) {688 break;689 }690 }691 }692 }693 if (checkType(role.actions.voteshield, ["number", "array"], act + ".voteshield")) {694 if (Array.isArray(role.actions.voteshield)) {695 for (e in role.actions.voteshield) {696 if (!checkType(role.actions.voteshield[e], ["number"], "All values for " + act + ".voteshield")) {697 break;698 }699 }700 }701 }702 if (checkType(role.actions.voteMultiplier, ["number", "array"], act + ".voteMultiplier")) {703 if (Array.isArray(role.actions.voteMultiplier)) {704 for (e in role.actions.voteMultiplier) {705 if (!checkType(role.actions.voteMultiplier[e], ["number"], "All values for " + act + ".voteMultiplier")) {706 break;707 }708 }709 }710 }711 if (checkType(role.actions.preventTeamvote, ["boolean", "array"], act + ".preventTeamvote")) {712 if (Array.isArray(role.actions.preventTeamvote)) {713 for (e in role.actions.preventTeamvote) {714 checkValidRole(role.actions.preventTeamvote[e], act + ".preventTeamvote");715 }716 }717 }718 checkType(role.actions.noVote, ["boolean"], act + ".noVote");719 checkType(role.actions.noVoteMsg, ["string"], act + ".noVoteMsg");720 721 //Defensive Modes722 for (e in possibleNightActions) {723 if (possibleNightActions[e] in role.actions && typeof role.actions[possibleNightActions[e]] !== "function") {724 command = possibleNightActions[e];725 action = role.actions[command];726 comm = act + "." + command;727 if (command == "inspect") {728 checkAttributes(action, [], ["mode", "seenSide", "revealSide", "revealAs", "msg", "targetmsg", "hookermsg", "evadechargemsg", "count", "poisonDeadMessage", "silent"], comm);729 730 checkValidValue(action.revealSide, [true, false], comm + ".revealSide");731 732 if (checkType(action.seenSide, ["string"], comm + ".seenSide")) {733 checkValidSide(action.seenSide, comm + ".seenSide");734 }735 736 if (checkType(action.revealAs, ["string", "array", "number"], comm + ".revealAs")) {737 if (typeof action.revealAs == "string") {738 if (action.revealAs !== "*") {739 checkValidRole(action.revealAs, comm + ".revealAs");740 }741 } else if (Array.isArray(action.revealAs)) {742 for (e in action.revealAs) {743 checkValidRole(action.revealAs[e], comm + ".revealAs");744 }745 }746 }747 } else {748 requiredAtt = [];749 if ("mode" in action && typeof action.mode == "object" && "killif" in action.mode) {750 requiredAtt = ["msg"];751 }752 checkAttributes(action, [].concat(requiredAtt), ["mode", "msg", "targetmsg", "hookermsg", "evadechargemsg", "count", "poisonDeadMessage", "rate", "constant", "silent", "identifymsg"], comm);753 }754 if (checkType(action.mode, ["string", "object"], comm + ".mode")) {755 mode = action.mode;756 if (typeof mode == "string") {757 extraModes = [];758 759 if (command === "stalk") {760 extraModes.push("noVisit");761 }762 if (command === "poison" || command == "curse") {763 extraModes.push("resistance");764 }765 766 checkValidValue(mode, ["ignore", "ChangeTarget", "killattacker", "killattackerevenifprotected", "poisonattacker", "poisonattackerevenifprotected", "identify", "die"].concat(extraModes), comm + ".mode");767 } else if (typeof mode == "object") {768 checkAttributes(action.mode, [], ["evadeCharges", "evadeChance", "ignore", "killif", "identify"], comm + ".mode");769 770 if (checkType(mode.evadeCharges, ["number", "string"], comm + ".mode.evadeCharges")) {771 if (typeof mode.evadeCharges == "string") {772 checkValidValue(mode.evadeCharges, ["*"], comm + ".mode.evadeCharges");773 }774 }775 checkType(mode.evadeChance, ["number"], comm + ".mode.evadeChance");776 777 if (checkType(mode.ignore, ["array"], comm + ".mode.ignore")) {778 for (e in mode.ignore) {779 checkValidRole(mode.ignore[e], comm + ".mode.ignore");780 }781 }782 if (checkType(mode.killif, ["array"], comm + ".mode.killif")) {783 for (e in mode.killif) {784 checkValidRole(mode.killif[e], comm + ".mode.killif");785 }786 }787 if (checkType(mode.identify, ["array"], comm + ".mode.identify")) {788 for (e in mode.identify) {789 checkValidRole(mode.identify[e], comm + ".mode.identify");790 }791 }792 }793 }794 795 checkType(action.msg, ["string"], comm + ".msg");796 checkType(action.hookermsg, ["string"], comm + ".hookermsg");797 checkType(action.targetmsg, ["string"], comm + ".targetmsg");798 checkType(action.evadechargemsg, ["string"], comm + ".evadechargemsg");799 checkType(action.poisonDeadMessage, ["string"], comm + ".poisonDeadMessage");800 checkType(action.count, ["number"], comm + ".count");801 checkType(action.rate, ["number"], comm + ".rate");802 checkType(action.constant, ["number"], comm + ".constant");803 checkValidValue(action.silent, [true, false], comm + ".silent");804 }805 }806 if (checkType(role.actions.daykill, ["object", "string"], act + ".daykill")) {807 action = role.actions.daykill;808 comm = act + ".daykill";809 810 if (checkType(action, ["string", "object"], comm)) {811 if (typeof action == "string") {812 checkValidValue(action, ["evade", "revenge", "bomb", "revealkiller"], comm);813 } else {814 checkAttributes(action, ["mode"], ["msg", "targetmsg", "expend"], comm);815 if (checkType(action.mode, ["object"], comm + ".mode")) {816 checkAttributes(action.mode, [], ["evadeCharges", "evadeChance", "ignore", "revenge", "evasionmsg"], comm + ".mode");817 818 checkType(action.mode.evadeChance, ["number"], comm + ".mode.evadeChance");819 820 if (checkType(action.mode.evadeCharges, ["number", "string"], comm + ".mode.evadeCharges")) {821 if (typeof action.mode.evadeCharges == "string") {822 checkValidValue(action.mode.evadeCharges, ["*"], comm + ".mode.evadeCharges");823 }824 }825 if (checkType(action.mode.ignore, ["array"], comm + ".mode.ignore")) {826 for (i in action.mode.ignore) {827 checkValidRole(action.mode.ignore[i], comm + ".mode.ignore");828 }829 }830 if (checkType(action.mode.revenge, ["array"], comm + ".mode.revenge")) {831 for (i in action.mode.revenge) {832 checkValidRole(action.mode.revenge[i], comm + ".mode.revenge");833 }834 }835 checkType(action.mode.evasionmsg, ["string"], comm + ".mode.evasionmsg");836 }837 838 checkType(action.expend, ["boolean"], comm + ".expend");839 checkType(action.msg, ["string"], comm + ".msg");840 checkType(action.targetmsg, ["string"], comm + ".targetmsg");841 }842 }843 }844 if (checkType(role.actions.daykillevademsg, ["string"], act + ".daykillevademsg")) {845 if (!("daykill" in role.actions)) {846 addMinorError("'daykillevademsg' found at " + act + ", but there's no '" + act + ".daykill'");847 }848 }849 if (checkType(role.actions.daykillrevengemsg, ["string"], act + ".daykillrevengemsg")) {850 if (!("daykill" in role.actions)) {851 addMinorError("'daykillrevengemsg' found at " + act + ", but there's no '" + act + ".daykill'");852 }853 }854 if (checkType(role.actions.daykillmissmsg, ["string"], act + ".daykillmissmsg")) {855 if (!("daykill" in role.actions)) {856 addMinorError("'daykillmissmsg' found at " + act + ", but there's no '" + act + ".daykill'");857 }858 }859 if (checkType(role.actions.expose, ["object", "string"], act + ".expose")) {860 action = role.actions.expose;861 comm = act + ".expose";862 863 if (typeof action == "string") {864 checkValidValue(action, ["evade", "die", "revenge", "revealexposer"], comm);865 } else if (typeof action == "object") {866 checkAttributes(action, ["mode"], ["msg", "targetmsg", "expend"], comm);867 if (checkType(action.mode, ["object"], comm + ".mode")) {868 checkAttributes(action.mode, [], ["evadeCharges", "evadeChance", "ignore", "revenge", "evasionmsg"], comm + ".mode");869 870 checkType(action.mode.evadeChance, ["number"], comm + ".mode.evadeChance");871 872 if (checkType(action.mode.evadeCharges, ["number", "string"], comm + ".mode.evadeCharges")) {873 if (typeof action.mode.evadeCharges == "string") {874 checkValidValue(action.mode.evadeCharges, ["*"], comm + ".mode.evadeCharges");875 }876 }877 if (checkType(action.mode.ignore, ["array"], comm + ".mode.ignore")) {878 for (i in action.mode.ignore) {879 checkValidRole(action.mode.ignore[i], comm + ".mode.ignore");880 }881 }882 if (checkType(action.mode.revenge, ["array"], comm + ".mode.revenge")) {883 for (i in action.mode.revenge) {884 checkValidRole(action.mode.revenge[i], comm + ".mode.revenge");885 }886 }887 888 checkType(action.mode.evasionmsg, ["string"], comm + ".mode.evasionmsg");889 }890 checkType(action.expend, ["boolean"], comm + ".expend");891 checkType(action.msg, ["string"], comm + ".msg");892 checkType(action.targetmsg, ["string"], comm + ".targetmsg");893 }894 }895 if (checkType(role.actions.revealexposermsg, ["string"], act + ".revealexposermsg")) {896 if (!("expose" in role.actions)) {897 addMinorError("'revealexposermsg' found at " + act + ", but there's no '" + act + ".expose'");898 }899 }900 if (checkType(role.actions.exposerevengemsg, ["string"], act + ".exposerevengemsg")) {901 if (!("expose" in role.actions)) {902 addMinorError("'exposerevengemsg' found at " + act + ", but there's no '" + act + ".expose'");903 }904 }905 if (checkType(role.actions.exposeevademsg, ["string"], act + ".exposeevademsg")) {906 if (!("expose" in role.actions)) {907 addMinorError("'exposeevademsg' found at " + act + ", but there's no '" + act + ".expose'");908 }909 }910 if (checkType(role.actions.exposemissmsg, ["string"], act + ".exposemissmsg")) {911 if (!("expose" in role.actions)) {912 addMinorError("'exposemissmsg' found at " + act + ", but there's no '" + act + ".expose'");913 }914 }915 if (checkType(role.actions.exposediemsg , ["string"], act + ".exposediemsg ")) {916 if (!("expose" in role.actions)) {917 addMinorError("'exposediemsg ' found at " + act + ", but there's no '" + act + ".expose'");918 }919 }920 if (checkType(role.actions.avoidHax, ["array"], act + ".avoidHax")) {921 action = role.actions.avoidHax;922 if (checkType(action, ["array"], act + ".avoidHax")) {923 for (e in action) {924 if (!checkType(action[e], ["string"], "All values for " + act + ".avoidHax")) {925 break;926 }927 }928 }929 }930 if (checkType(role.actions.avoidStandbyHax, ["array"], act + ".avoidStandbyHax")) {931 action = role.actions.avoidStandbyHax;932 if (checkType(action, ["array"], act + ".avoidStandbyHax")) {933 for (e in action) {934 if (!checkType(action[e], ["string"], "All values for " + act + ".avoidStandbyHax")) {935 break;936 }937 }938 }939 }940 if (checkType(role.actions.initialCondition, ["object"], act + ".initialCondition")) {941 action = role.actions.initialCondition;942 comm = act + ".initialCondition";943 944 checkAttributes(action, [], ["poison", "clearPoison", "curse", "clearCurse"], comm);945 946 if (checkType(action.poison, ["object"], comm + ".poison")) {947 checkAttributes(action.poison, [], ["count", "poisonDeadMessage"], comm + ".poison");948 checkType(action.poison.count, ["number"], comm + ".poison.count");949 checkType(action.poison.poisonDeadMessage, ["string"], comm + ".poison.poisonDeadMessage");950 }951 952 checkValidValue(action.clearPoison, [true, false], comm + ".clearPoison");953 954 if (checkType(action.curse, ["object"], comm + ".curse")) {955 checkAttributes(action.curse, ["cursedRole"], ["curseCount", "curseConvertMessage", "silentCurse"], comm + ".curse");956 957 if (checkType(action.curse.cursedRole, ["string"], comm + ".curse.cursedRole")) {958 checkValidRole(action.curse.cursedRole, comm + ".curse.cursedRole");959 }960 checkType(action.curse.curseCount, ["number"], comm + ".curse.curseCount");961 checkType(action.curse.curseConvertMessage, ["string"], comm + ".curse.curseConvertMessage");962 checkType(action.curse.silentCurse, ["boolean"], comm + ".curse.silentCurse");963 }964 965 checkValidValue(action.clearCurse, [true, false], comm + ".clearCurse");966 }967 if (checkType(role.actions.startup, ["string", "object"], act + ".startup")) {968 action = role.actions.startup;969 comm = act + ".startup";970 971 if (typeof action == "string") {972 checkValidValue(action, ["team-reveal", "role-reveal", "team-reveal-with-roles"], act + ".startup");973 } else if (typeof action == "object") {974 checkAttributes(action, [], ["revealRole", "team-revealif", "team-revealif-with-roles", "revealAs", "revealPlayers", "revealPlayersMsg"], act + ".startup");975 976 if (checkType(action.revealAs, ["string"], comm + ".revealAs")){977 checkValidRole(action.revealAs, comm + ".revealAs");978 }979 980 if (checkType(action.revealRole, ["string", "array"], comm + ".revealRole")) {981 if (typeof action.revealRole == "string") {982 checkValidRole(action.revealRole, comm + ".revealRole");983 } else if (Array.isArray(action.revealRole)) {984 for (e in action.revealRole) {985 checkValidRole(action.revealRole[e], comm + ".revealRole");986 }987 }988 }989 990 if (checkType(action.revealPlayers, ["string", "array"], comm + ".revealPlayers")) {991 if (typeof action.revealPlayers == "string") {992 checkValidRole(action.revealPlayers, comm + ".revealPlayers");993 } else if (Array.isArray(action.revealPlayers)) {994 for (e in action.revealPlayers) {995 checkValidRole(action.revealPlayers[e], comm + ".revealPlayers");996 }997 }998 }999 checkType(action.revealPlayersMsg, ["string"], comm + ".revealPlayersMsg");1000 1001 if (checkType(action["team-revealif"], ["array"], comm + ".team-revealif")) {1002 for (e in action["team-revealif"]) {1003 checkValidSide(action["team-revealif"][e], comm + ".team-revealif");1004 }1005 }1006 1007 if (checkType(action["team-revealif-with-roles"], ["array"], comm + ".team-revealif-with-roles")) {1008 for (e in action["team-revealif-with-roles"]) {1009 checkValidSide(action["team-revealif-with-roles"][e], comm + ".team-revealif-with-roles");1010 }1011 }1012 }1013 }1014 1015 checkType(role.actions.updateCharges, ["boolean"], act + ".updateCharges");1016 checkType(role.actions.updateTeam, ["boolean"], act + ".updateTeam");1017 checkType(role.actions.teamUtilities, ["boolean"], act + ".teamUtilities");1018 1019 if (checkType(role.actions.onlist, ["string"], act + ".onlist")) {1020 checkValidRole(role.actions.onlist, act + ".onlist");1021 }1022 if (checkType(role.actions.onteam, ["string"], act + ".onteam")) {1023 checkValidRole(role.actions.onteam, act + ".onteam");1024 }1025 if (checkType(role.actions.lynch, ["object"], act + ".lynch")) {1026 action = role.actions.lynch;1027 comm = act + ".lynch";1028 var lynchActions = ["revealAs", "convertTo", "convertmsg", "lynchmsg", "killVoters", "convertVoters"];1029 this.checkOnDeath(action, comm, lynchActions, true);1030 1031 if (checkType(action.revealAs, ["string"], comm + ".revealAs")) {1032 checkValidRole(role.actions.lynch.revealAs, comm + ".revealAs");1033 }1034 if (checkType(action.convertTo, ["string"], comm + ".convertTo")) {1035 checkValidRole(role.actions.lynch.convertTo, comm + ".convertTo");1036 }1037 if (checkType(action.lynchmsg, ["string"], comm + ".lynchmsg")) {1038 if (!("convertTo" in action)) {1039 addMinorError("'lynchmsg' found at " + comm + ", but there's no '" + comm + ".convertTo'");1040 }1041 }1042 if (checkType(action.killVoters, ["object"], comm + ".killVoters")) {1043 checkAttributes(action.killVoters, [], ["first", "last", "message"], comm + ".killVoters");1044 1045 checkType(action.killVoters.first, ["number"], comm + ".killVoters.first");1046 checkType(action.killVoters.last, ["number"], comm + ".killVoters.last");1047 checkType(action.killVoters.message, ["string"], comm + ".killVoters.message");1048 }1049 if (checkType(action.convertVoters, ["object"], comm + ".convertVoters")) {1050 checkAttributes(action.convertVoters, ["newRole"], ["first", "last", "message"], comm + ".convertVoters");1051 1052 if (checkType(action.convertVoters.newRole, ["object"], comm + ".convertVoters.newRole")) {1053 for (e in action.convertVoters.newRole) {1054 checkValidRole(e, comm + ".convertVoters.newRole");1055 if (checkType(action.convertVoters.newRole[e], ["array"], comm + ".convertVoters.newRole." + e)) {1056 for (i in action.convertVoters.newRole[e]) {1057 checkValidRole(action.convertVoters.newRole[e][i], comm + ".convertVoters.newRole." + e);1058 }1059 }1060 }1061 }1062 checkType(action.convertVoters.first, ["number"], comm + ".convertVoters.first");1063 checkType(action.convertVoters.last, ["number"], comm + ".convertVoters.last");1064 checkType(action.convertVoters.message, ["string"], comm + ".convertVoters.message");1065 }1066 }1067 if (checkType(role.actions.teamTalk, ["boolean", "array"], act + ".teamTalk")) {1068 if (Array.isArray(role.actions.teamTalk)) {1069 action = role.actions.teamTalk;1070 for (e in action) {1071 checkValidRole(action[e], act + ".teamTalk");1072 }1073 }1074 }1075 }1076 }1077 };1078 Theme.prototype.checkOnDeath = function(action, comm, extra, isLynch) {1079 var e;1080 1081 checkAttributes(action, [], ["killRoles", "poisonRoles", "convertRoles", "curseRoles", "exposeRoles", "killmsg", "convertmsg", "curseCount", "cursemsg", "curseConvertMessage", "poisonmsg", "poisonDeadMessage", "exposemsg", "singlekillmsg", "singlepoisonmsg", "singleconvertmsg", "singlecursemsg", "silentConvert", "silentCurse"].concat(extra), comm);1082 1083 checkType(action.onslay, ["boolean"], comm + ".onslay");1084 1085 /* onDeath.killRoles related attributes */1086 if (checkType(action.killRoles, ["array"], comm + ".killRoles")) {1087 for (e in action.killRoles) {1088 checkValidRole(action.killRoles[e], comm + ".killRoles");1089 }1090 }1091 1092 if (checkType(action.killmsg, ["string"], comm + ".killmsg")) {1093 if (!("killRoles" in action)) {1094 addMinorError("'killmsg' found at " + comm + ", but there's no 'killRoles'");1095 }1096 }1097 if (checkType(action.singlekillmsg, ["string"], comm + ".singlekillmsg")) {1098 if (!("killRoles" in action)) {1099 addMinorError("'singlekillmsg' found at " + comm + ", but there's no 'singlekillmsg'");1100 }1101 if ("killmsg" in action) {1102 addMinorError(comm + " has both 'killmsg' and 'singlekillmsg', so 'killmsg' won't be used");1103 }1104 }1105 1106 /* onDeath.poisonRoles related attributes */1107 if (checkType(action.poisonRoles, ["object"], comm + ".poisonRoles")) {1108 for (e in action.poisonRoles) {1109 checkValidRole(e, comm + ".poisonRoles");1110 checkType(action.poisonRoles[e], ["number"], comm + ".poisonRoles." + e);1111 }1112 }1113 if (checkType(action.poisonDeadMessage, ["string"], comm + ".poisonDeadMessage")) {1114 if (!("poisonRoles" in action)) {1115 addMinorError("'poisonDeadMessage' found at " + comm + ", but there's no 'poisonRoles'");1116 }1117 }1118 if (checkType(action.poisonmsg, ["string"], comm + ".poisonmsg")) {1119 if (!("poisonRoles" in action)) {1120 addMinorError("'poisonmsg' found at " + comm + ", but there's no 'poisonRoles'");1121 }1122 }1123 if (checkType(action.singlepoisonmsg, ["string"], comm + ".singlepoisonmsg")) {1124 if (!("poisonRoles" in action)) {1125 addMinorError("'singlepoisonmsg' found at " + comm + ", but there's no 'singlepoisonmsg'");1126 }1127 if ("poisonmsg" in action) {1128 addMinorError(comm + " has both 'poisonmsg' and 'singlepoisonmsg', so 'poisonmsg' won't be used");1129 }1130 }1131 1132 /* onDeath.convertRoles related attributes */1133 if (checkType(action.convertRoles, ["object"], comm + ".convertRoles")) {1134 for (e in action.convertRoles) {1135 checkValidRole(e, comm + ".convertRoles");1136 checkValidRole(action.convertRoles[e], comm + ".convertRoles." + e);1137 }1138 }1139 if (checkType(action.convertmsg, ["string"], comm + ".convertmsg")) {1140 if (!("convertRoles" in action) && (!isLynch || !("convertTo" in action))) {1141 addMinorError("'convertmsg' found at " + comm + ", but there's no 'convertRoles'" + (isLynch ? " or 'convertTo'" : ""));1142 }1143 }1144 if (checkType(action.singleconvertmsg, ["string"], comm + ".singleconvertmsg")) {1145 if (!("convertRoles" in action)) {1146 addMinorError("'singleconvertmsg' found at " + comm + ", but there's no 'singleconvertmsg'");1147 }1148 if ("convertmsg" in action) {1149 addMinorError(comm + " has both 'convertmsg' and 'singleconvertmsg', so 'convertmsg' won't be used");1150 }1151 }1152 checkType(action.silentConvert, ["boolean"], comm + ".silentConvert");1153 1154 /* onDeath.curseRoles related attributes */1155 if (checkType(action.curseRoles, ["object"], comm + ".curseRoles")) {1156 for (e in action.curseRoles) {1157 checkValidRole(e, comm + ".curseRoles");1158 checkValidRole(action.curseRoles[e], comm + ".curseRoles." + e);1159 }1160 }1161 if (checkType(action.curseCount, ["number"], comm + ".curseCount")) {1162 if (!("curseRoles" in action)) {1163 addMinorError("'curseCount' found at " + comm + ", but there's no 'curseRoles'");1164 }1165 }1166 if (checkType(action.curseConvertMessage, ["string"], comm + ".curseConvertMessage")) {1167 if (!("curseRoles" in action)) {1168 addMinorError("'curseConvertMessage' found at " + comm + ", but there's no 'curseRoles'");1169 }1170 }1171 if (checkType(action.cursemsg, ["string"], comm + ".cursemsg")) {1172 if (!("curseRoles" in action)) {1173 addMinorError("'cursemsg' found at " + comm + ", but there's no 'curseRoles'");1174 }1175 }1176 if (checkType(action.singlecursemsg, ["string"], comm + ".singlecursemsg")) {1177 if (!("curseRoles" in action)) {1178 addMinorError("'singlecursemsg' found at " + comm + ", but there's no 'singlecursemsg'");1179 }1180 if ("cursemsg" in action) {1181 addMinorError(comm + " has both 'cursemsg' and 'singlecursemsg', so 'cursemsg' won't be used");1182 }1183 }1184 checkType(action.silentCurse, ["boolean"], comm + ".silentCurse");1185 1186 /* onDeath.exposeRoles related attributes */1187 if (checkType(action.exposeRoles, ["array"], comm + ".exposeRoles")) {1188 for (e in action.exposeRoles) {1189 checkValidRole(action.exposeRoles[e], comm + ".exposeRoles");1190 }1191 }1192 if (checkType(action.exposemsg, ["string"], comm + ".exposemsg")) {1193 if (!("exposeRoles" in action)) {1194 addMinorError("'exposemsg' found at " + comm + ", but there's no 'exposeRoles'");1195 }1196 }1197 };1198 Theme.prototype.checkActions = function() {1199 var r, e, i, role, act;1200 var night = [], standby = [];1201 for (r in this.roles) {1202 role = this.roles[r];1203 if ("night" in role.actions) {1204 for (e in role.actions.night) {1205 if (night.indexOf(e) == -1) {1206 night.push(e);1207 }1208 if (badCommands.indexOf(e.toLowerCase()) !== -1) {1209 addMinorError("Command '" + e + "' found at " + role.role + ".actions.night is not advised as it's a channel/server command." );1210 }1211 }1212 }1213 if ("standby" in role.actions) {1214 for (e in role.actions.standby) {1215 if (standby.indexOf(e) == -1) {1216 standby.push(e);1217 }1218 if (badCommands.indexOf(e.toLowerCase()) !== -1) {1219 addMinorError("Command '" + e + "' found at " + role.role + ".actions.standby is not advised as it's a channel/server command." );1220 }1221 }1222 }1223 }1224 for (r in this.roles) {1225 role = this.roles[r];1226 if ("night" in role.actions) {1227 for (e in role.actions.night) {1228 if ("cancel" in role.actions.night[e]) {1229 act = role.actions.night[e].cancel;1230 for (i in act) {1231 if (night.indexOf(act[i]) == -1) {1232 addMinorError("Your role <b>" + r + "</b> has an invalid command " + act[i] + " night action " + e + ".cancel.");1233 }1234 }1235 }1236 if ("restrict" in role.actions.night[e]) {1237 act = role.actions.night[e].restrict;1238 for (i in act) {1239 if (night.indexOf(act[i]) == -1) {1240 addMinorError("Your role <b>" + r + "</b> has an invalid command " + act[i] + " night action " + e + ".restrict.");1241 }1242 }1243 }1244 }1245 }1246 if ("hax" in role.actions) {1247 for (e in role.actions.hax) {1248 if (night.indexOf(e) == -1) {1249 addMinorError("Your role <b>" + r + "</b> gets hax on an inexistent " + e + " night action.");1250 }1251 }1252 }1253 if ("avoidHax" in role.actions) {1254 for (e in role.actions.avoidHax) {1255 if (!("night" in role.actions) || !(role.actions.avoidHax[e] in role.actions.night)) {1256 addMinorError("Your role <b>" + r + "</b> avoids hax from an inexistent " + role.actions.avoidHax[e] + " night action.");1257 }1258 }1259 }1260 if ("standbyHax" in role.actions) {1261 for (e in role.actions.standbyHax) {1262 if (standby.indexOf(e) == -1) {1263 addMinorError("Your role <b>" + r + "</b> gets hax on an inexistent " + e + " standby action.");1264 }1265 }1266 }1267 if ("avoidStandbyHax" in role.actions) {1268 for (e in role.actions.avoidStandbyHax) {1269 if (!("standby" in role.actions) || !(role.actions.avoidStandbyHax[e] in role.actions.standby)) {1270 addMinorError("Your role <b>" + r + "</b> avoids hax from an inexistent " + role.actions.avoidStandbyHax[e] + " standby action.");1271 }1272 }1273 }1274 }1275 };1276 function isRole(role) {1277 return role in theme.roles;1278 }1279 function isSide(side) {1280 return side in theme.sideTranslations;1281 }1282 function checkValidSide(side, what) {1283 if (!isSide(side)) {1284 if (theme.lowerCaseSides.indexOf(side.toLowerCase()) !== -1) {1285 addFatalError("Invalid side \"" + side + "\" found in " + what + ". Did you mean '" + theme.correctSides[theme.lowerCaseSides.indexOf(side.toLowerCase())] + "'?");1286 } else {1287 addFatalError("Invalid side \"" + side + "\" found in " + what + ". ");1288 }1289 }1290 }1291 function checkValidRole(role, what) {1292 if (!isRole(role)) {1293 if (theme.lowerCaseRoles.indexOf(role.toLowerCase()) !== -1) {1294 addFatalError("Invalid role \"" + role + "\" found in " + what + ". Did you mean '" + theme.correctRoles[theme.lowerCaseRoles.indexOf(role.toLowerCase())] + "'?");1295 } else {1296 addFatalError("Invalid role \"" + role + "\" found in " + what + ". ");1297 }1298 }1299 }1300 function checkValidValue(attr, valid, msg) {1301 if (attr === undefined) {1302 return false;1303 }1304 var fullValid = valid.concat();1305 if (valid.indexOf(true) !== -1) {1306 fullValid.push("true");1307 }1308 if (valid.indexOf(false) !== -1) {1309 fullValid.push("false");1310 }1311 if (fullValid.indexOf(attr) === -1) {1312 addMinorError("Invalid value '" + attr + "' found at " + msg + " (Valid values are " + valid.join(", ") + ")");1313 return false;1314 }1315 return true;1316 }1317 function checkType(atr, types, what) {1318 if (atr === undefined) {1319 return false;1320 }1321 if (types.indexOf(typeof atr) !== -1) {1322 return true;1323 }1324 if (types.indexOf("array") !== -1 && Array.isArray(atr)) {1325 return true;1326 }1327 addFatalError(what + " must be a valid " + readable(types, "or") + ".");1328 return false;1329 }1330 function checkAttributes(obj, mandatory, optional, what) {1331 var e;1332 var correct = mandatory.concat(optional);1333 var lower = correct.map(function(x) { return x.toLowerCase(); });1334 if (typeof obj == "object") {1335 for (e in mandatory) {1336 if (!(mandatory[e] in obj)) {1337 addFatalError(what + ' is missing the attribute "' + mandatory[e] + '".');1338 }1339 }1340 for (e in obj) {1341 if (mandatory.indexOf(e) == -1 && optional.indexOf(e) == -1) {1342 if (lower.indexOf(e.toLowerCase()) !== -1) {1343 addMinorError('Attribute "' + e + '" for "' + what + '" should be written as "' + correct[lower.indexOf(e.toLowerCase())]+ '".');1344 } else {1345 addMinorError(what + ' has an extra attribute "' + e + '".');1346 }1347 }1348 }1349 } else {1350 addFatalError(what + ' is not a valid object.');1351 }1352 }1353 function commonNightActions(yourRole, action, command) {1354 var act = yourRole + ".night." + command, c;1355 1356 checkValidValue(action.target, ["Any", "Self", "AnyButTeam", "AnyButRole", "AnyButSelf", "OnlySelf", "OnlyTeam", "OnlyTeammates"], act + ".target");1357 checkValidValue(action.common, ["Self", "Team", "Role"], act + ".common");1358 checkType(action.priority, ["number"], act + ".priority");1359 if (checkType(action.broadcast, ["string", "array"], act + ".broadcast")) {1360 if (Array.isArray(action.broadcast)) {1361 for (var e in action.broadcast) {1362 checkValidRole(action.broadcast[e], act + ".broadcast");1363 }1364 } else {1365 checkValidValue(action.broadcast, ["none", "team", "role", "all", "*"], act + ".broadcast");1366 }1367 }1368 1369 if (checkType(action.command, ["string", "array", "object"], act + ".command")) {1370 if (Array.isArray(action.command)) {1371 for (c in action.command) {1372 checkValidValue(action.command[c], possibleNightActions, act + ".command");1373 }1374 } else if (typeof action.command === "object") {1375 for (c in action.command) {1376 checkValidValue(c, possibleNightActions, act + ".command");1377 }1378 } else if (typeof action.command === "string") {1379 checkValidValue(action.command, possibleNightActions, act + ".command");1380 }1381 } else {1382 checkValidValue(command, possibleNightActions, yourRole + ".night");1383 }1384 checkType(action.limit, ["number"], act + ".limit");1385 checkType(action.failChance, ["number"], act + ".failChance");1386 checkType(action.recharge, ["number"], act + ".recharge");1387 checkType(action.initialrecharge, ["number"], act + ".initialrecharge");1388 checkType(action.broadcastmsg, ["string"], act + ".broadcastmsg");1389 checkType(action.charges, ["number"], act + ".charges");1390 checkType(action.chargesmsg, ["string"], act + ".chargesmsg");1391 checkType(action.clearCharges, ["boolean"], act + ".clearCharges");1392 checkType(action.addCharges, ["number"], act + ".addCharges");1393 checkType(action.suicideChance, ["number"], act + ".suicideChance");1394 checkType(action.suicidemsg, ["string"], act + ".suicidemsg");1395 checkType(action.restrict, ["array"], act + ".restrict");1396 checkType(action.cancel, ["array"], act + ".cancel");1397 checkType(action.pierce, ["boolean"], act + ".pierce");1398 checkType(action.pierceChance, ["number"], act + ".pierceChance");1399 checkType(action.haxMultiplier, ["number"], act + ".haxMultiplier");1400 checkType(action.noFollow, ["boolean"], act + ".noFollow");1401 checkType(action.userMustBeVisited, ["boolean"], act + ".userMustBeVisited");1402 checkType(action.targetMustBeVisited, ["boolean"], act + ".targetMustBeVisited");1403 checkType(action.targetMustVisit, ["boolean"], act + ".targetMustVisit");1404 checkType(action.userMustVisit, ["boolean"], act + ".userMustVisit");1405 if (checkType(action.bypass, ["array"], act + ".bypass")) {1406 for (c in action.bypass) {1407 checkValidValue(action.bypass[c], ["ignore", "ChangeTarget", "killattacker", "poisonattacker", "identify", "die", "evadeChance", "evadeCharges", "killif", "resistance"], act + ".bypass");1408 }1409 }1410 }1411 function addMinorError(msg) {1412 minorErrors.push(msg);1413 noMinor = false;1414 }1415 function addFatalError(msg) {1416 fatalErrors.push(msg);1417 noFatal = false;1418 }1419 function cap(string) {...
types-test.js
Source:types-test.js
...42 jelAssert.equal('OptionType([any, null])', new OptionType(new List([AnyType.instance, null])));43 jelAssert.equal('OptionalType(any)', new OptionalType(AnyType.instance));44 });45 it('checks non-db types', function() {46 jelAssert.fuzzy('any.checkType(1)', 1);47 jelAssert.fuzzy('any?.checkType(null)', 1);48 jelAssert.fuzzy('any.checkType(null)', 0);49 jelAssert.fuzzy('any.checkType("a")', 1);50 jelAssert.fuzzy('string.checkType(1)', 0);51 jelAssert.fuzzy('string.checkType(null)', 0);52 jelAssert.fuzzy('string.checkType("a")', 1);53 jelAssert.fuzzy('string.checkType("")', 0);54 jelAssert.fuzzy('int.checkType(1)', 1);55 jelAssert.fuzzy('int.checkType(1.1)', 0);56 jelAssert.fuzzy('int.checkType(null)', 0);57 jelAssert.fuzzy('int.checkType("a")', 0);58 jelAssert.fuzzy('int.checkType(15/5)', 1);59 jelAssert.fuzzy('int.checkType(15/4)', 0);60 jelAssert.fuzzy('int(2...3).checkType(2)', 1);61 jelAssert.fuzzy('int(2...3).checkType(3)', 1);62 jelAssert.fuzzy('int(2...3).checkType(4)', 0);63 jelAssert.fuzzy('int(1...10).checkType(4)', 1);64 jelAssert.fuzzy('number.checkType(1)', 1);65 jelAssert.fuzzy('number.checkType(1.1)', 1);66 jelAssert.fuzzy('number.checkType(null)', 0);67 jelAssert.fuzzy('number.checkType("a")', 0);68 jelAssert.fuzzy('number.checkType(15/5)', 1);69 jelAssert.fuzzy('number.checkType(15/4)', 1);70 jelAssert.fuzzy('number(2...3).checkType(2)', 1);71 jelAssert.fuzzy('number(2...3).checkType(2.5)', 1);72 jelAssert.fuzzy('number(2...3).checkType(3)', 1);73 jelAssert.fuzzy('number(2...3).checkType(17/8)', 1);74 jelAssert.fuzzy('number(2...3).checkType(7/8)', 0);75 jelAssert.fuzzy('number(1...10).checkType(4)', 1);76 77 jelAssert.fuzzy('numeric.checkType(2)', 1);78 jelAssert.fuzzy('numeric(2...3).checkType(2.5)', 1);79 jelAssert.fuzzy('numeric(2...3).checkType(ApproximateNumber(2.4))', 1);80 jelAssert.fuzzy('numeric(2...3).checkType(17/8)', 1);81 jelAssert.fuzzy('numeric(2...3).checkType(7/8)', 0);82 jelAssert.fuzzy('numeric(1...10).checkType(4)', 1);83 jelAssert.fuzzy('InRangeType(2...3).checkType(2.5)', 1);84 jelAssert.fuzzy('InRangeType(2...3).checkType(3)', 1);85 jelAssert.fuzzy('InRangeType(2...3).checkType(4)', 0);86 jelAssert.fuzzy('InRangeType(1...10).checkType(4)', 1);87 jelAssert.fuzzy('bool.checkType(true)', 1);88 jelAssert.fuzzy('bool.checkType(1.1)', 0);89 jelAssert.fuzzy('bool.checkType(null)', 0);90 jelAssert.fuzzy('bool.checkType("a")', 0);91 jelAssert.fuzzy('bool.checkType(false)', 1);92 jelAssert.fuzzy('SimpleType(Float).checkType(2)', 1);93 jelAssert.fuzzy('SimpleType(Float).checkType(null)', 0);94 jelAssert.fuzzy('SimpleType(Float).checkType("x")', 0);95 jelAssert.fuzzy('SimpleType("Float").checkType(2)', 1);96 jelAssert.fuzzy('SimpleType("Float").checkType(null)', 0);97 jelAssert.fuzzy('SimpleType("Float").checkType("x")', 0);98 jelAssert.fuzzy('ComplexType({b: number}).checkType({b: 2})', 1);99 jelAssert.fuzzy('ComplexType({b: number}).checkType({b: 2, x: 1})', 1);100 jelAssert.fuzzy('ComplexType({b: number}).checkType({b: "d"})', 0);101 jelAssert.fuzzy('ComplexType({b: number}).checkType({a: 2})', 0);102 jelAssert.fuzzy('ComplexType({b: number}).checkType(2)', 0);103 jelAssert.fuzzy('ListType(number).checkType([1,2,3])', 1);104 jelAssert.fuzzy('ListType(number).checkType([])', 1);105 jelAssert.fuzzy('ListType(number).checkType([1, "a"])', 0);106 jelAssert.fuzzy('ListType(number).checkType("a")', 0);107 jelAssert.fuzzy('Float[].checkType([1,2,3])', 1);108 jelAssert.fuzzy('Float[].checkType([])', 1);109 jelAssert.fuzzy('Float[].checkType([1, "a"])', 0);110 jelAssert.fuzzy('Float[].checkType("a")', 0);111 jelAssert.fuzzy('DictionaryType(Float).checkType({a:2, b: 3})', 1);112 jelAssert.fuzzy('DictionaryType(Float).checkType({})', 1);113 jelAssert.fuzzy('DictionaryType(Float).checkType({a: 2, b: "a"})', 0);114 jelAssert.fuzzy('DictionaryType(Float).checkType("a")', 0);115 jelAssert.fuzzy('OptionType([Float, String, null]).checkType(1)', 1);116 jelAssert.fuzzy('OptionType([Float, String, null]).checkType("foo")', 1);117 jelAssert.fuzzy('OptionType([Float, String]).checkType(null)', 0);118 jelAssert.fuzzy('(Float|String|null).checkType(1)', 1);119 jelAssert.fuzzy('(Float|String|null).checkType("foo")', 1);120 jelAssert.fuzzy('(Float|String|null).checkType(null)', 1);121 jelAssert.fuzzy('(Float|String|null).checkType({})', 0);122 jelAssert.fuzzy('(Float|String|null).checkType({})', 0);123 jelAssert.fuzzy('(Float|null).checkType(100)', 1);124 jelAssert.fuzzy('(Float|null).checkType(null)', 1);125 jelAssert.fuzzy('(Float|null).checkType("a")', 0);126 jelAssert.fuzzy('(Float&String&null).checkType(null)', 0);127 jelAssert.fuzzy('(Float&null).checkType(100)', 0);128 jelAssert.fuzzy('(Float&null).checkType(null)', 0);129 jelAssert.fuzzy('(Float&int).checkType("a")', 0);130 jelAssert.fuzzy('(Float&int).checkType(1.5)', 0);131 jelAssert.fuzzy('(Float&int).checkType(1)', 1);132 jelAssert.fuzzy('OptionalType(Float).checkType(1)', 1);133 jelAssert.fuzzy('OptionalType(Float).checkType(null)', 1);134 jelAssert.fuzzy('OptionalType(Float).checkType("a")', 0);135 jelAssert.fuzzy('number?.checkType(1)', 1);136 jelAssert.fuzzy('number?.checkType(null)', 1);137 jelAssert.fuzzy('number?.checkType("a")', 0);138 jelAssert.fuzzy('do let e1 = enum AEnum a,b,c: EnumType(e1).checkType(e1.a)', 1);139 jelAssert.fuzzy('do let e1 = enum AEnum a,b,c: EnumType(e1).checkType(6)', 0);140 jelAssert.fuzzy('do let e1 = enum AEnum a,b,c: let e2 = enum BEnum a,b,c: EnumType(e2).checkType(e1.a)', 0);141 jelAssert.fuzzy('do let e1 = enum AEnum a,b,c: (e1)?.checkType(e1.a)', 1);142 jelAssert.fuzzy('do let e1 = enum AEnum a,b,c: (e1)?.checkType(#a)', 1);143 jelAssert.fuzzy('do let e1 = enum AEnum a,b,c: (e1)?.checkType(#x)', 0);144 });145 it('checks functions', function() {146 jelAssert.fuzzy('FunctionType().checkType(()=>1)', 1);147 jelAssert.fuzzy('FunctionType().checkType((a:int): any=>1)', 1);148 jelAssert.fuzzy('function.checkType(()=>1)', 1);149 jelAssert.fuzzy('function.checkType((a:int): any=>1)', 1);150 jelAssert.fuzzy('function(()=>1).checkType(()=>1)', 1);151 jelAssert.fuzzy('function((c,v)=>1).checkType((c,v)=>55)', 1);152 jelAssert.fuzzy('function((c,v)=>1).checkType((c,v,x)=>55)', 0);153 jelAssert.fuzzy('function((c,v,x)=>1).checkType((c,v)=>55)', 1);154 jelAssert.fuzzy('function((c,v,x)=>1, false).checkType((c,v)=>55)', 1);155 jelAssert.fuzzy('function((c,v)=>1).checkType((c,x)=>1)', 1);156 jelAssert.fuzzy('function((c,v)=>1, false).checkType((c,x)=>1)', 1);157 jelAssert.fuzzy('function((c,o): int=>1).checkType((c,o)=>55)', 1);158 jelAssert.fuzzy('function((c,o): int=>1, false).checkType((c,o)=>55)', 1);159 jelAssert.fuzzy('function((c,o): int=>1, true).checkType((c,o)=>55)', 0);160 jelAssert.fuzzy('function((c:int,o:int)=>1).checkType((c,o)=>55)', 1);161 jelAssert.fuzzy('function((c:int,o:int)=>1, false).checkType((c,o)=>55)', 1);162 jelAssert.fuzzy('function((c:int,o:int)=>1, true).checkType((c,o)=>55)', 0);163 jelAssert.fuzzy('function((c:int,o:int)=>1, false).checkType(c=>55)', 1);164 jelAssert.fuzzy('function((c:int,o:int): int=>1).checkType((c,o)=>55)', 1);165 jelAssert.fuzzy('function((c:int,o:int): int=>1, false).checkType((c,o)=>55)', 1);166 jelAssert.fuzzy('function((c:int,o:int): int=>1, true).checkType((c,o)=>55)', 0);167 jelAssert.fuzzy('function((c:int,v:int): int=>1, false).checkType((c,o)=>55)', 1);168 jelAssert.fuzzy('function((c:int,v:int): int=>1, true).checkType((c,o)=>55)', 0);169 jelAssert.fuzzy('function(()=>1).checkType((c)=>1)', 0);170 jelAssert.fuzzy('function(()=>1, false).checkType((c)=>1)', 0);171 jelAssert.fuzzy('function((c)=>1).checkType(()=>1)', 1);172 jelAssert.fuzzy('function((c)=>1, false).checkType(()=>1)', 1);173 jelAssert.fuzzy('function(()=>1).checkType("eek")', 0);174 jelAssert.fuzzy('FunctionType(()=>1).checkType("eek")', 0);175 });176 177 it('checks all convertable typedefs', function() {178 jelAssert.fuzzy('true instanceof typedef', 1);179 jelAssert.fuzzy('"foo" instanceof typedef', 1);180 jelAssert.fuzzy('null instanceof typedef', 1);181 jelAssert.fuzzy('{a: any} instanceof typedef', 1);182 jelAssert.fuzzy('1...10 instanceof typedef', 1);183 jelAssert.fuzzy('any instanceof typedef', 1);184 jelAssert.fuzzy('@Test instanceof typedef', 1);185 jelAssert.fuzzy('String instanceof typedef', 1);186 jelAssert.fuzzy('(enum AEnum: a, b, c) instanceof typedef', 1);187 jelAssert.fuzzy('function(()=>1) instanceof typedef', 1);188 });...
objects.js
Source:objects.js
...33 }34 })35 return foundType36}37function checkType(d, k, typeArray, isOpt) {38 if(!isOpt) {39 checkExists(d, k)40 }41 else if(d[k] == null) {42 return null43 }44 if(!isArray(typeArray)) {45 typeArray = [typeArray]46 }47 if(validateType(d[k], typeArray)) {48 return d[k]49 }50 else {51 throw 'Object type ' + typeof(d[k]) + ' does not match required ' + typeNames(typeArray) + ' in field ' + k + ' in ' + d.typeName52 }53}54function checkArrayType(d, k, typeArray, isOpt) {55 if(!isOpt) {56 checkExists(d, k)57 }58 else if(d[k] == null) {59 return null60 }61 if(!isArray(typeArray)) {62 typeArray = [typeArray]63 }64 d[k].forEach(function(e, index) {65 if(!validateType(e, typeArray)) {66 throw 'Object type ' + typeof(e) + ' does not match required ' + typeNames(typeArray) + ' in field ' + k67 }68 })69 return d[k]70}71var BaseObject = function(initHash) {72 for(k in initHash) {73 this[k] = initHash[k]74 }75 this.set = function(k, v) {76 this[k] = v77 }78}79exports.VarType = function() {80 BaseObject.apply(this, arguments)81 this.validate = function() {82 checkType(this, 'type', STRING_TYPE, false)83 }84}85exports.VarType.prototype.typeName = 'VarType'86varTypes = {87 INPUT: new exports.VarType({type: 'INPUT'}),88 OUTPUT: new exports.VarType({type: 'OUTPUT'}),89 LOCAL: new exports.VarType({type: 'LOCAL'})90}91exports.VarTypes = varTypes92exports.VarDataType = function() {93 BaseObject.apply(this, arguments)94 this.validate = function() {95 checkType(this, 'type', STRING_TYPE, false)96 }97}98exports.VarDataType.prototype.typeName = 'VarDataType'99varDataTypes = {}100varDataTypes[c.REAL_VAR_TKN] = new exports.VarDataType({type: c.REAL_VAR_TKN})101exports.VarDataTypes = varDataTypes102exports.Var = function() {103 BaseObject.apply(this, arguments)104 this.validate = function() {105 checkType(this, 'name', STRING_TYPE, false)106 checkType(this, 'type', exports.VarType, false)107 checkType(this, 'dataType', exports.VarDataType, false)108 }109}110exports.Var.prototype.typeName = 'Var'111exports.VarBlock = function() {112 BaseObject.apply(this, arguments)113 this.validate = function() {114 checkArrayType(this, 'vars', exports.Var, false)115 }116}117exports.VarBlock.prototype.typeName = 'VarBlock'118/**119 * Membership Functions (all fall under MemFunc type)120 */121exports.Point = function() {122 BaseObject.apply(this, arguments)123 this.validate = function() {124 checkType(this, 'x', [exports.Var, NUMBER_TYPE], false)125 checkType(this, 'y', [exports.Var, NUMBER_TYPE], false)126 }127}128exports.Point.prototype.typeName = 'Point'129exports.Trian = function() {130 BaseObject.apply(this, arguments)131 this.validate = function() {132 checkType(this, 'min', [exports.Var, NUMBER_TYPE], false)133 checkType(this, 'mid', [exports.Var, NUMBER_TYPE], false)134 checkType(this, 'max', [exports.Var, NUMBER_TYPE], false)135 }136}137exports.Trian.prototype.typeName = 'Trian'138exports.Trape = function() {139 BaseObject.apply(this, arguments)140 this.validate = function() {141 checkType(this, 'min', [exports.Var, NUMBER_TYPE], false)142 checkType(this, 'midLow', [exports.Var, NUMBER_TYPE], false)143 checkType(this, 'midHigh', [exports.Var, NUMBER_TYPE], false)144 checkType(this, 'max', [exports.Var, NUMBER_TYPE], false)145 }146}147exports.Trape.prototype.typeName = 'Trape'148exports.Gauss = function() {149 BaseObject.apply(this, arguments)150 this.validate = function() {151 checkType(this, 'mean', [exports.Var, NUMBER_TYPE], false)152 checkType(this, 'stdev', [exports.Var, NUMBER_TYPE], false)153 }154}155exports.Gauss.prototype.typeName = 'Gauss'156exports.Gbell = function() {157 BaseObject.apply(this, arguments)158 this.validate = function() {159 checkType(this, 'a', [exports.Var, NUMBER_TYPE], false)160 checkType(this, 'b', [exports.Var, NUMBER_TYPE], false)161 checkType(this, 'mean', [exports.Var, NUMBER_TYPE], false)162 }163}164exports.Gbell.prototype.typeName = 'Gbell'165exports.Sigm = function() {166 BaseObject.apply(this, arguments)167 this.validate = function() {168 checkType(this, 'gain', [exports.Var, NUMBER_TYPE], false)169 checkType(this, 'center', [exports.Var, NUMBER_TYPE], false)170 }171}172exports.Sigm.prototype.typeName = 'Sigm'173exports.Singleton = function() {174 BaseObject.apply(this, arguments)175 this.validate = function() {176 checkType(this, 'value', [exports.Var, NUMBER_TYPE], false)177 }178}179exports.Singleton.prototype.typeName = 'Singleton'180exports.Piecewise = function() {181 BaseObject.apply(this, arguments)182 this.validate = function() {183 checkArrayType(this, 'points', exports.Point, false)184 }185}186exports.Piecewise.prototype.typeName = 'Piecewise'187exports.Func = function() {188 BaseObject.apply(this, arguments)189 this.validate = function() {190 checkType(this, 'func', STRING_TYPE, false)191 }192}193exports.Func.prototype.typeName = 'Func'194exports.Term = function() {195 BaseObject.apply(this, arguments)196 this.validate = function() {197 checkType(this, 'name', STRING_TYPE, false)198 checkType(this, 'func', [exports.Trian, exports.Trape, exports.Gauss, exports.Gbell, exports.Sigm, exports.Singleton, exports.Piecewise, exports.Func], false)199 }200}201exports.Term.prototype.typeName = 'Term'202exports.FuzzifyBlock = function() {203 BaseObject.apply(this, arguments)204 this.validate = function() {205 checkType(this, 'var', exports.Var, false)206 checkArrayType(this, 'terms', exports.Term, false)207 }208}209exports.FuzzifyBlock.prototype.typeName = 'FuzzifyBlock'210exports.DefuzzMethod = function() {211 BaseObject.apply(this, arguments)212 this.validate = function() {213 checkType(this, 'method', STRING_TYPE, false)214 }215}216exports.DefuzzMethod.prototype.typeName = 'DefuzzMethod'217defuzzMethods = {}218defuzzMethods[c.COG_METHOD_TKN] = new exports.DefuzzMethod({method: c.COG_METHOD_TKN})219defuzzMethods[c.COGS_METHOD_TKN] = new exports.DefuzzMethod({method: c.COGS_METHOD_TKN})220defuzzMethods[c.COA_METHOD_TKN] = new exports.DefuzzMethod({method: c.COA_METHOD_TKN})221defuzzMethods[c.LM_METHOD_TKN] = new exports.DefuzzMethod({method: c.LM_METHOD_TKN})222defuzzMethods[c.RM_METHOD_TKN] = new exports.DefuzzMethod({method: c.RM_METHOD_TKN})223exports.DefuzzMethods = defuzzMethods224exports.DefuzzDefVal = function() {225 BaseObject.apply(this, arguments)226 this.validate = function() {227 checkType(this, 'isNC', BOOL_TYPE, false)228 checkType(this, 'value', NUMBER_TYPE, false)229 }230}231exports.DefuzzDefVal.prototype.typeName = 'DefuzzDefVal'232exports.DefuzzRange = function() {233 BaseObject.apply(this, arguments)234 this.validate = function() {235 checkType(this, 'min', NUMBER_TYPE, false)236 checkType(this, 'max', NUMBER_TYPE, false)237 }238}239exports.DefuzzRange.prototype.typeName = 'DefuzzRange'240exports.DefuzzifyBlock = function() {241 BaseObject.apply(this, arguments)242 this.validate = function() {243 checkType(this, 'var', exports.Var, false)244 checkArrayType(this, 'terms', exports.Term, false)245 checkType(this, 'defuzzMethod', exports.DefuzzMethod, false)246 checkType(this, 'defaultVal', exports.DefuzzDefVal, true)247 checkType(this, 'range', exports.Range, true)248 }249}250exports.DefuzzifyBlock.prototype.typeName = 'DefuzzifyBlock'251exports.Operator = function() {252 BaseObject.apply(this, arguments)253 this.validate = function() {254 checkType(this, 'operator', STRING_TYPE, false)255 }256}257exports.Operator.prototype.typeName = 'Operator'258operators = {}259operators[c.AND_TKN] = new exports.Operator({operator: c.AND_TKN})260operators[c.OR_TKN] = new exports.Operator({operator: c.OR_TKN})261exports.Operators = operators262exports.OperatorFunc = function() {263 BaseObject.apply(this, arguments)264 this.validate = function() {265 checkType(this, 'func', STRING_TYPE, false)266 }267}268exports.OperatorFunc.prototype.typeName = 'OperatorFunc'269operatorFuncs = {}270operatorFuncs[c.AND_METHOD_BDIF_TKN] = new exports.OperatorFunc({func: c.AND_METHOD_BDIF_TKN})271operatorFuncs[c.MIN_TKN] = new exports.OperatorFunc({func: c.MIN_TKN})272operatorFuncs[c.PROD_TKN] = new exports.OperatorFunc({func: c.PROD_TKN})273operatorFuncs[c.MAX_TKN] = new exports.OperatorFunc({func: c.MAX_TKN})274operatorFuncs[c.OR_METHOD_ASUM_TKN] = new exports.OperatorFunc({func: c.OR_METHOD_ASUM_TKN})275operatorFuncs[c.BSUM_TKN] = new exports.OperatorFunc({func: c.BSUM_TKN})276exports.OperatorFuncs = operatorFuncs277exports.OperatorDef = function() {278 BaseObject.apply(this, arguments)279 this.validate = function() {280 checkType(this, 'operator', exports.Operator, false)281 checkType(this, 'func', exports.OperatorFunc, false)282 }283}284exports.OperatorDef.prototype.typeName = 'OperatorDef'285exports.ActivationMethod = function() {286 BaseObject.apply(this, arguments)287 this.validate = function() {288 checkType(this, 'method', STRING_TYPE, false)289 }290}291exports.ActivationMethod.prototype.typeName = 'ActivationMethod'292activationMethods = {}293activationMethods[c.MIN_TKN] = new exports.ActivationMethod({method: c.MIN_TKN})294activationMethods[c.PROD_TKN] = new exports.ActivationMethod({method: c.PROD_TKN})295exports.ActivationMethods = activationMethods296exports.AccumulationMethod = function() {297 BaseObject.apply(this, arguments)298 this.validate = function() {299 checkType(this, 'method', STRING_TYPE, false)300 }301}302exports.AccumulationMethod.prototype.typeName = 'AccumulationMethod'303accumulationMethods = {}304accumulationMethods[c.MAX_TKN] = new exports.AccumulationMethod({method: c.MAX_TKN})305accumulationMethods[c.BSUM] = new exports.AccumulationMethod({method: c.BSUM})306accumulationMethods[c.ACCUM_METHOD_NSUM_TKN] = new exports.AccumulationMethod({method: c.ACCUM_METHOD_NSUM_TKN})307exports.AccumulationMethods = accumulationMethods308exports.Assertion = function() {309 BaseObject.apply(this, arguments)310 this.validate = function() {311 checkType(this, 'var', exports.Var, false)312 checkType(this, 'term', exports.Term, false)313 checkType(this, 'not', BOOL_TYPE, true)314 }315}316exports.Assertion.prototype.typeName = 'Assertion'317exports.Expression = function() {318 BaseObject.apply(this, arguments)319 this.validate = function() {320 checkType(this, 'operator', exports.Operator, false)321 checkType(this, 'firstHalf', [exports.Assertion, exports.Expression], false)322 checkType(this, 'secondHalf', [exports.Assertion, exports.Expression], false)323 }324}325exports.Expression.prototype.typeName = 'Expression'326exports.WithCond = function() {327 BaseObject.apply(this, arguments)328 this.validate = function() {329 checkType(this, 'value', [exports.Var, NUMBER_TYPE], false)330 }331}332exports.WithCond.prototype.typeName = 'WithCond'333exports.Rule = function() {334 BaseObject.apply(this, arguments)335 this.validate = function() {336 checkType(this, 'number', NUMBER_TYPE, false)337 checkType(this, 'ifCond', [exports.Assertion, exports.Expression], false)338 checkArrayType(this, 'thenCond', [exports.Assertion], false)339 checkType(this, 'withCond', exports.WithCond, true)340 }341}342exports.Rule.prototype.typeName = 'Rule'343exports.RuleBlock = function() {344 BaseObject.apply(this, arguments)345 this.validate = function() {346 checkType(this, 'name', STRING_TYPE, true)347 checkType(this, 'andOperatorDef', exports.OperatorDef, true)348 checkType(this, 'orOperatorDef', exports.OperatorDef, true)349 checkType(this, 'activationMethod', exports.ActivationMethod, true)350 checkType(this, 'accumulationMethod', exports.AccumulationMethod, true)351 checkArrayType(this, 'rules', exports.Rule, false)352 }353}354exports.RuleBlock.prototype.typeName = 'RuleBlock'355exports.FunctionBlock = function() {356 BaseObject.apply(this, arguments)357 this.validate = function() {358 checkType(this, 'name', STRING_TYPE, false)359 checkArrayType(this, 'varBlocks', exports.VarBlock, false)360 checkArrayType(this, 'fuzzifyBlocks', exports.FuzzifyBlock, false)361 checkArrayType(this, 'defuzzifyBlocks', exports.DefuzzifyBlock, true)362 checkArrayType(this, 'ruleBlocks', exports.RuleBlock, true)363 }364}...
str.js
Source:str.js
...12 checkType2(value, 'string', 'number', 1)13 return typeof value === 'number' ? String.fromCharCode(value) : value.charCodeAt(0)14}15export function bytelength (text) {16 checkType(text, 'string', 1)17 return typeof Buffer !== 'undefined'18 ? Buffer.from(text).length19 : new TextEncoder().encode(text).length20}21export function capitalize (text) {22 checkType(text, 'string', 1)23 return text.replace(/(\w+)/g, match =>24 match.charAt(0).toUpperCase() + match.substr(1).toLowerCase())25}26export function catenate (values, delimiter) {27 checkList(values, 1)28 checkType(delimiter, 'string', 2)29 const suffix = values.length ? delimiter : ''30 return `${values.join(delimiter)}${suffix}`31}32export function chr (hay, needle) {33 checkType(hay, 'string', 1)34 checkType(needle, 'string', 2)35 const index = hay.indexOf(needle.charAt(0))36 return index < 0 ? undefined : index + 137}38export function cmp (left, right, length) {39 checkType(left, 'string', 1)40 checkType(right, 'string', 2)41 checkTypeOptional(length, 'number', 3)42 if (length !== undefined) {43 left = left.substr(0, length)44 right = right.substr(0, length)45 }46 return left < right ? -1 : left > right ? 1 : 047}48export function cmpbe (left, right, length) {49 checkType(left, 'string', 1)50 checkType(right, 'string', 2)51 checkTypeOptional(length, 'number', 3)52 return cmp(left.trimEnd(), right.trimEnd(), length)53}54export function cmpi (left, right, length) {55 checkType(left, 'string', 1)56 checkType(right, 'string', 2)57 checkTypeOptional(length, 'number', 3)58 return cmp(left.toLowerCase(), right.toLowerCase(), length)59}60export function cmpibe (left, right, length) {61 checkType(left, 'string', 1)62 checkType(right, 'string', 2)63 checkTypeOptional(length, 'number', 3)64 return cmp(left.trimEnd().toLowerCase(), right.trimEnd().toLowerCase(), length)65}66export function collapse (text) {67 checkType(text, 'string', 1)68 return text.replace(/[ \t]/g, '')69}70export function compress (text) {71 checkType(text, 'string', 1)72 return text.replace(/[ \t]+/g, ' ')73}74export function cspn (text, chars) {75 checkType(text, 'string', 1)76 checkType(chars, 'string', 2)77 const regexp = new RegExp(`^[^${chars.split('').map(escapeRegExp).join('|')}]+`)78 const match = regexp.exec(text)79 return match ? match[0].length : 080}81export function cstring (text, quote = '\'') {82 return text.replace(new RegExp(`[\r\n\t\\${quote}]`, 'g'), '\\$1')83}84export function elements (text, delimiter) {85 checkType(text, 'string', 1)86 checkType(delimiter, 'string', 2)87 return text.split(delimiter.charAt(0))88}89export function filetostring (name) {90 checkType(name, 'string', 1)91 return readFileSync(name, 'utf8')92}93export function format (format, ...args) {94 return format.replace(/%(\d)/g, (match, index) => '' + args[index - 1])95}96export function frombase64 (text) {97 checkType(text, 'string', 1)98 return typeof Buffer !== 'undefined'99 ? Buffer.from(text, 'base64').toString('ascii')100 : atob(text)101}102export function hyphenate (text, length) {103 checkType(text, 'string', 1)104 checkType(text, 'number', 2)105 const parts = []106 do {107 parts.push(text.substr(0, length))108 text = text.substr(length)109 } while (text.length)110 return parts111}112export function join (values, delimiter) {113 checkList(values, 1)114 checkType(delimiter, 'string', 2)115 return values.join(delimiter)116}117export function locate (hay, needle) {118 checkType(hay, 'string', 1)119 checkType(needle, 'string', 2)120 const index = hay.indexOf(needle)121 return index < 0 ? undefined : index + 1122}123export function locatei (hay, needle) {124 checkType(hay, 'string', 1)125 checkType(needle, 'string', 2)126 const index = hay.toLowerCase().indexOf(needle.toLowerCase())127 return index < 0 ? undefined : index + 1128}129export function lower (text) {130 checkType(text, 'string', 1)131 return text.toLowerCase()132}133export function quote (text, quote = '\'') {134 checkType(text, 'string', 1)135 checkQuote(quote, 2)136 return `${quote}${text.replace(new RegExp(quote, 'g'), `\\${quote}`)}${quote}`137}138export function rchr (hay, needle) {139 checkType(hay, 'string', 1)140 checkType(needle, 'string', 2)141 const index = hay.lastIndexOf(needle.charAt(0))142 return index < 0 ? undefined : index + 1143}144export function replace (text, find, replace) {145 checkType(text, 'string', 1)146 checkType(find, 'string', 2)147 checkType(replace, 'string', 3)148 return text.replace(find, replace)149}150export function replaceall (text, find, replace) {151 checkType(text, 'string', 1)152 checkType(find, 'string', 2)153 checkType(replace, 'string', 3)154 const regexp = new RegExp(`${find.split('').map(escapeRegExp).join('')}`, 'g')155 return text.replace(regexp, replace)156}157export function set (length, text) {158 checkType2(text, 'string', 'number', 1)159 checkType(text, 'string', 2)160 if (typeof length === 'string') length = length.length161 else if (length < 0) length = 0162 return text.charAt(0).repeat(length)163}164export function spn (text, chars) {165 checkType(text, 'string', 1)166 checkType(chars, 'string', 2)167 const regexp = new RegExp(`^[${chars.split('').map(escapeRegExp).join('')}]+`)168 const match = regexp.exec(text)169 return match ? match[0].length : 0170}171export function string (value, raw) {172 checkTypeOptional(raw, 'boolean', 2)173 return !raw && value instanceof Error ? value.message : valuetostring(value)174}175export function stringtointegher (text) {176 return parseInt(text)177}178export function stringtoreal (text) {179 checkType(text, 'string', 1)180 return parseFloat(text)181}182export function stringtovalue (text) {183 checkType(text, 'string', 1)184 const number = parseInt(text)185 if (isNaN(number)) return number186 const normalized = text.toLowerCase()187 if (normalized === 'true') return true188 if (normalized === 'false') return false189 if (normalized === 'undefined') return undefined190 return text191}192export function strip (text, chars) {193 checkType(text, 'string', 1)194 checkType(chars, 'string', 2)195 const regexp = new RegExp(`[${chars.split('').map(escapeRegExp).join('')}]`, 'g')196 return text.replace(regexp, '')197}198export function tobase64 (text) {199 checkType(text, 'string', 1)200 return typeof Buffer !== 'undefined'201 ? Buffer.from(text).toString('base64')202 : btoa(text)203}204export function upper (text) {205 checkType(text, 'string', 1)206 return text.toUpperCase()207}208export function valuetostring (value) {209 return String(value)210}211// ---------- other methods212function escapeRegExp (char) {213 return char === '*' || char === '+' || char === '.' || char === '?' ||214 char === '[' || char === ']' || char === '(' || char === ')' ||215 char === '{' || char === '}' || char === '^' || char === '$'216 ? `\\${char}`217 : char...
formRule.config.js
Source:formRule.config.js
1/* 2 * åºç¨è¡¨åæ ¡éªç¸å
³é
ç½®3 * ä¾èµï¼graceChecker.js è¿è¡æ ¡éª4 * 5 * 使ç¨ï¼å¼å
¥è¯¥jså°é¡µé¢ï¼let res = graceChecker.check({phoneNo:"",code:""},formRule.loginRule)6 */7export default {8 /* ç¨æ·ç»å½ */9 loginRule: [{10 name: "openId",11 checkType: "notnull",12 checkRule: "",13 errorMsg: "ç»å½çopenId为空,请ä»æå±å
¬ä¼å·èåæå¼é¾æ¥"14 },{15 name: "phoneNo",16 checkType: "phoneno",17 checkRule: "",18 errorMsg: "ææºå·æ ¼å¼ä¸æ£ç¡®"19 }, {20 name: "code",21 checkType: "string",22 checkRule: "6",23 errorMsg: "请è¾å
¥6ä½éªè¯ç "24 }],25 /* åééªè¯ç éªè¯ææºå· */26 sendCodeRule: [{27 name: "phoneNo",28 checkType: "notnull",29 checkRule: "",30 errorMsg: "ææºå·ä¸è½ä¸ºç©º"31 }, {32 name: "phoneNo",33 checkType: "phoneno",34 checkRule: "",35 errorMsg: "ææºå·æ ¼å¼ä¸æ£ç¡®"36 }],37 /* åæ·æ³¨å */38 regCustomerRule: [{39 name: "openId",40 checkType: "notnull",41 checkRule: "",42 errorMsg: "缺失openId"43 }, {44 name: "referrer",45 checkType: "notnull",46 checkRule: "",47 errorMsg: "缺失referrer"48 }, {49 name: "userName",50 checkType: "string",51 checkRule: "1,3",52 errorMsg: "å§ååºä¸º1-3个å符"53 }, {54 name: "idCard",55 checkType: "string",56 checkRule: "15,18",57 errorMsg: "身份è¯å·æ ¼å¼ä¸æ£ç¡®"58 }, {59 name: "cardNo",60 checkType: "int",61 checkRule: "3,20",62 errorMsg: "é¶è¡å¡å·æ ¼å¼ä¸æ£ç¡®"63 }, {64 name: "cityNo",65 checkType: "notnull",66 checkRule: "",67 errorMsg: "请éæ©å¼æ·å°åº"68 }, {69 name: "bankName",70 checkType: "notnull",71 checkRule: "",72 errorMsg: "é¶è¡å称ä¸è½ä¸ºç©º"73 }, {74 name: "phoneNo",75 checkType: "phoneno",76 checkRule: "",77 errorMsg: "ææºå·æ ¼å¼ä¸æ£ç¡®"78 }, {79 name: "settleCardImgId",80 checkType: "notnull",81 checkRule: "",82 errorMsg: "请ä¸ä¼ 身份è¯åç»ç®å¡ç
§ç"83 }, {84 name: "cardHolderBackImgId",85 checkType: "notnull",86 checkRule: "",87 errorMsg: "请ä¸ä¼ 身份è¯å½å¾½é¢ç
§ç"88 }, {89 name: "cardHolderIdImgId",90 checkType: "notnull",91 checkRule: "",92 errorMsg: "请ä¸ä¼ ææ身份è¯åå½±ç
§ç"93 }],94 /* ä¿®æ¹ç»ç®å¡ */95 updataCustomerCardRule: [{96 name: "customerNo",97 checkType: "notnull",98 checkRule: "",99 errorMsg: "åæ·ç¼å·ä¸ºç©º"100 }, {101 name: "userName",102 checkType: "string",103 checkRule: "1,3",104 errorMsg: "å§ååºä¸º1-3个å符"105 }, {106 name: "idCard",107 checkType: "string",108 checkRule: "15,18",109 errorMsg: "身份è¯å·æ ¼å¼ä¸æ£ç¡®"110 }, {111 name: "cardNo",112 checkType: "int",113 checkRule: "3,20",114 errorMsg: "é¶è¡å¡å·æ ¼å¼ä¸æ£ç¡®"115 }, {116 name: "cityNo",117 checkType: "notnull",118 checkRule: "",119 errorMsg: "请éæ©å¼æ·å°åº"120 }, {121 name: "bankName",122 checkType: "notnull",123 checkRule: "",124 errorMsg: "æªæ¥è¯¢å°é¶è¡å称"125 }, {126 name: "phoneNo",127 checkType: "phoneno",128 checkRule: "",129 errorMsg: "ææºå·æ ¼å¼ä¸æ£ç¡®"130 }, {131 name: "settleCardImgId",132 checkType: "notnull",133 checkRule: "",134 errorMsg: "请ä¸ä¼ 身份è¯åç»ç®å¡ç
§ç"135 }, {136 name: "cardHolderIdImgId",137 checkType: "notnull",138 checkRule: "",139 errorMsg: "请ä¸ä¼ ææ身份è¯åå½±ç
§ç"140 }],141 /* ä¿¡ç¨å¡æ·»å */142 ccAddRule: [{143 name: "cardNo",144 checkType: "int",145 checkRule: "3,20",146 errorMsg: "é¶è¡å¡å·æ ¼å¼ä¸æ£ç¡®"147 }, {148 name: "accountName",149 checkType: "notnull",150 checkRule: "",151 errorMsg: "å¼æ·å称ä¸è½ä¸ºç©º"152 }, {153 name: "reservedPhoneNo",154 checkType: "phoneno",155 checkRule: "",156 errorMsg: "ææºå·æ ¼å¼ä¸æ£ç¡®"157 }, {158 name: "idCard",159 checkType: "string",160 checkRule: "15,18",161 errorMsg: "身份è¯å·æ ¼å¼ä¸æ£ç¡®"162 }, {163 name: "bankName",164 checkType: "notnull",165 checkRule: "",166 errorMsg: "é¶è¡å称ä¸è½ä¸ºç©º"167 }]...
datasetMixins.js
Source:datasetMixins.js
...101 }102 };103 },104 computed: {105 checkType() {106 if (!(this.check.name in this.checkTypeVersionControl)) {107 throw "unknown check: " + this.check.name;108 }109 if (this.check.meta.version != this.checkTypeVersionControl[this.check.name].version) {110 return null;111 }112 return this.checkTypeVersionControl[this.check.name].checkType;113 },114 shares() {115 if (this.checkType == "donut") {116 return this.orderedShares(this.check.meta.shares);117 } else {118 return null;119 }...
check.test.js
Source:check.test.js
1import test from 'ava'2import mockRequire from 'mock-require'3import sinon from 'sinon'4import { CheckCondition, CheckSubject, CheckType } from 'enum'5import { extrinsic } from 'aid'6import { assay as makeAssay } from 'make'7let check8const checkVariant = {}9for (const name of Object.keys(CheckType)) {10 checkVariant[name] = sinon.stub()11}12test.before(() => {13 mockRequire('../../../src/validate/checkVariant', checkVariant)14 check = require('validate/check')15})16test.afterEach.always(() => {17 for (const name of Object.keys(checkVariant)) {18 checkVariant[name].reset()19 }20})21test.serial('missing type', (t) => {22 t.throws(23 () => {24 check({}, 0, 0, makeAssay())25 },26 { name: 'MissingCheckType' }27 )28})29test.serial('invalid type', (t) => {30 t.throws(31 () => {32 check({ type: extrinsic(CheckType) }, 0, 0, makeAssay())33 },34 { name: 'InvalidCheckType' }35 )36})37test.serial('invalid subject', (t) => {38 t.throws(39 () => {40 check(41 {42 type: CheckType.Text,43 subject: extrinsic(CheckSubject),44 },45 0,46 0,47 makeAssay()48 )49 },50 { name: 'InvalidCheckSubject' }51 )52})53test.serial('invalid condition', (t) => {54 t.throws(55 () => {56 check(57 {58 type: CheckType.Text,59 condition: extrinsic(CheckCondition),60 },61 0,62 0,63 makeAssay()64 )65 },66 { name: 'InvalidCheckCondition' }67 )68})69test.serial('invalid expression', (t) => {70 t.throws(71 () => {72 check({ type: CheckType.Text, expression: 5 }, 0, 0, makeAssay())73 },74 { name: 'InvalidCheckExpression' }75 )76})77test.serial('invalid flags', (t) => {78 t.throws(79 () => {80 check({ type: CheckType.Text, flags: 5 }, 0, 0, makeAssay())81 },82 { name: 'InvalidCheckFlags' }83 )84})85test.serial('invalid value', (t) => {86 t.throws(87 () => {88 check({ type: CheckType.Text, value: 5 }, 0, 0, makeAssay())89 },90 { name: 'InvalidCheckValue' }91 )92})93test.serial('invalid comment', (t) => {94 t.throws(95 () => {96 check({ type: CheckType.Text, comment: 5 }, 0, 0, makeAssay())97 },98 { name: 'InvalidComment' }99 )100})101test.serial('duplicate name', (t) => {102 const assay = makeAssay()103 check({ type: CheckType.JSONPath, expression: '$.token' }, 5, 0, assay)104 t.throws(105 () => {106 check({ type: CheckType.JSONPath, expression: '$.token' }, 5, 1, assay)107 },108 {109 name: 'DuplicateCheckName',110 message: 'Duplicate check name (5:1): $.token exists',111 }112 )113})114test.serial('valid minimal', (t) => {115 check(116 {117 type: CheckType.JSONPath,118 expression: '$.token',119 },120 0,121 0,122 makeAssay()123 )124 t.true(checkVariant.JSONPath.calledOnce)125})126test.serial('valid full', (t) => {127 check(128 {129 type: CheckType.JSONPathValue,130 subject: CheckSubject.HttpStatusCode,131 condition: CheckCondition.Equals,132 expression: 'user.id',133 flags: 'i',134 value: '7484',135 comment: 'How deep does the rabbit hole go?',136 },137 0,138 0,139 makeAssay()140 )141 t.true(checkVariant.JSONPathValue.calledOnce)...
07.Typeof.js
Source:07.Typeof.js
1function checkType(input) {2 console.log(typeof input);3}4// null is of type "object" in JavaScript5// NaN is of type "number"6// Other types are:7// object8// function 9// string10// number 11// boolean12// undefined13// symbol14checkType({}); // object15checkType(function(){}); // function16checkType(Object); // function17checkType([]); // object18checkType(null); // <-------------- object19checkType(1); // number20checkType("hello"); // string21checkType(Function); // function22checkType(false); // boolean23checkType(Symbol); // function24checkType(undefined); // undefined25checkType(foo); // <-------------- undefined ; if the below is present. 26var foo;27checkType(null); // <-------------- object28checkType(Symbol(88));...
Using AI Code Generation
1const { chromium } = require('playwright');2const { checkType } = require('playwright/lib/internal/stackTrace');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.screenshot({ path: `example.png` });8 await browser.close();9})();10const { chromium } = require('playwright');11const { checkType } = require('playwright/lib/internal/stackTrace');12(async () => {13 const browser = await chromium.launch();14 const context = await browser.newContext();15 const page = await context.newPage();16 await page.screenshot({ path: `example.png` });17 await browser.close();18})();19const { chromium } = require('playwright');20const { checkType } = require('playwright/lib/internal/stackTrace');21(async () => {22 const browser = await chromium.launch();23 const context = await browser.newContext();24 const page = await context.newPage();25 await page.screenshot({ path: `example.png` });26 await browser.close();27})();28const { chromium } = require('playwright');29const { checkType } = require('playwright/lib/internal/stackTrace');30(async () => {31 const browser = await chromium.launch();32 const context = await browser.newContext();33 const page = await context.newPage();34 await page.screenshot({ path: `example.png` });35 await browser.close();36})();37const { chromium } = require('playwright');38const { checkType } = require('playwright/lib/internal/stackTrace');39(async () => {40 const browser = await chromium.launch();41 const context = await browser.newContext();42 const page = await context.newPage();43 await page.screenshot({ path: `example
Using AI Code Generation
1const { checkType } = require('playwright/lib/utils/utils');2const { isString } = require('playwright/lib/utils/utils');3const { isRegExp } = require('playwright/lib/utils/utils');4const { isObject } = require('playwright/lib/utils/utils');5const { isNumber } = require('playwright/lib/utils/utils');6const { isBoolean } = require('playwright/lib/utils/utils');7const { isUndefined } = require('playwright/lib/utils/utils');8const { isNull } = require('playwright/lib/utils/utils');9const { isFunction } = require('playwright/lib/utils/utils');10const { isArrayOfStrings } = require('playwright/lib/utils/utils');11const { isArrayOfNumbers } = require('playwright/lib/utils/utils');12const { isDebugMode } = require('playwright/lib/utils/utils');13const { isDebugAt } = require('playwright/lib/utils/utils');14const { isDebugAtAny } = require('playwright/lib/utils/utils');15const { isDebugAtAll } = require('playwright/lib/utils/utils');16const { isDebugAtPlaywright } = require('playwright/lib/utils/utils');17const { isDebugAtBrowser } = require('playwright/lib/utils/utils');18const { isDebugAtBrowserContext } = require('playwright/lib/utils/utils');19const { isDebugAtPage } = require('playwright/lib/utils/utils');20const { isDebugAtApi } = require('playwright/lib/utils/utils');21const { isDebugAtWorker } = require('playwright/lib/utils/utils');22const { isDebugAtBrowserServer } = require('playwright/lib/utils/utils');23const { isDebugAtSelector } = require('playwright/lib/utils/utils');24const { isDebugAtChannelOwner } = require('playwright/lib/utils/utils');25const { isDebugAtDispatcher } = require('playwright/lib/utils/utils');26const { isDebugAtProtocol } = require('playwright/lib/utils/utils');27const { isDebugAtConnection } = require('playwright/lib/utils/utils');28const { isDebugAtLauncher } = require('playwright/lib/utils/utils');29const { isDebugAtTest } = require('playwright/lib/utils/utils');30const { isDebugAtTestRunner } = require('playwright/lib/utils/utils');31const { isDebugAtTestReporter } = require('playwright/lib/utils/utils');32const { isDebugAtTestFixtures } = require('playwright/lib/utils/utils
Using AI Code Generation
1const { checkType } = require('playwright/lib/utils/utils');2const { assert } = require('playwright/lib/utils/helper');3const { Page } = require('playwright/lib/page');4const { ElementHandle } = require('playwright/lib/elementHandle');5const page = new Page();6assert(checkType(page, Page), 'Object is not of type Page');7const elementHandle = new ElementHandle();8assert(checkType(elementHandle, ElementHandle), 'Object is not of type ElementHandle');9assert(checkType([elementHandle, elementHandle], [ElementHandle]), 'Object is not of type Array of ElementHandles');10assert(checkType([elementHandle, elementHandle], [ElementHandle]), 'Object is not of type Array of ElementHandles');11assert(checkType([elementHandle, elementHandle], [ElementHandle]), 'Object is not of type Array of ElementHandles');12assert(checkType([elementHandle, elementHandle], [ElementHandle]), 'Object is not of type Array of ElementHandles');13assert(checkType([elementHandle, elementHandle], [ElementHandle]), 'Object is not of type Array of ElementHandles');14assert(checkType([elementHandle, elementHandle], [ElementHandle]), 'Object is not of type Array of ElementHandles');15assert(checkType([elementHandle, elementHandle], [ElementHandle]), 'Object is not of type Array of ElementHandles');16assert(checkType([elementHandle, elementHandle], [ElementHandle]), 'Object is not of type Array of ElementHandles');17assert(checkType([elementHandle, elementHandle], [ElementHandle]), 'Object
Using AI Code Generation
1const { checkType } = require('@playwright/test/lib/utils/utils');2const { expect } = require('@playwright/test');3test('test checkType', async ({ page }) => {4 expect(checkType('string', 'string')).toBe(true);5 expect(checkType('string', 'number')).toBe(false);6 expect(checkType('string', 'boolean')).toBe(false);7 expect(checkType('string', 'object')).toBe(false);8 expect(checkType('string', 'function')).toBe(false);9 expect(checkType('string', 'undefined')).toBe(false);10 expect(checkType('string', 'symbol')).toBe(false);11 expect(checkType('string', 'bigint')).toBe(false);12 expect(checkType('string', 'array')).toBe(false);13 expect(checkType('string', 'null')).toBe(false);14 expect(checkType('string', 'regexp')).toBe(false);15 expect(checkType('string', 'date')).toBe(false);16 expect(checkType('string', 'map')).toBe(false);17 expect(checkType('string', 'set')).toBe(false);18 expect(checkType('string', 'promise')).toBe(false);19 expect(checkType('string', 'weakmap')).toBe(false);20 expect(checkType('string', 'weakset')).toBe(false);21 expect(checkType('string', 'iterator')).toBe(false);22 expect(checkType('string', 'generator')).toBe(false);23 expect(checkType('string', 'error')).toBe(false);24 expect(checkType('string', 'url')).toBe(false);25 expect(checkType('string', 'nan')).toBe(false);26 expect(checkType('string', 'infinity')).toBe(false);27 expect(checkType('string', 'int8array')).toBe(false);28 expect(checkType('string', 'uint8array')).toBe(false);29 expect(checkType('string', 'uint8clampedarray')).toBe(false);30 expect(checkType('string', 'int16array')).toBe(false);31 expect(checkType('string', 'uint16array')).toBe(false);32 expect(checkType('string', 'int32array')).toBe(false);33 expect(checkType('string', 'uint32array')).toBe(false);34 expect(checkType('string', 'float32array')).toBe(false);35 expect(checkType('string', 'float64array')).toBe(false);36 expect(checkType('string', '
Using AI Code Generation
1const { checkType } = require('playwright/lib/utils/utils');2const { checkType } = require('playwright/lib/utils/utils');3const { checkType } = require('playwright/lib/utils/utils');4const { checkType } = require('playwright/lib/utils/utils');5const { checkType } = require('playwright/lib/utils/utils');6const { checkType } = require('playwright/lib/utils/utils');7const { checkType } = require('playwright/lib/utils/utils');8const { checkType } = require('playwright/lib/utils/utils');9checkType('myType', '
Using AI Code Generation
1const { checkType } = require('@playwright/test/lib/utils/utils');2const { test } = require('@playwright/test');3test('test', async ({ page }) => {4 const title = await page.title();5 console.log('Page title: ' + title);6});7const { test } = require('@playwright/test');8test('test', async ({ page }) => {9 const title = await page.title();10 console.log('Page title: ' + title);11});12const { test, expect } = require('@playwright/test');13test('basic test', async ({ page }) => {14 const title = await page.title();15 expect(title).toBe('Playwright');16});
Using AI Code Generation
1const { checkType } = require('playwright-core/lib/server/utils');2console.log(checkType('value', 'type'));3console.log(checkType('value', 'type', 'name'));4console.log(checkType('value', 'type', 'name', 'valueName'));5console.log(checkType('value', 'type', 'name', 'valueName', 'expectedType'));6console.log(checkType('value', 'type', 'name', 'valueName', 'expectedType', 'expectedType2'));7console.log(checkType('value', 'type', 'name', 'valueName', 'expectedType', 'expectedType2', 'expectedType3'));8console.log(checkType('value', 'type', 'name', 'valueName', 'expectedType', 'expectedType2', 'expectedType3', 'expectedType4'));9console.log(checkType('value', 'type', 'name', 'valueName', 'expectedType', 'expectedType2', 'expectedType3', 'expectedType4', 'expectedType5'));10console.log(checkType('value', 'type', 'name', 'valueName', 'expectedType', 'expectedType2', 'expectedType3', 'expectedType4', 'expectedType5', 'expectedType6'));11console.log(checkType('value', 'type', 'name', 'valueName', 'expectedType', 'expectedType2', 'expectedType3', 'expectedType4', 'expectedType5', 'expectedType6', 'expectedType7'));12console.log(checkType('value', 'type', 'name', 'valueName', 'expectedType', 'expectedType2', 'expectedType3', 'expectedType4', 'expectedType5', 'expectedType6', '
Using AI Code Generation
1const { checkType } = require('playwright/lib/utils/utils');2const { assert } = require('chai');3describe('Playwright Internal API', function () {4 it('should validate the type of the input', function () {5 assert.isTrue(checkType('name', 'string', 'test'));6 });7});8 1 passing (12ms)
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!