Use Standard as JavaScript standard style

This commit is contained in:
Christoph Diehl 2017-04-26 01:21:31 +03:00
parent 6e986d5702
commit 6cbda76fea
23 changed files with 766 additions and 762 deletions

View File

@ -2,75 +2,75 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var websocket = null; var websocket = null
var logger = (function () { var logger = (function () {
let color = { let color = {
red: "\033[1;31m", red: '\u0033[1;31m',
green: "\033[1;32m", green: '\u0033[1;32m',
clear: "\033[0m" clear: '\u0033[0m'
}; }
if (utils.platform.isWindows) { if (utils.platform.isWindows) {
color = { color = {
red: "", red: '',
green: "", green: '',
clear: "" clear: ''
}; }
} }
let sep = "\n/* ### NEXT TESTCASE ############################## */"; let sep = '\n/* ### NEXT TESTCASE ############################## */'
function console(msg) { function console (msg) {
if (websocket) { if (websocket) {
websocket.send(msg); websocket.send(msg)
} }
if (typeof window === 'undefined') { if (typeof window === 'undefined') {
print(msg); print(msg)
} else if (window.dump) { } else if (window.dump) {
window.dump(msg); window.dump(msg)
} else if (window.console && window.console.log) { } else if (window.console && window.console.log) {
window.console.log(msg); window.console.log(msg)
} else { } else {
throw "Unable to run console logger."; throw new Error('Unable to run console logger.')
} }
} }
function dump(msg) { function dump (msg) {
console(msg); console(msg)
} }
function testcase(msg) { function testcase (msg) {
dump("/*L*/ " + JSON.stringify(msg) + "\n"); dump('/*L*/ ' + JSON.stringify(msg) + '\n')
} }
function dumpln(msg) { function dumpln (msg) {
dump(msg + "\n"); dump(msg + '\n')
} }
function error(msg) { function error (msg) {
dumpln(color.red + msg + color.clear); dumpln(color.red + msg + color.clear)
} }
function JSError(msg) { function JSError (msg) {
error(comment(msg)) error(comment(msg))
} }
function comment(msg) { function comment (msg) {
return "/* " + msg + " */"; return '/* ' + msg + ' */'
} }
function separator() { function separator () {
dumpln(color.green + sep + color.clear); dumpln(color.green + sep + color.clear)
} }
function traceback() { function traceback () {
error("===[ Traceback ]"); error('===[ Traceback ]')
try { try {
throw new Error(); throw new Error()
} catch (e) { } catch (e) {
dump(e.stack || e.stacktrace || ""); dump(e.stack || e.stacktrace || '')
} }
error("==="); error('===')
} }
return { return {
@ -83,5 +83,5 @@ var logger = (function () {
testcase: testcase, testcase: testcase,
separator: separator, separator: separator,
traceback: traceback traceback: traceback
}; }
})(); })()

View File

@ -4,13 +4,13 @@
make.arrays = { make.arrays = {
filledArray: function (fn, limit) { filledArray: function (fn, limit) {
let array = []; let array = []
let size = limit || random.number(make.number.tinyNumber); let size = limit || random.number(make.number.tinyNumber)
for (let i = 0; i < size; i++) { for (let i = 0; i < size; i++) {
array.push(fn()); array.push(fn())
} }
return array; return array
} }
}; }

View File

@ -8,78 +8,78 @@ make.colors = {
make.colors.rgb, make.colors.rgb,
make.colors.hsl, make.colors.hsl,
make.colors.keyword make.colors.keyword
]); ])
}, },
rgb: function () { rgb: function () {
let values; let values
switch (random.number(4)) { switch (random.number(4)) {
case 0: case 0:
// Rgb functional notation // Rgb functional notation
if (random.bool()) { if (random.bool()) {
// Ints // Ints
values = [random.number(255), random.number(255), random.number(255)]; values = [random.number(255), random.number(255), random.number(255)]
} else { } else {
// Percents // Percents
values = ["%" + random.number(255), "%" + random.number(255), "%" + random.number(255)]; values = ['%' + random.number(255), '%' + random.number(255), '%' + random.number(255)]
} }
return "rgba(" + values.join(',') + ")"; return 'rgba(' + values.join(',') + ')'
case 1: case 1:
// Rgba functional notation // Rgba functional notation
values = [random.number(255), random.number(255), random.number(255), random.float()]; values = [random.number(255), random.number(255), random.number(255), random.float()]
return "rgba(" + values.join(',') + ")"; return 'rgba(' + values.join(',') + ')'
case 2: case 2:
// 4 char hex // 4 char hex
return "#" + random.hex(4); return '#' + random.hex(4)
default: default:
// 8 char hex // 8 char hex
return "#" + random.hex(8); return '#' + random.hex(8)
} }
}, },
hsl: function () { hsl: function () {
let values, opt; let values, opt
switch (random.number(4)) { switch (random.number(4)) {
case 0: case 0:
values = [random.number(255), "%" + random.number(255), "%" + random.number(255)]; values = [random.number(255), '%' + random.number(255), '%' + random.number(255)]
return "hsl(" + values.join(',') + ")"; return 'hsl(' + values.join(',') + ')'
case 1: case 1:
values = [random.number(255), "%" + random.number(255), "%" + random.number(255), "%" + random.number(255)]; values = [random.number(255), '%' + random.number(255), '%' + random.number(255), '%' + random.number(255)]
return "hsl(" + values.join(',') + ")"; return 'hsl(' + values.join(',') + ')'
case 2: case 2:
opt = random.pick(['deg', 'rad', 'grad', 'turn']); opt = random.pick(['deg', 'rad', 'grad', 'turn'])
values = [random.number(255) + opt, "%" + random.number(255), "%" + random.number(255), "%" + random.number(255)]; values = [random.number(255) + opt, '%' + random.number(255), '%' + random.number(255), '%' + random.number(255)]
return "hsl(" + values.join(',') + ")"; return 'hsl(' + values.join(',') + ')'
default: default:
values = [random.number(255), "%" + random.number(255), "%" + random.number(255), random.float()]; values = [random.number(255), '%' + random.number(255), '%' + random.number(255), random.float()]
return "hsl(" + values.join(',') + ")"; return 'hsl(' + values.join(',') + ')'
} }
}, },
keyword: function () { keyword: function () {
return random.pick([ return random.pick([
"lime", "red", "blue", "invert", "currentColor", "ActiveBorder", "ActiveCaption", 'lime', 'red', 'blue', 'invert', 'currentColor', 'ActiveBorder', 'ActiveCaption',
"AppWorkspace", "Background", "ButtonFace", "ButtonHighlight", "ButtonShadow", 'AppWorkspace', 'Background', 'ButtonFace', 'ButtonHighlight', 'ButtonShadow',
"ButtonText", "CaptionText", "GrayText", "Highlight", "HighlightText", 'ButtonText', 'CaptionText', 'GrayText', 'Highlight', 'HighlightText',
"InactiveBorder", "InactiveCaption", "InactiveCaptionText", "InfoBackground", 'InactiveBorder', 'InactiveCaption', 'InactiveCaptionText', 'InfoBackground',
"InfoText", "Menu", "MenuText", "Scrollbar", "ThreeDDarkShadow", "ThreeDFace", 'InfoText', 'Menu', 'MenuText', 'Scrollbar', 'ThreeDDarkShadow', 'ThreeDFace',
"ThreeDHighlight", "ThreeDLightShadow", "ThreeDShadow", "Window", "WindowFrame", 'ThreeDHighlight', 'ThreeDLightShadow', 'ThreeDShadow', 'Window', 'WindowFrame',
"WindowText", "-moz-ButtonDefault", "-moz-ButtonHoverFace", "-moz-ButtonHoverText", 'WindowText', '-moz-ButtonDefault', '-moz-ButtonHoverFace', '-moz-ButtonHoverText',
"-moz-CellHighlight", "-moz-CellHighlightText", "-moz-Combobox", "-moz-ComboboxText", '-moz-CellHighlight', '-moz-CellHighlightText', '-moz-Combobox', '-moz-ComboboxText',
"-moz-Dialog", "-moz-DialogText", "-moz-dragtargetzone", "-moz-EvenTreeRow", '-moz-Dialog', '-moz-DialogText', '-moz-dragtargetzone', '-moz-EvenTreeRow',
"-moz-Field", "-moz-FieldText", "-moz-html-CellHighlight", '-moz-Field', '-moz-FieldText', '-moz-html-CellHighlight',
"-moz-html-CellHighlightText", "-moz-mac-accentdarkestshadow", '-moz-html-CellHighlightText', '-moz-mac-accentdarkestshadow',
"-moz-mac-accentdarkshadow", "-moz-mac-accentface", '-moz-mac-accentdarkshadow', '-moz-mac-accentface',
"-moz-mac-accentlightesthighlight", "-moz-mac-accentlightshadow", '-moz-mac-accentlightesthighlight', '-moz-mac-accentlightshadow',
"-moz-mac-accentregularhighlight", "-moz-mac-accentregularshadow", '-moz-mac-accentregularhighlight', '-moz-mac-accentregularshadow',
"-moz-mac-chrome-active", "-moz-mac-chrome-inactive", "-moz-mac-focusring", '-moz-mac-chrome-active', '-moz-mac-chrome-inactive', '-moz-mac-focusring',
"-moz-mac-menuselect", "-moz-mac-menushadow", "-moz-mac-menutextselect", '-moz-mac-menuselect', '-moz-mac-menushadow', '-moz-mac-menutextselect',
"-moz-MenuHover", "-moz-MenuHoverText", "-moz-MenuBarText", "-moz-MenuBarHoverText", '-moz-MenuHover', '-moz-MenuHoverText', '-moz-MenuBarText', '-moz-MenuBarHoverText',
"-moz-nativehyperlinktext", "-moz-OddTreeRow", "-moz-win-communicationstext", '-moz-nativehyperlinktext', '-moz-OddTreeRow', '-moz-win-communicationstext',
"-moz-win-mediatext", "-moz-activehyperlinktext", "-moz-default-background-color", '-moz-win-mediatext', '-moz-activehyperlinktext', '-moz-default-background-color',
"-moz-default-color", "-moz-hyperlinktext", "-moz-visitedhyperlinktext" '-moz-default-color', '-moz-hyperlinktext', '-moz-visitedhyperlinktext'
]); ])
} }
}; }

View File

@ -5,41 +5,41 @@
make.files = { make.files = {
image: function () { image: function () {
return utils.quote(random.pick([ return utils.quote(random.pick([
"data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs=", 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs=',
"data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==", 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==',
"data:image/gif;base64,R0lGODlhAQABAAAAACwAAAAAAQABAAA=", 'data:image/gif;base64,R0lGODlhAQABAAAAACwAAAAAAQABAAA=',
"data:image/gif;base64,R0lGODlhAQABAAAAACw=", 'data:image/gif;base64,R0lGODlhAQABAAAAACw=',
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAAAAAA6fptVAAAACklEQVQYV2P4DwABAQEAWk1v8QAAAABJRU5ErkJggg==", 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAAAAAA6fptVAAAACklEQVQYV2P4DwABAQEAWk1v8QAAAABJRU5ErkJggg==',
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVQYV2NgYAAAAAMAAWgmWQ0AAAAASUVORK5CYII=", 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVQYV2NgYAAAAAMAAWgmWQ0AAAAASUVORK5CYII=',
"media/images/image1.jpg", 'media/images/image1.jpg',
"media/images/image3.jpg" 'media/images/image3.jpg'
])); ]))
}, },
video: function () { video: function () {
return utils.quote(random.pick([ return utils.quote(random.pick([
"media/video/video1.webm", 'media/video/video1.webm',
"media/video/video2.webm" 'media/video/video2.webm'
])); ]))
}, },
audio: function () { audio: function () {
return utils.quote(random.pick([ return utils.quote(random.pick([
"media/audio/mono-uncompressed-8bit-8000hz.wav", 'media/audio/mono-uncompressed-8bit-8000hz.wav',
"media/audio/mono-uncompressed-8bit-44100hz.wav", 'media/audio/mono-uncompressed-8bit-44100hz.wav',
"media/audio/mono-uncompressed-32bit-8000hz.wav", 'media/audio/mono-uncompressed-32bit-8000hz.wav',
"media/audio/mono-uncompressed-32bit-44100hz.wav" 'media/audio/mono-uncompressed-32bit-44100hz.wav'
])); ]))
}, },
webvtt: function () { webvtt: function () {
return utils.quote(random.pick([ return utils.quote(random.pick([
//'data:text/vtt,' + encodeURIComponent('WEBVTT\n\n00:00:00.000 --> 00:00:00.001\ntest');, // 'data:text/vtt,' + encodeURIComponent('WEBVTT\n\n00:00:00.000 --> 00:00:00.001\ntest');,
"media/video/sample.vtt" 'media/video/sample.vtt'
])); ]))
}, },
file: function () { file: function () {
return random.pick([ return random.pick([
make.files.image, make.files.image,
make.files.video, make.files.video,
make.files.audio make.files.audio
]); ])
}, }
}; }

View File

@ -3,67 +3,67 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
make.font = { make.font = {
globalValue: function() { globalValue: function () {
return random.pick(["inherit", "initial", "unset"]); return random.pick(['inherit', 'initial', 'unset'])
}, },
style: function () { style: function () {
return random.pick(["italic", "normal", "oblique", "inherit"]); return random.pick(['italic', 'normal', 'oblique', 'inherit'])
}, },
variant: function () { variant: function () {
return random.pick(["normal", "small-caps", "inherit"]); return random.pick(['normal', 'small-caps', 'inherit'])
}, },
weight: function () { weight: function () {
return random.pick([ return random.pick([
/* standard */ /* standard */
["normal", "bold"], ['normal', 'bold'],
/* Relative to the parent */ /* Relative to the parent */
["bolder", "lighter"], ['bolder', 'lighter'],
/* numeric values */ /* numeric values */
[100, 200, 300, 400, 500, 600, 700, 800, 900], [100, 200, 300, 400, 500, 600, 700, 800, 900]
]); ])
}, },
size: function () { size: function () {
return random.pick([ return random.pick([
/* <absolute-size> values */ /* <absolute-size> values */
["xx-small", "x-small", "small", "medium", "large", "x-large", "xx-large"], ['xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'],
/* <relative-size> values */ /* <relative-size> values */
["larger", "smaller"], ['larger', 'smaller'],
/* <length> values */ /* <length> values */
make.number.unsignedNumber() + make.unit.unit(), make.number.unsignedNumber() + make.unit.unit(),
/* <percentage> values */ /* <percentage> values */
make.unit.percent(), make.unit.percent()
]); ])
}, },
genericFamily: function () { genericFamily: function () {
return random.pick(["serif", "sans-serif", "cursive", "fantasy", "monospace"]); return random.pick(['serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'])
}, },
familyName: function () { familyName: function () {
return random.pick(["Times New Roman", "Arial", "Courier", "Helvetica"]); return random.pick(['Times New Roman', 'Arial', 'Courier', 'Helvetica'])
}, },
family: function () { family: function () {
let s = random.pick(make.font.familyName); let s = random.pick(make.font.familyName)
if (random.chance(8)) { if (random.chance(8)) {
s += ", " + random.pick(make.font.genericFamily); s += ', ' + random.pick(make.font.genericFamily)
} }
return s; return s
}, },
font: function () { font: function () {
let s = ""; let s = ''
if (random.chance(4)) { if (random.chance(4)) {
s += random.pick(make.font.style) + " "; s += random.pick(make.font.style) + ' '
} }
if (random.chance(4)) { if (random.chance(4)) {
s += random.pick(make.font.variant) + " "; s += random.pick(make.font.variant) + ' '
} }
if (random.chance(4)) { if (random.chance(4)) {
s += random.pick(make.font.weight) + " "; s += random.pick(make.font.weight) + ' '
} }
if (random.chance(4)) { if (random.chance(4)) {
s += make.number.any() + "/"; s += make.number.any() + '/'
} }
s += make.font.size(); s += make.font.size()
s += " "; s += ' '
s += make.font.family(); s += make.font.family()
return "'" + s + "'"; return '\'' + s + '\''
} }
}; }

View File

@ -1 +1 @@
var make = {}; var make = {}

View File

@ -10,63 +10,63 @@ make.mime = {
make.mime.image, make.mime.image,
make.mime.media, make.mime.media,
make.mime.form make.mime.form
]); ])
}, },
standard: function () { standard: function () {
return random.pick([ return random.pick([
"text/html", 'text/html',
"text/html; charset=utf-8", 'text/html; charset=utf-8',
"text/plain", 'text/plain',
"text/css", 'text/css',
"text/javascript", 'text/javascript',
"foo/bar", 'foo/bar',
"application/octet-stream", 'application/octet-stream',
"application/x-shockwave-flash", 'application/x-shockwave-flash',
"application/x-test", 'application/x-test'
]); ])
}, },
xml: function () { xml: function () {
return random.pick([ return random.pick([
"application/xml", 'application/xml',
"text/xml", 'text/xml',
"application/xhtml+xml", 'application/xhtml+xml',
"image/svg+xml", 'image/svg+xml',
"application/vnd.mozilla.xul+xml", 'application/vnd.mozilla.xul+xml',
"application/rss+xml", 'application/rss+xml',
"application/rdf+xml", 'application/rdf+xml',
"application/xslt+xml", 'application/xslt+xml'
]); ])
}, },
image: function () { image: function () {
return random.pick([ return random.pick([
"image/jpeg", 'image/jpeg',
"image/gif", 'image/gif',
"image/png", 'image/png',
"image/mng", 'image/mng',
"image/*", 'image/*'
]); ])
}, },
media: function () { media: function () {
return random.pick([ return random.pick([
"audio/mpeg", 'audio/mpeg',
"audio/ogg", 'audio/ogg',
"audio/ogg; codecs=vorbis", 'audio/ogg; codecs=vorbis',
"video/ogg", 'video/ogg',
"video/ogg; codecs=\"theora, vorbis\"", 'video/ogg; codecs="theora, vorbis"',
"video/mp4", 'video/mp4',
"video/mp4; codecs=\"avc1.42E01E, mp4a.40.2\"", 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"'
]); ])
}, },
form: function () { form: function () {
return random.pick([ return random.pick([
"application/x-www-form-urlencoded", 'application/x-www-form-urlencoded',
"multipart/form-data", 'multipart/form-data',
"text/plain" 'text/plain'
]); ])
}, }
}; }

View File

@ -6,82 +6,82 @@ make.network = {
sdp: function () { sdp: function () {
// session description protocol template // session description protocol template
return [ return [
"v=0", 'v=0',
"o=Mozilla-SIPUA 23597 0 IN IP4 0.0.0.0", 'o=Mozilla-SIPUA 23597 0 IN IP4 0.0.0.0',
"s=SIP Call", 's=SIP Call',
"t=0 0", 't=0 0',
"a=ice-ufrag:f5fda439", 'a=ice-ufrag:f5fda439',
"a=ice-pwd:d0df8e2904bdbd29587966e797655970", 'a=ice-pwd:d0df8e2904bdbd29587966e797655970',
"a=fingerprint:sha-256 DF:69:78:20:8D:2E:08:CE:49:82:A3:11:79:1D:BF:B5:49:49:2D:32:82:2F:0D:88:84:A7:C6:63:23:63:A9:0F", 'a=fingerprint:sha-256 DF:69:78:20:8D:2E:08:CE:49:82:A3:11:79:1D:BF:B5:49:49:2D:32:82:2F:0D:88:84:A7:C6:63:23:63:A9:0F',
"m=audio 52757 RTP/SAVPF 109 0 8 101", 'm=audio 52757 RTP/SAVPF 109 0 8 101',
"c=IN IP4 192.168.129.33", 'c=IN IP4 192.168.129.33',
"a=rtpmap:109 opus/48000/2", 'a=rtpmap:109 opus/48000/2',
"a=ptime:20", 'a=ptime:20',
"a=rtpmap:0 PCMU/8000", 'a=rtpmap:0 PCMU/8000',
"a=rtpmap:8 PCMA/8000", 'a=rtpmap:8 PCMA/8000',
"a=rtpmap:101 telephone-event/8000", 'a=rtpmap:101 telephone-event/8000',
"a=fmtp:101 0-15", 'a=fmtp:101 0-15',
"a=sendrecv", 'a=sendrecv',
"a=candidate:0 1 UDP 2113601791 192.168.129.33 52757 typ host", 'a=candidate:0 1 UDP 2113601791 192.168.129.33 52757 typ host',
"a=candidate:0 2 UDP 2113601790 192.168.129.33 59738 typ host", 'a=candidate:0 2 UDP 2113601790 192.168.129.33 59738 typ host',
"m=video 63901 RTP/SAVPF 120", 'm=video 63901 RTP/SAVPF 120',
"c=IN IP4 192.168.129.33", 'c=IN IP4 192.168.129.33',
"a=rtpmap:120 VP8/90000", 'a=rtpmap:120 VP8/90000',
"a=sendrecv", 'a=sendrecv',
"a=candidate:0 1 UDP 2113601791 192.168.129.33 63901 typ host", 'a=candidate:0 1 UDP 2113601791 192.168.129.33 63901 typ host',
"a=candidate:0 2 UDP 2113601790 192.168.129.33 54165 typ host", 'a=candidate:0 2 UDP 2113601790 192.168.129.33 54165 typ host',
"m=application 65080 SCTP/DTLS 5000", 'm=application 65080 SCTP/DTLS 5000',
"c=IN IP4 192.168.129.33", 'c=IN IP4 192.168.129.33',
"a=fmtp:5000 protocol=webrtc-datachannel;streams=16", 'a=fmtp:5000 protocol=webrtc-datachannel;streams=16',
"a=sendrecv", 'a=sendrecv',
"a=candidate:0 1 UDP 2113601791 192.168.129.33 65080 typ host", 'a=candidate:0 1 UDP 2113601791 192.168.129.33 65080 typ host',
"a=candidate:0 2 UDP 2113601790 192.168.129.33 62658 typ host", 'a=candidate:0 2 UDP 2113601790 192.168.129.33 62658 typ host'
].join("\n"); ].join('\n')
}, },
PeerConnectionProtocols: function () { PeerConnectionProtocols: function () {
return ["turn", "turns", "stun", "stuns"]; return ['turn', 'turns', 'stun', 'stuns']
}, },
randomIPv4: function () { randomIPv4: function () {
return random.pick([random.number(255), make.number.any]) + "." + return random.pick([random.number(255), make.number.any]) + '.' +
random.pick([random.number(255), make.number.any]) + "." + random.pick([random.number(255), make.number.any]) + '.' +
random.pick([random.number(255), make.number.any]) + "." + random.pick([random.number(255), make.number.any]) + '.' +
random.pick([random.number(255), make.number.any]); random.pick([random.number(255), make.number.any])
}, },
randomIPv6: function () { randomIPv6: function () {
return "[" + make.strings.stringFromBlocks([":", function () { return '[' + make.strings.stringFromBlocks([':', function () {
return make.strings.digitsHex(random.range(1, 4)); return make.strings.digitsHex(random.range(1, 4))
}]) + "]"; }]) + ']'
}, },
goodHostnames: function () { goodHostnames: function () {
return [ return [
"0.0.0.0", '0.0.0.0',
"127.0.0.1:8080", '127.0.0.1:8080'
]; ]
}, },
badHostnames: function () { badHostnames: function () {
return [ return [
"google.org:8080", 'google.org:8080',
"::1", '::1',
"[::192.9.5.5]:42", '[::192.9.5.5]:42',
"2001:db8:85a3::8a2e:370:3478", '2001:db8:85a3::8a2e:370:3478',
"2001:db8:85a3:0:0:8a2e:370:3478", '2001:db8:85a3:0:0:8a2e:370:3478',
"::ffff:192.0.2.1", '::ffff:192.0.2.1',
"0000:0000:0000:0000:0000:0000:0000:0001", '0000:0000:0000:0000:0000:0000:0000:0001',
"::192.0.2.128", '::192.0.2.128',
"::ffff:192.0.2.128", '::ffff:192.0.2.128',
"2001:db8::1:2", '2001:db8::1:2',
"2001:db8::1:1:1:1:1" '2001:db8::1:1:1:1:1'
]; ]
}, },
randomBitmask: function (list) { randomBitmask: function (list) {
if (list.length <= 1) { if (list.length <= 1) {
return list.join(""); return list.join('')
} }
let max = random.range(2, list.length); let max = random.range(2, list.length)
let mask = random.pick(list); let mask = random.pick(list)
for (let i = 1; i < max; i++) { for (let i = 1; i < max; i++) {
mask += "|" + random.pick(list); mask += '|' + random.pick(list)
} }
return mask; return mask
}, }
}; }

View File

@ -4,54 +4,54 @@
make.number = { make.number = {
bool: function () { bool: function () {
return random.bool(); return random.bool()
}, },
float: function () { float: function () {
let n; let n
if (random.chance(32)) { if (random.chance(32)) {
switch (random.number(4)) { switch (random.number(4)) {
case 0: case 0:
n = random.range(Number.MAX_VALUE, Number.MIN_VALUE); n = random.range(Number.MAX_VALUE, Number.MIN_VALUE)
break; break
case 1: case 1:
n = Math.pow(10, 1) / Math.pow(10, random.number(307)); n = Math.pow(10, 1) / Math.pow(10, random.number(307))
break; break
case 2: case 2:
n = Math.pow(2, random.float() * random.float() * 64); n = Math.pow(2, random.float() * random.float() * 64)
break; break
case 3: case 3:
n = Math.pow(10, random.range(1, 9)) / Math.pow(10, random.range(1, 9)); n = Math.pow(10, random.range(1, 9)) / Math.pow(10, random.range(1, 9))
break; break
} }
return n; return n
} }
switch (random.number(6)) { switch (random.number(6)) {
default: default:
n = random.float(); n = random.float()
} }
return n; return n
}, },
rangeNumber: function () { rangeNumber: function () {
return random.pick([1, 2, 3, 4, 6, 8, 16, 32, 64, make.number.tinyNumber]); return random.pick([1, 2, 3, 4, 6, 8, 16, 32, 64, make.number.tinyNumber])
}, },
tinyNumber: function () { tinyNumber: function () {
return Math.pow(2, random.number(12)); return Math.pow(2, random.number(12))
}, },
unsignedNumber: function () { unsignedNumber: function () {
if (random.chance(2)) { if (random.chance(2)) {
return Math.abs(make.number.any()); return Math.abs(make.number.any())
} }
return Math.pow(2, random.number(65)) + random.number(3) - 1; return Math.pow(2, random.number(65)) + random.number(3) - 1
}, },
evenNumber: function (number) { evenNumber: function (number) {
return number % 2 === 1 ? ++number : number; return number % 2 === 1 ? ++number : number
}, },
anynumber: function () { anynumber: function () {
let value = random.choose([ let value = random.choose([
[10, make.number.float], [10, make.number.float],
[10, [make.number.rangeNumber, make.number.tinyNumber]], [10, [make.number.rangeNumber, make.number.tinyNumber]],
[1, make.number.unsignedNumber] [1, make.number.unsignedNumber]
]); ])
return random.chance(10) ? -value : value; return random.chance(10) ? -value : value
} }
}; }

View File

@ -6,141 +6,141 @@ make.shaders = {
fragment1: function () { fragment1: function () {
return random.pick([ return random.pick([
[ [
"#ifdef GL_ES", '#ifdef GL_ES',
"precision mediump float;", 'precision mediump float;',
"#endif", '#endif',
"varying vec4 vColor;", 'varying vec4 vColor;',
"void main() {", 'void main() {',
"gl_FragColor=vColor;", 'gl_FragColor=vColor;',
"}", '}'
], ],
[ [
"varying highp vec2 vTextureCoord;", 'varying highp vec2 vTextureCoord;',
"varying highp vec3 vLighting;", 'varying highp vec3 vLighting;',
"uniform sampler2D uSampler;", 'uniform sampler2D uSampler;',
"void main(void) {", 'void main(void) {',
"highp vec4 texelColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t));", 'highp vec4 texelColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t));',
"gl_FragColor = vec4(texelColor.rgb * vLighting, texelColor.a);", 'gl_FragColor = vec4(texelColor.rgb * vLighting, texelColor.a);',
"}" '}'
] ]
]); ])
}, },
vertex1: function () { vertex1: function () {
return random.pick([ return random.pick([
[ [
"attribute vec4 aVertex;", 'attribute vec4 aVertex;',
"attribute vec4 aColor;", 'attribute vec4 aColor;',
"varying vec4 vColor;", 'varying vec4 vColor;',
"void main(){", 'void main(){',
"vColor=aColor;", 'vColor=aColor;',
"gl_Position=aVertex;", 'gl_Position=aVertex;',
"}", '}'
], ],
[ [
"attribute highp vec3 aVertexNormal;", 'attribute highp vec3 aVertexNormal;',
"attribute highp vec3 aVertexPosition;", 'attribute highp vec3 aVertexPosition;',
"attribute highp vec2 aTextureCoord;", 'attribute highp vec2 aTextureCoord;',
"uniform highp mat4 uNormalMatrix;", 'uniform highp mat4 uNormalMatrix;',
"uniform highp mat4 uMVMatrix;", 'uniform highp mat4 uMVMatrix;',
"uniform highp mat4 uPMatrix;", 'uniform highp mat4 uPMatrix;',
"varying highp vec2 vTextureCoord;", 'varying highp vec2 vTextureCoord;',
"varying highp vec3 vLighting;", 'varying highp vec3 vLighting;',
"void main(void) {", 'void main(void) {',
"gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);", 'gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);',
"vTextureCoord = aTextureCoord;", 'vTextureCoord = aTextureCoord;',
"highp vec3 ambientLight = vec3(0.6, 0.6, 0.6);", 'highp vec3 ambientLight = vec3(0.6, 0.6, 0.6);',
"highp vec3 directionalLightColor = vec3(0.5, 0.5, 0.75);", 'highp vec3 directionalLightColor = vec3(0.5, 0.5, 0.75);',
"highp vec3 directionalVector = vec3(0.85, 0.8, 0.75);", 'highp vec3 directionalVector = vec3(0.85, 0.8, 0.75);',
"highp vec4 transformedNormal = uNormalMatrix * vec4(aVertexNormal, 1.0);", 'highp vec4 transformedNormal = uNormalMatrix * vec4(aVertexNormal, 1.0);',
"highp float directional = max(dot(transformedNormal.xyz, directionalVector), 0.0);", 'highp float directional = max(dot(transformedNormal.xyz, directionalVector), 0.0);',
"vLighting = ambientLight + (directionalLightColor * directional);", 'vLighting = ambientLight + (directionalLightColor * directional);',
"}" '}'
] ]
]); ])
}, },
fragment2: function () { fragment2: function () {
return random.pick([ return random.pick([
[ [
"varying highp vec2 vTextureCoord;", 'varying highp vec2 vTextureCoord;',
"varying highp vec3 vLighting;", 'varying highp vec3 vLighting;',
"uniform sampler2D uSampler;", 'uniform sampler2D uSampler;',
"void main(void) {", 'void main(void) {',
"highp vec4 texelColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t));", 'highp vec4 texelColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t));',
"gl_FragColor = vec4(texelColor.rgb * vLighting, texelColor.a);", 'gl_FragColor = vec4(texelColor.rgb * vLighting, texelColor.a);',
"}" '}'
], ],
[ [
"#version proto-200", '#version proto-200',
"uniform sampler2D albedoMap;", 'uniform sampler2D albedoMap;',
"uniform sampler2D normalMap;", 'uniform sampler2D normalMap;',
"varying vec3 varyingTangent;", 'varying vec3 varyingTangent;',
"varying vec3 varyingBitangent;", 'varying vec3 varyingBitangent;',
"varying vec3 varyingNormal;", 'varying vec3 varyingNormal;',
"varying vec2 varyingUV;", 'varying vec2 varyingUV;',
"void main(void) {", 'void main(void) {',
"vec3 albedo=texture2D(albedoMap,varyingUV).rgb;", 'vec3 albedo=texture2D(albedoMap,varyingUV).rgb;',
"vec3 normal=texture2D(normalMap,varyingUV).rgb*2.0-1.0;", 'vec3 normal=texture2D(normalMap,varyingUV).rgb*2.0-1.0;',
"float specularFactor=pow((albedo.r+albedo.g+albedo.b)*0.33,2.0);", 'float specularFactor=pow((albedo.r+albedo.g+albedo.b)*0.33,2.0);',
"float specularHardness=2.0;", 'float specularHardness=2.0;',
"vec3 spaceNormal=varyingTangent*normal.x+varyingBitangent*normal.y+varyingNormal*normal.z;", 'vec3 spaceNormal=varyingTangent*normal.x+varyingBitangent*normal.y+varyingNormal*normal.z;',
"gl_FragData[0]=vec4(albedo,1.0);", 'gl_FragData[0]=vec4(albedo,1.0);',
"gl_FragData[1]=vec4(spaceNormal*0.5 +0.5,1.0);", 'gl_FragData[1]=vec4(spaceNormal*0.5 +0.5,1.0);',
"gl_FragData[2]=vec4(specularFactor,specularHardness*0.1,0.0,1.0);", 'gl_FragData[2]=vec4(specularFactor,specularHardness*0.1,0.0,1.0);',
"}" '}'
] ]
]); ])
}, },
vertex2: function () { vertex2: function () {
return random.pick([ return random.pick([
[ [
"attribute highp vec3 aVertexNormal;", 'attribute highp vec3 aVertexNormal;',
"attribute highp vec3 aVertexPosition;", 'attribute highp vec3 aVertexPosition;',
"attribute highp vec2 aTextureCoord;", 'attribute highp vec2 aTextureCoord;',
"uniform highp mat4 uNormalMatrix;", 'uniform highp mat4 uNormalMatrix;',
"uniform highp mat4 uMVMatrix;", 'uniform highp mat4 uMVMatrix;',
"uniform highp mat4 uPMatrix;", 'uniform highp mat4 uPMatrix;',
"varying highp vec2 vTextureCoord;", 'varying highp vec2 vTextureCoord;',
"varying highp vec3 vLighting;", 'varying highp vec3 vLighting;',
"void main(void) {", 'void main(void) {',
"gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);", 'gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);',
"vTextureCoord = aTextureCoord;", 'vTextureCoord = aTextureCoord;',
"highp vec3 ambientLight = vec3(0.6, 0.6, 0.6);", 'highp vec3 ambientLight = vec3(0.6, 0.6, 0.6);',
"highp vec3 directionalLightColor = vec3(0.5, 0.5, 0.75);", 'highp vec3 directionalLightColor = vec3(0.5, 0.5, 0.75);',
"highp vec3 directionalVector = vec3(0.85, 0.8, 0.75);", 'highp vec3 directionalVector = vec3(0.85, 0.8, 0.75);',
"highp vec4 transformedNormal = uNormalMatrix * vec4(aVertexNormal, 1.0);", 'highp vec4 transformedNormal = uNormalMatrix * vec4(aVertexNormal, 1.0);',
"highp float directional = max(dot(transformedNormal.xyz, directionalVector), 0.0);", 'highp float directional = max(dot(transformedNormal.xyz, directionalVector), 0.0);',
"vLighting = ambientLight + (directionalLightColor * directional);", 'vLighting = ambientLight + (directionalLightColor * directional);',
"}" '}'
], ],
[ [
"#version proto-200", '#version proto-200',
"attribute vec3 vertexPosition;", 'attribute vec3 vertexPosition;',
"attribute vec3 vertexTangent;", 'attribute vec3 vertexTangent;',
"attribute vec3 vertexBitangent;", 'attribute vec3 vertexBitangent;',
"attribute vec3 vertexNormal;", 'attribute vec3 vertexNormal;',
"attribute vec2 vertexUV;", 'attribute vec2 vertexUV;',
"uniform mat4 modelMatrix;", 'uniform mat4 modelMatrix;',
"uniform mat4 viewMatrix;", 'uniform mat4 viewMatrix;',
"varying vec3 varyingTangent;", 'varying vec3 varyingTangent;',
"varying vec3 varyingBitangent;", 'varying vec3 varyingBitangent;',
"varying vec3 varyingNormal;", 'varying vec3 varyingNormal;',
"varying vec2 varyingUV;", 'varying vec2 varyingUV;',
"void main(void){", 'void main(void){',
"gl_Position=viewMatrix*(modelMatrix*vec4(vertexPosition,1.0));", 'gl_Position=viewMatrix*(modelMatrix*vec4(vertexPosition,1.0));',
"gl_Position.xy=gl_Position.xy*0.5+(float(gl_InstanceID)-0.5);", 'gl_Position.xy=gl_Position.xy*0.5+(float(gl_InstanceID)-0.5);',
"varyingTangent=(modelMatrix*vec4(vertexTangent,0.0)).xyz;", 'varyingTangent=(modelMatrix*vec4(vertexTangent,0.0)).xyz;',
"varyingBitangent=(modelMatrix*vec4(vertexBitangent,0.0)).xyz;", 'varyingBitangent=(modelMatrix*vec4(vertexBitangent,0.0)).xyz;',
"varyingNormal=(modelMatrix*vec4(vertexNormal,0.0)).xyz;", 'varyingNormal=(modelMatrix*vec4(vertexNormal,0.0)).xyz;',
"varyingUV = vertexUV;", 'varyingUV = vertexUV;',
"}" '}'
] ]
]); ])
}, },
shaderPair: function (v, f) { shaderPair: function (v, f) {
let i = random.number(v.length); let i = random.number(v.length)
return { return {
vertex: utils.common.quote(v[i].join("\n")), vertex: utils.common.quote(v[i].join('\n')),
fragment: utils.common.quote(f[i].join("\n")) fragment: utils.common.quote(f[i].join('\n'))
}; }
}, }
}; }

View File

@ -4,39 +4,39 @@
make.strings = { make.strings = {
toString: function (object) { toString: function (object) {
return object ? object.toSource() : '' + object; return object ? object.toSource() : '' + object
}, },
string: function (maxlen) { string: function (maxlen) {
let s = ""; let s = ''
if (maxlen === null || maxlen === undefined) { if (maxlen === null || maxlen === undefined) {
maxlen = make.number.rangeNumber(); maxlen = make.number.rangeNumber()
} }
for (let i = 0; i < maxlen; i++) { for (let i = 0; i < maxlen; i++) {
//s += String.fromCodePoint(Random.pick(make.fonts.layoutCharCodes)); // Todo: s += String.fromCodePoint(Random.pick(make.fonts.layoutCharCodes));
s += "A"; s += 'A'
} }
return s; return s
}, },
quotedString: function (maxlen) { quotedString: function (maxlen) {
return utils.common.quote(make.strings.string(maxlen)); return utils.common.quote(make.strings.string(maxlen))
}, },
stringFromBlocks: function (set, maxlen) { stringFromBlocks: function (set, maxlen) {
let s = ""; let s = ''
for (let i = 0; i < random.number(maxlen || 255); i++) { for (let i = 0; i < random.number(maxlen || 255); i++) {
s += random.pick(set); s += random.pick(set)
} }
return s; return s
}, },
digitsHex: function (n) { digitsHex: function (n) {
let s = ''; let s = ''
while (n-- > 0) { while (n-- > 0) {
s += (random.number(16)).toString(16); s += (random.number(16)).toString(16)
} }
return s; return s
}, }
}; }

View File

@ -5,30 +5,30 @@
make.text = { make.text = {
lineEnd: function () { lineEnd: function () {
return random.pick([ return random.pick([
"\n", "\r", "\r\n", "\n\r" '\n', '\r', '\r\n', '\n\r'
]); ])
}, },
controlChar: function () { controlChar: function () {
return random.pick([ return random.pick([
"\b", "\t", "\n", "\v", "\f", "\r", "\0", "\c", "\a", "\e" '\b', '\t', '\n', '\v', '\f', '\r', '\0', '\c', '\a', '\e' // eslint-disable-line no-useless-escape
]); ])
}, },
token: function () { token: function () {
return random.pick([ return random.pick([
'*', '+', '%', '-', '!', '^', ':', '|', '&', '<', '>', '.', '"', '*', '+', '%', '-', '!', '^', ':', '|', '&', '<', '>', '.', '"',
'#', ' ', ';', ',', '{', '}', '(', ')', '[', ']', '/', '\\', '/*', '*/' '#', ' ', ';', ',', '{', '}', '(', ')', '[', ']', '/', '\\', '/*', '*/'
]); ])
}, },
charset: function () { charset: function () {
return random.pick([ return random.pick([
"UTF-8", "ISO-8859-1" 'UTF-8', 'ISO-8859-1'
]); ])
}, },
language: function () { language: function () {
// https://gist.github.com/tonyhb/635401 // https://gist.github.com/tonyhb/635401
return random.pick([ return random.pick([
"en-US", "en", "de" 'en-US', 'en', 'de'
]); ])
}, },
layoutCharCodes: function () { layoutCharCodes: function () {
return random.pick([ return random.pick([
@ -96,7 +96,7 @@ make.text = {
0x2061, // mathematical function application 0x2061, // mathematical function application
0x2064, // mathematical invisible separator 0x2064, // mathematical invisible separator
0x2044 // fraction slash character 0x2044 // fraction slash character
]); ])
}, },
// http://www.unicode.org/Public/6.0.0/ucd/UnicodeData.txt // http://www.unicode.org/Public/6.0.0/ucd/UnicodeData.txt
@ -120,13 +120,13 @@ make.text = {
[0x1D17B, 0x1D18B], [0x1D17B, 0x1D18B],
[0x1D1AA, 0x1D1AD], [0x1D1AA, 0x1D1AD],
[0x1D242, 0x1D244] [0x1D242, 0x1D244]
]); ])
}, },
unicodeBMP: function () { unicodeBMP: function () {
return random.item([ return random.item([
// BMP = Basic Multilingual Plane // BMP = Basic Multilingual Plane
[0x0000, 0xFFFF] [0x0000, 0xFFFF]
]); ])
}, },
unicodeSMP: function () { unicodeSMP: function () {
return random.item([ return random.item([
@ -136,20 +136,20 @@ make.text = {
[0x1B000, 0x1BFFF], [0x1B000, 0x1BFFF],
[0x1D000, 0x1DFFF], [0x1D000, 0x1DFFF],
[0x1F000, 0x1FFFF] [0x1F000, 0x1FFFF]
]); ])
}, },
unicodeSIP: function () { unicodeSIP: function () {
return random.item([ return random.item([
// SIP = Supplementary Ideographic Plane // SIP = Supplementary Ideographic Plane
[0x20000, 0x2BFFF], [0x20000, 0x2BFFF],
[0x2F000, 0x2FFFF] [0x2F000, 0x2FFFF]
]); ])
}, },
unicodeSSP: function () { unicodeSSP: function () {
return random.item([ return random.item([
// SSP = Supplementary Special-purpose Plane // SSP = Supplementary Special-purpose Plane
[0xE0000, 0xE0FFF] [0xE0000, 0xE0FFF]
]); ])
}, },
registeredFontFeatures: function () { registeredFontFeatures: function () {
return random.pick([ return random.pick([
@ -168,23 +168,23 @@ make.text = {
'ss14', 'ss15', 'ss16', 'ss17', 'ss18', 'ss19', 'ss20', 'subs', 'sups', 'ss14', 'ss15', 'ss16', 'ss17', 'ss18', 'ss19', 'ss20', 'subs', 'sups',
'swsh', 'titl', 'tjmo', 'tnam', 'tnum', 'trad', 'twid', 'unic', 'valt', 'swsh', 'titl', 'tjmo', 'tnam', 'tnum', 'trad', 'twid', 'unic', 'valt',
'vatu', 'vert', 'vhal', 'vjmo', 'vkna', 'vkrn', 'vpal', 'vrt2', 'zero' 'vatu', 'vert', 'vhal', 'vjmo', 'vkna', 'vkrn', 'vpal', 'vrt2', 'zero'
]); ])
}, },
assignmentOperator: function () { assignmentOperator: function () {
return random.pick([ return random.pick([
"=", "-=", "+=", "*=", "/=" '=', '-=', '+=', '*=', '/='
]); ])
}, },
arithmeticOperator: function () { arithmeticOperator: function () {
return random.pick([ return random.pick([
"%", "-", "+", "*", "/" '%', '-', '+', '*', '/'
]); ])
}, },
currency: function () { currency: function () {
return random.pick([ return random.pick([
// https://en.wikipedia.org/wiki/ISO_4217 // https://en.wikipedia.org/wiki/ISO_4217
"USD", "USS", "USN", "EUR", "CHF", "GBP", "XAG", "XBA", "XBB", "XBC", 'USD', 'USS', 'USN', 'EUR', 'CHF', 'GBP', 'XAG', 'XBA', 'XBB', 'XBC',
"XBD", "XSU", "XTS", "XXX", 'XBD', 'XSU', 'XTS', 'XXX'
]); ])
}, }
}; }

View File

@ -5,14 +5,14 @@
make.types = { make.types = {
random: function () { random: function () {
return random.item([ return random.item([
"true", 'true',
"null", 'null',
"(new Object())", '(new Object())',
"undefined", 'undefined',
"{}", '{}',
"[]", '[]',
"''", '\'\'',
"function() {}" 'function() {}'
]); ])
} }
}; }

View File

@ -5,13 +5,13 @@
make.unit = { make.unit = {
unit: function () { unit: function () {
return random.pick([ return random.pick([
"px", "em", "ex", "ch", "rem", "mm", "cm", "in", "pt", "pc", "%" 'px', 'em', 'ex', 'ch', 'rem', 'mm', 'cm', 'in', 'pt', 'pc', '%'
]); ])
}, },
length: function () { length: function () {
return make.number.any() + make.unit.unit(); return make.number.any() + make.unit.unit()
}, },
percent: function () { percent: function () {
return make.number.any() + "%"; return make.number.any() + '%'
}, }
}; }

View File

@ -9,78 +9,78 @@
* *
*/ */
function MersenneTwister() { function MersenneTwister () {
const N = 624; const N = 624
const M = 397; const M = 397
const UPPER_MASK = 0x80000000; const UPPER_MASK = 0x80000000
const LOWER_MASK = 0x7fffffff; const LOWER_MASK = 0x7fffffff
const MAG01 = new Int32Array([0, 0x9908b0df]); const MAG01 = new Int32Array([0, 0x9908b0df])
let mt = new Int32Array(N); let mt = new Int32Array(N)
/* the array for the state vector */ /* the array for the state vector */
let mti = 625; let mti = 625
this.seed = function (s) { this.seed = function (s) {
mt[0] = s | 0; mt[0] = s | 0
for (mti = 1; mti < N; mti++) { for (mti = 1; mti < N; mti++) {
mt[mti] = Math.imul(1812433253, mt[mti - 1] ^ (mt[mti - 1] >>> 30)) + mti; mt[mti] = Math.imul(1812433253, mt[mti - 1] ^ (mt[mti - 1] >>> 30)) + mti
} }
}; }
this.export_state = function () { this.export_state = function () {
return [mt, mti]; return [mt, mti]
}; }
this.import_state = function (s) { this.import_state = function (s) {
mt = s[0]; mt = s[0]
mti = s[1]; mti = s[1]
}; }
this.export_mta = function () { this.export_mta = function () {
return mt; return mt
}; }
this.import_mta = function (_mta) { this.import_mta = function (_mta) {
mt = _mta; mt = _mta
}; }
this.export_mti = function () { this.export_mti = function () {
return mti; return mti
}; }
this.import_mti = function (_mti) { this.import_mti = function (_mti) {
mti = _mti; mti = _mti
}; }
this.int32 = function () { this.int32 = function () {
let y, kk; let y, kk
if (mti >= N) { /* generate N words at one time */ if (mti >= N) { /* generate N words at one time */
for (kk = 0; kk < N - M; kk++) { for (kk = 0; kk < N - M; kk++) {
y = ((mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK)); y = ((mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK))
mt[kk] = (mt[kk + M] ^ (y >>> 1) ^ MAG01[y & 0x1]); mt[kk] = (mt[kk + M] ^ (y >>> 1) ^ MAG01[y & 0x1])
} }
for (; kk < N - 1; kk++) { for (; kk < N - 1; kk++) {
y = ((mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK)); y = ((mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK))
mt[kk] = (mt[kk + (M - N)] ^ (y >>> 1) ^ MAG01[y & 0x1]); mt[kk] = (mt[kk + (M - N)] ^ (y >>> 1) ^ MAG01[y & 0x1])
} }
y = ((mt[N - 1] & UPPER_MASK) | (mt[0] & LOWER_MASK)); y = ((mt[N - 1] & UPPER_MASK) | (mt[0] & LOWER_MASK))
mt[N - 1] = (mt[M - 1] ^ (y >>> 1) ^ MAG01[y & 0x1]); mt[N - 1] = (mt[M - 1] ^ (y >>> 1) ^ MAG01[y & 0x1])
mti = 0; mti = 0
} }
y = mt[mti++]; y = mt[mti++]
/* Tempering */ /* Tempering */
y = y ^ (y >>> 11); y = y ^ (y >>> 11)
y = y ^ ((y << 7) & 0x9d2c5680); y = y ^ ((y << 7) & 0x9d2c5680)
y = y ^ ((y << 15) & 0xefc60000); y = y ^ ((y << 15) & 0xefc60000)
y = y ^ (y >>> 18); y = y ^ (y >>> 18)
return y >>> 0; return y >>> 0
}; }
this.real2 = function () { this.real2 = function () {
return ((this.int32() >>> 5) * 67108864.0 + (this.int32() >>> 6)) / 9007199254740992.0; return ((this.int32() >>> 5) * 67108864.0 + (this.int32() >>> 6)) / 9007199254740992.0
}; }
} }

View File

@ -11,155 +11,156 @@ var random = {
*/ */
init: function (seed) { init: function (seed) {
if (seed === null || seed === undefined) { if (seed === null || seed === undefined) {
seed = new Date().getTime(); seed = new Date().getTime()
} }
this.twister = new MersenneTwister(); this.twister = new MersenneTwister()
this.twister.seed(seed); this.twister.seed(seed)
}, },
number: function (limit) { number: function (limit) {
// Returns an integer in [0, limit). Uniform distribution. // Returns an integer in [0, limit). Uniform distribution.
if (limit === 0) { if (limit === 0) {
return limit; return limit
} }
if (limit === null || limit === undefined) { if (limit === null || limit === undefined) {
limit = 0xffffffff; limit = 0xffffffff
} }
let x = (0x100000000 / limit) >>> 0, let x = (0x100000000 / limit) >>> 0
y = (x * limit) >>> 0, r; let y = (x * limit) >>> 0
let r
do { do {
r = this.twister.int32(); r = this.twister.int32()
} while (y && r >= y); } while (y && r >= y) // eslint-disable-line no-unmodified-loop-condition
return (r / x) >>> 0; return (r / x) >>> 0
}, },
float: function () { float: function () {
// Returns a float in [0, 1). Uniform distribution. // Returns a float in [0, 1). Uniform distribution.
return this.twister.real2(); return this.twister.real2()
}, },
range: function (start, limit) { range: function (start, limit) {
// Returns an integer in [start, limit]. Uniform distribution. // Returns an integer in [start, limit]. Uniform distribution.
if (isNaN(start) || isNaN(limit)) { if (isNaN(start) || isNaN(limit)) {
logger.traceback(); logger.console.traceback()
throw new TypeError("random.range() received a non number type: '" + start + "', '" + limit + "')"); throw new TypeError('random.range() received a non number type: \'' + start + '\', \'' + limit + '\')')
} }
return this.number(limit - start + 1) + start; return this.number(limit - start + 1) + start
}, },
ludOneTo: function (limit) { ludOneTo: function (limit) {
// Returns a float in [1, limit]. The logarithm has uniform distribution. // Returns a float in [1, limit]. The logarithm has uniform distribution.
return Math.exp(this.float() * Math.log(limit)); return Math.exp(this.float() * Math.log(limit))
}, },
item: function (list) { item: function (list) {
if (!(list instanceof Array || (list !== undefined && typeof list !== "string" && list.hasOwnProperty("length")))) { if (!(list instanceof Array || (list !== undefined && typeof list !== 'string' && list.hasOwnProperty('length')))) {
logger.traceback(); logger.console.traceback()
throw new TypeError("this.item() received a non array type: '" + list + "'"); throw new TypeError('this.item() received a non array type: \'' + list + '\'')
} }
return list[this.number(list.length)]; return list[this.number(list.length)]
}, },
key: function (obj) { key: function (obj) {
let list = []; let list = []
for (let i in obj) { for (let i in obj) {
list.push(i); list.push(i)
} }
return this.item(list); return this.item(list)
}, },
bool: function () { bool: function () {
return this.item([true, false]); return this.item([true, false])
}, },
pick: function (obj) { pick: function (obj) {
if (typeof obj === "function") { if (typeof obj === 'function') {
return obj(); return obj()
} }
if (obj instanceof Array) { if (obj instanceof Array) {
return this.pick(this.item(obj)); return this.pick(this.item(obj))
} }
return obj; return obj
}, },
chance: function (limit) { chance: function (limit) {
if (limit === null || limit === undefined) { if (limit === null || limit === undefined) {
limit = 2; limit = 2
} }
if (isNaN(limit)) { if (isNaN(limit)) {
logger.traceback(); logger.traceback()
throw new TypeError("random.chance() received a non number type: '" + limit + "'"); throw new TypeError('random.chance() received a non number type: \'' + limit + '\'')
} }
return this.number(limit) === 1; return this.number(limit) === 1
}, },
choose: function (list, flat) { choose: function (list, flat) {
if (!(list instanceof Array)) { if (!(list instanceof Array)) {
logger.traceback(); logger.console.traceback()
throw new TypeError("random.choose() received a non-array type: '" + list + "'"); throw new TypeError('random.choose() received a non-array type: \'' + list + '\'')
} }
let total = 0; let total = 0
for (let i = 0; i < list.length; i++) { for (let i = 0; i < list.length; i++) {
total += list[i][0]; total += list[i][0]
} }
let n = this.number(total); let n = this.number(total)
for (let i = 0; i < list.length; i++) { for (let i = 0; i < list.length; i++) {
if (n < list[i][0]) { if (n < list[i][0]) {
if (flat === true) { if (flat === true) {
return list[i][1]; return list[i][1]
} else { } else {
return this.pick([list[i][1]]); return this.pick([list[i][1]])
} }
} }
n = n - list[i][0]; n = n - list[i][0]
} }
if (flat === true) { if (flat === true) {
return list[0][1]; return list[0][1]
} }
return this.pick([list[0][1]]); return this.pick([list[0][1]])
}, },
weighted: function (wa) { weighted: function (wa) {
// More memory-hungry but hopefully faster than random.choose$flat // More memory-hungry but hopefully faster than random.choose$flat
let a = []; let a = []
for (let i = 0; i < wa.length; ++i) { for (let i = 0; i < wa.length; ++i) {
for (let j = 0; j < wa[i].w; ++j) { for (let j = 0; j < wa[i].w; ++j) {
a.push(wa[i].v); a.push(wa[i].v)
} }
} }
return a; return a
}, },
use: function (obj) { use: function (obj) {
return this.bool() ? obj : ""; return this.bool() ? obj : ''
}, },
shuffle: function (arr) { shuffle: function (arr) {
let i = arr.length; let i = arr.length
while (i--) { while (i--) {
let p = this.number(i + 1); let p = this.number(i + 1)
let t = arr[i]; let t = arr[i]
arr[i] = arr[p]; arr[i] = arr[p]
arr[p] = t; arr[p] = t
} }
}, },
shuffled: function (arr) { shuffled: function (arr) {
let newArray = arr.slice(); let newArray = arr.slice()
this.shuffle(newArray); this.shuffle(newArray)
return newArray; return newArray
}, },
subset: function (list, limit) { subset: function (list, limit) {
if (!(list instanceof Array)) { if (!(list instanceof Array)) {
logger.traceback(); logger.console.traceback()
throw new TypeError("random.some() received a non-array type: '" + list + "'"); throw new TypeError('random.some() received a non-array type: \'' + list + '\'')
} }
if (typeof limit !== 'number') { if (typeof limit !== 'number') {
limit = this.number(list.length + 1); limit = this.number(list.length + 1)
} }
let result = []; let result = []
for (let i = 0; i < limit; i++) { for (let i = 0; i < limit; i++) {
result.push(this.pick(list)); result.push(this.pick(list))
} }
return result; return result
}, },
pop: function (arr) { pop: function (arr) {
// Removes and returns a random item from an array // Removes and returns a random item from an array
let i, obj; let i, obj
i = this.number(arr.length); i = this.number(arr.length)
obj = arr[i]; obj = arr[i]
arr.splice(i, 1); arr.splice(i, 1)
return obj; return obj
}, },
hex: function(len) { hex: function (len) {
return Math.floor(Math.random() * ("0x1" + Array(len + 1).join("0"))).toString(16) return Math.floor(Math.random() * ('0x1' + Array(len + 1).join('0'))).toString(16)
}, }
}; }

View File

@ -6,35 +6,35 @@ utils.block = {
block: function (list, optional) { block: function (list, optional) {
if (optional === true) { if (optional === true) {
if (random.chance(6)) { if (random.chance(6)) {
return ''; return ''
} }
} }
function go_deeper(item) { function deeper (item) {
if (item === null || item === undefined) { if (item === null || item === undefined) {
return ""; return ''
} }
if (typeof(item) === "function") { if (typeof (item) === 'function') {
return item(); return item()
} }
if (typeof(item) === "string") { if (typeof (item) === 'string') {
return item; return item
} }
if (item instanceof (Array)) { if (item instanceof (Array)) {
let s = ""; let s = ''
for (let i = 0; i < item.length; i++) { for (let i = 0; i < item.length; i++) {
s += go_deeper(item[i]); s += deeper(item[i])
} }
return s; return s
} }
return item; return item
} }
let asString = ""; let asString = ''
for (let i = 0; i < list.length; i++) { for (let i = 0; i < list.length; i++) {
asString += go_deeper(list[i]); asString += deeper(list[i])
} }
return asString; return asString
} }
}; }

View File

@ -5,63 +5,64 @@
utils.common = { utils.common = {
objToString: function (obj) { objToString: function (obj) {
try { try {
return "" + obj return '' + obj
} catch (e) { } catch (e) {
return "[" + e + "]" return '[' + e + ']'
} }
}, },
getAllProperties: function (obj) { getAllProperties: function (obj) {
let list = []; let list = []
while (obj) { while (obj) {
list = list.concat(Object.getOwnPropertyNames(obj)); list = list.concat(Object.getOwnPropertyNames(obj))
obj = Object.getPrototypeOf(obj); obj = Object.getPrototypeOf(obj)
} }
return list; return list
}, },
getKeysFromHash: function (obj) { getKeysFromHash: function (obj) {
let list = []; let list = []
for (let p in obj) { for (let p in obj) {
list.push(p); list.push(p)
} }
return list; return list
}, },
quote: function (obj) { quote: function (obj) {
return JSON.stringify(obj); return JSON.stringify(obj)
}, },
shuffle: function (list) { shuffle: function (list) {
let newArray = list.slice(); let newArray = list.slice()
let len = newArray.length; let len = newArray.length
let i = len; let i = len
while (i--) { while (i--) {
let p = parseInt(Math.random() * len); let p = parseInt(Math.random() * len)
let t = newArray[i]; let t = newArray[i]
newArray[i] = newArray[p]; newArray[i] = newArray[p]
newArray[p] = t; newArray[p] = t
} }
return newArray; return newArray
}, },
uniqueList: function (list) { uniqueList: function (list) {
let tmp = {}, r = []; let tmp = {}
let r = []
for (let i = 0; i < list.length; i++) { for (let i = 0; i < list.length; i++) {
tmp[list[i]] = list[i]; tmp[list[i]] = list[i]
} }
for (let i in tmp) { for (let i in tmp) {
r.push(tmp[i]); r.push(tmp[i])
} }
return r; return r
}, },
mergeHash: function (obj1, obj2) { mergeHash: function (obj1, obj2) {
for (let p in obj2) { for (let p in obj2) {
try { try {
if (obj2[p].constructor === Object) { if (obj2[p].constructor === Object) {
obj1[p] = utils.common.mergeHash(obj1[p], obj2[p]); obj1[p] = utils.common.mergeHash(obj1[p], obj2[p])
} else { } else {
obj1[p] = obj2[p]; obj1[p] = obj2[p]
} }
} catch (e) { } catch (e) {
obj1[p] = obj2[p]; obj1[p] = obj2[p]
} }
} }
return obj1; return obj1
} }
}; }

View File

@ -1 +1 @@
var utils = {}; var utils = {}

View File

@ -2,106 +2,110 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var o = null; var o = null
// TODO: https://github.com/MozillaSecurity/octo/issues/7 // TODO: https://github.com/MozillaSecurity/octo/issues/7
function Objects() { function Objects () {
this.counter = 0; this.counter = 0
this.container = {}; this.container = {}
} }
Objects.prototype.add = function (category, member) { Objects.prototype.add = function (category, member) {
member = member ? member : "o" + this.counter; if (!member) {
if (!this.has(category)) { member = 'o' + this.counter
this.container[category] = [];
} }
this.container[category].push({type: category, name: member}); if (!this.has(category)) {
++this.counter; this.container[category] = []
return this.container[category].slice(-1)[0].name; }
}; this.container[category].push({type: category, name: member})
++this.counter
return this.container[category].slice(-1)[0].name
}
Objects.prototype.get = function (category, last) { Objects.prototype.get = function (category, last) {
if (!(category in this.container)) { if (!(category in this.container)) {
//return {type:null, name:null}; // return {type:null, name:null};
Utils.traceback(); logger.console.traceback()
throw new Error(category + " is not available."); throw new Error(category + ' is not available.')
} }
if (last) { if (last) {
return this.container[category].slice(-1)[0]; return this.container[category].slice(-1)[0]
} }
return Random.index(this.container[category]); return random.index(this.container[category])
}; }
Objects.prototype.pick = function (category, last) { Objects.prototype.pick = function (category, last) {
try { try {
return this.get(category, last).name; return this.get(category, last).name
} catch (e) { } catch (e) {
Utils.traceback(); logger.console.traceback()
throw Logger.JSError("Error: pick(" + category + ") " + category + " is undefined."); throw logger.console.JSError('Error: pick(' + category + ') ' + category + ' is undefined.')
} }
}; }
Objects.prototype.pop = function (objectName) { Objects.prototype.pop = function (objectName) {
var self = this; var self = this
Utils.getKeysFromHash(this.container).forEach(function (category) { utils.getKeysFromHash(this.container).forEach(function (category) {
self.container[category].forEach(function (obj) { self.container[category].forEach(function (obj) {
if (obj.name === objectName) { if (obj.name === objectName) {
self.container[category].splice(self.container[category].indexOf(obj), 1); self.container[category].splice(self.container[category].indexOf(obj), 1)
} }
}); })
}); })
}; }
Objects.prototype.contains = function (categoryNames) { Objects.prototype.contains = function (categoryNames) {
var categories = [], self = this; var categories = []
var self = this
categoryNames.forEach(function (name) { categoryNames.forEach(function (name) {
if (self.has(name)) { if (self.has(name)) {
categories.push(name); categories.push(name)
} }
}); })
return (categories.length === 0) ? null : categories; return (categories.length === 0) ? null : categories
}; }
Objects.prototype.show = function (category) { Objects.prototype.show = function (category) {
return (category in this.container) ? this.container[category] : this.container; return (category in this.container) ? this.container[category] : this.container
}; }
Objects.prototype.count = function (category) { Objects.prototype.count = function (category) {
return (category in this.container) ? this.container[category].length : 0; return (category in this.container) ? this.container[category].length : 0
}; }
Objects.prototype.has = function (category) { Objects.prototype.has = function (category) {
if (category in this.container) { if (category in this.container) {
this.check(category); this.check(category)
return !!(this.container[category].length > 0); return !!(this.container[category].length > 0)
} }
return false; return false
}; }
Objects.prototype.valid = function () { Objects.prototype.valid = function () {
var items = [], self = this; var items = []
Utils.getKeysFromHash(self.container).forEach(function (category) { var self = this
self.check(category); utils.common.getKeysFromHash(self.container).forEach(function (category) {
}); self.check(category)
Utils.getKeysFromHash(self.container).forEach(function (category) { })
utils.common.getKeysFromHash(self.container).forEach(function (category) {
for (var i = 0; i < self.container[category].length; i++) { for (var i = 0; i < self.container[category].length; i++) {
items.push(self.container[category][i].name); items.push(self.container[category][i].name)
} }
}); })
return items; return items
}; }
Objects.prototype.check = function (category) { Objects.prototype.check = function (category) {
var self = this; var self = this
self.container[category].forEach(function (object) { self.container[category].forEach(function (object) {
try { try {
var x = /*frame.contentWindow.*/eval(object.name); let x = /* frame.contentWindow. */ eval(object.name) // eslint-disable-line no-eval
if (x === undefined || x === null) { if (x === undefined || x === null) {
self.pop(object.name); self.pop(object.name)
} }
} catch (e) { } catch (e) {
self.pop(object.name); self.pop(object.name)
} }
}); })
}; }

View File

@ -4,99 +4,94 @@
utils.platform = { utils.platform = {
platform: function () { platform: function () {
var version, webkitVersion, platform = {}; var version, webkitVersion
var platform = {}
var userAgent = (navigator.userAgent).toLowerCase(); var userAgent = (navigator.userAgent).toLowerCase()
var language = navigator.language || navigator.browserLanguage; var language = navigator.language || navigator.browserLanguage
version = platform.version = (userAgent.match(/.*(?:rv|chrome|webkit|opera|ie)[\/: ](.+?)([ \);]|$)/) || [])[1]; version = platform.version = (userAgent.match(/.*(?:rv|chrome|webkit|opera|ie)[/: ](.+?)([ );]|$)/) || [])[1]
webkitVersion = (userAgent.match(/webkit\/(.+?) /) || [])[1]; webkitVersion = (userAgent.match(/webkit\/(.+?) /) || [])[1]
platform.windows = platform.isWindows = !!/windows/.test(userAgent); platform.windows = platform.isWindows = !!/windows/.test(userAgent)
platform.mac = platform.isMac = !!/macintosh/.test(userAgent) || (/mac os x/.test(userAgent) && !/like mac os x/.test(userAgent)); platform.mac = platform.isMac = !!/macintosh/.test(userAgent) || (/mac os x/.test(userAgent) && !/like mac os x/.test(userAgent))
platform.lion = platform.isLion = !!(/mac os x 10_7/.test(userAgent) && !/like mac os x 10_7/.test(userAgent)); platform.lion = platform.isLion = !!(/mac os x 10_7/.test(userAgent) && !/like mac os x 10_7/.test(userAgent))
platform.iPhone = platform.isiPhone = !!/iphone/.test(userAgent); platform.iPhone = platform.isiPhone = !!/iphone/.test(userAgent)
platform.iPod = platform.isiPod = !!/ipod/.test(userAgent); platform.iPod = platform.isiPod = !!/ipod/.test(userAgent)
platform.iPad = platform.isiPad = !!/ipad/.test(userAgent); platform.iPad = platform.isiPad = !!/ipad/.test(userAgent)
platform.iOS = platform.isiOS = platform.iPhone || platform.iPod || platform.iPad; platform.iOS = platform.isiOS = platform.iPhone || platform.iPod || platform.iPad
platform.android = platform.isAndroid = !!/android/.test(userAgent); platform.android = platform.isAndroid = !!/android/.test(userAgent)
platform.opera = /opera/.test(userAgent) ? version : 0; platform.opera = /opera/.test(userAgent) ? version : 0
platform.isOpera = !!platform.opera; platform.isOpera = !!platform.opera
platform.msie = /msie/.test(userAgent) && !platform.opera ? version : 0; platform.msie = /msie/.test(userAgent) && !platform.opera ? version : 0
platform.isIE = !!platform.msie; platform.isIE = !!platform.msie
platform.isIE8OrLower = !!(platform.msie && parseInt(platform.msie, 10) <= 8); platform.isIE8OrLower = !!(platform.msie && parseInt(platform.msie, 10) <= 8)
platform.mozilla = /mozilla/.test(userAgent) && !/(compatible|webkit|msie)/.test(userAgent) ? version : 0; platform.mozilla = /mozilla/.test(userAgent) && !/(compatible|webkit|msie)/.test(userAgent) ? version : 0
platform.isMozilla = !!platform.mozilla; platform.isMozilla = !!platform.mozilla
platform.webkit = /webkit/.test(userAgent) ? webkitVersion : 0; platform.webkit = /webkit/.test(userAgent) ? webkitVersion : 0
platform.isWebkit = !!platform.webkit; platform.isWebkit = !!platform.webkit
platform.chrome = /chrome/.test(userAgent) ? version : 0; platform.chrome = /chrome/.test(userAgent) ? version : 0
platform.isChrome = !!platform.chrome; platform.isChrome = !!platform.chrome
platform.mobileSafari = /apple.*mobile/.test(userAgent) && platform.iOS ? webkitVersion : 0; platform.mobileSafari = /apple.*mobile/.test(userAgent) && platform.iOS ? webkitVersion : 0
platform.isMobileSafari = !!platform.mobileSafari; platform.isMobileSafari = !!platform.mobileSafari
platform.iPadSafari = platform.iPad && platform.isMobileSafari ? webkitVersion : 0; platform.iPadSafari = platform.iPad && platform.isMobileSafari ? webkitVersion : 0
platform.isiPadSafari = !!platform.iPadSafari; platform.isiPadSafari = !!platform.iPadSafari
platform.iPhoneSafari = platform.iPhone && platform.isMobileSafari ? webkitVersion : 0; platform.iPhoneSafari = platform.iPhone && platform.isMobileSafari ? webkitVersion : 0
platform.isiPhoneSafari = !!platform.iphoneSafari; platform.isiPhoneSafari = !!platform.iphoneSafari
platform.iPodSafari = platform.iPod && platform.isMobileSafari ? webkitVersion : 0; platform.iPodSafari = platform.iPod && platform.isMobileSafari ? webkitVersion : 0
platform.isiPodSafari = !!platform.iPodSafari; platform.isiPodSafari = !!platform.iPodSafari
platform.isiOSHomeScreen = platform.isMobileSafari && !/apple.*mobile.*safari/.test(userAgent); platform.isiOSHomeScreen = platform.isMobileSafari && !/apple.*mobile.*safari/.test(userAgent)
platform.safari = platform.webkit && !platform.chrome && !platform.iOS && !platform.android ? webkitVersion : 0; platform.safari = platform.webkit && !platform.chrome && !platform.iOS && !platform.android ? webkitVersion : 0
platform.isSafari = !!platform.safari; platform.isSafari = !!platform.safari
platform.language = language.split("-", 1)[0]; platform.language = language.split('-', 1)[0]
platform.current = platform.current =
platform.msie ? "msie" : platform.msie ? 'msie' : platform.mozilla ? 'mozilla' : platform.chrome ? 'chrome' : platform.safari ? 'safari' : platform.opera ? 'opera' : platform.mobileSafari ? 'mobile-safari' : platform.android ? 'android' : 'unknown'
platform.mozilla ? "mozilla" :
platform.chrome ? "chrome" :
platform.safari ? "safari" :
platform.opera ? "opera" :
platform.mobileSafari ? "mobile-safari" :
platform.android ? "android" : "unknown";
function platformName(candidates) { function platformName (candidates) {
for (var i = 0; i < candidates.length; i++) { for (var i = 0; i < candidates.length; i++) {
if (candidates[i] in window) { if (candidates[i] in window) {
return "window." + candidates[i]; return 'window.' + candidates[i]
} }
if (candidates[i] in navigator) { if (candidates[i] in navigator) {
return "navigator." + candidates[i]; return 'navigator.' + candidates[i]
} }
} }
return undefined; return undefined
} }
platform.GUM = platformName(['getUserMedia', 'webkitGetUserMedia', 'mozGetUserMedia', 'msGetUserMedia', 'getGUM']); platform.GUM = platformName(['getUserMedia', 'webkitGetUserMedia', 'mozGetUserMedia', 'msGetUserMedia', 'getGUM'])
platform.PeerConnection = platformName(['webkitRTCPeerConnection', 'mozRTCPeerConnection', 'msPeerConnection']); platform.PeerConnection = platformName(['webkitRTCPeerConnection', 'mozRTCPeerConnection', 'msPeerConnection'])
platform.IceCandidate = platformName(['mozRTCIceCandidate', 'RTCIceCandidate']); platform.IceCandidate = platformName(['mozRTCIceCandidate', 'RTCIceCandidate'])
platform.SessionDescription = platformName(['mozRTCSessionDescription', 'RTCSessionDescription']); platform.SessionDescription = platformName(['mozRTCSessionDescription', 'RTCSessionDescription'])
platform.URL = platformName(['URL', 'webkitURL']); platform.URL = platformName(['URL', 'webkitURL'])
platform.AudioContext = platformName(['AudioContext', 'webkitAudioContext']); platform.AudioContext = platformName(['AudioContext', 'webkitAudioContext'])
platform.OfflineAudioContext = platformName(['OfflineAudioContext', 'webkitOfflineAudioContext']); platform.OfflineAudioContext = platformName(['OfflineAudioContext', 'webkitOfflineAudioContext'])
platform.MediaSource = platformName(["MediaSource", "WebKitMediaSource"]); platform.MediaSource = platformName(['MediaSource', 'WebKitMediaSource'])
platform.SpeechRecognition = platformName(["SpeechRecognition", "webkitSpeechRecognition"]); platform.SpeechRecognition = platformName(['SpeechRecognition', 'webkitSpeechRecognition'])
platform.SpeechGrammarList = platformName(["SpeechGrammarList", "webkitSpeechGrammarList"]); platform.SpeechGrammarList = platformName(['SpeechGrammarList', 'webkitSpeechGrammarList'])
function findWebGLContextName(candidates) { function findWebGLContextName (candidates) {
var canvas = document.createElement("canvas"); var canvas = document.createElement('canvas')
for (var i=0; i<candidates.length; i++) { for (var i = 0; i < candidates.length; i++) {
var name = candidates[i]; var name = candidates[i]
try { try {
if (canvas.getContext(name)) { if (canvas.getContext(name)) {
return name; return name
} }
} catch (e) {} } catch (e) {}
} }
return null; return null
} }
platform.WebGL = "webgl";//findWebGLContextName(["webgl", "experimental-webgl", "webkit-3d"]); platform.WebGL = 'webgl' // findWebGLContextName(["webgl", "experimental-webgl", "webkit-3d"]);
platform.WebGL2 = "webgl2";//findWebGLContextName(["webgl2", "experimental-webgl2"]); platform.WebGL2 = 'webgl2' // findWebGLContextName(["webgl2", "experimental-webgl2"]);
platform.captureStreamUntilEnded = "captureStreamUntilEnded"; platform.captureStreamUntilEnded = 'captureStreamUntilEnded'
if (platform.isMozilla) { platform.captureStreamUntilEnded = "mozCaptureStreamUntilEnded"; } if (platform.isMozilla) { platform.captureStreamUntilEnded = 'mozCaptureStreamUntilEnded' }
platform.srcObject = "srcObject"; platform.srcObject = 'srcObject'
if (platform.isMozilla) { platform.srcObject = "mozSrcObject"; } if (platform.isMozilla) { platform.srcObject = 'mozSrcObject' }
return platform; return platform
} }
}; }

View File

@ -5,60 +5,61 @@
// TODO: https://github.com/MozillaSecurity/octo/issues/7 // TODO: https://github.com/MozillaSecurity/octo/issues/7
if (!String.fromCodePoint) { if (!String.fromCodePoint) {
String.fromCodePoint = function fromCodePoint() { String.fromCodePoint = function fromCodePoint () {
var chars = [], point, offset, units, i; var chars = []
var point, offset, units, i
for (i = 0; i < arguments.length; ++i) { for (i = 0; i < arguments.length; ++i) {
point = arguments[i]; point = arguments[i]
offset = point - 0x10000; offset = point - 0x10000
units = point > 0xFFFF ? [0xD800 + (offset >> 10), 0xDC00 + (offset & 0x3FF)] : [point]; units = point > 0xFFFF ? [0xD800 + (offset >> 10), 0xDC00 + (offset & 0x3FF)] : [point]
chars.push(String.fromCharCode.apply(null, units)); chars.push(String.fromCharCode.apply(null, units))
} }
return chars.join(""); return chars.join('')
} }
} }
if (!String.prototype.endsWith) { if (!String.prototype.endsWith) {
String.prototype.endsWith = function (str) { return (this.match(str + "$") === str) }; String.prototype.endsWith = function (str) { return (this.match(str + '$') === str) }
} }
if (!String.prototype.startsWith) { if (!String.prototype.startsWith) {
String.prototype.startsWith = function (str) { String.prototype.startsWith = function (str) {
return (this.match("^" + str) === str) return (this.match('^' + str) === str)
}; }
} }
if (!String.prototype.trim) { if (!String.prototype.trim) {
String.prototype.trim = function () { String.prototype.trim = function () {
return (this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, "")) return (this.replace(/^[\s\xA0]+/, '').replace(/[\s\xA0]+$/, ''))
}; }
} }
if (!String.prototype.insert) { if (!String.prototype.insert) {
String.prototype.insert = function (data, idx) { String.prototype.insert = function (data, idx) {
return this.slice(0, idx) + data + this.slice(idx, this.length); return this.slice(0, idx) + data + this.slice(idx, this.length)
}; }
} }
if (!Array.prototype.has) { if (!Array.prototype.has) {
Array.prototype.has = function (v) { Array.prototype.has = function (v) {
return this.indexOf(v) !== -1; return this.indexOf(v) !== -1
}; }
} }
if (!Array.prototype.forEach) { if (!Array.prototype.forEach) {
Array.prototype.forEach = function (array, fn) { Array.prototype.forEach = function (array, fn) {
for (var i = 0; i < array.length; i++) { for (var i = 0; i < array.length; i++) {
fn(array[i]); fn(array[i])
} }
} }
} }
if (!Array.prototype.map) { if (!Array.prototype.map) {
Array.prototype.map = function (fn, array) { Array.prototype.map = function (fn, array) {
var result = []; var result = []
Array.forEach(array, function (element) { Array.forEach(array, function (element) {
result.push(fn(element)); result.push(fn(element))
}); })
return result; return result
} }
} }

View File

@ -5,33 +5,33 @@
utils.script = { utils.script = {
methodHead: function (list, numOptional) { methodHead: function (list, numOptional) {
if (isNaN(numOptional)) { if (isNaN(numOptional)) {
numOptional = 0; numOptional = 0
} }
var arity = list.length - random.number(numOptional); var arity = list.length - random.number(numOptional)
var params = []; var params = []
for (var i = 0; i < arity; i++) { for (var i = 0; i < arity; i++) {
params.push(random.pick([list[i]])); params.push(random.pick([list[i]]))
} }
return "(" + params.join(", ") + ")"; return '(' + params.join(', ') + ')'
}, },
methodCall: function (objectName, methodHash) { methodCall: function (objectName, methodHash) {
if (!utils.common.getKeysFromHash(methodHash).length || !objectName) { if (!utils.common.getKeysFromHash(methodHash).length || !objectName) {
return ""; return ''
} }
var methodName = random.key(methodHash); var methodName = random.key(methodHash)
var methodArgs = methodHash[methodName]; var methodArgs = methodHash[methodName]
if (typeof(methodArgs) === "function") { // Todo: Hmmmm.. if (typeof (methodArgs) === 'function') { // Todo: Hmmmm..
return methodArgs(); return methodArgs()
} }
return objectName + "." + methodName + utils.script.methodHead(methodArgs); return objectName + '.' + methodName + utils.script.methodHead(methodArgs)
}, },
setAttribute: function (objectName, attributeHash) { setAttribute: function (objectName, attributeHash) {
if (!utils.common.getKeysFromHash(attributeHash).length || !objectName) { if (!utils.common.getKeysFromHash(attributeHash).length || !objectName) {
return ""; return ''
} }
var attributeName = random.key(attributeHash); var attributeName = random.key(attributeHash)
var attributeValue = random.pick(attributeHash[attributeName]); var attributeValue = random.pick(attributeHash[attributeName])
var operator = " = "; var operator = ' = '
/* /*
if (typeof(attributeValue) == "number" && Random.chance(8)) { if (typeof(attributeValue) == "number" && Random.chance(8)) {
operator = " " + Make.randomAssignmentOperator() + " "; operator = " " + Make.randomAssignmentOperator() + " ";
@ -40,60 +40,62 @@ utils.script = {
attributeValue = "'" + attributeValue + "'"; attributeValue = "'" + attributeValue + "'";
} }
*/ */
return objectName + "." + attributeName + operator + attributeValue + ";"; return objectName + '.' + attributeName + operator + attributeValue + ';'
}, },
makeConstraint: function (keys, values) { makeConstraint: function (keys, values) {
var o = {}; var o = {}
var n = random.range(0, keys.length); var n = random.range(0, keys.length)
while (n--) { while (n--) {
o[random.pick(keys)] = random.pick(values); o[random.pick(keys)] = random.pick(values)
} }
return o; return o
}, },
makeRandomOptions: function (base_o) { makeRandomOptions: function (baseObject) {
var o = {}, unique = random.some(Object.keys(base_o)); var o = {}
var unique = random.some(Object.keys(baseObject))
for (var i = 0; i < unique.length; i++) { for (var i = 0; i < unique.length; i++) {
o[unique[i]] = random.pick(base_o[unique[i]]); o[unique[i]] = random.pick(baseObject[unique[i]])
} }
return JSON.stringify(o); return JSON.stringify(o)
}, },
safely: function (s) { safely: function (s) {
if (window.debug) { if (window.debug) {
return "try { " + s + " } catch(e) { logger.JSError(e); }"; return 'try { ' + s + ' } catch(e) { logger.JSError(e); }'
} }
return "try { " + s + " } catch(e) { }"; return 'try { ' + s + ' } catch(e) { }'
}, },
makeLoop: function (s, max) { makeLoop: function (s, max) {
return "for (var i = 0; i < " + (max || make.number.rangeNumber()) + "; i++) {" + s + "}"; return 'for (var i = 0; i < ' + (max || make.number.rangeNumber()) + '; i++) {' + s + '}'
}, },
makeArray: function (type, arrayLength, cb) { makeArray: function (type, arrayLength, cb) {
if (type === null || type === undefined) { if (type === null || type === undefined) {
type = random.index(["Uint8", "Float32"]); type = random.index(['Uint8', 'Float32'])
} }
switch (random.number(8)) { switch (random.number(8)) {
case 0: case 0:
var src = "function() { var buffer = new " + type + "Array(" + arrayLength + ");"; var src = 'function() { var buffer = new ' + type + 'Array(' + arrayLength + ');'
src += utils.script.makeLoop("buffer[i] = " + cb() + ";", arrayLength); src += utils.script.makeLoop('buffer[i] = ' + cb() + ';', arrayLength)
src += "return buffer;}()"; src += 'return buffer;}()'
return src; return src
case 1: case 1:
return "new " + type + "Array([" + make.arrays.filledArray(cb, arrayLength) + "])"; return 'new ' + type + 'Array([' + make.arrays.filledArray(cb, arrayLength) + '])'
default: default:
return "new " + type + "Array(" + arrayLength + ")"; return 'new ' + type + 'Array(' + arrayLength + ')'
} }
}, },
randListIndex: function (objName) { randListIndex: function (objName) {
return random.number() + ' % ' + o.pick(objName) + '.length'; return random.number() + ' % ' + o.pick(objName) + '.length'
}, },
addElementToBody: function (name) { addElementToBody: function (name) {
return "(document.body || document.documentElement).appendChild" + utils.script.methodHead([name]); return '(document.body || document.documentElement).appendChild' + utils.script.methodHead([name])
}, },
forceGC: function () { forceGC: function () {
if (platform.isMozilla) { if (platform.isMozilla) {
} }
if (platform.isChrome) { if (platform.isChrome) {
if (window.GCController) if (window.GCController) {
return GCController.collect(); return GCController.collect() // eslint-disable-line no-undef
}
} }
if (platform.isSafari) { if (platform.isSafari) {
} }
@ -101,6 +103,6 @@ utils.script = {
} }
}, },
getRandomElement: function () { getRandomElement: function () {
return "document.getElementsByTagName('*')[" + random.number(document.getElementsByTagName("*").length) + "]"; return 'document.getElementsByTagName(\'*\')[' + random.number(document.getElementsByTagName('*').length) + ']'
} }
}; }