Blob = function (array, opt) {
/*
* this function will create a node-compatible Blob instance
* https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob
*/
this.bff = local.bufferConcat(array.map(function (elem) {
return (
// ternary-operator
(
typeof elem === "string"
|| Object.prototype.toString.call(elem)
=== "[object Uint8Array]"
)
? elem
: String(elem)
);
}));
this.type = opt && opt.type;
}
...
var reader;
var tmp;
var utility2;
utility2 = globalThis.utility2 || {};
ajaxProgressUpdate = utility2.ajaxProgressUpdate || local.nop;
switch (evt.target.dataset.oneventDb) {
case "dbExport":
tmp = URL.createObjectURL(new globalThis.Blob([
local.dbExport()
]));
document.querySelector(
"#dbExportA1"
).href = tmp;
document.querySelector(
"#dbExportA1"
...
FormData = function () {
/*
* this function will create a serverLocal-compatible FormData instance
* The FormData(form) constructor must run these steps:
* 1. Let fd be a new FormData object.
* 2. If form is given, set fd's entries to the result
* of constructing the form data set for form. (not implemented)
* 3. Return fd.
* https://xhr.spec.whatwg.org/#dom-formdata
*/
this.entryList = [];
}
...
swaggerJson: local.swaggerJson
})[0];
// init default
local.objectSetDefault(opt, {
inForm: (
// ternary-operator
that._consumes0 === "multipart/form-data"
? new local.FormData()
: ""
),
inHeader: {},
inPath: that._path.replace((
/#.*?$/
), ""),
inQuery: "",
...
function Module(id = '', parent) { this.id = id; this.path = path.dirname(id); this.exports = {}; this.parent = parent; updateChildren(parent, this, false); this.filename = null; this.loaded = false; this.children = []; }
...
// init example.js
tmp = process.cwd() + "/example.js";
// jslint code
local.jslintAndPrint(code, tmp);
// cover code
code = local.istanbulInstrumentInPackage(code, tmp);
// init module.exports
module = new local.Module(tmp);
require.cache[tmp] = module;
// load code into module
module._compile(code, tmp);
// init exports
module.exports.utility2 = local;
module.exports[local.env.npm_package_nameLib] = (
globalThis.utility2_moduleExports
...
_http.IncomingMessage = function (xhr) {
/*
* An IncomingMessage object is created by http.Server or http.ClientRequest
* and passed as the first argument to the 'req' and 'res' event
* respectively.
* It may be used to access res status, headers and data.
* https://nodejs.org/dist/v0.12.18/docs/api/all.html#all_http_incomingmessage
*/
this.headers = xhr.headers;
this.httpVersion = "1.1";
this.method = xhr.method;
this.onEvent = document.createDocumentFragment();
this.readable = true;
this.url = xhr.url;
}
...
xhr.serverResponse
);
});
};
xhr.on = function () {
return xhr;
};
xhr.serverReq = new local._http.IncomingMessage(xhr);
xhr.serverResponse = new local._http.ServerResponse(onResponse);
return xhr;
};
local._testCase_buildApidoc_default = function (opt, onError) {
/*
* this function will test buildApidoc's default handling-behavior
...
_http.ServerResponse = function (onResponse) {
/*
* This object is created internally by a HTTP server--not by the user.
* It is passed as the second parameter to the 'req' event.
* https://nodejs.org/dist/v0.12.18/docs/api/all.html#all_class_http_serverresponse
*/
this.chunkList = [];
this.onEvent = document.createDocumentFragment();
this.onResponse = onResponse;
this.resHeaders = {};
this.statusCode = 200;
}
...
);
});
};
xhr.on = function () {
return xhr;
};
xhr.serverReq = new local._http.IncomingMessage(xhr);
xhr.serverResponse = new local._http.ServerResponse(onResponse);
return xhr;
};
local._testCase_buildApidoc_default = function (opt, onError) {
/*
* this function will test buildApidoc's default handling-behavior
*/
...
_testCase_buildApidoc_default = function (opt, onError) {
/*
* this function will test buildApidoc's default handling-behavior
*/
if (local.isBrowser) {
onError(null, opt);
return;
}
return local.buildApidoc(opt, onError);
}
...
buildTest: local.nop,
testCase_buildReadme_default: local.nop,
testCase_buildLib_default: local.nop,
testCase_buildTest_default: local.nop
}
]
], function (onError) {
local._testCase_buildApidoc_default(null, local.nop);
local._testCase_buildApp_default(null, local.nop);
local._testCase_buildLib_default(null, local.nop);
local._testCase_buildReadme_default(null, local.nop);
local._testCase_buildTest_default(null, local.nop);
local._testCase_webpage_default(null, local.nop);
local.assetsDict["/"] = "<script src=\"assets.test.js\"></script>";
local._testCase_webpage_default(null, local.nop);
...
_testCase_buildApp_default = function (opt, onError) {
/*
* this function will test buildApp's default handling-behavior
*/
if (local.isBrowser) {
onError(null, opt);
return;
}
globalThis.local.testCase_buildReadme_default(opt, local.onErrorThrow);
globalThis.local.testCase_buildLib_default(opt, local.onErrorThrow);
globalThis.local.testCase_buildTest_default(opt, local.onErrorThrow);
local.buildApp(opt, onError);
}
...
testCase_buildReadme_default: local.nop,
testCase_buildLib_default: local.nop,
testCase_buildTest_default: local.nop
}
]
], function (onError) {
local._testCase_buildApidoc_default(null, local.nop);
local._testCase_buildApp_default(null, local.nop);
local._testCase_buildLib_default(null, local.nop);
local._testCase_buildReadme_default(null, local.nop);
local._testCase_buildTest_default(null, local.nop);
local._testCase_webpage_default(null, local.nop);
local.assetsDict["/"] = "<script src=\"assets.test.js\"></script>";
local._testCase_webpage_default(null, local.nop);
onError(null, opt);
...
_testCase_buildLib_default = function (opt, onError) {
/*
* this function will test buildLib's default handling-behavior
*/
if (local.isBrowser) {
onError(null, opt);
return;
}
return local.buildLib({}, onError);
}
...
testCase_buildLib_default: local.nop,
testCase_buildTest_default: local.nop
}
]
], function (onError) {
local._testCase_buildApidoc_default(null, local.nop);
local._testCase_buildApp_default(null, local.nop);
local._testCase_buildLib_default(null, local.nop);
local._testCase_buildReadme_default(null, local.nop);
local._testCase_buildTest_default(null, local.nop);
local._testCase_webpage_default(null, local.nop);
local.assetsDict["/"] = "<script src=\"assets.test.js\"></script>";
local._testCase_webpage_default(null, local.nop);
onError(null, opt);
}, onError);
...
_testCase_buildReadme_default = function (opt, onError) {
/*
* this function will test buildReadme's default handling-behavior
*/
if (local.isBrowser) {
onError(null, opt);
return;
}
return local.buildReadme({}, onError);
}
...
testCase_buildTest_default: local.nop
}
]
], function (onError) {
local._testCase_buildApidoc_default(null, local.nop);
local._testCase_buildApp_default(null, local.nop);
local._testCase_buildLib_default(null, local.nop);
local._testCase_buildReadme_default(null, local.nop);
local._testCase_buildTest_default(null, local.nop);
local._testCase_webpage_default(null, local.nop);
local.assetsDict["/"] = "<script src=\"assets.test.js\"></script>";
local._testCase_webpage_default(null, local.nop);
onError(null, opt);
}, onError);
};
...
_testCase_buildTest_default = function (opt, onError) {
/*
* this function will test buildTest's default handling-behavior
*/
if (local.isBrowser) {
onError(null, opt);
return;
}
return local.buildTest({}, onError);
}
...
}
]
], function (onError) {
local._testCase_buildApidoc_default(null, local.nop);
local._testCase_buildApp_default(null, local.nop);
local._testCase_buildLib_default(null, local.nop);
local._testCase_buildReadme_default(null, local.nop);
local._testCase_buildTest_default(null, local.nop);
local._testCase_webpage_default(null, local.nop);
local.assetsDict["/"] = "<script src=\"assets.test.js\"></script>";
local._testCase_webpage_default(null, local.nop);
onError(null, opt);
}, onError);
};
...
_testCase_testRunDefault_failure = function (opt, onError) {
/*
* this function will test testRunDefault's failure handling-behavior
*/
// test failure from callback handling-behavior
onError(local.errDefault);
// test failure from multiple-callback handling-behavior
onError(null, opt);
// test failure from ajax handling-behavior
local.ajax({
url: "/undefined"
}, onError);
// test failure from uncaught-uncaughtexception handling-behavior
setTimeout(local.throwError);
// test console.error handling-behavior
local.testMock([
[
globalThis, {
__coverage__: null
}
]
], function (onError) {
console.error();
onError(null, opt);
}, local.onErrorThrow);
// test failure from thrown err handling-behavior
throw local.errDefault;
}
n/a
_testCase_webpage_default = function (opt, onError) {
/*
* this function will test webpage's default handling-behavior
*/
local.domStyleValidate();
if (local.isBrowser) {
onError(null, opt);
return;
}
local.browserTest({
fileScreenshot: (
local.env.npm_config_dir_build
+ "/screenshot." + local.env.MODE_BUILD + ".browser.%2F.png"
),
modeCoverageMerge: true,
url: (
local.assetsDict["/"].indexOf(
"<script src=\"assets.test.js\"></script>"
) >= 0
? local.serverLocalHost + "?modeTest=1&timeoutDefault="
+ local.timeoutDefault
: local.serverLocalHost
+ "/assets.utility2.base.html?modeTest=1&timeoutDefault=1"
) + "&modeTestCase=" + local.modeTestCase.replace((
/_?testCase_webpage_default/
), "")
}, onError);
}
...
]
], function (onError) {
local._testCase_buildApidoc_default(null, local.nop);
local._testCase_buildApp_default(null, local.nop);
local._testCase_buildLib_default(null, local.nop);
local._testCase_buildReadme_default(null, local.nop);
local._testCase_buildTest_default(null, local.nop);
local._testCase_webpage_default(null, local.nop);
local.assetsDict["/"] = "<script src=\"assets.test.js\"></script>";
local._testCase_webpage_default(null, local.nop);
onError(null, opt);
}, onError);
};
local.testCase_childProcessSpawnWithTimeout_default = function (
...
_testRunConsoleError = function () { [native code] }
...
testReportDiv1.innerHTML = local.testReportMerge(testReport, {});
if (!testReport.testsPending) {
// cleanup timerInterval
clearInterval(timerInterval);
}
// notify of remaining tests
if (testPlatform.timeElapsed % 5000 < 1000) {
local._testRunConsoleError(
"testRunDefault - "
+ testPlatform.timeElapsed + " ms - testCase pending - "
+ testPlatform.testCaseList
.filter(function (testCase) {
return testCase.status === "pending";
})
.slice(0, 4)
...
ajax = function (opt, onError) {
/*
* this function will send an ajax-req
* with given <opt>.url and callback <onError>
* with err and timeout handling
* example usage:
local.ajax({
data: "hello world",
header: {"x-header-hello": "world"},
method: "POST",
url: "/index.html"
}, function (err, xhr) {
console.log(xhr.statusCode);
console.log(xhr.responseText);
});
*/
var ajaxProgressUpdate;
var bufferValidateAndCoerce;
var isDone;
var local2;
var onEvent;
var streamCleanup;
var timeout;
var tmp;
var xhr;
var xhrInit;
// init local2
local2 = opt.local2 || local.utility2 || {};
// init function
ajaxProgressUpdate = local2.ajaxProgressUpdate || local.nop;
bufferValidateAndCoerce = local2.bufferValidateAndCoerce || function (
bff,
mode
) {
/*
* this function will validate and coerce/convert <bff> -> Buffer
* (or String if <mode> = "string")
*/
// coerce ArrayBuffer -> Buffer
if (Object.prototype.toString.call(bff) === "[object ArrayBuffer]") {
bff = new Uint8Array(bff);
}
// convert Buffer -> utf8
if (mode === "string" && typeof bff !== "string") {
bff = String(bff);
}
return bff;
};
onEvent = function (evt) {
/*
* this function will handle events
*/
if (Object.prototype.toString.call(evt) === "[object Error]") {
xhr.err = xhr.err || evt;
xhr.onEvent({
type: "error"
});
return;
}
// init statusCode
xhr.statusCode = (xhr.statusCode || xhr.status) | 0;
switch (evt.type) {
case "abort":
case "error":
case "load":
if (isDone) {
return;
}
isDone = true;
// decrement ajaxProgressCounter
local2.ajaxProgressCounter = Math.max(
local2.ajaxProgressCounter - 1,
0
);
ajaxProgressUpdate();
// handle abort or err event
switch (!xhr.err && evt.type) {
case "abort":
case "error":
xhr.err = new Error("ajax - event " + evt.type);
break;
case "load":
if (xhr.statusCode >= 400) {
xhr.err = new Error(
"ajax - statusCode " + xhr.statusCode
);
}
break;
}
// debug statusCode / method / url
if (xhr.err) {
xhr.statusCode = xhr.statusCode || 500;
xhr.err.statusCode = xhr.statusCode;
tmp = (
// ternary-operator
(
local.isBrowser
? "browser"
: "node"
)
+ " - " + xhr.statusCode + " " + xhr.method + " " + xhr.url
+ "\n"
);
xhr.err.message = tmp + xhr.err.message;
xhr.err.stack = tmp + xhr.err.stack;
}
// update resHeaders
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/getAllResponseHeaders
if (xhr.getAllResponseHeaders) {
xhr.getAllResponseHeaders().replace((
/(.*?):\u0020*(.*?)\r\n/g
), function (ignore, match1, match2) {
xhr.resHeaders[match1.toLowerCase()] = match2;
});
}
// debug ajaxResponse
xhr.resContentLeng...
...
/* validateLineSortedReset */
local.ajax = function (opt, onError) {
/*
* this function will send an ajax-req
* with given <opt>.url and callback <onError>
* with err and timeout handling
* example usage:
local.ajax({
data: "hello world",
header: {"x-header-hello": "world"},
method: "POST",
url: "/index.html"
}, function (err, xhr) {
console.log(xhr.statusCode);
console.log(xhr.responseText);
...
ajaxProgressUpdate = function () {
/*
* this function will update ajaxProgress
*/
var ajaxProgressDiv1;
// init state
local.ajaxProgressCounter = local.ajaxProgressCounter || 0;
local.ajaxProgressState = local.ajaxProgressState || 0;
ajaxProgressDiv1 = (local.isBrowser && document.querySelector(
"#ajaxProgressDiv1"
)) || {
style: {
width: ""
}
};
// init ajaxProgressDiv1StyleBackground
local.ajaxProgressDiv1StyleBackground = (
local.ajaxProgressDiv1StyleBackground
|| ajaxProgressDiv1.style.background
);
// show ajaxProgress
ajaxProgressDiv1.style.background = local.ajaxProgressDiv1StyleBackground;
// increment ajaxProgress
if (local.ajaxProgressCounter > 0) {
local.timerIntervalAjaxProgressHide = (
local.timerIntervalAjaxProgressHide
|| setInterval(local.ajaxProgressUpdate, 2000)
);
// this algorithm will indefinitely increment ajaxProgressBar
// with successively smaller increments without ever reaching 100%
if ((ajaxProgressDiv1.style.width.slice(0, -1) | 0) > 95) {
ajaxProgressDiv1.style.width = "0%";
local.ajaxProgressState = 0;
}
local.ajaxProgressState += 1;
ajaxProgressDiv1.style.width = Math.max(
100 - 75 * Math.exp(-0.125 * local.ajaxProgressState),
ajaxProgressDiv1.style.width.slice(0, -1) | 0
) + "%";
} else {
// finish ajaxProgress
ajaxProgressDiv1.style.width = "100%";
}
// cleanup timerTimeout
clearTimeout(local.timerTimeoutAjaxProgressHide);
// hide ajaxProgress
local.timerTimeoutAjaxProgressHide = setTimeout(function () {
ajaxProgressDiv1.style.background = "transparent";
local.ajaxProgressCounter = 0;
local.ajaxProgressState = 0;
// reset ajaxProgress
clearInterval(local.timerIntervalAjaxProgressHide);
local.timerIntervalAjaxProgressHide = null;
setTimeout(function () {
if (!local.ajaxProgressState) {
ajaxProgressDiv1.style.width = "0%";
}
}, 500);
}, (
local.ajaxProgressCounter > 0
? local.timeoutDefault
: 1000
));
}
...
) {
return;
}
// test-run
globalThis.utility2_modeTest += 1;
}
// visual notification - testRun
local.ajaxProgressUpdate();
// mock serverLog
local._testRunConsoleError = local._testRunConsoleError || console.error;
console.error = function (arg0) {
/*
* this function will ignore serverLog-messages during test-run
*/
/* istanbul ignore next */
...
apidocCreate = function (opt) {
/*
* this function will create the apidoc from <opt>.dir
*/
var elemCreate;
var module;
var moduleMain;
var readExample;
var tmp;
var toString;
var trimLeft;
elemCreate = function (module, prefix, key) {
/*
* this function will create the apidoc-elem in given <module>
*/
var elem;
if (opt.modeNoApidoc) {
return elem;
}
elem = {};
elem.moduleName = prefix.split(".");
// handle case where module is a function
if (elem.moduleName.slice(-1)[0] === key) {
elem.moduleName.pop();
}
elem.moduleName = elem.moduleName.join(".");
elem.id = encodeURIComponent("apidoc.elem." + prefix + "." + key);
elem.typeof = typeof module[key];
elem.name = (
elem.typeof + " <span class=\"apidocSignatureSpan\">"
+ elem.moduleName + ".</span>" + key
)
// handle case where module is a function
.replace(">.<", "><");
if (elem.typeof !== "function") {
return elem;
}
// init source
elem.source = local.stringHtmlSafe(
trimLeft(toString(module[key])) || "n/a"
).replace((
/\([\S\s]*?\)/
), function (match0) {
// init signature
elem.signature = match0.replace((
/\u0020*?\/\*[\S\s]*?\*\/\u0020*/g
), "")
.replace((
/,/g
), ", ")
.replace((
/\s+/g
), " ");
return elem.signature;
})
.replace((
/(\u0020*?\/\*[\S\s]*?\*\/\n)/
), "<span class=\"apidocCodeCommentSpan\">$1</span>")
.replace((
/^function\u0020\(/
), key + " = function (");
// init example
opt.exampleList.some(function (example) {
example.replace(
new RegExp("((?:\n.*?){8}\\.)(" + key + ")(\\((?:.*?\n){8})"),
function (ignore, match1, match2, match3) {
elem.example = "..." + trimLeft(
local.stringHtmlSafe(match1)
+ "<span class=\"apidocCodeKeywordSpan\">"
+ local.stringHtmlSafe(match2)
+ "</span>"
+ local.stringHtmlSafe(match3)
).trimRight() + "\n...";
}
);
return elem.example;
});
elem.example = elem.example || "n/a";
return elem;
};
readExample = function (file) {
/*
* this function will read the example from given file
*/
var result;
local.tryCatchOnError(function () {
file = local.path.resolve(opt.dir, file);
console.error("apidocCreate - readExample " + file);
result = "";
result = (
"\n\n\n\n\n\n\n\n"
// bug-workaround - truncate example to manageable size
+ local.fs.readFileSync(file, "utf8").slice(0, 262144)
+ "\n\n\n\n\n\n\n\n"
).replace((
/\r\n*/g
), "\n");
}, console.error);
return result;
};
toString = function (value) {
/*
* this function will try to return the string form of the value
*/
var result;
local.tryCatchOnError(function () {
result = "";
result = String(value);
}, console.error);
return result;
};
trimLeft = function (text) {
/*
* this function will...
...
local.cliDict._default = function () {
/*
* <moduleDirectory>
* will create apidoc from <moduleDirectory>
*/
// jslint files
process.stdout.write(local.apidocCreate({
dir: process.argv[2],
modulePathList: module.paths
}));
};
// run the cli
if (module === require.main && !globalThis.utility2_rollup) {
...
function ok(...args) { innerOk(ok, args.length, ...args); }
...
key = '0123456789abcdef0123456789abcdef';
mode = null;
local.cryptoAesXxxCbcRawEncrypt({
data: data,
key: key,
mode: mode
}, function (err, data) {
console.assert(!err, err);
local.cryptoAesXxxCbcRawDecrypt({
data: data,
key: key,
mode: mode
}, console.log);
});
*/
...
assertJsonEqual = function (aa, bb, message) {
/*
* this function will assert jsonStringifyOrdered(<aa>) === JSON.stringify(<bb>)
*/
aa = local.jsonStringifyOrdered(aa);
bb = JSON.stringify(bb);
local.assertThrow(aa === bb, message || [
aa, bb
]);
}
...
}
}
]
], function (onError) {
// update ajax-progress
local.ajaxProgressUpdate();
// validate data
local.assertJsonEqual(local.ajaxProgressCounter, 0);
local.assertJsonEqual(local.ajaxProgressState, 2);
// update ajax-progress
local.ajaxProgressUpdate();
// validate data
local.assertJsonEqual(local.ajaxProgressCounter, 0);
local.assertJsonEqual(local.ajaxProgressState, 1);
// update ajax-progress
...
assertJsonNotEqual = function (aa, bb, message) {
/*
* this function will assert jsonStringifyOrdered(<aa>) !== JSON.stringify(<bb>)
*/
aa = local.jsonStringifyOrdered(aa);
bb = JSON.stringify(bb);
local.assertThrow(aa !== bb, [
aa
], message || aa);
}
...
"", 0, false, null, undefined
].forEach(function (bb, jj) {
if (ii === jj) {
// test assertJsonEqual's handling-behavior
local.assertJsonEqual(aa, bb);
} else {
// test assertJsonNotEqual's handling-behavior
local.assertJsonNotEqual(aa, bb);
}
});
});
onError(null, opt);
};
local.testCase_base64Xxx_default = function (opt, onError) {
...
assertThrow = function (passed, message) {
/*
* this function will throw err.<message> if <passed> is falsy
*/
var err;
if (passed) {
return;
}
err = (
// ternary-operator
(
message
&& typeof message.message === "string"
&& typeof message.stack === "string"
)
// if message is errObj, then leave as is
? message
: new Error(
typeof message === "string"
// if message is a string, then leave as is
? message
// else JSON.stringify message
: JSON.stringify(message, null, 4)
)
);
throw err;
}
...
argList: (commandList[ii][1] || "").trim(),
command: [
key
],
description: commandList[ii][2]
};
} catch (ignore) {
local.assertThrow(null, new Error(
"cliRun - cannot parse comment in COMMAND "
+ key
+ ":\nnew RegExp("
+ JSON.stringify(opt.rgxComment.source)
+ ").exec(" + JSON.stringify(text).replace((
/\\\\/g
), "\u0000").replace((
...
base64FromBuffer = function (bff) {
/*
* this function will convert Uint8Array <bff> to base64
* https://developer.mozilla.org/en-US/Add-ons/Code_snippets/StringView#The_code
*/
var ii;
var mod3;
var text;
var uint24;
var uint6ToB64;
// convert utf8 -> Uint8Array
if (typeof bff === "string") {
bff = new TextEncoder().encode(bff);
}
bff = bff || [];
text = "";
uint24 = 0;
uint6ToB64 = function (uint6) {
return (
uint6 < 26
? uint6 + 65
: uint6 < 52
? uint6 + 71
: uint6 < 62
? uint6 - 4
: uint6 === 62
? 43
: 47
);
};
ii = 0;
while (ii < bff.length) {
mod3 = ii % 3;
uint24 |= bff[ii] << (16 >>> mod3 & 24);
if (mod3 === 2 || bff.length - ii === 1) {
text += String.fromCharCode(
uint6ToB64(uint24 >>> 18 & 63),
uint6ToB64(uint24 >>> 12 & 63),
uint6ToB64(uint24 >>> 6 & 63),
uint6ToB64(uint24 & 63)
);
uint24 = 0;
}
ii += 1;
}
return text.replace((
/A(?=A$|$)/gm
), "=");
}
...
value = (
opt.modeNotRandom
? "abcd1234"
: ((1 + Math.random()) * 0x10000000000000).toString(36).slice(1)
);
switch (schemaP.format) {
case "byte":
value = local.base64FromBuffer(value);
break;
case "date":
case "date-time":
value = new Date().toISOString();
break;
case "email":
value = value + "@example.com";
...
base64ToBuffer = function (b64, mode) {
/*
* this function will convert <b64> to Uint8Array
* https://gist.github.com/wang-bin/7332335
*/
var bff;
var byte;
var chr;
var ii;
var jj;
var map64;
var mod4;
b64 = b64 || "";
bff = new Uint8Array(b64.length); // 3/4
byte = 0;
jj = 0;
map64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
mod4 = 0;
ii = 0;
while (ii < b64.length) {
chr = map64.indexOf(b64[ii]);
if (chr >= 0) {
mod4 %= 4;
if (mod4 === 0) {
byte = chr;
} else {
byte = byte * 64 + chr;
bff[jj] = 255 & (byte >> ((-2 * (mod4 + 1)) & 6));
jj += 1;
}
mod4 += 1;
}
ii += 1;
}
// optimization - create resized-view of bff
bff = bff.subarray(0, jj);
return local.bufferValidateAndCoerce(bff, mode);
}
...
if (!data) {
local.serverRespondDefault(req, res, 404);
return;
}
local.serverRespondHeadSet(req, res, null, {
"Content-Type": data.fileContentType
});
res.end(local.base64ToBuffer(data.fileBlob));
break;
case "userLogout":
opt.onNext();
break;
default:
opt.onNext(null, data, meta);
}
...
base64ToUtf8 = function (b64) {
/*
* this function will convert <b64> -> utf8
*/
return local.base64ToBuffer(b64, "string");
}
...
// validate signature
local.assertThrow(local.sjcl.codec.base64url.fromBits(
new Hmac(local.sjcl.codec.base64url.toBits(
local.jwtAes256KeyInit(key)
)).encrypt(token[0] + "." + token[1])
) === token[2]);
// return decoded data
token = JSON.parse(local.base64ToUtf8(token[1]));
// https://tools.ietf.org/html/rfc7519#section-4.1
// validate jwt-registered-headers
local.assertThrow(!token.exp || token.exp >= timeNow);
local.assertThrow(!token.nbf || token.nbf <= timeNow);
return token;
}, local.nop) || {};
};
...
blobRead = function (blob, onError) {
/*
* this function will read from <blob>
*/
var isDone;
var reader;
if (blob && blob.constructor && blob.constructor === local.FormData) {
blob.read(onError);
return;
}
if (!local.isBrowser) {
onError(null, local.bufferValidateAndCoerce(blob.bff));
return;
}
reader = new FileReader();
reader.onabort = function (evt) {
if (isDone) {
return;
}
isDone = true;
switch (evt.type) {
case "abort":
case "error":
onError(new Error("blobRead - " + evt.type));
break;
case "load":
onError(
null,
Object.prototype.toString.call(reader.result)
=== "[object ArrayBuffer]"
// convert ArrayBuffer -> Uint8Array
? new Uint8Array(reader.result)
: reader.result
);
break;
}
};
reader.onerror = reader.onabort;
reader.onload = reader.onabort;
reader.readAsArrayBuffer(blob);
}
...
switch ((xhr.data && xhr.data.constructor) || true) {
// Blob
// https://developer.mozilla.org/en-US/docs/Web/API/Blob
case local2.Blob:
// FormData
// https://developer.mozilla.org/en-US/docs/Web/API/FormData
case local2.FormData:
local2.blobRead(xhr.data, function (err, data) {
if (err) {
xhr.onEvent(err);
return;
}
// send data
xhr.send(data);
});
...
browserTest = function (opt, onError) {
/*
* this function will spawn an electron process to test <opt>.url
*/
var isDone;
var isDoneHtml;
var onMessage;
var onParallel;
var timerTimeout;
var window;
window = opt.window || globalThis;
// init utility2_testReport
window.utility2_testReport = window.utility2_testReport || {
coverage: window.__coverage__,
testPlatformList: [
{
name: (
local.isBrowser
? (
"browser - "
+ location.pathname + " - " + navigator.userAgent
)
: "node - " + process.platform + " " + process.version
) + " - " + new Date().toISOString(),
screenshot: local.env && local.env.MODE_BUILD_SCREENSHOT_IMG,
testCaseList: []
}
]
};
window.utility2_testReportSave = (
window.utility2_testReportSave
|| local.nop
);
if (opt.modeTestReportCreate) {
return;
}
onMessage = function (evt, type, data) {
switch (evt && type) {
case "html":
if (isDoneHtml) {
return;
}
isDoneHtml = true;
opt.fs.writeFile(opt.fileScreenshot.replace((
/\.\w+$/
), ".html"), data, onParallel);
return;
case "testReport":
if (opt.isDoneTestReport || opt.modeBrowserTest !== "test") {
return;
}
opt.isDoneTestReport = true;
// save browser-coverage
if (data.coverage) {
onParallel.counter += 1;
opt.fs.writeFile(
opt.fileCoverage,
JSON.stringify(data.coverage),
onParallel
);
data.coverage = null;
}
// save browser-screenshot
data.testPlatformList[0].screenshot = (
opt.fileScreenshot.replace((
/.*\//
), "")
);
// save browser-test-report
onParallel.counter += 1;
opt.fs.writeFile(
opt.fileTestReport,
JSON.stringify(data, null, 4),
onParallel
);
onParallel();
return;
}
};
local.onNext(opt, function (err, data) {
switch (opt.modeNext) {
// node - init
case 1:
// init fileElectronHtml
opt.fileElectronHtml = (
opt.npm_config_dir_tmp
+ "/electron."
+ Date.now().toString(16)
+ Math.random().toString(16)
+ ".html"
);
// init url
if (!(
/^\w+:\/\//
).test(opt.url)) {
opt.url = local.path.resolve(process.cwd(), opt.url);
}
opt.urlParsed = local.urlParse(opt.url);
// init testName
opt.testName = opt.urlParsed.pathname;
if (opt.testName.indexOf(process.cwd()) === 0) {
opt.testName = opt.testName.replace(process.cwd(), "");
}
opt.testName = (
opt.MODE_BUILD + ".browser."
+ encodeURIComponent(opt.testName.replace(
"/build.."
+ opt.CI_BRANCH
+ ".." + opt.CI_HOST,
"/build"
))
);
local.objectSetDefault(opt, {
fileCoverage: (
opt.npm_config_dir_tmp + "/coverage."
+ opt.testName + ".json"
),
fileScreenshot: (...
...
? (
/\s/g
)
: (
/[,\s]/g
)
).filter(local.identity).forEach(function (url) {
local.browserTest({
url
}, local.onErrorDefault);
});
};
local.cliDict["utility2.githubCrudContentDelete"] = function () {
/*
...
bufferConcat = function (bffList) {
/*
* this function will emulate node's Buffer.concat for Uint8Array in browser
*/
var byteLength;
var ii;
var isString;
var jj;
var result;
isString = true;
result = [
""
];
byteLength = 0;
bffList.forEach(function (bff) {
if (bff !== 0 && !(bff && bff.length)) {
return;
}
// optimization - concat string
if (isString && typeof bff === "string") {
result[0] += bff;
return;
}
isString = null;
bff = local.bufferValidateAndCoerce(bff);
byteLength += bff.byteLength;
result.push(bff);
});
// optimization - return string
if (isString) {
return result[0];
}
result[0] = local.bufferValidateAndCoerce(result[0]);
byteLength += result[0].byteLength;
bffList = result;
result = local.bufferValidateAndCoerce(new Uint8Array(byteLength));
ii = 0;
bffList.forEach(function (bff) {
jj = 0;
while (jj < bff.byteLength) {
result[ii] = bff[jj];
ii += 1;
jj += 1;
}
});
return result;
}
...
]);
// init boundary
ii = 0;
jj = local.bufferIndexOfSubBuffer(req.bodyRaw, crlf, ii);
if (jj <= 0) {
break;
}
boundary = local.bufferConcat([
crlf, req.bodyRaw.slice(ii, jj)
]);
ii = jj + 2;
while (true) {
jj = local.bufferIndexOfSubBuffer(
req.bodyRaw,
boundary,
...
bufferIndexOfSubBuffer = function (bff, subBff, fromIndex) {
/*
* this function will search <bff> for <fromIndex> position of <subBff>
*/
var ii;
var jj;
var kk;
if (!subBff.length) {
return 0;
}
ii = fromIndex || 0;
while (ii < bff.length) {
kk = ii;
jj = 0;
while (jj < subBff.length) {
if (subBff[jj] !== bff[kk]) {
break;
}
kk += 1;
jj += 1;
}
if (jj === subBff.length) {
return kk - jj;
}
ii += 1;
}
return -1;
}
...
req.swgg.bodyParsed = {};
req.swgg.bodyMeta = {};
crlf = new Uint8Array([
0x0d, 0x0a
]);
// init boundary
ii = 0;
jj = local.bufferIndexOfSubBuffer(req.bodyRaw, crlf, ii);
if (jj <= 0) {
break;
}
boundary = local.bufferConcat([
crlf, req.bodyRaw.slice(ii, jj)
]);
ii = jj + 2;
...
bufferRandomBytes = function (length) {
/*
* this function will return a Buffer with given <length>,
* filled with cryptographically-strong random-values
*/
return (
// ternary-operator
(
typeof window === "object"
&& window.crypto
&& typeof window.crypto.getRandomValues === "function"
)
? window.crypto.getRandomValues(new Uint8Array(length))
: require("crypto").randomBytes(length)
);
}
...
};
local.jwtAes256KeyCreate = function () {
/*
* this function will create a random, aes-256-base64url-jwt-key
*/
return local.normalizeJwtBase64Url(
local.base64FromBuffer(local.bufferRandomBytes(32))
);
};
local.jwtAes256KeyInit = function (key) {
/*
* this function will init aes-256-base64url-jwt-<key>
* https://jwt.io/
...
bufferToUtf8 = function (bff) {
/*
* this function will convert Uint8Array <bff> -> utf8
*/
return local.bufferValidateAndCoerce(bff, "string");
}
...
var name;
// if req is already parsed, then goto next
if (!req.swgg.operation || !local.isNullOrUndefined(req.swgg.bodyParsed)) {
next();
return;
}
headerParse = function () {
local.bufferToUtf8(req.bodyRaw.slice(ii, ii + 1024)).replace((
/^content-disposition:\u0020?form-data;(.+?)\r\n(?:content-type:\u0020?(.*?)$)?/im
), function (ignore, match1, match2) {
data = {
contentType: match2,
name: ""
};
match1.replace((
...
bufferValidateAndCoerce = function (bff, mode) {
/*
* this function will validate and coerce/convert <bff> -> Buffer
* (or String if <mode> = "string")
*/
// validate not 0
if (bff !== 0) {
bff = bff || "";
}
if (typeof bff === "string" && mode === "string") {
return bff;
}
// convert utf8 -> Uint8Array
if (typeof bff === "string") {
bff = (
local.isBrowser
? new TextEncoder().encode(bff)
: Buffer.from(bff)
);
// validate instanceof Uint8Array
} else if (Object.prototype.toString.call(bff) !== "[object Uint8Array]") {
throw new Error(
"bufferValidateAndCoerce - value is not instanceof "
+ "ArrayBuffer, String, or Uint8Array"
);
}
// convert Uint8Array -> utf8
if (mode === "string") {
return new TextDecoder().decode(bff);
}
// coerce Uint8Array -> Buffer
if (!local.isBrowser && !Buffer.isBuffer(bff)) {
Object.setPrototypeOf(bff, Buffer.prototype);
}
return bff;
}
...
}
mod4 += 1;
}
ii += 1;
}
// optimization - create resized-view of bff
bff = bff.subarray(0, jj);
return local.bufferValidateAndCoerce(bff, mode);
};
local.base64ToUtf8 = function (b64) {
/*
* this function will convert <b64> -> utf8
*/
return local.base64ToBuffer(b64, "string");
...
buildApidoc = function (opt, onError) {
/*
* this function will build apidoc with given <opt>
*/
var result;
// optimization - do not run if $npm_config_mode_coverage = all
if (local.env.npm_config_mode_coverage === "all") {
onError();
return;
}
opt = local.objectSetDefault(opt, {
blacklistDict: local,
require: local.requireInSandbox
});
// save apidoc.html
result = (
local.fsReadFileOrEmptyStringSync("apidoc.html", "utf8")
|| local.apidocCreate(opt)
);
local.fsWriteFileWithMkdirpSync("tmp/build/apidoc.html", result);
console.error(
"created apidoc file " + process.cwd() + "/apidoc.html\n"
);
onError();
}
...
/*
* this function will test buildApidoc's default handling-behavior
*/
if (local.isBrowser) {
onError(null, opt);
return;
}
return local.buildApidoc(opt, onError);
};
local._testCase_buildApp_default = function (opt, onError) {
/*
* this function will test buildApp's default handling-behavior
*/
if (local.isBrowser) {
...
buildApp = function (opt, onError) {
/*
* this function will build app with given <opt>
*/
opt = local.objectSetDefault(opt, {
assetsList: []
});
// build assets
local.fsRmrSync("tmp/build/app");
local.onParallelList({
list: [
{
file: "/LICENSE",
url: "/LICENSE"
}, {
file: "/assets." + local.env.npm_package_nameLib + ".html",
url: "/index.html"
}, {
file: "/assets." + local.env.npm_package_nameLib + ".js",
url: "/assets." + local.env.npm_package_nameLib + ".js"
}, {
file: "/assets.app.js",
url: "/assets.app.js"
}, {
file: "/assets.example.html",
url: "/assets.example.html"
}, {
file: "/assets.example.js",
url: "/assets.example.js"
}, {
file: "/assets.swgg.html",
url: "/assets.swgg.html"
}, {
file: "/assets.swgg.swagger.json",
url: "/assets.swgg.swagger.json"
}, {
file: "/assets.swgg.swagger.petstore.json",
url: "/assets.swgg.swagger.petstore.json"
}, {
file: "/assets.swgg.swagger.server.json",
url: "/assets.swgg.swagger.server.json"
}, {
file: "/assets.test.js",
url: "/assets.test.js"
}, {
file: "/assets.utility2.html",
url: "/assets.utility2.html"
}, {
file: "/assets.utility2.base.html",
url: "/assets.utility2.base.html"
}, {
file: "/assets.utility2.rollup.js",
url: "/assets.utility2.rollup.js"
}, {
file: "/index.html",
url: "/index.html"
}, {
file: "/index.rollup.html",
url: "/index.rollup.html"
}, {
file: "/jsonp.utility2.stateInit",
url: (
"/jsonp.utility2.stateInit"
+ "?callback=window.utility2.stateInit"
)
}
].concat(opt.assetsList)
}, function (option2, onParallel) {
option2 = option2.elem;
onParallel.counter += 1;
local.ajax(option2, function (err, xhr) {
// validate no err occurred
local.assertThrow(!err, err);
// jslint file
local.jslintAndPrint(xhr.responseText, option2.file, {
conditional: true,
coverage: local.env.npm_config_mode_coverage
});
// validate no err occurred
local.assertThrow(
!local.jslint.jslintResult.errText,
local.jslint.jslintResult.errText
);
local.fsWriteFileWithMkdirpSync(
"tmp/build/app" + option2.file,
xhr.response
);
onParallel();
});
}, function (err) {
// validate no err occurred
local.assertThrow(!err, err);
// test standalone assets.app.js
local.fsWriteFileWithMkdirpSync(
"tmp/buildApp/assets.app.js",
local.assetsDict["/assets.app.js"]
);
local.childProcessSpawnWithTimeout("node", [
"assets.app.js"
], {
cwd: "tmp/buildApp",
env: {
PATH: local.env.PATH,...
...
if (local.isBrowser) {
onError(null, opt);
return;
}
globalThis.local.testCase_buildReadme_default(opt, local.onErrorThrow);
globalThis.local.testCase_buildLib_default(opt, local.onErrorThrow);
globalThis.local.testCase_buildTest_default(opt, local.onErrorThrow);
local.buildApp(opt, onError);
};
local._testCase_buildLib_default = function (opt, onError) {
/*
* this function will test buildLib's default handling-behavior
*/
if (local.isBrowser) {
...
buildLib = function (opt, onError) {
/*
* this function will build lib with given <opt>
*/
var result;
local.objectSetDefault(opt, {
customize: local.nop,
dataFrom: local.fsReadFileOrEmptyStringSync(
"lib." + local.env.npm_package_nameLib + ".js",
"utf8"
),
dataTo: local.templateRenderMyApp(
local.assetsDict["/assets.my_app.template.js"],
opt
)
});
// search-and-replace - customize dataTo
[
// customize top-level comment-description
(
/\n\u0020\*\n(?:[\S\s]*?\n)?\u0020\*\/\n/
),
// customize body after /* validateLineSortedReset */
(
/\n\/\*\u0020validateLineSortedReset\u0020\*\/\n[\S\s]*?$/
)
].forEach(function (rgx) {
opt.dataTo = local.stringMerge(opt.dataTo, opt.dataFrom, rgx);
});
// customize local for assets.utility2.rollup.js
if (
local.fs.existsSync("./assets.utility2.rollup.js")
&& local.env.npm_package_nameLib !== "swgg"
) {
opt.dataTo = opt.dataTo.replace(
" // || globalThis.utility2_rollup_old",
" || globalThis.utility2_rollup_old"
).replace(
" // || require(\"./assets.utility2.rollup.js\")",
" || require(\"./assets.utility2.rollup.js\")"
);
}
// save lib
result = opt.dataTo;
local.fsWriteFileWithMkdirpSync(
"lib." + local.env.npm_package_nameLib + ".js",
result,
local.env.npm_config_mode_coverage && local.identity("noWrite")
);
opt.customize(opt);
onError();
return result;
}
...
/*
* this function will test buildLib's default handling-behavior
*/
if (local.isBrowser) {
onError(null, opt);
return;
}
return local.buildLib({}, onError);
};
local._testCase_buildReadme_default = function (opt, onError) {
/*
* this function will test buildReadme's default handling-behavior
*/
if (local.isBrowser) {
...
buildReadme = function (opt, onError) {
/*
* this function will build readme with given <opt> my-app-lite template
*/
var result;
local.objectSetDefault(opt, {
customize: local.nop,
// reset toc
dataFrom: local.fsReadFileOrEmptyStringSync(
"README.md",
"utf8"
).replace((
/\n#\u0020table\u0020of\u0020contents$[\S\s]*?\n\n\n\n/m
), "\n# table of contents\n\n\n\n"),
packageJsonRgx: (
/\n#\u0020package.json\n```json\n([\S\s]*?)\n```\n/
)
});
// render dataTo
opt.dataTo = local.templateRenderMyApp(
local.assetsDict["/assets.readme.template.md"],
opt
);
// init package.json
opt.dataFrom.replace(opt.packageJsonRgx, function (match0, match1) {
// remove null-items from package.json
opt.packageJson = JSON.parse(match1.replace((
/\u0020{4}".*?":\u0020null,?$/gm
), ""));
opt.packageJson.description = opt.dataFrom.split("\n")[1];
local.tryCatchOnError(function () {
local.objectSetDefault(opt.packageJson, {
nameLib: local.fsReadFileOrEmptyStringSync(
"./package.json",
"json"
).nameLib
});
}, local.nop);
opt.packageJson = local.objectSetDefault(opt.packageJson, {
nameLib: opt.packageJson.name.replace((
/\W/g
), "_"),
nameOriginal: opt.packageJson.name
});
opt.packageJson = local.objectSetDefault(
opt.packageJson,
JSON.parse(local.templateRenderMyApp(opt.packageJsonRgx.exec(
local.assetsDict["/assets.readme.template.md"]
)[1], opt)),
2
);
// avoid npm-installing that
delete opt.packageJson.devDependencies[opt.packageJson.name];
// reset scripts
opt.packageJson.scripts = {
"build-ci": "sh ./npm_scripts.sh",
env: "env",
eval: "sh ./npm_scripts.sh",
"heroku-postbuild": "sh ./npm_scripts.sh",
postinstall: "sh ./npm_scripts.sh",
start: "sh ./npm_scripts.sh",
test: "sh ./npm_scripts.sh",
utility2: "sh ./npm_scripts.sh"
};
// save package.json
local.fsWriteFileWithMkdirpSync(
"package.json",
local.jsonStringifyOrdered(opt.packageJson, null, 4) + "\n"
);
// re-render dataTo
opt.dataTo = local.templateRenderMyApp(
local.assetsDict["/assets.readme.template.md"],
opt
);
opt.dataTo = opt.dataTo.replace(
opt.packageJsonRgx,
match0.replace(
match1,
local.jsonStringifyOrdered(opt.packageJson, null, 4)
)
);
});
// search-and-replace - customize dataTo
[
// customize name and description
(
/.*?\n.*?\n/
),
// customize cdn-download
(
/\n#\u0020cdn\u0020download\n[\S\s]*?\n\n\n\n/
),
// customize live-web-demo
(
/\n#\u0020live\u0020web\u0020demo\n[\S\s]*?\n\n\n\n/
),
// customize to-do
(
/\n####\u0020todo\n[\S\s]*?\n\n\n\n/
),
// customize example.js - shared js-env code - init-before
(
/\nglobalThis\.local\u0020=\u0020local;\n[^`]*?\n\/\/\u0020run\u0020browser\u0020js\-env\u0020code\u0020-\u0020init-
test\n/
),
// customize example.js - html-body
(
/\nutility2-comment\u0020-->(?:\\n\\\n){4}[^`]*?^<!--\u0020utility2-comment\\n\\\n/m
),
// customize example.js - testRunBro...
...
/*
* this function will test buildReadme's default handling-behavior
*/
if (local.isBrowser) {
onError(null, opt);
return;
}
return local.buildReadme({}, onError);
};
local._testCase_buildTest_default = function (opt, onError) {
/*
* this function will test buildTest's default handling-behavior
*/
if (local.isBrowser) {
...
buildTest = function (opt, onError) {
/*
* this function will build test with given <opt>
*/
var result;
local.objectSetDefault(opt, {
customize: local.nop,
dataFrom: local.fsReadFileOrEmptyStringSync("test.js", "utf8"),
dataTo: local.templateRenderMyApp(
local.assetsDict["/assets.test.template.js"],
opt
)
});
// search-and-replace - customize dataTo
[
// customize shared js\-env code - function
(
/\n\}\(\)\);\n\n\n\n\/\/\u0020run\u0020shared\u0020js\-env\u0020code\u0020-\u0020function\n[\S\s]*?$/
)
].forEach(function (rgx) {
opt.dataTo = local.stringMerge(opt.dataTo, opt.dataFrom, rgx);
});
// customize require("utility2")
[
"./assets.utility2.rollup.js",
"./lib.utility2.js"
].forEach(function (file) {
if (local.fs.existsSync(file)) {
opt.dataTo = opt.dataTo.replace(
"require(\"utility2\")",
"require(\"" + file + "\")"
);
}
});
opt.customize(opt);
// save test.js
result = opt.dataTo;
local.fs.writeFileSync("test.js", result);
onError();
return result;
}
...
/*
* this function will test buildTest's default handling-behavior
*/
if (local.isBrowser) {
onError(null, opt);
return;
}
return local.buildTest({}, onError);
};
local._testCase_webpage_default = function (opt, onError) {
/*
* this function will test webpage's default handling-behavior
*/
local.domStyleValidate();
...
childProcessSpawnWithTimeout = function (command, args, opt) {
/*
* this function will run like child_process.spawn,
* but with auto-timeout after timeout milliseconds
* example usage:
var child = local.childProcessSpawnWithTimeout(
"/bin/sh",
["-c", "echo hello world"],
{stdio: ["ignore", 1, 2], timeout: 5000}
);
child.on("error", console.error);
child.on("exit", function (exitCode) {
console.error("exitCode " + exitCode);
});
*/
var child;
var child_process;
var timerTimeout;
child_process = require("child_process");
// spawn child
child = child_process.spawn(command, args, opt).on("exit", function () {
// cleanup timerTimeout
try {
process.kill(timerTimeout.pid);
} catch (ignore) {}
});
// init timerTimeout
timerTimeout = child_process.spawn(
// convert timeout to integer seconds with 2 second delay
"sleep "
+ Math.floor(
0.001 * (Number(opt && opt.timeout) || local.timeoutDefault)
+ 2
)
+ "; kill -9 " + child.pid + " 2>/dev/null",
{
shell: true,
stdio: "ignore"
}
);
return child;
}
...
"\nbrowserTest - created fileElectronHtml "
+ opt.fileElectronHtml
+ "\n"
);
// spawn an electron process to test a url
opt.npm_config_time_exit = opt.timeExit;
data.modeNext = 10;
local.childProcessSpawnWithTimeout("electron", [
__filename,
"utility2.browserTest",
opt.url,
"--enable-logging"
], {
env: data,
stdio: (
...
childProcessSpawnWithUtility2 = function (script, onError) {
/*
* this function will run child_process.spawn, with lib.utility2.sh sourced
*/
require("child_process").spawn(
". " + (process.env.npm_config_dir_utility2 || __dirname)
+ "/lib.utility2.sh; " + script,
{
shell: true,
stdio: [
"ignore", 1, 2
]
}
).on("exit", function (exitCode) {
onError(exitCode && Object.assign(new Error(), {
exitCode
}));
});
}
...
// test __dirname handling-behavior
[
process.env, {
npm_config_dir_utility2: ""
}
]
], function (onError) {
local.local.childProcessSpawnWithUtility2("undefined", function (err
) {
// validate err occurred
local.assertThrow(err, err);
});
onError(null, opt);
}, onError);
};
...
cliRun = function (opt) {
/*
* this function will run the cli with given <opt>
*/
local.cliDict._eval = local.cliDict._eval || function () {
/*
* <code>
* will eval <code>
*/
globalThis.local = local;
local.vm.runInThisContext(process.argv[3]);
};
local.cliDict["--eval"] = local.cliDict["--eval"] || local.cliDict._eval;
local.cliDict["-e"] = local.cliDict["-e"] || local.cliDict._eval;
local.cliDict._help = local.cliDict._help || function () {
/*
*
* will print help
*/
var commandList;
var file;
var packageJson;
var text;
var textDict;
commandList = [
{
argList: "<arg2> ...",
description: "usage:",
command: [
"<arg1>"
]
}, {
argList: "'console.log(\"hello world\")'",
description: "example:",
command: [
"--eval"
]
}
];
file = __filename.replace((
/.*\//
), "");
opt = Object.assign({}, opt);
packageJson = require("./package.json");
// validate comment
opt.rgxComment = opt.rgxComment || (
/\)\u0020\{\n(?:|\u0020{4})\/\*\n(?:\u0020|\u0020{5})\*((?:\u0020<[^>]*?>|\u0020\.\.\.)*?)\n(?:\u0020|\u0020{5})\*\u0020
(will\u0020.*?\S)\n(?:\u0020|\u0020{5})\*\/\n(?:\u0020{4}|\u0020{8})\S/
);
textDict = {};
Object.keys(local.cliDict).sort().forEach(function (key, ii) {
if (key[0] === "_" && key !== "_default") {
return;
}
text = String(local.cliDict[key]);
if (key === "_default") {
key = "";
}
textDict[text] = textDict[text] || (ii + 2);
ii = textDict[text];
if (commandList[ii]) {
commandList[ii].command.push(key);
return;
}
try {
commandList[ii] = opt.rgxComment.exec(text);
commandList[ii] = {
argList: (commandList[ii][1] || "").trim(),
command: [
key
],
description: commandList[ii][2]
};
} catch (ignore) {
local.assertThrow(null, new Error(
"cliRun - cannot parse comment in COMMAND "
+ key
+ ":\nnew RegExp("
+ JSON.stringify(opt.rgxComment.source)
+ ").exec(" + JSON.stringify(text).replace((
/\\\\/g
), "\u0000").replace((
/\\n/g
), "\\n\\\n").replace((
/\u0000/g
), "\\\\") + ");"
));
}
});
text = "";
text += packageJson.name + " (" + packageJson.version + ")\n\n";
text += commandList.filter(function (elem) {
return elem;
}).map(function (elem, ii) {
elem.command = elem.command.filter(function (elem) {
return elem;
});
switch (ii) {
case 0:
case 1:
elem.argList = [
elem.argList
];
break;
default:
elem.argList = elem.argList.split(" ");
elem.description = (
"# COMMAND "
+ (elem.command[0] || "<none>") + "\n# &...
...
dir: process.argv[2],
modulePathList: module.paths
}));
};
// run the cli
if (module === require.main && !globalThis.utility2_rollup) {
local.cliRun();
}
}());
}());
...
corsBackendHostInject = function (url, backendHost, rgx, location) {
/*
* this function will if <location>.host is a github site,
* inject <backendHost> into <url> with given <rgx>
*/
location = (
location
|| (typeof window === "object" && window && window.location)
);
if (!(backendHost && location && (
/\bgithub.io$/
).test(location.host))) {
return url;
}
// init github-branch
location.pathname.replace((
/\/build\.\.(alpha|beta|master)\.\.travis-ci\.org\//
), function (ignore, match1) {
backendHost = backendHost.replace("-alpha.", "-" + match1 + ".");
});
return url.replace(rgx || (
/.*?($)/m
), backendHost + "$1");
}
...
};
local.testCase_corsBackendHostInject_default = function (opt, onError) {
/*
* this function will corsBackendHostInject's default handling-behavior
*/
// test null-case handling-behavior
local.assertJsonEqual(local.corsBackendHostInject(), undefined);
// test override-all handling-behavior
local.assertJsonEqual(local.corsBackendHostInject(
"cc.com",
"aa-alpha.bb.com",
null,
{
host: "github.io",
...
corsForwardProxyHostIfNeeded = function (xhr) {
/*
* this function will return xhr.corsForwardProxyHost, if needed
*/
return (
local.isBrowser
&& local.env.npm_package_nameLib
&& (
/^https?:\/\//
).test(xhr.url)
&& xhr.url.indexOf(xhr.location.protocol + "//" + xhr.location.host)
!== 0
&& (
/\.github\.io$/
).test(xhr.location.host)
&& xhr.corsForwardProxyHost !== "disabled"
&& (xhr.corsForwardProxyHost || "https://h1-proxy1.herokuapp.com")
);
}
...
xhr.addEventListener("progress", ajaxProgressUpdate);
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/upload
if (xhr.upload && xhr.upload.addEventListener) {
xhr.upload.addEventListener("progress", ajaxProgressUpdate);
}
// open url - corsForwardProxyHost
if (local.functionOrNop(local2.corsForwardProxyHostIfNeeded)(xhr)) {
xhr.open(xhr.method, local2.corsForwardProxyHostIfNeeded(xhr));
xhr.setRequestHeader(
"forward-proxy-headers",
JSON.stringify(xhr.headers)
);
xhr.setRequestHeader("forward-proxy-url", xhr.url);
// open url - default
} else {
...
cryptoAesXxxCbcRawDecrypt = function (opt, onError) {
/*
* this function will aes-xxx-cbc decrypt with given <opt>
* example usage:
data = new Uint8Array([1,2,3]);
key = '0123456789abcdef0123456789abcdef';
mode = null;
local.cryptoAesXxxCbcRawEncrypt({
data: data,
key: key,
mode: mode
}, function (err, data) {
console.assert(!err, err);
local.cryptoAesXxxCbcRawDecrypt({
data: data,
key: key,
mode: mode
}, console.log);
});
*/
var cipher;
var crypto;
var data;
var ii;
var iv;
var key;
// init key
key = new Uint8Array(0.5 * opt.key.length);
ii = 0;
while (ii < key.byteLength) {
key[ii] = parseInt(opt.key.slice(2 * ii, 2 * ii + 2), 16);
ii += 2;
}
data = opt.data;
// base64
if (opt.mode === "base64") {
data = local.base64ToBuffer(data);
}
// normalize data
if (Object.prototype.toString.call(data) !== "[object Uint8Array]") {
data = new Uint8Array(data);
}
// init iv
iv = data.subarray(0, 16);
// optimization - create resized-view of data
data = data.subarray(16);
crypto = globalThis.crypto;
if (!local.isBrowser) {
setTimeout(function () {
crypto = require("crypto");
cipher = crypto.createDecipheriv(
"aes-" + (8 * key.byteLength) + "-cbc",
key,
iv
);
onError(null, Buffer.concat([
cipher.update(data), cipher.final()
]));
});
return;
}
crypto.subtle.importKey("raw", key, {
name: "AES-CBC"
}, false, [
"decrypt"
]).then(function (key) {
crypto.subtle.decrypt({
iv,
name: "AES-CBC"
}, key, data).then(function (data) {
onError(null, new Uint8Array(data));
}).catch(onError);
}).catch(onError);
}
...
mode = null;
local.cryptoAesXxxCbcRawEncrypt({
data: data,
key: key,
mode: mode
}, function (err, data) {
console.assert(!err, err);
local.cryptoAesXxxCbcRawDecrypt({
data: data,
key: key,
mode: mode
}, console.log);
});
*/
var cipher;
...
cryptoAesXxxCbcRawEncrypt = function (opt, onError) {
/*
* this function will aes-xxx-cbc encrypt with given <opt>
* example usage:
data = new Uint8Array([1,2,3]);
key = '0123456789abcdef0123456789abcdef';
mode = null;
local.cryptoAesXxxCbcRawEncrypt({
data: data,
key: key,
mode: mode
}, function (err, data) {
console.assert(!err, err);
local.cryptoAesXxxCbcRawDecrypt({
data: data,
key: key,
mode: mode
}, console.log);
});
*/
var cipher;
var crypto;
var data;
var ii;
var iv;
var key;
// init key
key = new Uint8Array(0.5 * opt.key.length);
ii = 0;
while (ii < key.byteLength) {
key[ii] = parseInt(opt.key.slice(2 * ii, 2 * ii + 2), 16);
ii += 2;
}
data = opt.data;
// init iv
iv = new Uint8Array((((data.byteLength) >> 4) << 4) + 32);
crypto = globalThis.crypto;
if (!local.isBrowser) {
setTimeout(function () {
crypto = require("crypto");
// init iv
iv.set(crypto.randomBytes(16));
cipher = crypto.createCipheriv(
"aes-" + (8 * key.byteLength) + "-cbc",
key,
iv.subarray(0, 16)
);
data = cipher.update(data);
iv.set(data, 16);
iv.set(cipher.final(), 16 + data.byteLength);
if (opt.mode === "base64") {
iv = local.base64FromBuffer(iv);
iv += "\n";
}
onError(null, iv);
});
return;
}
// init iv
iv.set(crypto.getRandomValues(new Uint8Array(16)));
crypto.subtle.importKey("raw", key, {
name: "AES-CBC"
}, false, [
"encrypt"
]).then(function (key) {
crypto.subtle.encrypt({
iv: iv.subarray(0, 16),
name: "AES-CBC"
}, key, data).then(function (data) {
iv.set(new Uint8Array(data), 16);
// base64
if (opt.mode === "base64") {
iv = local.base64FromBuffer(iv);
iv += "\n";
}
onError(null, iv);
}).catch(onError);
}).catch(onError);
}
...
local.cryptoAesXxxCbcRawDecrypt = function (opt, onError) {
/*
* this function will aes-xxx-cbc decrypt with given <opt>
* example usage:
data = new Uint8Array([1,2,3]);
key = '0123456789abcdef0123456789abcdef';
mode = null;
local.cryptoAesXxxCbcRawEncrypt({
data: data,
key: key,
mode: mode
}, function (err, data) {
console.assert(!err, err);
local.cryptoAesXxxCbcRawDecrypt({
data: data,
...
dateGetWeekOfMonth = function (date) {
/*
* this function will return sunday-based week-of-month from <date>
*/
date = new Date(date.slice(0, 10) + "T00:00:00Z");
return Math.ceil((date.getUTCDate() + new Date(
date.getUTCFullYear(),
date.getUTCMonth(),
1
).getUTCDay()) / 7) - 1;
}
n/a
dateGetWeekOfYear = function (date) {
/*
* this function will return ISO week-of-year from <date>
*
* Based on information at:
*
* http://www.merlyn.demon.co.uk/weekcalc.htm#WNR
*
* Algorithm is to find nearest thursday, it's year
* is the year of the week number. Then get weeks
* between that date and the first day of that year.
*
* Note that dates in one year can be weeks of previous
* or next year, overlap is up to 3 days.
*
* e.g. 2014/12/29 is Monday in week 1 of 2015
* 2012/1/1 is Sunday in week 52 of 2011
*
* https://stackoverflow.com/questions/6117814/get-week-of-year-in-javascript-like-in-php
*/
date = new Date(date.slice(0, 10) + "T00:00:00Z");
// Set to nearest Thursday: current date + 4 - current day number
// Make Sunday's day number 7
date.setUTCDate(date.getUTCDate() + 4 - (date.getUTCDay() || 7));
// Calculate full weeks to nearest Thursday
return Math.ceil((((
date
// Get first day of year
- new Date(Date.UTC(date.getUTCFullYear(), 0, 1))
) / 86400000) + 1) / 7);
}
n/a
dateUtcFromLocal = function (date, timezoneOffset) {
/*
* this function will convert local-<date> to utc-date
*/
if (!date) {
return "";
}
local.assertThrow((
/^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+?)?$/
).test(date), "invalid local-date " + date);
if (!timezoneOffset) {
return new Date(date).toISOString();
}
return new Date(
new Date(date + "Z").getTime() + timezoneOffset * 60000
).toISOString();
}
n/a
dateUtcToLocal = function (date, timezoneOffset) {
/*
* this function will convert utc-<date> to local-date
*/
if (!date) {
return "";
}
local.assertThrow((
/^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+?)?Z$/
).test(date), "invalid utc-date " + date);
timezoneOffset = timezoneOffset || new Date(date).getTimezoneOffset();
return new Date(
new Date(date).getTime() - timezoneOffset * 60000
).toISOString();
}
n/a
db._DbTable = function (opt) {
/*
* this function will create a dbTable
*/
this.name = String(opt.name);
// register dbTable in dbTableDict
local.dbTableDict[this.name] = this;
this.dbRowList = [];
this.isDirty = null;
this.idIndexList = [
{
isInteger: false,
name: "_id",
dict: {}
}
];
this.onSaveList = [];
this.sizeLimit = opt.sizeLimit || 0;
}
n/a
domFragmentRender = function (template, dict) {
/*
* this function will return dom-elem rendered from <template>
*/
var tmp;
tmp = document.createElement("template");
tmp.innerHTML = local.templateRender(template, dict);
return tmp.content;
}
...
});
// init uiFragment
swaggerJson.uiFragment = document.createDocumentFragment();
// init resourceDict
Object.keys(swaggerJson.resourceDict).sort().forEach(function (key) {
// templateRender resource
swaggerJson.uiFragment.appendChild(
local.domFragmentRender(
local.templateUiResource,
swaggerJson.resourceDict[key]
)
);
});
Object.keys(swaggerJson.operationDict).sort(function (aa, bb) {
aa = swaggerJson.operationDict[aa];
...
domQuerySelectorAllTagName = function (selector) {
/*
* this function will return all tagName that match <selector>
*/
var set;
set = new Set();
Array.from(document.querySelectorAll(
selector
)).forEach(function (elem) {
set.add(elem.tagName);
});
return Array.from(set).sort();
}
n/a
domSelectOptionValue = function (elem) {
/*
* this function will return <elem>.options[<elem>.selectedIndex].value
*/
elem = elem && elem.options[elem.selectedIndex];
return (elem && elem.value) || "";
}
n/a
domStyleValidate = function () {
/*
* this function will validate <style> tags
*/
var rgx;
var tmp;
rgx = (
/^0\u0020(?:(body\u0020>\u0020)?(?:form\u0020>\u0020)?(?:\.testReportDiv\u0020.+|\.x-istanbul\u0020.+|\.button|\.colorError
|\.readonly|\.textarea|\.uiAnimateShake|\.uiAnimateSlide|a|body|code|div|input|pre|textarea)(?:,|\u0020\{))|^[1-9]\d*?\u0020#/m
);
tmp = [];
Array.from(
// ternary-operator
(
typeof document === "object"
&& document
&& typeof document.querySelector === "function"
)
? document.querySelectorAll(
"style"
)
: []
).map(function (elem, ii) {
elem.innerHTML.replace((
/\/\*[\S\s]*?\*\/|;|\}/g
), "\n").replace((
/^([^\n\u0020@].*?)[,{:].*?$/gm
), function (match0, match1) {
try {
ii = document.querySelectorAll(
match1
).length;
} catch (errCaught) {
console.error(errCaught);
}
if (!(ii > 1)) {
tmp.push(ii + " " + match0);
}
});
});
tmp.filter(function (elem) {
return !rgx.test(elem);
}).sort().reverse().forEach(function (elem, ii, list) {
console.error(
"domStyleValidateUnmatched " + (list.length - ii) + ". " + elem
);
});
}
...
return local.buildTest({}, onError);
};
local._testCase_webpage_default = function (opt, onError) {
/*
* this function will test webpage's default handling-behavior
*/
local.domStyleValidate();
if (local.isBrowser) {
onError(null, opt);
return;
}
local.browserTest({
fileScreenshot: (
local.env.npm_config_dir_build
...
errorMessagePrepend = function (err, message) {
/*
* this function will prepend message to <err>.message and <err>.stack
*/
if (err === local.errDefault) {
return;
}
err.message = message + err.message;
err.stack = message + err.stack;
return err;
}
...
*/
local.onErrorJsonapi(function (err, data) {
local.serverRespondHeadSet(req, res, err && err.statusCode, {
"Content-Type": "application/json"
});
if (err) {
// debug statusCode / method / url
local.errorMessagePrepend(
err,
res.statusCode + " " + req.method + " " + req.url + "\n"
);
// print err.stack to stderr
local.onErrorDefault(err);
}
data = err || data;
...
function EventEmitter() { EventEmitter.init.call(this); }
n/a
exit = function (exitCode, testReport) {
/*
* this function will exit current process with given <exitCode>
*/
local.onErrorDefault(typeof exitCode !== "number" && exitCode);
exitCode = (
(!exitCode || Number(exitCode) === 0)
? 0
: Number(exitCode) || 1
);
if (!local.isBrowser) {
process.exit(exitCode);
return;
}
if (testReport !== globalThis.utility2_testReport) {
return;
}
// update coverage
(document.querySelector(
"#coverageReportDiv1"
) || {}).innerHTML = (
local.istanbulCoverageReportCreate()
);
// save testReport
globalThis.utility2_testReportSave();
}
...
* <fileRemote|dirRemote> <commitMessage>
* will delete from github <fileRemote|dirRemote>
*/
local.github_crud.githubCrudContentDelete({
message: process.argv[4],
url: process.argv[3]
}, function (err) {
process.exit(Boolean(err));
});
};
local.cliDict.get = function () {
/*
* <fileRemote>
* will get from github <fileRemote>
...
fsReadFileOrEmptyStringSync = function (file, opt) {
/*
* this function will try to read file or return empty-string, or
* if <opt> === "json", then try to JSON.parse file or return null
*/
try {
return (
opt === "json"
? JSON.parse(local.fs.readFileSync(file, "utf8"))
: local.fs.readFileSync(file, opt)
);
} catch (ignore) {
return (
opt === "json"
? {}
: ""
);
}
}
...
local.templateSwaggerUiLogoMediumBase64,
"base64"
);
local.assetsDict["/assets.swagger-ui.logo.small.png"] = Buffer.from(
local.templateSwaggerUiLogoSmallBase64,
"base64"
);
local.swgg.apiUpdate(local.fsReadFileOrEmptyStringSync(
local.__dirname + "/assets.swgg.swagger.json",
"json"
));
}());
...
fsRmrSync = function (dir) {
/*
* this function will synchronously "rm -fr" dir
*/
local.child_process.execFileSync(
"rm",
[
"-fr", local.path.resolve(process.cwd(), dir)
],
{
stdio: [
"ignore", 1, 2
]
}
);
}
...
/*
* this function will build app with given <opt>
*/
opt = local.objectSetDefault(opt, {
assetsList: []
});
// build assets
local.fsRmrSync("tmp/build/app");
local.onParallelList({
list: [
{
file: "/LICENSE",
url: "/LICENSE"
}, {
file: "/assets." + local.env.npm_package_nameLib + ".html",
...
fsWriteFileWithMkdirpSync = function (file, data, mode) {
/*
* this function will synchronously "mkdir -p" and write <data> to <file>
*/
try {
if (
mode === "noWrite"
|| typeof require("fs").writeFileSync !== "function"
) {
return;
}
} catch (ignore) {
return;
}
// try to write to file
try {
require("fs").writeFileSync(file, data);
} catch (ignore) {
// mkdir -p
require("child_process").spawnSync(
"mkdir",
[
"-p", require("path").dirname(file)
],
{
stdio: [
"ignore", 1, 2
]
}
);
// re-write to file
require("fs").writeFileSync(file, data);
}
}
...
// 1. print coverage in text-format to stdout
new local.TextReport(opt).writeReport(local.collector);
// 2. write coverage in html-format to filesystem
new local.HtmlReport(opt).writeReport(local.collector);
local.writer.writeFile("", local.nop);
if (!local.isBrowser) {
// write coverage.json
local.fsWriteFileWithMkdirpSync(
opt.dir + "/coverage.json",
JSON.stringify(globalThis.__coverage__)
);
// write coverage.code-dict.json
local.fsWriteFileWithMkdirpSync(
opt.dir + "/coverage.code-dict.json",
JSON.stringify(globalThis.__coverageCodeDict__)
...
functionOrNop = function (fnc) {
/*
* this function will if <fnc> exists,
* them return <fnc>,
* else return <nop>
*/
return fnc || local.nop;
}
...
if (element.isDescending) {
result.reverse();
}
});
// skip
result = result.slice(skip || 0);
// shuffle
local.functionOrNop(shuffle && local.listShuffle)(result);
// limit
result = result.slice(0, limit || Infinity);
return result;
};
local._DbTable.prototype._crudGetOneById = function (idDict) {
/*
...
identity = function (value) {
/*
* this function will return <value>
*/
return value;
}
...
local.cliDict.help = local.cliDict.help || local.cliDict._help;
local.cliDict._interactive = local.cliDict._interactive || function () {
/*
*
* will start interactive-mode
*/
globalThis.local = local;
local.identity(local.replStart || require("repl").start)({
useGlobal: true
});
};
local.cliDict["--interactive"] = (
local.cliDict["--interactive"]
|| local.cliDict._interactive
);
...
isNullOrUndefined = function (arg0) {
/*
* this function will test if arg0 is null or undefined
*/
return arg0 === null || arg0 === undefined;
}
...
? "arraybuffer"
: ""
)
});
// init paramDict
that.parameters.forEach(function (schemaP) {
tmp = opt.paramDict[schemaP.name];
if (local.isNullOrUndefined(tmp)) {
return;
}
// serialize array
if (Array.isArray(tmp) && schemaP.in !== "body") {
switch (
schemaP.collectionFormat || schemaP["x-swgg-collectionFormat"]
) {
...
function HtmlReport(opts) { Report.call(this); this.opts = opts || {}; this.opts.dir = this.opts.dir || path.resolve(process.cwd(), 'html-report'); this.opts.sourceStore = this.opts.sourceStore || Store.create('fslookup'); this.opts.linkMapper = this.opts.linkMapper || this.standardLinkMapper(); this.opts.writer = this.opts.writer || null; // coverage-hack - new Date() bugfix this.opts.templateData = { datetime: new Date().toGMTString() }; this.opts.watermarks = this.opts.watermarks || defaults.watermarks(); }
n/a
function Instrumenter(options) { this.opts = options || { debug: false, walkDebug: false, coverageVariable: '__coverage__', codeGenerationOptions: undefined, noAutoWrap: false, noCompact: false, embedSource: false, preserveComments: false, esModules: false }; if (this.opts.esModules && !this.opts.noAutoWrap) { this.opts.noAutoWrap = true; if (this.opts.debug) { console.log('Setting noAutoWrap to true as required by esModules'); } } this.walker = new Walker({ ArrowFunctionExpression: [ this.arrowBlockConverter ], ExpressionStatement: this.coverStatement, ExportNamedDeclaration: this.coverExport, BreakStatement: this.coverStatement, ContinueStatement: this.coverStatement, DebuggerStatement: this.coverStatement, ReturnStatement: this.coverStatement, ThrowStatement: this.coverStatement, TryStatement: [ this.paranoidHandlerCheck, this.coverStatement], VariableDeclaration: this.coverStatement, IfStatement: [ this.ifBlockConverter, this.coverStatement, this.ifBranchInjector ], ForStatement: [ this.skipInit, this.loopBlockConverter, this.coverStatement ], ForInStatement: [ this.skipLeft, this.loopBlockConverter, this.coverStatement ], ForOfStatement: [ this.skipLeft, this.loopBlockConverter, this.coverStatement ], WhileStatement: [ this.loopBlockConverter, this.coverStatement ], DoWhileStatement: [ this.loopBlockConverter, this.coverStatement ], SwitchStatement: [ this.coverStatement, this.switchBranchInjector ], SwitchCase: [ this.switchCaseInjector ], WithStatement: [ this.withBlockConverter, this.coverStatement ], FunctionDeclaration: [ this.coverFunction, this.coverStatement ], FunctionExpression: this.coverFunction, LabeledStatement: this.coverStatement, ConditionalExpression: this.conditionalBranchInjector, LogicalExpression: this.logicalExpressionBranchInjector, ObjectExpression: this.maybeAddType, MetaProperty: this.coverMetaProperty, }, this.extractCurrentHint, this, this.opts.walkDebug); //unit testing purposes only if (this.opts.backdoor && this.opts.backdoor.omitTrackerSuffix) { this.omitTrackerSuffix = true; } }
n/a
function TextReport(opts) { Report.call(this); opts = opts || {}; this.dir = opts.dir || process.cwd(); this.file = opts.file; this.summary = opts.summary; this.maxCols = opts.maxCols || 0; this.watermarks = opts.watermarks || defaults.watermarks(); }
n/a
function require(path) { return mod.require(path); }
n/a
istanbulCoverageMerge = function (coverage1, coverage2) {
/*
* this function will inplace-merge coverage2 into coverage1
*/
var dict1;
var dict2;
coverage1 = coverage1 || {};
coverage2 = coverage2 || {};
Object.keys(coverage2).forEach(function (file) {
if (!coverage2[file]) {
return;
}
// if file is undefined in coverage1, then add it
if (!coverage1[file]) {
coverage1[file] = coverage2[file];
return;
}
// merge file from coverage2 into coverage1
[
"b", "f", "s"
].forEach(function (key) {
dict1 = coverage1[file][key];
dict2 = coverage2[file][key];
switch (key) {
// increment coverage for branch lines
case "b":
Object.keys(dict2).forEach(function (key) {
dict2[key].forEach(function (count, ii) {
dict1[key][ii] += count;
});
});
break;
// increment coverage for function and statement lines
case "f":
case "s":
Object.keys(dict2).forEach(function (key) {
dict1[key] += dict2[key];
});
break;
}
});
});
return coverage1;
}
...
return;
}
// merge browser coverage
data = (
opt.modeCoverageMerge
&& local.fsReadFileOrEmptyStringSync(opt.fileCoverage, "json")
);
local.istanbulCoverageMerge(window.__coverage__, data);
console.error(
"\nbrowserTest - merged coverage from file "
+ opt.fileCoverage
+ "\n"
);
// merge browser test-report
data = local.fsReadFileOrEmptyStringSync(
...
istanbulCoverageReportCreate = function () {
/*
* this function will
* 1. print coverage in text-format to stdout
* 2. write coverage in html-format to filesystem
* 3. return coverage in html-format as single document
*/
var opt;
/* istanbul ignore next */
if (!globalThis.__coverage__) {
return "";
}
opt = {};
opt.dir = process.cwd() + "/tmp/build/coverage.html";
// merge previous coverage
if (!local.isBrowser && process.env.npm_config_mode_coverage_merge) {
console.log("merging file " + opt.dir + "/coverage.json to coverage");
try {
local.coverageMerge(globalThis.__coverage__, JSON.parse(
local.fs.readFileSync(opt.dir + "/coverage.json", "utf8")
));
} catch (ignore) {}
try {
opt.coverageCodeDict = JSON.parse(local.fs.readFileSync(
opt.dir + "/coverage.code-dict.json",
"utf8"
));
Object.keys(opt.coverageCodeDict).forEach(function (key) {
globalThis.__coverageCodeDict__[key] = (
globalThis.__coverageCodeDict__[key]
|| opt.coverageCodeDict[key]
);
});
} catch (ignore) {}
}
// init writer
local.coverageReportHtml = "";
local.coverageReportHtml += (
"<div class=\"coverageReportDiv\">\n"
+ "<h1>coverage-report</h1>\n"
+ "<div style=\""
+ "background: #fff; border: 1px solid #000; margin 0; padding: 0;"
+ "\">\n"
);
local.writerData = "";
opt.sourceStore = {};
opt.writer = local.writer;
// 1. print coverage in text-format to stdout
new local.TextReport(opt).writeReport(local.collector);
// 2. write coverage in html-format to filesystem
new local.HtmlReport(opt).writeReport(local.collector);
local.writer.writeFile("", local.nop);
if (!local.isBrowser) {
// write coverage.json
local.fsWriteFileWithMkdirpSync(
opt.dir + "/coverage.json",
JSON.stringify(globalThis.__coverage__)
);
// write coverage.code-dict.json
local.fsWriteFileWithMkdirpSync(
opt.dir + "/coverage.code-dict.json",
JSON.stringify(globalThis.__coverageCodeDict__)
);
// write coverage.badge.svg
opt.pct = local.coverageReportSummary.root.metrics.lines.pct;
local.fsWriteFileWithMkdirpSync(
local._istanbul_path.dirname(opt.dir) + "/coverage.badge.svg",
local.templateCoverageBadgeSvg
// edit coverage badge percent
.replace((
/100.0/g
), opt.pct)
// edit coverage badge color
.replace((
/0d0/g
), ((
"0" + Math.round((100 - opt.pct) * 2.21).toString(16)
).slice(-2) + (
"0" + Math.round(opt.pct * 2.21).toString(16)
).slice(-2) + "00"))
);
}
console.log("created coverage file " + opt.dir + "/index.html");
// 3. return coverage in html-format as a single document
local.coverageReportHtml += "</div>\n</div>\n";
// write coverage.rollup.html
if (!local.isBrowser) {
local.fsWriteFileWithMkdirpSync(
opt.dir + "/coverage.rollup.html",
local.coverageReportHtml
);
}
return local.coverageReportHtml;
}
...
if (testReport !== globalThis.utility2_testReport) {
return;
}
// update coverage
(document.querySelector(
"#coverageReportDiv1"
) || {}).innerHTML = (
local.istanbulCoverageReportCreate()
);
// save testReport
globalThis.utility2_testReportSave();
};
local.fsReadFileOrEmptyStringSync = function (file, opt) {
/*
...
istanbulInstrumentInPackage = function (code, file) {
/*
* this function will instrument the code
* only if the macro /\* istanbul instrument in package $npm_package_nameLib *\/
* exists in the code
*/
return (
// ternary-operator
(
process.env.npm_config_mode_coverage
&& code.indexOf("/* istanbul ignore all */\n") < 0 && (
process.env.npm_config_mode_coverage === "all"
|| code.indexOf(
"/* istanbul instrument in package "
+ process.env.npm_package_nameLib + " */\n"
) >= 0
|| code.indexOf(
"/* istanbul instrument in package "
+ process.env.npm_config_mode_coverage + " */\n"
) >= 0
)
)
? local.instrumentSync(code, file)
: code
);
}
...
"globalThis.utility2_moduleExports"
);
// init example.js
tmp = process.cwd() + "/example.js";
// jslint code
local.jslintAndPrint(code, tmp);
// cover code
code = local.istanbulInstrumentInPackage(code, tmp);
// init module.exports
module = new local.Module(tmp);
require.cache[tmp] = module;
// load code into module
module._compile(code, tmp);
// init exports
module.exports.utility2 = local;
...
istanbulInstrumentSync = function (code, file) {
/*
* this function will
* 1. normalize the file
* 2. save code to __coverageCodeDict__[file] for future html-report
* 3. return instrumented code
*/
// 1. normalize the file
file = local._istanbul_path.resolve("/", file);
// 2. save code to __coverageCodeDict__[file] for future html-report
globalThis.__coverageCodeDict__[file] = code;
// 3. return instrumented code
return new local.Instrumenter({
embedSource: true,
esModules: true,
noAutoWrap: true
}).instrumentSync(code, file).trimLeft();
}
n/a
jslintAndPrint = function (code, file, opt) {
/*
* this function will jslint / csslint <code> and print any errors to stderr
*/
var tmp;
if (!(opt && opt.modeNext)) {
local.jslintResult = {
modeNext: 0
};
}
code = code || "";
file = file || "undefined";
opt = Object.assign(local.jslintResult, opt || {}, {
code,
file
});
opt.modeNext += 1;
switch (opt.modeNext) {
// jslint - init
case 1:
// cleanup
opt.errList = [];
opt.errText = "";
switch (opt.fileType0) {
// deembed-js - '\\n\\\n...\\n\\\n'
case ".\\n\\":
// rgx - remove \\n\\
code = code.replace((
/\\n\\$|\\(.)/gm
), function (match0) {
return (
match0 === "\\n\\"
? ""
: match0[1]
);
});
break;
// deembed-js - '\n...\n'
case ".sh":
// rgx - convert '"'"' to '
code = code.replace((
/'"'"'/g
), "'");
break;
}
// init
opt = Object.assign(opt, {
".css": (
/^\/\*csslint\b|(^\/\*\u0020jslint\u0020utility2:true\u0020\*\/$)/m
),
".html": (
/^\/\*csslint\b|(^\/\*\u0020jslint\u0020utility2:true\u0020\*\/$)/m
),
".js": (
/^\/\*jslint\b|(^\/\*\u0020jslint\u0020utility2:true\u0020\*\/$)/m
),
".md": (
/(^\/\*\u0020jslint\u0020utility2:true\u0020\*\/$)/m
),
".sh": (
/(^#\u0020jslint\u0020utility2:true$)/m
),
code0: code,
fileType: (
/\.\w+?$|$/m
).exec(file)[0]
});
// jslint - .json
if (
code && (opt.fileType === ".js" || opt.fileType === ".json")
&& !opt.fileType0
) {
try {
tmp = JSON.parse(code);
opt.fileType = ".json";
if (opt.autofix) {
code = JSON.stringify(tmp, null, 4) + "\n";
opt.code0 = code;
}
opt.modeNext = Infinity;
break;
} catch (errCaught) {
if (opt.fileType === ".json") {
opt.errList.push({
column: 0,
evidence: code.slice(0, 100),
line: 0,
message: errCaught.message
});
opt.modeNext = Infinity;
break;
}
}
}
try {
opt.conditionalPassed = opt[opt.fileType].exec(code);
} catch (ignore) {}
opt.utility2 = (
opt.conditionalPassed
&& opt.conditionalPassed[1]
) || opt.autofix;
if (
opt.conditional
&& (!opt.conditionalPassed || opt.coverage)
) {
break;
}
opt.modeNext = 10;
break;
// jslint - autofix
case 11:
code = local.jslintAutofix(code, file, opt);
local.jslintResult = opt;
break;
// jslint - csslint and jslint
case 12:
// restore lineOffset
code = "\n".repeat(opt.lineOffset | 0) + code;
switch (opt.fileType) {
case ".css":
// csslint
Object.assign(opt, local.CSSLint.verify(code));
// init errList
opt.errList = opt.messages.map(function (err) {
err...
...
return;
}
// read file
local.fs.readFile(opt.file, "utf8", opt.onNext);
break;
case 2:
// jslint
local.jslint.jslintAndPrint(data, opt.file);
local.assertThrow(
!local.jslint.jslintResult.errText,
local.jslint.jslintResult.errText.replace((
/\u001b\[\d*m/g
), "")
);
// validate
...
jslintAutofixLocalFunction = function (code, file) {
/*
* this function will jslint-autofix local-function
*/
var code2;
var dictFnc;
var dictProp;
var tmp;
if (local.isBrowser) {
return code;
}
file = file.replace(process.cwd() + "/", "");
switch (file) {
case "README.md":
case "lib." + process.env.npm_package_nameLib + ".js":
case "lib." + process.env.npm_package_nameLib + ".sh":
case "lib.apidoc.js":
case "lib.db.js":
case "lib.github_crud.js":
case "lib.istanbul.js":
case "lib.jslint.js":
case "lib.marked.js":
case "lib.sjcl.js":
case "lib.swgg.js":
case "npm_scripts.sh":
case "test.js":
break;
default:
return code;
}
// autofix - assets.example.begin.js
code = code.replace((
/^\(function\u0020\(globalThis\)\u0020\{\n[\S\s]*?\n\}\(this\)\);\n/m
), local.assetsDict["/assets.example.begin.js"]);
// autofix - assets.my_app.template.js
code = local.stringMerge(
code,
local.assetsDict["/assets.my_app.template.js"].replace((
/my_app/g
), file.split(".")[1]),
file !== "README.md" && local.identity(
/\n\/\*\u0020istanbul\u0020instrument\u0020in\u0020package\u0020[\S\s]*?\n\/\*\u0020validateLineSortedReset\u0020\*\/\n/
)
);
// customize local for assets.utility2.rollup.js
if (
file === "lib." + process.env.npm_package_nameLib + ".js"
&& local.fs.existsSync("./assets.utility2.rollup.js")
&& local.env.npm_package_nameLib !== "swgg"
) {
code = code.replace(
" // || globalThis.utility2_rollup_old",
" || globalThis.utility2_rollup_old"
).replace(
" // || require(\"./assets.utility2.rollup.js\")",
" || require(\"./assets.utility2.rollup.js\")"
);
}
// init functionAllDict and functionBaseDict
[
[
"utility2", "swgg"
], [
"utility2", "apidoc", "db", "github_crud", "swgg"
]
].forEach(function (dictList, ii) {
tmp = (
ii
? "functionAllDict"
: "functionBaseDict"
);
if (local[tmp]) {
return;
}
local[tmp] = {};
dictList.forEach(function (dict) {
dict = local[dict];
Object.keys(dict).forEach(function (key) {
if (
!(
/^[A-Z_]|^testCase_/m
).test(key)
&& typeof dict[key] === "function"
) {
local[tmp][key] = local[tmp][key] || String(dict[key]);
}
});
});
Object.keys(local[tmp]).forEach(function (key) {
if (process.binding("natives")[key]) {
local[tmp][key] = undefined;
}
});
});
// autofix - local-function
dictFnc = {};
dictProp = {};
code = code.replace((
/^local\.(.*?)\u0020=\u0020(function\u0020\([\S\s]*?\n\});\n+/gm
), function (match0, key, match2, match3) {
// local-function - duplicate
if (dictFnc[key]) {
return "";
}
// local-function - normalize
dictFnc[key] = true;
match3 = local.functionAllDict[key] || "";
// make shell-safe
// https://unix.stackexchange.com/questions/57794/shell-escape-characters-for-sh-c
if (file.slice(-3) === ".sh") {
match3 = match3.re...
n/a
jsonCopy = function (obj) {
/*
* this function will deep-copy obj
*/
return (
obj === undefined
? undefined
: JSON.parse(JSON.stringify(obj))
);
}
...
? undefined
// recurse
: normalize(dbRow[key])
);
});
return dbRow;
};
dbRow = local.jsonCopy(local.objectSetOverride(dbRow));
// update timestamp
timeNow = new Date().toISOString();
dbRow._timeCreated = dbRow._timeCreated || timeNow;
if (!local.modeImport) {
dbRow._timeUpdated = timeNow;
}
// normalize
...
jsonStringifyOrdered = function (obj, replacer, space) {
/*
* this function will JSON.stringify <obj>,
* with object-keys sorted and circular-references removed
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Syntax
*/
var circularSet;
var stringify;
var tmp;
stringify = function (obj) {
/*
* this function will recursively JSON.stringify obj,
* with object-keys sorted and circular-references removed
*/
// if obj is not an object or function, then JSON.stringify as normal
if (!(
obj
&& typeof obj === "object"
&& typeof obj.toJSON !== "function"
)) {
return JSON.stringify(obj);
}
// ignore circular-reference
if (circularSet.has(obj)) {
return;
}
circularSet.add(obj);
// if obj is an array, then recurse its items
if (Array.isArray(obj)) {
tmp = "[" + obj.map(function (obj) {
// recurse
tmp = stringify(obj);
return (
typeof tmp === "string"
? tmp
: "null"
);
}).join(",") + "]";
circularSet.delete(obj);
return tmp;
}
// if obj is not an array,
// then recurse its items with object-keys sorted
tmp = "{" + Object.keys(obj).sort().map(function (key) {
// recurse
tmp = stringify(obj[key]);
if (typeof tmp === "string") {
return JSON.stringify(key) + ":" + tmp;
}
}).filter(function (obj) {
return typeof obj === "string";
}).join(",") + "}";
circularSet.delete(obj);
return tmp;
};
circularSet = new Set();
return JSON.stringify((
(typeof obj === "object" && obj)
// recurse
? JSON.parse(stringify(obj))
: obj
), replacer, space);
}
...
}
result = {};
fieldList.forEach(function (key) {
if (key[0] !== "$") {
result[key] = dbRow[key];
}
});
return JSON.parse(local.jsonStringifyOrdered(result));
};
local.dbRowSetId = function (dbRow, idIndex) {
/*
* this function will if does not exist,
* then set a random and unique id into dbRow for given idIndex,
*/
...
jwtAes256GcmDecrypt = function (token, key) {
/*
* this function will use json-web-encryption to
* aes-256-gcm-decrypt <token> with given base64url-encoded <key>
* https://tools.ietf.org/html/rfc7516
*/
return local.tryCatchOnError(function () {
token = token
.replace((
/-/g
), "+")
.replace((
/_/g
), "/")
.split(".");
token = local.sjcl.decrypt(
local.sjcl.codec.base64url.toBits(local.jwtAes256KeyInit(key)),
JSON.stringify({
adata: token[4],
ct: token[3],
iv: token[2],
ks: 256,
mode: "gcm"
})
);
return local.jwtHs256Decode(token, key);
}, local.nop) || {};
}
...
crud = req.swgg.crud;
user = {};
req.swgg.user = user;
user.jwtEncrypted = (
req.headers.authorization
&& req.headers.authorization.replace("Bearer ", "")
);
user.jwtDecrypted = local.jwtAes256GcmDecrypt(user.jwtEncrypted);
switch (crud.crudType[0]) {
// coverage-hack - test err handling-behavior
case "crudErrorLogin":
opt.onNext(local.errDefault);
return;
case "userLoginByPassword":
user.password = req.urlParsed.query.password;
...
jwtAes256GcmEncrypt = function (data, key) {
/*
* this function will use json-web-encryption to
* aes-256-gcm-encrypt <data> with given base64url-encoded <key>
* https://tools.ietf.org/html/rfc7516
*/
var adata;
adata = local.jwtAes256KeyCreate();
data = local.jwtHs256Encode(data, key);
data = JSON.parse(local.sjcl.encrypt(
local.sjcl.codec.base64url.toBits(local.jwtAes256KeyInit(key)),
data,
{
adata: local.sjcl.codec.base64url.toBits(adata),
ks: 256,
mode: "gcm"
}
));
return local.normalizeJwtBase64Url(
"eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4R0NNIn0.."
+ data.iv + "." + data.ct + "." + adata
);
}
...
// init isAuthenticated
user.isAuthenticated = true;
// create JSON Web Token (JWT)
// https://tools.ietf.org/html/rfc7519
user.jwtDecrypted = {};
user.jwtDecrypted.sub = user.data.username;
// update jwtEncrypted in client
user.jwtEncrypted = local.jwtAes256GcmEncrypt(
user.jwtDecrypted
);
local.serverRespondHeadSet(req, res, null, {
"swgg-jwt-encrypted": user.jwtEncrypted
});
// update jwtEncrypted in dbTableUser
local.dbTableUser.crudUpdateOneById({
...
jwtAes256KeyCreate = function () {
/*
* this function will create a random, aes-256-base64url-jwt-key
*/
return local.normalizeJwtBase64Url(
local.base64FromBuffer(local.bufferRandomBytes(32))
);
}
...
local.jwtAes256GcmEncrypt = function (data, key) {
/*
* this function will use json-web-encryption to
* aes-256-gcm-encrypt <data> with given base64url-encoded <key>
* https://tools.ietf.org/html/rfc7516
*/
var adata;
adata = local.jwtAes256KeyCreate();
data = local.jwtHs256Encode(data, key);
data = JSON.parse(local.sjcl.encrypt(
local.sjcl.codec.base64url.toBits(local.jwtAes256KeyInit(key)),
data,
{
adata: local.sjcl.codec.base64url.toBits(adata),
ks: 256,
...
jwtAes256KeyInit = function (key) {
/*
* this function will init aes-256-base64url-jwt-<key>
* https://jwt.io/
*/
// init npm_config_jwtAes256Key
local.env.npm_config_jwtAes256Key = (
local.env.npm_config_jwtAes256Key
|| "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
);
return key || local.env.npm_config_jwtAes256Key;
}
...
/-/g
), "+")
.replace((
/_/g
), "/")
.split(".");
token = local.sjcl.decrypt(
local.sjcl.codec.base64url.toBits(local.jwtAes256KeyInit(key)),
JSON.stringify({
adata: token[4],
ct: token[3],
iv: token[2],
ks: 256,
mode: "gcm"
})
...
jwtHs256Decode = function (token, key) {
/*
* this function will decode json-web-token with given base64-encoded <key>
* https://jwt.io/
*/
var Hmac;
var timeNow;
Hmac = local.sjcl.misc.hmac;
timeNow = Date.now() / 1000;
// try to decode token
return local.tryCatchOnError(function () {
token = token.split(".");
// validate header
local.assertThrow(
token[0] === "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9",
token
);
// validate signature
local.assertThrow(local.sjcl.codec.base64url.fromBits(
new Hmac(local.sjcl.codec.base64url.toBits(
local.jwtAes256KeyInit(key)
)).encrypt(token[0] + "." + token[1])
) === token[2]);
// return decoded data
token = JSON.parse(local.base64ToUtf8(token[1]));
// https://tools.ietf.org/html/rfc7519#section-4.1
// validate jwt-registered-headers
local.assertThrow(!token.exp || token.exp >= timeNow);
local.assertThrow(!token.nbf || token.nbf <= timeNow);
return token;
}, local.nop) || {};
}
...
adata: token[4],
ct: token[3],
iv: token[2],
ks: 256,
mode: "gcm"
})
);
return local.jwtHs256Decode(token, key);
}, local.nop) || {};
};
local.jwtAes256GcmEncrypt = function (data, key) {
/*
* this function will use json-web-encryption to
* aes-256-gcm-encrypt <data> with given base64url-encoded <key>
...
jwtHs256Encode = function (data, key) {
/*
* this function will encode <data> into a json-web-token
* with given base64-encoded <key>
* https://jwt.io/
*/
var Hmac;
Hmac = local.sjcl.misc.hmac;
data = (
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9."
+ local.normalizeJwtBase64Url(
local.base64FromBuffer(JSON.stringify(data))
)
);
return data + "." + local.sjcl.codec.base64url.fromBits(
new Hmac(local.sjcl.codec.base64url.toBits(
local.jwtAes256KeyInit(key)
)).encrypt(data)
);
}
...
/*
* this function will use json-web-encryption to
* aes-256-gcm-encrypt <data> with given base64url-encoded <key>
* https://tools.ietf.org/html/rfc7516
*/
var adata;
adata = local.jwtAes256KeyCreate();
data = local.jwtHs256Encode(data, key);
data = JSON.parse(local.sjcl.encrypt(
local.sjcl.codec.base64url.toBits(local.jwtAes256KeyInit(key)),
data,
{
adata: local.sjcl.codec.base64url.toBits(adata),
ks: 256,
mode: "gcm"
...
listGetElementRandom = function (list) {
/*
* this function will return random elem from <list>
*/
return list[Math.floor(Math.random() * list.length)];
}
...
return local.jsonCopy(schemaP.default);
}
// init enum-value
if (schemaP.enum) {
value = (
opt.modeNotRandom
? schemaP.enum[0]
: local.listGetElementRandom(schemaP.enum)
);
return (
local.schemaPType(schemaP) === "array"
? [
value
]
: value
...
listShuffle = function (list) {
/*
* this function will inplace shuffle <list> using fisher-yates algorithm
* https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
*/
var ii;
var random;
var swap;
ii = list.length;
while (ii > 1) {
ii -= 1;
random = Math.floor(Math.random() * (ii + 1));
swap = list[ii];
list[ii] = list[random];
list[random] = swap;
}
return list;
}
...
opt = {};
// init list
opt.list = "[0,1]";
// shuffle list 100 times
opt.ii = 0;
while (opt.ii < 100) {
opt.listShuffled = JSON.stringify(
local.listShuffle(JSON.parse(opt.list))
);
// validate shuffled list
local.assertJsonEqual(opt.listShuffled.length, opt.list.length);
opt.changed = opt.changed || opt.listShuffled !== opt.list;
opt.ii += 1;
}
// validate list changed at least once during the shuffle
...
localStorageSetItemOrClear = function (key, value) {
/*
* this function will try to set <key>/<value> pair to localStorage,
* or else call localStorage.clear()
*/
try {
localStorage.setItem(key, value);
} catch (ignore) {
localStorage.clear();
}
}
...
);
local.apiKeyValue = localStorage.getItem(local.apiKeyKey) || "";
// save apiKeyValue
} else {
local.apiKeyValue = document.querySelector(
"#swggApiKeyInput1"
).value;
local.localStorageSetItemOrClear(
local.apiKeyKey,
local.apiKeyValue
);
}
// if keyup-event is not return-key, then return
if (
(opt.type === "keyup" && opt.code !== "Enter")
...
function c (e, n, r){if(r||typeof n=="function"){r||(r=n,n=null),n=l({},c.defaults,n||{});var i= n.highlight,u,a,f=0;try{u=t.lex(e,n)}catch(h){return r(h)}a=u.length;var p=function( e){if(e)return n.highlight=i,r(e);var t;try{t=s.parse(u,n)}catch(o){e=o}return n .highlight=i,e?r(e):r(null,t)};if(!i||i.length<3)return p();delete n.highlight;if(! a)return p();for(;f<u.length;f++)(function(e){return e.type!=="code"?--a||p():i( e.text,e.lang,function(t,n){if(t)return p(t);if(n==null||n===e.text)return--a||p ();e.text=n,e.escaped=!0,--a||p()})})(u[f]);return}try{return n&&(n=l({},c.defaults ,n)),s.parse(t.lex(e,n),n)}catch(h){h.message+="\nPlease report this to https://github.com/chjj/marked." ;if((n||c.defaults).silent)return"<p>An error occured:</p><pre>"+o(h.message+"",!0 )+"</pre>";throw h}}
n/a
function r(e, t){this.options=t||c.defaults,this.links= e,this.rules=n.normal,this.renderer=this.options.renderer||new i,this.renderer.options= this.options;if(!this.links)throw new Error("Tokens array requires a `links` property." );this.options.gfm?this.options.breaks?this.rules=n.breaks:this.rules=n.gfm:this .options.pedantic&&(this.rules=n.pedantic)}
n/a
function t(t){this.tokens=[],this.tokens.links={},this.options=t||c. defaults,this.rules=e.normal,this.options.gfm&&(this.options.tables?this.rules=e .tables:this.rules=e.gfm)}
n/a
function s (e){this.tokens=[],this.token=null,this.options=e||c.defaults,this.options.renderer= this.options.renderer||new i,this.renderer=this.options.renderer,this.renderer.options= this.options}
n/a
function i(e){this.options=e||{}}
n/a
middlewareAssetsCached = function (req, res, next) {
/*
* this function will run middleware that will serve cached-assets
*/
var opt;
opt = {};
local.onNext(opt, function (err, data) {
opt.result = opt.result || local.assetsDict[req.urlParsed.pathname];
if (opt.result === undefined) {
next(err);
return;
}
switch (opt.modeNext) {
case 1:
// skip gzip
if (
res.headersSent
|| !(
/\bgzip\b/
).test(req.headers["accept-encoding"])
) {
opt.modeNext += 1;
opt.onNext();
return;
}
// gzip and cache result
local.taskCreateCached({
cacheDict: "middlewareAssetsCachedGzip",
key: req.urlParsed.pathname
}, function (onError) {
local.zlib.gzip(opt.result, function (err, data) {
onError(err, !err && data.toString("base64"));
});
}, opt.onNext);
break;
case 2:
// set gzip header
opt.result = local.base64ToBuffer(data);
res.setHeader("Content-Encoding", "gzip");
res.setHeader("Content-Length", opt.result.length);
opt.onNext();
break;
case 3:
local.middlewareCacheControlLastModified(
req,
res,
opt.onNext
);
break;
case 4:
res.end(opt.result);
break;
}
});
opt.modeNext = 0;
opt.onNext();
}
n/a
middlewareBodyRead = function (req, ignore, next) {
/*
* this function will run middleware that will
* read and save the <req>-body to <req>.bodyRaw
*/
// if req is already read, then goto next
if (!req.readable) {
next();
return;
}
local.streamReadAll(req, function (err, data) {
req.bodyRaw = req.bodyRaw || data;
next(err);
});
}
...
/*
* this function will run the test-middleware
*/
switch (req.urlParsed.pathname) {
// test http POST handling-behavior
case "/test.body":
// test req-body-read handling-behavior
local.middlewareBodyRead(req, res, function () {
// test multiple req-body-read handling-behavior
local.middlewareBodyRead(req, res, function () {
res.write(req.bodyRaw);
res.end();
});
});
break;
...
middlewareCacheControlLastModified = function (req, res, next) {
/*
* this function will run middleware that will update res-header last-modified
*/
// do not cache if headers already sent or url has '?' search indicator
if (res.headersSent || req.url.indexOf("?") >= 0) {
next();
return;
}
// init serverResponseHeaderLastModified
local.serverResponseHeaderLastModified = (
local.serverResponseHeaderLastModified
// resolve to 1000 ms
|| new Date(new Date().toUTCString())
);
// respond with 304 If-Modified-Since serverResponseHeaderLastModified
if (
new Date(req.headers["if-modified-since"])
>= local.serverResponseHeaderLastModified
) {
res.statusCode = 304;
res.end();
return;
}
res.setHeader("Cache-Control", "no-cache");
res.setHeader(
"Last-Modified",
local.serverResponseHeaderLastModified.toUTCString()
);
next();
}
...
// set gzip header
opt.result = local.base64ToBuffer(data);
res.setHeader("Content-Encoding", "gzip");
res.setHeader("Content-Length", opt.result.length);
opt.onNext();
break;
case 3:
local.middlewareCacheControlLastModified(
req,
res,
opt.onNext
);
break;
case 4:
res.end(opt.result);
...
middlewareError = function (err, req, res) {
/*
* this function will run middleware that will handle errors
*/
// default - 404 Not Found
if (!err) {
local.serverRespondDefault(req, res, 404);
return;
}
// http://jsonapi.org/format/#errors
if (local.swgg && typeof local.swgg.serverRespondJsonapi === "function") {
local.swgg.serverRespondJsonapi(req, res, err);
}
// statusCode [400, 600)
local.serverRespondDefault(req, res, (
(err.statusCode >= 400 && err.statusCode < 600)
? err.statusCode
: 500
), err);
}
...
local.middlewareFileServer
];
local.serverLocalReqHandler = function (req, res) {
var that;
that = {};
local.onNext(that, function (err) {
if (err || that.modeNext >= local.middlewareList.length) {
local.middlewareError(err, req, res);
return;
}
// recurse with next middleware in middlewareList
local.middlewareList[that.modeNext](req, res, that.onNext);
});
that.modeNext = -1;
that.onNext();
...
middlewareFileServer = function (req, res, next) {
/*
* this function will run middleware that will serve files
*/
if (req.method !== "GET" || local.isBrowser) {
next();
return;
}
req.urlFile = (process.cwd() + req.urlParsed.pathname
// security - disable parent directory lookup
.replace((
/.*\/\.\.\//g
), "/"))
// replace trailing '/' with '/index.html'
.replace((
/\/$/
), "/index.html");
// serve file from cache
local.taskCreateCached({
cacheDict: "middlewareFileServer",
key: req.urlFile
// run background-task to re-cache file
}, function (onError) {
local.fs.readFile(req.urlFile, function (err, data) {
onError(err, data && local.base64FromBuffer(data));
});
}, function (err, data) {
// default to next
if (err) {
next();
return;
}
// init res-header content-type
local.serverRespondHeadSet(req, res, null, {
"Content-Type": local.contentTypeDict[(
/\.[^.]*?$|$/m
).exec(req.urlParsed.pathname)[0]]
});
// serve file from cache
res.end(local.base64ToBuffer(data));
});
}
...
case "/test.timeout":
setTimeout(function () {
res.end();
}, 2000);
break;
// serve file
default:
local.middlewareFileServer(req, res, next);
}
});
}());
// run node js-env code - init-after
...
middlewareForwardProxy = function (req, res, next) {
/*
* this function will run middleware that will forward-proxy <req>
* to its destination-host
*/
var isDone;
var onError;
var opt;
var timerTimeout;
// handle preflight-cors
if (req.method === "OPTIONS" && (
/forward-proxy-url/
)
.test(req.headers["access-control-request-headers"])) {
local.serverRespondCors(req, res);
res.end();
return;
}
if (!req.headers["forward-proxy-url"]) {
next();
return;
}
local.serverRespondCors(req, res);
// init onError
onError = function (err) {
if (isDone) {
return;
}
isDone = true;
// cleanup timerTimeout
clearTimeout(timerTimeout);
// debug middlewareForwardProxy
console.error("serverLog - " + JSON.stringify({
time: new Date(opt.timeStart).toISOString(),
type: "middlewareForwardProxyResponse",
method: opt.method,
url: opt.url,
statusCode: res.statusCode | 0,
timeElapsed: Date.now() - opt.timeStart,
// extra
headers: opt.headers
}));
if (!err) {
return;
}
// cleanup clientReq and clientRes
local.streamCleanup(opt.clientReq);
local.streamCleanup(opt.clientResponse);
next(err);
};
// init opt
opt = local.urlParse(req.headers["forward-proxy-url"]);
opt.method = req.method;
opt.url = req.headers["forward-proxy-url"];
// init timerTimeout
timerTimeout = local.onTimeout(
onError,
local.timeoutDefault,
"forward-proxy " + opt.method + " " + opt.url
);
// parse headers
opt.headers = {};
local.tryCatchOnError(function () {
opt.headers = JSON.parse(req.headers["forward-proxy-headers"]);
}, local.nop);
// debug opt
local._debugForwardProxy = opt;
opt.clientReq = (
opt.protocol === "https:"
? local.https
: local.http
).request(opt, function (clientResponse) {
opt.clientResponse = clientResponse.on("error", onError);
res.statusCode = opt.clientResponse.statusCode;
// pipe clientResponse to serverResponse
opt.clientResponse.pipe(res);
}).on("error", onError);
opt.timeStart = Date.now();
// init event-handling
req.on("error", onError);
res.on("finish", onError).on("error", onError);
// pipe serverReq to clientReq
req.pipe(opt.clientReq);
}
n/a
middlewareInit = function (req, res, next) {
/*
* this function will run middleware that will init <req> and <res>
*/
// debug req and res
local._debugServerReqRes4 = local._debugServerReqRes3;
local._debugServerReqRes3 = local._debugServerReqRes2;
local._debugServerReqRes2 = local._debugServerReqRes1;
local._debugServerReqRes1 = {
req,
res
};
// init timerTimeout
local.serverRespondTimeoutDefault(req, res, local.timeoutDefault);
// init req.urlParsed
req.urlParsed = local.urlParse(req.url);
// init res-header content-type
local.serverRespondHeadSet(req, res, null, {
"Content-Type": local.contentTypeDict[(
/\.[^.]*?$|$/m
).exec(req.urlParsed.pathname)[0]]
});
// set main-page content-type to text/html
if (req.urlParsed.pathname === "/") {
local.serverRespondHeadSet(req, res, null, {
"Content-Type": "text/html; charset=utf-8"
});
}
// default to next
next();
}
n/a
middlewareJsonpStateInit = function (req, res, next) {
/*
* this function will run middleware that will
* serve the browser-state wrapped in given jsonp-callback
*/
var state;
if (!(req.stateInit || (
req.urlParsed
&& req.urlParsed.pathname === "/jsonp.utility2.stateInit"
))) {
next();
return;
}
state = {
utility2: {
assetsDict: {
"/assets.example.html":
local.assetsDict["/assets.example.html"],
"/assets.example.js": local.assetsDict["/assets.example.js"],
"/assets.swgg.swagger.json":
local.assetsDict["/assets.swgg.swagger.json"],
"/assets.test.js": local.assetsDict["/assets.test.js"],
"/assets.utility2.base.html":
local.assetsDict["/assets.utility2.base.rollup.html"],
"/index.rollup.html": local.assetsDict["/index.rollup.html"]
},
env: {
NODE_ENV: local.env.NODE_ENV,
npm_config_mode_backend: local.env.npm_config_mode_backend,
npm_package_assetsList: local.env.npm_package_assetsList,
npm_package_description: local.env.npm_package_description,
npm_package_homepage: local.env.npm_package_homepage,
npm_package_name: local.env.npm_package_name,
npm_package_nameLib: local.env.npm_package_nameLib,
npm_package_version: local.env.npm_package_version
}
}
};
(local.env.npm_package_assetsList || "").split(" ").forEach(function (
file
) {
local.assetsDict["/" + file] = (
local.assetsDict["/" + file]
|| local.fsReadFileOrEmptyStringSync(file, "utf8")
);
state.utility2.assetsDict["/" + file] = local.assetsDict["/" + file];
});
if (req.stateInit) {
return state;
}
res.end(
req.urlParsed.query.callback + "(" + JSON.stringify(state) + ");"
);
}
...
code += "\n";
code += local.assetsDict[tmp];
break;
case "local.stateInit":
// handle large string-replace
code = local.assetsDict["/assets.utility2.rollup.content.js"]
.split("/* utility2.rollup.js content */");
tmp = local.middlewareJsonpStateInit({
stateInit: true
});
// add extra physical files to assetsDict
local.fs.readdirSync(".").forEach(function (file) {
file = "/" + file;
if (
local.assetsDict[file]
...
moduleDirname = function (module, modulePathList) {
/*
* this function will search modulePathList for the module's __dirname
*/
var result;
// search process.cwd()
if (!module || module === "." || module.indexOf("/") >= 0) {
return require("path").resolve(process.cwd(), module || "");
}
// search modulePathList
[
"node_modules"
]
.concat(modulePathList)
.concat(require("module").globalPaths)
.concat([
process.env.HOME + "/node_modules", "/usr/local/lib/node_modules"
])
.some(function (modulePath) {
try {
result = require("path").resolve(
process.cwd(),
modulePath + "/" + module
);
result = require("fs").statSync(result).isDirectory() && result;
return result;
} catch (ignore) {
result = null;
}
return result;
});
return result || "";
}
...
return match0.replace((
/(.{128}(?:\b|\w+))/g
), "$1\n").trimRight();
});
return text;
};
// init opt
opt.dir = local.moduleDirname(
opt.dir,
opt.modulePathList || require("module").paths
);
local.objectSetDefault(opt, {
env: {
npm_package_description: ""
},
...
nop = function () {
/*
* this function will do nothing
*/
return;
}
...
process.stdout._writeDefault = (
process.stdout._writeDefault
|| process.stdout._write
);
process.stdout._write = function (chunk, encoding, callback) {
process.stdout._writeDefault(chunk, encoding, callback);
// coverage-hack - ignore else-statement
local.nop(that.socket.writable && (function () {
that.socket.write(chunk, encoding);
}()));
};
// start serverRepl1
globalThis.utility2_serverRepl1 = require("net").createServer(function (
socket
) {
...
normalizeChunk = function (chunk) {
/*
* this function will normalize the chunk
*/
return chunk || "";
}
...
req.onTimeout,
timeout || local.timeoutDefault,
"server " + req.method + " " + req.url
);
res.contentLength = 0;
res.writeContentLength = res.writeContentLength || res.write;
res.write = function (chunk, encoding, callback) {
chunk = local.normalizeChunk(chunk);
res.contentLength += chunk.length;
res.writeContentLength(chunk, encoding, callback);
};
res.on("error", onError);
res.on("finish", onError);
};
...
normalizeJwt = function (data) {
/*
* this function will normalize the jwt-data with registered-headers
* https://tools.ietf.org/html/rfc7519#section-4.1
*/
var timeNow;
timeNow = Date.now() / 1000;
return local.objectSetDefault(data, {
exp: timeNow + 5 * 60,
iat: timeNow,
jti: Math.random().toString(16).slice(2),
nbf: timeNow
});
}
...
local.testCase_jwtAes256GcmXxx_default = function (opt, onError) {
/*
* this function will test jwtAes256GcmXxx's default handling-behavior
*/
opt = {};
opt.key = local.jwtAes256KeyCreate();
// use canonical example at https://jwt.io/
opt.data = JSON.parse(local.jsonStringifyOrdered(local.normalizeJwt({
sub: "1234567890",
name: "John Doe",
admin: true
})));
// encrypt token
opt.token = local.jwtAes256GcmEncrypt(opt.data, opt.key);
// validate encrypted-token
...
normalizeJwtBase64Url = function (b64) {
/*
* this function will normlize <b64> to base64url format
*/
return b64
.replace((
/\=/g
), "")
.replace((
/\+/g
), "-")
.replace((
/\//g
), "_");
}
...
data,
{
adata: local.sjcl.codec.base64url.toBits(adata),
ks: 256,
mode: "gcm"
}
));
return local.normalizeJwtBase64Url(
"eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4R0NNIn0.."
+ data.iv + "." + data.ct + "." + adata
);
};
local.jwtAes256KeyCreate = function () {
/*
...
numberToRomanNumerals = function (num) {
/*
* this function will convert num to a roman-numeral
* https://stackoverflow.com/questions/9083037/convert-a-number-into-a-roman-numeral-in-javascript
*/
var digits;
var ii;
var key;
var roman;
digits = String(num).split("");
key = [
"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM",
"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC",
"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"
];
roman = "";
ii = 3;
while (ii) {
ii -= 1;
roman = (key[Number(digits.pop()) + (ii * 10)] || "") + roman;
}
return new Array(Number(digits.join("") + 1)).join("M") + roman;
}
...
"XCVIII",
"XCIX",
"C"
];
opt.ii = 0;
while (opt.ii < 10) {
local.assertJsonEqual(
local.numberToRomanNumerals(opt.ii),
opt.list[opt.ii]
);
opt.ii += 1;
}
onError(null, opt);
};
...
objectAssignDefault = function (target, source) {
/*
* this function will if items from <target> are
* null, undefined, or empty-string,
* then overwrite them with items from <source>
*/
target = target || {};
Object.keys(source || {}).forEach(function (key) {
if (
target[key] === null
|| target[key] === undefined
|| target[key] === ""
) {
target[key] = target[key] || source[key];
}
});
return target;
}
...
if (key[0] !== "_") {
xhr[key] = opt[key];
}
});
// init timeout
timeout = xhr.timeout || local2.timeoutDefault || 30000;
// init default
local.objectAssignDefault(xhr, {
corsForwardProxyHost: local2.corsForwardProxyHost,
headers: {},
location: (local.isBrowser && location) || {},
method: "GET",
responseType: ""
});
// init headers
...
objectSetDefault = function (dict, defaults, depth) {
/*
* this function will recursively set defaults for undefined-items in dict
*/
dict = dict || {};
defaults = defaults || {};
Object.keys(defaults).forEach(function (key) {
var defaults2;
var dict2;
dict2 = dict[key];
// handle misbehaving getter
try {
defaults2 = defaults[key];
} catch (ignore) {}
if (defaults2 === undefined) {
return;
}
// init dict[key] to default value defaults[key]
switch (dict2) {
case "":
case null:
case undefined:
dict[key] = defaults2;
return;
}
// if dict2 and defaults2 are both non-null and non-array objects,
// then recurse with dict2 and defaults2
if (
depth > 1
// dict2 is a non-null and non-array object
&& typeof dict2 === "object" && dict2 && !Array.isArray(dict2)
// defaults2 is a non-null and non-array object
&& typeof defaults2 === "object" && defaults2
&& !Array.isArray(defaults2)
) {
// recurse
local.objectSetDefault(dict2, defaults2, depth - 1);
}
});
return dict;
}
...
// dict2 is a non-null and non-array object
&& typeof dict2 === "object" && dict2 && !Array.isArray(dict2)
// defaults2 is a non-null and non-array object
&& typeof defaults2 === "object" && defaults2
&& !Array.isArray(defaults2)
) {
// recurse
local.objectSetDefault(dict2, defaults2, depth - 1);
}
});
return dict;
};
local.stringHtmlSafe = function (text) {
/*
...
objectSetOverride = function (dict, overrides, depth, env) {
/*
* this function will recursively set overrides for items in dict
*/
dict = dict || {};
env = env || (typeof process === "object" && process.env) || {};
overrides = overrides || {};
Object.keys(overrides).forEach(function (key) {
var dict2;
var overrides2;
dict2 = dict[key];
overrides2 = overrides[key];
if (overrides2 === undefined) {
return;
}
// if both dict2 and overrides2 are non-null and non-array objects,
// then recurse with dict2 and overrides2
if (
depth > 1
// dict2 is a non-null and non-array object
&& typeof dict2 === "object" && dict2 && !Array.isArray(dict2)
// overrides2 is a non-null and non-array object
&& typeof overrides2 === "object" && overrides2
&& !Array.isArray(overrides2)
) {
local.objectSetOverride(dict2, overrides2, depth - 1, env);
return;
}
// else set dict[key] with overrides[key]
dict[key] = (
dict === env
// if dict is env, then overrides falsy-value with empty-string
? overrides2 || ""
: overrides2
);
});
return dict;
}
...
depth > 1
// dict2 is a non-null and non-array object
&& typeof dict2 === "object" && dict2 && !Array.isArray(dict2)
// overrides2 is a non-null and non-array object
&& typeof overrides2 === "object" && overrides2
&& !Array.isArray(overrides2)
) {
local.objectSetOverride(dict2, overrides2, depth - 1, env);
return;
}
// else set dict[key] with overrides[key]
dict[key] = (
dict === env
// if dict is env, then overrides falsy-value with empty-string
? overrides2 || ""
...
onErrorDefault = function (err) {
/*
* this function will if <err> exists, then print it to stderr
*/
if (err) {
console.error(err);
}
return err;
}
...
dbTable = local.dbTableCreateOne({
isLoaded: true,
name: match1
});
dbTable.sortDefault = JSON.parse(match3);
break;
default:
local.onErrorDefault(new Error(
"db - dbImport - invalid operation - " + match0
));
}
});
Object.keys(dbTableDict).forEach(function (name) {
console.error("db - importing dbTable " + name + " ...");
});
...
onErrorThrow = function (err) {
/*
* this function will if <err> exists, then throw it
*/
if (err) {
throw err;
}
return err;
}
...
};
local.testCase_onErrorThrow_err = function (opt, onError) {
/*
* this function will test onErrorThrow's err handling-behavior
*/
local.tryCatchOnError(function () {
local.onErrorThrow(local.errDefault);
}, function (err) {
// validate err occurred
local.assertThrow(err, err);
onError(null, opt);
});
};
...
onErrorWithStack = function (onError) {
/*
* this function will create wrapper around <onError>
* that will append current-stack to err.stack
*/
var onError2;
var stack;
stack = new Error().stack.replace((
/(.*?)\n.*?$/m
), "$1");
onError2 = function (err, data, meta) {
if (
err
&& typeof err.stack === "string"
&& err !== local.errDefault
&& String(err.stack).indexOf(stack.split("\n")[2]) < 0
) {
// append current-stack to err.stack
err.stack += "\n" + stack;
}
onError(err, data, meta);
};
// debug onError
onError2.toString = function () {
return String(onError);
};
return onError2;
}
...
local.onParallel = function (onError, onEach, onRetry) {
/*
* this function will create a function that will
* 1. run async tasks in parallel
* 2. if counter === 0 or err occurred, then call onError(err)
*/
var onParallel;
onError = local.onErrorWithStack(onError);
onEach = onEach || local.nop;
onRetry = onRetry || local.nop;
onParallel = function (err, data) {
if (onRetry(err, data)) {
return;
}
// decrement counter
...
onFileModifiedRestart = function (file) {
/*
* this function will watch the file, and if modified, then restart the process
*/
if (
local.env.npm_config_mode_auto_restart
&& local.fs.existsSync(file)
&& local.fs.statSync(file).isFile()
) {
local.fs.watchFile(file, {
interval: 1000,
persistent: false
}, function (stat2, stat1) {
if (stat2.mtime > stat1.mtime) {
console.error("file modified - " + file);
setTimeout(function () {
local.exit(77);
}, 1000);
}
});
}
}
...
[
__dirname + "/lib.jslint.js",
__filename,
"undefined"
].forEach(function (file) {
local.fs.exists(file, function (exists) {
if (exists) {
local.onFileModifiedRestart(file);
}
});
});
local.fs.readdirSync(process.cwd()).forEach(function (file) {
file = process.cwd() + "/" + file;
// if the file is modified, then restart the process
local.onFileModifiedRestart(file);
...
onNext = function (opt, onError) {
/*
* this function will wrap onError inside recursive-function <opt>.onNext,
* and append the current-stack to any err
*/
opt.onNext = local.onErrorWithStack(function (err, data, meta) {
try {
opt.modeNext += (
(err && !opt.modeErrorIgnore)
? 1000
: 1
);
if (opt.modeDebug) {
console.error("onNext - " + JSON.stringify({
modeNext: opt.modeNext,
errorMessage: err && err.message
}));
if (err && err.stack) {
console.error(err.stack);
}
}
onError(err, data, meta);
} catch (errCaught) {
// throw errCaught to break infinite recursion-loop
if (opt.errCaught) {
local.assertThrow(null, opt.errCaught);
}
opt.errCaught = errCaught;
opt.onNext(errCaught, data, meta);
}
});
return opt;
}
...
onError(err, data, meta);
} catch (errCaught) {
// throw errCaught to break infinite recursion-loop
if (opt.errCaught) {
local.assertThrow(null, opt.errCaught);
}
opt.errCaught = errCaught;
opt.onNext(errCaught, data, meta);
}
});
return opt;
};
local.onParallel = function (onError, onEach, onRetry) {
/*
...
onParallel = function (onError, onEach, onRetry) {
/*
* this function will create a function that will
* 1. run async tasks in parallel
* 2. if counter === 0 or err occurred, then call onError(err)
*/
var onParallel;
onError = local.onErrorWithStack(onError);
onEach = onEach || local.nop;
onRetry = onRetry || local.nop;
onParallel = function (err, data) {
if (onRetry(err, data)) {
return;
}
// decrement counter
onParallel.counter -= 1;
// validate counter
if (!(onParallel.counter >= 0 || err || onParallel.err)) {
err = new Error(
"invalid onParallel.counter = " + onParallel.counter
);
// ensure onError is run only once
} else if (onParallel.counter < 0) {
return;
}
// handle err
if (err) {
onParallel.err = err;
// ensure counter <= 0
onParallel.counter = -Math.abs(onParallel.counter);
}
// call onError when isDone
if (onParallel.counter <= 0) {
onError(err, data);
return;
}
onEach();
};
// init counter
onParallel.counter = 0;
// return callback
return onParallel;
}
...
};
local.dbCrudRemoveAll = function (onError) {
/*
* this function will remove all dbRow's from the db
*/
var onParallel;
onParallel = local.onParallel(function (err) {
local.setTimeoutOnError(onError, 0, err);
});
onParallel.counter += 1;
Object.keys(local.dbTableDict).forEach(function (key) {
onParallel.counter += 1;
local.dbTableDict[key].crudRemoveAll(onParallel);
});
...
onParallelList = function (opt, onEach, onError) {
/*
* this function will
* 1. async-run onEach in parallel,
* with given <opt>.rateLimit and <opt>.retryLimit
* 2. call <onError> when onParallel.ii + 1 === <opt>.list.length
*/
var isListEnd;
var onEach2;
var onParallel;
opt.list = opt.list || [];
onEach2 = function () {
while (true) {
if (!(onParallel.ii + 1 < opt.list.length)) {
isListEnd = true;
return;
}
if (!(onParallel.counter < opt.rateLimit + 1)) {
return;
}
onParallel.ii += 1;
onEach({
elem: opt.list[onParallel.ii],
ii: onParallel.ii,
list: opt.list,
retry: 0
}, onParallel);
}
};
onParallel = local.onParallel(onError, onEach2, function (err, data) {
if (err && data && data.retry < opt.retryLimit) {
local.onErrorDefault(err);
data.retry += 1;
setTimeout(function () {
onParallel.counter -= 1;
onEach(data, onParallel);
}, 1000);
return true;
}
// restart if opt.list has grown
if (isListEnd && (onParallel.ii + 1 < opt.list.length)) {
isListEnd = null;
onEach2();
}
});
onParallel.ii = -1;
opt.rateLimit = Number(opt.rateLimit) || 6;
opt.rateLimit = Math.max(opt.rateLimit, 1);
opt.retryLimit = Number(opt.retryLimit) || 2;
onParallel.counter += 1;
onEach2();
onParallel();
}
...
method: "DELETE",
sha: data.sha,
url: opt.url
}, opt.onNext);
return;
}
// delete tree
local.onParallelList({
list: data
}, function (option2, onParallel) {
onParallel.counter += 1;
// recurse
local.githubCrudContentDelete({
httpReq: opt.httpReq,
message: opt.message,
...
onTimeout = function (onError, timeout, message) {
/*
* this function will create a timeout-err-handler,
* that appends current-stack to any err encountered
*/
onError = local.onErrorWithStack(onError);
// create timerTimeout
return setTimeout(function () {
onError(new Error(
"onTimeout - errTimeout - " + timeout + " ms - " + message
));
// coerce to finite integer
}, timeout);
}
...
+ ".json"
),
modeBrowserTest: "test",
timeExit: Date.now() + opt.timeoutDefault,
timeoutScreenshot: opt.timeoutScreenshot || 15000
}, 1);
// init timerTimeout
timerTimeout = local.onTimeout(
opt.onNext,
opt.timeoutDefault,
opt.testName
).unref();
data = {};
Object.keys(opt).forEach(function (key) {
if (typeof opt[key] !== "object") {
...
profile = function (fnc, onError) {
/*
* this function will profile async <fnc> in milliseconds
* with callback <onError>
*/
var timeStart;
timeStart = Date.now();
// run async fnc
fnc(function (err) {
// call onError with difference in milliseconds
// between Date.now() and timeStart
onError(err, Date.now() - timeStart);
});
}
...
});
// validate timeElapsed
local.assertThrow(
0 <= opt.timeElapsed && opt.timeElapsed < 1000,
opt.timeElapsed
);
// test profile's async handling-behavior
local.profile(function (onError) {
setTimeout(onError);
}, function (err, timeElapsed) {
// validate no err occurred
local.assertThrow(!err, err);
opt.timeElapsed = timeElapsed;
// validate timeElapsed
local.assertThrow((
...
profileSync = function (fnc) {
/*
* this function will profile sync <fnc> in milliseconds
*/
var timeStart;
timeStart = Date.now();
// run sync fnc
fnc();
// return difference in milliseconds between Date.now() and timeStart
return Date.now() - timeStart;
}
...
local.testCase_profileXxx_default = function (opt, onError) {
/*
* this function will test profileXxx's default handling-behavior
*/
opt = {};
// test profileSync's handling-behavior
opt.timeElapsed = local.profileSync(function () {
return;
});
// validate timeElapsed
local.assertThrow(
0 <= opt.timeElapsed && opt.timeElapsed < 1000,
opt.timeElapsed
);
...
replStart = function () {
/*
* this function will start the repl-debugger
*/
var that;
if (globalThis.utility2_repl1) {
return;
}
// start repl
that = require("repl").start({
useGlobal: true
});
globalThis.utility2_repl1 = that;
that.onError = function (err) {
/*
* this function will debug repl-err
*/
globalThis.utility2_debugReplError = err;
console.error(err);
};
// save eval-function
that.evalDefault = that.eval;
// hook custom-eval-function
that.eval = function (script, context, file, onError) {
var onError2;
onError2 = function (err, data) {
// debug err
globalThis.utility2_debugReplError = (
err || globalThis.utility2_debugReplError
);
onError(err, data);
};
script.replace((
/^(\S+)\u0020(.*?)\n/
), function (ignore, match1, match2) {
switch (match1) {
// syntax-sugar - run async shell-command
case "$":
switch (match2) {
// syntax-sugar - run git diff
case "git diff":
match2 = "git diff --color | cat";
break;
// syntax-sugar - run git log
case "git log":
match2 = "git log -n 4 | cat";
break;
// syntax-sugar - run git log
case "ll":
match2 = "ls -Fal";
break;
}
// source lib.utility2.sh
if (
process.platform !== "win32"
&& process.env.npm_config_dir_utility2 && (match2 !== ":")
) {
match2 = (
". " + process.env.npm_config_dir_utility2
+ "/lib.utility2.sh;" + match2
);
}
// run async shell-command
require("child_process").spawn(match2, {
shell: true,
stdio: [
"ignore", 1, 2
]
// on shell exit, print return prompt
}).on("exit", function (exitCode) {
console.error("exit-code " + exitCode);
that.evalDefault(
"\n",
context,
file,
onError2
);
});
script = "\n";
break;
// syntax-sugar - map text with charCodeAt
case "charCode":
console.error(
match2.split("").map(function (chr) {
return (
"\\u"
+ chr.charCodeAt(0).toString(16).padStart(4, 0)
);
}).join("")
);
script = "\n";
break;
// syntax-sugar - sort chr
case "charSort":
console.error(JSON.stringify(match2.split("").sort().join("")));
script = "\n";
break;
// syntax-sugar - grep current dir
case "grep":
// run async shell-command
require("child_process").spawn((
"find . -type f | grep -v -E "
/* jslint ignore:start */
+ '"\
/\\.|(\\b|_)(\\.\\d|\
archive|artifact|\
bower_component|build|\
coverage|\
doc|\
external|\
fixture|\
git_module|\
jquery|\
log|\
min|misc|mock|\
node_module|\
raw|\rollup|\
swp|\
tmp|\
v...
...
local.cliDict["utility2.start"] = function () {
/*
* <port>
* will start utility2 http-server on given <port> (default 8081)
*/
local.env.PORT = process.argv[3] || local.env.PORT;
globalThis.local = local;
local.replStart();
local.testRunServer({});
};
local.cliDict["utility2.swaggerValidateFile"] = function () {
/*
* <file/url>
* will swagger-validate file/url
...
requireInSandbox = function (file) {
/*
* this function will require the file in a sandbox-lite env
*/
var exports;
var mockDict;
var mockList;
var tmp;
mockList = [
[
globalThis, {
setImmediate: local.nop,
setInterval: local.nop,
setTimeout: local.nop
}
]
];
[
[
local, "child_process"
], [
local, "cluster"
], [
local, "http"
], [
local, "https"
], [
local, "net"
], [
local, "repl"
], [
local.events, "prototype"
], [
globalThis, "process"
], [
local.stream, "prototype"
], [
process, "stdin"
]
].forEach(function (elem) {
tmp = elem[0][elem[1]];
mockDict = {};
Object.keys(tmp).forEach(function (key) {
if (
typeof tmp[key] === "function"
&& !(
/^(?:fs\.Read|fs\.read|process\.binding|process\.dlopen)/
)
.test(elem[1] + "." + key)
) {
mockDict[key] = function () {
return;
};
// coverage-hack
mockDict[key]();
}
});
mockList.push([
tmp, mockDict
]);
});
local.testMock(mockList, function (onError) {
local.tryCatchOnError(function () {
exports = require(file);
}, local.onErrorDefault);
onError();
}, local.onErrorThrow);
return exports;
}
n/a
requireReadme = function () {
/*
* this function will require and export example.js embedded in README.md
*/
var code;
var module;
var tmp;
// init module.exports
module = {};
if (local.isBrowser) {
module.exports = local.objectSetDefault(
globalThis.utility2_rollup || globalThis.local,
local
);
return module.exports;
}
// start repl-debugger
local.replStart();
// debug dir
[
__dirname + "/lib.jslint.js",
__filename,
"undefined"
].forEach(function (file) {
local.fs.exists(file, function (exists) {
if (exists) {
local.onFileModifiedRestart(file);
}
});
});
local.fs.readdirSync(process.cwd()).forEach(function (file) {
file = process.cwd() + "/" + file;
// if the file is modified, then restart the process
local.onFileModifiedRestart(file);
switch (local.path.basename(file)) {
// swagger-validate assets.swgg.swagger.json
case "assets.swgg.swagger.json":
local.fs.readFile(file, "utf8", function (err, data) {
local.tryCatchOnError(function () {
// validate no err occurred
local.assertThrow(!err, err);
local.swgg.swaggerValidate(JSON.parse(data));
}, local.onErrorDefault);
});
break;
}
});
// jslint process.cwd()
if (!local.env.npm_config_mode_library) {
local.child_process.spawn("node", [
"-e", (
"require("
+ JSON.stringify(__filename)
+ ").jslint.jslintAndPrintDir("
+ JSON.stringify(process.cwd())
+ ", {autofix:true,conditional:true}, process.exit);"
)
], {
env: local.objectAssignDefault({
npm_config_mode_library: "1"
}, local.env),
stdio: [
"ignore", "ignore", 2
]
});
}
if (globalThis.utility2_rollup || local.env.npm_config_mode_start) {
// init assets
local.assetsDict["/index.html"] = (
local.fsReadFileOrEmptyStringSync("index.html")
|| local.assetsDict["/index.rollup.html"] || ""
);
local.assetsDict["/"] = local.assetsDict["/index.html"];
local.assetsDict["/assets.app.js"] = local.fs.readFileSync(
__filename,
"utf8"
).replace((
/^#!\//
), "// ");
// init exports
local[local.env.npm_package_nameLib] = local;
module.exports = local;
return module.exports;
}
// init file $npm_package_main
globalThis.utility2_moduleExports = require(
process.cwd() + "/" + local.env.npm_package_main
);
globalThis.utility2_moduleExports.globalThis = globalThis;
// read code from README.md
code = local.templateRenderMyApp(
local.assetsDict["/assets.example.template.js"],
{}
);
local.tryCatchOnError(function () {
tmp = (
/```\w*?(\n[\W\s]*?example\.js[\n"][\S\s]*?)\n```/
).exec(
local.fs.readFileSync("README.md", "utf8")
);
code = tmp.input.slice(0, tmp.index).replace((
/.+/g
), "") + tmp[1];
}, local.nop);
code = code
// alias require($npm_package_name) to utility2_moduleExports;
.replace(
new RegExp("require\\(." + local.env.npm_package_name + ".\\)"),
"globalThis.utility2_moduleExports"
)
.replace(
new RegExp("require\\(." + local.env.npm_package_nameOriginal + ".\\)")...
...
\n\
\n\
// run shared js\-env code - init-before\n\
(function () {\n\
// init local\n\
local = (\n\
globalThis.utility2 || require("utility2")\n\
).requireReadme();\n\
globalThis.local = local;\n\
// init test\n\
local.testRunDefault(local);\n\
}());\n\
\n\
\n\
\n\
...
semverCompare = function (aa, bb) {
/*
* this function will compare semver versions aa ? bb and return
* -1 if aa < bb
* 0 if aa = bb
* 1 if aa > bb
* https://semver.org/#spec-item-11
*/
return [
aa, bb
].map(function (aa) {
aa = aa.split("-");
return [
aa[0], aa.slice(1).join("-") || "\u00ff"
].map(function (aa) {
return aa.split(".").map(function (aa) {
return ("0000000000000000" + aa).slice(-16);
}).join(".");
}).join("-");
}).reduce(function (aa, bb) {
return (
aa === bb
? 0
: aa < bb
? -1
: 1
);
});
}
...
), "."));
bb = (process.argv[2] || "0.0.0").replace((
/^(\d+?\.\d+?\.)(\d+)(\.*?)$/
), function (ignore, match1, match2, match3) {
return match1 + (Number(match2) + 1) + match3;
});
packageJson.version = (
local.semverCompare(aa, bb) === 1
? aa
: bb
);
console.error([
aa, bb, packageJson.version
]);
// update package.json
...
serverLocalReqHandler = function (req, res) { var that; that = {}; local.onNext(that, function (err) { if (err || that.modeNext >= local.middlewareList.length) { local.middlewareError(err, req, res); return; } // recurse with next middleware in middlewareList local.middlewareList[that.modeNext](req, res, that.onNext); }); that.modeNext = -1; that.onNext(); }
...
if (isDone) {
return;
}
isDone = true;
xhr.serverReq.data = data;
// asynchronously send req from client -> server
setTimeout(function () {
local.serverLocalReqHandler(
xhr.serverReq,
xhr.serverResponse
);
});
};
xhr.on = function () {
return xhr;
...
serverLocalUrlTest = function (url) {
/*
* this function will test if the url is local
*/
url = local.urlParse(url).pathname;
return local.isBrowser && !local.env.npm_config_mode_backend && (
/^\/test\./
).test(url);
}
...
if (local2.onErrorWithStack) {
onError = local2.onErrorWithStack(onError);
}
// init xhr - XMLHttpRequest
xhr = (
local.isBrowser
&& !opt.httpReq
&& !(local2.serverLocalUrlTest && local2.serverLocalUrlTest(opt.url
))
&& new XMLHttpRequest()
);
// init xhr - http.request
if (!xhr) {
xhr = local.identity(local2.urlParse || require("url").parse)(opt.url);
// init xhr
xhrInit();
...
serverRespondCors = function (req, res) {
/*
* this function will enable cors for the req
* http://en.wikipedia.org/wiki/Cross-origin_resource_sharing
*/
local.serverRespondHeadSet(req, res, null, local.jsonCopy({
"access-control-allow-headers":
req.headers["access-control-request-headers"],
"access-control-allow-methods":
req.headers["access-control-request-method"],
"access-control-allow-origin": "*"
}));
}
...
var opt;
var timerTimeout;
// handle preflight-cors
if (req.method === "OPTIONS" && (
/forward-proxy-url/
)
.test(req.headers["access-control-request-headers"])) {
local.serverRespondCors(req, res);
res.end();
return;
}
if (!req.headers["forward-proxy-url"]) {
next();
return;
}
...
serverRespondDefault = function (req, res, statusCode, err) {
/*
* this function will respond with a default message,
* or <err>.stack for given statusCode
*/
// init statusCode and contentType
local.serverRespondHeadSet(
req,
res,
statusCode,
{
"Content-Type": "text/plain; charset=utf-8"
}
);
if (err) {
// debug statusCode / method / url
local.errorMessagePrepend(
err,
res.statusCode + " " + req.method + " " + req.url
+ "\n"
);
// print err.stack to stderr
local.onErrorDefault(err);
// end res with err.stack
res.end(err.stack);
return;
}
// end res with default statusCode message
res.end(
statusCode + " " + local.http.STATUS_CODES[statusCode]
);
}
...
opt.onNext(null, data, meta);
}
break;
case 3:
switch (crud.crudType[0]) {
case "fileGetOneById":
if (!data) {
local.serverRespondDefault(req, res, 404);
return;
}
local.serverRespondHeadSet(req, res, null, {
"Content-Type": data.fileContentType
});
res.end(local.base64ToBuffer(data.fileBlob));
break;
...
serverRespondEcho = function (req, res) {
/*
* this function will respond with debug info
*/
res.write(
req.method + " " + req.url
+ " HTTP/" + req.httpVersion + "\r\n"
+ Object.keys(req.headers).map(function (key) {
return key + ": " + req.headers[key] + "\r\n";
}).join("") + "\r\n"
);
req.pipe(res);
}
...
break;
// test http POST handling-behavior
case "/test.echo":
// test res-header handling-behavior
local.serverRespondHeadSet(req, res, null, {
"X-Res-Header-Test": "bb"
});
local.serverRespondEcho(req, res);
break;
// test 500-internal-server-error handling-behavior
case "/test.err-500":
// test multiple-callback serverRespondHeadSet handling-behavior
local.serverRespondHeadSet(req, res, null, {});
next(local.errDefault);
// test multiple-callback-error handling-behavior
...
serverRespondHeadSet = function (ignore, res, statusCode, headers) {
/*
* this function will set the <res> object's <statusCode> and <headers>
*/
if (res.headersSent) {
return;
}
// init res.statusCode
if (Number(statusCode)) {
res.statusCode = Number(statusCode);
}
Object.keys(headers).forEach(function (key) {
if (headers[key]) {
res.setHeader(key, headers[key]);
}
});
return true;
}
...
});
local.dbTableFile.crudSetManyById(crud.body, opt.onNext);
break;
case "userLoginByPassword":
case "userLogout":
// respond with 401 Unauthorized
if (!user.isAuthenticated) {
local.serverRespondHeadSet(req, res, 401, {});
req.swgg.crud.endArgList = [
req, res
];
opt.modeNext = Infinity;
opt.onNext();
return;
}
...
serverRespondTimeoutDefault = function (req, res, timeout) {
/*
* this function will create a timeout-err-handler for server-<req>
*/
var isDone;
var onError;
onError = function () {
if (isDone) {
return;
}
isDone = true;
// debug serverResponse
console.error("serverLog - " + JSON.stringify({
time: new Date(req.timeStart).toISOString(),
type: "serverResponse",
method: req.method,
url: req.url,
statusCode: res.statusCode | 0,
timeElapsed: Date.now() - req.timeStart,
// extra
requestContentLength: req.dataLength || 0,
resContentLength: res.contentLength,
requestHeaderXForwardedFor:
req.headers["x-forwarded-for"] || "",
requestHeaderOrigin: req.headers.origin || "",
requestHeaderReferer: req.headers.referer || "",
requestHeaderUserAgent: req.headers["user-agent"]
}));
// cleanup timerTimeout
clearTimeout(req.timerTimeout);
};
req.timeStart = Date.now();
req.onTimeout = req.onTimeout || function (err) {
local.serverRespondDefault(req, res, 500, err);
setTimeout(function () {
// cleanup <req> and <res>
local.streamCleanup(req);
local.streamCleanup(res);
}, 1000);
};
// init timerTimeout
req.timerTimeout = local.onTimeout(
req.onTimeout,
timeout || local.timeoutDefault,
"server " + req.method + " " + req.url
);
res.contentLength = 0;
res.writeContentLength = res.writeContentLength || res.write;
res.write = function (chunk, encoding, callback) {
chunk = local.normalizeChunk(chunk);
res.contentLength += chunk.length;
res.writeContentLength(chunk, encoding, callback);
};
res.on("error", onError);
res.on("finish", onError);
}
...
local._debugServerReqRes3 = local._debugServerReqRes2;
local._debugServerReqRes2 = local._debugServerReqRes1;
local._debugServerReqRes1 = {
req,
res
};
// init timerTimeout
local.serverRespondTimeoutDefault(req, res, local.timeoutDefault);
// init req.urlParsed
req.urlParsed = local.urlParse(req.url);
// init res-header content-type
local.serverRespondHeadSet(req, res, null, {
"Content-Type": local.contentTypeDict[(
/\.[^.]*?$|$/m
).exec(req.urlParsed.pathname)[0]]
...
setTimeoutOnError = function (onError, timeout, err, data) {
/*
* this function will after timeout has passed,
* then call <onError>(<err>, <data>)
*/
if (typeof onError === "function") {
setTimeout(function () {
onError(err, data);
}, timeout);
}
return data;
}
...
};
local._DbTable.prototype.crudCountAll = function (onError) {
/*
* this function will count all of dbRow's in dbTable
*/
this._cleanup();
return local.setTimeoutOnError(onError, 0, null, this.dbRowList.length);
};
local._DbTable.prototype.crudCountManyByQuery = function (query, onError) {
/*
* this function will count the number of dbRow's in dbTable with given query
*/
this._cleanup();
...
function(a){this.c=[new sjcl.hash.sha256];this.m=[0];this.P=0;this.H={};this.N=0;this.U={};this.Z=this.f=this.o=this.ha=0;this.b =[0,0,0,0,0,0,0,0];this.h=[0,0,0,0];this.L=void 0;this.M=a;this.D=!1;this.K={progress:{},seeded:{}};this.u=this.ga=0;this.I=1;this .J=2;this.ca=0x10000;this.T=[0,48,64,96,128,192,0x100,384,512,768,1024];this.da=3E4;this.ba=80}
n/a
sjclHashScryptCreate = function (password, opt) {
/*
* this function will create a scrypt-hash of the password
* with given <opt> (default = $s0$10801)
* e.g.
* $s0$e0801$epIxT/h6HbbwHaehFnh/bw==$7H0vs
* XlY8UxxyW/BWx/9GuY7jEvGjT71GFd6O4SZND0=
* https://github.com/wg/scrypt
*/
// init opt
opt = (opt || "$s0$10801").split("$");
// init salt
if (!opt[3]) {
opt[3] = local.sjcl.codec.base64.fromBits(
local.sjcl.random.randomWords(4, 0)
);
}
// init hash
opt[4] = local.sjcl.codec.base64.fromBits(
local.sjcl.misc.scrypt(
password || "",
local.sjcl.codec.base64.toBits(opt[3]),
Math.pow(2, parseInt(opt[2].slice(0, 1), 16)),
parseInt(opt[2].slice(1, 2), 16),
parseInt(opt[2].slice(3, 4), 16)
)
);
return opt.slice(0, 5).join("$");
}
...
};
local.sjclHashScryptValidate = function (password, hash) {
/*
* this function will validate the password against the scrypt-hash
* https://github.com/wg/scrypt
*/
return local.sjclHashScryptCreate(password, hash) === hash;
};
local.sjclHashSha1Create = function (data) {
/*
* this function will create a base64-encoded sha1 hash of the string data
*/
return local.sjcl.codec.base64.fromBits(local.sjcl.hash.sha1.hash(data));
...
sjclHashScryptValidate = function (password, hash) {
/*
* this function will validate the password against the scrypt-hash
* https://github.com/wg/scrypt
*/
return local.sjclHashScryptCreate(password, hash) === hash;
}
...
opt.modeNext = Infinity;
opt.onNext();
break;
case 2:
switch (crud.crudType[0]) {
case "userLoginByPassword":
user.data = data;
if (!local.sjclHashScryptValidate(
user.password,
user.data && user.data.password
)) {
opt.modeNext = Infinity;
opt.onNext();
return;
}
...
sjclHashSha1Create = function (data) {
/*
* this function will create a base64-encoded sha1 hash of the string data
*/
return local.sjcl.codec.base64.fromBits(local.sjcl.hash.sha1.hash(data));
}
...
};
local.testCase_sjclHashShaXxxCreate_default = function (opt, onError) {
/*
* this function will test sjclHashShaXxxCreate's default handling-behavior
*/
local.assertJsonEqual(
local.sjclHashSha1Create("aa"),
"4MkDWJjdUvxlxBRUzsnE0mEb+zc="
);
local.assertJsonEqual(
local.sjclHashSha256Create("aa"),
"lhtt0+3jy47LqsvWjeBAzXjrLtWIkTDM60xJJo6k1QY="
);
onError(null, opt);
...
sjclHashSha256Create = function (data) {
/*
* this function will create a base64-encoded sha256 hash of the string data
*/
return local.sjcl.codec.base64.fromBits(local.sjcl.hash.sha256.hash(data));
}
...
* this function will test sjclHashShaXxxCreate's default handling-behavior
*/
local.assertJsonEqual(
local.sjclHashSha1Create("aa"),
"4MkDWJjdUvxlxBRUzsnE0mEb+zc="
);
local.assertJsonEqual(
local.sjclHashSha256Create("aa"),
"lhtt0+3jy47LqsvWjeBAzXjrLtWIkTDM60xJJo6k1QY="
);
onError(null, opt);
};
local.testCase_sjclHmacShaXxx_default = function (opt, onError) {
/*
...
sjclHmacSha1Create = function (key, data) {
/*
* this function will create a base64-encoded sha1 hmac
* from the string key and string data
*/
var Hmac;
Hmac = local.sjcl.misc.hmac;
return local.sjcl.codec.base64.fromBits(
(new Hmac(
local.sjcl.codec.utf8String.toBits(key),
local.sjcl.hash.sha1
)).mac(local.sjcl.codec.utf8String.toBits(data))
);
}
...
};
local.testCase_sjclHmacShaXxx_default = function (opt, onError) {
/*
* this function will test sjclHmacShaXxx's default handling-behavior
*/
local.assertJsonEqual(
local.sjclHmacSha1Create("aa", "bb"),
"15pOinCz63A+qZoxnv+mJB6UF1k="
);
local.assertJsonEqual(
local.sjclHmacSha256Create("aa", "bb"),
"94Xv3VdPHA+ohKyjkM1pb0W5ZVAuMVcmIAAI2AqNRCQ="
);
onError(null, opt);
...
sjclHmacSha256Create = function (key, data) {
/*
* this function will create a base64-encoded sha256 hmac
* from the string key and string data
*/
var Hmac;
Hmac = local.sjcl.misc.hmac;
return local.sjcl.codec.base64.fromBits(
(new Hmac(
local.sjcl.codec.utf8String.toBits(key),
local.sjcl.hash.sha256
)).mac(local.sjcl.codec.utf8String.toBits(data))
);
}
...
* this function will test sjclHmacShaXxx's default handling-behavior
*/
local.assertJsonEqual(
local.sjclHmacSha1Create("aa", "bb"),
"15pOinCz63A+qZoxnv+mJB6UF1k="
);
local.assertJsonEqual(
local.sjclHmacSha256Create("aa", "bb"),
"94Xv3VdPHA+ohKyjkM1pb0W5ZVAuMVcmIAAI2AqNRCQ="
);
onError(null, opt);
};
local.testCase_stringHtmlSafe_default = function (opt, onError) {
/*
...
stateInit = function (opt) {
/*
* this function will init state <opt>
*/
local.objectSetOverride(local, opt, 10);
// init swgg
local.swgg.apiUpdate(local.swgg.swaggerJson);
}
...
local.fsReadFileOrEmptyStringSync("assets.swgg.swagger.json")
|| local.assetsDict["/assets.swgg.swagger.json"]
|| local.assetsDict["/assets.swgg.swagger.petstore.json"]
);
// coverage-hack - re-run test-server
local.testRunServer(local);
// coverage-hack - stateInit
local.stateInit({});
// init test-middleware
local.middlewareList.push(function (req, res, next) {
/*
* this function will run the test-middleware
*/
switch (req.urlParsed.pathname) {
// test http POST handling-behavior
...
function Stream() { EE.call(this); }
n/a
streamCleanup = function (stream) {
/*
* this function will try to end or destroy the stream
*/
var err;
// try to end the stream
try {
stream.end();
} catch (errCaught) {
err = errCaught;
}
// if err, then try to destroy the stream
if (err) {
try {
stream.destroy();
} catch (ignore) {}
}
}
...
// extra
headers: opt.headers
}));
if (!err) {
return;
}
// cleanup clientReq and clientRes
local.streamCleanup(opt.clientReq);
local.streamCleanup(opt.clientResponse);
next(err);
};
// init opt
opt = local.urlParse(req.headers["forward-proxy-url"]);
opt.method = req.method;
opt.url = req.headers["forward-proxy-url"];
...
streamReadAll = function (stream, onError) {
/*
* this function will concat data from <stream>
* and pass to <onError> when finished reading
*/
var chunkList;
chunkList = [];
stream.dataLength = 0;
// on event-data, push buffer-chunk to chunkList
stream.on("data", function (chunk) {
chunk = local.normalizeChunk(chunk);
chunkList.push(chunk);
stream.dataLength += chunk.length;
// on event-end, pass concatenated-buffer to onError
}).on("end", function () {
onError(
null,
local.isBrowser
? chunkList[0]
: local.bufferConcat(chunkList)
);
// on event-error, pass error to onError
}).on("error", onError);
}
...
* read and save the <req>-body to <req>.bodyRaw
*/
// if req is already read, then goto next
if (!req.readable) {
next();
return;
}
local.streamReadAll(req, function (err, data) {
req.bodyRaw = req.bodyRaw || data;
next(err);
});
};
local.middlewareCacheControlLastModified = function (req, res, next) {
/*
...
stringHtmlSafe = function (text) {
/*
* this function will make the text html-safe
* https://stackoverflow.com/questions/7381974/which-characters-need-to-be-escaped-on-html
*/
return text
.replace((
/&/g
), "&")
.replace((
/"/g
), """)
.replace((
/'/g
), "'")
.replace((
/</g
), "<")
.replace((
/>/g
), ">")
.replace((
/&(amp;|apos;|gt;|lt;|quot;)/ig
), "&$1");
}
...
)
// handle case where module is a function
.replace(">.<", "><");
if (elem.typeof !== "function") {
return elem;
}
// init source
elem.source = local.stringHtmlSafe(
trimLeft(toString(module[key])) || "n/a"
).replace((
/\([\S\s]*?\)/
), function (match0) {
// init signature
elem.signature = match0.replace((
/\u0020*?\/\*[\S\s]*?\*\/\u0020*/g
...
stringMerge = function (str1, str2, rgx) {
/*
* this function will merge <str2> into <str1>,
* for sections where both match <rgx>
*/
str2.replace(rgx, function (match2) {
str1.replace(rgx, function (match1) {
str1 = str1.replace(match1, function () {
return match2;
});
});
});
return str1;
}
...
/\n\u0020\*\n(?:[\S\s]*?\n)?\u0020\*\/\n/
),
// customize body after /* validateLineSortedReset */
(
/\n\/\*\u0020validateLineSortedReset\u0020\*\/\n[\S\s]*?$/
)
].forEach(function (rgx) {
opt.dataTo = local.stringMerge(opt.dataTo, opt.dataFrom, rgx);
});
// customize local for assets.utility2.rollup.js
if (
local.fs.existsSync("./assets.utility2.rollup.js")
&& local.env.npm_package_nameLib !== "swgg"
) {
opt.dataTo = opt.dataTo.replace(
...
stringQuotedToAscii = function (str) {
/*
* this function will replace non-ascii-chr to unicode-escaped-ascii-chr
* in quoted-<str>
*/
return str
.replace((
/\r/g
), "\\r")
.replace((
/\t/g
), "\\t")
.replace((
/[^\n\u0020-\u007e]/g
), function (chr) {
return "\\u" + ("0000" + chr.charCodeAt(0).toString(16)).slice(-4);
});
}
...
};
local.testCase_stringQuotedToAscii_default = function (opt, onError) {
/*
* this function will test stringQuotedToAscii's default handling-behavior
*/
local.assertJsonEqual(
local.stringQuotedToAscii(local.stringHelloEmoji),
"hello \\ud83d\\ude01\n"
);
onError(null, opt);
};
local.testCase_stringRegexpEscape_default = function (opt, onError) {
/*
...
stringRegexpEscape = function (text) {
/*
* this function will regexp-escape text
* https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
*/
return text.replace((
/[\-\/\\\^$*+?.()|\[\]{}]/g
), "\\$&");
}
...
};
local.testCase_stringRegexpEscape_default = function (opt, onError) {
/*
* this function will test stringRegexpEscape's default handling-behavior
*/
local.assertJsonEqual(
local.stringRegexpEscape(local.stringCharsetAscii),
(
"\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007"
+ "\b\t\n\u000b\f\r\u000e\u000f"
+ "\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017"
+ "\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f"
+ " !\"#\\$%&'\\(\\)\\*\\+,\\-\\.\\/0123456789:;<=>\\?@"
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ\\[\\\\\\]\\^_`"
...
stringTruncate = function (text, maxLength) {
/*
* this function will truncate text to given maxLength
*/
return (
text.length > maxLength
? text.slice(0, maxLength - 3).trimRight() + "..."
: text
);
}
...
].forEach(function (ii) {
opt["prefix" + ii] = opt.prefix[ii] + opt.prefix.slice(
ii + 1
).map(function (element) {
return "[" + JSON.stringify(element) + "]";
}).join("");
});
opt.prefix0 += " = " + local.stringTruncate(
JSON.stringify(opt.data) || "undefined",
100
);
opt.schema2 = local.stringTruncate(
JSON.stringify(opt.schema) || "undefined",
500
);
...
stringUniqueKey = function (text) {
/*
* this function will return a string-key that is unique in given text
*/
var key;
// seed the key with the least frequent letters in the english-language
// https://en.wikipedia.org/wiki/Letter_frequency
key = "zqxj";
do {
key += ((1 + Math.random()) * 0x10000000000000).toString(36).slice(1);
} while (text.indexOf(key) >= 0);
return key;
}
...
var arg;
var argList;
var doubleBackslash;
var opt;
var quote;
arg = "";
argList = [];
doubleBackslash = local.stringUniqueKey(text);
// parse doubleBackslash
text = text.replace((
/\\\\/g
), doubleBackslash);
// parse line-continuation
text = text.replace((
/\\\n/g
...
taskCreate = function (opt, onTask, onError) {
/*
* this function will create the task onTask named <opt>.key,
* if it does not exist, and push onError to its onErrorList
*/
var task;
// init task
local.taskOnTaskDict[opt.key] = (
local.taskOnTaskDict[opt.key]
|| {
onErrorList: []
}
);
task = local.taskOnTaskDict[opt.key];
// push callback onError to the task
if (onError) {
onError = local.onErrorWithStack(onError);
task.onErrorList.push(onError);
}
// if task exists, then return it
if (!onTask || task.onTask) {
return task;
}
task.onDone = function (err, data, meta) {
// if isDone, then do nothing
if (task.isDone) {
return;
}
task.isDone = true;
// cleanup timerTimeout
clearTimeout(task.timerTimeout);
// cleanup task
delete local.taskOnTaskDict[opt.key];
// preserve err.message and err.stack
task.result = JSON.stringify([
(
(err && err.stack)
? Object.assign(local.jsonCopy(err), {
message: err.message,
name: err.name,
stack: err.stack
})
: err
), data, meta
]);
// pass result to callbacks in onErrorList
task.onErrorList.forEach(function (onError) {
onError.apply(null, JSON.parse(task.result));
});
};
// init timerTimeout
task.timerTimeout = local.onTimeout(
task.onDone,
opt.timeout || local.timeoutDefault,
"taskCreate " + opt.key
);
task.onTask = onTask;
// run onTask
task.onTask(task.onDone);
return task;
}
...
}
}
// run background-task with lower priority for cache-hit
setTimeout(opt.onNext, opt.modeCacheHit && opt.cacheTtl);
break;
// 2. run onTask in background to update cache
case 2:
local.taskCreate(opt, onTask, opt.onNext);
break;
default:
// 3. save onTask's result to cache
// JSON.stringify data to prevent side-effects on cache
opt.cacheValue = JSON.stringify(data);
if (!err && opt.cacheValue) {
local.cacheDict[opt.cacheDict][opt.key] = opt.cacheValue;
...
taskCreateCached = function (opt, onTask, onError) {
/*
* this function will
* 1. if cache-hit, then call onError with cacheValue
* 2. run onTask in background to update cache
* 3. save onTask's result to cache
* 4. if cache-miss, then call onError with onTask's result
*/
local.onNext(opt, function (err, data) {
switch (opt.modeNext) {
// 1. if cache-hit, then call onError with cacheValue
case 1:
// read cacheValue from memory-cache
local.cacheDict[opt.cacheDict] = (
local.cacheDict[opt.cacheDict]
|| {}
);
opt.cacheValue = local.cacheDict[opt.cacheDict][opt.key];
if (opt.cacheValue) {
// call onError with cacheValue
opt.modeCacheHit = true;
onError(null, JSON.parse(opt.cacheValue));
if (!opt.modeCacheUpdate) {
break;
}
}
// run background-task with lower priority for cache-hit
setTimeout(opt.onNext, opt.modeCacheHit && opt.cacheTtl);
break;
// 2. run onTask in background to update cache
case 2:
local.taskCreate(opt, onTask, opt.onNext);
break;
default:
// 3. save onTask's result to cache
// JSON.stringify data to prevent side-effects on cache
opt.cacheValue = JSON.stringify(data);
if (!err && opt.cacheValue) {
local.cacheDict[opt.cacheDict][opt.key] = opt.cacheValue;
}
// 4. if cache-miss, then call onError with onTask's result
if (!opt.modeCacheHit) {
onError(err, opt.cacheValue && JSON.parse(opt.cacheValue));
}
local.functionOrNop(opt.onCacheWrite)();
}
});
opt.modeNext = 0;
opt.onNext();
}
...
).test(req.headers["accept-encoding"])
) {
opt.modeNext += 1;
opt.onNext();
return;
}
// gzip and cache result
local.taskCreateCached({
cacheDict: "middlewareAssetsCachedGzip",
key: req.urlParsed.pathname
}, function (onError) {
local.zlib.gzip(opt.result, function (err, data) {
onError(err, !err && data.toString("base64"));
});
}, opt.onNext);
...
templateRender = function (template, dict, opt) {
/*
* this function will render the template with given dict
*/
var argList;
var getValue;
var match;
var renderPartial;
var rgx;
var skip;
var value;
dict = dict || {};
opt = opt || {};
getValue = function (key) {
argList = key.split(" ");
value = dict;
if (argList[0] === "#this/") {
return;
}
// iteratively lookup nested values in the dict
argList[0].split(".").forEach(function (key) {
value = value && value[key];
});
return value;
};
renderPartial = function (match0, helper, key, partial) {
switch (helper) {
case "each":
case "eachTrimRightComma":
value = getValue(key);
value = (
Array.isArray(value)
? value.map(function (dict) {
// recurse with partial
return local.templateRender(partial, dict, opt);
}).join("")
: ""
);
// remove trailing-comma from last elem
if (helper === "eachTrimRightComma") {
value = value.trimRight().replace((
/,$/
), "");
}
return value;
case "if":
partial = partial.split("{{#unless " + key + "}}");
partial = (
getValue(key)
? partial[0]
// handle 'unless' case
: partial.slice(1).join("{{#unless " + key + "}}")
);
// recurse with partial
return local.templateRender(partial, dict, opt);
case "unless":
return (
getValue(key)
? ""
// recurse with partial
: local.templateRender(partial, dict, opt)
);
default:
// recurse with partial
return match0[0] + local.templateRender(match0.slice(1), dict, opt);
}
};
// render partials
rgx = (
/\{\{#(\w+)\u0020([^}]+?)\}\}/g
);
template = template || "";
match = rgx.exec(template);
while (match) {
rgx.lastIndex += 1 - match[0].length;
template = template.replace(
new RegExp(
"\\{\\{#(" + match[1] + ") (" + match[2]
+ ")\\}\\}([\\S\\s]*?)\\{\\{/" + match[1] + " " + match[2]
+ "\\}\\}"
),
renderPartial
);
match = rgx.exec(template);
}
// search for keys in the template
return template.replace((
/\{\{[^}]+?\}\}/g
), function (match0) {
var markdownToHtml;
var notHtmlSafe;
notHtmlSafe = opt.notHtmlSafe;
try {
getValue(match0.slice(2, -2));
if (value === undefined) {
return match0;
}
argList.slice(1).forEach(function (arg0, ii, list) {
switch (arg0) {
case "alphanumeric":
value = value.replace((
/\W/g
), "_");
break;
case "decodeURIComponent":
value = decodeURIComponent(value);
break;
case "encodeURIComponent":
value = encodeURIComponent(value);
break;
case "jsonStringify":
value = JSON.stringify(value);
break;
case "jsonStringify4":
value = JSON.stringify(value, null, 4);
break;
case "markdownSafe&qu...
...
case "each":
case "eachTrimRightComma":
value = getValue(key);
value = (
Array.isArray(value)
? value.map(function (dict) {
// recurse with partial
return local.templateRender(partial, dict, opt);
}).join("")
: ""
);
// remove trailing-comma from last elem
if (helper === "eachTrimRightComma") {
value = value.trimRight().replace((
/,$/
...
templateRenderMyApp = function (template, opt) {
/*
* this function will render my-app-lite template with given <opt>.packageJson
*/
opt.packageJson = local.fsReadFileOrEmptyStringSync("package.json", "json");
local.objectSetDefault(opt.packageJson, {
nameLib: opt.packageJson.name.replace((
/\W/g
), "_"),
repository: {
url: (
"https://github.com/kaizhu256/node-"
+ opt.packageJson.name
+ ".git"
)
}
}, 2);
opt.githubRepo = opt.packageJson.repository.url.replace((
/\.git$/
), "").split("/").slice(-2);
template = template.replace((
/kaizhu256(\.github\.io\/|%252F|\/)/g
), opt.githubRepo[0] + ("$1"));
template = template.replace((
/node-my-app-lite/g
), opt.githubRepo[1]);
template = template.replace((
/\bh1-my-app\b/g
), (
opt.packageJson.nameHeroku
|| ("h1-" + opt.packageJson.nameLib.replace((
/_/g
), "-"))
));
template = template.replace((
/my-app-lite/g
), opt.packageJson.name);
template = template.replace((
/my_app/g
), opt.packageJson.nameLib);
template = template.replace((
/\{\{packageJson\.(\S+)\}\}/g
), function (ignore, match1) {
return opt.packageJson[match1];
});
return template;
}
...
var result;
local.objectSetDefault(opt, {
customize: local.nop,
dataFrom: local.fsReadFileOrEmptyStringSync(
"lib." + local.env.npm_package_nameLib + ".js",
"utf8"
),
dataTo: local.templateRenderMyApp(
local.assetsDict["/assets.my_app.template.js"],
opt
)
});
// search-and-replace - customize dataTo
[
// customize top-level comment-description
...
testMock = function (mockList, onTestCase, onError) {
/*
* this function will mock the objects in mockList while running the onTestCase
*/
var onError2;
onError2 = function (err) {
// restore mock[0] from mock[2]
mockList.reverse().forEach(function (mock) {
Object.keys(mock[2]).forEach(function (key) {
mock[0][key] = mock[2][key];
});
});
onError(err);
};
// suppress console.error and console.log
if (!(mockList[0] && mockList[0][0] === console)) {
mockList.unshift([
console, {}
]);
}
local.objectSetDefault(mockList[0][1], {
error: local.nop,
log: local.nop
});
// mock-objects
mockList.forEach(function (mock) {
mock[2] = {};
// backup mock[0] into mock[2]
Object.keys(mock[1]).forEach(function (key) {
mock[2][key] = (
// ternary-operator
(
typeof process === "object"
&& process.env === mock[0]
&& mock[0][key] === undefined
)
// handle process.env
? ""
: mock[0][key]
);
});
// override mock[0] with mock[1]
Object.keys(mock[1]).forEach(function (key) {
mock[0][key] = mock[1][key];
});
});
// try to call onError with mock-objects
local.tryCatchOnError(function () {
// run onTestCase
onTestCase(onError2);
}, onError2);
}
...
mockDict[key]();
}
});
mockList.push([
tmp, mockDict
]);
});
local.testMock(mockList, function (onError) {
local.tryCatchOnError(function () {
exports = require(file);
}, local.onErrorDefault);
onError();
}, local.onErrorThrow);
return exports;
};
...
testReportCreate = function (testReport) {
/*
* this function will create test-report artifacts
*/
testReport = local.objectSetDefault(testReport, {
testPlatformList: []
});
// print test-report summary
console.error(
"\n" + new Array(56).join("-")
+ "\n" + testReport.testPlatformList.filter(function (testPlatform) {
// if testPlatform has no tests, then filter it out
return testPlatform.testCaseList.length;
}).map(function (testPlatform) {
return (
"| test-report - " + testPlatform.name + "\n|"
+ (" " + testPlatform.timeElapsed + " ms ")
.slice(-16)
+ (" " + testPlatform.testsFailed + " failed ")
.slice(-16)
+ (" " + testPlatform.testsPassed + " passed ")
.slice(-16) + " |\n" + new Array(56).join("-")
);
}).join("\n") + "\n"
);
// create test-report.html
local.fs.writeFileSync(
"tmp/build/test-report.html",
local.testReportMerge(testReport, {})
);
// create build.badge.svg
local.fs.writeFileSync(
"tmp/build/build.badge.svg",
local.assetsDict["/assets.buildBadge.template.svg"].replace((
/0000-00-00\u002000:00:00\u0020UTC\u0020-\u0020master\u0020-\u0020aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/g
), (
new Date().toISOString().slice(0, 19).replace("T", " ")
+ " - " + local.env.CI_BRANCH + " - " + local.env.CI_COMMIT_ID
))
);
// create test-report.badge.svg
local.fs.writeFileSync(
"tmp/build/test-report.badge.svg",
local.assetsDict["/assets.testReportBadge.template.svg"]
// edit number of tests failed
.replace((
/999/g
), testReport.testsFailed)
// edit badge color
.replace((
/d00/g
), (
testReport.testsFailed
? "d00"
: "0d0"
))
);
console.error(
"created test-report file "
+ process.cwd() + "/tmp/build/test-report.html\n"
);
// if any test failed, then exit with non-zero exit-code
console.error(
"\n" + local.env.MODE_BUILD
+ " - " + testReport.testsFailed + " failed tests\n"
);
// print failed testCase
testReport.testPlatformList.forEach(function (testPlatform) {
testPlatform.testCaseList.forEach(function (testCase) {
if (testCase.status !== "passed") {
console.error(JSON.stringify(testCase, null, 4));
}
});
});
return testReport;
}
...
local.cliDict["utility2.testReportCreate"] = function () {
/*
*
* will create test-report
*/
local.exit(
local.testReportCreate(
JSON.parse(local.fs.readFileSync(
local.env.npm_config_dir_build + "/test-report.json"
))
).testsFailed
);
};
}());
...
testReportMerge = function (testReport1, testReport2) {
/*
* this function will
* 1. merge testReport2 into testReport1
* 2. return testReport1 in html-format
*/
var errorStackList;
var testCaseNumber;
var testReport;
testReport2 = testReport2 || {};
// 1. merge testReport2 into testReport1
[
testReport1, testReport2
].forEach(function (testReport, ii) {
ii += 1;
local.objectSetDefault(testReport, {
date: new Date().toISOString(),
errorStackList: [],
testPlatformList: [],
timeElapsed: 0
}, 8);
// security - handle malformed testReport
local.assertThrow(
typeof testReport === "object" && testReport,
ii + " invalid testReport " + typeof testReport
);
// validate timeElapsed
local.assertThrow(
typeof testReport.timeElapsed === "number",
ii + " invalid testReport.timeElapsed "
+ typeof testReport.timeElapsed
);
// security - handle malformed testReport.testPlatformList
testReport.testPlatformList.forEach(function (testPlatform) {
local.objectSetDefault(testPlatform, {
name: "undefined",
testCaseList: [],
timeElapsed: 0
}, 8);
local.assertThrow(
typeof testPlatform.name === "string",
ii + " invalid testPlatform.name " + typeof testPlatform.name
);
// insert $MODE_BUILD into testPlatform.name
if (local.env.MODE_BUILD) {
testPlatform.name = testPlatform.name.replace((
/^(browser|node)\b/
), local.env.MODE_BUILD + " - $1");
}
// validate timeElapsed
local.assertThrow(
typeof testPlatform.timeElapsed === "number",
(
ii + " invalid testPlatform.timeElapsed "
+ typeof testPlatform.timeElapsed
)
);
// security - handle malformed testPlatform.testCaseList
testPlatform.testCaseList.forEach(function (testCase) {
local.objectSetDefault(testCase, {
errorStack: "",
name: "undefined",
timeElapsed: 0
}, 8);
local.assertThrow(
typeof testCase.errorStack === "string",
ii + " invalid testCase.errorStack "
+ typeof testCase.errorStack
);
local.assertThrow(
typeof testCase.name === "string",
ii + " invalid testCase.name " + typeof testCase.name
);
// validate timeElapsed
local.assertThrow(
typeof testCase.timeElapsed === "number",
(
ii + " invalid testCase.timeElapsed "
+ typeof testCase.timeElapsed
)
);
});
});
});
// merge testReport2.testPlatformList into testReport1.testPlatformList
testReport2.testPlatformList.forEach(function (testPlatform2) {
// add testPlatform2 to testReport1.testPlatformList
testReport1.testPlatformList.push(testPlatform2);
});
testReport = testReport1;
testReport.testsFailed = 0;
testReport.testsPassed = 0;
testReport.testsPending = 0;
testReport.testPlatformList.forEach(function (testPlatform) {
testPlatform.testsFailed = 0;
testPlatform.testsPassed = 0;
testPlatform.testsPending = 0;
testPlatform.testCaseList.forEach(function (testCase) {
switch (testCase.status) {
//...
...
+ "\n"
);
// merge browser test-report
data = local.fsReadFileOrEmptyStringSync(
opt.fileTestReport,
"json"
);
local.testReportMerge(
window.utility2_testReport,
!opt.modeSilent && data
);
console.error(
"\nbrowserTest - merged test-report from file "
+ opt.fileTestReport
+ "\n"
...
testRunDefault = function (opt) {
/*
* this function will run the tests in testPlatform.testCaseList
*/
var processExit;
var testPlatform;
var testReport;
var testReportDiv1;
var timerInterval;
// run-server
if (!local.isBrowser) {
local.testRunServer(opt);
}
globalThis.utility2_modeTest = Number(
globalThis.utility2_modeTest
|| opt.modeTest
|| local.modeTest
|| local.env.npm_config_mode_test
);
switch (globalThis.utility2_modeTest) {
// init
case 1:
globalThis.utility2_modeTest += 1;
// reset db
if (local.db && typeof local.db.dbReset === "function") {
local.db.dbReset(
globalThis.utility2_dbSeedList,
local.onErrorThrow
);
}
globalThis.utility2_onReadyAfter(function () {
local.testRunDefault(opt);
});
return;
// test-run
default:
// test-ignore
if (
globalThis.utility2_onReadyBefore.counter
|| !globalThis.utility2_modeTest
|| globalThis.utility2_modeTest > 2
) {
return;
}
// test-run
globalThis.utility2_modeTest += 1;
}
// visual notification - testRun
local.ajaxProgressUpdate();
// mock serverLog
local._testRunConsoleError = local._testRunConsoleError || console.error;
console.error = function (arg0) {
/*
* this function will ignore serverLog-messages during test-run
*/
/* istanbul ignore next */
if (!globalThis.__coverage__ && !(
/^serverLog\u0020-\u0020\{/
).test(arg0)) {
local._testRunConsoleError.apply(console, arguments); // jslint ignore:line
}
};
if (!local.isBrowser) {
// mock proces.exit
processExit = process.exit;
process.exit = local.nop;
}
// init modeTestCase
local.modeTestCase = (
local.modeTestCase
|| local.env.npm_config_mode_test_case || ""
);
// init testReport
testReport = globalThis.utility2_testReport;
// init testReport timer
local.timeElapsedStart(testReport);
// init testPlatform
testPlatform = testReport.testPlatformList[0];
// init testPlatform timer
local.timeElapsedStart(testPlatform);
// reset testPlatform.testCaseList
testPlatform.testCaseList.length = 0;
// add tests into testPlatform.testCaseList
Object.keys(opt).forEach(function (key) {
// add testCase opt[key] to testPlatform.testCaseList
if (
typeof opt[key] === "function" && (
local.modeTestCase
? local.modeTestCase.split(
/[,\s]/g
).indexOf(key) >= 0
: key.indexOf("testCase_") === 0
)
) {
testPlatform.testCaseList.push({
isBrowser: local.isBrowser,
name: key,
status: "pending",
onTestCase: opt[key]
});
}
});
// visual notification - update test-progress until isDone
// init testReportDiv1 elem
if (local.isBrowser) {
testReportDiv1 = document.querySelector(
"#testReportDiv1"
);
}
testReportDiv1 = testReportDiv1 || {
style: {}
};
local.uiAnimateSlideDown(testReportDiv1);
testReportDiv1.innerHTML = local.testReportMerge(testReport, {});
// update test-report status every 1000 ms until isDone
timerInterval = setInterval(function () {
// update testPlatform.timeElapsed
local.timeElapsedPoll(testPlatform);
// update testReportDiv1 in browser
testReportDiv1.innerHTML = local.testReportMerge(testReport, {});
if (!testReport.testsPending) {
// cleanup timerInterval
clearInterval(timerInterval);
}
// notify of...
...
local.uiAnimateSlideDown(document.querySelector(\n\
"#testReportDiv1"\n\
));\n\
document.querySelector(\n\
"#testRunButton1"\n\
).textContent = "hide internal test";\n\
local.modeTest = 1;\n\
local.testRunDefault(local);\n\
return;\n\
}\n\
// hide browser-tests\n\
local.uiAnimateSlideUp(document.querySelector(\n\
"#testReportDiv1"\n\
));\n\
document.querySelector(\n\
...
testRunServer = function (opt) {
/*
* this function will
* 1. create server from local.middlewareList
* 2. start server on local.env.PORT
* 3. run tests
*/
if (globalThis.utility2_serverHttp1) {
return;
}
globalThis.utility2_onReadyBefore.counter += 1;
// 1. create server from local.middlewareList
local.middlewareList = local.middlewareList || [
local.middlewareInit,
local.middlewareForwardProxy,
local.middlewareAssetsCached,
local.middlewareJsonpStateInit,
local.middlewareFileServer
];
local.serverLocalReqHandler = function (req, res) {
var that;
that = {};
local.onNext(that, function (err) {
if (err || that.modeNext >= local.middlewareList.length) {
local.middlewareError(err, req, res);
return;
}
// recurse with next middleware in middlewareList
local.middlewareList[that.modeNext](req, res, that.onNext);
});
that.modeNext = -1;
that.onNext();
};
globalThis.utility2_serverHttp1 = local.http.createServer(
local.serverLocalReqHandler
);
// 2. start server on local.env.PORT
if (local.env.npm_config_mode_library) {
globalThis.utility2_onReadyBefore();
return;
}
console.error("http-server listening on port " + local.env.PORT);
globalThis.utility2_onReadyBefore.counter += 1;
globalThis.utility2_serverHttp1.listen(
local.env.PORT,
globalThis.utility2_onReadyBefore
);
// 3. run tests
local.testRunDefault(opt);
globalThis.utility2_onReadyBefore();
}
...
/*
* <port>
* will start utility2 http-server on given <port> (default 8081)
*/
local.env.PORT = process.argv[3] || local.env.PORT;
globalThis.local = local;
local.replStart();
local.testRunServer({});
};
local.cliDict["utility2.swaggerValidateFile"] = function () {
/*
* <file/url>
* will swagger-validate file/url
*/
...
throwError = function () {
/*
* this function will throw new err
*/
throw new Error();
}
...
};
local.testCase_throwError_default = function (opt, onError) {
/*
* this function will test throwError's default handling-behavior
*/
local.tryCatchOnError(function () {
local.throwError();
}, function (err) {
// validate err occurred
local.assertThrow(err, err);
onError(null, opt);
});
};
...
timeElapsedPoll = function (opt) {
/*
* this function will poll <opt>.timeElapsed
*/
opt = local.timeElapsedStart(opt);
opt.timeElapsed = Date.now() - opt.timeStart;
return opt;
}
...
> bb.status.replace("passed", "z") + bb.name
? 1
: -1
);
});
// stop testReport timer
if (!testReport.testsPending) {
local.timeElapsedPoll(testReport);
}
// 2. return testReport1 in html-format
// json-copy testReport that will be modified for html templating
testReport = local.jsonCopy(testReport1);
// update timeElapsed
local.timeElapsedPoll(testReport);
testReport.testPlatformList.forEach(function (testPlatform) {
...
timeElapsedStart = function (opt, timeStart) {
/*
* this function will start <opt>.timeElapsed
*/
opt = opt || {};
opt.timeStart = timeStart || opt.timeStart || Date.now();
return opt;
}
...
local.modeTestCase = (
local.modeTestCase
|| local.env.npm_config_mode_test_case || ""
);
// init testReport
testReport = globalThis.utility2_testReport;
// init testReport timer
local.timeElapsedStart(testReport);
// init testPlatform
testPlatform = testReport.testPlatformList[0];
// init testPlatform timer
local.timeElapsedStart(testPlatform);
// reset testPlatform.testCaseList
testPlatform.testCaseList.length = 0;
// add tests into testPlatform.testCaseList
...
tryCatchOnError = function (fnc, onError) {
/*
* this function will run the fnc in a tryCatch block,
* else call onError with errCaught
*/
var result;
// validate onError
local.assertThrow(typeof onError === "function", typeof onError);
try {
// reset errCaught
local._debugTryCatchError = null;
result = fnc();
local._debugTryCatchError = null;
return result;
} catch (errCaught) {
// debug errCaught
local._debugTryCatchError = errCaught;
return onError(errCaught);
}
}
...
return elem;
};
readExample = function (file) {
/*
* this function will read the example from given file
*/
var result;
local.tryCatchOnError(function () {
file = local.path.resolve(opt.dir, file);
console.error("apidocCreate - readExample " + file);
result = "";
result = (
"\n\n\n\n\n\n\n\n"
// bug-workaround - truncate example to manageable size
+ local.fs.readFileSync(file, "utf8").slice(0, 262144)
...
uiAnimateShake = function (elem, onError) {
/*
* this function will shake dom-<elem>
*/
if (!elem || elem.classList.contains("uiAnimateShake")) {
local.setTimeoutOnError(onError);
return;
}
elem.classList.add("uiAnimateShake");
setTimeout(function () {
elem.classList.remove("uiAnimateShake");
local.setTimeoutOnError(onError);
}, 500);
}
...
if (!elem) {
local.setTimeoutOnError(onError);
return;
}
hasError = elem.classList.contains("hasError");
if (err && !hasError) {
elem.classList.add("hasError");
local.uiAnimateShake(elem, onError);
return;
}
if (!err && hasError) {
elem.classList.remove("hasError");
}
local.setTimeoutOnError(onError);
};
...
uiAnimateShakeIfError = function (err, elem, onError) {
/*
* this function will shake dom-<elem> if <err> occurred
*/
var hasError;
if (!elem) {
local.setTimeoutOnError(onError);
return;
}
hasError = elem.classList.contains("hasError");
if (err && !hasError) {
elem.classList.add("hasError");
local.uiAnimateShake(elem, onError);
return;
}
if (!err && hasError) {
elem.classList.remove("hasError");
}
local.setTimeoutOnError(onError);
}
...
errorDict[err.opt.prefix[2]] = err;
});
// shake input on err
Array.from(opt.targetOnEvent.querySelectorAll(
".schemaP[data-name]"
)).forEach(function (element) {
tmp = errorDict[element.dataset.name];
local.uiAnimateShakeIfError(tmp, element.querySelector(
".input"
));
element.querySelector(
".colorError"
).textContent = (
tmp
? tmp.messageShort
...
uiAnimateSlideAccordian = function (elem, elemList, onError) {
/*
* this function will slideDown <elem>, but slideUp elements in <elemList>
*/
elemList.forEach(function (elem2) {
if (elem2 !== elem) {
local.uiAnimateSlideUp(elem2);
}
});
setTimeout(function () {
local.uiAnimateSlideDown(elem, onError);
}, 250);
}
...
// show parent resource
local.uiAnimateSlideDown(element.closest(
".resource"
).querySelector(
".operationList"
));
// show the operation, but hide all other operations
local.uiAnimateSlideAccordian(
element.querySelector(
".operation > form"
),
Array.from(element.closest(
".operationList"
).querySelectorAll(
".operation > form"
...
uiAnimateSlideDown = function (elem, onError) {
/*
* this function will slideDown dom-<elem>
*/
onError = onError || local.nop;
if (!(
elem
&& elem.style && elem.style.maxHeight !== "100%"
&& elem.classList && elem.classList.contains("uiAnimateSlide")
)) {
onError();
return;
}
elem.style.borderBottom = "";
elem.style.borderTop = "";
elem.style.marginBottom = "";
elem.style.marginTop = "";
elem.style.maxHeight = 1.5 * globalThis.innerHeight + "px";
elem.style.paddingBottom = "";
elem.style.paddingTop = "";
setTimeout(function () {
elem.style.maxHeight = "100%";
onError();
}, 250);
}
...
".operation"
);
location.hash = "!" + element.id;
element.closest(
".resource"
).classList.remove("expanded");
// show parent resource
local.uiAnimateSlideDown(element.closest(
".resource"
).querySelector(
".operationList"
));
// show the operation, but hide all other operations
local.uiAnimateSlideAccordian(
element.querySelector(
...
uiAnimateSlideUp = function (elem, onError) {
/*
* this function will slideUp dom-<elem>
*/
if (!(
elem
&& elem.style && elem.style.maxHeight !== "0px"
&& elem.classList && elem.classList.contains("uiAnimateSlide")
)) {
local.setTimeoutOnError(onError);
return;
}
elem.style.borderBottom = "0";
elem.style.borderTop = "0";
elem.style.marginBottom = "0";
elem.style.marginTop = "0";
elem.style.maxHeight = "0";
elem.style.paddingBottom = "0";
elem.style.paddingTop = "0";
local.setTimeoutOnError(onError, 250);
}
...
);
// collapse all operations in the resource
if (evt.currentTarget.classList.contains("expanded")) {
evt.currentTarget.classList.remove("expanded");
Array.from(evt.currentTarget.querySelectorAll(
".operation > form"
)).forEach(function (element) {
local.uiAnimateSlideUp(element);
});
// expand all operations in the resource
} else {
evt.currentTarget.classList.add("expanded");
Array.from(evt.currentTarget.querySelectorAll(
".operation > form"
)).forEach(function (element) {
...
urlJoin = function (aa, bb) {
/*
* this function will if bb is relative, url-join aa with bb
*/
// bb is absolute-url
if ((
/^\w+?:\/\//
).test(bb)) {
return bb;
}
// bb is absolute-url without protocol
if (bb.slice(0, 2) === "//") {
return aa.split("/")[0] + bb;
}
// bb is absolute-url without host
if (bb[0] === "/") {
return aa.split("/").slice(0, 3).join("/") + bb;
}
// bb is relative-url
if (aa.split("/").length < 4) {
aa += "/";
}
return aa.replace((
/[?#].*?$/
), "").replace((
/[^\/]*?$/
), "") + bb;
}
...
onError(null, opt);
};
local.testCase_urlJoin_default = function (opt, onError) {
/*
* this function will test urlJoin's default handling-behavior
*/
local.assertJsonEqual(local.urlJoin("", ""), "/");
local.assertJsonEqual(local.urlJoin("http://aa/bb", "zz"), "http://aa/zz");
local.assertJsonEqual(
local.urlJoin("http://aa/bb/", "zz"),
"http://aa/bb/zz"
);
local.assertJsonEqual(
local.urlJoin("http://aa/bb/", "/zz"),
...
urlParse = function (url) {
/*
* this function will parse <url> according to below spec, plus a query param
* https://developer.mozilla.org/en-US/docs/Web/API/URL
*/
var urlParsed;
urlParsed = {};
// try to parse url
local.tryCatchOnError(function () {
// resolve host-less url
if (local.isBrowser) {
local.serverLocalHost = (
local.serverLocalHost
|| location.protocol + "//" + location.host
);
// resolve absolute path
if (url[0] === "/") {
url = local.serverLocalHost + url;
// resolve relative path
} else if (!(
/^\w+?:\/\//
).test(url)) {
url = (
local.serverLocalHost
+ location.pathname.replace((
/\/[^\/]*?$/
), "") + "/" + url
);
}
urlParsed = new globalThis.URL(url);
urlParsed.path = "/" + urlParsed.href
.split("/")
.slice(3)
.join("/")
.split("#")[0];
} else {
local.env.PORT = local.env.PORT || "8081";
local.serverLocalHost = (
local.serverLocalHost
|| ("http://127.0.0.1:" + local.env.PORT)
);
// resolve absolute path
if (url[0] === "/") {
url = local.serverLocalHost + url;
// resolve relative path
} else if (!(
/^\w+?:\/\//
).test(url)) {
url = local.serverLocalHost + "/" + url;
}
urlParsed = local.url.parse(url);
}
// init query
urlParsed.query = {};
(urlParsed.search || "").slice(1).replace((
/[^&]+/g
), function (item) {
item = item.split("=");
item[0] = decodeURIComponent(item[0]);
item[1] = decodeURIComponent(item.slice(1).join("="));
// parse repeating query-param as an array
if (urlParsed.query[item[0]]) {
if (!Array.isArray(urlParsed.query[item[0]])) {
urlParsed.query[item[0]] = [
urlParsed.query[item[0]]
];
}
urlParsed.query[item[0]].push(item[1]);
} else {
urlParsed.query[item[0]] = item[1];
}
});
urlParsed.basename = urlParsed.pathname.replace((
/^.*\//
), "");
}, local.nop);
// https://developer.mozilla.org/en/docs/Web/API/URL#Properties
return {
basename: urlParsed.basename || "",
hash: urlParsed.hash || "",
host: urlParsed.host || "",
hostname: urlParsed.hostname || "",
href: urlParsed.href || "",
path: urlParsed.path || "",
pathname: urlParsed.pathname || "",
port: urlParsed.port || "",
protocol: urlParsed.protocol || "",
query: urlParsed.query || {},
search: urlParsed.search || ""
};
}
...
);
}
// init url
opt.url = "";
opt.url += (
local.identity(
that["x-swgg-schemes"] || local.swaggerJson.schemes || []
)[0] || local.urlParse("").protocol.slice(0, -1)
);
opt.url += "://";
opt.url += (
that["x-swgg-host"]
|| local.swaggerJson.host
|| local.urlParse("").host
);
...
uuid4Create = function () {
/*
* this function will create a random uuid,
* with format 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
*/
// code derived from http://jsperf.com/uuid4
var id;
var ii;
id = "";
ii = 0;
while (ii < 32) {
switch (ii) {
case 8:
case 20:
id += "-";
// coerce to finite integer
id += ((Math.random() * 16) | 0).toString(16);
break;
case 12:
id += "-";
id += "4";
break;
case 16:
id += "-";
id += ((Math.random() * 4) | 8).toString(16);
break;
default:
// coerce to finite integer
id += ((Math.random() * 16) | 0).toString(16);
}
ii += 1;
}
return id;
}
...
};
local.testCase_uuid4Create_default = function (opt, onError) {
/*
* this function will test uuid4Create's default handling-behavior
*/
local.assertThrow(
local.regexpValidateUuid.test(local.uuid4Create()),
local.uuid4Create()
);
onError(null, opt);
};
local.testCase_webpage_err = function (opt, onError) {
/*
...
FormData = function () {
/*
* this function will create a serverLocal-compatible FormData instance
* The FormData(form) constructor must run these steps:
* 1. Let fd be a new FormData object.
* 2. If form is given, set fd's entries to the result
* of constructing the form data set for form. (not implemented)
* 3. Return fd.
* https://xhr.spec.whatwg.org/#dom-formdata
*/
this.entryList = [];
}
...
swaggerJson: local.swaggerJson
})[0];
// init default
local.objectSetDefault(opt, {
inForm: (
// ternary-operator
that._consumes0 === "multipart/form-data"
? new local.FormData()
: ""
),
inHeader: {},
inPath: that._path.replace((
/#.*?$/
), ""),
inQuery: "",
...
append = function (name, value, filename) {
/*
* The append(name, value, filename) method, when invoked, must run these steps:
* 1. If the filename argument is given, set value to a new File object
* whose contents are value and name is filename.
* 2. Append a new entry whose name is name, and value is value,
* to context object's list of entries.
* https://xhr.spec.whatwg.org/#dom-formdata-append
*/
if (filename) {
// bug-workaround - chromium cannot assign name to Blob instance
local.tryCatchOnError(function () {
value.name = filename;
}, local.nop);
}
this.entryList.push({
name,
value
});
}
...
"\n<" + schemaP.name + ">" + "<![CDATA["
+ tmp.replace((
/\]\]>/g
), "]]>") + "]]></" + schemaP.name + ">"
);
break;
case "multipart/form-data":
opt.inForm.append(schemaP.name, tmp, tmp && tmp.name);
break;
default:
if (opt.inForm) {
opt.inForm += "&";
}
opt.inForm += (
encodeURIComponent(schemaP.name) + "="
...
read = function (onError) {
/*
* this function will read from formData as a buffer, e.g.
* --Boundary\r\n
* Content-Disposition: form-data; name="key"\r\n
* \r\n
* value\r\n
* --Boundary\r\n
* Content-Disposition: form-data; name="input1"; filename="file1.png"\r\n
* Content-Type: image/jpeg\r\n
* \r\n
* <data1>\r\n
* --Boundary\r\n
* Content-Disposition: form-data; name="input2"; filename="file2.png"\r\n
* Content-Type: image/jpeg\r\n
* \r\n
* <data2>\r\n
* --Boundary--\r\n
* https://tools.ietf.org/html/rfc7578
*/
var boundary;
var result;
// handle null-case
if (!this.entryList.length) {
onError(null, "");
return;
}
// init boundary
boundary = "--" + Date.now().toString(16) + Math.random().toString(16);
// init result
result = [];
local.onParallelList({
list: this.entryList
}, function (option2, onParallel) {
var value;
value = option2.elem.value;
if (!(value && value.constructor === local.Blob)) {
result[option2.ii] = [
(
boundary + "\r\nContent-Disposition: form-data; name=\""
+ option2.elem.name + "\"\r\n\r\n"
), value, "\r\n"
];
onParallel.counter += 1;
onParallel();
return;
}
// read from blob in parallel
onParallel.counter += 1;
local.blobRead(value, function (err, data) {
result[option2.ii] = !err && [
(
boundary + "\r\nContent-Disposition: form-data; name=\""
+ option2.elem.name + "\"" + (
(value && value.name)
// read param filename
? "; filename=\"" + value.name + "\""
: ""
) + "\r\n" + (
(value && value.type)
// read param Content-Type
? "Content-Type: " + value.type + "\r\n"
: ""
) + "\r\n"
), data, "\r\n"
];
onParallel(err);
});
}, function (err) {
// add closing boundary
result.push([
boundary + "--\r\n"
]);
// concatenate result
onError(
err,
// flatten result
!err
&& local.bufferConcat(Array.prototype.concat.apply([], result))
);
});
}
...
var c,
reader = this._reader,
token = null,
startLine = reader.getLine(),
startCol = reader.getCol();
c = reader.read();
while (c) {
switch (c) {
/*
* Potential tokens:
* - COMMENT
...
function Module(id = '', parent) { this.id = id; this.path = path.dirname(id); this.exports = {}; this.parent = parent; updateChildren(parent, this, false); this.filename = null; this.loaded = false; this.children = []; }
...
// init example.js
tmp = process.cwd() + "/example.js";
// jslint code
local.jslintAndPrint(code, tmp);
// cover code
code = local.istanbulInstrumentInPackage(code, tmp);
// init module.exports
module = new local.Module(tmp);
require.cache[tmp] = module;
// load code into module
module._compile(code, tmp);
// init exports
module.exports.utility2 = local;
module.exports[local.env.npm_package_nameLib] = (
globalThis.utility2_moduleExports
...
function deprecated(...args) { if (!warned) { warned = true; if (code !== undefined) { if (!codesWarned.has(code)) { process.emitWarning(msg, 'DeprecationWarning', code, deprecated); codesWarned.add(code); } } else { process.emitWarning(msg, 'DeprecationWarning', deprecated); } } if (new.target) { return Reflect.construct(fn, args, new.target); } return fn.apply(this, args); }
n/a
function(request, paths, isMain) { const absoluteRequest = path.isAbsolute(request); if (absoluteRequest) { paths = ['']; } else if (!paths || paths.length === 0) { return false; } const cacheKey = request + '\x00' + (paths.length === 1 ? paths[0] : paths.join('\x00')); const entry = Module._pathCache[cacheKey]; if (entry) return entry; var exts; var trailingSlash = request.length > 0 && request.charCodeAt(request.length - 1) === CHAR_FORWARD_SLASH; if (!trailingSlash) { trailingSlash = /(?:^|\/)\.?\.$/.test(request); } // For each path for (var i = 0; i < paths.length; i++) { // Don't search further if path doesn't exist const curPath = paths[i]; if (curPath && stat(curPath) < 1) continue; var basePath = resolveExports(curPath, request, absoluteRequest); var filename; var rc = stat(basePath); if (!trailingSlash) { if (rc === 0) { // File. if (!isMain) { if (preserveSymlinks) { filename = path.resolve(basePath); } else { filename = toRealPath(basePath); } } else if (preserveSymlinksMain) { // For the main module, we use the preserveSymlinksMain flag instead // mainly for backward compatibility, as the preserveSymlinks flag // historically has not applied to the main module. Most likely this // was intended to keep .bin/ binaries working, as following those // symlinks is usually required for the imports in the corresponding // files to resolve; that said, in some use cases following symlinks // causes bigger problems which is why the preserveSymlinksMain option // is needed. filename = path.resolve(basePath); } else { filename = toRealPath(basePath); } } if (!filename) { // Try it with each of the extensions if (exts === undefined) exts = Object.keys(Module._extensions); filename = tryExtensions(basePath, exts, isMain); } } if (!filename && rc === 1) { // Directory. // try it with each of the extensions at "index" if (exts === undefined) exts = Object.keys(Module._extensions); filename = tryPackage(basePath, exts, isMain, request); } if (filename) { Module._pathCache[cacheKey] = filename; return filename; } } return false; }
n/a
function() { var homeDir; var nodePath; if (isWindows) { homeDir = process.env.USERPROFILE; nodePath = process.env.NODE_PATH; } else { homeDir = safeGetenv('HOME'); nodePath = safeGetenv('NODE_PATH'); } // $PREFIX/lib/node, where $PREFIX is the root of the Node.js installation. var prefixDir; // process.execPath is $PREFIX/bin/node except on Windows where it is // $PREFIX\node.exe. if (isWindows) { prefixDir = path.resolve(process.execPath, '..'); } else { prefixDir = path.resolve(process.execPath, '..', '..'); } var paths = [path.resolve(prefixDir, 'lib', 'node')]; if (homeDir) { paths.unshift(path.resolve(homeDir, '.node_libraries')); paths.unshift(path.resolve(homeDir, '.node_modules')); } if (nodePath) { paths = nodePath.split(path.delimiter).filter(function pathsFilterCB(path) { return !!path; }).concat(paths); } modulePaths = paths; // Clone as a shallow copy, for introspection. Module.globalPaths = modulePaths.slice(0); }
n/a
function(request, parent, isMain) { let relResolveCacheIdentifier; if (parent) { debug('Module._load REQUEST %s parent: %s', request, parent.id); // Fast path for (lazy loaded) modules in the same directory. The indirect // caching is required to allow cache invalidation without changing the old // cache key names. relResolveCacheIdentifier = `${parent.path}\x00${request}`; const filename = relativeResolveCache[relResolveCacheIdentifier]; if (filename !== undefined) { const cachedModule = Module._cache[filename]; if (cachedModule !== undefined) { updateChildren(parent, cachedModule, true); return cachedModule.exports; } delete relativeResolveCache[relResolveCacheIdentifier]; } } const filename = Module._resolveFilename(request, parent, isMain); const cachedModule = Module._cache[filename]; if (cachedModule !== undefined) { updateChildren(parent, cachedModule, true); return cachedModule.exports; } const mod = loadNativeModule(filename, request, experimentalModules); if (mod && mod.canBeRequiredByUsers) return mod.exports; // Don't call updateChildren(), Module constructor already does. const module = new Module(filename, parent); if (isMain) { process.mainModule = module; module.id = '.'; } Module._cache[filename] = module; if (parent !== undefined) { relativeResolveCache[relResolveCacheIdentifier] = filename; } let threw = true; try { module.load(filename); threw = false; } finally { if (threw) { delete Module._cache[filename]; if (parent !== undefined) { delete relativeResolveCache[relResolveCacheIdentifier]; } } } return module.exports; }
n/a
function(from) { // Guarantee that 'from' is absolute. from = path.resolve(from); // Return early not only to avoid unnecessary work, but to *avoid* returning // an array of two items for a root: [ '//node_modules', '/node_modules' ] if (from === '/') return ['/node_modules']; // note: this approach *only* works when the path is guaranteed // to be absolute. Doing a fully-edge-case-correct path.split // that works on both Windows and Posix is non-trivial. const paths = []; var p = 0; var last = from.length; for (var i = from.length - 1; i >= 0; --i) { const code = from.charCodeAt(i); if (code === CHAR_FORWARD_SLASH) { if (p !== nmLen) paths.push(from.slice(0, last) + '/node_modules'); last = i; p = 0; } else if (p !== -1) { if (nmChars[p] === code) { ++p; } else { p = -1; } } } // Append /node_modules to handle root paths. paths.push('/node_modules'); return paths; }
n/a
function(requests) { if (!Array.isArray(requests)) return; // Preloaded modules have a dummy parent module which is deemed to exist // in the current working directory. This seeds the search path for // preloaded modules. const parent = new Module('internal/preload', null); try { parent.paths = Module._nodeModulePaths(process.cwd()); } catch (e) { if (e.code !== 'ENOENT') { throw e; } } for (var n = 0; n < requests.length; n++) parent.require(requests[n]); }
n/a
function(request, parent, isMain, options) { if (NativeModule.canBeRequiredByUsers(request)) { return request; } var paths; if (typeof options === 'object' && options !== null) { if (Array.isArray(options.paths)) { const isRelative = request.startsWith('./') || request.startsWith('../') || (isWindows && request.startsWith('.\\') || request.startsWith('..\\')); if (isRelative) { paths = options.paths; } else { const fakeParent = new Module('', null); paths = []; for (var i = 0; i < options.paths.length; i++) { const path = options.paths[i]; fakeParent.paths = Module._nodeModulePaths(path); const lookupPaths = Module._resolveLookupPaths(request, fakeParent); for (var j = 0; j < lookupPaths.length; j++) { if (!paths.includes(lookupPaths[j])) paths.push(lookupPaths[j]); } } } } else if (options.paths === undefined) { paths = Module._resolveLookupPaths(request, parent); } else { throw new ERR_INVALID_OPT_VALUE('options.paths', options.paths); } } else { paths = Module._resolveLookupPaths(request, parent); } // Look up the filename first, since that's the cache key. const filename = Module._findPath(request, paths, isMain); if (!filename) { const requireStack = []; for (var cursor = parent; cursor; cursor = cursor.parent) { requireStack.push(cursor.filename || cursor.id); } let message = `Cannot find module '${request}'`; if (requireStack.length > 0) { message = message + '\nRequire stack:\n- ' + requireStack.join('\n- '); } // eslint-disable-next-line no-restricted-syntax var err = new Error(message); err.code = 'MODULE_NOT_FOUND'; err.requireStack = requireStack; throw err; } return filename; }
n/a
function(request, parent) { if (NativeModule.canBeRequiredByUsers(request)) { debug('looking for %j in []', request); return null; } // Check for node modules paths. if (request.charAt(0) !== '.' || (request.length > 1 && request.charAt(1) !== '.' && request.charAt(1) !== '/' && (!isWindows || request.charAt(1) !== '\\'))) { let paths = modulePaths; if (parent != null && parent.paths && parent.paths.length) { paths = parent.paths.concat(paths); } debug('looking for %j in %j', request, paths); return paths.length > 0 ? paths : null; } // With --eval, parent.id is not set and parent.filename is null. if (!parent || !parent.id || !parent.filename) { // Make require('./path/to/foo') work - normally the path is taken // from realpath(__filename) but with eval there is no filename const mainPaths = ['.'].concat(Module._nodeModulePaths('.'), modulePaths); debug('looking for %j in %j', request, mainPaths); return mainPaths; } debug('RELATIVE: requested: %s from parent.id %s', request, parent.id); const parentDir = [path.dirname(parent.filename)]; debug('looking for %j', parentDir); return parentDir; }
n/a
function createRequire(filename) { let filepath; if (filename instanceof URL || (typeof filename === 'string' && !path.isAbsolute(filename))) { try { filepath = fileURLToPath(filename); } catch { throw new ERR_INVALID_ARG_VALUE('filename', filename, createRequireError); } } else if (typeof filename !== 'string') { throw new ERR_INVALID_ARG_VALUE('filename', filename, createRequireError); } else { filepath = filename; } return createRequireFromPath(filepath); }
n/a
function createRequireFromPath(filename) { // Allow a directory to be passed as the filename const trailingSlash = filename.endsWith('/') || (isWindows && filename.endsWith('\\')); const proxyPath = trailingSlash ? path.join(filename, 'noop.js') : filename; const m = new Module(proxyPath); m.filename = proxyPath; m.paths = Module._nodeModulePaths(m.path); return makeRequireFunction(m, null); }
n/a
function() {
// Load the main module--the command line argument.
if (experimentalModules) {
asyncESM.loaderPromise.then((loader) => {
return loader.import(pathToFileURL(process.argv[1]).pathname);
})
.catch((e) => {
internalBinding('errors').triggerUncaughtException(
e,
true /* fromPromise */
);
});
return;
}
Module._load(process.argv[1], null, true);
}
...
process.argv.splice(1, 1, __dirname + "/lib.istanbul.js", "cover");
local.istanbul.cliDict[process.argv[2]]();
return;
}
// start
process.argv.splice(1, 1);
process.argv[1] = local.path.resolve(process.cwd(), process.argv[1]);
local.Module.runMain();
}
}());
}());
...
function(content, filename) { let moduleURL; let redirects; if (manifest) { moduleURL = pathToFileURL(filename); redirects = manifest.getRedirects(moduleURL); manifest.assertIntegrity(moduleURL, content); } content = stripShebang(content); let compiledWrapper; if (patched) { const wrapper = Module.wrap(content); compiledWrapper = vm.runInThisContext(wrapper, { filename, lineOffset: 0, displayErrors: true, importModuleDynamically: experimentalModules ? async (specifier) => { const loader = await asyncESM.loaderPromise; return loader.import(specifier, normalizeReferrerURL(filename)); } : undefined, }); } else { const compiled = compileFunction( content, filename, 0, 0, undefined, false, undefined, [], [ 'exports', 'require', 'module', '__filename', '__dirname', ] ); if (experimentalModules) { const { callbackMap } = internalBinding('module_wrap'); callbackMap.set(compiled.cacheKey, { importModuleDynamically: async (specifier) => { const loader = await asyncESM.loaderPromise; return loader.import(specifier, normalizeReferrerURL(filename)); } }); } compiledWrapper = compiled.function; } var inspectorWrapper = null; if (getOptionValue('--inspect-brk') && process._eval == null) { if (!resolvedArgv) { // We enter the repl if we're not given a filename argument. if (process.argv[1]) { resolvedArgv = Module._resolveFilename(process.argv[1], null, false); } else { resolvedArgv = 'repl'; } } // Set breakpoint on module start if (!hasPausedEntry && filename === resolvedArgv) { hasPausedEntry = true; inspectorWrapper = internalBinding('inspector').callAndPauseOnStart; } } const dirname = path.dirname(filename); const require = makeRequireFunction(this, redirects); var result; const exports = this.exports; const thisValue = exports; const module = this; if (requireDepth === 0) statCache = new Map(); if (inspectorWrapper) { result = inspectorWrapper(compiledWrapper, thisValue, exports, require, module, filename, dirname); } else { result = compiledWrapper.call(thisValue, exports, require, module, filename, dirname); } if (requireDepth === 0) statCache = null; return result; }
...
local.jslintAndPrint(code, tmp);
// cover code
code = local.istanbulInstrumentInPackage(code, tmp);
// init module.exports
module = new local.Module(tmp);
require.cache[tmp] = module;
// load code into module
module._compile(code, tmp);
// init exports
module.exports.utility2 = local;
module.exports[local.env.npm_package_nameLib] = (
globalThis.utility2_moduleExports
);
// init assets
tmp = process.cwd() + "/" + local.env.npm_package_main;
...
function(filename) { debug('load %j for module %j', filename, this.id); assert(!this.loaded); this.filename = filename; this.paths = Module._nodeModulePaths(path.dirname(filename)); const extension = findLongestRegisteredExtension(filename); Module._extensions[extension](this, filename); this.loaded = true; if (experimentalModules) { const ESMLoader = asyncESM.ESMLoader; const url = `${pathToFileURL(filename)}`; const module = ESMLoader.moduleMap.get(url); // Create module entry at load time to snapshot exports correctly const exports = this.exports; if (module !== undefined) { // Called from cjs translator if (module.reflect) { module.reflect.onReady((reflect) => { reflect.exports.default.set(exports); }); } } else { // preemptively cache ESMLoader.moduleMap.set( url, new ModuleJob(ESMLoader, url, async () => { return createDynamicModule( [], ['default'], url, (reflect) => { reflect.exports.default.set(exports); }); }) ); } } }
n/a
function(id) { validateString(id, 'id'); if (id === '') { throw new ERR_INVALID_ARG_VALUE('id', id, 'must be a non-empty string'); } requireDepth++; try { return Module._load(id, this, /* isMain */ false); } finally { requireDepth--; } }
...
}).slice(0, 256).map(readExample);
// init moduleMain
local.tryCatchOnError(function () {
console.error("apidocCreate - requiring " + opt.dir + " ...");
moduleMain = {};
moduleMain = (
opt.moduleDict[opt.env.npm_package_name]
|| opt.require(opt.dir)
|| opt.require(
opt.dir + "/"
+ (opt.packageJson.bin)[Object.keys(opt.packageJson.bin)[0]]
) || {}
);
opt.circularSet.add(moduleMain);
console.error("apidocCreate - ... required " + opt.dir);
...
IncomingMessage = function (xhr) {
/*
* An IncomingMessage object is created by http.Server or http.ClientRequest
* and passed as the first argument to the 'req' and 'res' event
* respectively.
* It may be used to access res status, headers and data.
* https://nodejs.org/dist/v0.12.18/docs/api/all.html#all_http_incomingmessage
*/
this.headers = xhr.headers;
this.httpVersion = "1.1";
this.method = xhr.method;
this.onEvent = document.createDocumentFragment();
this.readable = true;
this.url = xhr.url;
}
...
xhr.serverResponse
);
});
};
xhr.on = function () {
return xhr;
};
xhr.serverReq = new local._http.IncomingMessage(xhr);
xhr.serverResponse = new local._http.ServerResponse(onResponse);
return xhr;
};
local._testCase_buildApidoc_default = function (opt, onError) {
/*
* this function will test buildApidoc's default handling-behavior
...
ServerResponse = function (onResponse) {
/*
* This object is created internally by a HTTP server--not by the user.
* It is passed as the second parameter to the 'req' event.
* https://nodejs.org/dist/v0.12.18/docs/api/all.html#all_class_http_serverresponse
*/
this.chunkList = [];
this.onEvent = document.createDocumentFragment();
this.onResponse = onResponse;
this.resHeaders = {};
this.statusCode = 200;
}
...
);
});
};
xhr.on = function () {
return xhr;
};
xhr.serverReq = new local._http.IncomingMessage(xhr);
xhr.serverResponse = new local._http.ServerResponse(onResponse);
return xhr;
};
local._testCase_buildApidoc_default = function (opt, onError) {
/*
* this function will test buildApidoc's default handling-behavior
*/
...
createServer = function () {
/*
* Returns a new instance of http.Server.
* https://nodejs.org/dist/v0.12.18/docs/api/all.html#all_http_createserver_requestlistener
*/
return {
listen: function (port, onError) {
/*
* This will cause the server to accept connections
* on the specified handle,
* but it is presumed that the file descriptor or handle
* has already been bound to a port or domain socket.
* https://nodejs.org/dist/v0.12.18/docs/api/all.html#all_server_listen_handle_callback
*/
onError(null, port);
}
};
}
...
process.stdout._writeDefault(chunk, encoding, callback);
// coverage-hack - ignore else-statement
local.nop(that.socket.writable && (function () {
that.socket.write(chunk, encoding);
}()));
};
// start serverRepl1
globalThis.utility2_serverRepl1 = require("net").createServer(function (
socket
) {
// init socket
that.socket = socket;
that.socket.on("data", that.write.bind(that));
that.socket.on("error", that.onError);
that.socket.setKeepAlive(true);
...
request = function (xhr, onResponse) { var isDone; xhr = { headers: xhr.headers, method: xhr.method, timeout: xhr.timeout, url: xhr.href }; xhr.end = function (data) { if (isDone) { return; } isDone = true; xhr.serverReq.data = data; // asynchronously send req from client -> server setTimeout(function () { local.serverLocalReqHandler( xhr.serverReq, xhr.serverResponse ); }); }; xhr.on = function () { return xhr; }; xhr.serverReq = new local._http.IncomingMessage(xhr); xhr.serverResponse = new local._http.ServerResponse(onResponse); return xhr; }
...
}, local.nop);
// debug opt
local._debugForwardProxy = opt;
opt.clientReq = (
opt.protocol === "https:"
? local.https
: local.http
).request(opt, function (clientResponse) {
opt.clientResponse = clientResponse.on("error", onError);
res.statusCode = opt.clientResponse.statusCode;
// pipe clientResponse to serverResponse
opt.clientResponse.pipe(res);
}).on("error", onError);
opt.timeStart = Date.now();
// init event-handling
...
IncomingMessage = function (xhr) {
/*
* An IncomingMessage object is created by http.Server or http.ClientRequest
* and passed as the first argument to the 'req' and 'res' event
* respectively.
* It may be used to access res status, headers and data.
* https://nodejs.org/dist/v0.12.18/docs/api/all.html#all_http_incomingmessage
*/
this.headers = xhr.headers;
this.httpVersion = "1.1";
this.method = xhr.method;
this.onEvent = document.createDocumentFragment();
this.readable = true;
this.url = xhr.url;
}
...
xhr.serverResponse
);
});
};
xhr.on = function () {
return xhr;
};
xhr.serverReq = new local._http.IncomingMessage(xhr);
xhr.serverResponse = new local._http.ServerResponse(onResponse);
return xhr;
};
local._testCase_buildApidoc_default = function (opt, onError) {
/*
* this function will test buildApidoc's default handling-behavior
...
addListener = function (evt, onEvent) {
/*
* Adds a listener to the end of the listeners array for the specified event.
* No checks are made to see if the listener has already been added.
* Multiple calls passing the same combination of event and listener will result
* in the listener being added multiple times.
* https://nodejs.org/dist/v0.12.18/docs/api/all.html#all_emitter_addlistener_event_listener
*/
this.onEvent.addEventListener(evt, function (evt) {
onEvent(evt.data);
});
if (this.readable && evt === "end") {
this.readable = null;
this.emit("data", this.data);
this.emit("end");
}
return this;
}
n/a
emit = function (evt, data) {
/*
* Execute each of the listeners in order with the supplied arguments.
* https://nodejs.org/dist/v0.12.18/docs/api/all.html#all_emitter_emit_event_arg1_arg2
*/
evt = new Event(evt);
evt.data = data;
this.onEvent.dispatchEvent(evt);
}
...
* https://nodejs.org/dist/v0.12.18/docs/api/all.html#all_emitter_addlistener_event_listener
*/
this.onEvent.addEventListener(evt, function (evt) {
onEvent(evt.data);
});
if (this.readable && evt === "end") {
this.readable = null;
this.emit("data", this.data);
this.emit("end");
}
return this;
};
local._http.IncomingMessage.prototype.emit = function (evt, data) {
/*
...
on = function (evt, onEvent) {
/*
* Adds a listener to the end of the listeners array for the specified event.
* No checks are made to see if the listener has already been added.
* Multiple calls passing the same combination of event and listener will result
* in the listener being added multiple times.
* https://nodejs.org/dist/v0.12.18/docs/api/all.html#all_emitter_addlistener_event_listener
*/
this.onEvent.addEventListener(evt, function (evt) {
onEvent(evt.data);
});
if (this.readable && evt === "end") {
this.readable = null;
this.emit("data", this.data);
this.emit("end");
}
return this;
}
...
// run async shell-command
require("child_process").spawn(match2, {
shell: true,
stdio: [
"ignore", 1, 2
]
// on shell exit, print return prompt
}).on("exit", function (exitCode) {
console.error("exit-code " + exitCode);
that.evalDefault(
"\n",
context,
file,
onError2
);
...
pipe = function (writable) {
/*
* This method pulls all the data out of a readable stream, and writes it
* to the supplied destination, automatically managing the flow
* so that the destination is not overwhelmed by a fast readable stream.
* https://nodejs.org/dist/v0.12.18/docs/api/all.html#all_readable_pipe_destination_options
*/
this.on("data", function (chunk) {
writable.write(chunk);
});
this.on("end", function () {
writable.end();
});
return writable;
}
...
opt.protocol === "https:"
? local.https
: local.http
).request(opt, function (clientResponse) {
opt.clientResponse = clientResponse.on("error", onError);
res.statusCode = opt.clientResponse.statusCode;
// pipe clientResponse to serverResponse
opt.clientResponse.pipe(res);
}).on("error", onError);
opt.timeStart = Date.now();
// init event-handling
req.on("error", onError);
res.on("finish", onError).on("error", onError);
// pipe serverReq to clientReq
req.pipe(opt.clientReq);
...
ServerResponse = function (onResponse) {
/*
* This object is created internally by a HTTP server--not by the user.
* It is passed as the second parameter to the 'req' event.
* https://nodejs.org/dist/v0.12.18/docs/api/all.html#all_class_http_serverresponse
*/
this.chunkList = [];
this.onEvent = document.createDocumentFragment();
this.onResponse = onResponse;
this.resHeaders = {};
this.statusCode = 200;
}
...
);
});
};
xhr.on = function () {
return xhr;
};
xhr.serverReq = new local._http.IncomingMessage(xhr);
xhr.serverResponse = new local._http.ServerResponse(onResponse);
return xhr;
};
local._testCase_buildApidoc_default = function (opt, onError) {
/*
* this function will test buildApidoc's default handling-behavior
*/
...
addListener = function (evt, onEvent) {
/*
* Adds a listener to the end of the listeners array for the specified event.
* No checks are made to see if the listener has already been added.
* Multiple calls passing the same combination of event and listener will result
* in the listener being added multiple times.
* https://nodejs.org/dist/v0.12.18/docs/api/all.html#all_emitter_addlistener_event_listener
*/
this.onEvent.addEventListener(evt, function (evt) {
onEvent(evt.data);
});
if (this.readable && evt === "end") {
this.readable = null;
this.emit("data", this.data);
this.emit("end");
}
return this;
}
n/a
emit = function (evt, data) {
/*
* Execute each of the listeners in order with the supplied arguments.
* https://nodejs.org/dist/v0.12.18/docs/api/all.html#all_emitter_emit_event_arg1_arg2
*/
evt = new Event(evt);
evt.data = data;
this.onEvent.dispatchEvent(evt);
}
...
* https://nodejs.org/dist/v0.12.18/docs/api/all.html#all_emitter_addlistener_event_listener
*/
this.onEvent.addEventListener(evt, function (evt) {
onEvent(evt.data);
});
if (this.readable && evt === "end") {
this.readable = null;
this.emit("data", this.data);
this.emit("end");
}
return this;
};
local._http.IncomingMessage.prototype.emit = function (evt, data) {
/*
...
end = function (data) {
/*
* This method signals to the server that all of the res headers and body
* have been sent; that server should consider this message complete.
* The method, res.end(), MUST be called on each res.
* https://nodejs.org/dist/v0.12.18/docs/api/all.html#all_response_end_data_encoding_callback
*/
var that;
that = this;
if (that._isDone) {
return;
}
that._isDone = true;
that.chunkList.push(data);
// notify server res is finished
that.emit("finish");
// asynchronously send res from server to client
setTimeout(function () {
that.onResponse(that);
that.emit("data", local.bufferConcat(that.chunkList));
that.emit("end");
});
}
...
streamCleanup = function (stream) {
/*
* this function will try to end or destroy <stream>
*/
var err;
// try to end stream
try {
stream.end();
} catch (errCaught) {
err = errCaught;
}
// if err, then try to destroy stream
if (err) {
try {
stream.destroy();
...
on = function (evt, onEvent) {
/*
* Adds a listener to the end of the listeners array for the specified event.
* No checks are made to see if the listener has already been added.
* Multiple calls passing the same combination of event and listener will result
* in the listener being added multiple times.
* https://nodejs.org/dist/v0.12.18/docs/api/all.html#all_emitter_addlistener_event_listener
*/
this.onEvent.addEventListener(evt, function (evt) {
onEvent(evt.data);
});
if (this.readable && evt === "end") {
this.readable = null;
this.emit("data", this.data);
this.emit("end");
}
return this;
}
...
// run async shell-command
require("child_process").spawn(match2, {
shell: true,
stdio: [
"ignore", 1, 2
]
// on shell exit, print return prompt
}).on("exit", function (exitCode) {
console.error("exit-code " + exitCode);
that.evalDefault(
"\n",
context,
file,
onError2
);
...
setHeader = function (key, value) {
/*
* Sets a single header value for implicit headers.
* If this header already exists in the to-be-sent headers,
* its value will be replaced.
* Use an array of strings here if you need to send multiple headers
* with the same name.
* https://nodejs.org/dist/v0.12.18/docs/api/all.html#all_response_setheader_name_value
*/
this.resHeaders[key.toLowerCase()] = value;
}
...
onError(err, !err && data.toString("base64"));
});
}, opt.onNext);
break;
case 2:
// set gzip header
opt.result = local.base64ToBuffer(data);
res.setHeader("Content-Encoding", "gzip");
res.setHeader("Content-Length", opt.result.length);
opt.onNext();
break;
case 3:
local.middlewareCacheControlLastModified(
req,
res,
...
write = function (data) {
/*
* This sends a chunk of the res body.
* This method may be called multiple times
* to provide successive parts of the body.
* https://nodejs.org/dist/v0.12.18/docs/api/all.html#all_response_write_chunk_encoding_callback
*/
this.chunkList.push(data);
}
...
local.cliDict._default = function () {
/*
* <moduleDirectory>
* will create apidoc from <moduleDirectory>
*/
// jslint files
process.stdout.write(local.apidocCreate({
dir: process.argv[2],
modulePathList: module.paths
}));
};
// run the cli
if (module === require.main && !globalThis.utility2_rollup) {
...
apidocCreate = function (opt) {
/*
* this function will create the apidoc from <opt>.dir
*/
var elemCreate;
var module;
var moduleMain;
var readExample;
var tmp;
var toString;
var trimLeft;
elemCreate = function (module, prefix, key) {
/*
* this function will create the apidoc-elem in given <module>
*/
var elem;
if (opt.modeNoApidoc) {
return elem;
}
elem = {};
elem.moduleName = prefix.split(".");
// handle case where module is a function
if (elem.moduleName.slice(-1)[0] === key) {
elem.moduleName.pop();
}
elem.moduleName = elem.moduleName.join(".");
elem.id = encodeURIComponent("apidoc.elem." + prefix + "." + key);
elem.typeof = typeof module[key];
elem.name = (
elem.typeof + " <span class=\"apidocSignatureSpan\">"
+ elem.moduleName + ".</span>" + key
)
// handle case where module is a function
.replace(">.<", "><");
if (elem.typeof !== "function") {
return elem;
}
// init source
elem.source = local.stringHtmlSafe(
trimLeft(toString(module[key])) || "n/a"
).replace((
/\([\S\s]*?\)/
), function (match0) {
// init signature
elem.signature = match0.replace((
/\u0020*?\/\*[\S\s]*?\*\/\u0020*/g
), "")
.replace((
/,/g
), ", ")
.replace((
/\s+/g
), " ");
return elem.signature;
})
.replace((
/(\u0020*?\/\*[\S\s]*?\*\/\n)/
), "<span class=\"apidocCodeCommentSpan\">$1</span>")
.replace((
/^function\u0020\(/
), key + " = function (");
// init example
opt.exampleList.some(function (example) {
example.replace(
new RegExp("((?:\n.*?){8}\\.)(" + key + ")(\\((?:.*?\n){8})"),
function (ignore, match1, match2, match3) {
elem.example = "..." + trimLeft(
local.stringHtmlSafe(match1)
+ "<span class=\"apidocCodeKeywordSpan\">"
+ local.stringHtmlSafe(match2)
+ "</span>"
+ local.stringHtmlSafe(match3)
).trimRight() + "\n...";
}
);
return elem.example;
});
elem.example = elem.example || "n/a";
return elem;
};
readExample = function (file) {
/*
* this function will read the example from given file
*/
var result;
local.tryCatchOnError(function () {
file = local.path.resolve(opt.dir, file);
console.error("apidocCreate - readExample " + file);
result = "";
result = (
"\n\n\n\n\n\n\n\n"
// bug-workaround - truncate example to manageable size
+ local.fs.readFileSync(file, "utf8").slice(0, 262144)
+ "\n\n\n\n\n\n\n\n"
).replace((
/\r\n*/g
), "\n");
}, console.error);
return result;
};
toString = function (value) {
/*
* this function will try to return the string form of the value
*/
var result;
local.tryCatchOnError(function () {
result = "";
result = String(value);
}, console.error);
return result;
};
trimLeft = function (text) {
/*
* this function will...
...
local.cliDict._default = function () {
/*
* <moduleDirectory>
* will create apidoc from <moduleDirectory>
*/
// jslint files
process.stdout.write(local.apidocCreate({
dir: process.argv[2],
modulePathList: module.paths
}));
};
// run the cli
if (module === require.main && !globalThis.utility2_rollup) {
...
apidocModuleDictAdd = function (opt, moduleDict) {
/*
* this function will add the modules in <moduleDict> to <opt>.moduleDict
*/
var isModule;
var objectKeys;
var tmp;
objectKeys = function (dict) {
/*
* this function will return a list of the dict's keys, with valid getters
*/
return Object.keys(dict).sort().filter(function (key) {
return local.tryCatchOnError(function () {
return dict[key] || true;
}, local.nop);
});
};
[
"child", "prototype", "grandchild", "prototype"
].forEach(function (elem) {
objectKeys(moduleDict).forEach(function (prefix) {
if (!(
/^\w[\w\-.]*?$/
).test(prefix)) {
return;
}
objectKeys(moduleDict[prefix]).forEach(function (key) {
if (!(
/^\w[\w\-.]*?$/
).test(key) || !moduleDict[prefix][key]) {
return;
}
tmp = (
elem === "prototype"
? {
module: moduleDict[prefix][key].prototype,
name: prefix + "." + key + ".prototype"
}
: {
module: moduleDict[prefix][key],
name: prefix + "." + key
}
);
if (
!tmp.module
|| !(
typeof tmp.module === "function"
|| typeof tmp.module === "object"
)
|| Array.isArray(tmp.module)
|| opt.moduleDict[tmp.name]
|| opt.circularSet.has(tmp.module)
) {
return;
}
isModule = ([
tmp.module,
tmp.module.prototype
]).some(function (dict) {
return objectKeys(dict || {}).some(function (key) {
return typeof dict[key] === "function";
});
});
if (!isModule) {
return;
}
opt.circularSet.add(tmp.module);
opt.moduleDict[tmp.name] = tmp.module;
});
});
});
}
...
opt.circularSet.add(opt.moduleDict[key]);
});
// init circularSet - prototype
opt.circularSet.forEach(function (elem) {
opt.circularSet.add(elem && elem.prototype);
});
// init moduleDict child
local.apidocModuleDictAdd(opt, opt.moduleDict);
// init swgg.apiDict
Object.keys(
(moduleMain.swgg && moduleMain.swgg.apiDict) || {}
).forEach(function (key) {
tmp = "swgg.apiDict";
opt.moduleDict[tmp] = opt.moduleDict[tmp] || {};
tmp = opt.moduleDict[tmp];
...
function ok(...args) { innerOk(ok, args.length, ...args); }
...
key = '0123456789abcdef0123456789abcdef';
mode = null;
local.cryptoAesXxxCbcRawEncrypt({
data: data,
key: key,
mode: mode
}, function (err, data) {
console.assert(!err, err);
local.cryptoAesXxxCbcRawDecrypt({
data: data,
key: key,
mode: mode
}, console.log);
});
*/
...
assertThrow = function (passed, message) {
/*
* this function will throw err.<message> if <passed> is falsy
*/
var err;
if (passed) {
return;
}
err = (
// ternary-operator
(
message
&& typeof message.message === "string"
&& typeof message.stack === "string"
)
// if message is errObj, then leave as is
? message
: new Error(
typeof message === "string"
// if message is a string, then leave as is
? message
// else JSON.stringify message
: JSON.stringify(message, null, 4)
)
);
throw err;
}
...
argList: (commandList[ii][1] || "").trim(),
command: [
key
],
description: commandList[ii][2]
};
} catch (ignore) {
local.assertThrow(null, new Error(
"cliRun - cannot parse comment in COMMAND "
+ key
+ ":\nnew RegExp("
+ JSON.stringify(opt.rgxComment.source)
+ ").exec(" + JSON.stringify(text).replace((
/\\\\/g
), "\u0000").replace((
...
cliRun = function (opt) {
/*
* this function will run the cli with given <opt>
*/
local.cliDict._eval = local.cliDict._eval || function () {
/*
* <code>
* will eval <code>
*/
globalThis.local = local;
local.vm.runInThisContext(process.argv[3]);
};
local.cliDict["--eval"] = local.cliDict["--eval"] || local.cliDict._eval;
local.cliDict["-e"] = local.cliDict["-e"] || local.cliDict._eval;
local.cliDict._help = local.cliDict._help || function () {
/*
*
* will print help
*/
var commandList;
var file;
var packageJson;
var text;
var textDict;
commandList = [
{
argList: "<arg2> ...",
description: "usage:",
command: [
"<arg1>"
]
}, {
argList: "'console.log(\"hello world\")'",
description: "example:",
command: [
"--eval"
]
}
];
file = __filename.replace((
/.*\//
), "");
opt = Object.assign({}, opt);
packageJson = require("./package.json");
// validate comment
opt.rgxComment = opt.rgxComment || (
/\)\u0020\{\n(?:|\u0020{4})\/\*\n(?:\u0020|\u0020{5})\*((?:\u0020<[^>]*?>|\u0020\.\.\.)*?)\n(?:\u0020|\u0020{5})\*\u0020
(will\u0020.*?\S)\n(?:\u0020|\u0020{5})\*\/\n(?:\u0020{4}|\u0020{8})\S/
);
textDict = {};
Object.keys(local.cliDict).sort().forEach(function (key, ii) {
if (key[0] === "_" && key !== "_default") {
return;
}
text = String(local.cliDict[key]);
if (key === "_default") {
key = "";
}
textDict[text] = textDict[text] || (ii + 2);
ii = textDict[text];
if (commandList[ii]) {
commandList[ii].command.push(key);
return;
}
try {
commandList[ii] = opt.rgxComment.exec(text);
commandList[ii] = {
argList: (commandList[ii][1] || "").trim(),
command: [
key
],
description: commandList[ii][2]
};
} catch (ignore) {
local.assertThrow(null, new Error(
"cliRun - cannot parse comment in COMMAND "
+ key
+ ":\nnew RegExp("
+ JSON.stringify(opt.rgxComment.source)
+ ").exec(" + JSON.stringify(text).replace((
/\\\\/g
), "\u0000").replace((
/\\n/g
), "\\n\\\n").replace((
/\u0000/g
), "\\\\") + ");"
));
}
});
text = "";
text += packageJson.name + " (" + packageJson.version + ")\n\n";
text += commandList.filter(function (elem) {
return elem;
}).map(function (elem, ii) {
elem.command = elem.command.filter(function (elem) {
return elem;
});
switch (ii) {
case 0:
case 1:
elem.argList = [
elem.argList
];
break;
default:
elem.argList = elem.argList.split(" ");
elem.description = (
"# COMMAND "
+ (elem.command[0] || "<none>") + "\n# &...
...
dir: process.argv[2],
modulePathList: module.paths
}));
};
// run the cli
if (module === require.main && !globalThis.utility2_rollup) {
local.cliRun();
}
}());
}());
...
function EventEmitter() { EventEmitter.init.call(this); }
n/a
functionOrNop = function (fnc) {
/*
* this function will if <fnc> exists,
* them return <fnc>,
* else return <nop>
*/
return fnc || local.nop;
}
...
if (element.isDescending) {
result.reverse();
}
});
// skip
result = result.slice(skip || 0);
// shuffle
local.functionOrNop(shuffle && local.listShuffle)(result);
// limit
result = result.slice(0, limit || Infinity);
return result;
};
local._DbTable.prototype._crudGetOneById = function (idDict) {
/*
...
identity = function (value) {
/*
* this function will return <value>
*/
return value;
}
...
local.cliDict.help = local.cliDict.help || local.cliDict._help;
local.cliDict._interactive = local.cliDict._interactive || function () {
/*
*
* will start interactive-mode
*/
globalThis.local = local;
local.identity(local.replStart || require("repl").start)({
useGlobal: true
});
};
local.cliDict["--interactive"] = (
local.cliDict["--interactive"]
|| local.cliDict._interactive
);
...
moduleDirname = function (module, modulePathList) {
/*
* this function will search modulePathList for the module's __dirname
*/
var result;
// search process.cwd()
if (!module || module === "." || module.indexOf("/") >= 0) {
return require("path").resolve(process.cwd(), module || "");
}
// search modulePathList
[
"node_modules"
]
.concat(modulePathList)
.concat(require("module").globalPaths)
.concat([
process.env.HOME + "/node_modules", "/usr/local/lib/node_modules"
])
.some(function (modulePath) {
try {
result = require("path").resolve(
process.cwd(),
modulePath + "/" + module
);
result = require("fs").statSync(result).isDirectory() && result;
return result;
} catch (ignore) {
result = null;
}
return result;
});
return result || "";
}
...
return match0.replace((
/(.{128}(?:\b|\w+))/g
), "$1\n").trimRight();
});
return text;
};
// init opt
opt.dir = local.moduleDirname(
opt.dir,
opt.modulePathList || require("module").paths
);
local.objectSetDefault(opt, {
env: {
npm_package_description: ""
},
...
nop = function () {
/*
* this function will do nothing
*/
return;
}
...
process.stdout._writeDefault = (
process.stdout._writeDefault
|| process.stdout._write
);
process.stdout._write = function (chunk, encoding, callback) {
process.stdout._writeDefault(chunk, encoding, callback);
// coverage-hack - ignore else-statement
local.nop(that.socket.writable && (function () {
that.socket.write(chunk, encoding);
}()));
};
// start serverRepl1
globalThis.utility2_serverRepl1 = require("net").createServer(function (
socket
) {
...
objectAssignDefault = function (target, source) {
/*
* this function will if items from <target> are
* null, undefined, or empty-string,
* then overwrite them with items from <source>
*/
target = target || {};
Object.keys(source || {}).forEach(function (key) {
if (
target[key] === null
|| target[key] === undefined
|| target[key] === ""
) {
target[key] = target[key] || source[key];
}
});
return target;
}
...
if (key[0] !== "_") {
xhr[key] = opt[key];
}
});
// init timeout
timeout = xhr.timeout || local2.timeoutDefault || 30000;
// init default
local.objectAssignDefault(xhr, {
corsForwardProxyHost: local2.corsForwardProxyHost,
headers: {},
location: (local.isBrowser && location) || {},
method: "GET",
responseType: ""
});
// init headers
...
objectSetDefault = function (dict, defaults, depth) {
/*
* this function will recursively set defaults for undefined-items in dict
*/
dict = dict || {};
defaults = defaults || {};
Object.keys(defaults).forEach(function (key) {
var defaults2;
var dict2;
dict2 = dict[key];
// handle misbehaving getter
try {
defaults2 = defaults[key];
} catch (ignore) {}
if (defaults2 === undefined) {
return;
}
// init dict[key] to default value defaults[key]
switch (dict2) {
case "":
case null:
case undefined:
dict[key] = defaults2;
return;
}
// if dict2 and defaults2 are both non-null and non-array objects,
// then recurse with dict2 and defaults2
if (
depth > 1
// dict2 is a non-null and non-array object
&& typeof dict2 === "object" && dict2 && !Array.isArray(dict2)
// defaults2 is a non-null and non-array object
&& typeof defaults2 === "object" && defaults2
&& !Array.isArray(defaults2)
) {
// recurse
local.objectSetDefault(dict2, defaults2, depth - 1);
}
});
return dict;
}
...
// dict2 is a non-null and non-array object
&& typeof dict2 === "object" && dict2 && !Array.isArray(dict2)
// defaults2 is a non-null and non-array object
&& typeof defaults2 === "object" && defaults2
&& !Array.isArray(defaults2)
) {
// recurse
local.objectSetDefault(dict2, defaults2, depth - 1);
}
});
return dict;
};
local.stringHtmlSafe = function (text) {
/*
...
function Stream() { EE.call(this); }
n/a
stringHtmlSafe = function (text) {
/*
* this function will make the text html-safe
* https://stackoverflow.com/questions/7381974/which-characters-need-to-be-escaped-on-html
*/
return text
.replace((
/&/g
), "&")
.replace((
/"/g
), """)
.replace((
/'/g
), "'")
.replace((
/</g
), "<")
.replace((
/>/g
), ">")
.replace((
/&(amp;|apos;|gt;|lt;|quot;)/ig
), "&$1");
}
...
)
// handle case where module is a function
.replace(">.<", "><");
if (elem.typeof !== "function") {
return elem;
}
// init source
elem.source = local.stringHtmlSafe(
trimLeft(toString(module[key])) || "n/a"
).replace((
/\([\S\s]*?\)/
), function (match0) {
// init signature
elem.signature = match0.replace((
/\u0020*?\/\*[\S\s]*?\*\/\u0020*/g
...
templateRender = function (template, dict, opt) {
/*
* this function will render the template with given dict
*/
var argList;
var getValue;
var match;
var renderPartial;
var rgx;
var skip;
var value;
dict = dict || {};
opt = opt || {};
getValue = function (key) {
argList = key.split(" ");
value = dict;
if (argList[0] === "#this/") {
return;
}
// iteratively lookup nested values in the dict
argList[0].split(".").forEach(function (key) {
value = value && value[key];
});
return value;
};
renderPartial = function (match0, helper, key, partial) {
switch (helper) {
case "each":
case "eachTrimRightComma":
value = getValue(key);
value = (
Array.isArray(value)
? value.map(function (dict) {
// recurse with partial
return local.templateRender(partial, dict, opt);
}).join("")
: ""
);
// remove trailing-comma from last elem
if (helper === "eachTrimRightComma") {
value = value.trimRight().replace((
/,$/
), "");
}
return value;
case "if":
partial = partial.split("{{#unless " + key + "}}");
partial = (
getValue(key)
? partial[0]
// handle 'unless' case
: partial.slice(1).join("{{#unless " + key + "}}")
);
// recurse with partial
return local.templateRender(partial, dict, opt);
case "unless":
return (
getValue(key)
? ""
// recurse with partial
: local.templateRender(partial, dict, opt)
);
default:
// recurse with partial
return match0[0] + local.templateRender(match0.slice(1), dict, opt);
}
};
// render partials
rgx = (
/\{\{#(\w+)\u0020([^}]+?)\}\}/g
);
template = template || "";
match = rgx.exec(template);
while (match) {
rgx.lastIndex += 1 - match[0].length;
template = template.replace(
new RegExp(
"\\{\\{#(" + match[1] + ") (" + match[2]
+ ")\\}\\}([\\S\\s]*?)\\{\\{/" + match[1] + " " + match[2]
+ "\\}\\}"
),
renderPartial
);
match = rgx.exec(template);
}
// search for keys in the template
return template.replace((
/\{\{[^}]+?\}\}/g
), function (match0) {
var markdownToHtml;
var notHtmlSafe;
notHtmlSafe = opt.notHtmlSafe;
try {
getValue(match0.slice(2, -2));
if (value === undefined) {
return match0;
}
argList.slice(1).forEach(function (arg0, ii, list) {
switch (arg0) {
case "alphanumeric":
value = value.replace((
/\W/g
), "_");
break;
case "decodeURIComponent":
value = decodeURIComponent(value);
break;
case "encodeURIComponent":
value = encodeURIComponent(value);
break;
case "jsonStringify":
value = JSON.stringify(value);
break;
case "jsonStringify4":
value = JSON.stringify(value, null, 4);
break;
case "markdownSafe&qu...
...
case "each":
case "eachTrimRightComma":
value = getValue(key);
value = (
Array.isArray(value)
? value.map(function (dict) {
// recurse with partial
return local.templateRender(partial, dict, opt);
}).join("")
: ""
);
// remove trailing-comma from last elem
if (helper === "eachTrimRightComma") {
value = value.trimRight().replace((
/,$/
...
tryCatchOnError = function (fnc, onError) {
/*
* this function will run the fnc in a tryCatch block,
* else call onError with errCaught
*/
var result;
// validate onError
local.assertThrow(typeof onError === "function", typeof onError);
try {
// reset errCaught
local._debugTryCatchError = null;
result = fnc();
local._debugTryCatchError = null;
return result;
} catch (errCaught) {
// debug errCaught
local._debugTryCatchError = errCaught;
return onError(errCaught);
}
}
...
return elem;
};
readExample = function (file) {
/*
* this function will read the example from given file
*/
var result;
local.tryCatchOnError(function () {
file = local.path.resolve(opt.dir, file);
console.error("apidocCreate - readExample " + file);
result = "";
result = (
"\n\n\n\n\n\n\n\n"
// bug-workaround - truncate example to manageable size
+ local.fs.readFileSync(file, "utf8").slice(0, 262144)
...
_default = function () {
/*
* <moduleDirectory>
* will create apidoc from <moduleDirectory>
*/
// jslint files
process.stdout.write(local.apidocCreate({
dir: process.argv[2],
modulePathList: module.paths
}));
}
...
local.cliDict._help();
return;
}
if (local.cliDict[process.argv[2]]) {
local.cliDict[process.argv[2]]();
return;
}
local.cliDict._default();
};
local.moduleDirname = function (module, modulePathList) {
/*
* this function will search modulePathList for the module's __dirname
*/
var result;
...
utility2.browserTest = function () {
/*
* <urlList> <mode>
* will browser-test in parallel, comma-separated <urlList> with given <mode>
*/
process.argv[3].split(
process.argv[3].indexOf("?") >= 0
? (
/\s/g
)
: (
/[,\s]/g
)
).filter(local.identity).forEach(function (url) {
local.browserTest({
url
}, local.onErrorDefault);
});
}
n/a
utility2.githubCrudContentDelete = function () {
/*
* <fileRemote|dirRemote> <commitMessage>
* will delete from github <fileRemote|dirRemote>
*/
local.github_crud.githubCrudContentDelete({
message: process.argv[4],
url: process.argv[3]
}, function (err) {
process.exit(Boolean(err));
});
}
n/a
utility2.githubCrudContentGet = function () {
/*
* <fileRemote>
* will get from github <fileRemote>
*/
local.github_crud.githubCrudContentGet({
url: process.argv[3]
}, function (err, data) {
try {
process.stdout.write(data);
} catch (ignore) {}
process.exit(Boolean(err));
});
}
n/a
utility2.githubCrudContentPut = function () {
/*
* <fileRemote> <fileLocal> <commitMessage>
* will put on github <fileRemote>, <fileLocal>
*/
local.github_crud.githubCrudContentPutFile({
message: process.argv[5],
url: process.argv[3],
file: process.argv[4]
}, function (err) {
process.exit(Boolean(err));
});
}
n/a
utility2.githubCrudContentTouch = function () {
/*
* <fileRemoteList> <commitMessage>
* will touch on github in parallel, comma-separated <fileRemoteList>
*/
local.github_crud.githubCrudContentTouchList({
message: process.argv[4],
urlList: process.argv[3].split(
/[,\s]/g
).filter(local.identity)
}, function (err) {
process.exit(Boolean(err));
});
}
n/a
utility2.githubCrudRepoCreate = function () {
/*
* <repoList>
* will create on github in parallel, comma-separated <repoList>
*/
local.github_crud.githubCrudRepoCreateList({
urlList: process.argv[3].split(
/[,\s]/g
).filter(local.identity)
}, function (err) {
process.exit(Boolean(err));
});
}
n/a
utility2.githubCrudRepoDelete = function () {
/*
* <repoList>
* will delete from github in parallel, comma-separated <repoList>
*/
local.github_crud.githubCrudRepoDeleteList({
urlList: process.argv[3].split(
/[,\s]/g
).filter(local.identity)
}, function (err) {
process.exit(Boolean(err));
});
}
n/a
utility2.start = function () {
/*
* <port>
* will start utility2 http-server on given <port> (default 8081)
*/
local.env.PORT = process.argv[3] || local.env.PORT;
globalThis.local = local;
local.replStart();
local.testRunServer({});
}
n/a
utility2.swaggerValidateFile = function () {
/*
* <file/url>
* will swagger-validate file/url
*/
setTimeout(function () {
local.swgg.swaggerValidateFile({
file: process.argv[3]
}, function (err, data) {
console.error(data);
process.exit(err);
});
});
}
n/a
utility2.testReportCreate = function () {
/*
*
* will create test-report
*/
local.exit(
local.testReportCreate(
JSON.parse(local.fs.readFileSync(
local.env.npm_config_dir_build + "/test-report.json"
))
).testsFailed
);
}
n/a
_DbTable = function (opt) {
/*
* this function will create a dbTable
*/
this.name = String(opt.name);
// register dbTable in dbTableDict
local.dbTableDict[this.name] = this;
this.dbRowList = [];
this.isDirty = null;
this.idIndexList = [
{
isInteger: false,
name: "_id",
dict: {}
}
];
this.onSaveList = [];
this.sizeLimit = opt.sizeLimit || 0;
}
n/a
function ok(...args) { innerOk(ok, args.length, ...args); }
...
key = '0123456789abcdef0123456789abcdef';
mode = null;
local.cryptoAesXxxCbcRawEncrypt({
data: data,
key: key,
mode: mode
}, function (err, data) {
console.assert(!err, err);
local.cryptoAesXxxCbcRawDecrypt({
data: data,
key: key,
mode: mode
}, console.log);
});
*/
...
assertThrow = function (passed, message) {
/*
* this function will throw err.<message> if <passed> is falsy
*/
var err;
if (passed) {
return;
}
err = (
// ternary-operator
(
message
&& typeof message.message === "string"
&& typeof message.stack === "string"
)
// if message is errObj, then leave as is
? message
: new Error(
typeof message === "string"
// if message is a string, then leave as is
? message
// else JSON.stringify message
: JSON.stringify(message, null, 4)
)
);
throw err;
}
...
argList: (commandList[ii][1] || "").trim(),
command: [
key
],
description: commandList[ii][2]
};
} catch (ignore) {
local.assertThrow(null, new Error(
"cliRun - cannot parse comment in COMMAND "
+ key
+ ":\nnew RegExp("
+ JSON.stringify(opt.rgxComment.source)
+ ").exec(" + JSON.stringify(text).replace((
/\\\\/g
), "\u0000").replace((
...
cliRun = function (opt) {
/*
* this function will run the cli with given <opt>
*/
local.cliDict._eval = local.cliDict._eval || function () {
/*
* <code>
* will eval <code>
*/
globalThis.local = local;
local.vm.runInThisContext(process.argv[3]);
};
local.cliDict["--eval"] = local.cliDict["--eval"] || local.cliDict._eval;
local.cliDict["-e"] = local.cliDict["-e"] || local.cliDict._eval;
local.cliDict._help = local.cliDict._help || function () {
/*
*
* will print help
*/
var commandList;
var file;
var packageJson;
var text;
var textDict;
commandList = [
{
argList: "<arg2> ...",
description: "usage:",
command: [
"<arg1>"
]
}, {
argList: "'console.log(\"hello world\")'",
description: "example:",
command: [
"--eval"
]
}
];
file = __filename.replace((
/.*\//
), "");
opt = Object.assign({}, opt);
packageJson = require("./package.json");
// validate comment
opt.rgxComment = opt.rgxComment || (
/\)\u0020\{\n(?:|\u0020{4})\/\*\n(?:\u0020|\u0020{5})\*((?:\u0020<[^>]*?>|\u0020\.\.\.)*?)\n(?:\u0020|\u0020{5})\*\u0020
(will\u0020.*?\S)\n(?:\u0020|\u0020{5})\*\/\n(?:\u0020{4}|\u0020{8})\S/
);
textDict = {};
Object.keys(local.cliDict).sort().forEach(function (key, ii) {
if (key[0] === "_" && key !== "_default") {
return;
}
text = String(local.cliDict[key]);
if (key === "_default") {
key = "";
}
textDict[text] = textDict[text] || (ii + 2);
ii = textDict[text];
if (commandList[ii]) {
commandList[ii].command.push(key);
return;
}
try {
commandList[ii] = opt.rgxComment.exec(text);
commandList[ii] = {
argList: (commandList[ii][1] || "").trim(),
command: [
key
],
description: commandList[ii][2]
};
} catch (ignore) {
local.assertThrow(null, new Error(
"cliRun - cannot parse comment in COMMAND "
+ key
+ ":\nnew RegExp("
+ JSON.stringify(opt.rgxComment.source)
+ ").exec(" + JSON.stringify(text).replace((
/\\\\/g
), "\u0000").replace((
/\\n/g
), "\\n\\\n").replace((
/\u0000/g
), "\\\\") + ");"
));
}
});
text = "";
text += packageJson.name + " (" + packageJson.version + ")\n\n";
text += commandList.filter(function (elem) {
return elem;
}).map(function (elem, ii) {
elem.command = elem.command.filter(function (elem) {
return elem;
});
switch (ii) {
case 0:
case 1:
elem.argList = [
elem.argList
];
break;
default:
elem.argList = elem.argList.split(" ");
elem.description = (
"# COMMAND "
+ (elem.command[0] || "<none>") + "\n# &...
...
dir: process.argv[2],
modulePathList: module.paths
}));
};
// run the cli
if (module === require.main && !globalThis.utility2_rollup) {
local.cliRun();
}
}());
}());
...
dbCrudRemoveAll = function (onError) {
/*
* this function will remove all dbRow's from the db
*/
var onParallel;
onParallel = local.onParallel(function (err) {
local.setTimeoutOnError(onError, 0, err);
});
onParallel.counter += 1;
Object.keys(local.dbTableDict).forEach(function (key) {
onParallel.counter += 1;
local.dbTableDict[key].crudRemoveAll(onParallel);
});
onParallel();
}
n/a
dbDrop = function (onError) {
/*
* this function will drop the db
*/
var onParallel;
console.error("db - dropping database ...");
onParallel = local.onParallel(function (err) {
local.setTimeoutOnError(onError, 0, err);
});
onParallel.counter += 1;
onParallel.counter += 1;
local.storageClear(onParallel);
Object.keys(local.dbTableDict).forEach(function (key) {
onParallel.counter += 1;
local.dbTableDict[key].drop(onParallel);
});
onParallel();
}
...
* this function will drop and seed the db with given dbSeedList
*/
var onParallel;
onParallel = globalThis.utility2_onReadyBefore || local.onParallel(onError);
onParallel.counter += 1;
// drop db
onParallel.counter += 1;
local.dbDrop(function (err) {
local.onErrorDefault(err);
// seed db
local.dbSeed(
dbSeedList,
!globalThis.utility2_onReadyBefore && onParallel
);
local.functionOrNop(globalThis.utility2_onReadyBefore)();
...
dbExport = function (onError) {
/*
* this function will export the db as serialized text
*/
var result;
result = "";
Object.keys(local.dbTableDict).forEach(function (key) {
console.error(
"db - exporting dbTable " + local.dbTableDict[key].name + " ..."
);
result += local.dbTableDict[key].export();
result += "\n\n";
});
return local.setTimeoutOnError(onError, 0, null, result.trim());
}
...
var tmp;
var utility2;
utility2 = globalThis.utility2 || {};
ajaxProgressUpdate = utility2.ajaxProgressUpdate || local.nop;
switch (evt.target.dataset.oneventDb) {
case "dbExport":
tmp = URL.createObjectURL(new globalThis.Blob([
local.dbExport()
]));
document.querySelector(
"#dbExportA1"
).href = tmp;
document.querySelector(
"#dbExportA1"
).click();
...
dbImport = function (text, onError) {
/*
* this function will import the serialized text into the db
*/
var dbTable;
var dbTableDict;
dbTableDict = {};
local.modeImport = true;
setTimeout(function () {
local.modeImport = null;
});
text.replace((
/^(\w\S*?)\u0020(\S+?)\u0020(\S.*?)$/gm
), function (match0, match1, match2, match3) {
switch (match2) {
case "dbRowSet":
dbTableDict[match1] = true;
dbTable = local.dbTableCreateOne({
isLoaded: true,
name: match1
});
dbTable.crudSetOneById(JSON.parse(match3));
break;
case "idIndexCreate":
dbTableDict[match1] = true;
dbTable = local.dbTableCreateOne({
isLoaded: true,
name: match1
});
dbTable.idIndexCreate(JSON.parse(match3));
break;
case "sizeLimit":
dbTableDict[match1] = true;
dbTable = local.dbTableCreateOne({
isLoaded: true,
name: match1
});
dbTable.sizeLimit = JSON.parse(match3);
break;
case "sortDefault":
dbTableDict[match1] = true;
dbTable = local.dbTableCreateOne({
isLoaded: true,
name: match1
});
dbTable.sortDefault = JSON.parse(match3);
break;
default:
local.onErrorDefault(new Error(
"db - dbImport - invalid operation - " + match0
));
}
});
Object.keys(dbTableDict).forEach(function (name) {
console.error("db - importing dbTable " + name + " ...");
});
local.modeImport = null;
return local.setTimeoutOnError(onError);
}
...
if (key.indexOf("dbTable.") !== 0) {
return;
}
onParallel.counter += 1;
local.storageGetItem(key, function (err, data) {
onParallel.counter += 1;
onParallel(err);
local.dbImport(data, onParallel);
});
});
onParallel();
});
};
local.dbReset = function (dbSeedList, onError) {
...
dbLoad = function (onError) {
/*
* this function will load the db from storage
*/
var onParallel;
onParallel = local.onParallel(function (err) {
local.setTimeoutOnError(onError, 0, err);
});
local.storageKeys(function (err, data) {
onParallel.counter += 1;
// validate no err occurred
onParallel.counter += 1;
onParallel(err);
(data || []).forEach(function (key) {
if (key.indexOf("dbTable.") !== 0) {
return;
}
onParallel.counter += 1;
local.storageGetItem(key, function (err, data) {
onParallel.counter += 1;
onParallel(err);
local.dbImport(data, onParallel);
});
});
onParallel();
});
}
n/a
dbReset = function (dbSeedList, onError) {
/*
* this function will drop and seed the db with given dbSeedList
*/
var onParallel;
onParallel = globalThis.utility2_onReadyBefore || local.onParallel(onError);
onParallel.counter += 1;
// drop db
onParallel.counter += 1;
local.dbDrop(function (err) {
local.onErrorDefault(err);
// seed db
local.dbSeed(
dbSeedList,
!globalThis.utility2_onReadyBefore && onParallel
);
local.functionOrNop(globalThis.utility2_onReadyBefore)();
});
local.functionOrNop(globalThis.utility2_onReadyAfter)(onError);
onParallel();
}
...
local.dbImport(reader.result);
ajaxProgressUpdate();
});
reader.readAsText(evt.target.files[0]);
break;
case "dbReset":
ajaxProgressUpdate();
local.dbReset(globalThis.utility2_dbSeedList, function (err) {
local.onErrorDefault(err);
if (
utility2.uiEventListenerDict
&& typeof utility2.uiEventListenerDict[".onEventUiReload"]
=== "function"
) {
utility2.uiEventListenerDict[".onEventUiReload"]();
...
dbRowGetItem = function (dbRow, key) {
/*
* this function will get the item with given key from dbRow
*/
var ii;
var value;
value = dbRow;
key = String(key).split(".");
// optimization - while-loop
ii = 0;
while (ii < key.length && typeof value === "object" && value) {
value = value[key[ii]];
ii += 1;
}
return (
value === undefined
? null
: value
);
}
...
ii = 0;
while (ii < result.length) {
result[ii].$ii = ii;
ii += 1;
}
result.sort(function (aa, bb) {
return local.sortCompare(
local.dbRowGetItem(aa, element.fieldName),
local.dbRowGetItem(bb, element.fieldName),
aa.$ii,
bb.$ii
);
});
if (element.isDescending) {
result.reverse();
...
dbRowListGetManyByOperator = function ( dbRowList, fieldName, operator, bb, not ) {
/*
* this function will get the dbRow's in dbRowList with given operator
*/
var fieldValue;
var ii;
var jj;
var result;
var test;
var typeof2;
result = [];
typeof2 = typeof bb;
if (bb && typeof2 === "object") {
switch (operator) {
case "$in":
case "$nin":
case "$regex":
break;
default:
return result;
}
}
switch (operator) {
case "$eq":
test = function (aa, bb) {
return aa === bb;
};
break;
case "$exists":
bb = !bb;
test = function (aa, bb) {
return !((aa === null) ^ bb); // jslint ignore:line
};
break;
case "$gt":
test = function (aa, bb, typeof1, typeof2) {
return typeof1 === typeof2 && aa > bb;
};
break;
case "$gte":
test = function (aa, bb, typeof1, typeof2) {
return typeof1 === typeof2 && aa >= bb;
};
break;
case "$in":
if (bb && typeof bb.indexOf === "function") {
if (typeof2 === "string") {
test = function (aa, bb, typeof1, typeof2) {
return typeof1 === typeof2 && bb.indexOf(aa) >= 0;
};
} else {
test = function (aa, bb) {
return bb.indexOf(aa) >= 0;
};
}
}
break;
case "$lt":
test = function (aa, bb, typeof1, typeof2) {
return typeof1 === typeof2 && aa < bb;
};
break;
case "$lte":
test = function (aa, bb, typeof1, typeof2) {
return typeof1 === typeof2 && aa <= bb;
};
break;
case "$ne":
test = function (aa, bb) {
return aa !== bb;
};
break;
case "$nin":
if (bb && typeof bb.indexOf === "function") {
if (typeof2 === "string") {
test = function (aa, bb, typeof1, typeof2) {
return typeof1 === typeof2 && bb.indexOf(aa) < 0;
};
} else {
test = function (aa, bb) {
return bb.indexOf(aa) < 0;
};
}
}
break;
case "$regex":
if (bb && typeof bb.test === "function") {
test = function (aa, bb) {
return bb.test(aa);
};
}
break;
case "$typeof":
test = function (ignore, bb, typeof1) {
return typeof1 === bb;
};
break;
}
if (!test) {
return result;
}
// optimization - while-loop
ii = dbRowList.length;
while (ii >= 1) {
ii -= 1;
fieldValue = local.dbRowGetItem(dbRowList[ii], fieldName);
// normalize to list
if (!Array.isArray(fieldValue)) {
fieldValue = [
fieldValue
];
}
// optimization - while-loop
jj = fieldValue.length;
while (jj >= 1) {
jj -= 1;
if (Boolean(
not ^ test(fieldValue[jj], bb, typeof fieldValue[jj], typeof2)
)) {
result.push(dbRowList[ii]);
break;
}
}
}
return result;
}
...
var bb;
var dbRowDict;
var result;
// optimization - convert to boolean
not = Boolean(not);
result = dbRowList;
if (!(typeof query === "object" && query)) {
result = local.dbRowListGetManyByOperator(
result,
fieldName,
"$eq",
query,
not
);
return result;
...
dbRowListGetManyByQuery = function (dbRowList, query, fieldName, not) {
/*
* this function will get the dbRow's in dbRowList with given query
*/
var bb;
var dbRowDict;
var result;
// optimization - convert to boolean
not = Boolean(not);
result = dbRowList;
if (!(typeof query === "object" && query)) {
result = local.dbRowListGetManyByOperator(
result,
fieldName,
"$eq",
query,
not
);
return result;
}
Object.keys(query).some(function (key) {
bb = query[key];
switch (key) {
case "$not":
key = fieldName;
not = !not;
break;
case "$or":
if (!Array.isArray(bb)) {
break;
}
dbRowDict = {};
bb.forEach(function (query) {
// recurse
local.dbRowListGetManyByQuery(result, query).forEach(function (
dbRow
) {
dbRowDict[dbRow._id] = dbRow;
});
});
result = Object.keys(dbRowDict).map(function (id) {
return dbRowDict[id];
});
return !result.length;
}
if (key[0] === "$") {
result = local.dbRowListGetManyByOperator(
result,
fieldName,
key,
bb,
not
);
return !result.length;
}
// recurse
result = local.dbRowListGetManyByQuery(result, bb, key, not);
return !result.length;
});
return result;
}
...
* with given query, sort, skip, and limit
*/
var ii;
var result;
result = this.dbRowList;
// get by query
if (result.length && query && Object.keys(query).length) {
result = local.dbRowListGetManyByQuery(this.dbRowList, query);
}
// sort
(sort || []).forEach(function (element) {
// bug-workaround - v8 does not have stable-sort
// optimization - while-loop
ii = 0;
while (ii < result.length) {
...
dbRowProject = function (dbRow, fieldList) {
/*
* this function will deepcopy and project the dbRow with given fieldList
*/
var result;
if (!dbRow) {
return null;
}
// handle list-case
if (Array.isArray(dbRow)) {
return dbRow.map(function (dbRow) {
// recurse
return local.dbRowProject(dbRow, fieldList);
});
}
// normalize to list
if (!(Array.isArray(fieldList) && fieldList.length)) {
fieldList = Object.keys(dbRow);
}
result = {};
fieldList.forEach(function (key) {
if (key[0] !== "$") {
result[key] = dbRow[key];
}
});
return JSON.parse(local.jsonStringifyOrdered(result));
}
...
local._DbTable.prototype.crudGetManyById = function (idDictList, onError) {
/*
* this function will get the dbRow's in the dbTable with given idDictList
*/
var that;
this._cleanup();
that = this;
return local.setTimeoutOnError(onError, 0, null, local.dbRowProject(
(idDictList || []).map(function (idDict) {
return that._crudGetOneById(idDict);
})
));
};
local._DbTable.prototype.crudGetManyByQuery = function (opt, onError) {
...
dbRowSetId = function (dbRow, idIndex) {
/*
* this function will if does not exist,
* then set a random and unique id into dbRow for given idIndex,
*/
var id;
id = dbRow[idIndex.name];
if (typeof id !== "number" && typeof id !== "string") {
do {
id = (
idIndex.isInteger
? (1 + Math.random()) * 0x10000000000000
: "a" + (
(1 + Math.random()) * 0x10000000000000
).toString(36).slice(1)
);
// optimization - hasOwnProperty
} while (idIndex.dict.hasOwnProperty(id));
dbRow[idIndex.name] = id;
}
return id;
}
...
// normalize
dbRow = normalize(dbRow);
dbRow = local.jsonCopy(dbRow);
// remove existing dbRow
existing = this._crudRemoveOneById(dbRow) || dbRow;
this.idIndexList.forEach(function (idIndex) {
// auto-set id
id = local.dbRowSetId(existing, idIndex);
// copy id from existing to dbRow
dbRow[idIndex.name] = id;
// set dbRow
idIndex.dict[id] = dbRow;
});
// update dbRowList
this.dbRowList.push(dbRow);
...
dbSave = function (onError) {
/*
* this function will save the db to storage
*/
var onParallel;
onParallel = local.onParallel(function (err) {
local.setTimeoutOnError(onError, 0, err);
});
onParallel.counter += 1;
Object.keys(local.dbTableDict).forEach(function (key) {
onParallel.counter += 1;
local.dbTableDict[key].save(onParallel);
});
onParallel();
}
n/a
dbSeed = function (dbSeedList, onError) {
/*
* this function will seed the db with given dbSeedList
*/
var dbTableDict;
var onParallel;
dbTableDict = {};
onParallel = globalThis.utility2_onReadyBefore || local.onParallel(onError);
onParallel.counter += 1;
// seed db
onParallel.counter += 1;
local.dbTableCreateMany(dbSeedList, onParallel);
(dbSeedList || []).forEach(function (opt) {
dbTableDict[opt.name] = true;
});
Object.keys(dbTableDict).forEach(function (name) {
console.error("db - seeding dbTable " + name + " ...");
});
local.functionOrNop(globalThis.utility2_onReadyAfter)(onError);
onParallel();
}
...
onParallel = globalThis.utility2_onReadyBefore || local.onParallel(onError);
onParallel.counter += 1;
// drop db
onParallel.counter += 1;
local.dbDrop(function (err) {
local.onErrorDefault(err);
// seed db
local.dbSeed(
dbSeedList,
!globalThis.utility2_onReadyBefore && onParallel
);
local.functionOrNop(globalThis.utility2_onReadyBefore)();
});
local.functionOrNop(globalThis.utility2_onReadyAfter)(onError);
onParallel();
...
dbTableCreateMany = function (optionList, onError) {
/*
* this function will create many dbTables with given optionList
*/
var onParallel;
var result;
onParallel = local.onParallel(function (err) {
local.setTimeoutOnError(onError, 0, err, result);
});
onParallel.counter += 1;
result = (optionList || []).map(function (opt) {
onParallel.counter += 1;
return local.dbTableCreateOne(opt, onParallel);
});
return local.setTimeoutOnError(onParallel, 0, null, result);
}
...
var dbTableDict;
var onParallel;
dbTableDict = {};
onParallel = globalThis.utility2_onReadyBefore || local.onParallel(onError);
onParallel.counter += 1;
// seed db
onParallel.counter += 1;
local.dbTableCreateMany(dbSeedList, onParallel);
(dbSeedList || []).forEach(function (opt) {
dbTableDict[opt.name] = true;
});
Object.keys(dbTableDict).forEach(function (name) {
console.error("db - seeding dbTable " + name + " ...");
});
local.functionOrNop(globalThis.utility2_onReadyAfter)(onError);
...
dbTableCreateOne = function (opt, onError) {
/*
* this function will create a dbTable with given <opt>
*/
var DbTable;
var that;
opt = local.objectSetOverride(opt);
// register dbTable
DbTable = local._DbTable;
local.dbTableDict[opt.name] = local.dbTableDict[opt.name] || new DbTable(
opt
);
that = local.dbTableDict[opt.name];
that.sortDefault = (
opt.sortDefault
|| that.sortDefault
|| [
{
fieldName: "_timeUpdated",
isDescending: true
}
]
);
// remove idIndex
(opt.idIndexRemoveList || []).forEach(function (idIndex) {
that.idIndexRemove(idIndex);
});
// create idIndex
(opt.idIndexCreateList || []).forEach(function (idIndex) {
that.idIndexCreate(idIndex);
});
// upsert dbRow
that.crudSetManyById(opt.dbRowList);
// restore dbTable from persistent-storage
that.isLoaded = that.isLoaded || opt.isLoaded;
if (!that.isLoaded) {
local.storageGetItem("dbTable." + that.name + ".json", function (
err,
data
) {
// validate no err occurred
local.assertThrow(!err, err);
if (!that.isLoaded) {
local.dbImport(data);
}
that.isLoaded = true;
local.setTimeoutOnError(onError, 0, null, that);
});
return that;
}
return local.setTimeoutOnError(onError, 0, null, that);
}
...
* https://github.com/kaizhu256/node-db-lite
* this zero-dependency package will provide a persistent, in-browser database, with a working web-demo
*
* browser example:
<script src="assets.db-lite.js"></script>
<script>
var dbTable1;
dbTable1 = window.dbTable1 = window.utility2_db.dbTableCreateOne({
name: "dbTable1"
});
dbTable1.idIndexCreate({ name: "field1" });
dbTable1.crudSetOneById({ field1: "hello", field2: "world" });
console.log(dbTable1.crudGetManyByQuery({
limit: Infinity,
query: { field1: "hello" },
...
function EventEmitter() { EventEmitter.init.call(this); }
n/a
functionOrNop = function (fnc) {
/*
* this function will if <fnc> exists,
* them return <fnc>,
* else return <nop>
*/
return fnc || local.nop;
}
...
if (element.isDescending) {
result.reverse();
}
});
// skip
result = result.slice(skip || 0);
// shuffle
local.functionOrNop(shuffle && local.listShuffle)(result);
// limit
result = result.slice(0, limit || Infinity);
return result;
};
local._DbTable.prototype._crudGetOneById = function (idDict) {
/*
...
identity = function (value) {
/*
* this function will return <value>
*/
return value;
}
...
local.cliDict.help = local.cliDict.help || local.cliDict._help;
local.cliDict._interactive = local.cliDict._interactive || function () {
/*
*
* will start interactive-mode
*/
globalThis.local = local;
local.identity(local.replStart || require("repl").start)({
useGlobal: true
});
};
local.cliDict["--interactive"] = (
local.cliDict["--interactive"]
|| local.cliDict._interactive
);
...
jsonCopy = function (obj) {
/*
* this function will deep-copy obj
*/
return (
obj === undefined
? undefined
: JSON.parse(JSON.stringify(obj))
);
}
...
? undefined
// recurse
: normalize(dbRow[key])
);
});
return dbRow;
};
dbRow = local.jsonCopy(local.objectSetOverride(dbRow));
// update timestamp
timeNow = new Date().toISOString();
dbRow._timeCreated = dbRow._timeCreated || timeNow;
if (!local.modeImport) {
dbRow._timeUpdated = timeNow;
}
// normalize
...
jsonStringifyOrdered = function (obj, replacer, space) {
/*
* this function will JSON.stringify <obj>,
* with object-keys sorted and circular-references removed
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Syntax
*/
var circularSet;
var stringify;
var tmp;
stringify = function (obj) {
/*
* this function will recursively JSON.stringify obj,
* with object-keys sorted and circular-references removed
*/
// if obj is not an object or function, then JSON.stringify as normal
if (!(
obj
&& typeof obj === "object"
&& typeof obj.toJSON !== "function"
)) {
return JSON.stringify(obj);
}
// ignore circular-reference
if (circularSet.has(obj)) {
return;
}
circularSet.add(obj);
// if obj is an array, then recurse its items
if (Array.isArray(obj)) {
tmp = "[" + obj.map(function (obj) {
// recurse
tmp = stringify(obj);
return (
typeof tmp === "string"
? tmp
: "null"
);
}).join(",") + "]";
circularSet.delete(obj);
return tmp;
}
// if obj is not an array,
// then recurse its items with object-keys sorted
tmp = "{" + Object.keys(obj).sort().map(function (key) {
// recurse
tmp = stringify(obj[key]);
if (typeof tmp === "string") {
return JSON.stringify(key) + ":" + tmp;
}
}).filter(function (obj) {
return typeof obj === "string";
}).join(",") + "}";
circularSet.delete(obj);
return tmp;
};
circularSet = new Set();
return JSON.stringify((
(typeof obj === "object" && obj)
// recurse
? JSON.parse(stringify(obj))
: obj
), replacer, space);
}
...
}
result = {};
fieldList.forEach(function (key) {
if (key[0] !== "$") {
result[key] = dbRow[key];
}
});
return JSON.parse(local.jsonStringifyOrdered(result));
};
local.dbRowSetId = function (dbRow, idIndex) {
/*
* this function will if does not exist,
* then set a random and unique id into dbRow for given idIndex,
*/
...
listShuffle = function (list) {
/*
* this function will inplace shuffle <list> using fisher-yates algorithm
* https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
*/
var ii;
var random;
var swap;
ii = list.length;
while (ii > 1) {
ii -= 1;
random = Math.floor(Math.random() * (ii + 1));
swap = list[ii];
list[ii] = list[random];
list[random] = swap;
}
return list;
}
...
opt = {};
// init list
opt.list = "[0,1]";
// shuffle list 100 times
opt.ii = 0;
while (opt.ii < 100) {
opt.listShuffled = JSON.stringify(
local.listShuffle(JSON.parse(opt.list))
);
// validate shuffled list
local.assertJsonEqual(opt.listShuffled.length, opt.list.length);
opt.changed = opt.changed || opt.listShuffled !== opt.list;
opt.ii += 1;
}
// validate list changed at least once during the shuffle
...
nop = function () {
/*
* this function will do nothing
*/
return;
}
...
process.stdout._writeDefault = (
process.stdout._writeDefault
|| process.stdout._write
);
process.stdout._write = function (chunk, encoding, callback) {
process.stdout._writeDefault(chunk, encoding, callback);
// coverage-hack - ignore else-statement
local.nop(that.socket.writable && (function () {
that.socket.write(chunk, encoding);
}()));
};
// start serverRepl1
globalThis.utility2_serverRepl1 = require("net").createServer(function (
socket
) {
...
objectAssignDefault = function (target, source) {
/*
* this function will if items from <target> are
* null, undefined, or empty-string,
* then overwrite them with items from <source>
*/
target = target || {};
Object.keys(source || {}).forEach(function (key) {
if (
target[key] === null
|| target[key] === undefined
|| target[key] === ""
) {
target[key] = target[key] || source[key];
}
});
return target;
}
...
if (key[0] !== "_") {
xhr[key] = opt[key];
}
});
// init timeout
timeout = xhr.timeout || local2.timeoutDefault || 30000;
// init default
local.objectAssignDefault(xhr, {
corsForwardProxyHost: local2.corsForwardProxyHost,
headers: {},
location: (local.isBrowser && location) || {},
method: "GET",
responseType: ""
});
// init headers
...
objectSetOverride = function (dict, overrides, depth, env) {
/*
* this function will recursively set overrides for items in dict
*/
dict = dict || {};
env = env || (typeof process === "object" && process.env) || {};
overrides = overrides || {};
Object.keys(overrides).forEach(function (key) {
var dict2;
var overrides2;
dict2 = dict[key];
overrides2 = overrides[key];
if (overrides2 === undefined) {
return;
}
// if both dict2 and overrides2 are non-null and non-array objects,
// then recurse with dict2 and overrides2
if (
depth > 1
// dict2 is a non-null and non-array object
&& typeof dict2 === "object" && dict2 && !Array.isArray(dict2)
// overrides2 is a non-null and non-array object
&& typeof overrides2 === "object" && overrides2
&& !Array.isArray(overrides2)
) {
local.objectSetOverride(dict2, overrides2, depth - 1, env);
return;
}
// else set dict[key] with overrides[key]
dict[key] = (
dict === env
// if dict is env, then overrides falsy-value with empty-string
? overrides2 || ""
: overrides2
);
});
return dict;
}
...
depth > 1
// dict2 is a non-null and non-array object
&& typeof dict2 === "object" && dict2 && !Array.isArray(dict2)
// overrides2 is a non-null and non-array object
&& typeof overrides2 === "object" && overrides2
&& !Array.isArray(overrides2)
) {
local.objectSetOverride(dict2, overrides2, depth - 1, env);
return;
}
// else set dict[key] with overrides[key]
dict[key] = (
dict === env
// if dict is env, then overrides falsy-value with empty-string
? overrides2 || ""
...
onErrorDefault = function (err) {
/*
* this function will if <err> exists, then print it to stderr
*/
if (err) {
console.error(err);
}
return err;
}
...
dbTable = local.dbTableCreateOne({
isLoaded: true,
name: match1
});
dbTable.sortDefault = JSON.parse(match3);
break;
default:
local.onErrorDefault(new Error(
"db - dbImport - invalid operation - " + match0
));
}
});
Object.keys(dbTableDict).forEach(function (name) {
console.error("db - importing dbTable " + name + " ...");
});
...
onErrorWithStack = function (onError) {
/*
* this function will create wrapper around <onError>
* that will append current-stack to err.stack
*/
var onError2;
var stack;
stack = new Error().stack.replace((
/(.*?)\n.*?$/m
), "$1");
onError2 = function (err, data, meta) {
if (
err
&& typeof err.stack === "string"
&& err !== local.errDefault
&& String(err.stack).indexOf(stack.split("\n")[2]) < 0
) {
// append current-stack to err.stack
err.stack += "\n" + stack;
}
onError(err, data, meta);
};
// debug onError
onError2.toString = function () {
return String(onError);
};
return onError2;
}
...
local.onParallel = function (onError, onEach, onRetry) {
/*
* this function will create a function that will
* 1. run async tasks in parallel
* 2. if counter === 0 or err occurred, then call onError(err)
*/
var onParallel;
onError = local.onErrorWithStack(onError);
onEach = onEach || local.nop;
onRetry = onRetry || local.nop;
onParallel = function (err, data) {
if (onRetry(err, data)) {
return;
}
// decrement counter
...
onEventDomDb = function (evt) {
/*
* this function will handle db dom-events
*/
var ajaxProgressUpdate;
var reader;
var tmp;
var utility2;
utility2 = globalThis.utility2 || {};
ajaxProgressUpdate = utility2.ajaxProgressUpdate || local.nop;
switch (evt.target.dataset.oneventDb) {
case "dbExport":
tmp = URL.createObjectURL(new globalThis.Blob([
local.dbExport()
]));
document.querySelector(
"#dbExportA1"
).href = tmp;
document.querySelector(
"#dbExportA1"
).click();
setTimeout(function () {
URL.revokeObjectURL(tmp);
}, 30000);
break;
case "dbImport":
document.querySelector(
"[data-onevent-db='dbImportInput']"
).click();
break;
case "dbImportInput":
if (evt.type !== "change") {
return;
}
ajaxProgressUpdate();
reader = new FileReader();
reader.addEventListener("load", function () {
local.dbImport(reader.result);
ajaxProgressUpdate();
});
reader.readAsText(evt.target.files[0]);
break;
case "dbReset":
ajaxProgressUpdate();
local.dbReset(globalThis.utility2_dbSeedList, function (err) {
local.onErrorDefault(err);
if (
utility2.uiEventListenerDict
&& typeof utility2.uiEventListenerDict[".onEventUiReload"]
=== "function"
) {
utility2.uiEventListenerDict[".onEventUiReload"]();
}
});
break;
}
}
n/a
onParallel = function (onError, onEach, onRetry) {
/*
* this function will create a function that will
* 1. run async tasks in parallel
* 2. if counter === 0 or err occurred, then call onError(err)
*/
var onParallel;
onError = local.onErrorWithStack(onError);
onEach = onEach || local.nop;
onRetry = onRetry || local.nop;
onParallel = function (err, data) {
if (onRetry(err, data)) {
return;
}
// decrement counter
onParallel.counter -= 1;
// validate counter
if (!(onParallel.counter >= 0 || err || onParallel.err)) {
err = new Error(
"invalid onParallel.counter = " + onParallel.counter
);
// ensure onError is run only once
} else if (onParallel.counter < 0) {
return;
}
// handle err
if (err) {
onParallel.err = err;
// ensure counter <= 0
onParallel.counter = -Math.abs(onParallel.counter);
}
// call onError when isDone
if (onParallel.counter <= 0) {
onError(err, data);
return;
}
onEach();
};
// init counter
onParallel.counter = 0;
// return callback
return onParallel;
}
...
};
local.dbCrudRemoveAll = function (onError) {
/*
* this function will remove all dbRow's from the db
*/
var onParallel;
onParallel = local.onParallel(function (err) {
local.setTimeoutOnError(onError, 0, err);
});
onParallel.counter += 1;
Object.keys(local.dbTableDict).forEach(function (key) {
onParallel.counter += 1;
local.dbTableDict[key].crudRemoveAll(onParallel);
});
...
replStart = function () {
/*
* this function will start the repl-debugger
*/
var that;
if (globalThis.utility2_repl1) {
return;
}
// start repl
that = require("repl").start({
useGlobal: true
});
globalThis.utility2_repl1 = that;
that.onError = function (err) {
/*
* this function will debug repl-err
*/
globalThis.utility2_debugReplError = err;
console.error(err);
};
// save eval-function
that.evalDefault = that.eval;
// hook custom-eval-function
that.eval = function (script, context, file, onError) {
var onError2;
onError2 = function (err, data) {
// debug err
globalThis.utility2_debugReplError = (
err || globalThis.utility2_debugReplError
);
onError(err, data);
};
script.replace((
/^(\S+)\u0020(.*?)\n/
), function (ignore, match1, match2) {
switch (match1) {
// syntax-sugar - run async shell-command
case "$":
switch (match2) {
// syntax-sugar - run git diff
case "git diff":
match2 = "git diff --color | cat";
break;
// syntax-sugar - run git log
case "git log":
match2 = "git log -n 4 | cat";
break;
// syntax-sugar - run git log
case "ll":
match2 = "ls -Fal";
break;
}
// source lib.utility2.sh
if (
process.platform !== "win32"
&& process.env.npm_config_dir_utility2 && (match2 !== ":")
) {
match2 = (
". " + process.env.npm_config_dir_utility2
+ "/lib.utility2.sh;" + match2
);
}
// run async shell-command
require("child_process").spawn(match2, {
shell: true,
stdio: [
"ignore", 1, 2
]
// on shell exit, print return prompt
}).on("exit", function (exitCode) {
console.error("exit-code " + exitCode);
that.evalDefault(
"\n",
context,
file,
onError2
);
});
script = "\n";
break;
// syntax-sugar - map text with charCodeAt
case "charCode":
console.error(
match2.split("").map(function (chr) {
return (
"\\u"
+ chr.charCodeAt(0).toString(16).padStart(4, 0)
);
}).join("")
);
script = "\n";
break;
// syntax-sugar - sort chr
case "charSort":
console.error(JSON.stringify(match2.split("").sort().join("")));
script = "\n";
break;
// syntax-sugar - grep current dir
case "grep":
// run async shell-command
require("child_process").spawn((
"find . -type f | grep -v -E "
/* jslint ignore:start */
+ '"\
/\\.|(\\b|_)(\\.\\d|\
archive|artifact|\
bower_component|build|\
coverage|\
doc|\
external|\
fixture|\
git_module|\
jquery|\
log|\
min|misc|mock|\
node_module|\
raw|\rollup|\
swp|\
tmp|\
v...
...
local.cliDict["utility2.start"] = function () {
/*
* <port>
* will start utility2 http-server on given <port> (default 8081)
*/
local.env.PORT = process.argv[3] || local.env.PORT;
globalThis.local = local;
local.replStart();
local.testRunServer({});
};
local.cliDict["utility2.swaggerValidateFile"] = function () {
/*
* <file/url>
* will swagger-validate file/url
...
setTimeoutOnError = function (onError, timeout, err, data) {
/*
* this function will after timeout has passed,
* then call <onError>(<err>, <data>)
*/
if (typeof onError === "function") {
setTimeout(function () {
onError(err, data);
}, timeout);
}
return data;
}
...
};
local._DbTable.prototype.crudCountAll = function (onError) {
/*
* this function will count all of dbRow's in dbTable
*/
this._cleanup();
return local.setTimeoutOnError(onError, 0, null, this.dbRowList.length);
};
local._DbTable.prototype.crudCountManyByQuery = function (query, onError) {
/*
* this function will count the number of dbRow's in dbTable with given query
*/
this._cleanup();
...
sortCompare = function (aa, bb, ii, jj) {
/*
* this function will compare aa vs bb and return:
* -1 if aa < bb
* 0 if aa === bb
* 1 if aa > bb
* the priority for comparing different typeof's is:
* null < boolean < number < string < object < undefined
*/
var typeof1;
var typeof2;
if (aa === bb) {
return (
ii < jj
? -1
: 1
);
}
if (aa === null) {
return -1;
}
if (bb === null) {
return 1;
}
typeof1 = typeof aa;
typeof2 = typeof bb;
if (typeof1 === typeof2) {
return (
typeof1 === "object"
? 0
: aa > bb
? 1
: -1
);
}
if (typeof1 === "boolean") {
return -1;
}
if (typeof2 === "boolean") {
return 1;
}
if (typeof1 === "number") {
return -1;
}
if (typeof2 === "number") {
return 1;
}
if (typeof1 === "string") {
return -1;
}
if (typeof2 === "string") {
return 1;
}
return 0;
}
...
// optimization - while-loop
ii = 0;
while (ii < result.length) {
result[ii].$ii = ii;
ii += 1;
}
result.sort(function (aa, bb) {
return local.sortCompare(
local.dbRowGetItem(aa, element.fieldName),
local.dbRowGetItem(bb, element.fieldName),
aa.$ii,
bb.$ii
);
});
if (element.isDescending) {
...
storageClear = function (onError) {
/*
* this function will clear storage
*/
defer({
action: "clear"
}, onError);
}
...
var onParallel;
console.error("db - dropping database ...");
onParallel = local.onParallel(function (err) {
local.setTimeoutOnError(onError, 0, err);
});
onParallel.counter += 1;
onParallel.counter += 1;
local.storageClear(onParallel);
Object.keys(local.dbTableDict).forEach(function (key) {
onParallel.counter += 1;
local.dbTableDict[key].drop(onParallel);
});
onParallel();
};
...
storageDefer = function (opt, onError) {
/*
* this function will defer <opt>.action until storage is ready
*/
var data;
var isDone;
var objectStore;
var onError2;
var req;
var tmp;
onError = onError || function (err) {
// validate no err occurred
local.assertThrow(!err, err);
};
if (!storage) {
deferList.push(function () {
defer(opt, onError);
});
init();
return;
}
if (local.isBrowser) {
onError2 = function () {
/* istanbul ignore next */
if (isDone) {
return;
}
isDone = true;
onError(
req && (req.error || req.transaction.error),
data || req.result || ""
);
};
switch (opt.action) {
case "clear":
case "removeItem":
case "setItem":
objectStore = storage
.transaction(storageDir, "readwrite")
.objectStore(storageDir);
break;
default:
objectStore = storage
.transaction(storageDir, "readonly")
.objectStore(storageDir);
}
switch (opt.action) {
case "clear":
req = objectStore.clear();
break;
case "getItem":
req = objectStore.get(String(opt.key));
break;
case "keys":
data = [];
req = objectStore.openCursor();
req.onsuccess = function () {
if (!req.result) {
onError2();
return;
}
data.push(req.result.key);
req.result.continue();
};
break;
case "length":
req = objectStore.count();
break;
case "removeItem":
req = objectStore.delete(String(opt.key));
break;
case "setItem":
req = objectStore.put(opt.value, String(opt.key));
break;
}
[
"onabort", "onerror", "onsuccess"
].forEach(function (handler) {
req[handler] = req[handler] || onError2;
});
// debug req
local._debugStorageReq = req;
} else {
switch (opt.action) {
case "clear":
child_process.spawnSync("rm -f " + storage + "/*", {
shell: true,
stdio: [
"ignore", 1, 2
]
});
setTimeout(onError);
break;
case "getItem":
fs.readFile(
storage + "/" + encodeURIComponent(String(opt.key)),
"utf8",
function (ignore, data) {
onError(null, data || "");
}
);
break;
case "keys":
fs.readdir(storage, function (err, data) {
onError(err, data && data.map(decodeURIComponent));
});
break;
case "length":
fs.readdir(storage, function (err, data) {
onError(err, data && data.length);
});
break;
case "removeItem":
fs.unlink(
storage + "/" + encodeURIComponent(String(opt.key)),
// ignore err
function () {
onError();
}
);
break;
case "setItem":
tmp = os.tmpdir() + "/" + Date.now() + Math.random();
// save to tmp
fs.writeFile(tmp, opt.value, function (err) {
// validate no err occurred
local.assertThrow(!e...
n/a
storageGetItem = function (key, onError) {
/*
* this function will get the item with given key from storage
*/
defer({
action: "getItem",
key
}, onError);
}
...
onParallel.counter += 1;
onParallel(err);
(data || []).forEach(function (key) {
if (key.indexOf("dbTable.") !== 0) {
return;
}
onParallel.counter += 1;
local.storageGetItem(key, function (err, data) {
onParallel.counter += 1;
onParallel(err);
local.dbImport(data, onParallel);
});
});
onParallel();
});
...
storageInit = function () {
/*
* this function will init storage
*/
var onError;
var req;
onError = function (err) {
// validate no err occurred
local.assertThrow(!err, err);
if (local.isBrowser) {
storage = globalThis[storageDir];
}
while (deferList.length) {
deferList.shift()();
}
};
if (local.isBrowser) {
storage = globalThis[storageDir];
}
if (storage) {
onError();
return;
}
if (local.isBrowser) {
// init indexedDB
try {
req = globalThis.indexedDB.open(storageDir);
// debug req
local._debugStorageReqIndexedDB = req;
req.onerror = onError;
req.onsuccess = function () {
globalThis[storageDir] = req.result;
onError();
};
req.onupgradeneeded = function () {
if (!req.result.objectStoreNames.contains(storageDir)) {
req.result.createObjectStore(storageDir);
}
};
} catch (ignore) {}
} else {
// mkdirp storage
storage = storageDir;
child_process.spawnSync("mkdir", [
"-p", storage
], {
stdio: [
"ignore", 1, 2
]
});
onError();
}
}
n/a
storageKeys = function (onError) {
/*
* this function will get all the keys in storage
*/
defer({
action: "keys"
}, onError);
}
...
/*
* this function will load the db from storage
*/
var onParallel;
onParallel = local.onParallel(function (err) {
local.setTimeoutOnError(onError, 0, err);
});
local.storageKeys(function (err, data) {
onParallel.counter += 1;
// validate no err occurred
onParallel.counter += 1;
onParallel(err);
(data || []).forEach(function (key) {
if (key.indexOf("dbTable.") !== 0) {
return;
...
storageLength = function (onError) {
/*
* this function will get the number of items in storage
*/
defer({
action: "length"
}, onError);
}
n/a
storageRemoveItem = function (key, onError) {
/*
* this function will remove the item with given key from storage
*/
defer({
action: "removeItem",
key
}, onError);
}
...
this.timerSave = null;
while (this.onSaveList.length) {
this.onSaveList.shift()();
}
// reset dbTable
local._DbTable.call(this, this);
// clear persistence
local.storageRemoveItem("dbTable." + this.name + ".json", onError
);
};
local._DbTable.prototype.export = function (onError) {
/*
* this function will export the db
*/
var result;
...
storageSetItem = function (key, value, onError) {
/*
* this function will set the item with given key and value to storage
*/
defer({
action: "setItem",
key,
value
}, onError);
}
...
}
if (onError) {
that.onSaveList.push(onError);
}
// throttle storage-writes to once every 1000 ms
that.timerSave = that.timerSave || setTimeout(function () {
that.timerSave = null;
local.storageSetItem(
"dbTable." + that.name + ".json",
that.export(),
function (err) {
while (that.onSaveList.length) {
that.onSaveList.shift()(err);
}
}
...
function Stream() { EE.call(this); }
n/a
_DbTable = function (opt) {
/*
* this function will create a dbTable
*/
this.name = String(opt.name);
// register dbTable in dbTableDict
local.dbTableDict[this.name] = this;
this.dbRowList = [];
this.isDirty = null;
this.idIndexList = [
{
isInteger: false,
name: "_id",
dict: {}
}
];
this.onSaveList = [];
this.sizeLimit = opt.sizeLimit || 0;
}
n/a
_cleanup = function () {
/*
* this function will cleanup soft-deleted records from the dbTable
*/
var dbRow;
var ii;
var list;
if (!this.isDirty && this.dbRowList.length <= this.sizeLimit) {
return;
}
this.isDirty = null;
// cleanup dbRowList
list = this.dbRowList;
this.dbRowList = [];
// optimization - while-loop
ii = 0;
while (ii < list.length) {
dbRow = list[ii];
// cleanup isRemoved
if (!dbRow.$isRemoved) {
this.dbRowList.push(dbRow);
}
ii += 1;
}
if (this.sizeLimit && this.dbRowList.length >= 1.5 * this.sizeLimit) {
this.dbRowList = this._crudGetManyByQuery(
{},
this.sortDefault,
0,
this.sizeLimit
);
}
}
...
return result;
};
local._DbTable.prototype.crudCountAll = function (onError) {
/*
* this function will count all of dbRow's in dbTable
*/
this._cleanup();
return local.setTimeoutOnError(onError, 0, null, this.dbRowList.length);
};
local._DbTable.prototype.crudCountManyByQuery = function (query, onError) {
/*
* this function will count the number of dbRow's in dbTable with given query
*/
...
_crudGetManyByQuery = function ( query, sort, skip, limit, shuffle ) {
/*
* this function will get the dbRow's in the dbTable,
* with given query, sort, skip, and limit
*/
var ii;
var result;
result = this.dbRowList;
// get by query
if (result.length && query && Object.keys(query).length) {
result = local.dbRowListGetManyByQuery(this.dbRowList, query);
}
// sort
(sort || []).forEach(function (element) {
// bug-workaround - v8 does not have stable-sort
// optimization - while-loop
ii = 0;
while (ii < result.length) {
result[ii].$ii = ii;
ii += 1;
}
result.sort(function (aa, bb) {
return local.sortCompare(
local.dbRowGetItem(aa, element.fieldName),
local.dbRowGetItem(bb, element.fieldName),
aa.$ii,
bb.$ii
);
});
if (element.isDescending) {
result.reverse();
}
});
// skip
result = result.slice(skip || 0);
// shuffle
local.functionOrNop(shuffle && local.listShuffle)(result);
// limit
result = result.slice(0, limit || Infinity);
return result;
}
...
// cleanup isRemoved
if (!dbRow.$isRemoved) {
this.dbRowList.push(dbRow);
}
ii += 1;
}
if (this.sizeLimit && this.dbRowList.length >= 1.5 * this.sizeLimit) {
this.dbRowList = this._crudGetManyByQuery(
{},
this.sortDefault,
0,
this.sizeLimit
);
}
};
...
_crudGetOneById = function (idDict) {
/*
* this function will get the dbRow in the dbTable with given idDict
*/
var id;
var result;
idDict = local.objectSetOverride(idDict);
result = null;
this.idIndexList.some(function (idIndex) {
id = idDict[idIndex.name];
// optimization - hasOwnProperty
if (idIndex.dict.hasOwnProperty(id)) {
result = idIndex.dict[id];
return result;
}
});
return result;
}
...
* this function will get the dbRow's in the dbTable with given idDictList
*/
var that;
this._cleanup();
that = this;
return local.setTimeoutOnError(onError, 0, null, local.dbRowProject(
(idDictList || []).map(function (idDict) {
return that._crudGetOneById(idDict);
})
));
};
local._DbTable.prototype.crudGetManyByQuery = function (opt, onError) {
/*
* this function will get the dbRow's in the dbTable with given <opt>.query
...
_crudRemoveOneById = function (idDict, circularSet) {
/*
* this function will remove the dbRow from the dbTable with given idDict
*/
var id;
var result;
var that;
if (!idDict) {
return null;
}
that = this;
circularSet = circularSet || new Set([
idDict
]);
result = null;
that.idIndexList.forEach(function (idIndex) {
id = idDict[idIndex.name];
// optimization - hasOwnProperty
if (!idIndex.dict.hasOwnProperty(id)) {
return;
}
result = idIndex.dict[id];
delete idIndex.dict[id];
// optimization - soft-delete
result.$isRemoved = true;
that.isDirty = true;
if (circularSet.has(result)) {
return;
}
circularSet.add(result);
// recurse
that._crudRemoveOneById(result, circularSet);
});
that.save();
return result;
}
...
result.$isRemoved = true;
that.isDirty = true;
if (circularSet.has(result)) {
return;
}
circularSet.add(result);
// recurse
that._crudRemoveOneById(result, circularSet);
});
that.save();
return result;
};
local._DbTable.prototype._crudSetOneById = function (dbRow) {
/*
...
_crudSetOneById = function (dbRow) {
/*
* this function will set the dbRow into the dbTable with given dbRow._id
* WARNING - existing dbRow with conflicting dbRow._id will be removed
*/
var existing;
var id;
var normalize;
var timeNow;
normalize = function (dbRow) {
/*
* this function will recursively normalize dbRow
*/
switch (typeof dbRow) {
case "boolean":
case "string":
return dbRow;
case "number":
return (
Number.isFinite(dbRow)
? dbRow
: undefined
);
case "object":
if (!dbRow) {
return;
}
break;
default:
return;
}
Object.keys(dbRow).forEach(function (key) {
dbRow[key] = (
(key[0] === "$" || key.indexOf(".") >= 0)
// invalid-property
? undefined
// recurse
: normalize(dbRow[key])
);
});
return dbRow;
};
dbRow = local.jsonCopy(local.objectSetOverride(dbRow));
// update timestamp
timeNow = new Date().toISOString();
dbRow._timeCreated = dbRow._timeCreated || timeNow;
if (!local.modeImport) {
dbRow._timeUpdated = timeNow;
}
// normalize
dbRow = normalize(dbRow);
dbRow = local.jsonCopy(dbRow);
// remove existing dbRow
existing = this._crudRemoveOneById(dbRow) || dbRow;
this.idIndexList.forEach(function (idIndex) {
// auto-set id
id = local.dbRowSetId(existing, idIndex);
// copy id from existing to dbRow
dbRow[idIndex.name] = id;
// set dbRow
idIndex.dict[id] = dbRow;
});
// update dbRowList
this.dbRowList.push(dbRow);
this.save();
return dbRow;
}
...
});
// remove existing dbRow
result = local.jsonCopy(this._crudRemoveOneById(result)) || result;
// update dbRow
delete dbRow._timeCreated;
local.objectSetOverride(result, dbRow, 10);
// replace dbRow
result = this._crudSetOneById(result);
return result;
};
local._DbTable.prototype.crudCountAll = function (onError) {
/*
* this function will count all of dbRow's in dbTable
*/
...
_crudUpdateOneById = function (dbRow) {
/*
* this function will update the dbRow in the dbTable,
* if it exists with given dbRow._id
* WARNING
* existing dbRow's with conflicting unique-keys (besides the one being updated)
* will be removed
*/
var id;
var result;
dbRow = local.jsonCopy(local.objectSetOverride(dbRow));
result = {};
this.idIndexList.some(function (idIndex) {
id = dbRow[idIndex.name];
// optimization - hasOwnProperty
if (idIndex.dict.hasOwnProperty(id)) {
result = idIndex.dict[id];
return true;
}
});
// remove existing dbRow
result = local.jsonCopy(this._crudRemoveOneById(result)) || result;
// update dbRow
delete dbRow._timeCreated;
local.objectSetOverride(result, dbRow, 10);
// replace dbRow
result = this._crudSetOneById(result);
return result;
}
...
* this function will update the dbRowList in the dbTable,
* if they exist with given dbRow._id's
*/
var that;
that = this;
return local.setTimeoutOnError(onError, 0, null, local.dbRowProject(
(dbRowList || []).map(function (dbRow) {
return that._crudUpdateOneById(dbRow);
})
));
};
local._DbTable.prototype.crudUpdateManyByQuery = function (
query,
dbRow,
...
crudCountAll = function (onError) {
/*
* this function will count all of dbRow's in dbTable
*/
this._cleanup();
return local.setTimeoutOnError(onError, 0, null, this.dbRowList.length);
}
...
skip: crud.querySkip,
sort: crud.querySort
}, function (err, data) {
crud.queryData = data;
onParallel(err);
});
onParallel.counter += 1;
crud.dbTable.crudCountAll(function (err, data) {
crud.paginationCountTotal = data;
onParallel(err);
});
break;
case "crudGetOneById":
crud.dbTable.crudGetOneById(crud.queryById, opt.onNext);
break;
...
crudCountManyByQuery = function (query, onError) {
/*
* this function will count the number of dbRow's in dbTable with given query
*/
this._cleanup();
return local.setTimeoutOnError(
onError,
0,
null,
this._crudGetManyByQuery(query).length
);
}
...
local.onNext(opt, function (err, data, meta) {
switch (opt.modeNext) {
case 1:
crud = req.swgg.crud;
user = req.swgg.user;
switch (crud.crudType[0]) {
case "crudCountManyByQuery":
crud.dbTable.crudCountManyByQuery(crud.queryWhere, opt.onNext);
break;
case "crudSetManyById":
crud.dbTable.crudSetManyById(crud.body, opt.onNext);
break;
case "crudSetOneById":
// replace idName with idBackend in body
delete crud.body.id;
...
crudGetManyById = function (idDictList, onError) {
/*
* this function will get the dbRow's in the dbTable with given idDictList
*/
var that;
this._cleanup();
that = this;
return local.setTimeoutOnError(onError, 0, null, local.dbRowProject(
(idDictList || []).map(function (idDict) {
return that._crudGetOneById(idDict);
})
));
}
n/a
crudGetManyByQuery = function (opt, onError) {
/*
* this function will get the dbRow's in the dbTable with given <opt>.query
*/
this._cleanup();
opt = local.objectSetOverride(opt);
return local.setTimeoutOnError(onError, 0, null, local.dbRowProject(
this._crudGetManyByQuery(
opt.query,
opt.sort || this.sortDefault,
opt.skip,
opt.limit,
opt.shuffle
),
opt.fieldList
));
}
...
<script>
var dbTable1;
dbTable1 = window.dbTable1 = window.utility2_db.dbTableCreateOne({
name: "dbTable1"
});
dbTable1.idIndexCreate({ name: "field1" });
dbTable1.crudSetOneById({ field1: "hello", field2: "world" });
console.log(dbTable1.crudGetManyByQuery({
limit: Infinity,
query: { field1: "hello" },
skip: 0,
sort: [{ fieldName: 'field1', isDescending: false }]
}));
</script>
*
...
crudGetOneById = function (idDict, onError) {
/*
* this function will get the dbRow in the dbTable with given idDict
*/
this._cleanup();
return local.setTimeoutOnError(onError, 0, null, local.dbRowProject(
this._crudGetOneById(idDict)
));
}
...
onParallel.counter += 1;
crud.dbTable.crudCountAll(function (err, data) {
crud.paginationCountTotal = data;
onParallel(err);
});
break;
case "crudGetOneById":
crud.dbTable.crudGetOneById(crud.queryById, opt.onNext);
break;
case "crudGetOneByQuery":
crud.dbTable.crudGetOneByQuery({
query: crud.queryWhere
}, opt.onNext);
break;
case "crudNullDelete":
...
crudGetOneByQuery = function (query, onError) {
/*
* this function will get the dbRow in the dbTable with given query
*/
var ii;
var result;
this._cleanup();
// optimization - while-loop
ii = 0;
while (ii < this.dbRowList.length) {
result = local.dbRowListGetManyByQuery([
this.dbRowList[ii]
], query)[0];
if (result) {
break;
}
ii += 1;
}
return local.setTimeoutOnError(
onError,
0,
null,
local.dbRowProject(result)
);
}
...
onParallel(err);
});
break;
case "crudGetOneById":
crud.dbTable.crudGetOneById(crud.queryById, opt.onNext);
break;
case "crudGetOneByQuery":
crud.dbTable.crudGetOneByQuery({
query: crud.queryWhere
}, opt.onNext);
break;
case "crudNullDelete":
case "crudNullGet":
case "crudNullHead":
case "crudNullOptions":
...
crudGetOneByRandom = function (onError) {
/*
* this function will get a random dbRow in the dbTable
*/
this._cleanup();
return local.setTimeoutOnError(onError, 0, null, local.dbRowProject(
this.dbRowList[Math.floor(Math.random() * this.dbRowList.length)]
));
}
n/a
crudRemoveAll = function (onError) {
/*
* this function will remove all of the dbRow's from the dbTable
*/
var idIndexList;
// save idIndexList
idIndexList = this.idIndexList;
// reset dbTable
local._DbTable.call(this, this);
// restore idIndexList
local.dbTableCreateOne({
name: this.name,
idIndexCreateList: idIndexList
}, onError);
}
...
var onParallel;
onParallel = local.onParallel(function (err) {
local.setTimeoutOnError(onError, 0, err);
});
onParallel.counter += 1;
Object.keys(local.dbTableDict).forEach(function (key) {
onParallel.counter += 1;
local.dbTableDict[key].crudRemoveAll(onParallel);
});
onParallel();
};
local.dbDrop = function (onError) {
/*
* this function will drop the db
...
crudRemoveManyById = function (idDictList, onError) {
/*
* this function will remove the dbRow's from the dbTable with given idDictList
*/
var that;
that = this;
return local.setTimeoutOnError(onError, 0, null, local.dbRowProject(
(idDictList || []).map(function (dbRow) {
return that._crudRemoveOneById(dbRow);
})
));
}
n/a
crudRemoveManyByQuery = function (query, onError) {
/*
* this function will remove the dbRow's from the dbTable with given query
*/
var that;
that = this;
return local.setTimeoutOnError(onError, 0, null, local.dbRowProject(
that._crudGetManyByQuery(query).map(function (dbRow) {
return that._crudRemoveOneById(dbRow);
})
));
}
...
* will remove from <dbTable> with json <query>, <dbRowList>
*/
local.dbTableCreateOne({
name: process.argv[3]
}, function (err, that) {
// validate no err occurred
local.assertThrow(!err, err);
console.log(JSON.stringify(that.crudRemoveManyByQuery(
JSON.parse(process.argv[4])
), null, 4));
});
};
local.cliDict.dbTableCrudSetManyById = function () {
/*
...
crudRemoveOneById = function (idDict, onError) {
/*
* this function will remove the dbRow from the dbTable with given idDict
*/
return local.setTimeoutOnError(onError, 0, null, local.dbRowProject(
this._crudRemoveOneById(idDict)
));
}
...
case "crudNullPut":
opt.onNext();
break;
case "crudRemoveManyByQuery":
crud.dbTable.crudRemoveManyByQuery(crud.queryWhere, opt.onNext);
break;
case "crudRemoveOneById":
crud.dbTable.crudRemoveOneById(crud.queryById, opt.onNext);
break;
case "fileGetOneById":
local.dbTableFile = local.db.dbTableCreateOne({
name: "File"
});
crud.dbTable.crudGetOneById(crud.queryById, opt.onNext);
break;
...
crudSetManyById = function (dbRowList, onError) {
/*
* this function will set the dbRowList into the dbTable
*/
var that;
that = this;
return local.setTimeoutOnError(onError, 0, null, local.dbRowProject(
(dbRowList || []).map(function (dbRow) {
return that._crudSetOneById(dbRow);
})
));
}
...
that.idIndexRemove(idIndex);
});
// create idIndex
(opt.idIndexCreateList || []).forEach(function (idIndex) {
that.idIndexCreate(idIndex);
});
// upsert dbRow
that.crudSetManyById(opt.dbRowList);
// restore dbTable from persistent-storage
that.isLoaded = that.isLoaded || opt.isLoaded;
if (!that.isLoaded) {
local.storageGetItem("dbTable." + that.name + ".json", function (
err,
data
) {
...
crudSetOneById = function (dbRow, onError) {
/*
* this function will set the dbRow into the dbTable with given dbRow._id
*/
return local.setTimeoutOnError(onError, 0, null, local.dbRowProject(
this._crudSetOneById(dbRow)
));
}
...
<script src="assets.db-lite.js"></script>
<script>
var dbTable1;
dbTable1 = window.dbTable1 = window.utility2_db.dbTableCreateOne({
name: "dbTable1"
});
dbTable1.idIndexCreate({ name: "field1" });
dbTable1.crudSetOneById({ field1: "hello", field2: "world" });
console.log(dbTable1.crudGetManyByQuery({
limit: Infinity,
query: { field1: "hello" },
skip: 0,
sort: [{ fieldName: 'field1', isDescending: false }]
}));
</script>
...
crudUpdateManyById = function (dbRowList, onError) {
/*
* this function will update the dbRowList in the dbTable,
* if they exist with given dbRow._id's
*/
var that;
that = this;
return local.setTimeoutOnError(onError, 0, null, local.dbRowProject(
(dbRowList || []).map(function (dbRow) {
return that._crudUpdateOneById(dbRow);
})
));
}
n/a
crudUpdateManyByQuery = function ( query, dbRow, onError ) {
/*
* this function will update the dbRow's in the dbTable with given query
*/
var result;
var that;
var tmp;
that = this;
tmp = local.jsonCopy(local.objectSetOverride(dbRow));
result = that._crudGetManyByQuery(query).map(function (dbRow) {
tmp._id = dbRow._id;
return that._crudUpdateOneById(tmp);
});
return local.setTimeoutOnError(onError, 0, null, result);
}
n/a
crudUpdateOneById = function (dbRow, onError) {
/*
* this function will update the dbRow in the dbTable,
* if it exists with given dbRow._id
*/
return local.setTimeoutOnError(onError, 0, null, local.dbRowProject(
this._crudUpdateOneById(dbRow)
));
}
...
crud.dbTable.crudSetOneById(crud.body, opt.onNext);
break;
case "crudUpdateOneById":
// replace idName with idBackend in body
delete crud.body.id;
delete crud.body[crud.idName];
crud.body[crud.idBackend] = crud.data[crud.idName];
crud.dbTable.crudUpdateOneById(crud.body, opt.onNext);
break;
// coverage-hack - test err handling-behavior
case "crudErrorDelete":
case "crudErrorGet":
case "crudErrorHead":
case "crudErrorOptions":
case "crudErrorPatch":
...
drop = function (onError) {
/*
* this function will drop the dbTable
*/
console.error("db - dropping dbTable " + this.name + " ...");
// cancel pending save
this.timerSave = null;
while (this.onSaveList.length) {
this.onSaveList.shift()();
}
// reset dbTable
local._DbTable.call(this, this);
// clear persistence
local.storageRemoveItem("dbTable." + this.name + ".json", onError);
}
...
local.setTimeoutOnError(onError, 0, err);
});
onParallel.counter += 1;
onParallel.counter += 1;
local.storageClear(onParallel);
Object.keys(local.dbTableDict).forEach(function (key) {
onParallel.counter += 1;
local.dbTableDict[key].drop(onParallel);
});
onParallel();
};
local.dbExport = function (onError) {
/*
* this function will export the db as serialized text
...
export = function (onError) {
/*
* this function will export the db
*/
var result;
var that;
this._cleanup();
that = this;
result = "";
that.idIndexList.forEach(function (idIndex) {
result += that.name + " idIndexCreate " + JSON.stringify({
isInteger: idIndex.isInteger,
name: idIndex.name
}) + "\n";
});
result += that.name + " sizeLimit " + that.sizeLimit + "\n";
result += that.name + " sortDefault " + JSON.stringify(
that.sortDefault
) + "\n";
that.crudGetManyByQuery({}).forEach(function (dbRow) {
result += that.name + " dbRowSet " + JSON.stringify(dbRow) + "\n";
});
return local.setTimeoutOnError(onError, 0, null, result.trim());
}
...
that.onSaveList.push(onError);
}
// throttle storage-writes to once every 1000 ms
that.timerSave = that.timerSave || setTimeout(function () {
that.timerSave = null;
local.storageSetItem(
"dbTable." + that.name + ".json",
that.export(),
function (err) {
while (that.onSaveList.length) {
that.onSaveList.shift()(err);
}
}
);
}, 1000);
...
idIndexCreate = function (opt, onError) {
/*
* this function will create an idIndex with given <opt>.name
*/
var dbRow;
var idIndex;
var ii;
var name;
opt = local.objectSetOverride(opt);
name = String(opt.name);
// disallow idIndex with dot-name
if (name.indexOf(".") >= 0 || name === "_id") {
return local.setTimeoutOnError(onError);
}
// remove existing idIndex
this.idIndexRemove(opt);
// init idIndex
idIndex = {
dict: {},
isInteger: Boolean(opt.isInteger),
name
};
this.idIndexList.push(idIndex);
// populate idIndex with dbRowList
// optimization - while-loop
ii = 0;
while (ii < this.dbRowList.length) {
dbRow = this.dbRowList[ii];
// auto-set id
if (!dbRow.$isRemoved) {
idIndex.dict[local.dbRowSetId(dbRow, idIndex)] = dbRow;
}
ii += 1;
}
this.save();
return local.setTimeoutOnError(onError);
}
...
* browser example:
<script src="assets.db-lite.js"></script>
<script>
var dbTable1;
dbTable1 = window.dbTable1 = window.utility2_db.dbTableCreateOne({
name: "dbTable1"
});
dbTable1.idIndexCreate({ name: "field1" });
dbTable1.crudSetOneById({ field1: "hello", field2: "world" });
console.log(dbTable1.crudGetManyByQuery({
limit: Infinity,
query: { field1: "hello" },
skip: 0,
sort: [{ fieldName: 'field1', isDescending: false }]
}));
...
idIndexRemove = function (opt, onError) {
/*
* this function will remove the idIndex with given <opt>.name
*/
var name;
opt = local.objectSetOverride(opt);
name = String(opt.name);
this.idIndexList = this.idIndexList.filter(function (idIndex) {
return idIndex.name !== name || idIndex.name === "_id";
});
this.save();
return local.setTimeoutOnError(onError);
}
...
opt = local.objectSetOverride(opt);
name = String(opt.name);
// disallow idIndex with dot-name
if (name.indexOf(".") >= 0 || name === "_id") {
return local.setTimeoutOnError(onError);
}
// remove existing idIndex
this.idIndexRemove(opt);
// init idIndex
idIndex = {
dict: {},
isInteger: Boolean(opt.isInteger),
name
};
this.idIndexList.push(idIndex);
...
save = function (onError) {
/*
* this function will save the dbTable to storage
*/
var that;
that = this;
if (local.modeImport) {
return;
}
if (onError) {
that.onSaveList.push(onError);
}
// throttle storage-writes to once every 1000 ms
that.timerSave = that.timerSave || setTimeout(function () {
that.timerSave = null;
local.storageSetItem(
"dbTable." + that.name + ".json",
that.export(),
function (err) {
while (that.onSaveList.length) {
that.onSaveList.shift()(err);
}
}
);
}, 1000);
}
...
if (circularSet.has(result)) {
return;
}
circularSet.add(result);
// recurse
that._crudRemoveOneById(result, circularSet);
});
that.save();
return result;
};
local._DbTable.prototype._crudSetOneById = function (dbRow) {
/*
* this function will set the dbRow into the dbTable with given dbRow._id
* WARNING - existing dbRow with conflicting dbRow._id will be removed
...
dbTableCrudGetManyByQuery = function () {
/*
* <dbTable> <query>
* will get from <dbTable> with json <query>, <dbRowList>
*/
local.dbTableCreateOne({
name: process.argv[3]
}, function (err, that) {
// validate no err occurred
local.assertThrow(!err, err);
console.log(JSON.stringify(that.crudGetManyByQuery(
JSON.parse(process.argv[4] || "{}")
), null, 4));
});
}
n/a
dbTableCrudRemoveManyByQuery = function () {
/*
* <dbTable> <query>
* will remove from <dbTable> with json <query>, <dbRowList>
*/
local.dbTableCreateOne({
name: process.argv[3]
}, function (err, that) {
// validate no err occurred
local.assertThrow(!err, err);
console.log(JSON.stringify(that.crudRemoveManyByQuery(
JSON.parse(process.argv[4])
), null, 4));
});
}
n/a
dbTableCrudSetManyById = function () {
/*
* <dbTable> <dbRowList>
* will set in <dbTable>, <dbRowList>
*/
local.dbTableCreateOne({
name: process.argv[3]
}, function (err, that) {
// validate no err occurred
local.assertThrow(!err, err);
that.crudSetManyById(JSON.parse(process.argv[4]));
});
}
n/a
dbTableHeaderDictGet = function () {
/*
* <dbTable>
* will get from <dbTable>, <headerDict>
*/
local.dbTableCreateOne({
name: process.argv[3]
}, function (err, that) {
// validate no err occurred
local.assertThrow(!err, err);
var tmp;
tmp = [];
that.idIndexList.forEach(function (idIndex) {
tmp.push({
isInteger: idIndex.isInteger,
name: idIndex.name
});
});
console.log(JSON.stringify({
idIndexList: tmp,
sizeLimit: that.sizeLimit,
sortDefault: that.sortDefault
}, null, 4));
});
}
...
local.tmp = [];
that.idIndexList.forEach(function (idIndex) {
local.tmp.push({
isInteger: idIndex.isInteger,
name: idIndex.name
});
});
local.cliDict.dbTableHeaderDictGet();
});
};
local.cliDict.dbTableIdIndexCreate = function () {
/*
* <dbTable> <idIndex>
* will create in <dbTable>, <idIndex>
...
dbTableHeaderDictSet = function () {
/*
* <dbTable> <headerDict>
* will set in <dbTable>, <headerDict>
*/
local.dbTableCreateOne({
name: process.argv[3]
}, function (err, that) {
// validate no err occurred
local.assertThrow(!err, err);
local.tmp = JSON.parse(process.argv[4]);
that.sizeLimit = local.tmp.sizeLimit || that.sizeLimit;
that.sortDefault = local.tmp.sortDefault || that.sortDefault;
that.save();
local.tmp = [];
that.idIndexList.forEach(function (idIndex) {
local.tmp.push({
isInteger: idIndex.isInteger,
name: idIndex.name
});
});
local.cliDict.dbTableHeaderDictGet();
});
}
n/a
dbTableIdIndexCreate = function () {
/*
* <dbTable> <idIndex>
* will create in <dbTable>, <idIndex>
*/
local.dbTableCreateOne({
name: process.argv[3]
}, function (err, that) {
// validate no err occurred
local.assertThrow(!err, err);
that.idIndexCreate(JSON.parse(process.argv[4]));
that.save();
local.tmp = [];
that.idIndexList.forEach(function (idIndex) {
local.tmp.push({
isInteger: idIndex.isInteger,
name: idIndex.name
});
});
local.cliDict.dbTableHeaderDictGet();
});
}
n/a
dbTableIdIndexRemove = function () {
/*
* <dbTable> <idIndex>
* will remove from <dbTable>, <idIndex>
*/
local.dbTableCreateOne({
name: process.argv[3]
}, function (err, that) {
// validate no err occurred
local.assertThrow(!err, err);
that.idIndexRemove(JSON.parse(process.argv[4]));
that.save();
local.cliDict.dbTableHeaderDictGet();
});
}
n/a
dbTableList = function () {
/*
*
* will get from db, <dbTableList>
*/
local.storageKeys(function (err, data) {
// validate no err occurred
local.assertThrow(!err, err);
console.log(JSON.stringify(data.map(function (element) {
return element.split(".").slice(1, -1).join(".");
}), null, 4));
});
}
...
* will remove from db, <dbTable>
*/
local.storageRemoveItem("dbTable." + process.argv[3] + ".json", function (
err
) {
// validate no err occurred
local.assertThrow(!err, err);
local.cliDict.dbTableList();
});
};
// run the cli
if (module === require.main && !globalThis.utility2_rollup) {
local.cliRun();
}
...
dbTableRemove = function () {
/*
* <dbTable>
* will remove from db, <dbTable>
*/
local.storageRemoveItem("dbTable." + process.argv[3] + ".json", function (
err
) {
// validate no err occurred
local.assertThrow(!err, err);
local.cliDict.dbTableList();
});
}
n/a
ajax = function (opt, onError) {
/*
* this function will send an ajax-req
* with given <opt>.url and callback <onError>
* with err and timeout handling
* example usage:
local.ajax({
data: "hello world",
header: {"x-header-hello": "world"},
method: "POST",
url: "/index.html"
}, function (err, xhr) {
console.log(xhr.statusCode);
console.log(xhr.responseText);
});
*/
var ajaxProgressUpdate;
var bufferValidateAndCoerce;
var isDone;
var local2;
var onEvent;
var streamCleanup;
var timeout;
var tmp;
var xhr;
var xhrInit;
// init local2
local2 = opt.local2 || local.utility2 || {};
// init function
ajaxProgressUpdate = local2.ajaxProgressUpdate || local.nop;
bufferValidateAndCoerce = local2.bufferValidateAndCoerce || function (
bff,
mode
) {
/*
* this function will validate and coerce/convert <bff> -> Buffer
* (or String if <mode> = "string")
*/
// coerce ArrayBuffer -> Buffer
if (Object.prototype.toString.call(bff) === "[object ArrayBuffer]") {
bff = new Uint8Array(bff);
}
// convert Buffer -> utf8
if (mode === "string" && typeof bff !== "string") {
bff = String(bff);
}
return bff;
};
onEvent = function (evt) {
/*
* this function will handle events
*/
if (Object.prototype.toString.call(evt) === "[object Error]") {
xhr.err = xhr.err || evt;
xhr.onEvent({
type: "error"
});
return;
}
// init statusCode
xhr.statusCode = (xhr.statusCode || xhr.status) | 0;
switch (evt.type) {
case "abort":
case "error":
case "load":
if (isDone) {
return;
}
isDone = true;
// decrement ajaxProgressCounter
local2.ajaxProgressCounter = Math.max(
local2.ajaxProgressCounter - 1,
0
);
ajaxProgressUpdate();
// handle abort or err event
switch (!xhr.err && evt.type) {
case "abort":
case "error":
xhr.err = new Error("ajax - event " + evt.type);
break;
case "load":
if (xhr.statusCode >= 400) {
xhr.err = new Error(
"ajax - statusCode " + xhr.statusCode
);
}
break;
}
// debug statusCode / method / url
if (xhr.err) {
xhr.statusCode = xhr.statusCode || 500;
xhr.err.statusCode = xhr.statusCode;
tmp = (
// ternary-operator
(
local.isBrowser
? "browser"
: "node"
)
+ " - " + xhr.statusCode + " " + xhr.method + " " + xhr.url
+ "\n"
);
xhr.err.message = tmp + xhr.err.message;
xhr.err.stack = tmp + xhr.err.stack;
}
// update resHeaders
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/getAllResponseHeaders
if (xhr.getAllResponseHeaders) {
xhr.getAllResponseHeaders().replace((
/(.*?):\u0020*(.*?)\r\n/g
), function (ignore, match1, match2) {
xhr.resHeaders[match1.toLowerCase()] = match2;
});
}
// debug ajaxResponse
xhr.resContentLeng...
...
/* validateLineSortedReset */
local.ajax = function (opt, onError) {
/*
* this function will send an ajax-req
* with given <opt>.url and callback <onError>
* with err and timeout handling
* example usage:
local.ajax({
data: "hello world",
header: {"x-header-hello": "world"},
method: "POST",
url: "/index.html"
}, function (err, xhr) {
console.log(xhr.statusCode);
console.log(xhr.responseText);
...
function ok(...args) { innerOk(ok, args.length, ...args); }
...
key = '0123456789abcdef0123456789abcdef';
mode = null;
local.cryptoAesXxxCbcRawEncrypt({
data: data,
key: key,
mode: mode
}, function (err, data) {
console.assert(!err, err);
local.cryptoAesXxxCbcRawDecrypt({
data: data,
key: key,
mode: mode
}, console.log);
});
*/
...
assertThrow = function (passed, message) {
/*
* this function will throw err.<message> if <passed> is falsy
*/
var err;
if (passed) {
return;
}
err = (
// ternary-operator
(
message
&& typeof message.message === "string"
&& typeof message.stack === "string"
)
// if message is errObj, then leave as is
? message
: new Error(
typeof message === "string"
// if message is a string, then leave as is
? message
// else JSON.stringify message
: JSON.stringify(message, null, 4)
)
);
throw err;
}
...
argList: (commandList[ii][1] || "").trim(),
command: [
key
],
description: commandList[ii][2]
};
} catch (ignore) {
local.assertThrow(null, new Error(
"cliRun - cannot parse comment in COMMAND "
+ key
+ ":\nnew RegExp("
+ JSON.stringify(opt.rgxComment.source)
+ ").exec(" + JSON.stringify(text).replace((
/\\\\/g
), "\u0000").replace((
...
cliRun = function (opt) {
/*
* this function will run the cli with given <opt>
*/
local.cliDict._eval = local.cliDict._eval || function () {
/*
* <code>
* will eval <code>
*/
globalThis.local = local;
local.vm.runInThisContext(process.argv[3]);
};
local.cliDict["--eval"] = local.cliDict["--eval"] || local.cliDict._eval;
local.cliDict["-e"] = local.cliDict["-e"] || local.cliDict._eval;
local.cliDict._help = local.cliDict._help || function () {
/*
*
* will print help
*/
var commandList;
var file;
var packageJson;
var text;
var textDict;
commandList = [
{
argList: "<arg2> ...",
description: "usage:",
command: [
"<arg1>"
]
}, {
argList: "'console.log(\"hello world\")'",
description: "example:",
command: [
"--eval"
]
}
];
file = __filename.replace((
/.*\//
), "");
opt = Object.assign({}, opt);
packageJson = require("./package.json");
// validate comment
opt.rgxComment = opt.rgxComment || (
/\)\u0020\{\n(?:|\u0020{4})\/\*\n(?:\u0020|\u0020{5})\*((?:\u0020<[^>]*?>|\u0020\.\.\.)*?)\n(?:\u0020|\u0020{5})\*\u0020
(will\u0020.*?\S)\n(?:\u0020|\u0020{5})\*\/\n(?:\u0020{4}|\u0020{8})\S/
);
textDict = {};
Object.keys(local.cliDict).sort().forEach(function (key, ii) {
if (key[0] === "_" && key !== "_default") {
return;
}
text = String(local.cliDict[key]);
if (key === "_default") {
key = "";
}
textDict[text] = textDict[text] || (ii + 2);
ii = textDict[text];
if (commandList[ii]) {
commandList[ii].command.push(key);
return;
}
try {
commandList[ii] = opt.rgxComment.exec(text);
commandList[ii] = {
argList: (commandList[ii][1] || "").trim(),
command: [
key
],
description: commandList[ii][2]
};
} catch (ignore) {
local.assertThrow(null, new Error(
"cliRun - cannot parse comment in COMMAND "
+ key
+ ":\nnew RegExp("
+ JSON.stringify(opt.rgxComment.source)
+ ").exec(" + JSON.stringify(text).replace((
/\\\\/g
), "\u0000").replace((
/\\n/g
), "\\n\\\n").replace((
/\u0000/g
), "\\\\") + ");"
));
}
});
text = "";
text += packageJson.name + " (" + packageJson.version + ")\n\n";
text += commandList.filter(function (elem) {
return elem;
}).map(function (elem, ii) {
elem.command = elem.command.filter(function (elem) {
return elem;
});
switch (ii) {
case 0:
case 1:
elem.argList = [
elem.argList
];
break;
default:
elem.argList = elem.argList.split(" ");
elem.description = (
"# COMMAND "
+ (elem.command[0] || "<none>") + "\n# &...
...
dir: process.argv[2],
modulePathList: module.paths
}));
};
// run the cli
if (module === require.main && !globalThis.utility2_rollup) {
local.cliRun();
}
}());
}());
...
function EventEmitter() { EventEmitter.init.call(this); }
n/a
functionOrNop = function (fnc) {
/*
* this function will if <fnc> exists,
* them return <fnc>,
* else return <nop>
*/
return fnc || local.nop;
}
...
if (element.isDescending) {
result.reverse();
}
});
// skip
result = result.slice(skip || 0);
// shuffle
local.functionOrNop(shuffle && local.listShuffle)(result);
// limit
result = result.slice(0, limit || Infinity);
return result;
};
local._DbTable.prototype._crudGetOneById = function (idDict) {
/*
...
githubCrudAjax = function (opt, onError) {
/*
* this function will make a low-level content-req to github
* https://developer.github.com/v3/repos/contents/
*/
// init opt
opt = {
content: opt.content,
headers: Object.assign({
// github oauth authentication
Authorization: "token " + (
typeof process === "object"
&& process && process.env.GITHUB_TOKEN
),
// bug-workaround
// https://developer.github.com/v3/#user-agent-required
"User-Agent": "undefined"
}, opt.headers),
httpReq: opt.httpReq,
message: opt.message,
method: opt.method || "GET",
responseJson: {},
sha: opt.sha,
url: opt.url
};
opt.url = opt.url
/* jslint ignore:start */
// parse https://github.com/:owner/:repo/blob/:branch/:path
.replace(
(/^https:\/\/github.com\/([^\/]+?\/[^\/]+?)\/blob\/([^\/]+?)\/(.+)/),
'https://api.github.com/repos/$1/contents/$3?branch=$2'
)
// parse https://github.com/:owner/:repo/tree/:branch/:path
.replace(
(/^https:\/\/github.com\/([^\/]+?\/[^\/]+?)\/tree\/([^\/]+?)\/(.+)/),
'https://api.github.com/repos/$1/contents/$3?branch=$2'
)
// parse https://raw.githubusercontent.com/:owner/:repo/:branch/:path
.replace(
(/^https:\/\/raw.githubusercontent.com\/([^\/]+?\/[^\/]+?)\/([^\/]+?)\/(.+)/),
'https://api.github.com/repos/$1/contents/$3?branch=$2'
)
// parse https://:owner.github.io/:repo/:path
.replace(
(/^https:\/\/([^\.]+?)\.github\.io\/([^\/]+?)\/(.+)/),
'https://api.github.com/repos/$1/$2/contents/$3?branch=gh-pages'
)
// parse :owner/:repo
.replace(
(/^([^\/]+?\/[^\/]+?)$/),
'https://github.com/$1'
)
/* jslint ignore:end */
.replace((
/\?branch=(.*)/
), function (match0, match1) {
opt.branch = match1;
if (opt.method === "GET") {
match0 = match0.replace("branch", "ref");
}
return match0;
});
if ((
/^https:\/\/github\.com\/[^\/]+?\/[^\/]+?$/
).test(opt.url)) {
opt.data = JSON.stringify({
name: opt.url.split("/")[4]
});
switch (opt.method) {
case "DELETE":
opt.url = (
"https://api.github.com/repos/"
+ opt.url.split("/").slice(3).join("/")
);
break;
case "POST_ORG":
opt.url = (
"https://api.github.com/orgs/"
+ opt.url.split("/")[3] + "/repos"
);
break;
case "POST_USER":
opt.url = "https://api.github.com/user/repos";
break;
}
opt.method = opt.method.split("_")[0];
} else {
if (opt.url.indexOf("https://api.github.com/repos/") !== 0) {
console.error("githubCrud - invalid url " + opt.url);
onError(new Error("invalid url " + opt.url));
return;
}
if (opt.method !== "GET") {
opt.message = (
opt.message
|| "[ci skip] " + opt.method + " file "
+ opt.url.replace((
/\?.*/
), "")
);
opt.url += "&message=" + encodeURIComponent(opt.message);
if (opt.sha) {
opt.url += "&sha=" + opt.sha;
}
opt.data = JSON.stringify({
branch: opt.branch,
content: Buffer.from(opt.content || "").toString("base64"),
message: opt.message,
sha: opt.sha
});
}
}
local.ajax(opt, function (err, xhr) {...
...
message: opt.message,
url: opt.url
};
local.onNext(opt, function (err, data) {
switch (opt.modeNext) {
case 1:
// get sha
local.githubCrudAjax({
httpReq: opt.httpReq,
url: opt.url
}, opt.onNext);
break;
case 2:
// delete file with sha
if (!err && data.sha) {
...
githubCrudContentDelete = function (opt, onError) {
/*
* this function will delete github-file <opt>.url
* https://developer.github.com/v3/repos/contents/#delete-a-file
*/
opt = {
httpReq: opt.httpReq,
message: opt.message,
url: opt.url
};
local.onNext(opt, function (err, data) {
switch (opt.modeNext) {
case 1:
// get sha
local.githubCrudAjax({
httpReq: opt.httpReq,
url: opt.url
}, opt.onNext);
break;
case 2:
// delete file with sha
if (!err && data.sha) {
local.githubCrudAjax({
httpReq: opt.httpReq,
message: opt.message,
method: "DELETE",
sha: data.sha,
url: opt.url
}, opt.onNext);
return;
}
// delete tree
local.onParallelList({
list: data
}, function (option2, onParallel) {
onParallel.counter += 1;
// recurse
local.githubCrudContentDelete({
httpReq: opt.httpReq,
message: opt.message,
url: option2.elem.url
}, onParallel);
}, opt.onNext);
break;
default:
onError(err, data);
}
});
opt.modeNext = 0;
opt.onNext();
}
...
}
// delete tree
local.onParallelList({
list: data
}, function (option2, onParallel) {
onParallel.counter += 1;
// recurse
local.githubCrudContentDelete({
httpReq: opt.httpReq,
message: opt.message,
url: option2.elem.url
}, onParallel);
}, opt.onNext);
break;
default:
...
githubCrudContentGet = function (opt, onError) {
/*
* this function will get github-file <opt>.url
* https://developer.github.com/v3/repos/contents/#get-contents
*/
opt = {
httpReq: opt.httpReq,
url: opt.url
};
local.onNext(opt, function (err, data) {
switch (opt.modeNext) {
case 1:
local.githubCrudAjax({
httpReq: opt.httpReq,
url: opt.url
}, opt.onNext);
break;
case 2:
opt.onNext(null, Buffer.from(data.content || "", "base64"));
break;
default:
onError(err, !err && data);
}
});
opt.modeNext = 0;
opt.onNext();
}
...
};
local.cliDict.get = function () {
/*
* <fileRemote>
* will get from github <fileRemote>
*/
local.github_crud.githubCrudContentGet({
url: process.argv[3]
}, function (err, data) {
try {
process.stdout.write(data);
} catch (ignore) {}
process.exit(Boolean(err));
});
...
githubCrudContentPut = function (opt, onError) {
/*
* this function will put <opt>.content to github-file <opt>.url
* https://developer.github.com/v3/repos/contents/#create-a-file
* https://developer.github.com/v3/repos/contents/#update-a-file
*/
opt = {
content: opt.content,
httpReq: opt.httpReq,
message: opt.message,
modeErrorIgnore: true,
url: opt.url
};
local.onNext(opt, function (err, data) {
switch (opt.modeNext) {
case 1:
// get sha
local.githubCrudAjax({
httpReq: opt.httpReq,
url: opt.url
}, opt.onNext);
break;
case 2:
// put file with sha
local.githubCrudAjax({
content: opt.content,
httpReq: opt.httpReq,
message: opt.message,
method: "PUT",
sha: data.sha,
url: opt.url
}, opt.onNext);
break;
default:
onError(err, data);
}
});
opt.modeNext = 0;
opt.onNext();
}
...
});
return;
}
// get file
local.fs.readFile(opt.file, opt.onNext);
break;
case 2:
local.githubCrudContentPut({
content: data,
httpReq: opt.httpReq,
message: opt.message,
// resolve file in url
url: (
// ternary-operator
(
...
githubCrudContentPutFile = function (opt, onError) {
/*
* this function will put opt.file to github-file <opt>.url
* https://developer.github.com/v3/repos/contents/#update-a-file
*/
opt = {
file: opt.file,
httpReq: opt.httpReq,
message: opt.message,
url: opt.url
};
local.onNext(opt, function (err, data) {
switch (opt.modeNext) {
case 1:
// get file from url
if ((
/^(?:http|https):\/\//
).test(opt.file)) {
local.ajax({
httpReq: opt.httpReq,
url: opt.file
}, function (err, res) {
opt.onNext(err, res && res.data);
});
return;
}
// get file
local.fs.readFile(opt.file, opt.onNext);
break;
case 2:
local.githubCrudContentPut({
content: data,
httpReq: opt.httpReq,
message: opt.message,
// resolve file in url
url: (
// ternary-operator
(
/\/$/
).test(opt.url)
? opt.url + local.path.basename(opt.file)
: opt.url
)
}, opt.onNext);
break;
default:
onError(err, data);
}
});
opt.modeNext = 0;
opt.onNext();
}
...
};
local.cliDict.put = function () {
/*
* <fileRemote> <fileLocal> <commitMessage>
* will put on github <fileRemote> to <fileLocal>
*/
local.github_crud.githubCrudContentPutFile({
message: process.argv[5],
url: process.argv[3],
file: process.argv[4]
}, function (err) {
process.exit(Boolean(err));
});
};
...
githubCrudContentTouch = function (opt, onError) {
/*
* this function will touch github-file <opt>.url
* https://developer.github.com/v3/repos/contents/#update-a-file
*/
opt = {
httpReq: opt.httpReq,
message: opt.message,
modeErrorIgnore: true,
url: opt.url
};
local.onNext(opt, function (err, data) {
switch (opt.modeNext) {
case 1:
// get sha
local.githubCrudAjax({
httpReq: opt.httpReq,
url: opt.url
}, opt.onNext);
break;
case 2:
// put file with sha
local.githubCrudAjax({
content: Buffer.from(data.content || "", "base64"),
httpReq: opt.httpReq,
message: opt.message,
method: "PUT",
sha: data.sha,
url: opt.url
}, opt.onNext);
break;
default:
onError(err, data);
}
});
opt.modeNext = 0;
opt.onNext();
}
...
* this function will touch github-files <opt>.urlList in parallel
* https://developer.github.com/v3/repos/contents/#update-a-file
*/
local.onParallelList({
list: opt.urlList
}, function (option2, onParallel) {
onParallel.counter += 1;
local.githubCrudContentTouch({
httpReq: opt.httpReq,
message: opt.message,
url: option2.elem
}, onParallel);
}, onError);
};
...
githubCrudContentTouchList = function (opt, onError) {
/*
* this function will touch github-files <opt>.urlList in parallel
* https://developer.github.com/v3/repos/contents/#update-a-file
*/
local.onParallelList({
list: opt.urlList
}, function (option2, onParallel) {
onParallel.counter += 1;
local.githubCrudContentTouch({
httpReq: opt.httpReq,
message: opt.message,
url: option2.elem
}, onParallel);
}, onError);
}
...
};
local.cliDict.touch = function () {
/*
* <fileRemoteList> <commitMessage>
* will touch on github in parallel, comma-separated <fileRemoteList>
*/
local.github_crud.githubCrudContentTouchList({
message: process.argv[4],
urlList: process.argv[3].split(
/[,\s]/g
).filter(local.identity)
}, function (err) {
process.exit(Boolean(err));
});
...
githubCrudRepoCreate = function (opt, onError) {
/*
* this function will create github-repo <opt>.url
* https://developer.github.com/v3/repos/#create
*/
local.githubCrudAjax({
httpReq: opt.httpReq,
method: "POST_ORG",
url: opt.url
}, function (err, data) {
if (!(err && err.statusCode === 404)) {
onError(err, data);
return;
}
local.githubCrudAjax({
httpReq: opt.httpReq,
method: "POST_USER",
url: opt.url
}, onError);
});
}
...
* this function will create github-repos <opt>.urlList in parallel
* https://developer.github.com/v3/repos/#create
*/
local.onParallelList({
list: opt.urlList
}, function (option2, onParallel) {
onParallel.counter += 1;
local.githubCrudRepoCreate({
httpReq: opt.httpReq,
url: option2.elem
}, onParallel);
}, onError);
};
local.githubCrudRepoDelete = function (opt, onError) {
...
githubCrudRepoCreateList = function (opt, onError) {
/*
* this function will create github-repos <opt>.urlList in parallel
* https://developer.github.com/v3/repos/#create
*/
local.onParallelList({
list: opt.urlList
}, function (option2, onParallel) {
onParallel.counter += 1;
local.githubCrudRepoCreate({
httpReq: opt.httpReq,
url: option2.elem
}, onParallel);
}, onError);
}
...
};
local.cliDict.repo_create = function () {
/*
* <repoList>
* will create on github in parallel, comma-separated <repoList>
*/
local.github_crud.githubCrudRepoCreateList({
urlList: process.argv[3].split(
/[,\s]/g
).filter(local.identity)
}, function (err) {
process.exit(Boolean(err));
});
};
...
githubCrudRepoDelete = function (opt, onError) {
/*
* this function will delete github-repo <opt>.url
* https://developer.github.com/v3/repos/#delete-a-repository
*/
local.githubCrudAjax({
httpReq: opt.httpReq,
method: "DELETE",
url: opt.url
}, onError);
}
...
* this function will delete github-repos <opt>.urlList in parallel
* https://developer.github.com/v3/repos/#delete-a-repository
*/
local.onParallelList({
list: opt.urlList
}, function (option2, onParallel) {
onParallel.counter += 1;
local.githubCrudRepoDelete({
httpReq: opt.httpReq,
url: option2.elem
}, onParallel);
}, onError);
};
}());
...
githubCrudRepoDeleteList = function (opt, onError) {
/*
* this function will delete github-repos <opt>.urlList in parallel
* https://developer.github.com/v3/repos/#delete-a-repository
*/
local.onParallelList({
list: opt.urlList
}, function (option2, onParallel) {
onParallel.counter += 1;
local.githubCrudRepoDelete({
httpReq: opt.httpReq,
url: option2.elem
}, onParallel);
}, onError);
}
...
};
local.cliDict.repo_delete = function () {
/*
* <repoList>
* will delete from github in parallel, comma-separated <repoList>
*/
local.github_crud.githubCrudRepoDeleteList({
urlList: process.argv[3].split(
/[,\s]/g
).filter(local.identity)
}, function (err) {
process.exit(Boolean(err));
});
};
...
identity = function (value) {
/*
* this function will return <value>
*/
return value;
}
...
local.cliDict.help = local.cliDict.help || local.cliDict._help;
local.cliDict._interactive = local.cliDict._interactive || function () {
/*
*
* will start interactive-mode
*/
globalThis.local = local;
local.identity(local.replStart || require("repl").start)({
useGlobal: true
});
};
local.cliDict["--interactive"] = (
local.cliDict["--interactive"]
|| local.cliDict._interactive
);
...
nop = function () {
/*
* this function will do nothing
*/
return;
}
...
process.stdout._writeDefault = (
process.stdout._writeDefault
|| process.stdout._write
);
process.stdout._write = function (chunk, encoding, callback) {
process.stdout._writeDefault(chunk, encoding, callback);
// coverage-hack - ignore else-statement
local.nop(that.socket.writable && (function () {
that.socket.write(chunk, encoding);
}()));
};
// start serverRepl1
globalThis.utility2_serverRepl1 = require("net").createServer(function (
socket
) {
...
objectAssignDefault = function (target, source) {
/*
* this function will if items from <target> are
* null, undefined, or empty-string,
* then overwrite them with items from <source>
*/
target = target || {};
Object.keys(source || {}).forEach(function (key) {
if (
target[key] === null
|| target[key] === undefined
|| target[key] === ""
) {
target[key] = target[key] || source[key];
}
});
return target;
}
...
if (key[0] !== "_") {
xhr[key] = opt[key];
}
});
// init timeout
timeout = xhr.timeout || local2.timeoutDefault || 30000;
// init default
local.objectAssignDefault(xhr, {
corsForwardProxyHost: local2.corsForwardProxyHost,
headers: {},
location: (local.isBrowser && location) || {},
method: "GET",
responseType: ""
});
// init headers
...
onErrorDefault = function (err) {
/*
* this function will if <err> exists, then print it to stderr
*/
if (err) {
console.error(err);
}
return err;
}
...
dbTable = local.dbTableCreateOne({
isLoaded: true,
name: match1
});
dbTable.sortDefault = JSON.parse(match3);
break;
default:
local.onErrorDefault(new Error(
"db - dbImport - invalid operation - " + match0
));
}
});
Object.keys(dbTableDict).forEach(function (name) {
console.error("db - importing dbTable " + name + " ...");
});
...
onErrorWithStack = function (onError) {
/*
* this function will create wrapper around <onError>
* that will append current-stack to err.stack
*/
var onError2;
var stack;
stack = new Error().stack.replace((
/(.*?)\n.*?$/m
), "$1");
onError2 = function (err, data, meta) {
if (
err
&& typeof err.stack === "string"
&& err !== local.errDefault
&& String(err.stack).indexOf(stack.split("\n")[2]) < 0
) {
// append current-stack to err.stack
err.stack += "\n" + stack;
}
onError(err, data, meta);
};
// debug onError
onError2.toString = function () {
return String(onError);
};
return onError2;
}
...
local.onParallel = function (onError, onEach, onRetry) {
/*
* this function will create a function that will
* 1. run async tasks in parallel
* 2. if counter === 0 or err occurred, then call onError(err)
*/
var onParallel;
onError = local.onErrorWithStack(onError);
onEach = onEach || local.nop;
onRetry = onRetry || local.nop;
onParallel = function (err, data) {
if (onRetry(err, data)) {
return;
}
// decrement counter
...
onNext = function (opt, onError) {
/*
* this function will wrap onError inside recursive-function <opt>.onNext,
* and append the current-stack to any err
*/
opt.onNext = local.onErrorWithStack(function (err, data, meta) {
try {
opt.modeNext += (
(err && !opt.modeErrorIgnore)
? 1000
: 1
);
if (opt.modeDebug) {
console.error("onNext - " + JSON.stringify({
modeNext: opt.modeNext,
errorMessage: err && err.message
}));
if (err && err.stack) {
console.error(err.stack);
}
}
onError(err, data, meta);
} catch (errCaught) {
// throw errCaught to break infinite recursion-loop
if (opt.errCaught) {
local.assertThrow(null, opt.errCaught);
}
opt.errCaught = errCaught;
opt.onNext(errCaught, data, meta);
}
});
return opt;
}
...
onError(err, data, meta);
} catch (errCaught) {
// throw errCaught to break infinite recursion-loop
if (opt.errCaught) {
local.assertThrow(null, opt.errCaught);
}
opt.errCaught = errCaught;
opt.onNext(errCaught, data, meta);
}
});
return opt;
};
local.onParallel = function (onError, onEach, onRetry) {
/*
...
onParallel = function (onError, onEach, onRetry) {
/*
* this function will create a function that will
* 1. run async tasks in parallel
* 2. if counter === 0 or err occurred, then call onError(err)
*/
var onParallel;
onError = local.onErrorWithStack(onError);
onEach = onEach || local.nop;
onRetry = onRetry || local.nop;
onParallel = function (err, data) {
if (onRetry(err, data)) {
return;
}
// decrement counter
onParallel.counter -= 1;
// validate counter
if (!(onParallel.counter >= 0 || err || onParallel.err)) {
err = new Error(
"invalid onParallel.counter = " + onParallel.counter
);
// ensure onError is run only once
} else if (onParallel.counter < 0) {
return;
}
// handle err
if (err) {
onParallel.err = err;
// ensure counter <= 0
onParallel.counter = -Math.abs(onParallel.counter);
}
// call onError when isDone
if (onParallel.counter <= 0) {
onError(err, data);
return;
}
onEach();
};
// init counter
onParallel.counter = 0;
// return callback
return onParallel;
}
...
};
local.dbCrudRemoveAll = function (onError) {
/*
* this function will remove all dbRow's from the db
*/
var onParallel;
onParallel = local.onParallel(function (err) {
local.setTimeoutOnError(onError, 0, err);
});
onParallel.counter += 1;
Object.keys(local.dbTableDict).forEach(function (key) {
onParallel.counter += 1;
local.dbTableDict[key].crudRemoveAll(onParallel);
});
...
onParallelList = function (opt, onEach, onError) {
/*
* this function will
* 1. async-run onEach in parallel,
* with given <opt>.rateLimit and <opt>.retryLimit
* 2. call <onError> when onParallel.ii + 1 === <opt>.list.length
*/
var isListEnd;
var onEach2;
var onParallel;
opt.list = opt.list || [];
onEach2 = function () {
while (true) {
if (!(onParallel.ii + 1 < opt.list.length)) {
isListEnd = true;
return;
}
if (!(onParallel.counter < opt.rateLimit + 1)) {
return;
}
onParallel.ii += 1;
onEach({
elem: opt.list[onParallel.ii],
ii: onParallel.ii,
list: opt.list,
retry: 0
}, onParallel);
}
};
onParallel = local.onParallel(onError, onEach2, function (err, data) {
if (err && data && data.retry < opt.retryLimit) {
local.onErrorDefault(err);
data.retry += 1;
setTimeout(function () {
onParallel.counter -= 1;
onEach(data, onParallel);
}, 1000);
return true;
}
// restart if opt.list has grown
if (isListEnd && (onParallel.ii + 1 < opt.list.length)) {
isListEnd = null;
onEach2();
}
});
onParallel.ii = -1;
opt.rateLimit = Number(opt.rateLimit) || 6;
opt.rateLimit = Math.max(opt.rateLimit, 1);
opt.retryLimit = Number(opt.retryLimit) || 2;
onParallel.counter += 1;
onEach2();
onParallel();
}
...
method: "DELETE",
sha: data.sha,
url: opt.url
}, opt.onNext);
return;
}
// delete tree
local.onParallelList({
list: data
}, function (option2, onParallel) {
onParallel.counter += 1;
// recurse
local.githubCrudContentDelete({
httpReq: opt.httpReq,
message: opt.message,
...
function Stream() { EE.call(this); }
n/a
delete = function () {
/*
* <fileRemote|dirRemote> <commitMessage>
* will delete from github <fileRemote|dirRemote>
*/
local.github_crud.githubCrudContentDelete({
message: process.argv[4],
url: process.argv[3]
}, function (err) {
process.exit(Boolean(err));
});
}
...
tmp = stringify(obj);
return (
typeof tmp === "string"
? tmp
: "null"
);
}).join(",") + "]";
circularSet.delete(obj);
return tmp;
}
// if obj is not an array,
// then recurse its items with object-keys sorted
tmp = "{" + Object.keys(obj).sort().map(function (key) {
// recurse
tmp = stringify(obj[key]);
...
get = function () {
/*
* <fileRemote>
* will get from github <fileRemote>
*/
local.github_crud.githubCrudContentGet({
url: process.argv[3]
}, function (err, data) {
try {
process.stdout.write(data);
} catch (ignore) {}
process.exit(Boolean(err));
});
}
...
.objectStore(storageDir);
}
switch (opt.action) {
case "clear":
req = objectStore.clear();
break;
case "getItem":
req = objectStore.get(String(opt.key));
break;
case "keys":
data = [];
req = objectStore.openCursor();
req.onsuccess = function () {
if (!req.result) {
onError2();
...
put = function () {
/*
* <fileRemote> <fileLocal> <commitMessage>
* will put on github <fileRemote> to <fileLocal>
*/
local.github_crud.githubCrudContentPutFile({
message: process.argv[5],
url: process.argv[3],
file: process.argv[4]
}, function (err) {
process.exit(Boolean(err));
});
}
...
case "length":
req = objectStore.count();
break;
case "removeItem":
req = objectStore.delete(String(opt.key));
break;
case "setItem":
req = objectStore.put(opt.value, String(opt.key));
break;
}
[
"onabort", "onerror", "onsuccess"
].forEach(function (handler) {
req[handler] = req[handler] || onError2;
});
...
repo_create = function () {
/*
* <repoList>
* will create on github in parallel, comma-separated <repoList>
*/
local.github_crud.githubCrudRepoCreateList({
urlList: process.argv[3].split(
/[,\s]/g
).filter(local.identity)
}, function (err) {
process.exit(Boolean(err));
});
}
n/a
repo_delete = function () {
/*
* <repoList>
* will delete from github in parallel, comma-separated <repoList>
*/
local.github_crud.githubCrudRepoDeleteList({
urlList: process.argv[3].split(
/[,\s]/g
).filter(local.identity)
}, function (err) {
process.exit(Boolean(err));
});
}
n/a
touch = function () {
/*
* <fileRemoteList> <commitMessage>
* will touch on github in parallel, comma-separated <fileRemoteList>
*/
local.github_crud.githubCrudContentTouchList({
message: process.argv[4],
urlList: process.argv[3].split(
/[,\s]/g
).filter(local.identity)
}, function (err) {
process.exit(Boolean(err));
});
}
n/a
function HtmlReport(opts) { Report.call(this); this.opts = opts || {}; this.opts.dir = this.opts.dir || path.resolve(process.cwd(), 'html-report'); this.opts.sourceStore = this.opts.sourceStore || Store.create('fslookup'); this.opts.linkMapper = this.opts.linkMapper || this.standardLinkMapper(); this.opts.writer = this.opts.writer || null; // coverage-hack - new Date() bugfix this.opts.templateData = { datetime: new Date().toGMTString() }; this.opts.watermarks = this.opts.watermarks || defaults.watermarks(); }
...
);
local.writerData = "";
opt.sourceStore = {};
opt.writer = local.writer;
// 1. print coverage in text-format to stdout
new local.TextReport(opt).writeReport(local.collector);
// 2. write coverage in html-format to filesystem
new local.HtmlReport(opt).writeReport(local.collector);
local.writer.writeFile("", local.nop);
if (!local.isBrowser) {
// write coverage.json
local.fsWriteFileWithMkdirpSync(
opt.dir + "/coverage.json",
JSON.stringify(globalThis.__coverage__)
);
...
function Instrumenter(options) { this.opts = options || { debug: false, walkDebug: false, coverageVariable: '__coverage__', codeGenerationOptions: undefined, noAutoWrap: false, noCompact: false, embedSource: false, preserveComments: false, esModules: false }; if (this.opts.esModules && !this.opts.noAutoWrap) { this.opts.noAutoWrap = true; if (this.opts.debug) { console.log('Setting noAutoWrap to true as required by esModules'); } } this.walker = new Walker({ ArrowFunctionExpression: [ this.arrowBlockConverter ], ExpressionStatement: this.coverStatement, ExportNamedDeclaration: this.coverExport, BreakStatement: this.coverStatement, ContinueStatement: this.coverStatement, DebuggerStatement: this.coverStatement, ReturnStatement: this.coverStatement, ThrowStatement: this.coverStatement, TryStatement: [ this.paranoidHandlerCheck, this.coverStatement], VariableDeclaration: this.coverStatement, IfStatement: [ this.ifBlockConverter, this.coverStatement, this.ifBranchInjector ], ForStatement: [ this.skipInit, this.loopBlockConverter, this.coverStatement ], ForInStatement: [ this.skipLeft, this.loopBlockConverter, this.coverStatement ], ForOfStatement: [ this.skipLeft, this.loopBlockConverter, this.coverStatement ], WhileStatement: [ this.loopBlockConverter, this.coverStatement ], DoWhileStatement: [ this.loopBlockConverter, this.coverStatement ], SwitchStatement: [ this.coverStatement, this.switchBranchInjector ], SwitchCase: [ this.switchCaseInjector ], WithStatement: [ this.withBlockConverter, this.coverStatement ], FunctionDeclaration: [ this.coverFunction, this.coverStatement ], FunctionExpression: this.coverFunction, LabeledStatement: this.coverStatement, ConditionalExpression: this.conditionalBranchInjector, LogicalExpression: this.logicalExpressionBranchInjector, ObjectExpression: this.maybeAddType, MetaProperty: this.coverMetaProperty, }, this.extractCurrentHint, this, this.opts.walkDebug); //unit testing purposes only if (this.opts.backdoor && this.opts.backdoor.omitTrackerSuffix) { this.omitTrackerSuffix = true; } }
...
* 3. return instrumented code
*/
// 1. normalize the file
file = local._istanbul_path.resolve("/", file);
// 2. save code to __coverageCodeDict__[file] for future html-report
globalThis.__coverageCodeDict__[file] = code;
// 3. return instrumented code
return new local.Instrumenter({
embedSource: true,
esModules: true,
noAutoWrap: true
}).instrumentSync(code, file).trimLeft();
};
local.util = {
...
function TextReport(opts) { Report.call(this); opts = opts || {}; this.dir = opts.dir || process.cwd(); this.file = opts.file; this.summary = opts.summary; this.maxCols = opts.maxCols || 0; this.watermarks = opts.watermarks || defaults.watermarks(); }
...
+ "background: #fff; border: 1px solid #000; margin 0; padding: 0;"
+ "\">\n"
);
local.writerData = "";
opt.sourceStore = {};
opt.writer = local.writer;
// 1. print coverage in text-format to stdout
new local.TextReport(opt).writeReport(local.collector);
// 2. write coverage in html-format to filesystem
new local.HtmlReport(opt).writeReport(local.collector);
local.writer.writeFile("", local.nop);
if (!local.isBrowser) {
// write coverage.json
local.fsWriteFileWithMkdirpSync(
opt.dir + "/coverage.json",
...
function Module(id = '', parent) { this.id = id; this.path = path.dirname(id); this.exports = {}; this.parent = parent; updateChildren(parent, this, false); this.filename = null; this.loaded = false; this.children = []; }
n/a
function ok(...args) { innerOk(ok, args.length, ...args); }
...
key = '0123456789abcdef0123456789abcdef';
mode = null;
local.cryptoAesXxxCbcRawEncrypt({
data: data,
key: key,
mode: mode
}, function (err, data) {
console.assert(!err, err);
local.cryptoAesXxxCbcRawDecrypt({
data: data,
key: key,
mode: mode
}, console.log);
});
*/
...
assertThrow = function (passed, message) {
/*
* this function will throw err.<message> if <passed> is falsy
*/
var err;
if (passed) {
return;
}
err = (
// ternary-operator
(
message
&& typeof message.message === "string"
&& typeof message.stack === "string"
)
// if message is errObj, then leave as is
? message
: new Error(
typeof message === "string"
// if message is a string, then leave as is
? message
// else JSON.stringify message
: JSON.stringify(message, null, 4)
)
);
throw err;
}
...
argList: (commandList[ii][1] || "").trim(),
command: [
key
],
description: commandList[ii][2]
};
} catch (ignore) {
local.assertThrow(null, new Error(
"cliRun - cannot parse comment in COMMAND "
+ key
+ ":\nnew RegExp("
+ JSON.stringify(opt.rgxComment.source)
+ ").exec(" + JSON.stringify(text).replace((
/\\\\/g
), "\u0000").replace((
...
cliRun = function (opt) {
/*
* this function will run the cli with given <opt>
*/
local.cliDict._eval = local.cliDict._eval || function () {
/*
* <code>
* will eval <code>
*/
globalThis.local = local;
local.vm.runInThisContext(process.argv[3]);
};
local.cliDict["--eval"] = local.cliDict["--eval"] || local.cliDict._eval;
local.cliDict["-e"] = local.cliDict["-e"] || local.cliDict._eval;
local.cliDict._help = local.cliDict._help || function () {
/*
*
* will print help
*/
var commandList;
var file;
var packageJson;
var text;
var textDict;
commandList = [
{
argList: "<arg2> ...",
description: "usage:",
command: [
"<arg1>"
]
}, {
argList: "'console.log(\"hello world\")'",
description: "example:",
command: [
"--eval"
]
}
];
file = __filename.replace((
/.*\//
), "");
opt = Object.assign({}, opt);
packageJson = require("./package.json");
// validate comment
opt.rgxComment = opt.rgxComment || (
/\)\u0020\{\n(?:|\u0020{4})\/\*\n(?:\u0020|\u0020{5})\*((?:\u0020<[^>]*?>|\u0020\.\.\.)*?)\n(?:\u0020|\u0020{5})\*\u0020
(will\u0020.*?\S)\n(?:\u0020|\u0020{5})\*\/\n(?:\u0020{4}|\u0020{8})\S/
);
textDict = {};
Object.keys(local.cliDict).sort().forEach(function (key, ii) {
if (key[0] === "_" && key !== "_default") {
return;
}
text = String(local.cliDict[key]);
if (key === "_default") {
key = "";
}
textDict[text] = textDict[text] || (ii + 2);
ii = textDict[text];
if (commandList[ii]) {
commandList[ii].command.push(key);
return;
}
try {
commandList[ii] = opt.rgxComment.exec(text);
commandList[ii] = {
argList: (commandList[ii][1] || "").trim(),
command: [
key
],
description: commandList[ii][2]
};
} catch (ignore) {
local.assertThrow(null, new Error(
"cliRun - cannot parse comment in COMMAND "
+ key
+ ":\nnew RegExp("
+ JSON.stringify(opt.rgxComment.source)
+ ").exec(" + JSON.stringify(text).replace((
/\\\\/g
), "\u0000").replace((
/\\n/g
), "\\n\\\n").replace((
/\u0000/g
), "\\\\") + ");"
));
}
});
text = "";
text += packageJson.name + " (" + packageJson.version + ")\n\n";
text += commandList.filter(function (elem) {
return elem;
}).map(function (elem, ii) {
elem.command = elem.command.filter(function (elem) {
return elem;
});
switch (ii) {
case 0:
case 1:
elem.argList = [
elem.argList
];
break;
default:
elem.argList = elem.argList.split(" ");
elem.description = (
"# COMMAND "
+ (elem.command[0] || "<none>") + "\n# &...
...
dir: process.argv[2],
modulePathList: module.paths
}));
};
// run the cli
if (module === require.main && !globalThis.utility2_rollup) {
local.cliRun();
}
}());
}());
...
coverageMerge = function (coverage1, coverage2) {
/*
* this function will inplace-merge coverage2 into coverage1
*/
var dict1;
var dict2;
coverage1 = coverage1 || {};
coverage2 = coverage2 || {};
Object.keys(coverage2).forEach(function (file) {
if (!coverage2[file]) {
return;
}
// if file is undefined in coverage1, then add it
if (!coverage1[file]) {
coverage1[file] = coverage2[file];
return;
}
// merge file from coverage2 into coverage1
[
"b", "f", "s"
].forEach(function (key) {
dict1 = coverage1[file][key];
dict2 = coverage2[file][key];
switch (key) {
// increment coverage for branch lines
case "b":
Object.keys(dict2).forEach(function (key) {
dict2[key].forEach(function (count, ii) {
dict1[key][ii] += count;
});
});
break;
// increment coverage for function and statement lines
case "f":
case "s":
Object.keys(dict2).forEach(function (key) {
dict1[key] += dict2[key];
});
break;
}
});
});
return coverage1;
}
...
}
opt = {};
opt.dir = process.cwd() + "/tmp/build/coverage.html";
// merge previous coverage
if (!local.isBrowser && process.env.npm_config_mode_coverage_merge) {
console.log("merging file " + opt.dir + "/coverage.json to coverage");
try {
local.coverageMerge(globalThis.__coverage__, JSON.parse(
local.fs.readFileSync(opt.dir + "/coverage.json", "utf8")
));
} catch (ignore) {}
try {
opt.coverageCodeDict = JSON.parse(local.fs.readFileSync(
opt.dir + "/coverage.code-dict.json",
"utf8"
...
coverageReportCreate = function () {
/*
* this function will
* 1. print coverage in text-format to stdout
* 2. write coverage in html-format to filesystem
* 3. return coverage in html-format as single document
*/
var opt;
/* istanbul ignore next */
if (!globalThis.__coverage__) {
return "";
}
opt = {};
opt.dir = process.cwd() + "/tmp/build/coverage.html";
// merge previous coverage
if (!local.isBrowser && process.env.npm_config_mode_coverage_merge) {
console.log("merging file " + opt.dir + "/coverage.json to coverage");
try {
local.coverageMerge(globalThis.__coverage__, JSON.parse(
local.fs.readFileSync(opt.dir + "/coverage.json", "utf8")
));
} catch (ignore) {}
try {
opt.coverageCodeDict = JSON.parse(local.fs.readFileSync(
opt.dir + "/coverage.code-dict.json",
"utf8"
));
Object.keys(opt.coverageCodeDict).forEach(function (key) {
globalThis.__coverageCodeDict__[key] = (
globalThis.__coverageCodeDict__[key]
|| opt.coverageCodeDict[key]
);
});
} catch (ignore) {}
}
// init writer
local.coverageReportHtml = "";
local.coverageReportHtml += (
"<div class=\"coverageReportDiv\">\n"
+ "<h1>coverage-report</h1>\n"
+ "<div style=\""
+ "background: #fff; border: 1px solid #000; margin 0; padding: 0;"
+ "\">\n"
);
local.writerData = "";
opt.sourceStore = {};
opt.writer = local.writer;
// 1. print coverage in text-format to stdout
new local.TextReport(opt).writeReport(local.collector);
// 2. write coverage in html-format to filesystem
new local.HtmlReport(opt).writeReport(local.collector);
local.writer.writeFile("", local.nop);
if (!local.isBrowser) {
// write coverage.json
local.fsWriteFileWithMkdirpSync(
opt.dir + "/coverage.json",
JSON.stringify(globalThis.__coverage__)
);
// write coverage.code-dict.json
local.fsWriteFileWithMkdirpSync(
opt.dir + "/coverage.code-dict.json",
JSON.stringify(globalThis.__coverageCodeDict__)
);
// write coverage.badge.svg
opt.pct = local.coverageReportSummary.root.metrics.lines.pct;
local.fsWriteFileWithMkdirpSync(
local._istanbul_path.dirname(opt.dir) + "/coverage.badge.svg",
local.templateCoverageBadgeSvg
// edit coverage badge percent
.replace((
/100.0/g
), opt.pct)
// edit coverage badge color
.replace((
/0d0/g
), ((
"0" + Math.round((100 - opt.pct) * 2.21).toString(16)
).slice(-2) + (
"0" + Math.round(opt.pct * 2.21).toString(16)
).slice(-2) + "00"))
);
}
console.log("created coverage file " + opt.dir + "/index.html");
// 3. return coverage in html-format as a single document
local.coverageReportHtml += "</div>\n</div>\n";
// write coverage.rollup.html
if (!local.isBrowser) {
local.fsWriteFileWithMkdirpSync(
opt.dir + "/coverage.rollup.html",
local.coverageReportHtml
);
}
return local.coverageReportHtml;
}
...
).textContent.replace((
/^#!\//
), "// ")
);
document.querySelector(
"#coverageReportDiv1"
).innerHTML = (
local.istanbul.coverageReportCreate({
coverage: window.__coverage__
})
);
} catch (errorCaught2) {
console.error(errorCaught2);
}
return;
...
function EventEmitter() { EventEmitter.init.call(this); }
n/a
fsWriteFileWithMkdirpSync = function (file, data, mode) {
/*
* this function will synchronously "mkdir -p" and write <data> to <file>
*/
try {
if (
mode === "noWrite"
|| typeof require("fs").writeFileSync !== "function"
) {
return;
}
} catch (ignore) {
return;
}
// try to write to file
try {
require("fs").writeFileSync(file, data);
} catch (ignore) {
// mkdir -p
require("child_process").spawnSync(
"mkdir",
[
"-p", require("path").dirname(file)
],
{
stdio: [
"ignore", 1, 2
]
}
);
// re-write to file
require("fs").writeFileSync(file, data);
}
}
...
// 1. print coverage in text-format to stdout
new local.TextReport(opt).writeReport(local.collector);
// 2. write coverage in html-format to filesystem
new local.HtmlReport(opt).writeReport(local.collector);
local.writer.writeFile("", local.nop);
if (!local.isBrowser) {
// write coverage.json
local.fsWriteFileWithMkdirpSync(
opt.dir + "/coverage.json",
JSON.stringify(globalThis.__coverage__)
);
// write coverage.code-dict.json
local.fsWriteFileWithMkdirpSync(
opt.dir + "/coverage.code-dict.json",
JSON.stringify(globalThis.__coverageCodeDict__)
...
functionOrNop = function (fnc) {
/*
* this function will if <fnc> exists,
* them return <fnc>,
* else return <nop>
*/
return fnc || local.nop;
}
...
if (element.isDescending) {
result.reverse();
}
});
// skip
result = result.slice(skip || 0);
// shuffle
local.functionOrNop(shuffle && local.listShuffle)(result);
// limit
result = result.slice(0, limit || Infinity);
return result;
};
local._DbTable.prototype._crudGetOneById = function (idDict) {
/*
...
identity = function (value) {
/*
* this function will return <value>
*/
return value;
}
...
local.cliDict.help = local.cliDict.help || local.cliDict._help;
local.cliDict._interactive = local.cliDict._interactive || function () {
/*
*
* will start interactive-mode
*/
globalThis.local = local;
local.identity(local.replStart || require("repl").start)({
useGlobal: true
});
};
local.cliDict["--interactive"] = (
local.cliDict["--interactive"]
|| local.cliDict._interactive
);
...
instrumentInPackage = function (code, file) {
/*
* this function will instrument the code
* only if the macro /\* istanbul instrument in package $npm_package_nameLib *\/
* exists in the code
*/
return (
// ternary-operator
(
process.env.npm_config_mode_coverage
&& code.indexOf("/* istanbul ignore all */\n") < 0 && (
process.env.npm_config_mode_coverage === "all"
|| code.indexOf(
"/* istanbul instrument in package "
+ process.env.npm_package_nameLib + " */\n"
) >= 0
|| code.indexOf(
"/* istanbul instrument in package "
+ process.env.npm_config_mode_coverage + " */\n"
) >= 0
)
)
? local.instrumentSync(code, file)
: code
);
}
n/a
instrumentSync = function (code, file) {
/*
* this function will
* 1. normalize the file
* 2. save code to __coverageCodeDict__[file] for future html-report
* 3. return instrumented code
*/
// 1. normalize the file
file = local._istanbul_path.resolve("/", file);
// 2. save code to __coverageCodeDict__[file] for future html-report
globalThis.__coverageCodeDict__[file] = code;
// 3. return instrumented code
return new local.Instrumenter({
embedSource: true,
esModules: true,
noAutoWrap: true
}).instrumentSync(code, file).trimLeft();
}
...
) >= 0
|| code.indexOf(
"/* istanbul instrument in package "
+ process.env.npm_config_mode_coverage + " */\n"
) >= 0
)
)
? local.instrumentSync(code, file)
: code
);
};
local.instrumentSync = function (code, file) {
/*
* this function will
...
nop = function () {
/*
* this function will do nothing
*/
return;
}
...
process.stdout._writeDefault = (
process.stdout._writeDefault
|| process.stdout._write
);
process.stdout._write = function (chunk, encoding, callback) {
process.stdout._writeDefault(chunk, encoding, callback);
// coverage-hack - ignore else-statement
local.nop(that.socket.writable && (function () {
that.socket.write(chunk, encoding);
}()));
};
// start serverRepl1
globalThis.utility2_serverRepl1 = require("net").createServer(function (
socket
) {
...
objectAssignDefault = function (target, source) {
/*
* this function will if items from <target> are
* null, undefined, or empty-string,
* then overwrite them with items from <source>
*/
target = target || {};
Object.keys(source || {}).forEach(function (key) {
if (
target[key] === null
|| target[key] === undefined
|| target[key] === ""
) {
target[key] = target[key] || source[key];
}
});
return target;
}
...
if (key[0] !== "_") {
xhr[key] = opt[key];
}
});
// init timeout
timeout = xhr.timeout || local2.timeoutDefault || 30000;
// init default
local.objectAssignDefault(xhr, {
corsForwardProxyHost: local2.corsForwardProxyHost,
headers: {},
location: (local.isBrowser && location) || {},
method: "GET",
responseType: ""
});
// init headers
...
function require(path) { return mod.require(path); }
...
}).slice(0, 256).map(readExample);
// init moduleMain
local.tryCatchOnError(function () {
console.error("apidocCreate - requiring " + opt.dir + " ...");
moduleMain = {};
moduleMain = (
opt.moduleDict[opt.env.npm_package_name]
|| opt.require(opt.dir)
|| opt.require(
opt.dir + "/"
+ (opt.packageJson.bin)[Object.keys(opt.packageJson.bin)[0]]
) || {}
);
opt.circularSet.add(moduleMain);
console.error("apidocCreate - ... required " + opt.dir);
...
function Stream() { EE.call(this); }
n/a
function HtmlReport(opts) { Report.call(this); this.opts = opts || {}; this.opts.dir = this.opts.dir || path.resolve(process.cwd(), 'html-report'); this.opts.sourceStore = this.opts.sourceStore || Store.create('fslookup'); this.opts.linkMapper = this.opts.linkMapper || this.standardLinkMapper(); this.opts.writer = this.opts.writer || null; // coverage-hack - new Date() bugfix this.opts.templateData = { datetime: new Date().toGMTString() }; this.opts.watermarks = this.opts.watermarks || defaults.watermarks(); }
...
);
local.writerData = "";
opt.sourceStore = {};
opt.writer = local.writer;
// 1. print coverage in text-format to stdout
new local.TextReport(opt).writeReport(local.collector);
// 2. write coverage in html-format to filesystem
new local.HtmlReport(opt).writeReport(local.collector);
local.writer.writeFile("", local.nop);
if (!local.isBrowser) {
// write coverage.json
local.fsWriteFileWithMkdirpSync(
opt.dir + "/coverage.json",
JSON.stringify(globalThis.__coverage__)
);
...
fillTemplate = function (node, templateData) { var opts = this.opts, linkMapper = opts.linkMapper; templateData.entity = node.name || 'All files'; templateData.metrics = node.metrics; templateData.reportClass = getReportClass(node.metrics.statements, opts.watermarks.statements); templateData.pathHtml = pathTemplate({ html: this.getPathHtml(node, linkMapper) }); templateData.prettify = { js: linkMapper.asset(node, 'prettify.js'), css: linkMapper.asset(node, 'prettify.css') }; }
n/a
getPathHtml = function (node, linkMapper) { var parent = node.parent, nodePath = [], linkPath = [], i; while (parent) { nodePath.push(parent); parent = parent.parent; } for (i = 0; i < nodePath.length; i += 1) { linkPath.push('<a href="' + linkMapper.ancestor(node, i + 1) + '">' + (nodePath[i].relativeName || 'All files') + '</a>'); } linkPath.reverse(); return linkPath.length > 0 ? linkPath.join(' » ') + ' » ' + node.displayShortName() : ''; }
n/a
standardLinkMapper = function () { return { fromParent: function (node) { var i = 0, relativeName = node.relativeName, ch; if (SEP !== '/') { relativeName = ''; for (i = 0; i < node.relativeName.length; i += 1) { ch = node.relativeName.charAt(i); if (ch === SEP) { relativeName += '/'; } else { relativeName += ch; } } } return node.kind === 'dir' ? relativeName + 'index.html' : relativeName + '.html'; }, ancestorHref: function (node, num) { var href = '', separated, levels, i, j; for (i = 0; i < num; i += 1) { separated = node.relativeName.split(SEP); levels = separated.length - 1; for (j = 0; j < levels; j += 1) { href += '../'; } node = node.parent; } return href; }, ancestor: function (node, num) { return this.ancestorHref(node, num) + 'index.html'; }, asset: function (node, name) { var i = 0, parent = node.parent; while (parent) { i += 1; parent = parent.parent; } return this.ancestorHref(node, i) + name; } }; }
n/a
writeDetailPage = function (writer, node, fileCoverage) { var opts = this.opts, sourceStore = opts.sourceStore, templateData = opts.templateData, sourceText = fileCoverage.code && Array.isArray(fileCoverage.code) ? fileCoverage.code.join('\n') + '\n' : sourceStore.get(fileCoverage.path), code = sourceText.split(/(?:\r?\n)|\r/), count = 0, structured = code.map(function (str) { count += 1; return { line: count, covered: null, text: new InsertionText(str, true ) }; }), context; structured.unshift({ line: 0, covered: null, text: new InsertionText("") }); this.fillTemplate(node, templateData); writer.write(headerTemplate(templateData)); writer.write('<pre><table class="coverage">\n'); annotateLines(fileCoverage, structured); //note: order is important, since statements typically result in spanning the whole line and doing branches late //causes mismatched tags annotateBranches(fileCoverage, structured); annotateFunctions(fileCoverage, structured); annotateStatements(fileCoverage, structured); structured.shift(); context = { structured: structured, maxLines: structured.length, fileCoverage: fileCoverage }; writer.write(detailTemplate(context)); writer.write('</table></pre>\n'); writer.write(footerTemplate(templateData)); }
n/a
writeFiles = function (writer, node, dir, collector) { var that = this, indexFile = path.resolve(dir, 'index.html'), childFile; if (this.opts.verbose) { console.error('Writing ' + indexFile); } writer.writeFile(indexFile, function (contentWriter) { that.writeIndexPage(contentWriter, node); }); node.children.forEach(function (child) { if (child.kind === 'dir') { that.writeFiles(writer, child, path.resolve(dir, child.relativeName), collector); } else { childFile = path.resolve(dir, child.relativeName + '.html'); if (that.opts.verbose) { console.error('Writing ' + childFile); } writer.writeFile(childFile, function (contentWriter) { that.writeDetailPage(contentWriter, child, collector.fileCoverageFor(child.fullPath())); }); } }); }
n/a
writeIndexPage = function (writer, node) { var linkMapper = this.opts.linkMapper, templateData = this.opts.templateData, children = Array.prototype.slice.apply(node.children), watermarks = this.opts.watermarks; children.sort(function (a, b) { return a.name < b.name ? -1 : 1; }); this.fillTemplate(node, templateData); writer.write(headerTemplate(templateData)); writer.write(summaryTableHeader); children.forEach(function (child) { var metrics = child.metrics, reportClasses = { statements: getReportClass(metrics.statements, watermarks.statements), lines: getReportClass(metrics.lines, watermarks.lines), functions: getReportClass(metrics.functions, watermarks.functions), branches: getReportClass(metrics.branches, watermarks.branches) }, data = { metrics: metrics, reportClasses: reportClasses, file: child.displayShortName(), output: linkMapper.fromParent(child) }; writer.write(summaryLineTemplate(data) + '\n'); }); writer.write(summaryTableFooter); writer.write(footerTemplate(templateData)); }
n/a
writeReport = function (collector, sync) { var opts = this.opts, dir = opts.dir, summarizer = new TreeSummarizer(), writer = opts.writer || new FileWriter(sync), tree; collector.files().forEach(function (key) { summarizer.addFileCoverageSummary(key, utils.summarizeFileCoverage(collector.fileCoverageFor(key))); }); tree = summarizer.getTreeSummary(); fs.readdirSync(path.resolve(__dirname, '..', 'vendor')).forEach(function (f) { var resolvedSource = path.resolve(__dirname, '..', 'vendor', f), resolvedDestination = path.resolve(dir, f), stat = fs.statSync(resolvedSource); if (stat.isFile()) { if (opts.verbose) { console.log('Write asset: ' + resolvedDestination); } writer.copyFile(resolvedSource, resolvedDestination); } }); //console.log(JSON.stringify(tree.root, undefined, 4)); this.writeFiles(writer, tree.root, dir, collector); }
...
+ "background: #fff; border: 1px solid #000; margin 0; padding: 0;"
+ "\">\n"
);
local.writerData = "";
opt.sourceStore = {};
opt.writer = local.writer;
// 1. print coverage in text-format to stdout
new local.TextReport(opt).writeReport(local.collector);
// 2. write coverage in html-format to filesystem
new local.HtmlReport(opt).writeReport(local.collector);
local.writer.writeFile("", local.nop);
if (!local.isBrowser) {
// write coverage.json
local.fsWriteFileWithMkdirpSync(
opt.dir + "/coverage.json",
...
function Instrumenter(options) { this.opts = options || { debug: false, walkDebug: false, coverageVariable: '__coverage__', codeGenerationOptions: undefined, noAutoWrap: false, noCompact: false, embedSource: false, preserveComments: false, esModules: false }; if (this.opts.esModules && !this.opts.noAutoWrap) { this.opts.noAutoWrap = true; if (this.opts.debug) { console.log('Setting noAutoWrap to true as required by esModules'); } } this.walker = new Walker({ ArrowFunctionExpression: [ this.arrowBlockConverter ], ExpressionStatement: this.coverStatement, ExportNamedDeclaration: this.coverExport, BreakStatement: this.coverStatement, ContinueStatement: this.coverStatement, DebuggerStatement: this.coverStatement, ReturnStatement: this.coverStatement, ThrowStatement: this.coverStatement, TryStatement: [ this.paranoidHandlerCheck, this.coverStatement], VariableDeclaration: this.coverStatement, IfStatement: [ this.ifBlockConverter, this.coverStatement, this.ifBranchInjector ], ForStatement: [ this.skipInit, this.loopBlockConverter, this.coverStatement ], ForInStatement: [ this.skipLeft, this.loopBlockConverter, this.coverStatement ], ForOfStatement: [ this.skipLeft, this.loopBlockConverter, this.coverStatement ], WhileStatement: [ this.loopBlockConverter, this.coverStatement ], DoWhileStatement: [ this.loopBlockConverter, this.coverStatement ], SwitchStatement: [ this.coverStatement, this.switchBranchInjector ], SwitchCase: [ this.switchCaseInjector ], WithStatement: [ this.withBlockConverter, this.coverStatement ], FunctionDeclaration: [ this.coverFunction, this.coverStatement ], FunctionExpression: this.coverFunction, LabeledStatement: this.coverStatement, ConditionalExpression: this.conditionalBranchInjector, LogicalExpression: this.logicalExpressionBranchInjector, ObjectExpression: this.maybeAddType, MetaProperty: this.coverMetaProperty, }, this.extractCurrentHint, this, this.opts.walkDebug); //unit testing purposes only if (this.opts.backdoor && this.opts.backdoor.omitTrackerSuffix) { this.omitTrackerSuffix = true; } }
...
* 3. return instrumented code
*/
// 1. normalize the file
file = local._istanbul_path.resolve("/", file);
// 2. save code to __coverageCodeDict__[file] for future html-report
globalThis.__coverageCodeDict__[file] = code;
// 3. return instrumented code
return new local.Instrumenter({
embedSource: true,
esModules: true,
noAutoWrap: true
}).instrumentSync(code, file).trimLeft();
};
local.util = {
...
arrowBlockConverter = function (node) { var retStatement; if (node.expression) { // turn expression nodes into a block with a return statement retStatement = astgen.returnStatement(node.body); // ensure the generated return statement is covered retStatement.loc = node.body.loc; node.body = this.convertToBlock(retStatement); node.expression = false; } }
n/a
branchIncrementExprAst = function (varName, branchIndex, down) { var ret = astgen.postIncrement( astgen.subscript( astgen.subscript( astgen.dot(astgen.variable(this.currentState.trackerVar), astgen.variable('b')), astgen.stringLiteral(varName) ), astgen.numericLiteral(branchIndex) ), down ); return ret; }
n/a
branchLocationFor = function (name, index) { return this.coverState.branchMap[name].locations[index]; }
n/a
branchName = function (type, startLine, pathLocations) { var bName, paths = [], locations = [], i, ignoring = !!this.currentState.ignoring; this.currentState.branch += 1; bName = this.currentState.branch; for (i = 0; i < pathLocations.length; i += 1) { pathLocations[i].skip = pathLocations[i].skip || ignoring || undefined; locations.push(pathLocations[i]); paths.push(0); } this.coverState.b[bName] = paths; this.coverState.branchMap[bName] = { line: startLine, type: type, locations: locations }; return bName; }
n/a
conditionalBranchInjector = function (node, walker) { var bName = this.branchName('cond-expr', walker.startLineForNode(node), this.locationsForNodes([ node.consequent, node.alternate ])), ast1 = this.branchIncrementExprAst(bName, 0), ast2 = this.branchIncrementExprAst(bName, 1); node.consequent.preprocessor = this.maybeAddSkip(this.branchLocationFor(bName, 0)); node.alternate.preprocessor = this.maybeAddSkip(this.branchLocationFor(bName, 1)); node.consequent = astgen.sequence(ast1, node.consequent); node.alternate = astgen.sequence(ast2, node.alternate); }
n/a
convertToBlock = function (node) { if (!node) { return { type: 'BlockStatement', body: [] }; } else if (node.type === 'BlockStatement') { return node; } else { return { type: 'BlockStatement', body: [ node ] }; } }
n/a
coverExport = function (node, walker) { var sName, incrStatementCount; if ( !node.declaration || !node.declaration.declarations ) { return; } this.maybeSkipNode(node, 'next'); sName = this.statementName(node.declaration.loc); incrStatementCount = astgen.statement( astgen.postIncrement( astgen.subscript( astgen.dot(astgen.variable(this.currentState.trackerVar), astgen.variable('s')), astgen.stringLiteral(sName) ) ) ); this.splice(incrStatementCount, node, walker); }
n/a
coverFunction = function (node, walker) { var id, body = node.body, blockBody = body.body, popped; this.maybeSkipNode(node, 'next'); id = this.functionName(node, walker.startLineForNode(node), { start: node.loc.start, end: { line: node.body.loc.start.line, column: node.body.loc.start.column } }); if (blockBody.length > 0 && this.isUseStrictExpression(blockBody[0])) { popped = blockBody.shift(); } blockBody.unshift( astgen.statement( astgen.postIncrement( astgen.subscript( astgen.dot(astgen.variable(this.currentState.trackerVar), astgen.variable('f')), astgen.stringLiteral(id) ) ) ) ); if (popped) { blockBody.unshift(popped); } }
n/a
function(node) { node.skipSelf = true; }
n/a
coverStatement = function (node, walker) {
var sName,
incrStatementCount,
parent,
grandParent;
this.maybeSkipNode(node, 'next');
if (this.isUseStrictExpression(node)) {
grandParent = walker.ancestor(2);
/* istanbul ignore else: difficult to test */
if (grandParent) {
if ((grandParent.node.type === SYNTAX.FunctionExpression.name ||
grandParent.node.type === SYNTAX.FunctionDeclaration.name) &&
walker.parent().node.body[0] === node) {
return;
}
}
}
if (node.type === SYNTAX.FunctionDeclaration.name) {
// Called for the side-effect of setting the function's statement count to 1.
this.statementName(node.loc, 1);
} else {
// We let `coverExport` handle ExportNamedDeclarations.
parent = walker.parent();
if (parent && parent.node.type === SYNTAX.ExportNamedDeclaration.name) {
return;
}
sName = this.statementName(node.loc);
incrStatementCount = astgen.statement(
astgen.postIncrement(
astgen.subscript(
astgen.dot(astgen.variable(this.currentState.trackerVar), astgen.variable('s')),
astgen.stringLiteral(sName)
)
)
);
this.splice(incrStatementCount, node, walker);
}
}
n/a
endIgnore = function () { this.currentState.ignoring -= 1; }
n/a
extractCurrentHint = function (node) { if (!node.range) { return; } var i = this.currentState.lastHintPosition + 1, hints = this.currentState.hints, nodeStart = node.range[0], hint; this.currentState.currentHint = null; // coverage-hack - allow top-level istanbul-ignore-next if (node.type === "Program") { return; } while (i < hints.length) { hint = hints[i]; if (hint.end < nodeStart) { this.currentState.currentHint = hint; this.currentState.lastHintPosition = i; i += 1; } else { break; } } }
n/a
filterHints = function (comments) {
var ret = [],
i,
comment,
groups;
if (!(comments && isArray(comments))) {
return ret;
}
for (i = 0; i < comments.length; i += 1) {
comment = comments[i];
/* istanbul ignore else: paranoid check */
if (comment && comment.value && comment.range && isArray(comment.range)) {
groups = String(comment.value).match(COMMENT_RE);
if (groups) {
ret.push({ type: groups[1], start: comment.range[0], end: comment.range[1] });
}
}
}
return ret;
}
n/a
findLeaves = function (node, accumulator, parent, property) { if (node.type === SYNTAX.LogicalExpression.name) { this.findLeaves(node.left, accumulator, node, 'left'); this.findLeaves(node.right, accumulator, node, 'right'); } else { accumulator.push({ node: node, parent: parent, property: property }); } }
n/a
fixColumnPositions = function (coverState) {
var offset = LEADER_WRAP.length,
fixer = function (loc) {
if (loc.start.line === 1) {
loc.start.column -= offset;
}
if (loc.end.line === 1) {
loc.end.column -= offset;
}
},
k,
obj,
i,
locations;
obj = coverState.statementMap;
for (k in obj) {
/* istanbul ignore else: has own property */
if (obj.hasOwnProperty(k)) { fixer(obj[k]); }
}
obj = coverState.fnMap;
for (k in obj) {
/* istanbul ignore else: has own property */
if (obj.hasOwnProperty(k)) { fixer(obj[k].loc); }
}
obj = coverState.branchMap;
for (k in obj) {
/* istanbul ignore else: has own property */
if (obj.hasOwnProperty(k)) {
locations = obj[k].locations;
for (i = 0; i < locations.length; i += 1) {
fixer(locations[i]);
}
}
}
}
n/a
functionName = function (node, line, location) { this.currentState.func += 1; var id = this.currentState.func, ignoring = !!this.currentState.ignoring, name = node.id ? node.id.name : '(anonymous_' + id + ')', clone = function (attr) { var obj = location[attr] || /* istanbul ignore next */ {}; return { line: obj.line, column: obj.column }; }; this.coverState.fnMap[id] = { name: name, line: line, loc: { start: clone('start'), end: clone('end') }, skip: ignoring || undefined }; this.coverState.f[id] = 0; return id; }
n/a
getPreamble = function (sourceCode, emitUseStrict) { var varName = this.opts.coverageVariable || '__coverage__', file = this.coverState.path.replace(/\\/g, '\\\\'), tracker = this.currentState.trackerVar, coverState, strictLine = emitUseStrict ? '"use strict";' : '', // return replacements using the function to ensure that the replacement is // treated like a dumb string and not as a string with RE replacement patterns replacer = function (s) { return function () { return s; }; }, code; if (!this.opts.noAutoWrap) { this.fixColumnPositions(this.coverState); } if (this.opts.embedSource) { this.coverState.code = sourceCode.split(/(?:\r?\n)|\r/); } coverState = this.opts.debug ? JSON.stringify(this.coverState, undefined, 4) : JSON.stringify(this.coverState); code = [ "%STRICT%", "var %VAR% = (Function('return this'))();", "if (!%VAR%.%GLOBAL%) { %VAR%.%GLOBAL% = {}; }", "%VAR% = %VAR%.%GLOBAL%;", "if (!(%VAR%['%FILE%'])) {", " %VAR%['%FILE%'] = %OBJECT%;", "}", "%VAR% = %VAR%['%FILE%'];" ].join("\n") .replace(/%STRICT%/g, replacer(strictLine)) .replace(/%VAR%/g, replacer(tracker)) .replace(/%GLOBAL%/g, replacer(varName)) .replace(/%FILE%/g, replacer(file)) .replace(/%OBJECT%/g, replacer(coverState)); return code; }
n/a
ifBlockConverter = function (node) { node.consequent = this.convertToBlock(node.consequent); node.alternate = this.convertToBlock(node.alternate); }
n/a
ifBranchInjector = function (node, walker) { var alreadyIgnoring = !!this.currentState.ignoring, hint = this.currentState.currentHint, ignoreThen = !alreadyIgnoring && hint && hint.type === 'if', ignoreElse = !alreadyIgnoring && hint && hint.type === 'else', line = node.loc.start.line, col = node.loc.start.column, makeLoc = function () { return { line: line, column: col }; }, bName = this.branchName('if', walker.startLineForNode(node), [ { start: makeLoc(), end: makeLoc(), skip: ignoreThen || undefined }, { start: makeLoc(), end: makeLoc(), skip: ignoreElse || undefined } ]), thenBody = node.consequent.body, elseBody = node.alternate.body, child; thenBody.unshift(astgen.statement(this.branchIncrementExprAst(bName, 0))); elseBody.unshift(astgen.statement(this.branchIncrementExprAst(bName, 1))); if (ignoreThen) { child = node.consequent; child.preprocessor = this.startIgnore; child.postprocessor = this.endIgnore; } if (ignoreElse) { child = node.alternate; child.preprocessor = this.startIgnore; child.postprocessor = this.endIgnore; } }
n/a
instrument = function (code, filename, callback) { if (!callback && typeof filename === 'function') { callback = filename; filename = null; } try { callback(null, this.instrumentSync(code, filename)); } catch (ex) { callback(ex); } }
n/a
instrumentASTSync = function (program, filename, originalCode) { var usingStrict = false, codegenOptions, generated, preamble, lineCount, i; filename = filename || String(new Date().getTime()) + '.js'; this.sourceMap = null; this.coverState = { path: filename, s: {}, b: {}, f: {}, fnMap: {}, statementMap: {}, branchMap: {} }; this.currentState = { trackerVar: generateTrackerVar(filename, this.omitTrackerSuffix), func: 0, branch: 0, variable: 0, statement: 0, hints: this.filterHints(program.comments), currentHint: null, lastHintPosition: -1, ignoring: 0 }; if (program.body && program.body.length > 0 && this.isUseStrictExpression(program.body[0])) { //nuke it program.body.shift(); //and add it back at code generation time usingStrict = true; } this.walker.startWalk(program); codegenOptions = this.opts.codeGenerationOptions || { format: { compact: !this.opts.noCompact }}; codegenOptions.comment = this.opts.preserveComments; //console.log(JSON.stringify(program, undefined, 2)); generated = ESPGEN.generate(program, codegenOptions); preamble = this.getPreamble(originalCode || '', usingStrict); if (generated.map && generated.code) { lineCount = preamble.split(/\r\n|\r|\n/).length; // offset all the generated line numbers by the number of lines in the preamble for (i = 0; i < generated.map._mappings._array.length; i += 1) { generated.map._mappings._array[i].generatedLine += lineCount; } this.sourceMap = generated.map; generated = generated.code; } return preamble + '\n' + generated + '\n'; }
n/a
instrumentSync = function (code, filename) { var program; //protect from users accidentally passing in a Buffer object instead if (typeof code !== 'string') { throw new Error('Code must be string'); } if (code.charAt(0) === '#') { //shebang, 'comment' it out, won't affect syntax tree locations for things we care about code = '//' + code; } if (!this.opts.noAutoWrap) { code = LEADER_WRAP + code + TRAILER_WRAP; } try { program = ESP.parse(code, { loc: true, range: true, tokens: this.opts.preserveComments, comment: true, sourceType: this.opts.esModules ? 'module' : 'script' }); } catch (e) { console.log('Failed to parse file: ' + filename); throw e; } if (this.opts.preserveComments) { program = ESPGEN.attachComments(program, program.comments, program.tokens); } if (!this.opts.noAutoWrap) { program = { type: SYNTAX.Program.name, body: program.body[0].expression.callee.body.body, comments: program.comments }; } return this.instrumentASTSync(program, filename, code); }
...
) >= 0
|| code.indexOf(
"/* istanbul instrument in package "
+ process.env.npm_config_mode_coverage + " */\n"
) >= 0
)
)
? local.instrumentSync(code, file)
: code
);
};
local.instrumentSync = function (code, file) {
/*
* this function will
...
isUseStrictExpression = function (node) { return node && node.type === SYNTAX.ExpressionStatement.name && node.expression && node.expression.type === SYNTAX.Literal.name && node.expression.value === 'use strict'; }
n/a
lastFileCoverage = function () { return this.coverState; }
n/a
lastSourceMap = function () { return this.sourceMap; }
n/a
locationsForNodes = function (nodes) { var ret = [], i; for (i = 0; i < nodes.length; i += 1) { ret.push(nodes[i].loc); } return ret; }
n/a
logicalExpressionBranchInjector = function (node, walker) { var parent = walker.parent(), leaves = [], bName, tuple, i; this.maybeSkipNode(node, 'next'); if (parent && parent.node.type === SYNTAX.LogicalExpression.name) { //already covered return; } this.findLeaves(node, leaves); bName = this.branchName('binary-expr', walker.startLineForNode(node), this.locationsForNodes(leaves.map(function (item) { return item.node; })) ); for (i = 0; i < leaves.length; i += 1) { tuple = leaves[i]; tuple.parent[tuple.property] = astgen.sequence(this.branchIncrementExprAst(bName, i), tuple.node); tuple.node.preprocessor = this.maybeAddSkip(this.branchLocationFor(bName, i)); } }
n/a
loopBlockConverter = function (node) { node.body = this.convertToBlock(node.body); }
n/a
maybeAddSkip = function (branchLocation) { return function (node) { var alreadyIgnoring = !!this.currentState.ignoring, hint = this.currentState.currentHint, ignoreThis = !alreadyIgnoring && hint && hint.type === 'next'; if (ignoreThis) { this.startIgnore(); node.postprocessor = this.endIgnore; } if (ignoreThis || alreadyIgnoring) { branchLocation.skip = true; } }; }
n/a
maybeAddType = function (node) { var props = node.properties, i, child; for (i = 0; i < props.length; i += 1) { child = props[i]; if (!child.type) { child.type = SYNTAX.Property.name; } } }
n/a
maybeSkipNode = function (node, type) { var alreadyIgnoring = !!this.currentState.ignoring, hint = this.currentState.currentHint, ignoreThis = !alreadyIgnoring && hint && hint.type === type; if (ignoreThis) { this.startIgnore(); node.postprocessor = this.endIgnore; return true; } return false; }
n/a
paranoidHandlerCheck = function (node) {
// if someone is using an older esprima on the browser
// convert handlers array to single handler attribute
// containing its first element
/* istanbul ignore next */
if (!node.handler && node.handlers) {
node.handler = node.handlers[0];
}
}
n/a
skipInit = function (node) { if (node.init) { node.init.skipWalk = true; } }
n/a
skipLeft = function (node) { node.left.skipWalk = true; }
n/a
splice = function (statements, node, walker) { var targetNode = walker.isLabeled() ? walker.parent().node : node; targetNode.prepend = targetNode.prepend || []; pushAll(targetNode.prepend, statements); }
...
if (this.type === Syntax.BlockStatement && this.body.length === 0) {
innerComments = [];
for (i = extra.leadingComments.length - 1; i >= 0; --i) {
comment = extra.leadingComments[i];
if (this.range[1] >= comment.range[1]) {
innerComments.unshift(comment);
extra.leadingComments.splice(i, 1);
extra.trailingComments.splice(i, 1);
}
}
if (innerComments.length) {
this.innerComments = innerComments;
//bottomRight.push(this);
return;
...
startIgnore = function () { this.currentState.ignoring += 1; }
n/a
statementName = function (location, initValue) { var sName, ignoring = !!this.currentState.ignoring; location.skip = ignoring || undefined; initValue = initValue || 0; this.currentState.statement += 1; sName = this.currentState.statement; this.coverState.statementMap[sName] = location; this.coverState.s[sName] = initValue; return sName; }
n/a
switchBranchInjector = function (node, walker) { var cases = node.cases, bName, i; if (!(cases && cases.length > 0)) { return; } bName = this.branchName('switch', walker.startLineForNode(node), this.locationsForNodes(cases)); for (i = 0; i < cases.length; i += 1) { cases[i].branchLocation = this.branchLocationFor(bName, i); cases[i].consequent.unshift(astgen.statement(this.branchIncrementExprAst(bName, i))); } }
n/a
switchCaseInjector = function (node) { var location = node.branchLocation; delete node.branchLocation; if (this.maybeSkipNode(node, 'next')) { location.skip = true; } }
n/a
withBlockConverter = function (node) { node.body = this.convertToBlock(node.body); }
n/a
function TextReport(opts) { Report.call(this); opts = opts || {}; this.dir = opts.dir || process.cwd(); this.file = opts.file; this.summary = opts.summary; this.maxCols = opts.maxCols || 0; this.watermarks = opts.watermarks || defaults.watermarks(); }
...
+ "background: #fff; border: 1px solid #000; margin 0; padding: 0;"
+ "\">\n"
);
local.writerData = "";
opt.sourceStore = {};
opt.writer = local.writer;
// 1. print coverage in text-format to stdout
new local.TextReport(opt).writeReport(local.collector);
// 2. write coverage in html-format to filesystem
new local.HtmlReport(opt).writeReport(local.collector);
local.writer.writeFile("", local.nop);
if (!local.isBrowser) {
// write coverage.json
local.fsWriteFileWithMkdirpSync(
opt.dir + "/coverage.json",
...
writeReport = function (collector) { var summarizer = new TreeSummarizer(), tree, root, nameWidth, statsWidth = 4 * ( PCT_COLS + 2), maxRemaining, strings = [], text; collector.files().forEach(function (key) { summarizer.addFileCoverageSummary(key, utils.summarizeFileCoverage(collector.fileCoverageFor(key))); }); tree = summarizer.getTreeSummary(); root = tree.root; nameWidth = findNameWidth(root); if (this.maxCols > 0) { maxRemaining = this.maxCols - statsWidth - 2; if (nameWidth > maxRemaining) { nameWidth = maxRemaining; } } walk(root, nameWidth, strings, 0, this.watermarks); text = strings.join('\n') + '\n'; if (this.file) { mkdirp.sync(this.dir); fs.writeFileSync(path.join(this.dir, this.file), text, 'utf8'); } else { console.log(text); } }
...
+ "background: #fff; border: 1px solid #000; margin 0; padding: 0;"
+ "\">\n"
);
local.writerData = "";
opt.sourceStore = {};
opt.writer = local.writer;
// 1. print coverage in text-format to stdout
new local.TextReport(opt).writeReport(local.collector);
// 2. write coverage in html-format to filesystem
new local.HtmlReport(opt).writeReport(local.collector);
local.writer.writeFile("", local.nop);
if (!local.isBrowser) {
// write coverage.json
local.fsWriteFileWithMkdirpSync(
opt.dir + "/coverage.json",
...
readFileSync = function (file) { // return head.txt or foot.txt file = local[file.slice(-8)]; if (local.isBrowser) { file = file .replace("<!doctype html>\n", "") .replace(( /(<\/?)(?:body|html)/g ), "$1div"); } if (!local.isBrowser && process.env.npm_package_homepage) { file = file.replace( "https://github.com/kaizhu256/node-utility2", process.env.npm_package_homepage ).replace( "utility2", process.env.npm_package_name ).replace( "2019.8.11", process.env.npm_package_version ); } else { file = file.replace(( /<h1\u0020[\S\s]*<\/h1>/ ), ""); } return file; }
...
local.tryCatchOnError(function () {
file = local.path.resolve(opt.dir, file);
console.error("apidocCreate - readExample " + file);
result = "";
result = (
"\n\n\n\n\n\n\n\n"
// bug-workaround - truncate example to manageable size
+ local.fs.readFileSync(file, "utf8").slice(0, 262144)
+ "\n\n\n\n\n\n\n\n"
).replace((
/\r\n*/g
), "\n");
}, console.error);
return result;
};
...
readdirSync = function () { return []; }
...
].forEach(function (file) {
local.fs.exists(file, function (exists) {
if (exists) {
local.onFileModifiedRestart(file);
}
});
});
local.fs.readdirSync(process.cwd()).forEach(function (file) {
file = process.cwd() + "/" + file;
// if the file is modified, then restart the process
local.onFileModifiedRestart(file);
switch (local.path.basename(file)) {
// swagger-validate assets.swgg.swagger.json
case "assets.swgg.swagger.json":
local.fs.readFile(file, "utf8", function (err, data) {
...
cover = function () {
/*
* <script>
* will run and cover <script>
*/
var tmp;
try {
tmp = JSON.parse(local.fs.readFileSync("package.json", "utf8"));
process.env.npm_package_nameLib = (
process.env.npm_package_nameLib
|| tmp.nameLib
|| tmp.name.replace((
/-/g
), "_")
);
} catch (ignore) {}
process.env.npm_config_mode_coverage = (
process.env.npm_config_mode_coverage
|| process.env.npm_package_nameLib
|| "all"
);
// add coverage hook to require
local._istanbul_moduleExtensionsJs = (
local._istanbul_module._extensions[".js"]
);
local._istanbul_module._extensions[".js"] = function (module, file) {
if (typeof file === "string" && (
file.indexOf(process.env.npm_config_mode_coverage_dir) === 0 || (
file.indexOf(process.cwd()) === 0
&& file.indexOf(process.cwd() + "/node_modules/") !== 0
)
)) {
module._compile(local.instrumentInPackage(
local.fs.readFileSync(file, "utf8"),
file
), file);
return;
}
local._istanbul_moduleExtensionsJs(module, file);
};
// init process.argv
process.argv.splice(1, 2);
process.argv[1] = local.path.resolve(process.cwd(), process.argv[1]);
console.log("\ncovering $ " + process.argv.join(" "));
// create coverage on exit
process.on("exit", function () {
local.coverageReportCreate({
coverage: globalThis.__coverage__
});
});
// re-init cli
local._istanbul_module.runMain();
}
n/a
instrument = function () {
/*
* <script>
* will instrument <script> and print result to stdout
*/
process.argv[3] = local.path.resolve(process.cwd(), process.argv[3]);
process.stdout.write(local.instrumentSync(
local.fs.readFileSync(process.argv[3], "utf8"),
process.argv[3]
));
}
n/a
test = function () {
/*
* <script>
* will run and cover <script> if env var $npm_config_mode_coverage is set
*/
if (process.env.npm_config_mode_coverage) {
process.argv[2] = "cover";
// re-init cli
local.cliDict[process.argv[2]]();
return;
}
// restart node with __filename removed from process.argv
process.argv.splice(1, 2);
process.argv[1] = local.path.resolve(process.cwd(), process.argv[1]);
// re-init cli
local._istanbul_module.runMain();
}
...
return {
elemList: Object.keys(module).filter(function (key) {
return local.tryCatchOnError(function () {
return (
key
&& (
/^\w[\w\-.]*?$/
).test(key)
&& key.indexOf("testCase_") !== 0
&& (
module[key] !== opt.blacklistDict[key]
|| opt.whitelistDict[key]
)
);
}, console.error);
...
fileCoverageFor = function (file) { return globalThis.__coverage__[file]; }
n/a
files = function () { return Object.keys(globalThis.__coverage__).filter(function (key) { if ( globalThis.__coverage__[key] && globalThis.__coverageCodeDict__[key] ) { // reset derived info globalThis.__coverage__[key].l = null; return true; } }); }
n/a
function addDerivedInfo(coverage) { Object.keys(coverage).forEach(function (k) { addDerivedInfoForFile(coverage[k]); }); }
n/a
function addDerivedInfoForFile(fileCoverage) { var statementMap = fileCoverage.statementMap, statements = fileCoverage.s, lineMap; if (!fileCoverage.l) { fileCoverage.l = lineMap = {}; Object.keys(statements).forEach(function (st) { var line = statementMap[st].start.line, count = statements[st], prevVal = lineMap[line]; if (count === 0 && statementMap[st].skip) { count = 1; } if (typeof prevVal === 'undefined' || prevVal < count) { lineMap[line] = count; } }); } }
n/a
function blankSummary() { return { lines: { total: 0, covered: 0, skipped: 0, pct: 'Unknown' }, statements: { total: 0, covered: 0, skipped: 0, pct: 'Unknown' }, functions: { total: 0, covered: 0, skipped: 0, pct: 'Unknown' }, branches: { total: 0, covered: 0, skipped: 0, pct: 'Unknown' } }; }
n/a
function mergeFileCoverage(first, second) { var ret = JSON.parse(JSON.stringify(first)), i; delete ret.l; //remove derived info Object.keys(second.s).forEach(function (k) { ret.s[k] += second.s[k]; }); Object.keys(second.f).forEach(function (k) { ret.f[k] += second.f[k]; }); Object.keys(second.b).forEach(function (k) { var retArray = ret.b[k], secondArray = second.b[k]; for (i = 0; i < retArray.length; i += 1) { retArray[i] += secondArray[i]; } }); return ret; }
n/a
function mergeSummaryObjects() { var ret = blankSummary(), args = Array.prototype.slice.call(arguments), keys = ['lines', 'statements', 'branches', 'functions'], increment = function (obj) { if (obj) { keys.forEach(function (key) { ret[key].total += obj[key].total; ret[key].covered += obj[key].covered; ret[key].skipped += obj[key].skipped; }); } }; args.forEach(function (arg) { increment(arg); }); keys.forEach(function (key) { ret[key].pct = percent(ret[key].covered, ret[key].total); }); return ret; }
n/a
function removeDerivedInfo(coverage) { Object.keys(coverage).forEach(function (k) { delete coverage[k].l; }); }
n/a
function summarizeCoverage(coverage) { var fileSummary = []; Object.keys(coverage).forEach(function (key) { fileSummary.push(summarizeFileCoverage(coverage[key])); }); return mergeSummaryObjects.apply(null, fileSummary); }
n/a
function summarizeFileCoverage(fileCoverage) { var ret = blankSummary(); addDerivedInfoForFile(fileCoverage); ret.lines = computeSimpleTotals(fileCoverage, 'l'); ret.functions = computeSimpleTotals(fileCoverage, 'f', 'fnMap'); ret.statements = computeSimpleTotals(fileCoverage, 's', 'statementMap'); ret.branches = computeBranchTotals(fileCoverage); return ret; }
n/a
function toYUICoverage(coverage) { var ret = {}; addDerivedInfo(coverage); Object.keys(coverage).forEach(function (k) { var fileCoverage = coverage[k], lines = fileCoverage.l, functions = fileCoverage.f, fnMap = fileCoverage.fnMap, o; o = ret[k] = { lines: {}, calledLines: 0, coveredLines: 0, functions: {}, calledFunctions: 0, coveredFunctions: 0 }; Object.keys(lines).forEach(function (k) { o.lines[k] = lines[k]; o.coveredLines += 1; if (lines[k] > 0) { o.calledLines += 1; } }); Object.keys(functions).forEach(function (k) { var name = fnMap[k].name + ':' + fnMap[k].line; o.functions[name] = functions[k]; o.coveredFunctions += 1; if (functions[k] > 0) { o.calledFunctions += 1; } }); }); return ret; }
n/a
function attachComments(tree, providedComments, tokens) { // At first, we should calculate extended comment ranges. var comments = [], comment, len, i, cursor; if (!tree.range) { throw new Error('attachComments needs range information'); } // tokens array is empty, we attach comments to tree as 'leadingComments' if (!tokens.length) { if (providedComments.length) { for (i = 0, len = providedComments.length; i < len; i += 1) { comment = deepCopy(providedComments[i]); comment.extendedRange = [0, tree.range[0]]; comments.push(comment); } tree.leadingComments = comments; } return tree; } for (i = 0, len = providedComments.length; i < len; i += 1) { comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens)); } // This is based on John Freeman's implementation. cursor = 0; traverse(tree, { enter: function (node) { var comment; while (cursor < comments.length) { comment = comments[cursor]; if (comment.extendedRange[1] > node.range[0]) { break; } if (comment.extendedRange[1] === node.range[0]) { if (!node.leadingComments) { node.leadingComments = []; } node.leadingComments.push(comment); comments.splice(cursor, 1); } else { cursor += 1; } } // already out of owned node if (cursor === comments.length) { return VisitorOption.Break; } if (comments[cursor].extendedRange[0] > node.range[1]) { return VisitorOption.Skip; } } }); cursor = 0; traverse(tree, { leave: function (node) { var comment; while (cursor < comments.length) { comment = comments[cursor]; if (node.range[1] < comment.extendedRange[0]) { break; } if (node.range[1] === comment.extendedRange[0]) { if (!node.trailingComments) { node.trailingComments = []; } node.trailingComments.push(comment); comments.splice(cursor, 1); } else { cursor += 1; } } // already out of owned node if (cursor === comments.length) { return VisitorOption.Break; } if (comments[cursor].extendedRange[0] > node.range[1]) { return VisitorOption.Skip; } } }); return tree; }
n/a
function generate(node, options) { var defaultOptions = getDefaultOptions(), result, pair; if (options != null) { // Obsolete options // // `options.indent` // `options.base` // // Instead of them, we can use `option.format.indent`. if (typeof options.indent === 'string') { defaultOptions.format.indent.style = options.indent; } if (typeof options.base === 'number') { defaultOptions.format.indent.base = options.base; } options = updateDeeply(defaultOptions, options); indent = options.format.indent.style; if (typeof options.base === 'string') { base = options.base; } else { base = stringRepeat(indent, options.format.indent.base); } } else { options = defaultOptions; indent = options.format.indent.style; base = stringRepeat(indent, options.format.indent.base); } json = options.format.json; renumber = options.format.renumber; hexadecimal = json ? false : options.format.hexadecimal; quotes = json ? 'double' : options.format.quotes; escapeless = options.format.escapeless; newline = options.format.newline; space = options.format.space; if (options.format.compact) { newline = space = indent = base = ''; } parentheses = options.format.parentheses; semicolons = options.format.semicolons; safeConcatenation = options.format.safeConcatenation; directive = options.directive; parse = json ? null : options.parse; sourceMap = options.sourceMap; sourceCode = options.sourceCode; preserveBlankLines = options.format.preserveBlankLines && sourceCode !== null; extra = options; if (sourceMap) { if (!exports.browser) { // We assume environment is node.js // And prevent from including source-map by browserify SourceNode = require('source-map').SourceNode; } else { SourceNode = global.sourceMap.SourceNode; } } result = generateInternal(node); if (!sourceMap) { pair = {code: result.toString(), map: null}; return options.sourceMapWithCode ? pair : pair.code; } pair = result.toStringWithSourceMap({ file: options.file, sourceRoot: options.sourceMapRoot }); if (options.sourceContent) { pair.map.setSourceContent(options.sourceMap, options.sourceContent); } if (options.sourceMapWithCode) { return pair; } return pair.map.toString(); }
n/a
function parse(code, options) { var program, toString; toString = String; if (typeof code !== 'string' && !(code instanceof String)) { code = toString(code); } source = code; index = 0; lineNumber = (source.length > 0) ? 1 : 0; lineStart = 0; startIndex = index; startLineNumber = lineNumber; startLineStart = lineStart; length = source.length; lookahead = null; state = { allowIn: true, allowYield: true, labelSet: {}, inFunctionBody: false, inIteration: false, inSwitch: false, lastCommentStart: -1, curlyStack: [], sourceType: 'script' }; strict = false; extra = {}; if (typeof options !== 'undefined') { extra.range = (typeof options.range === 'boolean') && options.range; extra.loc = (typeof options.loc === 'boolean') && options.loc; extra.attachComment = (typeof options.attachComment === 'boolean') && options.attachComment; if (extra.loc && options.source !== null && options.source !== undefined) { extra.source = toString(options.source); } if (typeof options.tokens === 'boolean' && options.tokens) { extra.tokens = []; } if (typeof options.comment === 'boolean' && options.comment) { extra.comments = []; } if (typeof options.tolerant === 'boolean' && options.tolerant) { extra.errors = []; } if (extra.attachComment) { extra.range = true; extra.comments = []; extra.bottomRightStack = []; extra.trailingComments = []; extra.leadingComments = []; } if (options.sourceType === 'module') { // very restrictive condition for now state.sourceType = options.sourceType; strict = true; } } try { program = parseProgram(); if (typeof extra.comments !== 'undefined') { program.comments = extra.comments; } if (typeof extra.tokens !== 'undefined') { filterTokenLocation(); program.tokens = extra.tokens; } if (typeof extra.errors !== 'undefined') { program.errors = extra.errors; } } catch (e) { throw e; } finally { extra = {}; } return program; }
...
opt.dir,
opt.modulePathList || require("module").paths
);
local.objectSetDefault(opt, {
env: {
npm_package_description: ""
},
packageJson: JSON.parse(readExample("package.json")),
require: function (file) {
return local.tryCatchOnError(function () {
return require(file);
}, console.error);
}
});
Object.keys(opt.packageJson).forEach(function (key) {
...
function tokenize(code, options, delegate) { var toString, tokens; toString = String; if (typeof code !== 'string' && !(code instanceof String)) { code = toString(code); } source = code; index = 0; lineNumber = (source.length > 0) ? 1 : 0; lineStart = 0; startIndex = index; startLineNumber = lineNumber; startLineStart = lineStart; length = source.length; lookahead = null; state = { allowIn: true, allowYield: true, labelSet: {}, inFunctionBody: false, inIteration: false, inSwitch: false, lastCommentStart: -1, curlyStack: [] }; extra = {}; // Options matching. options = options || {}; // Of course we collect tokens here. options.tokens = true; extra.tokens = []; extra.tokenValues = []; extra.tokenize = true; extra.delegate = delegate; // The following two fields are necessary to compute the Regex tokens. extra.openParenToken = -1; extra.openCurlyToken = -1; extra.range = (typeof options.range === 'boolean') && options.range; extra.loc = (typeof options.loc === 'boolean') && options.loc; if (typeof options.comment === 'boolean' && options.comment) { extra.comments = []; } if (typeof options.tolerant === 'boolean' && options.tolerant) { extra.errors = []; } try { peek(); if (lookahead.type === Token.EOF) { return extra.tokens; } lex(); while (lookahead.type !== Token.EOF) { try { lex(); } catch (lexError) { if (extra.errors) { recordError(lexError); // We have to break on the first error // to avoid infinite loops. break; } else { throw lexError; } } } tokens = extra.tokens; if (typeof extra.errors !== 'undefined') { tokens.errors = extra.errors; } } catch (e) { throw e; } finally { extra = {}; } return tokens; }
n/a
function Controller() { }
n/a
function attachComments(tree, providedComments, tokens) { // At first, we should calculate extended comment ranges. var comments = [], comment, len, i, cursor; if (!tree.range) { throw new Error('attachComments needs range information'); } // tokens array is empty, we attach comments to tree as 'leadingComments' if (!tokens.length) { if (providedComments.length) { for (i = 0, len = providedComments.length; i < len; i += 1) { comment = deepCopy(providedComments[i]); comment.extendedRange = [0, tree.range[0]]; comments.push(comment); } tree.leadingComments = comments; } return tree; } for (i = 0, len = providedComments.length; i < len; i += 1) { comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens)); } // This is based on John Freeman's implementation. cursor = 0; traverse(tree, { enter: function (node) { var comment; while (cursor < comments.length) { comment = comments[cursor]; if (comment.extendedRange[1] > node.range[0]) { break; } if (comment.extendedRange[1] === node.range[0]) { if (!node.leadingComments) { node.leadingComments = []; } node.leadingComments.push(comment); comments.splice(cursor, 1); } else { cursor += 1; } } // already out of owned node if (cursor === comments.length) { return VisitorOption.Break; } if (comments[cursor].extendedRange[0] > node.range[1]) { return VisitorOption.Skip; } } }); cursor = 0; traverse(tree, { leave: function (node) { var comment; while (cursor < comments.length) { comment = comments[cursor]; if (node.range[1] < comment.extendedRange[0]) { break; } if (node.range[1] === comment.extendedRange[0]) { if (!node.trailingComments) { node.trailingComments = []; } node.trailingComments.push(comment); comments.splice(cursor, 1); } else { cursor += 1; } } // already out of owned node if (cursor === comments.length) { return VisitorOption.Break; } if (comments[cursor].extendedRange[0] > node.range[1]) { return VisitorOption.Skip; } } }); return tree; }
n/a
cloneEnvironment = function () { return clone({}); }
n/a
function replace(root, visitor) { var controller = new Controller(); return controller.replace(root, visitor); }
...
argList: "'console.log(\"hello world\")'",
description: "example:",
command: [
"--eval"
]
}
];
file = __filename.replace((
/.*\//
), "");
opt = Object.assign({}, opt);
packageJson = require("./package.json");
// validate comment
opt.rgxComment = opt.rgxComment || (
/\)\u0020\{\n(?:|\u0020{4})\/\*\n(?:\u0020|\u0020{5})\*((?:\u0020<[^>]*?>|\u0020\.\.\.)*?)\n(?:\u0020|\u0020{5})\*\
u0020(will\u0020.*?\S)\n(?:\u0020|\u0020{5})\*\/\n(?:\u0020{4}|\u0020{8})\S/
...
function traverse(root, visitor) { var controller = new Controller(); return controller.traverse(root, visitor); }
...
}
return outer.root;
};
function traverse(root, visitor) {
var controller = new Controller();
return controller.traverse(root, visitor);
}
function replace(root, visitor) {
var controller = new Controller();
return controller.replace(root, visitor);
}
...
function __execute(callback, element) { var previous, result; result = undefined; previous = this.__current; this.__current = element; this.__state = null; if (callback) { result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node); } this.__current = previous; return result; }
...
while (worklist.length) {
element = worklist.pop();
if (element === sentinel) {
element = leavelist.pop();
ret = this.__execute(visitor.leave, element);
if (this.__state === BREAK || ret === BREAK) {
return;
}
continue;
}
...
function(root, visitor) { this.visitor = visitor; this.root = root; this.__worklist = []; this.__leavelist = []; this.__current = null; this.__state = null; this.__fallback = null; if (visitor.fallback === 'iteration') { this.__fallback = objectKeys; } else if (typeof visitor.fallback === 'function') { this.__fallback = visitor.fallback; } this.__keys = VisitorKeys; if (visitor.keys) { this.__keys = extend(objectCreate(this.__keys), visitor.keys); } }
...
key,
current,
current2,
candidates,
candidate,
sentinel;
this.__initialize(root, visitor);
sentinel = {};
// reference
worklist = this.__worklist;
leavelist = this.__leavelist;
...
break = function () { this.notify(BREAK); }
n/a
function current() { return this.__current.node; }
...
addToPath(result, this.__current.path);
return result;
};
// API:
// return type of current node
Controller.prototype.type = function () {
var node = this.current();
return node.type || this.__current.wrap;
};
// API:
// return array of parent elements
Controller.prototype.parents = function parents() {
var i, iz, result;
...
function notify(flag) { this.__state = flag; }
...
Controller.prototype.notify = function notify(flag) {
this.__state = flag;
};
// API:
// skip child nodes of current node
Controller.prototype.skip = function () {
this.notify(SKIP);
};
// API:
// break traversals
Controller.prototype['break'] = function () {
this.notify(BREAK);
};
...
function parents() { var i, iz, result; // first node is sentinel result = []; for (i = 1, iz = this.__leavelist.length; i < iz; ++i) { result.push(this.__leavelist[i].node); } return result; }
n/a
function path() { var i, iz, j, jz, result, element; function addToPath(result, path) { if (isArray(path)) { for (j = 0, jz = path.length; j < jz; ++j) { result.push(path[j]); } } else { result.push(path); } } // root node if (!this.__current.path) { return null; } // first node is sentinel, second node is root element result = []; for (i = 2, iz = this.__leavelist.length; i < iz; ++i) { element = this.__leavelist[i]; addToPath(result, element.path); } addToPath(result, this.__current.path); return result; }
n/a
remove = function () { this.notify(REMOVE); }
...
function removeElem(element) {
var i,
key,
nextElem,
parent;
if (element.ref.remove()) {
// When the reference is an element of an array.
key = element.ref.key;
parent = element.ref.parent;
// If removed from array, then decrease following items' keys.
i = worklist.length;
while (i--) {
...
function replace(root, visitor) { var worklist, leavelist, node, nodeType, target, element, current, current2, candidates, candidate, sentinel, outer, key; function removeElem(element) { var i, key, nextElem, parent; if (element.ref.remove()) { // When the reference is an element of an array. key = element.ref.key; parent = element.ref.parent; // If removed from array, then decrease following items' keys. i = worklist.length; while (i--) { nextElem = worklist[i]; if (nextElem.ref && nextElem.ref.parent === parent) { if (nextElem.ref.key < key) { break; } --nextElem.ref.key; } } } } this.__initialize(root, visitor); sentinel = {}; // reference worklist = this.__worklist; leavelist = this.__leavelist; // initialize outer = { root: root }; element = new Element(root, null, null, new Reference(outer, 'root')); worklist.push(element); leavelist.push(element); while (worklist.length) { element = worklist.pop(); if (element === sentinel) { element = leavelist.pop(); target = this.__execute(visitor.leave, element); // node may be replaced with null, // so distinguish between undefined and null in this place if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { // replace element.ref.replace(target); } if (this.__state === REMOVE || target === REMOVE) { removeElem(element); } if (this.__state === BREAK || target === BREAK) { return outer.root; } continue; } target = this.__execute(visitor.enter, element); // node may be replaced with null, // so distinguish between undefined and null in this place if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { // replace element.ref.replace(target); element.node = target; } if (this.__state === REMOVE || target === REMOVE) { removeElem(element); element.node = null; } if (this.__state === BREAK || target === BREAK) { return outer.root; } // node may be null node = element.node; if (!node) { continue; } worklist.push(sentinel); leavelist.push(element); if (this.__state === SKIP || target === SKIP) { continue; } nodeType = node.type || element.wrap; candidates = this.__keys[nodeType]; if (!candidates) { if (this.__fallback) { candidates = this.__fallback(node); } else { throw new Error('Unknown node type ' + nodeType + '.'); } } current = candidates.length; while ((current -= 1) >= 0) { key = candidates[current]; candidate = node[key]; if (!candidate) { continue; } if (isArray(candidate)) { current2 = candidate.length; while ((current2 -= 1) >= 0) { if (!candidate[current2]) { continue; } if (isProperty(nodeType, candidates[current])) { element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2 )); } else if (isNode(candidat...
...
argList: "'console.log(\"hello world\")'",
description: "example:",
command: [
"--eval"
]
}
];
file = __filename.replace((
/.*\//
), "");
opt = Object.assign({}, opt);
packageJson = require("./package.json");
// validate comment
opt.rgxComment = opt.rgxComment || (
/\)\u0020\{\n(?:|\u0020{4})\/\*\n(?:\u0020|\u0020{5})\*((?:\u0020<[^>]*?>|\u0020\.\.\.)*?)\n(?:\u0020|\u0020{5})\*\
u0020(will\u0020.*?\S)\n(?:\u0020|\u0020{5})\*\/\n(?:\u0020{4}|\u0020{8})\S/
...
skip = function () { this.notify(SKIP); }
n/a
function traverse(root, visitor) { var worklist, leavelist, element, node, nodeType, ret, key, current, current2, candidates, candidate, sentinel; this.__initialize(root, visitor); sentinel = {}; // reference worklist = this.__worklist; leavelist = this.__leavelist; // initialize worklist.push(new Element(root, null, null, null)); leavelist.push(new Element(null, null, null, null)); while (worklist.length) { element = worklist.pop(); if (element === sentinel) { element = leavelist.pop(); ret = this.__execute(visitor.leave, element); if (this.__state === BREAK || ret === BREAK) { return; } continue; } if (element.node) { ret = this.__execute(visitor.enter, element); if (this.__state === BREAK || ret === BREAK) { return; } worklist.push(sentinel); leavelist.push(element); if (this.__state === SKIP || ret === SKIP) { continue; } node = element.node; nodeType = node.type || element.wrap; candidates = this.__keys[nodeType]; if (!candidates) { if (this.__fallback) { candidates = this.__fallback(node); } else { throw new Error('Unknown node type ' + nodeType + '.'); } } current = candidates.length; while ((current -= 1) >= 0) { key = candidates[current]; candidate = node[key]; if (!candidate) { continue; } if (isArray(candidate)) { current2 = candidate.length; while ((current2 -= 1) >= 0) { if (!candidate[current2]) { continue; } if (isProperty(nodeType, candidates[current])) { element = new Element(candidate[current2], [key, current2], 'Property', null); } else if (isNode(candidate[current2])) { element = new Element(candidate[current2], [key, current2], null, null); } else { continue; } worklist.push(element); } } else if (isNode(candidate)) { worklist.push(new Element(candidate, key, null, null)); } } } } }
...
}
return outer.root;
};
function traverse(root, visitor) {
var controller = new Controller();
return controller.traverse(root, visitor);
}
function replace(root, visitor) {
var controller = new Controller();
return controller.replace(root, visitor);
}
...
type = function () { var node = this.current(); return node.type || this.__current.wrap; }
...
token = tokenStream.token();
endChar = token.endChar;
value = token.value + this._expr(inFunction).text;
if (unary === null) {
line = tokenStream.token().startLine;
col = tokenStream.token().startCol;
}
tokenStream.mustMatch(Tokens.type(endChar));
value += endChar;
this._readWhitespace();
//see if there's a simple match
} else if (tokenStream.match([Tokens.NUMBER, Tokens.PERCENTAGE, Tokens.LENGTH,
Tokens.ANGLE, Tokens.TIME,
Tokens.FREQ, Tokens.STRING, Tokens.IDENT, Tokens.URI, Tokens.UNICODE_RANGE])) {
...
compile = function (template) {
/*
* this function will return a function
* that will render <template> with given <dict>
*/
return function (dict) {
var result;
result = template;
// render triple-curly-brace
result = result.replace((
/\{\{\{/g
), "{{").replace((
/\}\}\}/g
), "}}");
// render with-statement
result = result.replace((
/\{\{#with\u0020(.+?)\}\}([\S\s]+?)\{\{\/with\}\}/g
), function (ignore, match1, match2) {
return local.handlebars.replace(match2, dict, match1 + ".");
});
// render helper
result = result.replace(
"{{#show_ignores metrics}}{{/show_ignores}}",
function () {
return local.handlebars.show_ignores(dict.metrics);
}
);
result = result.replace((
"{{#show_line_execution_counts fileCoverage}}"
+ "{{maxLines}}{{/show_line_execution_counts}}"
), function () {
return local.handlebars.show_line_execution_counts(
dict.fileCoverage,
{
fn: function () {
return dict.maxLines;
}
}
);
});
result = result.replace(
"{{#show_lines}}{{maxLines}}{{/show_lines}}",
function () {
return local.handlebars.show_lines({
fn: function () {
return dict.maxLines;
}
});
}
);
result = result.replace(
"{{#show_picture}}{{metrics.statements.pct}}{{/show_picture}}",
function () {
return local.handlebars.show_picture({
fn: function () {
return dict.metrics.statements.pct;
}
});
}
);
result = local.handlebars.replace(result, dict, "");
// show code last
result = result.replace(
"{{#show_code structured}}{{/show_code}}",
function () {
return local.handlebars.show_code(dict.structured);
}
);
return result;
};
}
n/a
registerHelper = function (key, helper) {
/*
* this function will register the helper-function
*/
local.handlebars[key] = function (aa, bb) {
try {
return helper(aa, bb);
} catch (ignore) {}
};
}
n/a
replace = function (template, dict, withPrefix) {
/*
* this function will render <template> with given <dict>
*/
var value;
// search for keys in the template
return template.replace((
/\{\{.+?\}\}/g
), function (match0) {
value = dict;
// iteratively lookup nested values in the dict
(withPrefix + match0.slice(2, -2)).split(".").forEach(function (key) {
value = value && value[key];
});
return (
value === undefined
? match0
: String(value)
);
});
}
...
argList: "'console.log(\"hello world\")'",
description: "example:",
command: [
"--eval"
]
}
];
file = __filename.replace((
/.*\//
), "");
opt = Object.assign({}, opt);
packageJson = require("./package.json");
// validate comment
opt.rgxComment = opt.rgxComment || (
/\)\u0020\{\n(?:|\u0020{4})\/\*\n(?:\u0020|\u0020{5})\*((?:\u0020<[^>]*?>|\u0020\.\.\.)*?)\n(?:\u0020|\u0020{5})\*\
u0020(will\u0020.*?\S)\n(?:\u0020|\u0020{5})\*\/\n(?:\u0020{4}|\u0020{8})\S/
...
show_code = function (aa, bb) { try { return helper(aa, bb); } catch (ignore) {} }
n/a
show_ignores = function (aa, bb) { try { return helper(aa, bb); } catch (ignore) {} }
n/a
show_line_execution_counts = function (aa, bb) { try { return helper(aa, bb); } catch (ignore) {} }
n/a
show_lines = function (aa, bb) { try { return helper(aa, bb); } catch (ignore) {} }
n/a
show_picture = function (aa, bb) { try { return helper(aa, bb); } catch (ignore) {} }
n/a
function _debugEnd() { [native code] }
n/a
function _debugProcess() { [native code] }
n/a
(er, fromPromise) => { // It's possible that defaultTriggerAsyncId was set for a constructor // call that threw and was never cleared. So clear it now. clearDefaultTriggerAsyncId(); // If diagnostic reporting is enabled, call into its handler to see // whether it is interested in handling the situation. // Ignore if the error is scoped inside a domain. // use == in the checks as we want to allow for null and undefined if (er == null || er.domain == null) { try { const report = internalBinding('report'); if (report != null && report.shouldReportOnUncaughtException()) { report.writeReport(er ? er.message : 'Exception', 'Exception', null, er ? er.stack : undefined); } } catch {} // Ignore the exception. Diagnostic reporting is unavailable. } const type = fromPromise ? 'unhandledRejection' : 'uncaughtException'; if (exceptionHandlerState.captureFn !== null) { exceptionHandlerState.captureFn(er); } else if (!process.emit('uncaughtException', er, type)) { // If someone handled it, then great. Otherwise, die in C++ land // since that means that we'll exit the process, emit the 'exit' event. try { if (!process._exiting) { process._exiting = true; process.exitCode = 1; process.emit('exit', 1); } } catch { // Nothing to be done about it at this point. } return false; } // If we handled an error, then make sure any ticks get processed // by ensuring that the next Immediate cycle isn't empty. require('timers').setImmediate(noop); // Emit the after() hooks now that the exception has been handled. if (afterHooksExist()) { do { emitAfter(executionAsyncId()); } while (hasAsyncIdStack()); // Or completely empty the id stack. } else { clearAsyncIdStack(); } return true; }
n/a
function _getActiveHandles() { [native code] }
n/a
function _getActiveRequests() { [native code] }
n/a
function _kill() { [native code] }
n/a
function _linkedBinding(module) { module = String(module); let mod = bindingObj[module]; if (typeof mod !== 'object') mod = bindingObj[module] = getLinkedBinding(module); return mod; }
n/a
function _rawDebug(...args) { binding._rawDebug(format.apply(null, args)); }
n/a
function _startProfilerIdleNotifier() { [native code] }
n/a
function _stopProfilerIdleNotifier() { [native code] }
n/a
function runNextTicks() { if (!hasTickScheduled() && !hasRejectionToWarn()) runMicrotasks(); if (!hasTickScheduled() && !hasRejectionToWarn()) return; processTicksAndRejections(); }
n/a
function abort() { [native code] }
...
xhrInit();
// init timerTimeout
xhr.timerTimeout = setTimeout(function () {
xhr.err = xhr.err || new Error(
"onTimeout - errTimeout - "
+ timeout + " ms - " + "ajax " + xhr.method + " " + xhr.url
);
xhr.abort();
// cleanup reqStream and resStream
streamCleanup(xhr.reqStream);
streamCleanup(xhr.resStream);
}, timeout);
// increment ajaxProgressCounter
local2.ajaxProgressCounter = local2.ajaxProgressCounter || 0;
local2.ajaxProgressCounter += 1;
...
function deprecated(...args) { if (!warned) { warned = true; if (code !== undefined) { if (!codesWarned.has(code)) { process.emitWarning(msg, 'DeprecationWarning', code, deprecated); codesWarned.add(code); } } else { process.emitWarning(msg, 'DeprecationWarning', deprecated); } } if (new.target) { return Reflect.construct(fn, args, new.target); } return fn.apply(this, args); }
...
key = '0123456789abcdef0123456789abcdef';
mode = null;
local.cryptoAesXxxCbcRawEncrypt({
data: data,
key: key,
mode: mode
}, function (err, data) {
console.assert(!err, err);
local.cryptoAesXxxCbcRawDecrypt({
data: data,
key: key,
mode: mode
}, console.log);
});
*/
...
function binding(module) { module = String(module); // Deprecated specific process.binding() modules, but not all, allow // selective fallback to internalBinding for the deprecated ones. if (internalBindingWhitelist.has(module)) { return internalBinding(module); } // eslint-disable-next-line no-restricted-syntax throw new Error(`No such module: ${module}`); }
...
&& typeof dict[key] === "function"
) {
local[tmp][key] = local[tmp][key] || String(dict[key]);
}
});
});
Object.keys(local[tmp]).forEach(function (key) {
if (process.binding("natives")[key]) {
local[tmp][key] = undefined;
}
});
});
// autofix - local-function
dictFnc = {};
dictProp = {};
...
function chdir(directory) { validateString(directory, 'directory'); binding.chdir(directory); // Mark cache that it requires an update. cachedCwd = ''; }
n/a
function cpuUsage(prevValue) { // If a previous value was passed in, ensure it has the correct shape. if (prevValue) { if (!previousValueIsValid(prevValue.user)) { if (typeof prevValue !== 'object') throw new ERR_INVALID_ARG_TYPE('prevValue', 'object', prevValue); if (typeof prevValue.user !== 'number') { throw new ERR_INVALID_ARG_TYPE('prevValue.user', 'number', prevValue.user); } throw new ERR_INVALID_OPT_VALUE.RangeError('prevValue.user', prevValue.user); } if (!previousValueIsValid(prevValue.system)) { if (typeof prevValue.system !== 'number') { throw new ERR_INVALID_ARG_TYPE('prevValue.system', 'number', prevValue.system); } throw new ERR_INVALID_OPT_VALUE.RangeError('prevValue.system', prevValue.system); } } // Call the native function to get the current values. const errmsg = _cpuUsage(cpuValues); if (errmsg) { throw new ERR_CPU_USAGE(errmsg); } // If a previous value was passed in, return diff of current from previous. if (prevValue) { return { user: cpuValues[0] - prevValue.user, system: cpuValues[1] - prevValue.system }; } // If no previous value passed in, return current value. return { user: cpuValues[0], system: cpuValues[1] }; }
n/a
function cwd() { cachedCwd = binding.cwd(); return cachedCwd; }
...
};
local.moduleDirname = function (module, modulePathList) {
/*
* this function will search modulePathList for the module's __dirname
*/
var result;
// search process.cwd()
if (!module || module === "." || module.indexOf("/") >= 0) {
return require("path").resolve(process.cwd(), module || "");
}
// search modulePathList
[
"node_modules"
]
...
function dlopen() { [native code] }
n/a
function emitWarning(warning, type, code, ctor, now) { let detail; if (type !== null && typeof type === 'object' && !Array.isArray(type)) { ctor = type.ctor; code = type.code; if (typeof type.detail === 'string') detail = type.detail; type = type.type || 'Warning'; } else if (typeof type === 'function') { ctor = type; code = undefined; type = 'Warning'; } if (type !== undefined && typeof type !== 'string') { throw new ERR_INVALID_ARG_TYPE('type', 'string', type); } if (typeof code === 'function') { ctor = code; code = undefined; } else if (code !== undefined && typeof code !== 'string') { throw new ERR_INVALID_ARG_TYPE('code', 'string', code); } if (typeof warning === 'string') { // Improve error creation performance by skipping the error frames. // They are added in the `captureStackTrace()` function below. const tmpStackLimit = Error.stackTraceLimit; Error.stackTraceLimit = 0; // eslint-disable-next-line no-restricted-syntax warning = new Error(warning); Error.stackTraceLimit = tmpStackLimit; warning.name = String(type || 'Warning'); if (code !== undefined) warning.code = code; if (detail !== undefined) warning.detail = detail; // eslint-disable-next-line no-restricted-syntax Error.captureStackTrace(warning, ctor || process.emitWarning); } else if (!(warning instanceof Error)) { throw new ERR_INVALID_ARG_TYPE('warning', ['Error', 'string'], warning); } if (warning.name === 'DeprecationWarning') { if (process.noDeprecation) return; if (process.throwDeprecation) throw warning; } if (now) process.emit('warning', warning); else process.nextTick(doEmitWarning(warning)); }
n/a
exit = function () {
/*
* this function will do nothing
*/
return;
}
...
* <fileRemote|dirRemote> <commitMessage>
* will delete from github <fileRemote|dirRemote>
*/
local.github_crud.githubCrudContentDelete({
message: process.argv[4],
url: process.argv[3]
}, function (err) {
process.exit(Boolean(err));
});
};
local.cliDict.get = function () {
/*
* <fileRemote>
* will get from github <fileRemote>
...
function getegid() { [native code] }
n/a
function geteuid() { [native code] }
n/a
function getgid() { [native code] }
n/a
function getgroups() { [native code] }
n/a
function getuid() { [native code] }
n/a
function hasUncaughtExceptionCaptureCallback() { return exceptionHandlerState.captureFn !== null; }
n/a
function hrtime(time) { _hrtime(hrValues); if (time !== undefined) { if (!Array.isArray(time)) { throw new ERR_INVALID_ARG_TYPE('time', 'Array', time); } if (time.length !== 2) { throw new ERR_OUT_OF_RANGE('time', 2, time.length); } const sec = (hrValues[0] * 0x100000000 + hrValues[1]) - time[0]; const nsec = hrValues[2] - time[1]; const needsBorrow = nsec < 0; return [needsBorrow ? sec - 1 : sec, needsBorrow ? nsec + 1e9 : nsec]; } return [ hrValues[0] * 0x100000000 + hrValues[1], hrValues[2] ]; }
n/a
function initgroups(user, extraGroup) { validateId(user, 'user'); validateId(extraGroup, 'extraGroup'); // Result is 0 on success, 1 if user is unknown, 2 if group is unknown. const result = _initgroups(user, extraGroup); if (result === 1) { throw new ERR_UNKNOWN_CREDENTIAL('User', user); } else if (result === 2) { throw new ERR_UNKNOWN_CREDENTIAL('Group', extraGroup); } }
n/a
function kill(pid, sig) { var err; // eslint-disable-next-line eqeqeq if (pid != (pid | 0)) { throw new ERR_INVALID_ARG_TYPE('pid', 'number', pid); } // Preserve null signal if (sig === (sig | 0)) { // XXX(joyeecheung): we have to use process._kill here because // it's monkey-patched by tests. err = process._kill(pid, sig); } else { sig = sig || 'SIGTERM'; if (constants[sig]) { err = process._kill(pid, constants[sig]); } else { throw new ERR_UNKNOWN_SIGNAL(sig); } } if (err) throw errnoException(err, 'kill'); return true; }
...
var child_process;
var timerTimeout;
child_process = require("child_process");
// spawn child
child = child_process.spawn(command, args, opt).on("exit", function () {
// cleanup timerTimeout
try {
process.kill(timerTimeout.pid);
} catch (ignore) {}
});
// init timerTimeout
timerTimeout = child_process.spawn(
// convert timeout to integer seconds with 2 second delay
"sleep "
+ Math.floor(
...
function memoryUsage() { _memoryUsage(memValues); return { rss: memValues[0], heapTotal: memValues[1], heapUsed: memValues[2], external: memValues[3] }; }
n/a
function nextTick(callback) { if (typeof callback !== 'function') throw new ERR_INVALID_CALLBACK(callback); if (process._exiting) return; var args; switch (arguments.length) { case 1: break; case 2: args = [arguments[1]]; break; case 3: args = [arguments[1], arguments[2]]; break; case 4: args = [arguments[1], arguments[2], arguments[3]]; break; default: args = new Array(arguments.length - 1); for (var i = 1; i < arguments.length; i++) args[i - 1] = arguments[i]; } if (queue.isEmpty()) setHasTickScheduled(true); queue.push(new TickObject(callback, args)); }
n/a
function() { process.stdin.resume(); return process.stdin; }
n/a
function reallyExit() { [native code] }
n/a
function resourceUsage() { _resourceUsage(resourceValues); return { userCPUTime: resourceValues[0], systemCPUTime: resourceValues[1], maxRSS: resourceValues[2], sharedMemorySize: resourceValues[3], unsharedDataSize: resourceValues[4], unsharedStackSize: resourceValues[5], minorPageFault: resourceValues[6], majorPageFault: resourceValues[7], swappedOut: resourceValues[8], fsRead: resourceValues[9], fsWrite: resourceValues[10], ipcSent: resourceValues[11], ipcReceived: resourceValues[12], signalsCount: resourceValues[13], voluntaryContextSwitches: resourceValues[14], involuntaryContextSwitches: resourceValues[15] }; }
n/a
function(fn) { const err = new ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE(); err.stack = err.stack + '\n' + '-'.repeat(40) + '\n' + domainRequireStack; throw err; }
n/a
function(id) { validateId(id, 'id'); // Result is 0 on success, 1 if credential is unknown. const result = method(id); if (result === 1) { throw new ERR_UNKNOWN_CREDENTIAL(type, id); } }
n/a
function(id) { validateId(id, 'id'); // Result is 0 on success, 1 if credential is unknown. const result = method(id); if (result === 1) { throw new ERR_UNKNOWN_CREDENTIAL(type, id); } }
n/a
function(id) { validateId(id, 'id'); // Result is 0 on success, 1 if credential is unknown. const result = method(id); if (result === 1) { throw new ERR_UNKNOWN_CREDENTIAL(type, id); } }
n/a
function setgroups(groups) { if (!Array.isArray(groups)) { throw new ERR_INVALID_ARG_TYPE('groups', 'Array', groups); } for (var i = 0; i < groups.length; i++) { validateId(groups[i], `groups[${i}]`); } // Result is 0 on success. A positive integer indicates that the // corresponding group was not found. const result = _setgroups(groups); if (result > 0) { throw new ERR_UNKNOWN_CREDENTIAL('Group', groups[result - 1]); } }
n/a
function(id) { validateId(id, 'id'); // Result is 0 on success, 1 if credential is unknown. const result = method(id); if (result === 1) { throw new ERR_UNKNOWN_CREDENTIAL(type, id); } }
n/a
function umask(mask) { if (mask !== undefined) { mask = parseMode(mask, 'mask'); } return binding.umask(mask); }
n/a
function uptime() { [native code] }
n/a
function require(path) { return mod.require(path); }
...
}).slice(0, 256).map(readExample);
// init moduleMain
local.tryCatchOnError(function () {
console.error("apidocCreate - requiring " + opt.dir + " ...");
moduleMain = {};
moduleMain = (
opt.moduleDict[opt.env.npm_package_name]
|| opt.require(opt.dir)
|| opt.require(
opt.dir + "/"
+ (opt.packageJson.bin)[Object.keys(opt.packageJson.bin)[0]]
) || {}
);
opt.circularSet.add(moduleMain);
console.error("apidocCreate - ... required " + opt.dir);
...
function resolve(request, options) { validateString(request, 'request'); return Module._resolveFilename(request, mod, false, options); }
...
local.moduleDirname = function (module, modulePathList) {
/*
* this function will search modulePathList for the module's __dirname
*/
var result;
// search process.cwd()
if (!module || module === "." || module.indexOf("/") >= 0) {
return require("path").resolve(process.cwd(), module || "");
}
// search modulePathList
[
"node_modules"
]
.concat(modulePathList)
.concat(require("module").globalPaths)
...
inherits = function () {
/*
* this function will do nothing
*/
return;
}
n/a
write = function (data) { local.writerData += data; }
...
local.cliDict._default = function () {
/*
* <moduleDirectory>
* will create apidoc from <moduleDirectory>
*/
// jslint files
process.stdout.write(local.apidocCreate({
dir: process.argv[2],
modulePathList: module.paths
}));
};
// run the cli
if (module === require.main && !globalThis.utility2_rollup) {
...
writeFile = function (file, onError) { local.coverageReportHtml += local.writerData + "\n\n"; if (!local.isBrowser && local.writerFile) { local.fsWriteFileWithMkdirpSync(local.writerFile, local.writerData); } local.writerData = ""; local.writerFile = file; onError(local.writer); }
...
onError();
}
);
break;
case "setItem":
tmp = os.tmpdir() + "/" + Date.now() + Math.random();
// save to tmp
fs.writeFile(tmp, opt.value, function (err) {
// validate no err occurred
local.assertThrow(!err, err);
// rename tmp to key
fs.rename(
tmp,
storage + "/" + encodeURIComponent(String(opt.key)),
onError
...
function ok(...args) { innerOk(ok, args.length, ...args); }
...
key = '0123456789abcdef0123456789abcdef';
mode = null;
local.cryptoAesXxxCbcRawEncrypt({
data: data,
key: key,
mode: mode
}, function (err, data) {
console.assert(!err, err);
local.cryptoAesXxxCbcRawDecrypt({
data: data,
key: key,
mode: mode
}, console.log);
});
*/
...
assertThrow = function (passed, message) {
/*
* this function will throw err.<message> if <passed> is falsy
*/
var err;
if (passed) {
return;
}
err = (
// ternary-operator
(
message
&& typeof message.message === "string"
&& typeof message.stack === "string"
)
// if message is errObj, then leave as is
? message
: new Error(
typeof message === "string"
// if message is a string, then leave as is
? message
// else JSON.stringify message
: JSON.stringify(message, null, 4)
)
);
throw err;
}
...
argList: (commandList[ii][1] || "").trim(),
command: [
key
],
description: commandList[ii][2]
};
} catch (ignore) {
local.assertThrow(null, new Error(
"cliRun - cannot parse comment in COMMAND "
+ key
+ ":\nnew RegExp("
+ JSON.stringify(opt.rgxComment.source)
+ ").exec(" + JSON.stringify(text).replace((
/\\\\/g
), "\u0000").replace((
...
cliRun = function (opt) {
/*
* this function will run the cli with given <opt>
*/
local.cliDict._eval = local.cliDict._eval || function () {
/*
* <code>
* will eval <code>
*/
globalThis.local = local;
local.vm.runInThisContext(process.argv[3]);
};
local.cliDict["--eval"] = local.cliDict["--eval"] || local.cliDict._eval;
local.cliDict["-e"] = local.cliDict["-e"] || local.cliDict._eval;
local.cliDict._help = local.cliDict._help || function () {
/*
*
* will print help
*/
var commandList;
var file;
var packageJson;
var text;
var textDict;
commandList = [
{
argList: "<arg2> ...",
description: "usage:",
command: [
"<arg1>"
]
}, {
argList: "'console.log(\"hello world\")'",
description: "example:",
command: [
"--eval"
]
}
];
file = __filename.replace((
/.*\//
), "");
opt = Object.assign({}, opt);
packageJson = require("./package.json");
// validate comment
opt.rgxComment = opt.rgxComment || (
/\)\u0020\{\n(?:|\u0020{4})\/\*\n(?:\u0020|\u0020{5})\*((?:\u0020<[^>]*?>|\u0020\.\.\.)*?)\n(?:\u0020|\u0020{5})\*\u0020
(will\u0020.*?\S)\n(?:\u0020|\u0020{5})\*\/\n(?:\u0020{4}|\u0020{8})\S/
);
textDict = {};
Object.keys(local.cliDict).sort().forEach(function (key, ii) {
if (key[0] === "_" && key !== "_default") {
return;
}
text = String(local.cliDict[key]);
if (key === "_default") {
key = "";
}
textDict[text] = textDict[text] || (ii + 2);
ii = textDict[text];
if (commandList[ii]) {
commandList[ii].command.push(key);
return;
}
try {
commandList[ii] = opt.rgxComment.exec(text);
commandList[ii] = {
argList: (commandList[ii][1] || "").trim(),
command: [
key
],
description: commandList[ii][2]
};
} catch (ignore) {
local.assertThrow(null, new Error(
"cliRun - cannot parse comment in COMMAND "
+ key
+ ":\nnew RegExp("
+ JSON.stringify(opt.rgxComment.source)
+ ").exec(" + JSON.stringify(text).replace((
/\\\\/g
), "\u0000").replace((
/\\n/g
), "\\n\\\n").replace((
/\u0000/g
), "\\\\") + ");"
));
}
});
text = "";
text += packageJson.name + " (" + packageJson.version + ")\n\n";
text += commandList.filter(function (elem) {
return elem;
}).map(function (elem, ii) {
elem.command = elem.command.filter(function (elem) {
return elem;
});
switch (ii) {
case 0:
case 1:
elem.argList = [
elem.argList
];
break;
default:
elem.argList = elem.argList.split(" ");
elem.description = (
"# COMMAND "
+ (elem.command[0] || "<none>") + "\n# &...
...
dir: process.argv[2],
modulePathList: module.paths
}));
};
// run the cli
if (module === require.main && !globalThis.utility2_rollup) {
local.cliRun();
}
}());
}());
...
function EventEmitter() { EventEmitter.init.call(this); }
n/a
functionOrNop = function (fnc) {
/*
* this function will if <fnc> exists,
* them return <fnc>,
* else return <nop>
*/
return fnc || local.nop;
}
...
if (element.isDescending) {
result.reverse();
}
});
// skip
result = result.slice(skip || 0);
// shuffle
local.functionOrNop(shuffle && local.listShuffle)(result);
// limit
result = result.slice(0, limit || Infinity);
return result;
};
local._DbTable.prototype._crudGetOneById = function (idDict) {
/*
...
identity = function (value) {
/*
* this function will return <value>
*/
return value;
}
...
local.cliDict.help = local.cliDict.help || local.cliDict._help;
local.cliDict._interactive = local.cliDict._interactive || function () {
/*
*
* will start interactive-mode
*/
globalThis.local = local;
local.identity(local.replStart || require("repl").start)({
useGlobal: true
});
};
local.cliDict["--interactive"] = (
local.cliDict["--interactive"]
|| local.cliDict._interactive
);
...
jslintAndPrint = function (code, file, opt) {
/*
* this function will jslint / csslint <code> and print any errors to stderr
*/
var tmp;
if (!(opt && opt.modeNext)) {
local.jslintResult = {
modeNext: 0
};
}
code = code || "";
file = file || "undefined";
opt = Object.assign(local.jslintResult, opt || {}, {
code,
file
});
opt.modeNext += 1;
switch (opt.modeNext) {
// jslint - init
case 1:
// cleanup
opt.errList = [];
opt.errText = "";
switch (opt.fileType0) {
// deembed-js - '\\n\\\n...\\n\\\n'
case ".\\n\\":
// rgx - remove \\n\\
code = code.replace((
/\\n\\$|\\(.)/gm
), function (match0) {
return (
match0 === "\\n\\"
? ""
: match0[1]
);
});
break;
// deembed-js - '\n...\n'
case ".sh":
// rgx - convert '"'"' to '
code = code.replace((
/'"'"'/g
), "'");
break;
}
// init
opt = Object.assign(opt, {
".css": (
/^\/\*csslint\b|(^\/\*\u0020jslint\u0020utility2:true\u0020\*\/$)/m
),
".html": (
/^\/\*csslint\b|(^\/\*\u0020jslint\u0020utility2:true\u0020\*\/$)/m
),
".js": (
/^\/\*jslint\b|(^\/\*\u0020jslint\u0020utility2:true\u0020\*\/$)/m
),
".md": (
/(^\/\*\u0020jslint\u0020utility2:true\u0020\*\/$)/m
),
".sh": (
/(^#\u0020jslint\u0020utility2:true$)/m
),
code0: code,
fileType: (
/\.\w+?$|$/m
).exec(file)[0]
});
// jslint - .json
if (
code && (opt.fileType === ".js" || opt.fileType === ".json")
&& !opt.fileType0
) {
try {
tmp = JSON.parse(code);
opt.fileType = ".json";
if (opt.autofix) {
code = JSON.stringify(tmp, null, 4) + "\n";
opt.code0 = code;
}
opt.modeNext = Infinity;
break;
} catch (errCaught) {
if (opt.fileType === ".json") {
opt.errList.push({
column: 0,
evidence: code.slice(0, 100),
line: 0,
message: errCaught.message
});
opt.modeNext = Infinity;
break;
}
}
}
try {
opt.conditionalPassed = opt[opt.fileType].exec(code);
} catch (ignore) {}
opt.utility2 = (
opt.conditionalPassed
&& opt.conditionalPassed[1]
) || opt.autofix;
if (
opt.conditional
&& (!opt.conditionalPassed || opt.coverage)
) {
break;
}
opt.modeNext = 10;
break;
// jslint - autofix
case 11:
code = local.jslintAutofix(code, file, opt);
local.jslintResult = opt;
break;
// jslint - csslint and jslint
case 12:
// restore lineOffset
code = "\n".repeat(opt.lineOffset | 0) + code;
switch (opt.fileType) {
case ".css":
// csslint
Object.assign(opt, local.CSSLint.verify(code));
// init errList
opt.errList = opt.messages.map(function (err) {
err...
...
return;
}
// read file
local.fs.readFile(opt.file, "utf8", opt.onNext);
break;
case 2:
// jslint
local.jslint.jslintAndPrint(data, opt.file);
local.assertThrow(
!local.jslint.jslintResult.errText,
local.jslint.jslintResult.errText.replace((
/\u001b\[\d*m/g
), "")
);
// validate
...
jslintAndPrintDir = function (dir, opt, onError) {
/*
* this function will jslint files in shallow <dir>
*/
var onParallel;
onParallel = local.onParallel(onError);
local.fs.readdirSync(dir).forEach(function (file) {
var timeStart;
file = process.cwd() + "/" + file;
switch ((
/\.\w+?$|$/m
).exec(file)[0]) {
case ".css":
case ".html":
case ".js":
case ".json":
case ".md":
case ".sh":
if ((
/\b(?:assets\.app\.js|lock|min|raw|rollup)\b/
).test(file)) {
return;
}
onParallel.counter += 1;
// jslint file
local.fs.readFile(file, "utf8", function (err, data) {
// validate no err occurred
local.assertThrow(!err, err);
timeStart = Date.now();
local.jslintAndPrint(data, file, opt);
console.error(
"jslint - " + (Date.now() - timeStart) + "ms " + file
);
onParallel();
});
break;
}
});
}
...
});
// jslint process.cwd()
if (!local.env.npm_config_mode_library) {
local.child_process.spawn("node", [
"-e", (
"require("
+ JSON.stringify(__filename)
+ ").jslint.jslintAndPrintDir("
+ JSON.stringify(process.cwd())
+ ", {autofix:true,conditional:true}, process.exit);"
)
], {
env: local.objectAssignDefault({
npm_config_mode_library: "1"
}, local.env),
...
jslintAutofix = function (code, file, opt) {
/*
* this function will jslint-autofix <code>
*/
var code0;
var code2;
var dataList;
var ignoreList;
var ii;
var rgx1;
var rgx2;
var tmp;
// autofix-all
if (opt.autofix) {
// autofix-all - normalize local-function
if (typeof(
globalThis.utility2
&& globalThis.utility2.jslintAutofixLocalFunction
) === "function") {
code = globalThis.utility2.jslintAutofixLocalFunction(code, file);
}
// autofix-all - remove trailing-whitespace
code = code.replace((
/\u0020+$/gm
), "");
// autofix-all - remove leading-whitespace before )]}
code = code.replace((
/\n+?(\n\u0020*?[)\]}])/g
), "$1");
// autofix-all - normalize newlines to \n\n
code = code.replace((
/([^\n])\n{3}([^\n])/g
), "$1\n\n$2");
// autofix-all - normalize newlines to \n\n\n\n
code = code.replace((
/\n{5,}/g
), "\n\n\n\n");
// autofix-all - recurse <script>...</script>, <style>...</style>
code = code.replace((
/(^\/\*\u0020jslint\u0020utility2:true\u0020\*\/\\n\\\n(?:^.*?\\n\\\n)*?)(^(?:\/\/\u0020)?<\/(?:script|style)>\\n\\\
n)/gm
), function (ignore, match1, match2, ii) {
return local.jslintAndPrint(
match1,
file + (
match2.indexOf("style") >= 0
? ".<style>.css"
: ".<script>.js"
),
Object.assign({}, opt, {
fileType0: ".\\n\\",
lineOffset: (
opt.lineOffset | 0
) + code.slice(0, ii).replace((
/.+/g
), "").length,
modeNext: 0
})
) + match2;
});
}
switch (opt.autofix && opt.fileType) {
case ".css":
break;
case ".html":
// autofix-html - recurse <script>...</script>, <style>...</style>
code = code.replace((
/(^\/\*\u0020jslint\u0020utility2:true\u0020\*\/\n(?:^.*?\n)*?)(^<\/(?:script|style)>\n)/gm
), function (ignore, match1, match2, ii) {
return local.jslintAndPrint(
match1,
file + (
match2.indexOf("style") >= 0
? ".<style>.css"
: ".<script>.js"
),
local.objectAssignDefault({
fileType0: opt.fileType,
lineOffset: (
(opt.lineOffset | 0)
+ code.slice(0, ii).replace((
/.+/g
), "").length
),
modeNext: 0
}, opt)
) + match2;
});
break;
case ".js":
// autofix-js - demux code to [code, ignoreList]
ignoreList = [];
code = code.replace((
/^\u0020*?\/\*\u0020jslint\u0020ignore:start\u0020\*\/$[\S\s]*?^\/\*\u0020jslint\u0020ignore:end\u0020\*\/$/gm
), function (match0) {
ignoreList.push(match0);
return "/* jslint ignore:start:end */";
});
// autofix-js - escape non-ascii
code = code.replace((
/[^\n\r\t\u0020-\u007e]/g
), function (match0) {
return "\\u" + (
"0000"
+ match0.charCodeAt(0).toString(16)
).slice(-4);
});
// autofix-js - demux code2 to [code2, ignoreList]
code2 = "";...
n/a
jslintGetColumnLine = function (code, ii) {
/*
* this function will transform <code> and <ii> -> {column, line, evidence}
*/
var column;
var evidence;
var line;
evidence = code.slice(0, ii).split("\n");
line = evidence.length - 1;
column = evidence[line].length;
evidence = evidence[line] + code.slice(ii, ii + 100).split("\n")[0];
return {
column,
evidence,
line
};
}
n/a
jslintUtility2 = function (code, ignore, opt) {
/*
* this function will jslint <code> with utiity2-specific rules
*/
var code2;
var err;
var indent;
var previous;
// jslintUtility2 - all
if (opt.utility2) {
code2 = code;
code2 = code2.replace((
/^\/\*\u0020jslint\u0020ignore:start\u0020\*\/$[\S\s]+?^\/\*\u0020jslint\u0020ignore:end\u0020\*\/$/gm
), function (match0) {
// preserve lineno
return match0.replace((
/.+/g
), "");
});
code2.replace((
/^\u0020+?(?:\*|\/\/!!)|^\u0020+|[\r\t]/gm
), function (match0, ii) {
switch (match0.slice(-1)) {
case " ":
if (match0.length % 4 === 0) {
return;
}
err = {
message: "non 4-space indent"
};
break;
case "\r":
err = {
message: "unexpected \\r"
};
break;
case "\t":
err = {
message: "unexpected \\t"
};
break;
default:
return;
}
Object.assign(err, local.jslintGetColumnLine(code2, ii));
opt.errList.push({
column: err.column + 1,
evidence: JSON.stringify(err.evidence),
line: err.line + 1,
message: err.message
});
});
}
switch (opt.utility2 && opt.fileType) {
// jslintUtility2 - .css
case ".css":
// ignore comment
code2 = code2.replace((
/^\u0020*?\/\*[\S\s]*?\*\/\u0020*?$/gm
), function (match0) {
// preserve lineno
return match0.replace((
/.+/g
), "");
});
code2.replace((
/\S\u0020{2}|\u0020,|^\S.*?[,;{}]./gm
), function (match0, ii) {
switch (match0.slice(-2)) {
case " ":
err = {
colOffset: 2,
message: "unexpected multi-whitespace"
};
break;
case " ,":
err = {
colOffset: 1,
message: "unexpected whitespace before comma"
};
break;
default:
err = {
colOffset: match0.length,
message: "unexpected multiline-statement"
};
}
Object.assign(err, local.jslintGetColumnLine(code2, ii));
opt.errList.push({
column: err.column + err.colOffset,
evidence: JSON.stringify(err.evidence),
line: err.line + 1,
message: err.message
});
});
// validate line-sorted - css-selector
previous = "";
code2 = code2.replace((
/^.|[#.>]|[,}]$|\u0020\{$|\b\w/gm
), function (match0) {
switch (match0) {
case " ":
return match0;
case " {":
return "\u0001" + match0;
case "#":
return "\u0002" + match0;
case ",":
return "\u0000" + match0;
case ".":
return "\u0001" + match0;
case ">":
return "\u0003" + match0;
case "}":
return match0;
default:
return "\u0000" + match0;
}
});
code2.replace((
/\n{2,}|^\u0000@|^\}\n\}|\}|^(?:\S.*?\n)+/gm...
n/a
jslint_extra = function (source, opt, global_array) {
/*
* this function will run with extra-features inside jslint-function jslint()
*/
// init
line_ignore = null;
lines = (
// ternary-operator
Array.isArray(source)
? source
: source.split(rx_crlf)
);
lines_extra = lines.map(function () {
return {};
});
// jslint
jslint_result = jslint0(lines, opt, global_array);
// autofix
// expected_space_a_b: "Expected one space between '{a}' and '{b}'.",
// unexpected_space_a_b: "Unexpected space between '{a}' and '{b}'.",
source = lines_extra.map(function (element, ii) {
return element.source_autofix || lines[ii];
}).join("\n").replace((
/\s+?\u0000/g
), "\u0000").replace((
/(\n\u0020+)(.*?)\n\u0020*?(\/\/.*?)\u0000/g
), "$1$3$1$2\u0000").replace((
/\u0000expected_space_a_b\u0000/g
), " ").replace((
/\u0000unexpected_space_a_b\u0000/g
), "");
jslint_result.lines_extra = lines_extra;
jslint_result.source_autofix = source;
return jslint_result;
}
n/a
jsonStringifyOrdered = function (obj, replacer, space) {
/*
* this function will JSON.stringify <obj>,
* with object-keys sorted and circular-references removed
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Syntax
*/
var circularSet;
var stringify;
var tmp;
stringify = function (obj) {
/*
* this function will recursively JSON.stringify obj,
* with object-keys sorted and circular-references removed
*/
// if obj is not an object or function, then JSON.stringify as normal
if (!(
obj
&& typeof obj === "object"
&& typeof obj.toJSON !== "function"
)) {
return JSON.stringify(obj);
}
// ignore circular-reference
if (circularSet.has(obj)) {
return;
}
circularSet.add(obj);
// if obj is an array, then recurse its items
if (Array.isArray(obj)) {
tmp = "[" + obj.map(function (obj) {
// recurse
tmp = stringify(obj);
return (
typeof tmp === "string"
? tmp
: "null"
);
}).join(",") + "]";
circularSet.delete(obj);
return tmp;
}
// if obj is not an array,
// then recurse its items with object-keys sorted
tmp = "{" + Object.keys(obj).sort().map(function (key) {
// recurse
tmp = stringify(obj[key]);
if (typeof tmp === "string") {
return JSON.stringify(key) + ":" + tmp;
}
}).filter(function (obj) {
return typeof obj === "string";
}).join(",") + "}";
circularSet.delete(obj);
return tmp;
};
circularSet = new Set();
return JSON.stringify((
(typeof obj === "object" && obj)
// recurse
? JSON.parse(stringify(obj))
: obj
), replacer, space);
}
...
}
result = {};
fieldList.forEach(function (key) {
if (key[0] !== "$") {
result[key] = dbRow[key];
}
});
return JSON.parse(local.jsonStringifyOrdered(result));
};
local.dbRowSetId = function (dbRow, idIndex) {
/*
* this function will if does not exist,
* then set a random and unique id into dbRow for given idIndex,
*/
...
nop = function () {
/*
* this function will do nothing
*/
return;
}
...
process.stdout._writeDefault = (
process.stdout._writeDefault
|| process.stdout._write
);
process.stdout._write = function (chunk, encoding, callback) {
process.stdout._writeDefault(chunk, encoding, callback);
// coverage-hack - ignore else-statement
local.nop(that.socket.writable && (function () {
that.socket.write(chunk, encoding);
}()));
};
// start serverRepl1
globalThis.utility2_serverRepl1 = require("net").createServer(function (
socket
) {
...
objectAssignDefault = function (target, source) {
/*
* this function will if items from <target> are
* null, undefined, or empty-string,
* then overwrite them with items from <source>
*/
target = target || {};
Object.keys(source || {}).forEach(function (key) {
if (
target[key] === null
|| target[key] === undefined
|| target[key] === ""
) {
target[key] = target[key] || source[key];
}
});
return target;
}
...
if (key[0] !== "_") {
xhr[key] = opt[key];
}
});
// init timeout
timeout = xhr.timeout || local2.timeoutDefault || 30000;
// init default
local.objectAssignDefault(xhr, {
corsForwardProxyHost: local2.corsForwardProxyHost,
headers: {},
location: (local.isBrowser && location) || {},
method: "GET",
responseType: ""
});
// init headers
...
onErrorWithStack = function (onError) {
/*
* this function will create wrapper around <onError>
* that will append current-stack to err.stack
*/
var onError2;
var stack;
stack = new Error().stack.replace((
/(.*?)\n.*?$/m
), "$1");
onError2 = function (err, data, meta) {
if (
err
&& typeof err.stack === "string"
&& err !== local.errDefault
&& String(err.stack).indexOf(stack.split("\n")[2]) < 0
) {
// append current-stack to err.stack
err.stack += "\n" + stack;
}
onError(err, data, meta);
};
// debug onError
onError2.toString = function () {
return String(onError);
};
return onError2;
}
...
local.onParallel = function (onError, onEach, onRetry) {
/*
* this function will create a function that will
* 1. run async tasks in parallel
* 2. if counter === 0 or err occurred, then call onError(err)
*/
var onParallel;
onError = local.onErrorWithStack(onError);
onEach = onEach || local.nop;
onRetry = onRetry || local.nop;
onParallel = function (err, data) {
if (onRetry(err, data)) {
return;
}
// decrement counter
...
onParallel = function (onError, onEach, onRetry) {
/*
* this function will create a function that will
* 1. run async tasks in parallel
* 2. if counter === 0 or err occurred, then call onError(err)
*/
var onParallel;
onError = local.onErrorWithStack(onError);
onEach = onEach || local.nop;
onRetry = onRetry || local.nop;
onParallel = function (err, data) {
if (onRetry(err, data)) {
return;
}
// decrement counter
onParallel.counter -= 1;
// validate counter
if (!(onParallel.counter >= 0 || err || onParallel.err)) {
err = new Error(
"invalid onParallel.counter = " + onParallel.counter
);
// ensure onError is run only once
} else if (onParallel.counter < 0) {
return;
}
// handle err
if (err) {
onParallel.err = err;
// ensure counter <= 0
onParallel.counter = -Math.abs(onParallel.counter);
}
// call onError when isDone
if (onParallel.counter <= 0) {
onError(err, data);
return;
}
onEach();
};
// init counter
onParallel.counter = 0;
// return callback
return onParallel;
}
...
};
local.dbCrudRemoveAll = function (onError) {
/*
* this function will remove all dbRow's from the db
*/
var onParallel;
onParallel = local.onParallel(function (err) {
local.setTimeoutOnError(onError, 0, err);
});
onParallel.counter += 1;
Object.keys(local.dbTableDict).forEach(function (key) {
onParallel.counter += 1;
local.dbTableDict[key].crudRemoveAll(onParallel);
});
...
function Stream() { EE.call(this); }
n/a
function Reporter(lines, ruleset, allow, ignore) {
"use strict";
/**
* List of messages being reported.
* @property messages
* @type String[]
*/
this.messages = [];
/**
* List of statistics being reported.
* @property stats
* @type String[]
*/
this.stats = [];
/**
* Lines of code being reported on. Used to provide contextual information
* for messages.
* @property lines
* @type String[]
*/
this.lines = lines;
/**
* Information about the rules. Used to determine whether an issue is an
* error or warning.
* @property ruleset
* @type Object
*/
this.ruleset = ruleset;
/**
* Lines with specific rule messages to leave out of the report.
* @property allow
* @type Object
*/
this.allow = allow;
if (!this.allow) {
this.allow = {};
}
/**
* Linesets not to include in the report.
* @property ignore
* @type [][]
*/
this.ignore = ignore;
if (!this.ignore) {
this.ignore = [];
}
}
n/a
function(formatter) { // formatters.push(formatter); formatters[formatter.id] = formatter; }
n/a
function(rule) { rules.push(rule); rules[rule.id] = rule; }
n/a
function() { rules = []; }
n/a
function(results, filename, formatId, options) { var formatter = this.getFormatter(formatId), result = null; if (formatter) { result = formatter.startFormat(); result += formatter.formatResults(results, filename, options || {}); result += formatter.endFormat(); } return result; }
n/a
function(formatId) { return formatters[formatId]; }
n/a
function() { return [].concat(rules).sort(function(a, b) { return a.id > b.id ? 1 : 0; }); }
n/a
function() { var ruleset = {}, i = 0, len = rules.length; while (i < len) { ruleset[rules[i++].id] = 1; // by default, everything is a warning } return ruleset; }
n/a
function(formatId) { return formatters.hasOwnProperty(formatId); }
n/a
function(text, ruleset) { var i = 0, reporter, lines, allow = {}, ignore = [], report, parser = new parserlib.css.Parser({ starHack: true, ieFilters: true, underscoreHack: true, strict: false }); // normalize line endings lines = text.replace(/\n\r?/g, "$split$").split("$split$"); // find 'allow' comments CSSLint.Util.forEach(lines, function (line, lineno) { var allowLine = line && line.match(/\/\*[ \t]*csslint[ \t]+allow:[ \t]*([^\*]*)\*\//i), allowRules = allowLine && allowLine[1], allowRuleset = {}; if (allowRules) { allowRules.toLowerCase().split(",").forEach(function(allowRule) { allowRuleset[allowRule.trim()] = true; }); if (Object.keys(allowRuleset).length > 0) { allow[lineno + 1] = allowRuleset; } } }); var ignoreStart = null, ignoreEnd = null; CSSLint.Util.forEach(lines, function (line, lineno) { // Keep oldest, "unclosest" ignore:start if (ignoreStart === null && line.match(/\/\*[ \t]*csslint[ \t]+ignore:start[ \t]*\*\//i)) { ignoreStart = lineno; } if (line.match(/\/\*[ \t]*csslint[ \t]+ignore:end[ \t]*\*\//i)) { ignoreEnd = lineno; } if (ignoreStart !== null && ignoreEnd !== null) { ignore.push([ignoreStart, ignoreEnd]); ignoreStart = ignoreEnd = null; } }); // Close remaining ignore block, if any if (ignoreStart !== null) { ignore.push([ignoreStart, lines.length]); } if (!ruleset) { ruleset = this.getRuleset(); } if (embeddedRuleset.test(text)) { // defensively copy so that caller's version does not get modified ruleset = clone(ruleset); ruleset = applyEmbeddedRuleset(text, ruleset); } reporter = new Reporter(lines, ruleset, allow, ignore); ruleset.errors = 2; // always report parsing errors as errors for (i in ruleset) { if (ruleset.hasOwnProperty(i) && ruleset[i]) { if (rules[i]) { rules[i].init(parser, reporter); } } } // capture most horrible error type try { parser.parse(text); } catch (ex) { reporter.error("Fatal error, cannot continue: " + ex.message, ex.line, ex.col, {}); } report = { messages : reporter.messages, stats : reporter.stats, ruleset : reporter.ruleset, allow : reporter.allow, ignore : reporter.ignore }; // sort by line numbers, rollups at the bottom report.messages.sort(function (a, b) { if (a.rollup && !b.rollup) { return 1; } else if (!a.rollup && b.rollup) { return -1; } else { return a.line - b.line; } }); return report; }
n/a
function Reporter(lines, ruleset, allow, ignore) {
"use strict";
/**
* List of messages being reported.
* @property messages
* @type String[]
*/
this.messages = [];
/**
* List of statistics being reported.
* @property stats
* @type String[]
*/
this.stats = [];
/**
* Lines of code being reported on. Used to provide contextual information
* for messages.
* @property lines
* @type String[]
*/
this.lines = lines;
/**
* Information about the rules. Used to determine whether an issue is an
* error or warning.
* @property ruleset
* @type Object
*/
this.ruleset = ruleset;
/**
* Lines with specific rule messages to leave out of the report.
* @property allow
* @type Object
*/
this.allow = allow;
if (!this.allow) {
this.allow = {};
}
/**
* Linesets not to include in the report.
* @property ignore
* @type [][]
*/
this.ignore = ignore;
if (!this.ignore) {
this.ignore = [];
}
}
n/a
function(message, line, col, rule) { "use strict"; this.messages.push({ type : "error", line : line, col : col, message : message, evidence: this.lines[line-1], rule : rule || {} }); }
...
readExample = function (file) {
/*
* this function will read the example from given file
*/
var result;
local.tryCatchOnError(function () {
file = local.path.resolve(opt.dir, file);
console.error("apidocCreate - readExample " + file);
result = "";
result = (
"\n\n\n\n\n\n\n\n"
// bug-workaround - truncate example to manageable size
+ local.fs.readFileSync(file, "utf8").slice(0, 262144)
+ "\n\n\n\n\n\n\n\n"
).replace((
...
function(message, line, col, rule) { "use strict"; this.messages.push({ type : "info", line : line, col : col, message : message, evidence: this.lines[line-1], rule : rule }); }
n/a
function(message, line, col, rule) { "use strict"; // Check if rule violation should be allowed if (this.allow.hasOwnProperty(line) && this.allow[line].hasOwnProperty(rule.id)) { return; } var ignore = false; CSSLint.Util.forEach(this.ignore, function (range) { if (range[0] <= line && line <= range[1]) { ignore = true; } }); if (ignore) { return; } this.messages.push({ type : this.ruleset[rule.id] === 2 ? "error" : "warning", line : line, col : col, message : message, evidence: this.lines[line-1], rule : rule }); }
n/a
function(message, rule) { "use strict"; this.messages.push({ type : "error", rollup : true, message : message, rule : rule }); }
n/a
function(message, rule) { "use strict"; this.messages.push({ type : "warning", rollup : true, message : message, rule : rule }); }
n/a
function(name, value) { "use strict"; this.stats[name] = value; }
...
var onParallel;
if (local.isBrowser) {
onError(null, opt);
return;
}
onParallel = local.onParallel(onError);
onParallel.counter += 1;
local.fs.stat(__filename, function (err, stat) {
// test default watchFile handling-behavior
onParallel.counter += 1;
local.fs.utimes(__filename, stat.atime, new Date(), onParallel);
// test nop watchFile handling-behavior
onParallel.counter += 1;
setTimeout(function () {
local.fs.utimes(__filename, stat.atime, stat.mtime, onParallel);
...
function(message, line, col, rule) { "use strict"; this.report(message, line, col, rule); }
...
options.source_map.add(
mapping.token.file,
mapping.line, mapping.col,
mapping.token.line, mapping.token.col,
!mapping.name && mapping.token.type == "name" ? mapping.token.value : mapping.name
);
} catch(ex) {
mapping.token.file != null && AST_Node.warn("Couldn't figure out
mapping for {file}:{line},{col} → {cline},{ccol} [{name}]", {
file: mapping.token.file,
line: mapping.token.line,
col: mapping.token.col,
cline: mapping.line,
ccol: mapping.col,
name: mapping.name || ""
});
...
_default = function () {
/*
* <file1> <file2> ...
* will jslint <file1> <file2> ... and print errors to stderr
*/
// jslint files
process.argv.slice(2).forEach(function (file) {
if (file[0] === "-") {
return;
}
local.jslintAndPrint(
local.fs.readFileSync(local.path.resolve(file), "utf8"),
file,
{
autofix: process.argv.indexOf("--autofix") >= 0,
conditional: process.argv.indexOf("--conditional") >= 0
}
);
});
// if err occurred, then exit with non-zero code
process.exit(Boolean(local.jslintResult.errList.length));
}
...
local.cliDict._help();
return;
}
if (local.cliDict[process.argv[2]]) {
local.cliDict[process.argv[2]]();
return;
}
local.cliDict._default();
};
local.moduleDirname = function (module, modulePathList) {
/*
* this function will search modulePathList for the module's __dirname
*/
var result;
...
dir = function () {
/*
* <dir>
* will jslint files in shallow <dir>
*/
local.jslintAndPrintDir(process.argv[3], {
autofix: process.argv.indexOf("--autofix") >= 0,
conditional: process.argv.indexOf("--conditional") >= 0
}, process.exit);
}
n/a
function c (e, n, r){if(r||typeof n=="function"){r||(r=n,n=null),n=l({},c.defaults,n||{});var i= n.highlight,u,a,f=0;try{u=t.lex(e,n)}catch(h){return r(h)}a=u.length;var p=function( e){if(e)return n.highlight=i,r(e);var t;try{t=s.parse(u,n)}catch(o){e=o}return n .highlight=i,e?r(e):r(null,t)};if(!i||i.length<3)return p();delete n.highlight;if(! a)return p();for(;f<u.length;f++)(function(e){return e.type!=="code"?--a||p():i( e.text,e.lang,function(t,n){if(t)return p(t);if(n==null||n===e.text)return--a||p ();e.text=n,e.escaped=!0,--a||p()})})(u[f]);return}try{return n&&(n=l({},c.defaults ,n)),s.parse(t.lex(e,n),n)}catch(h){h.message+="\nPlease report this to https://github.com/chjj/marked." ;if((n||c.defaults).silent)return"<p>An error occured:</p><pre>"+o(h.message+"",!0 )+"</pre>";throw h}}
n/a
function r(e, t){this.options=t||c.defaults,this.links= e,this.rules=n.normal,this.renderer=this.options.renderer||new i,this.renderer.options= this.options;if(!this.links)throw new Error("Tokens array requires a `links` property." );this.options.gfm?this.options.breaks?this.rules=n.breaks:this.rules=n.gfm:this .options.pedantic&&(this.rules=n.pedantic)}
n/a
function t(t){this.tokens=[],this.tokens.links={},this.options=t||c. defaults,this.rules=e.normal,this.options.gfm&&(this.options.tables?this.rules=e .tables:this.rules=e.gfm)}
n/a
function s (e){this.tokens=[],this.token=null,this.options=e||c.defaults,this.options.renderer= this.options.renderer||new i,this.renderer=this.options.renderer,this.renderer.options= this.options}
n/a
function i(e){this.options=e||{}}
n/a
function(e, t, n){var i=new r(t,n);return i.output(e)}
n/a
function(e, n){var r=new t(n);return r.lex(e)}
n/a
function(e){return l(c.defaults,e),c}
n/a
function c (e, n, r){if(r||typeof n=="function"){r||(r=n,n=null),n=l({},c.defaults,n||{});var i= n.highlight,u,a,f=0;try{u=t.lex(e,n)}catch(h){return r(h)}a=u.length;var p=function( e){if(e)return n.highlight=i,r(e);var t;try{t=s.parse(u,n)}catch(o){e=o}return n .highlight=i,e?r(e):r(null,t)};if(!i||i.length<3)return p();delete n.highlight;if(! a)return p();for(;f<u.length;f++)(function(e){return e.type!=="code"?--a||p():i( e.text,e.lang,function(t,n){if(t)return p(t);if(n==null||n===e.text)return--a||p ();e.text=n,e.escaped=!0,--a||p()})})(u[f]);return}try{return n&&(n=l({},c.defaults ,n)),s.parse(t.lex(e,n),n)}catch(h){h.message+="\nPlease report this to https://github.com/chjj/marked." ;if((n||c.defaults).silent)return"<p>An error occured:</p><pre>"+o(h.message+"",!0 )+"</pre>";throw h}}
...
opt.dir,
opt.modulePathList || require("module").paths
);
local.objectSetDefault(opt, {
env: {
npm_package_description: ""
},
packageJson: JSON.parse(readExample("package.json")),
require: function (file) {
return local.tryCatchOnError(function () {
return require(file);
}, console.error);
}
});
Object.keys(opt.packageJson).forEach(function (key) {
...
function(e, t, n){var r=new s(t,n);return r.parse (e)}
n/a
function(e){return l(c.defaults,e),c}
n/a
function r(e, t){this.options=t||c.defaults,this.links= e,this.rules=n.normal,this.renderer=this.options.renderer||new i,this.renderer.options= this.options;if(!this.links)throw new Error("Tokens array requires a `links` property." );this.options.gfm?this.options.breaks?this.rules=n.breaks:this.rules=n.gfm:this .options.pedantic&&(this.rules=n.pedantic)}
n/a
function(e, t, n){var i=new r(t,n);return i.output(e)}
...
};n._inside=/(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/,n._href=/\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/
,n.link=a(n.link)("inside",n._inside)("href",n._href)(),n.reflink=a(n.reflink)("inside"
,n._inside)(),n.normal=l({},n),n.pedantic=l({},n.normal,{strong:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/
,em:/^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/}),n.gfm=l({},n.normal
,{escape:a(n.escape)("])","~|])")(),url:/^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,del
:/^~~(?=\S)([\s\S]*?\S)~~/,text:a(n.text)("]|","~]|")("|","|https?://|")()}),n.breaks=
l({},n.gfm,{br:a(n.br)("{2,}","*")(),text:a(n.gfm.text)("{2,}","*")()}),r.rules=
n,r.output=function(e,t,n){var i=new r(t,n);return i.output(e)},r.prototype.output=
function(e){var t="",n,r,i,s;while(e){if(s=this.rules.escape.exec(e)){e=e.substring
(s[0].length),t+=s[1];continue}if(s=this.rules.autolink.exec(e)){e=e.substring(s
[0].length),s[2]==="@"?(r=s[1].charAt(6)===":"?this.mangle(s[1].substring(7)):this
.mangle(s[1]),i=this.mangle("mailto:")+r):(r=o(s[1]),i=r),t+=this.renderer.link(
i,null,r);continue}if(!this.inLink&&(s=this.rules.url.exec(e))){e=e.substring(s[0
].length),r=o(s[1]),i=r,t+=this.renderer.link(i,null,r);continue}if(s=this.rules
.tag.exec(e)){!this.inLink&&/^<a /i.test(s[0])?this.inLink=!0:this.inLink&&/^<\/a>/i
...
function(e){if(!this.options. mangle)return e;var t="",n=e.length,r=0,i;for(;r<n;r++)i=e.charCodeAt(r),Math.random ()>.5&&(i="x"+i.toString(16)),t+="&#"+i+";";return t}
...
,em:/^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/}),n.gfm=l({},n.normal
,{escape:a(n.escape)("])","~|])")(),url:/^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,del
:/^~~(?=\S)([\s\S]*?\S)~~/,text:a(n.text)("]|","~]|")("|","|https?://|")()}),n.breaks=
l({},n.gfm,{br:a(n.br)("{2,}","*")(),text:a(n.gfm.text)("{2,}","*")()}),r.rules=
n,r.output=function(e,t,n){var i=new r(t,n);return i.output(e)},r.prototype.output=
function(e){var t="",n,r,i,s;while(e){if(s=this.rules.escape.exec(e)){e=e.substring
(s[0].length),t+=s[1];continue}if(s=this.rules.autolink.exec(e)){e=e.substring(s
[0].length),s[2]==="@"?(r=s[1].charAt(6)===":"?this.mangle(s[1].substring
(7)):this
.mangle(s[1]),i=this.mangle("mailto:")+r):(r=o(s[1]),i=r),t+=this.renderer.link(
i,null,r);continue}if(!this.inLink&&(s=this.rules.url.exec(e))){e=e.substring(s[0
].length),r=o(s[1]),i=r,t+=this.renderer.link(i,null,r);continue}if(s=this.rules
.tag.exec(e)){!this.inLink&&/^<a /i.test(s[0])?this.inLink=!0:this.inLink&&/^<\/a>/i
.test(s[0])&&(this.inLink=!1),e=e.substring(s[0].length),t+=this.options.sanitize?
this.options.sanitizer?this.options.sanitizer(s[0]):o(s[0]):s[0];continue}if(s=this
.rules.link.exec(e)){e=e.substring(s[0].length),this.inLink=!0,t+=this.outputLink
...
function(e){var t="",n,r,i,s;while(e){if(s=this.rules.escape.exec(e)){e=e.substring (s[0].length),t+=s[1];continue}if(s=this.rules.autolink.exec(e)){e=e.substring(s [0].length),s[2]==="@"?(r=s[1].charAt(6)===":"?this.mangle(s[1].substring(7)):this .mangle(s[1]),i=this.mangle("mailto:")+r):(r=o(s[1]),i=r),t+=this.renderer.link( i,null,r);continue}if(!this.inLink&&(s=this.rules.url.exec(e))){e=e.substring(s[0 ].length),r=o(s[1]),i=r,t+=this.renderer.link(i,null,r);continue}if(s=this.rules .tag.exec(e)){!this.inLink&&/^<a /i.test(s[0])?this.inLink=!0:this.inLink&&/^<\/a>/i .test(s[0])&&(this.inLink=!1),e=e.substring(s[0].length),t+=this.options.sanitize? this.options.sanitizer?this.options.sanitizer(s[0]):o(s[0]):s[0];continue}if(s=this .rules.link.exec(e)){e=e.substring(s[0].length),this.inLink=!0,t+=this.outputLink (s,{href:s[2],title:s[3]}),this.inLink=!1;continue}if((s=this.rules.reflink.exec (e))||(s=this.rules.nolink.exec(e))){e=e.substring(s[0].length),n=(s[2]||s[1]).replace (/\s+/g," "),n=this.links[n.toLowerCase()];if(!n||!n.href){t+=s[0].charAt(0),e=s [0].substring(1)+e;continue}this.inLink=!0,t+=this.outputLink(s,n),this.inLink=!1 ;continue}if(s=this.rules.strong.exec(e)){e=e.substring(s[0].length),t+=this.renderer .strong(this.output(s[2]||s[1]));continue}if(s=this.rules.em.exec(e)){e=e.substring (s[0].length),t+=this.renderer.em(this.output(s[2]||s[1]));continue}if(s=this.rules .code.exec(e)){e=e.substring(s[0].length),t+=this.renderer.codespan(o(s[2],!0)); continue}if(s=this.rules.br.exec(e)){e=e.substring(s[0].length),t+=this.renderer .br();continue}if(s=this.rules.del.exec(e)){e=e.substring(s[0].length),t+=this.renderer .del(this.output(s[1]));continue}if(s=this.rules.text.exec(e)){e=e.substring(s[0 ].length),t+=this.renderer.text(o(this.smartypants(s[0])));continue}if(e)throw new Error("Infinite loop on byte: "+e.charCodeAt(0))}return t}
...
};n._inside=/(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/,n._href=/\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/
,n.link=a(n.link)("inside",n._inside)("href",n._href)(),n.reflink=a(n.reflink)("inside"
,n._inside)(),n.normal=l({},n),n.pedantic=l({},n.normal,{strong:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/
,em:/^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/}),n.gfm=l({},n.normal
,{escape:a(n.escape)("])","~|])")(),url:/^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,del
:/^~~(?=\S)([\s\S]*?\S)~~/,text:a(n.text)("]|","~]|")("|","|https?://|")()}),n.breaks=
l({},n.gfm,{br:a(n.br)("{2,}","*")(),text:a(n.gfm.text)("{2,}","*")()}),r.rules=
n,r.output=function(e,t,n){var i=new r(t,n);return i.output(e)},r.prototype.output=
function(e){var t="",n,r,i,s;while(e){if(s=this.rules.escape.exec(e)){e=e.substring
(s[0].length),t+=s[1];continue}if(s=this.rules.autolink.exec(e)){e=e.substring(s
[0].length),s[2]==="@"?(r=s[1].charAt(6)===":"?this.mangle(s[1].substring(7)):this
.mangle(s[1]),i=this.mangle("mailto:")+r):(r=o(s[1]),i=r),t+=this.renderer.link(
i,null,r);continue}if(!this.inLink&&(s=this.rules.url.exec(e))){e=e.substring(s[0
].length),r=o(s[1]),i=r,t+=this.renderer.link(i,null,r);continue}if(s=this.rules
.tag.exec(e)){!this.inLink&&/^<a /i.test(s[0])?this.inLink=!0:this.inLink&&/^<\/a>/i
...
function(e, t){var n=o(t.href),r=t.title?o(t.title):null;return e[0].charAt(0)!=="!"? this.renderer.link(n,r,this.output(e[1])):this.renderer.image(n,r,o(e[1]))}
...
.tag.exec(e)){!this.inLink&&/^<a /i.test(s[0])?this.inLink=!0:this.inLink&&/^<\/a>/i
.test(s[0])&&(this.inLink=!1),e=e.substring(s[0].length),t+=this.options.sanitize?
this.options.sanitizer?this.options.sanitizer(s[0]):o(s[0]):s[0];continue}if(s=this
.rules.link.exec(e)){e=e.substring(s[0].length),this.inLink=!0,t+=this.outputLink
(s,{href:s[2],title:s[3]}),this.inLink=!1;continue}if((s=this.rules.reflink.exec
(e))||(s=this.rules.nolink.exec(e))){e=e.substring(s[0].length),n=(s[2]||s[1]).replace
(/\s+/g," "),n=this.links[n.toLowerCase()];if(!n||!n.href){t+=s[0].charAt(0),e=s
[0].substring(1)+e;continue}this.inLink=!0,t+=this.outputLink(s,n),this.inLink=!1
;continue}if(s=this.rules.strong.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.strong(this.output(s[2]||s[1]));continue}if(s=this.rules.em.exec(e)){e=e.substring
(s[0].length),t+=this.renderer.em(this.output(s[2]||s[1]));continue}if(s=this.rules
.code.exec(e)){e=e.substring(s[0].length),t+=this.renderer.codespan(o(s[2],!0));
continue}if(s=this.rules.br.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.br();continue}if(s=this.rules.del.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.del(this.output(s[1]));continue}if(s=this.rules.text.exec(e)){e=e.substring(s[0
...
function(e){return this.options.smartypants?e.replace(/---/g,"\u2014" ).replace(/--/g,"\u2013").replace(/(^|[-\u2014/(\[{"\s])'/g,"$1\u2018").replace(/'/g ,"\u2019").replace(/(^|[-\u2014/(\[{\u2018\s])"/g,"$1\u201c").replace(/"/g,"\u201d" ).replace(/\.{3}/g,"\u2026"):e}
...
;continue}if(s=this.rules.strong.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.strong(this.output(s[2]||s[1]));continue}if(s=this.rules.em.exec(e)){e=e.substring
(s[0].length),t+=this.renderer.em(this.output(s[2]||s[1]));continue}if(s=this.rules
.code.exec(e)){e=e.substring(s[0].length),t+=this.renderer.codespan(o(s[2],!0));
continue}if(s=this.rules.br.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.br();continue}if(s=this.rules.del.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.del(this.output(s[1]));continue}if(s=this.rules.text.exec(e)){e=e.substring(s[0
].length),t+=this.renderer.text(o(this.smartypants(s[0])));continue}if(e)throw new
Error("Infinite loop on byte: "+e.charCodeAt(0))}return t},r.prototype.outputLink=
function(e,t){var n=o(t.href),r=t.title?o(t.title):null;return e[0].charAt(0)!=="!"?
this.renderer.link(n,r,this.output(e[1])):this.renderer.image(n,r,o(e[1]))},r.prototype
.smartypants=function(e){return this.options.smartypants?e.replace(/---/g,"\u2014"
).replace(/--/g,"\u2013").replace(/(^|[-\u2014/(\[{"\s])'/g,"$1\u2018").replace(/'/g
,"\u2019").replace(/(^|[-\u2014/(\[{\u2018\s])"/g,"$1\u201c").replace(/"/g,"\u201d"
).replace(/\.{3}/g,"\u2026"):e},r.prototype.mangle=function(e){if(!this.options.
...
function t(t){this.tokens=[],this.tokens.links={},this.options=t||c. defaults,this.rules=e.normal,this.options.gfm&&(this.options.tables?this.rules=e .tables:this.rules=e.gfm)}
n/a
function(e, n){var r=new t(n);return r.lex(e)}
...
e,t){return t=t.toLowerCase(),t==="colon"?":":t.charAt(0)==="#"?t.charAt(1)==="x"?
String.fromCharCode(parseInt(t.substring(2),16)):String.fromCharCode(+t.substring
(1)):""})}function a(e,t){return e=e.source,t=t||"",function n(r,i){return r?(i=
i.source||i,i=i.replace(/(^|[^\[])\^/g,"$1"),e=e.replace(r,i),n):new RegExp(e,t)
}}function f(){}function l(e){var t=1,n,r;for(;t<arguments.length;t++){n=arguments
[t];for(r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}function c
(e,n,r){if(r||typeof n=="function"){r||(r=n,n=null),n=l({},c.defaults,n||{});var i=
n.highlight,u,a,f=0;try{u=t.lex(e,n)}catch(h){return r(h)}a=u.length;var p=function(
e){if(e)return n.highlight=i,r(e);var t;try{t=s.parse(u,n)}catch(o){e=o}return n
.highlight=i,e?r(e):r(null,t)};if(!i||i.length<3)return p();delete n.highlight;if(!
a)return p();for(;f<u.length;f++)(function(e){return e.type!=="code"?--a||p():i(
e.text,e.lang,function(t,n){if(t)return p(t);if(n==null||n===e.text)return--a||p
();e.text=n,e.escaped=!0,--a||p()})})(u[f]);return}try{return n&&(n=l({},c.defaults
,n)),s.parse(t.lex(e,n),n)}catch(h){h.message+="\nPlease report this to https://github.com/chjj/marked."
;if((n||c.defaults).silent)return"<p>An error occured:</p><pre>"+o(h.message+"",!0
...
function(e){return e= e.replace(/\r\n|\r/g,"\n").replace(/\t/g," ").replace(/\u00a0/g," ").replace(/\u2424/g ,"\n"),this.token(e,!0)}
...
e,t){return t=t.toLowerCase(),t==="colon"?":":t.charAt(0)==="#"?t.charAt(1)==="x"?
String.fromCharCode(parseInt(t.substring(2),16)):String.fromCharCode(+t.substring
(1)):""})}function a(e,t){return e=e.source,t=t||"",function n(r,i){return r?(i=
i.source||i,i=i.replace(/(^|[^\[])\^/g,"$1"),e=e.replace(r,i),n):new RegExp(e,t)
}}function f(){}function l(e){var t=1,n,r;for(;t<arguments.length;t++){n=arguments
[t];for(r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}function c
(e,n,r){if(r||typeof n=="function"){r||(r=n,n=null),n=l({},c.defaults,n||{});var i=
n.highlight,u,a,f=0;try{u=t.lex(e,n)}catch(h){return r(h)}a=u.length;var p=function(
e){if(e)return n.highlight=i,r(e);var t;try{t=s.parse(u,n)}catch(o){e=o}return n
.highlight=i,e?r(e):r(null,t)};if(!i||i.length<3)return p();delete n.highlight;if(!
a)return p();for(;f<u.length;f++)(function(e){return e.type!=="code"?--a||p():i(
e.text,e.lang,function(t,n){if(t)return p(t);if(n==null||n===e.text)return--a||p
();e.text=n,e.escaped=!0,--a||p()})})(u[f]);return}try{return n&&(n=l({},c.defaults
,n)),s.parse(t.lex(e,n),n)}catch(h){h.message+="\nPlease report this to https://github.com/chjj/marked."
;if((n||c.defaults).silent)return"<p>An error occured:</p><pre>"+o(h.message+"",!0
...
function(t, n, r){var t=t.replace(/^ +$/gm ,""),i,s,o,u,a,f,l,c,h;while(t){if(o=this.rules.newline.exec(t))t=t.substring(o[0 ].length),o[0].length>1&&this.tokens.push({type:"space"});if(o=this.rules.code.exec (t)){t=t.substring(o[0].length),o=o[0].replace(/^ {4}/gm,""),this.tokens.push({type :"code",text:this.options.pedantic?o:o.replace(/\n+$/,"")});continue}if(o=this.rules .fences.exec(t)){t=t.substring(o[0].length),this.tokens.push({type:"code",lang:o [2],text:o[3]||""});continue}if(o=this.rules.heading.exec(t)){t=t.substring(o[0] .length),this.tokens.push({type:"heading",depth:o[1].length,text:o[2]});continue} if(n&&(o=this.rules.nptable.exec(t))){t=t.substring(o[0].length),f={type:"table" ,header:o[1].replace(/^ *| *\| *$/g,"").split(/ *\| */),align:o[2].replace(/^ *|\| *$/g ,"").split(/ *\| */),cells:o[3].replace(/\n$/,"").split("\n")};for(c=0;c<f.align .length;c++)/^ *-+: *$/.test(f.align[c])?f.align[c]="right":/^ *:-+: *$/.test(f. align[c])?f.align[c]="center":/^ *:-+ *$/.test(f.align[c])?f.align[c]="left":f.align [c]=null;for(c=0;c<f.cells.length;c++)f.cells[c]=f.cells[c].split(/ *\| */);this .tokens.push(f);continue}if(o=this.rules.lheading.exec(t)){t=t.substring(o[0].length ),this.tokens.push({type:"heading",depth:o[2]==="="?1:2,text:o[1]});continue}if( o=this.rules.hr.exec(t)){t=t.substring(o[0].length),this.tokens.push({type:"hr"} );continue}if(o=this.rules.blockquote.exec(t)){t=t.substring(o[0].length),this.tokens .push({type:"blockquote_start"}),o=o[0].replace(/^ *> ?/gm,""),this.token(o,n,!0 ),this.tokens.push({type:"blockquote_end"});continue}if(o=this.rules.list.exec(t )){t=t.substring(o[0].length),u=o[2],this.tokens.push({type:"list_start",ordered :u.length>1}),o=o[0].match(this.rules.item),i=!1,h=o.length,c=0;for(;c<h;c++)f=o [c],l=f.length,f=f.replace(/^ *([*+-]|\d+\.) +/,""),~f.indexOf("\n ")&&(l-=f.length ,f=this.options.pedantic?f.replace(/^ {1,4}/gm,""):f.replace(new RegExp("^ {1,"+ l+"}","gm"),"")),this.options.smartLists&&c!==h-1&&(a=e.bullet.exec(o[c+1])[0],u!== a&&!(u.length>1&&a.length>1)&&(t=o.slice(c+1).join("\n")+t,c=h-1)),s=i||/\n\n(?!\s*$)/ .test(f),c!==h-1&&(i=f.charAt(f.length-1)==="\n",s||(s=i)),this.tokens.push({type :s?"loose_item_start":"list_item_start"}),this.token(f,!1,r),this.tokens.push({type :"list_item_end"});this.tokens.push({type:"list_end"});continue}if(o=this.rules. html.exec(t)){t=t.substring(o[0].length),this.tokens.push({type:this.options.sanitize?"paragraph" :"html",pre:!this.options.sanitizer&&(o[1]==="pre"||o[1]==="script"||o[1]==="style" ),text:o[0]});continue}if(!r&&n&&(o=this.rules.def.exec(t))){t=t.substring(o[0]. length),this.tokens.links[o[1].toLowerCase()]={href:o[2],title:o[3]};continue}if( n&&(o=this.rules.table.exec(t))){t=t.substring(o[0].length),f={type:"table",header :o[1].replace(/^ *| *\| *$/g,"").split(/ *\| */),align:o[2].replace(/^ *|\| *$/g ,"").split(/ *\| */),cells:o[3].replace(/(?: *\| *)?\n$/,"").split("\n")};for(c=0 ;c<f.align.length;c++)/^ *-+: *$/.test(f.align[c])?f.align[c]="right":/^ *:-+: *$/ .test(f.align[c])?f.align[c]="center":/^ *:-+ *$/.test(f.align[c])?f.align[c]="left" :f.align[c]=null;for(c=0;c<f.cells.length;c++)f.cells[c]=f.cells[c].replace(/^ *\| *| *\| *$/g ,"").split(/ *\| */);this.tokens.push(f);continue}if(n&&(o=this.rules.paragraph. exec(t))){t=t.substring(o[0].length),this.tokens.push({type:"paragraph",text:o[1 ].charAt(o[1].length-1)==="\n"?o[1].slice(0,-1):o[1]});c...
...
throw new SyntaxError("@import not allowed here.", token.startLine, token.startCol);
case Tokens.NAMESPACE_SYM:
token = tokenStream.LT(1);
this._namespace(false);
throw new SyntaxError("@namespace not allowed here.", token.startLine, token.startCol);
default:
tokenStream.get(); //get the last token
this._unexpectedToken(tokenStream.token());
}
}
}
} catch (ex) {
if (ex instanceof SyntaxError && !this.options.strict) {
this.fire({
type: "error",
...
function s (e){this.tokens=[],this.token=null,this.options=e||c.defaults,this.options.renderer= this.options.renderer||new i,this.renderer=this.options.renderer,this.renderer.options= this.options}
n/a
function(e, t, n){var r=new s(t,n);return r.parse (e)}
...
opt.dir,
opt.modulePathList || require("module").paths
);
local.objectSetDefault(opt, {
env: {
npm_package_description: ""
},
packageJson: JSON.parse(readExample("package.json")),
require: function (file) {
return local.tryCatchOnError(function () {
return require(file);
}, console.error);
}
});
Object.keys(opt.packageJson).forEach(function (key) {
...
function(){return this.token=this.tokens.pop()}
...
}
} else if (typeof spec !== "number") {
// All properties accept some CSS-wide values.
// https://drafts.csswg.org/css-values-3/#common-keywords
if (ValidationTypes.isAny(expression, "inherit | initial | unset")) {
if (expression.hasNext()) {
part = expression.next();
throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part
.col);
}
return;
}
// Property-specific validation.
this.singleProperty(spec, expression);
...
function(e){this.inline=new r(e.links,this.options,this.renderer ),this.tokens=e.reverse();var t="";while(this.next())t+=this.tok();return t}
...
opt.dir,
opt.modulePathList || require("module").paths
);
local.objectSetDefault(opt, {
env: {
npm_package_description: ""
},
packageJson: JSON.parse(readExample("package.json")),
require: function (file) {
return local.tryCatchOnError(function () {
return require(file);
}, console.error);
}
});
Object.keys(opt.packageJson).forEach(function (key) {
...
function(){ var e=this.token.text;while(this.peek().type==="text")e+="\n"+this.next().text;return this .inline.output(e)}
...
for(n=0;n<this.token.cells.length;n++){r=this.token.cells[n],i="";for(o=0;o<r.length
;o++)i+=this.renderer.tablecell(this.inline.output(r[o]),{header:!1,align:this.token
.align[o]});t+=this.renderer.tablerow(i)}return this.renderer.table(e,t);case"blockquote_start"
:var t="";while(this.next().type!=="blockquote_end")t+=this.tok();return this.renderer
.blockquote(t);case"list_start":var t="",u=this.token.ordered;while(this.next().
type!=="list_end")t+=this.tok();return this.renderer.list(t,u);case"list_item_start"
:var t="";while(this.next().type!=="list_item_end")t+=this.token.type==="text"?this
.parseText():this.tok();return this.renderer.listitem(t);case"loose_item_start"
;:
var t="";while(this.next().type!=="list_item_end")t+=this.tok();return this.renderer
.listitem(t);case"html":var a=!this.token.pre&&!this.options.pedantic?this.inline
.output(this.token.text):this.token.text;return this.renderer.html(a);case"paragraph"
:return this.renderer.paragraph(this.inline.output(this.token.text));case"text":
return this.renderer.paragraph(this.parseText())}},f.exec=f,c.options=c.setOptions=
function(e){return l(c.defaults,e),c},c.defaults={gfm:!0,tables:!0,breaks:!1,pedantic
:!1,sanitize:!1,sanitizer:null,mangle:!0,smartLists:!1,silent:!1,highlight:null,
...
function( ){return this.tokens[this.tokens.length-1]||0}
...
//try to read character set
this._charset();
this._skipCruft();
//try to read imports - may be more than one
while (tokenStream.peek() === Tokens.IMPORT_SYM) {
this._import();
this._skipCruft();
}
//try to read namespaces - may be more than one
while (tokenStream.peek() === Tokens.NAMESPACE_SYM) {
this._namespace();
...
function(){switch(this.token.type){case"space" :return"";case"hr":return this.renderer.hr();case"heading":return this.renderer. heading(this.inline.output(this.token.text),this.token.depth,this.token.text);case"code" :return this.renderer.code(this.token.text,this.token.lang,this.token.escaped);case"table" :var e="",t="",n,r,i,s,o;i="";for(n=0;n<this.token.header.length;n++)s={header:!0 ,align:this.token.align[n]},i+=this.renderer.tablecell(this.inline.output(this.token .header[n]),{header:!0,align:this.token.align[n]});e+=this.renderer.tablerow(i); for(n=0;n<this.token.cells.length;n++){r=this.token.cells[n],i="";for(o=0;o<r.length ;o++)i+=this.renderer.tablecell(this.inline.output(r[o]),{header:!1,align:this.token .align[o]});t+=this.renderer.tablerow(i)}return this.renderer.table(e,t);case"blockquote_start" :var t="";while(this.next().type!=="blockquote_end")t+=this.tok();return this.renderer .blockquote(t);case"list_start":var t="",u=this.token.ordered;while(this.next(). type!=="list_end")t+=this.tok();return this.renderer.list(t,u);case"list_item_start" :var t="";while(this.next().type!=="list_item_end")t+=this.token.type==="text"?this .parseText():this.tok();return this.renderer.listitem(t);case"loose_item_start": var t="";while(this.next().type!=="list_item_end")t+=this.tok();return this.renderer .listitem(t);case"html":var a=!this.token.pre&&!this.options.pedantic?this.inline .output(this.token.text):this.token.text;return this.renderer.html(a);case"paragraph" :return this.renderer.paragraph(this.inline.output(this.token.text));case"text": return this.renderer.paragraph(this.parseText())}}
...
e,t,n){if(this.options.sanitize){try{var r=decodeURIComponent(u(e)).replace(/[^\w:]/g
,"").toLowerCase()}catch(i){return""}if(r.indexOf("javascript:")===0||r.indexOf("vbscript:"
;
)===0||r.indexOf("data:")===0)return""}var s='<a href="'+e+'"';return t&
;&(s+=' title="'+
t+'"'),s+=">"+n+"</a>",s},i.prototype.image=function(e,t,n){var r='<img src=&
quot;'+e+'" alt="'+
n+'"';return t&&(r+=' title="'+t+'"'),r+=this.options.xhtml?"/>"
;:">",r},i.prototype
.text=function(e){return e},s.parse=function(e,t,n){var r=new s(t,n);return r.parse
(e)},s.prototype.parse=function(e){this.inline=new r(e.links,this.options,this.renderer
),this.tokens=e.reverse();var t="";while(this.next())t+=this.tok();return t
},s.prototype
.next=function(){return this.token=this.tokens.pop()},s.prototype.peek=function(
){return this.tokens[this.tokens.length-1]||0},s.prototype.parseText=function(){
var e=this.token.text;while(this.peek().type==="text")e+="\n"+this.next().text;return this
.inline.output(e)},s.prototype.tok=function(){switch(this.token.type){case"space"
:return"";case"hr":return this.renderer.hr();case"heading":return this.renderer.
heading(this.inline.output(this.token.text),this.token.depth,this.token.text);case"code"
:return this.renderer.code(this.token.text,this.token.lang,this.token.escaped);case"table"
...
function i(e){this.options=e||{}}
n/a
function(e){return"<blockquote>\n"+e+"</blockquote>\n"}
...
:var e="",t="",n,r,i,s,o;i="";for(n=0;n<this.token.header.length;n++)s={header:!0
,align:this.token.align[n]},i+=this.renderer.tablecell(this.inline.output(this.token
.header[n]),{header:!0,align:this.token.align[n]});e+=this.renderer.tablerow(i);
for(n=0;n<this.token.cells.length;n++){r=this.token.cells[n],i="";for(o=0;o<r.length
;o++)i+=this.renderer.tablecell(this.inline.output(r[o]),{header:!1,align:this.token
.align[o]});t+=this.renderer.tablerow(i)}return this.renderer.table(e,t);case"blockquote_start"
:var t="";while(this.next().type!=="blockquote_end")t+=this.tok();return this.renderer
.blockquote(t);case"list_start":var t="",u=this.token.ordered;while
(this.next().
type!=="list_end")t+=this.tok();return this.renderer.list(t,u);case"list_item_start"
:var t="";while(this.next().type!=="list_item_end")t+=this.token.type==="text"?this
.parseText():this.tok();return this.renderer.listitem(t);case"loose_item_start":
var t="";while(this.next().type!=="list_item_end")t+=this.tok();return this.renderer
.listitem(t);case"html":var a=!this.token.pre&&!this.options.pedantic?this.inline
.output(this.token.text):this.token.text;return this.renderer.html(a);case"paragraph"
:return this.renderer.paragraph(this.inline.output(this.token.text));case"text":
...
function(){return this.options.xhtml?"<br/>":"<br>"}
...
(/\s+/g," "),n=this.links[n.toLowerCase()];if(!n||!n.href){t+=s[0].charAt(0),e=s
[0].substring(1)+e;continue}this.inLink=!0,t+=this.outputLink(s,n),this.inLink=!1
;continue}if(s=this.rules.strong.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.strong(this.output(s[2]||s[1]));continue}if(s=this.rules.em.exec(e)){e=e.substring
(s[0].length),t+=this.renderer.em(this.output(s[2]||s[1]));continue}if(s=this.rules
.code.exec(e)){e=e.substring(s[0].length),t+=this.renderer.codespan(o(s[2],!0));
continue}if(s=this.rules.br.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.br();continue}if(s=this.rules.del.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.del(this.output(s[1]));continue}if(s=this.rules.text.exec(e)){e=e.substring(s[0
].length),t+=this.renderer.text(o(this.smartypants(s[0])));continue}if(e)throw new
Error("Infinite loop on byte: "+e.charCodeAt(0))}return t},r.prototype.outputLink=
function(e,t){var n=o(t.href),r=t.title?o(t.title):null;return e[0].charAt(0)!=="!"?
this.renderer.link(n,r,this.output(e[1])):this.renderer.image(n,r,o(e[1]))},r.prototype
.smartypants=function(e){return this.options.smartypants?e.replace(/---/g,"\u2014"
).replace(/--/g,"\u2013").replace(/(^|[-\u2014/(\[{"\s])'/g,"$1\u2018").replace(/'/g
...
function( e, t, n){if(this.options.highlight){var r=this.options.highlight(e,t);r!=null&&r!== e&&(n=!0,e=r)}return t?'<pre><code class="'+this.options.langPrefix+o(t,!0)+'">'+ (n?e:o(e,!0))+"\n</code></pre>\n":"<pre><code>"+(n?e:o(e,!0))+"\n</code></pre>"}
...
),this.tokens=e.reverse();var t="";while(this.next())t+=this.tok();return t},s.prototype
.next=function(){return this.token=this.tokens.pop()},s.prototype.peek=function(
){return this.tokens[this.tokens.length-1]||0},s.prototype.parseText=function(){
var e=this.token.text;while(this.peek().type==="text")e+="\n"+this.next().text;return this
.inline.output(e)},s.prototype.tok=function(){switch(this.token.type){case"space"
:return"";case"hr":return this.renderer.hr();case"heading":return this.renderer.
heading(this.inline.output(this.token.text),this.token.depth,this.token.text);case"code"
:return this.renderer.code(this.token.text,this.token.lang,this.token.escaped);case"
;table"
:var e="",t="",n,r,i,s,o;i="";for(n=0;n<this.token.header.length;n++)s={header:!0
,align:this.token.align[n]},i+=this.renderer.tablecell(this.inline.output(this.token
.header[n]),{header:!0,align:this.token.align[n]});e+=this.renderer.tablerow(i);
for(n=0;n<this.token.cells.length;n++){r=this.token.cells[n],i="";for(o=0;o<r.length
;o++)i+=this.renderer.tablecell(this.inline.output(r[o]),{header:!1,align:this.token
.align[o]});t+=this.renderer.tablerow(i)}return this.renderer.table(e,t);case"blockquote_start"
:var t="";while(this.next().type!=="blockquote_end")t+=this.tok();return this.renderer
...
function(e){return"<code>"+ e+"</code>"}
...
(s,{href:s[2],title:s[3]}),this.inLink=!1;continue}if((s=this.rules.reflink.exec
(e))||(s=this.rules.nolink.exec(e))){e=e.substring(s[0].length),n=(s[2]||s[1]).replace
(/\s+/g," "),n=this.links[n.toLowerCase()];if(!n||!n.href){t+=s[0].charAt(0),e=s
[0].substring(1)+e;continue}this.inLink=!0,t+=this.outputLink(s,n),this.inLink=!1
;continue}if(s=this.rules.strong.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.strong(this.output(s[2]||s[1]));continue}if(s=this.rules.em.exec(e)){e=e.substring
(s[0].length),t+=this.renderer.em(this.output(s[2]||s[1]));continue}if(s=this.rules
.code.exec(e)){e=e.substring(s[0].length),t+=this.renderer.codespan(o(s[2],!0));
continue}if(s=this.rules.br.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.br();continue}if(s=this.rules.del.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.del(this.output(s[1]));continue}if(s=this.rules.text.exec(e)){e=e.substring(s[0
].length),t+=this.renderer.text(o(this.smartypants(s[0])));continue}if(e)throw new
Error("Infinite loop on byte: "+e.charCodeAt(0))}return t},r.prototype.outputLink=
function(e,t){var n=o(t.href),r=t.title?o(t.title):null;return e[0].charAt(0)!=="!"?
this.renderer.link(n,r,this.output(e[1])):this.renderer.image(n,r,o(e[1]))},r.prototype
...
function(e){return"<del>"+e+"</del>"}
...
[0].substring(1)+e;continue}this.inLink=!0,t+=this.outputLink(s,n),this.inLink=!1
;continue}if(s=this.rules.strong.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.strong(this.output(s[2]||s[1]));continue}if(s=this.rules.em.exec(e)){e=e.substring
(s[0].length),t+=this.renderer.em(this.output(s[2]||s[1]));continue}if(s=this.rules
.code.exec(e)){e=e.substring(s[0].length),t+=this.renderer.codespan(o(s[2],!0));
continue}if(s=this.rules.br.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.br();continue}if(s=this.rules.del.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.del(this.output(s[1]));continue}if(s=this.rules.text.exec(e)){e=e.substring(s[0
].length),t+=this.renderer.text(o(this.smartypants(s[0])));continue}if(e)throw new
Error("Infinite loop on byte: "+e.charCodeAt(0))}return t},r.prototype.outputLink=
function(e,t){var n=o(t.href),r=t.title?o(t.title):null;return e[0].charAt(0)!=="!"?
this.renderer.link(n,r,this.output(e[1])):this.renderer.image(n,r,o(e[1]))},r.prototype
.smartypants=function(e){return this.options.smartypants?e.replace(/---/g,"\u2014"
).replace(/--/g,"\u2013").replace(/(^|[-\u2014/(\[{"\s])'/g,"$1\u2018").replace(/'/g
,"\u2019").replace(/(^|[-\u2014/(\[{\u2018\s])"/g,"$1\u201c").replace(/"/g,"\u201d"
...
function(e){return"<em>"+e+"</em>"}
...
.rules.link.exec(e)){e=e.substring(s[0].length),this.inLink=!0,t+=this.outputLink
(s,{href:s[2],title:s[3]}),this.inLink=!1;continue}if((s=this.rules.reflink.exec
(e))||(s=this.rules.nolink.exec(e))){e=e.substring(s[0].length),n=(s[2]||s[1]).replace
(/\s+/g," "),n=this.links[n.toLowerCase()];if(!n||!n.href){t+=s[0].charAt(0),e=s
[0].substring(1)+e;continue}this.inLink=!0,t+=this.outputLink(s,n),this.inLink=!1
;continue}if(s=this.rules.strong.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.strong(this.output(s[2]||s[1]));continue}if(s=this.rules.em.exec(e)){e=e.substring
(s[0].length),t+=this.renderer.em(this.output(s[2]||s[1]));continue}if(s=this.rules
.code.exec(e)){e=e.substring(s[0].length),t+=this.renderer.codespan(o(s[2],!0));
continue}if(s=this.rules.br.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.br();continue}if(s=this.rules.del.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.del(this.output(s[1]));continue}if(s=this.rules.text.exec(e)){e=e.substring(s[0
].length),t+=this.renderer.text(o(this.smartypants(s[0])));continue}if(e)throw new
Error("Infinite loop on byte: "+e.charCodeAt(0))}return t},r.prototype.outputLink=
function(e,t){var n=o(t.href),r=t.title?o(t.title):null;return e[0].charAt(0)!=="!"?
...
function(e, t, n){return"<h"+ t+' id="'+this.options.headerPrefix+n.toLowerCase().replace(/[^\w]+/g,"-")+'">'+ e+"</h"+t+">\n"}
n/a
function(){return this.options.xhtml?"<hr/>\n":"<hr>\n" }
...
.text=function(e){return e},s.parse=function(e,t,n){var r=new s(t,n);return r.parse
(e)},s.prototype.parse=function(e){this.inline=new r(e.links,this.options,this.renderer
),this.tokens=e.reverse();var t="";while(this.next())t+=this.tok();return t},s.prototype
.next=function(){return this.token=this.tokens.pop()},s.prototype.peek=function(
){return this.tokens[this.tokens.length-1]||0},s.prototype.parseText=function(){
var e=this.token.text;while(this.peek().type==="text")e+="\n"+this.next().text;return this
.inline.output(e)},s.prototype.tok=function(){switch(this.token.type){case"space"
:return"";case"hr":return this.renderer.hr();case"heading"
;:return this.renderer.
heading(this.inline.output(this.token.text),this.token.depth,this.token.text);case"code"
:return this.renderer.code(this.token.text,this.token.lang,this.token.escaped);case"table"
:var e="",t="",n,r,i,s,o;i="";for(n=0;n<this.token.header.length;n++)s={header:!0
,align:this.token.align[n]},i+=this.renderer.tablecell(this.inline.output(this.token
.header[n]),{header:!0,align:this.token.align[n]});e+=this.renderer.tablerow(i);
for(n=0;n<this.token.cells.length;n++){r=this.token.cells[n],i="";for(o=0;o<r.length
;o++)i+=this.renderer.tablecell(this.inline.output(r[o]),{header:!1,align:this.token
...
function(e){return e}
...
:var t="";while(this.next().type!=="blockquote_end")t+=this.tok();return this.renderer
.blockquote(t);case"list_start":var t="",u=this.token.ordered;while(this.next().
type!=="list_end")t+=this.tok();return this.renderer.list(t,u);case"list_item_start"
:var t="";while(this.next().type!=="list_item_end")t+=this.token.type==="text"?this
.parseText():this.tok();return this.renderer.listitem(t);case"loose_item_start":
var t="";while(this.next().type!=="list_item_end")t+=this.tok();return this.renderer
.listitem(t);case"html":var a=!this.token.pre&&!this.options.pedantic?this.inline
.output(this.token.text):this.token.text;return this.renderer.html(a);case"paragraph
"
:return this.renderer.paragraph(this.inline.output(this.token.text));case"text":
return this.renderer.paragraph(this.parseText())}},f.exec=f,c.options=c.setOptions=
function(e){return l(c.defaults,e),c},c.defaults={gfm:!0,tables:!0,breaks:!1,pedantic
:!1,sanitize:!1,sanitizer:null,mangle:!0,smartLists:!1,silent:!1,highlight:null,
langPrefix:"lang-",smartypants:!1,headerPrefix:"",renderer:new i,xhtml:!1},c.Parser=
s,c.parser=s.parse,c.Renderer=i,c.Lexer=t,c.lexer=t.lex,c.InlineLexer=r,c.inlineLexer=
r.output,c.parse=c,typeof module!="undefined"&&typeof exports=="object"?module.exports=
...
function(e, t, n){var r='<img src="'+e+'" alt="'+ n+'"';return t&&(r+=' title="'+t+'"'),r+=this.options.xhtml?"/>":">",r}
...
.code.exec(e)){e=e.substring(s[0].length),t+=this.renderer.codespan(o(s[2],!0));
continue}if(s=this.rules.br.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.br();continue}if(s=this.rules.del.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.del(this.output(s[1]));continue}if(s=this.rules.text.exec(e)){e=e.substring(s[0
].length),t+=this.renderer.text(o(this.smartypants(s[0])));continue}if(e)throw new
Error("Infinite loop on byte: "+e.charCodeAt(0))}return t},r.prototype.outputLink=
function(e,t){var n=o(t.href),r=t.title?o(t.title):null;return e[0].charAt(0)!=="!"?
this.renderer.link(n,r,this.output(e[1])):this.renderer.image(n,r,o(e[1]))},r.prototype
.smartypants=function(e){return this.options.smartypants?e.replace(/---/g,"\u2014"
).replace(/--/g,"\u2013").replace(/(^|[-\u2014/(\[{"\s])'/g,"$1\u2018").replace(/'/g
,"\u2019").replace(/(^|[-\u2014/(\[{\u2018\s])"/g,"$1\u201c").replace(/"/g,"\u201d"
).replace(/\.{3}/g,"\u2026"):e},r.prototype.mangle=function(e){if(!this.options.
mangle)return e;var t="",n=e.length,r=0,i;for(;r<n;r++)i=e.charCodeAt(r),Math.random
()>.5&&(i="x"+i.toString(16)),t+="&#"+i+";";return t},i.prototype.code=function(
e,t,n){if(this.options.highlight){var r=this.options.highlight(e,t);r!=null&&r!==
...
function( e, t, n){if(this.options.sanitize){try{var r=decodeURIComponent(u(e)).replace(/[^\w:]/g ,"").toLowerCase()}catch(i){return""}if(r.indexOf("javascript:")===0||r.indexOf("vbscript:" )===0||r.indexOf("data:")===0)return""}var s='<a href="'+e+'"';return t&&(s+=' title="'+ t+'"'),s+=">"+n+"</a>",s}
...
,{escape:a(n.escape)("])","~|])")(),url:/^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,del
:/^~~(?=\S)([\s\S]*?\S)~~/,text:a(n.text)("]|","~]|")("|","|https?://|")()}),n.breaks=
l({},n.gfm,{br:a(n.br)("{2,}","*")(),text:a(n.gfm.text)("{2,}","*")()}),r.rules=
n,r.output=function(e,t,n){var i=new r(t,n);return i.output(e)},r.prototype.output=
function(e){var t="",n,r,i,s;while(e){if(s=this.rules.escape.exec(e)){e=e.substring
(s[0].length),t+=s[1];continue}if(s=this.rules.autolink.exec(e)){e=e.substring(s
[0].length),s[2]==="@"?(r=s[1].charAt(6)===":"?this.mangle(s[1].substring(7)):this
.mangle(s[1]),i=this.mangle("mailto:")+r):(r=o(s[1]),i=r),t+=this.renderer.link(
i,null,r);continue}if(!this.inLink&&(s=this.rules.url.exec(e))){e=e.substring(s[0
].length),r=o(s[1]),i=r,t+=this.renderer.link(i,null,r);continue}if(s=this.rules
.tag.exec(e)){!this.inLink&&/^<a /i.test(s[0])?this.inLink=!0:this.inLink&&/^<\/a>/i
.test(s[0])&&(this.inLink=!1),e=e.substring(s[0].length),t+=this.options.sanitize?
this.options.sanitizer?this.options.sanitizer(s[0]):o(s[0]):s[0];continue}if(s=this
.rules.link.exec(e)){e=e.substring(s[0].length),this.inLink=!0,t+=this.outputLink
(s,{href:s[2],title:s[3]}),this.inLink=!1;continue}if((s=this.rules.reflink.exec
...
function(e, t){var n=t?"ol":"ul";return"<"+n+">\n"+e+"</"+n+">\n" }
...
,align:this.token.align[n]},i+=this.renderer.tablecell(this.inline.output(this.token
.header[n]),{header:!0,align:this.token.align[n]});e+=this.renderer.tablerow(i);
for(n=0;n<this.token.cells.length;n++){r=this.token.cells[n],i="";for(o=0;o<r.length
;o++)i+=this.renderer.tablecell(this.inline.output(r[o]),{header:!1,align:this.token
.align[o]});t+=this.renderer.tablerow(i)}return this.renderer.table(e,t);case"blockquote_start"
:var t="";while(this.next().type!=="blockquote_end")t+=this.tok();return this.renderer
.blockquote(t);case"list_start":var t="",u=this.token.ordered;while(this.next().
type!=="list_end")t+=this.tok();return this.renderer.list(t,u);case"list_item_start
"
:var t="";while(this.next().type!=="list_item_end")t+=this.token.type==="text"?this
.parseText():this.tok();return this.renderer.listitem(t);case"loose_item_start":
var t="";while(this.next().type!=="list_item_end")t+=this.tok();return this.renderer
.listitem(t);case"html":var a=!this.token.pre&&!this.options.pedantic?this.inline
.output(this.token.text):this.token.text;return this.renderer.html(a);case"paragraph"
:return this.renderer.paragraph(this.inline.output(this.token.text));case"text":
return this.renderer.paragraph(this.parseText())}},f.exec=f,c.options=c.setOptions=
...
function(e){return"<li>"+e+"</li>\n"}
...
for(n=0;n<this.token.cells.length;n++){r=this.token.cells[n],i="";for(o=0;o<r.length
;o++)i+=this.renderer.tablecell(this.inline.output(r[o]),{header:!1,align:this.token
.align[o]});t+=this.renderer.tablerow(i)}return this.renderer.table(e,t);case"blockquote_start"
:var t="";while(this.next().type!=="blockquote_end")t+=this.tok();return this.renderer
.blockquote(t);case"list_start":var t="",u=this.token.ordered;while(this.next().
type!=="list_end")t+=this.tok();return this.renderer.list(t,u);case"list_item_start"
:var t="";while(this.next().type!=="list_item_end")t+=this.token.type==="text"?this
.parseText():this.tok();return this.renderer.listitem(t);case"loose_item_start"
;:
var t="";while(this.next().type!=="list_item_end")t+=this.tok();return this.renderer
.listitem(t);case"html":var a=!this.token.pre&&!this.options.pedantic?this.inline
.output(this.token.text):this.token.text;return this.renderer.html(a);case"paragraph"
:return this.renderer.paragraph(this.inline.output(this.token.text));case"text":
return this.renderer.paragraph(this.parseText())}},f.exec=f,c.options=c.setOptions=
function(e){return l(c.defaults,e),c},c.defaults={gfm:!0,tables:!0,breaks:!1,pedantic
:!1,sanitize:!1,sanitizer:null,mangle:!0,smartLists:!1,silent:!1,highlight:null,
...
function(e){return"<p>"+e+"</p>\n"}
...
.blockquote(t);case"list_start":var t="",u=this.token.ordered;while(this.next().
type!=="list_end")t+=this.tok();return this.renderer.list(t,u);case"list_item_start"
:var t="";while(this.next().type!=="list_item_end")t+=this.token.type==="text"?this
.parseText():this.tok();return this.renderer.listitem(t);case"loose_item_start":
var t="";while(this.next().type!=="list_item_end")t+=this.tok();return this.renderer
.listitem(t);case"html":var a=!this.token.pre&&!this.options.pedantic?this.inline
.output(this.token.text):this.token.text;return this.renderer.html(a);case"paragraph"
:return this.renderer.paragraph(this.inline.output(this.token.text));case"text"
;:
return this.renderer.paragraph(this.parseText())}},f.exec=f,c.options=c.setOptions=
function(e){return l(c.defaults,e),c},c.defaults={gfm:!0,tables:!0,breaks:!1,pedantic
:!1,sanitize:!1,sanitizer:null,mangle:!0,smartLists:!1,silent:!1,highlight:null,
langPrefix:"lang-",smartypants:!1,headerPrefix:"",renderer:new i,xhtml:!1},c.Parser=
s,c.parser=s.parse,c.Renderer=i,c.Lexer=t,c.lexer=t.lex,c.InlineLexer=r,c.inlineLexer=
r.output,c.parse=c,typeof module!="undefined"&&typeof exports=="object"?module.exports=
c:typeof define=="function"&&define.amd?define(function(){return c}):this.marked=
...
function(e){return"<strong>"+e+"</strong>"}
...
this.options.sanitizer?this.options.sanitizer(s[0]):o(s[0]):s[0];continue}if(s=this
.rules.link.exec(e)){e=e.substring(s[0].length),this.inLink=!0,t+=this.outputLink
(s,{href:s[2],title:s[3]}),this.inLink=!1;continue}if((s=this.rules.reflink.exec
(e))||(s=this.rules.nolink.exec(e))){e=e.substring(s[0].length),n=(s[2]||s[1]).replace
(/\s+/g," "),n=this.links[n.toLowerCase()];if(!n||!n.href){t+=s[0].charAt(0),e=s
[0].substring(1)+e;continue}this.inLink=!0,t+=this.outputLink(s,n),this.inLink=!1
;continue}if(s=this.rules.strong.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.strong(this.output(s[2]||s[1]));continue}if(s=this.rules.em.exec(e)){e=e.substring
(s[0].length),t+=this.renderer.em(this.output(s[2]||s[1]));continue}if(s=this.rules
.code.exec(e)){e=e.substring(s[0].length),t+=this.renderer.codespan(o(s[2],!0));
continue}if(s=this.rules.br.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.br();continue}if(s=this.rules.del.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.del(this.output(s[1]));continue}if(s=this.rules.text.exec(e)){e=e.substring(s[0
].length),t+=this.renderer.text(o(this.smartypants(s[0])));continue}if(e)throw new
Error("Infinite loop on byte: "+e.charCodeAt(0))}return t},r.prototype.outputLink=
...
function(e, t){return"<table>\n<thead>\n"+ e+"</thead>\n"+"<tbody>\n"+t+"</tbody>\n"+"</table>\n"}
...
heading(this.inline.output(this.token.text),this.token.depth,this.token.text);case"code"
:return this.renderer.code(this.token.text,this.token.lang,this.token.escaped);case"table"
:var e="",t="",n,r,i,s,o;i="";for(n=0;n<this.token.header.length;n++)s={header:!0
,align:this.token.align[n]},i+=this.renderer.tablecell(this.inline.output(this.token
.header[n]),{header:!0,align:this.token.align[n]});e+=this.renderer.tablerow(i);
for(n=0;n<this.token.cells.length;n++){r=this.token.cells[n],i="";for(o=0;o<r.length
;o++)i+=this.renderer.tablecell(this.inline.output(r[o]),{header:!1,align:this.token
.align[o]});t+=this.renderer.tablerow(i)}return this.renderer.table(e,t);case"blockquote_start
"
:var t="";while(this.next().type!=="blockquote_end")t+=this.tok();return this.renderer
.blockquote(t);case"list_start":var t="",u=this.token.ordered;while(this.next().
type!=="list_end")t+=this.tok();return this.renderer.list(t,u);case"list_item_start"
:var t="";while(this.next().type!=="list_item_end")t+=this.token.type==="text"?this
.parseText():this.tok();return this.renderer.listitem(t);case"loose_item_start":
var t="";while(this.next().type!=="list_item_end")t+=this.tok();return this.renderer
.listitem(t);case"html":var a=!this.token.pre&&!this.options.pedantic?this.inline
...
function(e, t){var n=t.header?"th" :"td",r=t.align?"<"+n+' style="text-align:'+t.align+'">':"<"+n+">";return r+e+"</"+ n+">\n"}
...
){return this.tokens[this.tokens.length-1]||0},s.prototype.parseText=function(){
var e=this.token.text;while(this.peek().type==="text")e+="\n"+this.next().text;return this
.inline.output(e)},s.prototype.tok=function(){switch(this.token.type){case"space"
:return"";case"hr":return this.renderer.hr();case"heading":return this.renderer.
heading(this.inline.output(this.token.text),this.token.depth,this.token.text);case"code"
:return this.renderer.code(this.token.text,this.token.lang,this.token.escaped);case"table"
:var e="",t="",n,r,i,s,o;i="";for(n=0;n<this.token.header.length;n++)s={header:!0
,align:this.token.align[n]},i+=this.renderer.tablecell(this.inline.output(this.token
.header[n]),{header:!0,align:this.token.align[n]});e+=this.renderer.tablerow(i);
for(n=0;n<this.token.cells.length;n++){r=this.token.cells[n],i="";for(o=0;o<r.length
;o++)i+=this.renderer.tablecell(this.inline.output(r[o]),{header:!1,align:this.token
.align[o]});t+=this.renderer.tablerow(i)}return this.renderer.table(e,t);case"blockquote_start"
:var t="";while(this.next().type!=="blockquote_end")t+=this.tok();return this.renderer
.blockquote(t);case"list_start":var t="",u=this.token.ordered;while(this.next().
type!=="list_end")t+=this.tok();return this.renderer.list(t,u);case"list_item_start"
...
function( e){return"<tr>\n"+e+"</tr>\n"}
...
var e=this.token.text;while(this.peek().type==="text")e+="\n"+this.next().text;return this
.inline.output(e)},s.prototype.tok=function(){switch(this.token.type){case"space"
:return"";case"hr":return this.renderer.hr();case"heading":return this.renderer.
heading(this.inline.output(this.token.text),this.token.depth,this.token.text);case"code"
:return this.renderer.code(this.token.text,this.token.lang,this.token.escaped);case"table"
:var e="",t="",n,r,i,s,o;i="";for(n=0;n<this.token.header.length;n++)s={header:!0
,align:this.token.align[n]},i+=this.renderer.tablecell(this.inline.output(this.token
.header[n]),{header:!0,align:this.token.align[n]});e+=this.renderer.tablerow(i);
for(n=0;n<this.token.cells.length;n++){r=this.token.cells[n],i="";for(o=0;o<r.length
;o++)i+=this.renderer.tablecell(this.inline.output(r[o]),{header:!1,align:this.token
.align[o]});t+=this.renderer.tablerow(i)}return this.renderer.table(e,t);case"blockquote_start"
:var t="";while(this.next().type!=="blockquote_end")t+=this.tok();return this.renderer
.blockquote(t);case"list_start":var t="",u=this.token.ordered;while(this.next().
type!=="list_end")t+=this.tok();return this.renderer.list(t,u);case"list_item_start"
:var t="";while(this.next().type!=="list_item_end")t+=this.token.type==="text"?this
...
function(e){return e}
...
;continue}if(s=this.rules.strong.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.strong(this.output(s[2]||s[1]));continue}if(s=this.rules.em.exec(e)){e=e.substring
(s[0].length),t+=this.renderer.em(this.output(s[2]||s[1]));continue}if(s=this.rules
.code.exec(e)){e=e.substring(s[0].length),t+=this.renderer.codespan(o(s[2],!0));
continue}if(s=this.rules.br.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.br();continue}if(s=this.rules.del.exec(e)){e=e.substring(s[0].length),t+=this.renderer
.del(this.output(s[1]));continue}if(s=this.rules.text.exec(e)){e=e.substring(s[0
].length),t+=this.renderer.text(o(this.smartypants(s[0])));continue}if(e)throw new
Error("Infinite loop on byte: "+e.charCodeAt(0))}return t},r.prototype.outputLink=
function(e,t){var n=o(t.href),r=t.title?o(t.title):null;return e[0].charAt(0)!=="!"?
this.renderer.link(n,r,this.output(e[1])):this.renderer.image(n,r,o(e[1]))},r.prototype
.smartypants=function(e){return this.options.smartypants?e.replace(/---/g,"\u2014"
).replace(/--/g,"\u2013").replace(/(^|[-\u2014/(\[{"\s])'/g,"$1\u2018").replace(/'/g
,"\u2019").replace(/(^|[-\u2014/(\[{\u2018\s])"/g,"$1\u201c").replace(/"/g,"\u201d"
).replace(/\.{3}/g,"\u2026"):e},r.prototype.mangle=function(e){if(!this.options.
...
function(a, b, c, d){var e=sjcl.json;return e.ia(a,e.decode(b),c,d)}
...
f[7]+q|0}
sjcl.mode.ccm={name:"ccm",G:[],listenProgress:function(a){sjcl.mode.ccm.G.push(a)},unListenProgress:function(a){a=sjcl
.mode.ccm.G.indexOf(a);-1<a&&sjcl.mode.ccm.G.splice(a,1)},fa:function(a){var b=sjcl.mode.ccm.G.slice(),c;for(c=0;c<
;b.length;c+=1)b[c](a)},encrypt:function(a,b,c,d,e){var f,g=b.slice(0),h=sjcl.bitArray,k=h.bitLength(c)/8,l=h.bitLength(g)/8;e=e
||64;d=d||[];if(7>k)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(f=2;4>f&&l&
gt;>>8*f;f++);f<15-k&&(f=15-k);c=h.clamp(c,
8*(15-f));b=sjcl.mode.ccm.V(a,b,c,d,e,f);g=sjcl.mode.ccm.C(a,g,c,b,e,f);return h.concat(g.data,g.tag)},decrypt:function(a,b,c,d,
e){e=e||64;d=d||[];var f=sjcl.bitArray,g=f.bitLength(c)/8,h=f.bitLength(b),k=f.clamp(b,h-e),l=f.bitSlice(b,h-e),h=(h-e)/8;if(7>
;g)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(b=2;4>b&&h>>>8*b;b++);
b<15-g&&(b=15-g);c=f.clamp(c,8*(15-b));k=sjcl.mode.ccm.C(a,k,c,l,e,b);a=sjcl.mode.ccm.V(a,k.data,c,d,e,b);if(!f.equal
(k.tag,a))throw new sjcl.exception.corrupt("ccm: tag doesn't match");
return k.data},na:function(a,b,c,d,e,f){var g=[],h=sjcl.bitArray,k=h.i;d=[h.partial(8,(b.length?64:0)|d-2<<2|f-1)];d=h.concat
(d,c);d[3]|=e;d=a.encrypt(d);if(b.length)for(c=h.bitLength(b)/8,65279>=c?g=[h.partial(16,c)]:0xffffffff>=c&&(g=h.concat
([h.partial(16,65534)],[c])),g=h.concat(g,b),b=0;b<g.length;b+=4)d=a.encrypt(k(d,g.slice(b,b+4).concat([0,0,0])));return d},V
:function(a,b,c,d,e,f){var g=sjcl.bitArray,h=g.i;e/=8;if(e%2||4>e||16<e)throw new sjcl.exception.invalid("ccm: invalid
tag length");
if(0xffffffff<d.length||0xffffffff<b.length)throw new sjcl.exception.bug("ccm: can't deal with 4GiB or more data
");c=sjcl.mode.ccm.na(a,d,c,e,g.bitLength(b)/8,f);for(d=0;d<b.length;d+=4)c=a.encrypt(h(c,b.slice(d,d+4).concat([0,0,0])));
return g.clamp(c,8*e)},C:function(a,b,c,d,e,f){var g,h=sjcl.bitArray;g=h.i;var k=b.length,l=h.bitLength(b),n=k/50,m=n;c=h.concat
([h.partial(8,f-1)],c).concat([0,0,0]).slice(0,4);d=h.bitSlice(g(d,a.encrypt(c)),0,e);if(!k)return{tag:d,data:[]};for(g=0;g<k
;g+=4)g>n&&(sjcl.mode.ccm.fa(g/
k),n+=m),c[3]++,e=a.encrypt(c),b[g]^=e[0],b[g+1]^=e[1],b[g+2]^=e[2],b[g+3]^=e[3];return{tag:d,data:h.clamp(b,l)}}};
sjcl.mode.ocb2={name:"ocb2",encrypt:function(a,b,c,d,e,f){if(128!==sjcl.bitArray.bitLength(c))throw new sjcl.exception
.invalid("ocb iv must be 128 bits");var g,h=sjcl.mode.ocb2.S,k=sjcl.bitArray,l=k.i,n=[0,0,0,0];c=h(a.encrypt(c));var m
,p=[];d=d||[];e=e||64;for(g=0;g+4<b.length;g+=4)m=b.slice(g,g+4),n=l(n,m),p=p.concat(l(c,a.encrypt(l(c,m)))),c=h(c);m=b.slice
(g);b=k.bitLength(m);g=a.encrypt(l(c,[0,0,0,b]));m=k.clamp(l(m.concat([0,0,0]),g),b);n=l(n,l(m.concat([0,0,0]),g));n=a.encrypt(l
(n,l(c,h(c))));
d.length&&(n=l(n,f?d:sjcl.mode.ocb2.pmac(a,d)));return p.concat(k.concat(m,k.clamp(n,e)))},decrypt:function(a,b,c,d,e,f){
if(128!==sjcl.bitArray.bitLength(c))throw new sjcl.exception.invalid("ocb iv must be 128 bits");e=e||64;var g=sjcl.mode
.ocb2.S,h=sjcl.bitArray,k=h.i,l=[0,0,0,0],n=g(a.encrypt(c)),m,p,r=sjcl.bitArray.bitLength(b)-e,q=[];d=d||[];for(c=0;c+4<r/32;
c+=4)m=k(n,a.decrypt(k(n,b.slice(c,c+4)))),l=k(l,m),q=q.concat(m),n=g(n);p=r-32*c;m=a
.encrypt(k(n,[0,0,0,p]));m=k(m,h.clamp(b.slice(c),p).concat([0,
0,0]));l=k(l,m);l=a.encrypt(k(l,k(n,g(n))));d.length&&(l=k(l,f?d:sjcl.mode.ocb2.pmac(a,d)));if(!h.equal(h.clamp(l,e),h.bitSlice
(b,r)))throw new sjcl.exception.corrupt("ocb: tag doesn't match");return q.concat(h.clamp(m,p))},pmac:function(a,
b){var c,d=sjcl.mode.ocb2.S,e=sjcl.bitArray,f=e.i,g=[0,0,0,0],h=a.encrypt([0,0,0,0]),h=f(h,d(d(h)));for(c=0;c+4<b.length;c+=4
)h=d(h),g=f(g,a.encrypt(f(h,b.slice(c,c+4))));c=b.slice(c);128>e.bitLength(c)&&(h=f(h,d(h)),c=e.concat(c,[-2147483648
,0,0,0]));g=f(g,c);
return a.encrypt(f(d(f(h,d(h))),g))},S:function(a){return[a[0]<<1^a[1]>>>31,a[1]<<1^a[2]>>>31,a[2]&
lt;<1^a[3]>>>31,a[3]<<1^135*(a[0]>>>31)]}};
sjcl.mode.gcm={name:"gcm",encrypt:function(a,b,c,d,e){var f=b.slice(0);b=sjcl.bitArray;d=d||[];a=sjcl.mode.gcm.C(!0,a,
f,d,c,e||128);return b.concat(a.data,a.tag)},decrypt:function(a,b,c,d,e){var f=b.slice(0),g=sjcl.bitArray,h=g.bitLength(f);e=e||
128;d=d||[];e<=h?(b=g.bitSlice(f,h-e),f=g.bitSlice(f,0,h-e)):(b=f,f=[]);a=sjcl.mode.gcm.C(!1,a,f,d,c,e);if(!g.equal(a.tag,b))
throw new sjcl.exception.corrupt("gcm: tag doesn't match");return a.data},ka:function(a,b){var c,d,e,f,g,h=sjcl.bitArray
.i;e=[0,0,
0,0];f=b.slice(0);for(c=0;128>c;c++){(d=0!==(a[Math.floor(c/32)]&1<<31-c%32))&&(e=h(e,f));g=0!==(f[3]&1
);for(d=3;0<d;d--)f[d]=f[d]>>>1|(f[d-1]&1)<<31;f[0]>>>=1;g&&(f[0]^=-0x1f000000)}return e},
j:function(a,b,c){var d,e=c.length;b=b.slice(0);for(d=0;d<e;d+=4)b[0]^=0xffffffff&c[d],b[1]^=0xffffffff&c[d+1],b[2]^=
0xffffffff&c[d+2],b[3]^=0xffffffff&c[d+3],b=sjcl.mode.gcm.ka(b,a);return b},C:function(a,b,c,d,e,f){var g,h,k,l,n,m,p,r,
q=sjcl.bitArray;m=c.length;p=q.bitLength(c);r=q.bitLength(d);h=q.bitLength(e);
g=b.encrypt([0,0,0,0]);96===h?(e=e.slice(0),e=q.concat(e,[1])):(e=sjcl.mode.gcm.j(g,[0,0,0,0],e),e=sjcl.mode.gcm.j(g,e,[0,0,Math
.floor(h/0x100000000),h&0xffffffff]));h=sjcl.mode.gcm.j(g,[0,0,0,0],d);n=e.slice(0);d=h.slice(0);a||(d=sjcl.mode.gcm.j(g,h,c
));for(l=0;l<m;l+=4)n[3]++,k=b.encrypt(n),c[l]^=k[0],c[l+1]^=k[1],c[l+2]^=k[2],c[l+3]^=k[3];c=q.clamp(c,p);a&&(d=sjcl
.mode.gcm.j(g,h,c));a=[Math.floor(r/0x100000000),r&0xffffffff,Math.floor(p/0x100000000),p&0xffffffff];d=sjcl.mode.gcm.j(
g,d,a);k=b.encrypt(e);
d[0]^=k[0];d[1]^=k[1];d[2]^=k[2];d[3]^=k[3];return{tag:q.bitSlice(d,0,f),data:c}}};sjcl.misc.hmac=function(a,b){this.W=b=b||sjcl
.hash.sha256;var c=[[],[]],d,e=b.prototype.blockSize/32;this.w=[new b,new b];a.length>e&&(a=b.hash(a));for(d=0;d<e
;d++)c[0][d]=a[d]^909522486,c[1][d]=a[d]^1549556828;this.w[0].update(c[0]);this.w[1].update(c[1]);this.R=new b(this.w[0])};
sjcl.misc.hmac.prototype.encrypt=sjcl.misc.hmac.prototype.mac=function(a){if(this.aa)throw new sjcl.exception.invalid("encrypt
on already updated hmac called!");this.update(a);return this.digest(a)};sjcl.misc.hmac.prototype.reset=function(){this.R=new
this.W(this.w[0]);this.aa=!1};sjcl.misc.hmac.prototype.update=function(a){this.aa=!0;this.R.update(a)};sjcl.misc.hmac.prototype
.digest=function(){var a=this.R.finalize(),a=(new this.W(this.w[1])).update(a).finalize();this.reset();return a};
...
function(a, b, c, d){var e=sjcl.json,f=e.ja.apply(e,arguments);return e.encode(f)}
...
sjcl.hash.sha256.prototype={blockSize:512,reset:function(){this.F=this.Y.slice(0);this.A=[];this.l=0;return this},update:function
(a){"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));var b,c=this.A=sjcl.bitArray.concat(this.A,a);b=this
.l;a=this.l=b+sjcl.bitArray.bitLength(a);if(0x1fffffffffffff<a)throw new sjcl.exception.invalid("Cannot hash more than 2
^53 - 1 bits");if("undefined"!==typeof Uint32Array){var d=new Uint32Array(c),e=0;for(b=512+b-(512+b&0x1ff);b&
lt;=a;b+=512)u(this,d.subarray(16*e,
16*(e+1))),e+=1;c.splice(0,16*e)}else for(b=512+b-(512+b&0x1ff);b<=a;b+=512)u(this,c.splice(0,16));return this},finalize:
function(){var a,b=this.A,c=this.F,b=sjcl.bitArray.concat(b,[sjcl.bitArray.partial(1,1)]);for(a=b.length+2;a&15;a++)b.push(0
);b.push(Math.floor(this.l/0x100000000));for(b.push(this.l|0);b.length;)u(this,b.splice(0,16));this.reset();return c},Y:[],b:[],
O:function(){function a(a){return 0x100000000*(a-Math.floor(a))|0}for(var b=0,c=2,d,e;64>b;c++){e=!0;for(d=2;d*d<=c;d++)if
(0===c%d){e=
!1;break}e&&(8>b&&(this.Y[b]=a(Math.pow(c,.5))),this.b[b]=a(Math.pow(c,1/3)),b++)}}};
function u(a,b){var c,d,e,f=a.F,g=a.b,h=f[0],k=f[1],l=f[2],n=f[3],m=f[4],p=f[5],r=f[6],q=f[7];for(c=0;64>c;c++)16>c?d=b[c]:(
d=b[c+1&15],e=b[c+14&15],d=b[c&15]=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>
;>17^e>>>19^e>>>10^e<<15^e<<13)+b[c&15]+b[c+9&15]|0),d=d+q+(m>>>6^m>>>
;11^m>>>25^m<<26^m<<21^m<<7)+(r^m&(p^r))+g[c],q=r,r=p,p=m,m=n+d|0,n=l,l=k,k=h,h=d+(k&l^n&(
k^l))+(k>>>2^k>>>13^k>>>22^k<<30^k<<19^k<<10)|0;f[0]=f[0]+h|0;f[1]=f[1]+k|0;f[2]=f[
2]+l|0;f[3]=f[3]+n|0;f[4]=f[4]+m|0;f[5]=f[5]+p|0;f[6]=f[6]+r|0;f[7]=
f[7]+q|0}
sjcl.mode.ccm={name:"ccm",G:[],listenProgress:function(a){sjcl.mode.ccm.G.push(a)},unListenProgress:function(a){a=sjcl
.mode.ccm.G.indexOf(a);-1<a&&sjcl.mode.ccm.G.splice(a,1)},fa:function(a){var b=sjcl.mode.ccm.G.slice(),c;for(c=0;c<
;b.length;c+=1)b[c](a)},encrypt:function(a,b,c,d,e){var f,g=b.slice(0),h=sjcl.bitArray,k=h.bitLength(c)/8,l=h.bitLength(g)/8;e=e
||64;d=d||[];if(7>k)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(f=2;4>f&&l&
gt;>>8*f;f++);f<15-k&&(f=15-k);c=h.clamp(c,
8*(15-f));b=sjcl.mode.ccm.V(a,b,c,d,e,f);g=sjcl.mode.ccm.C(a,g,c,b,e,f);return h.concat(g.data,g.tag)},decrypt:function(a,b,c,d,
e){e=e||64;d=d||[];var f=sjcl.bitArray,g=f.bitLength(c)/8,h=f.bitLength(b),k=f.clamp(b,h-e),l=f.bitSlice(b,h-e),h=(h-e)/8;if(7>
;g)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(b=2;4>b&&h>>>8*b;b++);
b<15-g&&(b=15-g);c=f.clamp(c,8*(15-b));k=sjcl.mode.ccm.C(a,k,c,l,e,b);a=sjcl.mode.ccm.V(a,k.data,c,d,e,b);if(!f.equal
(k.tag,a))throw new sjcl.exception.corrupt("ccm: tag doesn't match");
return k.data},na:function(a,b,c,d,e,f){var g=[],h=sjcl.bitArray,k=h.i;d=[h.partial(8,(b.length?64:0)|d-2<<2|f-1)];d=h.concat
(d,c);d[3]|=e;d=a.encrypt(d);if(b.length)for(c=h.bitLength(b)/8,65279>=c?g=[h.partial
(16,c)]:0xffffffff>=c&&(g=h.concat([h.partial(16,65534)],[c])),g=h.concat(g,b),b=0;b<g.length;b+=4)d=a.encrypt(k(d
,g.slice(b,b+4).concat([0,0,0])));return d},V:function(a,b,c,d,e,f){var g=sjcl.bitArray,h=g.i;e/=8;if(e%2||4>e||16<e)throw
new sjcl.exception.invalid("ccm: invalid tag length");
if(0xffffffff<d.length||0xffffffff<b.length)throw new sjcl.exception.bug("ccm: can't deal with 4GiB or more data
");c=sjcl.mode.ccm.na(a,d,c,e,g.bitLength(b)/8,f);for(d=0;d<b.length;d+=4)c=a.encrypt(h(c,b.slice(d,d+4).concat([0,0,0])));
return g.clamp(c,8*e)},C:function(a,b,c,d,e,f){var g,h=sjcl.bitArray;g=h.i;var k=b.length,l=h.bitLength(b),n=k/50,m=n;c=h.concat
([h.partial(8,f-1)],c).concat([0,0,0]).slice(0,4);d=h.bitSlice(g(d,a.encrypt(c)),0,e);if(!k)return{tag:d,data:[]};for(g=0;g<k
;g+=4)g>n&&(sjcl.mode.ccm.fa(g/
k),n+=m),c[3]++,e=a.encrypt(c),b[g]^=e[0],b[g+1]^=e[1],b[g+2]^=e[2],b[g+3]^=e[3];return{tag:d,data:h.clamp(b,l)}}};
sjcl.mode.ocb2={name:"ocb2",encrypt:function(a,b,c,d,e,f){if(128!==sjcl.bitArray.bitLength(c))throw new sjcl.exception
.invalid("ocb iv must be 128 bits");var g,h=sjcl.mode.ocb2.S,k=sjcl.bitArray,l=k.i,n=[0,0,0,0];c=h(a.encrypt(c));var m
,p=[];d=d||[];e=e||64;for(g=0;g+4<b.length;g+=4)m=b.slice(g,g+4),n=l(n,m),p=p.concat(l(c,a.encrypt(l(c,m)))),c=h(c);m=b.slice
(g);b=k.bitLength(m);g=a.encrypt(l(c,[0,0,0,b]));m=k.clamp(l(m.concat([0,0,0]),g),b);n=l(n,l(m.concat([0,0,0]),g));n=a.encrypt(l
(n,l(c,h(c))));
d.length&&(n=l(n,f?d:sjcl.mode.ocb2.pmac(a,d)));return p.concat(k.concat(m,k.clamp(n,e)))},decrypt:function(a,b,c,d,e,f){
if(128!==sjcl.bitArray.bitLength(c))throw new sjcl.exception.invalid("ocb iv must be 128 bits");e=e||64;var g=sjcl.mode
.ocb2.S,h=sjcl.bitArray,k=h.i,l=[0,0,0,0],n=g(a.encrypt(c)),m,p,r=sjcl.bitArray.bitLength(b)-e,q=[];d=d||[];for(c=0;c+4<r/32;
c+=4)m=k(n,a.decrypt(k(n,b.slice(c,c+4)))),l=k(l,m),q=q.concat(m),n=g(n);p=r-32*c;m=a.encrypt(k(n,[0,0,0,p]));m=k(m,h.clamp(b.slice
(c),p).concat([0,
0,0]));l=k(l,m);l=a.encrypt(k(l,k(n,g(n))));d.length&&(l=k(l,f?d:sjcl.mode.ocb2.pmac(a,d)));if(!h.equal(h.clamp(l,e),h.bitSlice
(b,r)))throw new sjcl.exception.corrupt("ocb: tag doesn't match");return q.concat(h.clamp(m,p))},pmac:function(a,
b){var c,d=sjcl.mode.ocb2.S,e=sjcl.bitArray,f=e.i,g=[0,0,0,0],h=a.encrypt([0,0,0,0]),h=f(h,d(d(h)));for(c=0;c+4<b.length;c+=4
)h=d(h),g=f(g,a.encrypt(f(h,b.slice(c,c+4))));c=b.slice(c);128>e.bitLength(c)&&(h=f(h,d(h)),c=e.concat(c,[-2147483648
,0,0,0]));g=f(g,c);
return a.encrypt(f(d(f(h,d(h))),g))},S:function(a){return[a[0]<<1^a[1]>>>31,a[1]<<1^a[2]>>>31,a[2]&
lt;<1^a[3]>>>31,a[3]<<1^135*(a[0]>>>31)]}};
sjcl.mode.gcm={name:"gcm",encrypt:function(a,b,c,d,e){var f=b.slice(0);b=sjcl.bitArray;d=d||[];a=sjcl.mode.gcm.C(!0,a,
f,d,c,e||128);return b.concat(a.data,a.tag)},decrypt:function(a,b,c,d,e){var f=b.slice(0),g=sjcl.bitArray,h=g.bitLength(f);e=e||
128;d=d||[];e<=h?(b=g.bitSlice(f,h-e),f=g.bitSlice(f,0,h-e)):(b=f,f=[]);a=sjcl.mode.gcm.C(!1,a,f,d,c,e);if(!g.equal(a.tag,b))
throw new sjcl.exception.corrupt("gcm: tag doesn't match");return a.data},ka:function(a,b){var c,d,e,f,g,h=sjcl.bitArray
.i;e=[0,0,
...
function(a){this.c=[new sjcl.hash.sha256];this.m=[0];this.P=0;this.H={};this.N=0;this.U={};this.Z=this.f=this.o=this.ha=0;this.b =[0,0,0,0,0,0,0,0];this.h=[0,0,0,0];this.L=void 0;this.M=a;this.D=!1;this.K={progress:{},seeded:{}};this.u=this.ga=0;this.I=1;this .J=2;this.ca=0x10000;this.T=[0,48,64,96,128,192,0x100,384,512,768,1024];this.da=3E4;this.ba=80}
...
(k=1);if(!k){if(void 0===b)for(c=b=0;c<a.length;c++)for(e=a[c];0<e;)b++,e=e>>>1;this.c[g].update([d,this.N++,2,b,
f,a.length].concat(a))}break;case "string":void 0===b&&(b=a.length);this.c[g].update([d,this.N++,3,b,f,a.length
]);this.c[g].update(a);break;default:k=1}if(k)throw new sjcl.exception.bug("random: addEntropy only supports number, array
of numbers or string");this.m[g]+=b;this.f+=b;h===this.u&&(this.isReady()!==this.u&&A("seeded",Math
.max(this.o,this.f)),A("progress",this.getProgress()))},
isReady:function(a){a=this.T[void 0!==a?a:this.M];return this.o&&this.o>=a?this.m[0]>this.ba&&(new Date).valueOf
()>this.Z?this.J|this.I:this.I:this.f>=a?this.J|this.u:this.u},getProgress:function(a){a=this.T[a?a:this.M];return this.o&
gt;=a?1:this.f>a?1:this.f/a},startCollectors:function(){if(!this.D){this.a={loadTimeCollector:B(this,this.ma),mouseCollector:
B(this,this.oa),keyboardCollector:B(this,this.la),accelerometerCollector:B(this,this.ea),touchCollector:B(this,this.qa)};if(window
.addEventListener)window.addEventListener("load",
this.a.loadTimeCollector,!1),window.addEventListener("mousemove",this.a.mouseCollector,!1),window.addEventListener("
;keypress",this.a.keyboardCollector,!1),window.addEventListener("devicemotion",this.a.accelerometerCollector,!1),
window.addEventListener("touchmove",this.a.touchCollector,!1);else if(document.attachEvent)document.attachEvent("
onload",this.a.loadTimeCollector),document.attachEvent("onmousemove",this.a.mouseCollector),document.attachEvent(&
quot;keypress",this.a.keyboardCollector);else throw new sjcl.exception.bug("can't attach event");
this.D=!0}},stopCollectors:function(){this.D&&(window.removeEventListener?(window.removeEventListener("load",this
.a.loadTimeCollector,!1),window.removeEventListener("mousemove",this.a.mouseCollector,!1),window.removeEventListener(&
quot;keypress",this.a.keyboardCollector,!1),window.removeEventListener("devicemotion",this.a.accelerometerCollector
,!1),window.removeEventListener("touchmove",this.a.touchCollector,!1)):document.detachEvent&&(document.detachEvent
("onload",this.a.loadTimeCollector),document.detachEvent("onmousemove",
this.a.mouseCollector),document.detachEvent("keypress",this.a.keyboardCollector)),this.D=!1)},addEventListener:function
(a,b){this.K[a][this.ga++]=b},removeEventListener:function(a,b){var c,d,e=this.K[a],f=[];for(d in e)e.hasOwnProperty(d)&&
;e[d]===b&&f.push(d);for(c=0;c<f.length;c++)d=f[c],delete e[d]},la:function(){C(this,1)},oa:function(a){var b,c;try{b
=a.x||a.clientX||a.offsetX||0,c=a.y||a.clientY||a.offsetY||0}catch(d){c=b=0}0!=b&&0!=c&&this.addEntropy([b,c],2,&
quot;mouse");C(this,0)},qa:function(a){a=
a.touches[0]||a.changedTouches[0];this.addEntropy([a.pageX||a.clientX,a.pageY||a.clientY],1,"touch");C(this,0)},ma:function
(){C(this,2)},ea:function(a){a=a.accelerationIncludingGravity.x||a.accelerationIncludingGravity.y||a.accelerationIncludingGravity
.z;if(window.orientation){var b=window.orientation;"number"===typeof b&&this.addEntropy(b,1,"accelerometer
")}a&&this.addEntropy(a,2,"accelerometer");C(this,0)}};
function A(a,b){var c,d=sjcl.random.K[a],e=[];for(c in d)d.hasOwnProperty(c)&&e.push(d[c]);for(c=0;c<e.length;c++)e[c
](b)}function C(a,b){"undefined"!==typeof window&&window.performance&&"function"===typeof window
.performance.now?a.addEntropy(window.performance.now(),b,"loadtime"):a.addEntropy((new Date).valueOf(),b,"loadtime
")}function y(a){a.b=z(a).concat(z(a));a.L=new sjcl.cipher.aes(a.b)}function z(a){for(var b=0;4>b&&(a.h[b]=a.h[b
]+1|0,!a.h[b]);b++);return a.L.encrypt(a.h)}
function B(a,b){return function(){b.apply(a,arguments)}}sjcl.random=new sjcl.prng(6);
a:try{var D,E,F,G;if(G="undefined"!==typeof module&&module.exports){var H;try{H=require("crypto")}catch
(a){H=null}G=E=H}if(G&&E.randomBytes)D=E.randomBytes(128),D=new Uint32Array((new Uint8Array(D)).buffer),sjcl.random.addEntropy
(D,1024,"crypto['randomBytes']");else if("undefined"!==typeof window&&"undefined"
;!==typeof Uint32Array){F=new Uint32Array(32);if(window.crypto&&window.crypto.getRandomValues)window.crypto.getRandomValues
(F);else if(window.msCrypto&&window.msCrypto.getRandomValues)window.msCrypto.getRandomValues(F);
else break a;sjcl.random.addEntropy(F,1024,"crypto['getRandomValues']")}}catch(a){"undefined"!==typeof
window&&window.console&&(console.log("There was an error collecting entropy from the browser:"),console
.log(a))}
sjcl.json={defaults:{v:1,iter:1E4,ks:128,ts:64,mode:"ccm",adata:"",cipher:"aes"},ja:function(a,b,c
,d){c=c||{};d=d||{};var e=sjcl.json,f=e.g({iv:sjcl.random.randomWords(4,0)},e.defaults),g;e.g(f,c);c=f.adata;"string"===
typeof f.salt&&(f.salt=sjcl.codec.base64.toBits(f.salt));"string"===typeof f.iv&&(f.iv=sjcl.codec.base64
.toBits(f.iv));if(!sjcl.mode[f.mode]||!sjcl.cipher[f.cipher]||"string"===typeof a&&100>=f.iter||64!==f.ts&
;&96!==f.ts&&128!==f.ts||128!==f.ks&&192!==f.ks&&0x100!==f.ks||2>f.iv.length||
4<f.iv.length)throw new sjcl.exception.invalid("json encrypt: invalid parameters");"string"===typeof a?(g
=sjcl.misc.cachedPbkdf2(a,f),a=g.key.slice(0,f.ks/32),f.salt=g.salt):sjcl.ecc&&a instanceof sjcl.ecc.elGamal.publicKey&
;&(g=a.kem(),f.kemtag=g.tag,a=g.key.slice(0,f.ks/32));"string"===typeof b&&(b=sjcl.codec.utf8String.toBits
(b));"string"===typeof c&&(f.adata=c=sjcl.codec.utf8String.toBits(c));g=new sjcl.cipher[f.cipher](a);e.g(d,f);
d.key=a;f.ct="ccm"===f.mode&&sjcl.arrayBuffer&&sjcl.arrayBuffer.ccm&&
b instanceof ArrayBuffer?sjcl.arrayBuffer.ccm.encrypt(g,b,f.iv,c,f.ts):sjcl.mode[f.mode].encrypt(g,b,f.iv,c,f.ts);return f},encrypt
:function(a,b,c,d){var e=sjcl.json,f=e.ja.apply(e,arguments);return e.encode(f)},ia:function(a,b,c,d){c=c||{};d=d||{};var e=sjcl
.json;b=e.g(e.g(e.g({},e.defaults),b),c,!0);var f,g;f=b.adata;"string"===typeof b.salt&&(b.salt=sjcl.codec.base64
.toBits(b.salt));"string"===typeof b.iv&&(b.iv=sjcl.codec.base64.toBits(b.iv));if(!sjcl.mode[b.mode]||!sjcl.cipher
[b.cipher]||"string"===
typeof a&&100>=b.iter||64!==b.ts&&96!==b.ts&&128!==b.ts||128!==b.ks&&192!==b.ks&&0x100
!==b.ks||!b.iv||2>b.iv.length||4<b.iv.length)throw new sjcl.exception.invalid("json decrypt: invalid parameters");&
quot;string"===typeof a?(g=sjcl.misc.cachedPbkdf2(a,b),a=g.key.slice(0,b.ks/32),b.salt=g.salt):sjcl.ecc&&a instanceof
sjcl.ecc.elGamal.secretKey&&(a=a.unkem(sjcl.codec.base64.toBits(b.kemtag)).slice(0,b.ks/32));"string"===typeof
f&&(f=sjcl.codec.utf8String.toBits(f));g=new sjcl.cipher[b.cipher](a);f="ccm"===
b.mode&&sjcl.arrayBuffer&&sjcl.arrayBuffer.ccm&&b.ct instanceof ArrayBuffer?sjcl.arrayBuffer.ccm.decrypt
(g,b.ct,b.iv,b.tag,f,b.ts):sjcl.mode[b.mode].decrypt(g,b.ct,b.iv,f,b.ts);e.g(d,b);d.key=a;return 1===c.raw?f:sjcl.codec.utf8String
.fromBits(f)},decrypt:function(a,b,c,d){var e=sjcl.json;return e.ia(a,e.decode(b),c,d)},encode:function(a){var b,c="{",
d="";for(b in a)if(a.hasOwnProperty(b)){if(!b.match(/^[a-z0-9]+$/i))throw new sjcl.exception.invalid("json encode
: invalid property name");c+=d+'"'+
...
function(a){var b=a.length;return 0=== b?0:32*(b-1)+sjcl.bitArray.getPartial(a[b-1])}
...
sjcl.cipher.aes=function(a){this.s[0][0][0]||this.O();var b,c,d,e,f=this.s[0][4],g=this.s[1];b=a.length;var h=1;if(4!==b&&
;6!==b&&8!==b)throw new sjcl.exception.invalid("invalid aes key size");this.b=[d=a.slice(0),e=[]];for(a=b;a<
;4*b+28;a++){c=d[a-1];if(0===a%b||8===b&&4===a%b)c=f[c>>>24]<<24^f[c>>16&255]<<16^f[c>&
gt;8&255]<<8^f[c&255],0===a%b&&(c=c<<8^c>>>24^h<<24,h=h<<1^283*(h>>7));d[
a]=d[a-b]^c}for(b=0;a;b++,a--)c=d[b&3?a:a-4],e[b]=4>=a||4>b?c:g[0][f[c>>>24]]^g[1][f[c>>16&255]]^g[
2][f[c>>8&255]]^g[3][f[c&
255]]};
sjcl.cipher.aes.prototype={encrypt:function(a){return t(this,a,0)},decrypt:function(a){return t(this,a,1)},s:[[[],[],[],[],[]],[[],[],[],[],[]]],
O:function(){var a=this.s[0],b=this.s[1],c=a[4],d=b[4],e,f,g,h=[],k=[],l,n,m,p;for(e=0;0x100>e;e++)k[(h[e]=e<<1^283*(e&
gt;>7))^e]=e;for(f=g=0;!c[f];f^=l||1,g=k[g]||1)for(m=g^g<<1^g<<2^g<<3^g<<4,m=m>>8^m&255^99,
c[f]=m,d[m]=f,n=h[e=h[l=h[f]]],p=0x1010101*n^0x10001*e^0x101*l^0x1010100*f,n=0x101*h[m]^0x1010100*m,e=0;4>e;e++)a[e][f]=n=n<
;<24^n>>>8,b[e][m]=p=p<<24^p>>>8;for(e=
0;5>e;e++)a[e]=a[e].slice(0),b[e]=b[e].slice(0)}};
function t(a,b,c){if(4!==b.length)throw new sjcl.exception.invalid("invalid aes block size");var d=a.b[c],e=b[0]^d[0],
f=b[c?3:1]^d[1],g=b[2]^d[2];b=b[c?1:3]^d[3];var h,k,l,n=d.length/4-2,m,p=4,r=[0,0,0,0];h=a.s[c];a=h[0];var q=h[1],v=h[2],w=h[3],
x=h[4];for(m=0;m<n;m++)h=a[e>>>24]^q[f>>16&255]^v[g>>8&255]^w[b&255]^d[p],k=a[f>>>24
]^q[g>>16&255]^v[b>>8&255]^w[e&255]^d[p+1],l=a[g>>>24]^q[b>>16&255]^v[e>>8&
255]^w[f&255]^d[p+2],b=a[b>>>24]^q[e>>16&255]^v[f>>8&255]^w[g&255]^d[p+3],p+=4,e=h,f=k,g=l;
for(m=
0;4>m;m++)r[c?3&-m:m]=x[e>>>24]<<24^x[f>>16&255]<<16^x[g>>8&255]<<8^x[b&
;255]^d[p++],h=e,e=f,f=g,g=b,b=h;return r}
sjcl.bitArray={bitSlice:function(a,b,c){a=sjcl.bitArray.$(a.slice(b/32),32-(b&31)).slice(1);return void 0===c?a:sjcl.bitArray
.clamp(a,c-b)},extract:function(a,b,c){var d=Math.floor(-b-c&31);return((b+c-1^b)&-32?a[b/32|0]<<32-d^a[b/32+1|0]&
gt;>>d:a[b/32|0]>>>d)&(1<<c)-1},concat:function(a,b){if(0===a.length||0===b.length)return a.concat(b);var
c=a[a.length-1],d=sjcl.bitArray.getPartial(c);return 32===d?a.concat(b):sjcl.bitArray.$(b,d,c|0,a.slice(0,a.length-1))},bitLength
:function(a){var b=a.length;return 0===
b?0:32*(b-1)+sjcl.bitArray.getPartial(a[b-1])},clamp:function(a,b){if(32*a.length<b)return a;a=a.slice(0,Math.ceil(b/32));var
c=a.length;b=b&31;0<c&&b&&(a[c-1]=sjcl.bitArray.partial(b,a[c-1]&2147483648>>b-1,1));return a},
partial:function(a,b,c){return 32===a?b:(c?b|0:b<<32-a)+0x10000000000*a},getPartial:function(a){return Math.round(a/0x10000000000
)||32},equal:function(a,b){if(sjcl.bitArray.bitLength(a)!==sjcl.bitArray.bitLength(b))
return!1;var c=0,d;for(d=0;d<a.length;d++)c|=a[d]^b[d];return 0===
c},$:function(a,b,c,d){var e;e=0;for(void 0===d&&(d=[]);32<=b;b-=32)d.push(c),c=0;if(0===b)return d.concat(a);for(e=0
;e<a.length;e++)d.push(c|a[e]>>>b),c=a[e]<<32-b;e=a.length?a[a.length-1]:0;a=sjcl.bitArray.getPartial(e);d.push
(sjcl.bitArray.partial(b+a&31,32<b+a?c:d.pop(),1));return d},i:function(a,b){return[a[0]^b[0],a[1]^b[1],a[2]^b[2],a[3]^b[
3]]},byteswapM:function(a){var b,c;for(b=0;b<a.length;++b)c=a[b],a[b]=c>>>24|c>>>8&0xff00|(c&0xff00
)<<8|c<<24;return a}};
sjcl.codec.utf8String={fromBits:function(a){var b="",c=sjcl.bitArray.bitLength(a),d,e;for(d=0;d<c/8;d++)0===(d&
3)&&(e=a[d/4]),b+=String.fromCharCode(e>>>8>>>8>>>8),e<<=8;return decodeURIComponent(escape
(b))},toBits:function(a){a=unescape(encodeURIComponent(a));var b=[],c,d=0;for(c=0;c<a.length;c++)d=d<<8|a.charCodeAt(c),
3===(c&3)&&(b.push(d),d=0);c&3&&b.push(sjcl.bitArray.partial(8*(c&3),d));return b}};
sjcl.codec.hex={fromBits:function(a){var b="",c;for(c=0;c<a.length;c++)b+=((a[c]|0)+0xf00000000000).toString(16).substr
(4);return b.substr(0,sjcl.bitArray.bitLength(a)/4)},toBits:function(a){var b,c=[],d;a=a.replace(/\s|0x/g,"");d=a.length;a=a+"00000000";for(b=0;b<a.length;b+=8)c.push(parseInt(a.substr(b,8),16)^0);return sjcl.bitArray.clamp(c,4*d)}};
sjcl.codec.base32={B:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",X:"0123456789ABCDEFGHIJKLMNOPQRSTUV",BITS:32,BASE:5,
REMAINING:27,fromBits:function(a,b,c){var d=sjcl.codec.base32.BASE,e=sjcl.codec.base32.REMAINING,f="",g=0,h=sjcl.codec
.base32.B,k=0,l=sjcl.bitArray.bitLength(a);c&&(h=sjcl.codec.base32.X);for(c=0;f.length*d<l;)f+=h.charAt((k^a[c]>>
;>g)>>>e),g<d?(k=a[c]<<d-g,g+=e,c++):(k<<=d,g-=d);for(;f.length&7&&!b;)f+="=";return
f},toBits:function(a,b){a=a.replace(/\s|=/g,"").toUpperCase();var c=sjcl.codec.base32.BITS,
d=sjcl.codec.base32.BASE,e=sjcl.codec.base32.REMAINING,f=[],g,h=0,k=sjcl.codec.base32.B,l=0,n,m="base32";b&&(k
=sjcl.codec.base32.X,m="base32hex");for(g=0;g<a.length;g++){n=k.indexOf(a.charAt(g));if(0>n){if(!b)try{return sjcl
.codec.base32hex.toBits(a)}catch(p){}throw new sjcl.exception.invalid("this isn't "+m+"!");}h>e?(h-=
e,f.push(l^n>>>h),l=n<<c-h):(h+=d,l^=n<<c-h)}h&56&&f.push(sjcl.bitArray.partial(h&56,l,1));
return f}};
sjcl.codec.base32hex={fromBits:function(a,b){return sjcl.codec.base32.fromBits(a,b,1)},toBits:function(a){return sjcl.codec.base32
.toBits(a,1)}};
sjcl.codec.base64={B:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",fromBits:function(a,b,c){var d
="",e=0,f=sjcl.codec.base64.B,g=0,h=sjcl.bitArray.bitLength(a);c&&(f=f.substr(0,62)+"-_");for(c=0;6*
d.length<h;)d+=f.charAt((g^a[c]>>>e)>>>26),6>e?(g=a[c]<<6-e,e+=26,c++):(g<<=6,e-=6);for(;d.length
&3&&!b;)d+="=";return d},toBits:function(a,b){a=a.replace(/\s|=/g,"");var c=[],d,e=0,f=sjcl.codec.base64.B,g=0,h;b&&(f=f.substr(0,62)+"-_");for(d=0;d<a.length;d++){h=f.indexOf(a.charAt(d));
...
function(a, b, c){a=sjcl.bitArray.$(a.slice(b/32),32-(b&31)).slice(1);return void 0===c?a:sjcl.bitArray.clamp(a,c-b)}
...
if(0>h)throw new sjcl.exception.invalid("this isn't base64!");26<e?(e-=26,c.push(g^h>>>e),g=h<&
lt;32-e):(e+=6,g^=h<<32-e)}e&56&&c.push(sjcl.bitArray.partial(e&56,g,1));return c}};sjcl.codec.base64url={
fromBits:function(a){return sjcl.codec.base64.fromBits(a,1,1)},toBits:function(a){return sjcl.codec.base64.toBits(a,1)}};sjcl.hash
.sha256=function(a){this.b[0]||this.O();a?(this.F=a.F.slice(0),this.A=a.A.slice(0),this.l=a.l):this.reset()};sjcl.hash.sha256.hash
=function(a){return(new sjcl.hash.sha256).update(a).finalize()};
sjcl.hash.sha256.prototype={blockSize:512,reset:function(){this.F=this.Y.slice(0);this.A=[];this.l=0;return this},update:function
(a){"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));var b,c=this.A=sjcl.bitArray.concat(this.A,a);b=this
.l;a=this.l=b+sjcl.bitArray.bitLength(a);if(0x1fffffffffffff<a)throw new sjcl.exception.invalid("Cannot hash more than 2
^53 - 1 bits");if("undefined"!==typeof Uint32Array){var d=new Uint32Array(c),e=0;for(b=512+b-(512+b&0x1ff);b&
lt;=a;b+=512)u(this,d.subarray(16*e,
16*(e+1))),e+=1;c.splice(0,16*e)}else for(b=512+b-(512+b&0x1ff);b<=a;b+=512)u(this,c.splice(0,16));return this},finalize:
function(){var a,b=this.A,c=this.F,b=sjcl.bitArray.concat(b,[sjcl.bitArray.partial(1,1)]);for(a=b.length+2;a&15;a++)b.push(0
);b.push(Math.floor(this.l/0x100000000));for(b.push(this.l|0);b.length;)u(this,b.splice(0,16));this.reset();return c},Y:[],b:[],
O:function(){function a(a){return 0x100000000*(a-Math.floor(a))|0}for(var b=0,c=2,d,e;64>b;c++){e=!0;for(d=2;d*d<=c;d++)if
(0===c%d){e=
!1;break}e&&(8>b&&(this.Y[b]=a(Math.pow(c,.5))),this.b[b]=a(Math.pow(c,1/3)),b++)}}};
function u(a,b){var c,d,e,f=a.F,g=a.b,h=f[0],k=f[1],l=f[2],n=f[3],m=f[4],p=f[5],r=f[6],q=f[7];for(c=0;64>c;c++)16>c?d=b[c]:(
d=b[c+1&15],e=b[c+14&15],d=b[c&15]=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>
;>17^e>>>19^e>>>10^e<<15^e<<13)+b[c&15]+b[c+9&15]|0),d=d+q+(m>>>6^m>>>
;11^m>>>25^m<<26^m<<21^m<<7)+(r^m&(p^r))+g[c],q=r,r=p,p=m,m=n+d|0,n=l,l=k,k=h,h=d+(k&l^n&(
k^l))+(k>>>2^k>>>13^k>>>22^k<<30^k<<19^k<<10)|0;f[0]=f[0]+h|0;f[1]=f[1]+k|0;f[2]=f[
2]+l|0;f[3]=f[3]+n|0;f[4]=f[4]+m|0;f[5]=f[5]+p|0;f[6]=f[6]+r|0;f[7]=
f[7]+q|0}
sjcl.mode.ccm={name:"ccm",G:[],listenProgress:function(a){sjcl.mode.ccm.G.push(a)},unListenProgress:function(a){a=sjcl
.mode.ccm.G.indexOf(a);-1<a&&sjcl.mode.ccm.G.splice(a,1)},fa:function(a){var b=sjcl.mode.ccm.G.slice(),c;for(c=0;c<
;b.length;c+=1)b[c](a)},encrypt:function(a,b,c,d,e){var f,g=b.slice(0),h=sjcl.bitArray,k=h.bitLength(c)/8,l=h.bitLength(g)/8;e=e
||64;d=d||[];if(7>k)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(f=2;4>f&&l&
gt;>>8*f;f++);f<15-k&&(f=15-k);c=h.clamp(c,
8*(15-f));b=sjcl.mode.ccm.V(a,b,c,d,e,f);g=sjcl.mode.ccm.C(a,g,c,b,e,f);return h.concat(g.data,g.tag)},decrypt:function(a,b,c,d,
e){e=e||64;d=d||[];var f=sjcl.bitArray,g=f.bitLength(c)/8,h=f.bitLength(b),k=f.clamp(b,h-e),l=f.bitSlice(b,h-e),h=(h-e)/8;if(7>g)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(
b=2;4>b&&h>>>8*b;b++);b<15-g&&(b=15-g);c=f.clamp(c,8*(15-b));k=sjcl.mode.ccm.C(a,k,c,l,e,b);a=sjcl
.mode.ccm.V(a,k.data,c,d,e,b);if(!f.equal(k.tag,a))throw new sjcl.exception.corrupt("ccm: tag doesn't match");
return k.data},na:function(a,b,c,d,e,f){var g=[],h=sjcl.bitArray,k=h.i;d=[h.partial(8,(b.length?64:0)|d-2<<2|f-1)];d=h.concat
(d,c);d[3]|=e;d=a.encrypt(d);if(b.length)for(c=h.bitLength(b)/8,65279>=c?g=[h.partial(16,c)]:0xffffffff>=c&&(g=h.concat
([h.partial(16,65534)],[c])),g=h.concat(g,b),b=0;b<g.length;b+=4)d=a.encrypt(k(d,g.slice(b,b+4).concat([0,0,0])));return d},V
:function(a,b,c,d,e,f){var g=sjcl.bitArray,h=g.i;e/=8;if(e%2||4>e||16<e)throw new sjcl.exception.invalid("ccm: invalid
tag length");
if(0xffffffff<d.length||0xffffffff<b.length)throw new sjcl.exception.bug("ccm: can't deal with 4GiB or more data
");c=sjcl.mode.ccm.na(a,d,c,e,g.bitLength(b)/8,f);for(d=0;d<b.length;d+=4)c=a.encrypt(h(c,b.slice(d,d+4).concat([0,0,0])));
return g.clamp(c,8*e)},C:function(a,b,c,d,e,f){var g,h=sjcl.bitArray;g=h.i;var k=b.length,l=h.bitLength(b),n=k/50,m=n;c=h.concat
([h.partial(8,f-1)],c).concat([0,0,0]).slice(0,4);d=h.bitSlice(g(d,a.encrypt(c)),0,e);if(!k)return{tag:d,data:[]};for(g=0;g<k
;g+=4)g>n&&(sjcl.mode.ccm.fa(g/
k),n+=m),c[3]++,e=a.encrypt(c),b[g]^=e[0],b[g+1]^=e[1],b[g+2]^=e[2],b[g+3]^=e[3];return{tag:d,data:h.clamp(b,l)}}};
sjcl.mode.ocb2={name:"ocb2",encrypt:function(a,b,c,d,e,f){if(128!==sjcl.bitArray.bitLength(c))throw new sjcl.exception
.invalid("ocb iv must be 128 bits");var g,h=sjcl.mode.ocb2.S,k=sjcl.bitArray,l=k.i,n=[0,0,0,0];c=h(a.encrypt(c));var m
,p=[];d=d||[];e=e||64;for(g=0;g+4<b.length;g+=4)m=b.slice(g,g+4),n=l(n,m),p=p.concat(l(c,a.encrypt(l(c,m)))),c=h(c);m=b.slice
(g);b=k.bitLength(m);g=a.encrypt(l(c,[0,0,0,b]));m=k.clamp(l(m.concat([0,0,0]),g),b);n=l(n,l(m.concat([0,0,0]),g));n=a.encrypt(l
(n,l(c,h(c))));
d.length&&(n=l(n,f?d:sjcl.mode.ocb2.pmac(a,d)));return p.concat(k.concat(m,k.clamp(n,e)))},decrypt:function(a,b,c,d,e,f){
if(128!==sjcl.bitArray.bitLength(c))throw new sjcl.exception.invalid("ocb iv must be 128 bits");e=e||64;var g=sjcl.mode
.ocb2.S,h=sjcl.bitArray,k=h.i,l=[0,0,0,0],n=g(a.encrypt(c)),m,p,r=sjcl.bitArray.bitLength(b)-e,q=[];d=d||[];for(c=0;c+4<r/32;
c+=4)m=k(n,a.decrypt(k(n,b.slice(c,c+4)))),l=k(l,m),q=q.concat(m),n=g(n);p=r-32*c;m=a.encrypt(k(n,[0,0,0,p]));m=k(m,h.clamp(b.slice
(c),p).concat([0,
0,0]));l=k(l,m);l=a.encrypt(k(l,k(n,g(n))));d.length&&(l=k(l,f?d:sjcl.mode.ocb2.pmac(a,d)));if(!h.equal(h.clamp(l,e),h.bitSlice
(b,r)))throw new sjcl.exception.corrupt("ocb: tag doesn't match");return q.concat(h.clamp(m,p))},pmac:function(a,
b){var c,d=sjcl.mode.ocb2.S,e=sjcl.bitArray,f=e.i,g=[0,0,0,0],h=a.encrypt([0,0,0,0]),h=f(h,d(d(h)));for(c=0;c+4<b.length;c+=4
)h=d(h),g=f(g,a.encrypt(f(h,b.slice(c,c+4))));c=b.slice(c);128>e.bitLength(c)&&(h=f(h,d(h)),c=e.concat(c,[-2147483648
,0,0,0]));g=f(g,c);
return a.encrypt(f(d(f(h,d(h))),g))},S:function(a){return[a[0]<<1^a[1]>>>31,a[1]<<1^a[2]>>>31,a[2]&
lt;<1^a[3]>>>31,a[3]<<1^135*(a[0]>>>31)]}};
...
function(a){var b,c;for(b=0;b<a.length;++b)c=a[b],a[b]=c>>>24|c>>>8&0xff00|(c&0xff00)<<8|c<<24;return a}
n/a
function(a, b){if(32*a.length<b)return a;a=a.slice(0,Math.ceil(b/32));var c=a.length;b=b&31;0<c&&b&&(a[c-1]=sjcl.bitArray.partial (b,a[c-1]&2147483648>>b-1,1));return a}
...
"use strict";var sjcl={cipher:{},hash:{},keyexchange:{},mode:{},misc:{},codec:{},exception:{corrupt:function(a){this.toString
=function(){return"CORRUPT: "+this.message};this.message=a},invalid:function(a){this.toString=function(){return"INVALID
: "+this.message};this.message=a},bug:function(a){this.toString=function(){return"BUG: "+this.message};this.message
=a},notReady:function(a){this.toString=function(){return"NOT READY: "+this.message};this.message=a}}};
sjcl.cipher.aes=function(a){this.s[0][0][0]||this.O();var b,c,d,e,f=this.s[0][4],g=this.s[1];b=a.length;var h=1;if(4!==b&&
;6!==b&&8!==b)throw new sjcl.exception.invalid("invalid aes key size");this.b=[d=a.slice(0),e=[]];for(a=b;a<
;4*b+28;a++){c=d[a-1];if(0===a%b||8===b&&4===a%b)c=f[c>>>24]<<24^f[c>>16&255]<<16^f[c>&
gt;8&255]<<8^f[c&255],0===a%b&&(c=c<<8^c>>>24^h<<24,h=h<<1^283*(h>>7));d[
a]=d[a-b]^c}for(b=0;a;b++,a--)c=d[b&3?a:a-4],e[b]=4>=a||4>b?c:g[0][f[c>>>24]]^g[1][f[c>>16&255]]^g[
2][f[c>>8&255]]^g[3][f[c&
255]]};
sjcl.cipher.aes.prototype={encrypt:function(a){return t(this,a,0)},decrypt:function(a){return t(this,a,1)},s:[[[],[],[],[],[]],[[],[],[],[],[]]],
O:function(){var a=this.s[0],b=this.s[1],c=a[4],d=b[4],e,f,g,h=[],k=[],l,n,m,p;for(e=0;0x100>e;e++)k[(h[e]=e<<1^283*(e&
gt;>7))^e]=e;for(f=g=0;!c[f];f^=l||1,g=k[g]||1)for(m=g^g<<1^g<<2^g<<3^g<<4,m=m>>8^m&255^99,
c[f]=m,d[m]=f,n=h[e=h[l=h[f]]],p=0x1010101*n^0x10001*e^0x101*l^0x1010100*f,n=0x101*h[m]^0x1010100*m,e=0;4>e;e++)a[e][f]=n=n<
;<24^n>>>8,b[e][m]=p=p<<24^p>>>8;for(e=
0;5>e;e++)a[e]=a[e].slice(0),b[e]=b[e].slice(0)}};
function t(a,b,c){if(4!==b.length)throw new sjcl.exception.invalid("invalid aes block size");var d=a.b[c],e=b[0]^d[0],
f=b[c?3:1]^d[1],g=b[2]^d[2];b=b[c?1:3]^d[3];var h,k,l,n=d.length/4-2,m,p=4,r=[0,0,0,0];h=a.s[c];a=h[0];var q=h[1],v=h[2],w=h[3],
x=h[4];for(m=0;m<n;m++)h=a[e>>>24]^q[f>>16&255]^v[g>>8&255]^w[b&255]^d[p],k=a[f>>>24
]^q[g>>16&255]^v[b>>8&255]^w[e&255]^d[p+1],l=a[g>>>24]^q[b>>16&255]^v[e>>8&
255]^w[f&255]^d[p+2],b=a[b>>>24]^q[e>>16&255]^v[f>>8&255]^w[g&255]^d[p+3],p+=4,e=h,f=k,g=l;
for(m=
0;4>m;m++)r[c?3&-m:m]=x[e>>>24]<<24^x[f>>16&255]<<16^x[g>>8&255]<<8^x[b&
;255]^d[p++],h=e,e=f,f=g,g=b,b=h;return r}
sjcl.bitArray={bitSlice:function(a,b,c){a=sjcl.bitArray.$(a.slice(b/32),32-(b&31)).slice(1);return void 0===c?a:sjcl.bitArray
.clamp(a,c-b)},extract:function(a,b,c){var d=Math.floor(-b-c&31);return((b+c-1^b)&
amp;-32?a[b/32|0]<<32-d^a[b/32+1|0]>>>d:a[b/32|0]>>>d)&(1<<c)-1},concat:function(a,b){if(0===a
.length||0===b.length)return a.concat(b);var c=a[a.length-1],d=sjcl.bitArray.getPartial(c);return 32===d?a.concat(b):sjcl.bitArray
.$(b,d,c|0,a.slice(0,a.length-1))},bitLength:function(a){var b=a.length;return 0===
b?0:32*(b-1)+sjcl.bitArray.getPartial(a[b-1])},clamp:function(a,b){if(32*a.length<b)return a;a=a.slice(0,Math.ceil(b/32));var
c=a.length;b=b&31;0<c&&b&&(a[c-1]=sjcl.bitArray.partial(b,a[c-1]&2147483648>>b-1,1));return a},
partial:function(a,b,c){return 32===a?b:(c?b|0:b<<32-a)+0x10000000000*a},getPartial:function(a){return Math.round(a/0x10000000000
)||32},equal:function(a,b){if(sjcl.bitArray.bitLength(a)!==sjcl.bitArray.bitLength(b))return!1;var c=0,d;for(d=0;d<a.length;d
++)c|=a[d]^b[d];return 0===
c},$:function(a,b,c,d){var e;e=0;for(void 0===d&&(d=[]);32<=b;b-=32)d.push(c),c=0;if(0===b)return d.concat(a);for(e=0
;e<a.length;e++)d.push(c|a[e]>>>b),c=a[e]<<32-b;e=a.length?a[a.length-1]:0;a=sjcl.bitArray.getPartial(e);d.push
(sjcl.bitArray.partial(b+a&31,32<b+a?c:d.pop(),1));return d},i:function(a,b){return[a[0]^b[0],a[1]^b[1],a[2]^b[2],a[3]^b[
3]]},byteswapM:function(a){var b,c;for(b=0;b<a.length;++b)c=a[b],a[b]=c>>>24|c>>>8&0xff00|(c&0xff00
)<<8|c<<24;return a}};
sjcl.codec.utf8String={fromBits:function(a){var b="",c=sjcl.bitArray.bitLength(a),d,e;for(d=0;d<c/8;d++)0===(d&
3)&&(e=a[d/4]),b+=String.fromCharCode(e>>>8>>>8>>>8),e<<=8;return decodeURIComponent(escape
(b))},toBits:function(a){a=unescape(encodeURIComponent(a));var b=[],c,d=0;for(c=0;c<a.length;c++)d=d<<8|a.charCodeAt(c),
3===(c&3)&&(b.push(d),d=0);c&3&&b.push(sjcl.bitArray.partial(8*(c&3),d));return b}};
sjcl.codec.hex={fromBits:function(a){var b="",c;for(c=0;c<a.length;c++)b+=((a[c]|0)+0xf00000000000).toString(16).substr
(4);return b.substr(0,sjcl.bitArray.bitLength(a)/4)},toBits:function(a){var b,c=[],d;a=a.replace(/\s|0x/g,"");d=a.length;a=a+"00000000";for(b=0;b<a.length;b+=8)c.push(parseInt(a.substr(b,8),16)^0);return sjcl.bitArray.clamp(c,4*d)}};
sjcl.codec.base32={B:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",X:"0123456789ABCDEFGHIJKLMNOPQRSTUV",BITS:32,BASE:5,
REMAINING:27,fromBits:function(a,b,c){var d=sjcl.codec.base32.BASE,e=sjcl.codec.base32.REMAINING,f="",g=0,h=sjcl.codec
.base32.B,k=0,l=sjcl.bitArray.bitLength(a);c&&(h=sjcl.codec.base32.X);for(c=0;f.length*d<l;)f+=h.charAt((k^a[c]>>
;>g)>>>e),g<d?(k=a[c]<<d-g,g+=e,c++):(k<<=d,g-=d);for(;f.length&7&&!b;)f+="=";return
f},toBits:function(a,b){a=a.replace(/\s|=/g,"").toUpperCase();var c=sjcl.codec.base32.BITS,
d=sjcl.codec.base32.BASE,e=sjcl.codec.base32.REMAINING,f=[],g,h=0,k=sjcl.codec.base32.B,l=0,n,m="base32";b&&(k
=sjcl.codec.base32.X,m="base32hex");for(g=0;g<a.length;g++){n=k.indexOf(a.charAt(g));if(0>n){if(!b)try{return sjcl
.codec.base32hex.toBits(a)}catch(p){}throw new sjcl.exception.invalid("this isn't "+m+"!");}h>e?(h-=
e,f.push(l^n>>>h),l=n<<c-h):(h+=d,l^=n<<c-h)}h&56&&f.push(sjcl.bitArray.partial(h&56,l,1));
return f}};
sjcl.codec.base32hex={fromBits:function(a,b){return sjcl.codec.base32.fromBits(a,b,1)},toBits:function(a){return sjcl.codec.base32
.toBits(a,1)}};
...
function(a, b){if(0===a.length||0===b.length)return a.concat(b);var c=a[a.length-1],d=sjcl.bitArray.getPartial(c);return 32===d?a .concat(b):sjcl.bitArray.$(b,d,c|0,a.slice(0,a.length-1))}
...
if (!module || module === "." || module.indexOf("/") >= 0) {
return require("path").resolve(process.cwd(), module || "");
}
// search modulePathList
[
"node_modules"
]
.concat(modulePathList)
.concat(require("module").globalPaths)
.concat([
process.env.HOME + "/node_modules", "/usr/local/lib/node_modules"
])
.some(function (modulePath) {
try {
result = require("path").resolve(
...
function(a, b){if(sjcl.bitArray.bitLength(a)!==sjcl.bitArray.bitLength(b))return!1;var c=0,d;for(d=0;d<a.length;d++)c|=a[d]^b[d]; return 0=== c}
...
if(0>h)throw new sjcl.exception.invalid("this isn't base64!");26<e?(e-=26,c.push(g^h>>>e),g=h<&
lt;32-e):(e+=6,g^=h<<32-e)}e&56&&c.push(sjcl.bitArray.partial(e&56,g,1));return c}};sjcl.codec.base64url={
fromBits:function(a){return sjcl.codec.base64.fromBits(a,1,1)},toBits:function(a){return sjcl.codec.base64.toBits(a,1)}};sjcl.hash
.sha256=function(a){this.b[0]||this.O();a?(this.F=a.F.slice(0),this.A=a.A.slice(0),this.l=a.l):this.reset()};sjcl.hash.sha256.hash
=function(a){return(new sjcl.hash.sha256).update(a).finalize()};
sjcl.hash.sha256.prototype={blockSize:512,reset:function(){this.F=this.Y.slice(0);this.A=[];this.l=0;return this},update:function
(a){"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));var b,c=this.A=sjcl.bitArray.concat(this.A,a);b=this
.l;a=this.l=b+sjcl.bitArray.bitLength(a);if(0x1fffffffffffff<a)throw new sjcl.exception.invalid("Cannot hash more than 2
^53 - 1 bits");if("undefined"!==typeof Uint32Array){var d=new Uint32Array(c),e=0;for(b=512+b-(512+b&0x1ff);b&
lt;=a;b+=512)u(this,d.subarray(16*e,
16*(e+1))),e+=1;c.splice(0,16*e)}else for(b=512+b-(512+b&0x1ff);b<=a;b+=512)u(this,c.splice(0,16));return this},finalize:
function(){var a,b=this.A,c=this.F,b=sjcl.bitArray.concat(b,[sjcl.bitArray.partial(1,1)]);for(a=b.length+2;a&15;a++)b.push(0
);b.push(Math.floor(this.l/0x100000000));for(b.push(this.l|0);b.length;)u(this,b.splice(0,16));this.reset();return c},Y:[],b:[],
O:function(){function a(a){return 0x100000000*(a-Math.floor(a))|0}for(var b=0,c=2,d,e;64>b;c++){e=!0;for(d=2;d*d<=c;d++)if
(0===c%d){e=
!1;break}e&&(8>b&&(this.Y[b]=a(Math.pow(c,.5))),this.b[b]=a(Math.pow(c,1/3)),b++)}}};
function u(a,b){var c,d,e,f=a.F,g=a.b,h=f[0],k=f[1],l=f[2],n=f[3],m=f[4],p=f[5],r=f[6],q=f[7];for(c=0;64>c;c++)16>c?d=b[c]:(
d=b[c+1&15],e=b[c+14&15],d=b[c&15]=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>
;>17^e>>>19^e>>>10^e<<15^e<<13)+b[c&15]+b[c+9&15]|0),d=d+q+(m>>>6^m>>>
;11^m>>>25^m<<26^m<<21^m<<7)+(r^m&(p^r))+g[c],q=r,r=p,p=m,m=n+d|0,n=l,l=k,k=h,h=d+(k&l^n&(
k^l))+(k>>>2^k>>>13^k>>>22^k<<30^k<<19^k<<10)|0;f[0]=f[0]+h|0;f[1]=f[1]+k|0;f[2]=f[
2]+l|0;f[3]=f[3]+n|0;f[4]=f[4]+m|0;f[5]=f[5]+p|0;f[6]=f[6]+r|0;f[7]=
f[7]+q|0}
sjcl.mode.ccm={name:"ccm",G:[],listenProgress:function(a){sjcl.mode.ccm.G.push(a)},unListenProgress:function(a){a=sjcl
.mode.ccm.G.indexOf(a);-1<a&&sjcl.mode.ccm.G.splice(a,1)},fa:function(a){var b=sjcl.mode.ccm.G.slice(),c;for(c=0;c<
;b.length;c+=1)b[c](a)},encrypt:function(a,b,c,d,e){var f,g=b.slice(0),h=sjcl.bitArray,k=h.bitLength(c)/8,l=h.bitLength(g)/8;e=e
||64;d=d||[];if(7>k)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(f=2;4>f&&l&
gt;>>8*f;f++);f<15-k&&(f=15-k);c=h.clamp(c,
8*(15-f));b=sjcl.mode.ccm.V(a,b,c,d,e,f);g=sjcl.mode.ccm.C(a,g,c,b,e,f);return h.concat(g.data,g.tag)},decrypt:function(a,b,c,d,
e){e=e||64;d=d||[];var f=sjcl.bitArray,g=f.bitLength(c)/8,h=f.bitLength(b),k=f.clamp(b,h-e),l=f.bitSlice(b,h-e),h=(h-e)/8;if(7>
;g)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(b=2;4>b&&h>>>8*b;b++);
b<15-g&&(b=15-g);c=f.clamp(c,8*(15-b));k=sjcl.mode.ccm.C(a,k,c,l,e,b);a=sjcl.mode.ccm.V(a,k.data,c,d,e,b);if(!f.equal(k.tag,a))throw new sjcl.exception.corrupt("ccm: tag doesn't match");
return k.data},na:function(a,b,c,d,e,f){var g=[],h=sjcl.bitArray,k=h.i;d=[h.partial(8,(b.length?64:0)|d-2<<2|f-1)];d=h.concat
(d,c);d[3]|=e;d=a.encrypt(d);if(b.length)for(c=h.bitLength(b)/8,65279>=c?g=[h.partial(16,c)]:0xffffffff>=c&&(g=h.concat
([h.partial(16,65534)],[c])),g=h.concat(g,b),b=0;b<g.length;b+=4)d=a.encrypt(k(d,g.slice(b,b+4).concat([0,0,0])));return d},V
:function(a,b,c,d,e,f){var g=sjcl.bitArray,h=g.i;e/=8;if(e%2||4>e||16<e)throw new sjcl.exception.invalid("ccm: invalid
tag length");
if(0xffffffff<d.length||0xffffffff<b.length)throw new sjcl.exception.bug("ccm: can't deal with 4GiB or more data
");c=sjcl.mode.ccm.na(a,d,c,e,g.bitLength(b)/8,f);for(d=0;d<b.length;d+=4)c=a.encrypt(h(c,b.slice(d,d+4).concat([0,0,0])));
return g.clamp(c,8*e)},C:function(a,b,c,d,e,f){var g,h=sjcl.bitArray;g=h.i;var k=b.length,l=h.bitLength(b),n=k/50,m=n;c=h.concat
([h.partial(8,f-1)],c).concat([0,0,0]).slice(0,4);d=h.bitSlice(g(d,a.encrypt(c)),0,e);if(!k)return{tag:d,data:[]};for(g=0;g<k
;g+=4)g>n&&(sjcl.mode.ccm.fa(g/
k),n+=m),c[3]++,e=a.encrypt(c),b[g]^=e[0],b[g+1]^=e[1],b[g+2]^=e[2],b[g+3]^=e[3];return{tag:d,data:h.clamp(b,l)}}};
sjcl.mode.ocb2={name:"ocb2",encrypt:function(a,b,c,d,e,f){if(128!==sjcl.bitArray.bitLength(c))throw new sjcl.exception
.invalid("ocb iv must be 128 bits");var g,h=sjcl.mode.ocb2.S,k=sjcl.bitArray,l=k.i,n=[0,0,0,0];c=h(a.encrypt(c));var m
,p=[];d=d||[];e=e||64;for(g=0;g+4<b.length;g+=4)m=b.slice(g,g+4),n=l(n,m),p=p.concat(l(c,a.encrypt(l(c,m)))),c=h(c);m=b.slice
(g);b=k.bitLength(m);g=a.encrypt(l(c,[0,0,0,b]));m=k.clamp(l(m.concat([0,0,0]),g),b);n=l(n,l(m.concat([0,0,0]),g));n=a.encrypt(l
(n,l(c,h(c))));
d.length&&(n=l(n,f?d:sjcl.mode.ocb2.pmac(a,d)));return p.concat(k.concat(m,k.clamp(n,e)))},decrypt:function(a,b,c,d,e,f){
if(128!==sjcl.bitArray.bitLength(c))throw new sjcl.exception.invalid("ocb iv must be 128 bits");e=e||64;var g=sjcl.mode
.ocb2.S,h=sjcl.bitArray,k=h.i,l=[0,0,0,0],n=g(a.encrypt(c)),m,p,r=sjcl.bitArray.bitLength(b)-e,q=[];d=d||[];for(c=0;c+4<r/32;
c+=4)m=k(n,a.decrypt(k(n,b.slice(c,c+4)))),l=k(l,m),q=q.concat(m),n=g(n);p=r-32*c;m=a.encrypt(k(n,[0,0,0,p]));m=k(m,h.clamp(b.slice
(c),p).concat([0,
0,0]));l=k(l,m);l=a.encrypt(k(l,k(n,g(n))));d.length&&(l=k(l,f?d:sjcl.mode.ocb2.pmac(a,d)));if(!h.equal(h.clamp(l,e),h.bitSlice
(b,r)))throw new sjcl.exception.corrupt("ocb: tag doesn't match");return q.concat(h.clamp(m,p))},pmac:function(a,
b){var c,d=sjcl.mode.ocb2.S,e=sjcl.bitArray,f=e.i,g=[0,0,0,0],h=a.encrypt([0,0,0,0]),h=f(h,d(d(h)));for(c=0;c+4<b.length;c+=4
)h=d(h),g=f(g,a.encrypt(f(h,b.slice(c,c+4))));c=b.slice(c);128>e.bitLength(c)&&(h=f(h,d(h)),c=e.concat(c,[-2147483648
,0,0,0]));g=f(g,c);
return a.encrypt(f(d(f(h,d(h))),g))},S:function(a){return[a[0]<<1^a[1]>>>31,a[1]<<1^a[2]>>>31,a[2]&
lt;<1^a[3]>>>31,a[3]<<1^135*(a[0]>>>31)]}};
...
function(a, b, c){var d=Math.floor(-b-c&31);return((b+c-1^b)&-32?a[b/32|0]<<32-d^a[b/32+1|0]>>>d:a[b/32|0]>>>d)&(1<<c)-1}
n/a
function(a){return Math.round(a/0x10000000000)||32}
...
"use strict";var sjcl={cipher:{},hash:{},keyexchange:{},mode:{},misc:{},codec:{},exception:{corrupt:function(a){this.toString
=function(){return"CORRUPT: "+this.message};this.message=a},invalid:function(a){this.toString=function(){return"INVALID
: "+this.message};this.message=a},bug:function(a){this.toString=function(){return"BUG: "+this.message};this.message
=a},notReady:function(a){this.toString=function(){return"NOT READY: "+this.message};this.message=a}}};
sjcl.cipher.aes=function(a){this.s[0][0][0]||this.O();var b,c,d,e,f=this.s[0][4],g=this.s[1];b=a.length;var h=1;if(4!==b&&
;6!==b&&8!==b)throw new sjcl.exception.invalid("invalid aes key size");this.b=[d=a.slice(0),e=[]];for(a=b;a<
;4*b+28;a++){c=d[a-1];if(0===a%b||8===b&&4===a%b)c=f[c>>>24]<<24^f[c>>16&255]<<16^f[c>&
gt;8&255]<<8^f[c&255],0===a%b&&(c=c<<8^c>>>24^h<<24,h=h<<1^283*(h>>7));d[
a]=d[a-b]^c}for(b=0;a;b++,a--)c=d[b&3?a:a-4],e[b]=4>=a||4>b?c:g[0][f[c>>>24]]^g[1][f[c>>16&255]]^g[
2][f[c>>8&255]]^g[3][f[c&
255]]};
sjcl.cipher.aes.prototype={encrypt:function(a){return t(this,a,0)},decrypt:function(a){return t(this,a,1)},s:[[[],[],[],[],[]],[[],[],[],[],[]]],
O:function(){var a=this.s[0],b=this.s[1],c=a[4],d=b[4],e,f,g,h=[],k=[],l,n,m,p;for(e=0;0x100>e;e++)k[(h[e]=e<<1^283*(e&
gt;>7))^e]=e;for(f=g=0;!c[f];f^=l||1,g=k[g]||1)for(m=g^g<<1^g<<2^g<<3^g<<4,m=m>>8^m&255^99,
c[f]=m,d[m]=f,n=h[e=h[l=h[f]]],p=0x1010101*n^0x10001*e^0x101*l^0x1010100*f,n=0x101*h[m]^0x1010100*m,e=0;4>e;e++)a[e][f]=n=n<
;<24^n>>>8,b[e][m]=p=p<<24^p>>>8;for(e=
0;5>e;e++)a[e]=a[e].slice(0),b[e]=b[e].slice(0)}};
function t(a,b,c){if(4!==b.length)throw new sjcl.exception.invalid("invalid aes block size");var d=a.b[c],e=b[0]^d[0],
f=b[c?3:1]^d[1],g=b[2]^d[2];b=b[c?1:3]^d[3];var h,k,l,n=d.length/4-2,m,p=4,r=[0,0,0,0];h=a.s[c];a=h[0];var q=h[1],v=h[2],w=h[3],
x=h[4];for(m=0;m<n;m++)h=a[e>>>24]^q[f>>16&255]^v[g>>8&255]^w[b&255]^d[p],k=a[f>>>24
]^q[g>>16&255]^v[b>>8&255]^w[e&255]^d[p+1],l=a[g>>>24]^q[b>>16&255]^v[e>>8&
255]^w[f&255]^d[p+2],b=a[b>>>24]^q[e>>16&255]^v[f>>8&255]^w[g&255]^d[p+3],p+=4,e=h,f=k,g=l;
for(m=
0;4>m;m++)r[c?3&-m:m]=x[e>>>24]<<24^x[f>>16&255]<<16^x[g>>8&255]<<8^x[b&
;255]^d[p++],h=e,e=f,f=g,g=b,b=h;return r}
sjcl.bitArray={bitSlice:function(a,b,c){a=sjcl.bitArray.$(a.slice(b/32),32-(b&31)).slice(1);return void 0===c?a:sjcl.bitArray
.clamp(a,c-b)},extract:function(a,b,c){var d=Math.floor(-b-c&31);return((b+c-1^b)&-32?a[b/32|0]<<32-d^a[b/32+1|0]&
gt;>>d:a[b/32|0]>>>d)&(1<<c)-1},concat:function(a,b){if(0===a.length||0===b.length)return a.concat(b);var
c=a[a.length-1],d=sjcl.bitArray.getPartial(c);return 32===d?a.concat(b):sjcl.bitArray
.$(b,d,c|0,a.slice(0,a.length-1))},bitLength:function(a){var b=a.length;return 0===
b?0:32*(b-1)+sjcl.bitArray.getPartial(a[b-1])},clamp:function(a,b){if(32*a.length<b)return a;a=a.slice(0,Math.ceil(b/32));var
c=a.length;b=b&31;0<c&&b&&(a[c-1]=sjcl.bitArray.partial(b,a[c-1]&2147483648>>b-1,1));return a},
partial:function(a,b,c){return 32===a?b:(c?b|0:b<<32-a)+0x10000000000*a},getPartial:function(a){return Math.round(a/0x10000000000
)||32},equal:function(a,b){if(sjcl.bitArray.bitLength(a)!==sjcl.bitArray.bitLength(b))return!1;var c=0,d;for(d=0;d<a.length;d
++)c|=a[d]^b[d];return 0===
c},$:function(a,b,c,d){var e;e=0;for(void 0===d&&(d=[]);32<=b;b-=32)d.push(c),c=0;if(0===b)return d.concat(a);for(e=0
;e<a.length;e++)d.push(c|a[e]>>>b),c=a[e]<<32-b;e=a.length?a[a.length-1]:0;a=sjcl.bitArray.getPartial(e);d.push
(sjcl.bitArray.partial(b+a&31,32<b+a?c:d.pop(),1));return d},i:function(a,b){return[a[0]^b[0],a[1]^b[1],a[2]^b[2],a[3]^b[
3]]},byteswapM:function(a){var b,c;for(b=0;b<a.length;++b)c=a[b],a[b]=c>>>24|c>>>8&0xff00|(c&0xff00
)<<8|c<<24;return a}};
sjcl.codec.utf8String={fromBits:function(a){var b="",c=sjcl.bitArray.bitLength(a),d,e;for(d=0;d<c/8;d++)0===(d&
3)&&(e=a[d/4]),b+=String.fromCharCode(e>>>8>>>8>>>8),e<<=8;return decodeURIComponent(escape
(b))},toBits:function(a){a=unescape(encodeURIComponent(a));var b=[],c,d=0;for(c=0;c<a.length;c++)d=d<<8|a.charCodeAt(c),
3===(c&3)&&(b.push(d),d=0);c&3&&b.push(sjcl.bitArray.partial(8*(c&3),d));return b}};
sjcl.codec.hex={fromBits:function(a){var b="",c;for(c=0;c<a.length;c++)b+=((a[c]|0)+0xf00000000000).toString(16).substr
(4);return b.substr(0,sjcl.bitArray.bitLength(a)/4)},toBits:function(a){var b,c=[],d;a=a.replace(/\s|0x/g,"");d=a.length;a=a+"00000000";for(b=0;b<a.length;b+=8)c.push(parseInt(a.substr(b,8),16)^0);return sjcl.bitArray.clamp(c,4*d)}};
sjcl.codec.base32={B:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",X:"0123456789ABCDEFGHIJKLMNOPQRSTUV",BITS:32,BASE:5,
REMAINING:27,fromBits:function(a,b,c){var d=sjcl.codec.base32.BASE,e=sjcl.codec.base32.REMAINING,f="",g=0,h=sjcl.codec
.base32.B,k=0,l=sjcl.bitArray.bitLength(a);c&&(h=sjcl.codec.base32.X);for(c=0;f.length*d<l;)f+=h.charAt((k^a[c]>>
;>g)>>>e),g<d?(k=a[c]<<d-g,g+=e,c++):(k<<=d,g-=d);for(;f.length&7&&!b;)f+="=";return
f},toBits:function(a,b){a=a.replace(/\s|=/g,"").toUpperCase();var c=sjcl.codec.base32.BITS,
d=sjcl.codec.base32.BASE,e=sjcl.codec.base32.REMAINING,f=[],g,h=0,k=sjcl.codec.base32.B,l=0,n,m="base32";b&&(k
=sjcl.codec.base32.X,m="base32hex");for(g=0;g<a.length;g++){n=k.indexOf(a.charAt(g));if(0>n){if(!b)try{return sjcl
.codec.base32hex.toBits(a)}catch(p){}throw new sjcl.exception.invalid("this isn't "+m+"!");}h>e?(h-=
e,f.push(l^n>>>h),l=n<<c-h):(h+=d,l^=n<<c-h)}h&56&&f.push(sjcl.bitArray.partial(h&56,l,1));
return f}};
sjcl.codec.base32hex={fromBits:function(a,b){return sjcl.codec.base32.fromBits(a,b,1)},toBits:function(a){return sjcl.codec.base32
.toBits(a,1)}};
...
function(a, b){return[a[0]^b[0],a[1]^b[1],a[2]^b[2],a[3]^b[3]]}
n/a
function(a, b, c){return 32===a?b:(c?b|0:b<<32-a)+0x10000000000*a}
...
sjcl.cipher.aes=function(a){this.s[0][0][0]||this.O();var b,c,d,e,f=this.s[0][4],g=this.s[1];b=a.length;var h=1;if(4!==b&&
;6!==b&&8!==b)throw new sjcl.exception.invalid("invalid aes key size");this.b=[d=a.slice(0),e=[]];for(a=b;a<
;4*b+28;a++){c=d[a-1];if(0===a%b||8===b&&4===a%b)c=f[c>>>24]<<24^f[c>>16&255]<<16^f[c>&
gt;8&255]<<8^f[c&255],0===a%b&&(c=c<<8^c>>>24^h<<24,h=h<<1^283*(h>>7));d[
a]=d[a-b]^c}for(b=0;a;b++,a--)c=d[b&3?a:a-4],e[b]=4>=a||4>b?c:g[0][f[c>>>24]]^g[1][f[c>>16&255]]^g[
2][f[c>>8&255]]^g[3][f[c&
255]]};
sjcl.cipher.aes.prototype={encrypt:function(a){return t(this,a,0)},decrypt:function(a){return t(this,a,1)},s:[[[],[],[],[],[]],[[],[],[],[],[]]],
O:function(){var a=this.s[0],b=this.s[1],c=a[4],d=b[4],e,f,g,h=[],k=[],l,n,m,p;for(e=0;0x100>e;e++)k[(h[e]=e<<1^283*(e&
gt;>7))^e]=e;for(f=g=0;!c[f];f^=l||1,g=k[g]||1)for(m=g^g<<1^g<<2^g<<3^g<<4,m=m>>8^m&255^99,
c[f]=m,d[m]=f,n=h[e=h[l=h[f]]],p=0x1010101*n^0x10001*e^0x101*l^0x1010100*f,n=0x101*h[m]^0x1010100*m,e=0;4>e;e++)a[e][f]=n=n<
;<24^n>>>8,b[e][m]=p=p<<24^p>>>8;for(e=
0;5>e;e++)a[e]=a[e].slice(0),b[e]=b[e].slice(0)}};
function t(a,b,c){if(4!==b.length)throw new sjcl.exception.invalid("invalid aes block size");var d=a.b[c],e=b[0]^d[0],
f=b[c?3:1]^d[1],g=b[2]^d[2];b=b[c?1:3]^d[3];var h,k,l,n=d.length/4-2,m,p=4,r=[0,0,0,0];h=a.s[c];a=h[0];var q=h[1],v=h[2],w=h[3],
x=h[4];for(m=0;m<n;m++)h=a[e>>>24]^q[f>>16&255]^v[g>>8&255]^w[b&255]^d[p],k=a[f>>>24
]^q[g>>16&255]^v[b>>8&255]^w[e&255]^d[p+1],l=a[g>>>24]^q[b>>16&255]^v[e>>8&
255]^w[f&255]^d[p+2],b=a[b>>>24]^q[e>>16&255]^v[f>>8&255]^w[g&255]^d[p+3],p+=4,e=h,f=k,g=l;
for(m=
0;4>m;m++)r[c?3&-m:m]=x[e>>>24]<<24^x[f>>16&255]<<16^x[g>>8&255]<<8^x[b&
;255]^d[p++],h=e,e=f,f=g,g=b,b=h;return r}
sjcl.bitArray={bitSlice:function(a,b,c){a=sjcl.bitArray.$(a.slice(b/32),32-(b&31)).slice(1);return void 0===c?a:sjcl.bitArray
.clamp(a,c-b)},extract:function(a,b,c){var d=Math.floor(-b-c&31);return((b+c-1^b)&-32?a[b/32|0]<<32-d^a[b/32+1|0]&
gt;>>d:a[b/32|0]>>>d)&(1<<c)-1},concat:function(a,b){if(0===a.length||0===b.length)return a.concat(b);var
c=a[a.length-1],d=sjcl.bitArray.getPartial(c);return 32===d?a.concat(b):sjcl.bitArray.$(b,d,c|0,a.slice(0,a.length-1))},bitLength
:function(a){var b=a.length;return 0===
b?0:32*(b-1)+sjcl.bitArray.getPartial(a[b-1])},clamp:function(a,b){if(32*a.length<b)return a;a=a.slice(0,Math.ceil(b/32));var
c=a.length;b=b&31;0<c&&b&&(a[c-1]=sjcl.bitArray.partial(b,a[c
-1]&2147483648>>b-1,1));return a},partial:function(a,b,c){return 32===a?b:(c?b|0:b<<32-a)+0x10000000000*a},getPartial
:function(a){return Math.round(a/0x10000000000)||32},equal:function(a,b){if(sjcl.bitArray.bitLength(a)!==sjcl.bitArray.bitLength
(b))return!1;var c=0,d;for(d=0;d<a.length;d++)c|=a[d]^b[d];return 0===
c},$:function(a,b,c,d){var e;e=0;for(void 0===d&&(d=[]);32<=b;b-=32)d.push(c),c=0;if(0===b)return d.concat(a);for(e=0
;e<a.length;e++)d.push(c|a[e]>>>b),c=a[e]<<32-b;e=a.length?a[a.length-1]:0;a=sjcl.bitArray.getPartial(e);d.push
(sjcl.bitArray.partial(b+a&31,32<b+a?c:d.pop(),1));return d},i:function(a,b){return[a[0]^b[0],a[1]^b[1],a[2]^b[2],a[3]^b[
3]]},byteswapM:function(a){var b,c;for(b=0;b<a.length;++b)c=a[b],a[b]=c>>>24|c>>>8&0xff00|(c&0xff00
)<<8|c<<24;return a}};
sjcl.codec.utf8String={fromBits:function(a){var b="",c=sjcl.bitArray.bitLength(a),d,e;for(d=0;d<c/8;d++)0===(d&
3)&&(e=a[d/4]),b+=String.fromCharCode(e>>>8>>>8>>>8),e<<=8;return decodeURIComponent(escape
(b))},toBits:function(a){a=unescape(encodeURIComponent(a));var b=[],c,d=0;for(c=0;c<a.length;c++)d=d<<8|a.charCodeAt(c),
3===(c&3)&&(b.push(d),d=0);c&3&&b.push(sjcl.bitArray.partial(8*(c&3),d));return b}};
sjcl.codec.hex={fromBits:function(a){var b="",c;for(c=0;c<a.length;c++)b+=((a[c]|0)+0xf00000000000).toString(16).substr
(4);return b.substr(0,sjcl.bitArray.bitLength(a)/4)},toBits:function(a){var b,c=[],d;a=a.replace(/\s|0x/g,"");d=a.length;a=a+"00000000";for(b=0;b<a.length;b+=8)c.push(parseInt(a.substr(b,8),16)^0);return sjcl.bitArray.clamp(c,4*d)}};
sjcl.codec.base32={B:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",X:"0123456789ABCDEFGHIJKLMNOPQRSTUV",BITS:32,BASE:5,
REMAINING:27,fromBits:function(a,b,c){var d=sjcl.codec.base32.BASE,e=sjcl.codec.base32.REMAINING,f="",g=0,h=sjcl.codec
.base32.B,k=0,l=sjcl.bitArray.bitLength(a);c&&(h=sjcl.codec.base32.X);for(c=0;f.length*d<l;)f+=h.charAt((k^a[c]>>
;>g)>>>e),g<d?(k=a[c]<<d-g,g+=e,c++):(k<<=d,g-=d);for(;f.length&7&&!b;)f+="=";return
f},toBits:function(a,b){a=a.replace(/\s|=/g,"").toUpperCase();var c=sjcl.codec.base32.BITS,
d=sjcl.codec.base32.BASE,e=sjcl.codec.base32.REMAINING,f=[],g,h=0,k=sjcl.codec.base32.B,l=0,n,m="base32";b&&(k
=sjcl.codec.base32.X,m="base32hex");for(g=0;g<a.length;g++){n=k.indexOf(a.charAt(g));if(0>n){if(!b)try{return sjcl
.codec.base32hex.toBits(a)}catch(p){}throw new sjcl.exception.invalid("this isn't "+m+"!");}h>e?(h-=
e,f.push(l^n>>>h),l=n<<c-h):(h+=d,l^=n<<c-h)}h&56&&f.push(sjcl.bitArray.partial(h&56,l,1));
return f}};
sjcl.codec.base32hex={fromBits:function(a,b){return sjcl.codec.base32.fromBits(a,b,1)},toBits:function(a){return sjcl.codec.base32
.toBits(a,1)}};
sjcl.codec.base64={B:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",fromBits:function(a,b,c){var d
="",e=0,f=sjcl.codec.base64.B,g=0,h=sjcl.bitArray.bitLength(a);c&&(f=f.substr(0,62)+"-_");for(c=0;6*
d.length<h;)d+=f.charAt((g^a[c]>>>e)>>>26),6>e?(g=a[c]<<6-e,e+=26,c++):(g<<=6,e-=6);for(;d.length
&3&&!b;)d+="=";return d},toBits:function(a,b){a=a.replace(/\s|=/g,"");var c=[],d,e=0,f=sjcl.codec.base64.B,g=0,h;b&&(f=f.substr(0,62)+"-_");for(d=0;d<a.length;d++){h=f.indexOf(a.charAt(d));
...
function(a){this.s[0][0][0]||this.O();var b,c,d,e,f=this.s[0][4],g=this.s[1];b=a.length;var h=1;if(4!==b&&6!==b&&8!==b)throw new sjcl.exception.invalid("invalid aes key size");this.b=[d=a.slice(0),e=[]];for(a=b;a<4*b+28;a++){c=d[a-1];if(0===a%b||8===b&&4=== a%b)c=f[c>>>24]<<24^f[c>>16&255]<<16^f[c>>8&255]<<8^f[c&255],0===a%b&&(c=c<<8^c>>>24^h<<24,h=h<<1^283*(h>>7));d[a]=d[a-b]^c}for( b=0;a;b++,a--)c=d[b&3?a:a-4],e[b]=4>=a||4>b?c:g[0][f[c>>>24]]^g[1][f[c>>16&255]]^g[2][f[c>>8&255]]^g[3][f[c& 255]]}
...
0,0];f=b.slice(0);for(c=0;128>c;c++){(d=0!==(a[Math.floor(c/32)]&1<<31-c%32))&&(e=h(e,f));g=0!==(f[3]&1
);for(d=3;0<d;d--)f[d]=f[d]>>>1|(f[d-1]&1)<<31;f[0]>>>=1;g&&(f[0]^=-0x1f000000)}return e},
j:function(a,b,c){var d,e=c.length;b=b.slice(0);for(d=0;d<e;d+=4)b[0]^=0xffffffff&c[d],b[1]^=0xffffffff&c[d+1],b[2]^=
0xffffffff&c[d+2],b[3]^=0xffffffff&c[d+3],b=sjcl.mode.gcm.ka(b,a);return b},C:function(a,b,c,d,e,f){var g,h,k,l,n,m,p,r,
q=sjcl.bitArray;m=c.length;p=q.bitLength(c);r=q.bitLength(d);h=q.bitLength(e);
g=b.encrypt([0,0,0,0]);96===h?(e=e.slice(0),e=q.concat(e,[1])):(e=sjcl.mode.gcm.j(g,[0,0,0,0],e),e=sjcl.mode.gcm.j(g,e,[0,0,Math
.floor(h/0x100000000),h&0xffffffff]));h=sjcl.mode.gcm.j(g,[0,0,0,0],d);n=e.slice(0);d=h.slice(0);a||(d=sjcl.mode.gcm.j(g,h,c
));for(l=0;l<m;l+=4)n[3]++,k=b.encrypt(n),c[l]^=k[0],c[l+1]^=k[1],c[l+2]^=k[2],c[l+3]^=k[3];c=q.clamp(c,p);a&&(d=sjcl
.mode.gcm.j(g,h,c));a=[Math.floor(r/0x100000000),r&0xffffffff,Math.floor(p/0x100000000),p&0xffffffff];d=sjcl.mode.gcm.j(
g,d,a);k=b.encrypt(e);
d[0]^=k[0];d[1]^=k[1];d[2]^=k[2];d[3]^=k[3];return{tag:q.bitSlice(d,0,f),data:c}}};sjcl.misc.hmac=function(a,b){this.W=b=b||sjcl
.hash.sha256;var c=[[],[]],d,e=b.prototype.blockSize/32;this.w=[new b,new b];a.length>e&&(a=b.hash(a));for(d=0;d<e
;d++)c[0][d]=a[d]^909522486,c[1][d]=a[d]^1549556828;this.w[0].update(c[0]);this.w[1].update(c[1]);this.R=new b(this.w[0])};
sjcl.misc.hmac.prototype.encrypt=sjcl.misc.hmac.prototype.mac=function(a){if(this.aa)throw new sjcl.exception.invalid("encrypt
on already updated hmac called!");this.update(a);return this.digest(a)};sjcl.misc.hmac.prototype.reset=function(){this.R=new
this.W(this.w[0]);this.aa=!1};sjcl.misc.hmac.prototype.update=function(a){this.aa=!0;this.R.update(a)};sjcl.misc.hmac.prototype
.digest=function(){var a=this.R.finalize(),a=(new this.W(this.w[1])).update(a).finalize();this.reset();return a};
sjcl.misc.pbkdf2=function(a,b,c,d,e){c=c||1E4;if(0>d||0>c)throw new sjcl.exception.invalid("invalid params to pbkdf2&
quot;);"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));"string"===typeof b&&(b=sjcl
.codec.utf8String.toBits(b));e=e||sjcl.misc.hmac;a=new e(a);var f,g,h,k,l=[],n=sjcl.bitArray;for(k=1;32*l.length<(d||1);k++){
e=f=a.encrypt(n.concat(b,[k]));for(g=1;g<c;g++)for(f=a.encrypt(f),h=0;h<f.length;h++)e[h]^=f[h];l=l.concat(e)}d&&(
l=n.clamp(l,d));return l};
sjcl.prng=function(a){this.c=[new sjcl.hash.sha256];this.m=[0];this.P=0;this.H={};this.N=0;this.U={};this.Z=this.f=this.o=this.ha
=0;this.b=[0,0,0,0,0,0,0,0];this.h=[0,0,0,0];this.L=void 0;this.M=a;this.D=!1;this.K={progress:{},seeded:{}};this.u=this.ga=0;this
.I=1;this.J=2;this.ca=0x10000;this.T=[0,48,64,96,128,192,0x100,384,512,768,1024];this.da=3E4;this.ba=80};
sjcl.prng.prototype={randomWords:function(a,b){var c=[],d;d=this.isReady(b);var e;if(d===this.u)throw new sjcl.exception.notReady
("generator isn't seeded");if(d&this.J){d=!(d&this.I);e=[];var f=0,g;this.Z=e[0]=(new Date).valueOf()+this
.da;for(g=0;16>g;g++)e.push(0x100000000*Math.random()|0);for(g=0;g<this.c.length&&(e=e.concat(this.c[g].finalize()),
f+=this.m[g],this.m[g]=0,d||!(this.P&1<<g));g++);this.P>=1<<this.c.length&&(this.c.push(new sjcl.hash
.sha256),this.m.push(0));this.f-=f;f>this.o&&(this.o=
f);this.P++;this.b=sjcl.hash.sha256.hash(this.b.concat(e));this.L=new sjcl.cipher.aes(
this.b);for(d=0;4>d&&(this.h[d]=this.h[d]+1|0,!this.h[d]);d++);}for(d=0;d<a;d+=4)0===(d+1)%this.ca&&y(this
),e=z(this),c.push(e[0],e[1],e[2],e[3]);y(this);return c.slice(0,a)},setDefaultParanoia:function(a,b){if(0===a&&"Setting
paranoia=0 will ruin your security; use it only for testing"!==b)throw new sjcl.exception.invalid("Setting paranoia=0
will ruin your security; use it only for testing");this.M=a},addEntropy:function(a,
b,c){c=c||"user";var d,e,f=(new Date).valueOf(),g=this.H[c],h=this.isReady(),k=0;d=this.U[c];void 0===d&&(d=this
.U[c]=this.ha++);void 0===g&&(g=this.H[c]=0);this.H[c]=(this.H[c]+1)%this.c.length;switch(typeof a){case "number"
;:void 0===b&&(b=1);this.c[g].update([d,this.N++,1,b,f,1,a|0]);break;case "object":c=Object.prototype.toString
.call(a);if("[object Uint32Array]"===c){e=[];for(c=0;c<a.length;c++)e.push(a[c]);a=e}else for("[object Array]&
quot;!==c&&(k=1),c=0;c<a.length&&!k;c++)"number"!==typeof a[c]&&
(k=1);if(!k){if(void 0===b)for(c=b=0;c<a.length;c++)for(e=a[c];0<e;)b++,e=e>>>1;this.c[g].update([d,this.N++,2,b,
f,a.length].concat(a))}break;case "string":void 0===b&&(b=a.length);this.c[g].update([d,this.N++,3,b,f,a.length
]);this.c[g].update(a);break;default:k=1}if(k)throw new sjcl.exception.bug("random: addEntropy only supports number, array
of numbers or string");this.m[g]+=b;this.f+=b;h===this.u&&(this.isReady()!==this.u&&A("seeded",Math
.max(this.o,this.f)),A("progress",this.getProgress()))},
isReady:function(a){a=this.T[void 0!==a?a:this.M];return this.o&&this.o>=a?this.m[0]>this.ba&&(new Date).valueOf
()>this.Z?this.J|this.I:this.I:this.f>=a?this.J|this.u:this.u},getProgress:function(a){a=this.T[a?a:this.M];return this.o&
gt;=a?1:this.f>a?1:this.f/a},startCollectors:function(){if(!this.D){this.a={loadTimeCollector:B(this,this.ma),mouseCollector:
B(this,this.oa),keyboardCollector:B(this,this.la),accelerometerCollector:B(this,this.ea),touchCollector:B(this,this.qa)};if(window
.addEventListener)window.addEventListener("load",
this.a.loadTimeCollector,!1),window.addEventListener("mousemove",this.a.mouseCollector,!1),window.addEventListener("
;keypress",this.a.keyboardCollector,!1),window.addEventListener("devicemotion",this.a.accelerometerCollector,!1),
window.addEventListener("touchmove",this.a.touchCollector,!1);else if(document.attachEvent)document.attachEvent("
onload",this.a.loadTimeCollector),document.attachEvent("onmousemove",this.a.mouseCollector),document.attachEvent(&
quot;keypress",this.a.keyboardCollector);else throw new sjcl.exception.bug("can't attach event");
this.D=!0}},stopCollectors:function(){this.D&&(window.removeEventListener?(window.removeEventListener("load",this
.a.loadTimeCollector,!1),window.removeEventListener("mousemove",this.a.mouseCollector,!1),window.removeEventListener(&
quot;keypress",this.a.keyboardCollector,!1),window.removeEventListener("devicemotion",this.a.accelerometerCollector
,!1),window.removeEventListener("touchmove",this.a.touchCollector,!1)):document.detachEvent&&(document.detachEvent
("onload",this.a.loadTimeCollector),document.detachEvent("onmousemove",
this.a.mouseCollector),document.detachEvent("keypress",this.a.keyboardCollector)),this.D=!1)},addEventListener:function
(a,b){this.K[a][this.ga++]=b},removeEventListener:function(a,b){var c,d,e=this.K[a],f=[];for(d in e)e.hasOwnProperty(d)&&
;e[d]===b&&f.push(d);for(c=0;c<f.length;c++)d=f[c],delete e[d]},la:function(){C(this,1)},oa:function(a){var b,c;try{b
=a.x||a.clientX||a.offsetX||0,c=a.y||a.clientY||a.offsetY||0}catch(d){c=b=0}0!=b&&0!=c&&this.addEntropy([b,c],2,&
quot;mouse");C(this,0)},qa:function(a){a=
a.touches[0]||a.changedTouches[0];this.addEntropy([a.pageX||a.clientX,a.pageY||a.clientY],1,"touch");C(this,0)},ma:function
(){C(this,2)},ea:function(a){a=a.accelerationIncludingGravity.x||a.accelerationIncludingGravity.y||a.accelerationIncludingGravity
.z;if(window.orientation){var b=window.orientation;"number"===typeof b&&this.addEntropy(b,1,"accelerometer
")}a&&this.addEntropy(a,2,"accelerometer");C(this,0)}};
...
function(){var a=this.s[0],b=this.s[1],c=a[4],d=b[4],e,f,g,h=[],k=[],l,n,m,p;for(e=0;0x100>e;e++)k[(h[e]=e<<1^283*(e>>7))^e]=e;for (f=g=0;!c[f];f^=l||1,g=k[g]||1)for(m=g^g<<1^g<<2^g<<3^g<<4,m=m>>8^m&255^99,c[f]=m,d[m]=f,n=h[e=h[l=h[f]]],p=0x1010101*n^0x10001* e^0x101*l^0x1010100*f,n=0x101*h[m]^0x1010100*m,e=0;4>e;e++)a[e][f]=n=n<<24^n>>>8,b[e][m]=p=p<<24^p>>>8;for(e= 0;5>e;e++)a[e]=a[e].slice(0),b[e]=b[e].slice(0)}
...
file https://github.com/bitwiseshiftleft/sjcl/blob/1.0.8/sjcl.js
shGithubDateCommitted https://github.com/bitwiseshiftleft/sjcl/blob/1.0.8/sjcl.js # 2017-07-04T08:55:03Z
curl https://raw.githubusercontent.com/bitwiseshiftleft/sjcl/1.0.8/sjcl.js > /tmp/aa.js
*/
/* jslint ignore:start */
(function () { var module;
"use strict";var sjcl={cipher:{},hash:{},keyexchange:{},mode:{},misc:{},codec:{},exception:{corrupt:function(a){this.toString
=function(){return"CORRUPT: "+this.message};this.message=a},invalid:function(a){this.toString=function(){return"INVALID
: "+this.message};this.message=a},bug:function(a){this.toString=function(){return"BUG: "+this.message};this.message
=a},notReady:function(a){this.toString=function(){return"NOT READY: "+this.message};this.message=a}}};
sjcl.cipher.aes=function(a){this.s[0][0][0]||this.O();var b,c,d,e,f=this.s[0][4],g=this
.s[1];b=a.length;var h=1;if(4!==b&&6!==b&&8!==b)throw new sjcl.exception.invalid("invalid aes key size"
;);this.b=[d=a.slice(0),e=[]];for(a=b;a<4*b+28;a++){c=d[a-1];if(0===a%b||8===b&&4===a%b)c=f[c>>>24]<<24
^f[c>>16&255]<<16^f[c>>8&255]<<8^f[c&255],0===a%b&&(c=c<<8^c>>>24^h<
;<24,h=h<<1^283*(h>>7));d[a]=d[a-b]^c}for(b=0;a;b++,a--)c=d[b&3?a:a-4],e[b]=4>=a||4>b?c:g[0][f[c>>
;>24]]^g[1][f[c>>16&255]]^g[2][f[c>>8&255]]^g[3][f[c&
255]]};
sjcl.cipher.aes.prototype={encrypt:function(a){return t(this,a,0)},decrypt:function(a){return t(this,a,1)},s:[[[],[],[],[],[]],[[],[],[],[],[]]],
O:function(){var a=this.s[0],b=this.s[1],c=a[4],d=b[4],e,f,g,h=[],k=[],l,n,m,p;for(e=0;0x100>e;e++)k[(h[e]=e<<1^283*(e&
gt;>7))^e]=e;for(f=g=0;!c[f];f^=l||1,g=k[g]||1)for(m=g^g<<1^g<<2^g<<3^g<<4,m=m>>8^m&255^99,
c[f]=m,d[m]=f,n=h[e=h[l=h[f]]],p=0x1010101*n^0x10001*e^0x101*l^0x1010100*f,n=0x101*h[m]^0x1010100*m,e=0;4>e;e++)a[e][f]=n=n<
;<24^n>>>8,b[e][m]=p=p<<24^p>>>8;for(e=
0;5>e;e++)a[e]=a[e].slice(0),b[e]=b[e].slice(0)}};
function t(a,b,c){if(4!==b.length)throw new sjcl.exception.invalid("invalid aes block size");var d=a.b[c],e=b[0]^d[0],
f=b[c?3:1]^d[1],g=b[2]^d[2];b=b[c?1:3]^d[3];var h,k,l,n=d.length/4-2,m,p=4,r=[0,0,0,0];h=a.s[c];a=h[0];var q=h[1],v=h[2],w=h[3],
x=h[4];for(m=0;m<n;m++)h=a[e>>>24]^q[f>>16&255]^v[g>>8&255]^w[b&255]^d[p],k=a[f>>>24
]^q[g>>16&255]^v[b>>8&255]^w[e&255]^d[p+1],l=a[g>>>24]^q[b>>16&255]^v[e>>8&
255]^w[f&255]^d[p+2],b=a[b>>>24]^q[e>>16&255]^v[f>>8&255]^w[g&255]^d[p+3],p+=4,e=h,f=k,g=l;
for(m=
0;4>m;m++)r[c?3&-m:m]=x[e>>>24]<<24^x[f>>16&255]<<16^x[g>>8&255]<<8^x[b&
;255]^d[p++],h=e,e=f,f=g,g=b,b=h;return r}
sjcl.bitArray={bitSlice:function(a,b,c){a=sjcl.bitArray.$(a.slice(b/32),32-(b&31)).slice(1);return void 0===c?a:sjcl.bitArray
.clamp(a,c-b)},extract:function(a,b,c){var d=Math.floor(-b-c&31);return((b+c-1^b)&-32?a[b/32|0]<<32-d^a[b/32+1|0]&
gt;>>d:a[b/32|0]>>>d)&(1<<c)-1},concat:function(a,b){if(0===a.length||0===b.length)return a.concat(b);var
c=a[a.length-1],d=sjcl.bitArray.getPartial(c);return 32===d?a.concat(b):sjcl.bitArray.$(b,d,c|0,a.slice(0,a.length-1))},bitLength
:function(a){var b=a.length;return 0===
b?0:32*(b-1)+sjcl.bitArray.getPartial(a[b-1])},clamp:function(a,b){if(32*a.length<b)return a;a=a.slice(0,Math.ceil(b/32));var
c=a.length;b=b&31;0<c&&b&&(a[c-1]=sjcl.bitArray.partial(b,a[c-1]&2147483648>>b-1,1));return a},
partial:function(a,b,c){return 32===a?b:(c?b|0:b<<32-a)+0x10000000000*a},getPartial:function(a){return Math.round(a/0x10000000000
)||32},equal:function(a,b){if(sjcl.bitArray.bitLength(a)!==sjcl.bitArray.bitLength(b))return!1;var c=0,d;for(d=0;d<a.length;d
++)c|=a[d]^b[d];return 0===
...
function(a){return t(this,a,1)}
...
f[7]+q|0}
sjcl.mode.ccm={name:"ccm",G:[],listenProgress:function(a){sjcl.mode.ccm.G.push(a)},unListenProgress:function(a){a=sjcl
.mode.ccm.G.indexOf(a);-1<a&&sjcl.mode.ccm.G.splice(a,1)},fa:function(a){var b=sjcl.mode.ccm.G.slice(),c;for(c=0;c<
;b.length;c+=1)b[c](a)},encrypt:function(a,b,c,d,e){var f,g=b.slice(0),h=sjcl.bitArray,k=h.bitLength(c)/8,l=h.bitLength(g)/8;e=e
||64;d=d||[];if(7>k)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(f=2;4>f&&l&
gt;>>8*f;f++);f<15-k&&(f=15-k);c=h.clamp(c,
8*(15-f));b=sjcl.mode.ccm.V(a,b,c,d,e,f);g=sjcl.mode.ccm.C(a,g,c,b,e,f);return h.concat(g.data,g.tag)},decrypt:function(a,b,c,d,
e){e=e||64;d=d||[];var f=sjcl.bitArray,g=f.bitLength(c)/8,h=f.bitLength(b),k=f.clamp(b,h-e),l=f.bitSlice(b,h-e),h=(h-e)/8;if(7>
;g)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(b=2;4>b&&h>>>8*b;b++);
b<15-g&&(b=15-g);c=f.clamp(c,8*(15-b));k=sjcl.mode.ccm.C(a,k,c,l,e,b);a=sjcl.mode.ccm.V(a,k.data,c,d,e,b);if(!f.equal
(k.tag,a))throw new sjcl.exception.corrupt("ccm: tag doesn't match");
return k.data},na:function(a,b,c,d,e,f){var g=[],h=sjcl.bitArray,k=h.i;d=[h.partial(8,(b.length?64:0)|d-2<<2|f-1)];d=h.concat
(d,c);d[3]|=e;d=a.encrypt(d);if(b.length)for(c=h.bitLength(b)/8,65279>=c?g=[h.partial(16,c)]:0xffffffff>=c&&(g=h.concat
([h.partial(16,65534)],[c])),g=h.concat(g,b),b=0;b<g.length;b+=4)d=a.encrypt(k(d,g.slice(b,b+4).concat([0,0,0])));return d},V
:function(a,b,c,d,e,f){var g=sjcl.bitArray,h=g.i;e/=8;if(e%2||4>e||16<e)throw new sjcl.exception.invalid("ccm: invalid
tag length");
if(0xffffffff<d.length||0xffffffff<b.length)throw new sjcl.exception.bug("ccm: can't deal with 4GiB or more data
");c=sjcl.mode.ccm.na(a,d,c,e,g.bitLength(b)/8,f);for(d=0;d<b.length;d+=4)c=a.encrypt(h(c,b.slice(d,d+4).concat([0,0,0])));
return g.clamp(c,8*e)},C:function(a,b,c,d,e,f){var g,h=sjcl.bitArray;g=h.i;var k=b.length,l=h.bitLength(b),n=k/50,m=n;c=h.concat
([h.partial(8,f-1)],c).concat([0,0,0]).slice(0,4);d=h.bitSlice(g(d,a.encrypt(c)),0,e);if(!k)return{tag:d,data:[]};for(g=0;g<k
;g+=4)g>n&&(sjcl.mode.ccm.fa(g/
k),n+=m),c[3]++,e=a.encrypt(c),b[g]^=e[0],b[g+1]^=e[1],b[g+2]^=e[2],b[g+3]^=e[3];return{tag:d,data:h.clamp(b,l)}}};
sjcl.mode.ocb2={name:"ocb2",encrypt:function(a,b,c,d,e,f){if(128!==sjcl.bitArray.bitLength(c))throw new sjcl.exception
.invalid("ocb iv must be 128 bits");var g,h=sjcl.mode.ocb2.S,k=sjcl.bitArray,l=k.i,n=[0,0,0,0];c=h(a.encrypt(c));var m
,p=[];d=d||[];e=e||64;for(g=0;g+4<b.length;g+=4)m=b.slice(g,g+4),n=l(n,m),p=p.concat(l(c,a.encrypt(l(c,m)))),c=h(c);m=b.slice
(g);b=k.bitLength(m);g=a.encrypt(l(c,[0,0,0,b]));m=k.clamp(l(m.concat([0,0,0]),g),b);n=l(n,l(m.concat([0,0,0]),g));n=a.encrypt(l
(n,l(c,h(c))));
d.length&&(n=l(n,f?d:sjcl.mode.ocb2.pmac(a,d)));return p.concat(k.concat(m,k.clamp(n,e)))},decrypt:function(a,b,c,d,e,f){
if(128!==sjcl.bitArray.bitLength(c))throw new sjcl.exception.invalid("ocb iv must be 128 bits");e=e||64;var g=sjcl.mode
.ocb2.S,h=sjcl.bitArray,k=h.i,l=[0,0,0,0],n=g(a.encrypt(c)),m,p,r=sjcl.bitArray.bitLength(b)-e,q=[];d=d||[];for(c=0;c+4<r/32;
c+=4)m=k(n,a.decrypt(k(n,b.slice(c,c+4)))),l=k(l,m),q=q.concat(m),n=g(n);p=r-32*c;m=a
.encrypt(k(n,[0,0,0,p]));m=k(m,h.clamp(b.slice(c),p).concat([0,
0,0]));l=k(l,m);l=a.encrypt(k(l,k(n,g(n))));d.length&&(l=k(l,f?d:sjcl.mode.ocb2.pmac(a,d)));if(!h.equal(h.clamp(l,e),h.bitSlice
(b,r)))throw new sjcl.exception.corrupt("ocb: tag doesn't match");return q.concat(h.clamp(m,p))},pmac:function(a,
b){var c,d=sjcl.mode.ocb2.S,e=sjcl.bitArray,f=e.i,g=[0,0,0,0],h=a.encrypt([0,0,0,0]),h=f(h,d(d(h)));for(c=0;c+4<b.length;c+=4
)h=d(h),g=f(g,a.encrypt(f(h,b.slice(c,c+4))));c=b.slice(c);128>e.bitLength(c)&&(h=f(h,d(h)),c=e.concat(c,[-2147483648
,0,0,0]));g=f(g,c);
return a.encrypt(f(d(f(h,d(h))),g))},S:function(a){return[a[0]<<1^a[1]>>>31,a[1]<<1^a[2]>>>31,a[2]&
lt;<1^a[3]>>>31,a[3]<<1^135*(a[0]>>>31)]}};
sjcl.mode.gcm={name:"gcm",encrypt:function(a,b,c,d,e){var f=b.slice(0);b=sjcl.bitArray;d=d||[];a=sjcl.mode.gcm.C(!0,a,
f,d,c,e||128);return b.concat(a.data,a.tag)},decrypt:function(a,b,c,d,e){var f=b.slice(0),g=sjcl.bitArray,h=g.bitLength(f);e=e||
128;d=d||[];e<=h?(b=g.bitSlice(f,h-e),f=g.bitSlice(f,0,h-e)):(b=f,f=[]);a=sjcl.mode.gcm.C(!1,a,f,d,c,e);if(!g.equal(a.tag,b))
throw new sjcl.exception.corrupt("gcm: tag doesn't match");return a.data},ka:function(a,b){var c,d,e,f,g,h=sjcl.bitArray
.i;e=[0,0,
0,0];f=b.slice(0);for(c=0;128>c;c++){(d=0!==(a[Math.floor(c/32)]&1<<31-c%32))&&(e=h(e,f));g=0!==(f[3]&1
);for(d=3;0<d;d--)f[d]=f[d]>>>1|(f[d-1]&1)<<31;f[0]>>>=1;g&&(f[0]^=-0x1f000000)}return e},
j:function(a,b,c){var d,e=c.length;b=b.slice(0);for(d=0;d<e;d+=4)b[0]^=0xffffffff&c[d],b[1]^=0xffffffff&c[d+1],b[2]^=
0xffffffff&c[d+2],b[3]^=0xffffffff&c[d+3],b=sjcl.mode.gcm.ka(b,a);return b},C:function(a,b,c,d,e,f){var g,h,k,l,n,m,p,r,
q=sjcl.bitArray;m=c.length;p=q.bitLength(c);r=q.bitLength(d);h=q.bitLength(e);
g=b.encrypt([0,0,0,0]);96===h?(e=e.slice(0),e=q.concat(e,[1])):(e=sjcl.mode.gcm.j(g,[0,0,0,0],e),e=sjcl.mode.gcm.j(g,e,[0,0,Math
.floor(h/0x100000000),h&0xffffffff]));h=sjcl.mode.gcm.j(g,[0,0,0,0],d);n=e.slice(0);d=h.slice(0);a||(d=sjcl.mode.gcm.j(g,h,c
));for(l=0;l<m;l+=4)n[3]++,k=b.encrypt(n),c[l]^=k[0],c[l+1]^=k[1],c[l+2]^=k[2],c[l+3]^=k[3];c=q.clamp(c,p);a&&(d=sjcl
.mode.gcm.j(g,h,c));a=[Math.floor(r/0x100000000),r&0xffffffff,Math.floor(p/0x100000000),p&0xffffffff];d=sjcl.mode.gcm.j(
g,d,a);k=b.encrypt(e);
d[0]^=k[0];d[1]^=k[1];d[2]^=k[2];d[3]^=k[3];return{tag:q.bitSlice(d,0,f),data:c}}};sjcl.misc.hmac=function(a,b){this.W=b=b||sjcl
.hash.sha256;var c=[[],[]],d,e=b.prototype.blockSize/32;this.w=[new b,new b];a.length>e&&(a=b.hash(a));for(d=0;d<e
;d++)c[0][d]=a[d]^909522486,c[1][d]=a[d]^1549556828;this.w[0].update(c[0]);this.w[1].update(c[1]);this.R=new b(this.w[0])};
sjcl.misc.hmac.prototype.encrypt=sjcl.misc.hmac.prototype.mac=function(a){if(this.aa)throw new sjcl.exception.invalid("encrypt
on already updated hmac called!");this.update(a);return this.digest(a)};sjcl.misc.hmac.prototype.reset=function(){this.R=new
this.W(this.w[0]);this.aa=!1};sjcl.misc.hmac.prototype.update=function(a){this.aa=!0;this.R.update(a)};sjcl.misc.hmac.prototype
.digest=function(){var a=this.R.finalize(),a=(new this.W(this.w[1])).update(a).finalize();this.reset();return a};
...
function(a){return t(this,a,0)}
...
sjcl.hash.sha256.prototype={blockSize:512,reset:function(){this.F=this.Y.slice(0);this.A=[];this.l=0;return this},update:function
(a){"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));var b,c=this.A=sjcl.bitArray.concat(this.A,a);b=this
.l;a=this.l=b+sjcl.bitArray.bitLength(a);if(0x1fffffffffffff<a)throw new sjcl.exception.invalid("Cannot hash more than 2
^53 - 1 bits");if("undefined"!==typeof Uint32Array){var d=new Uint32Array(c),e=0;for(b=512+b-(512+b&0x1ff);b&
lt;=a;b+=512)u(this,d.subarray(16*e,
16*(e+1))),e+=1;c.splice(0,16*e)}else for(b=512+b-(512+b&0x1ff);b<=a;b+=512)u(this,c.splice(0,16));return this},finalize:
function(){var a,b=this.A,c=this.F,b=sjcl.bitArray.concat(b,[sjcl.bitArray.partial(1,1)]);for(a=b.length+2;a&15;a++)b.push(0
);b.push(Math.floor(this.l/0x100000000));for(b.push(this.l|0);b.length;)u(this,b.splice(0,16));this.reset();return c},Y:[],b:[],
O:function(){function a(a){return 0x100000000*(a-Math.floor(a))|0}for(var b=0,c=2,d,e;64>b;c++){e=!0;for(d=2;d*d<=c;d++)if
(0===c%d){e=
!1;break}e&&(8>b&&(this.Y[b]=a(Math.pow(c,.5))),this.b[b]=a(Math.pow(c,1/3)),b++)}}};
function u(a,b){var c,d,e,f=a.F,g=a.b,h=f[0],k=f[1],l=f[2],n=f[3],m=f[4],p=f[5],r=f[6],q=f[7];for(c=0;64>c;c++)16>c?d=b[c]:(
d=b[c+1&15],e=b[c+14&15],d=b[c&15]=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>
;>17^e>>>19^e>>>10^e<<15^e<<13)+b[c&15]+b[c+9&15]|0),d=d+q+(m>>>6^m>>>
;11^m>>>25^m<<26^m<<21^m<<7)+(r^m&(p^r))+g[c],q=r,r=p,p=m,m=n+d|0,n=l,l=k,k=h,h=d+(k&l^n&(
k^l))+(k>>>2^k>>>13^k>>>22^k<<30^k<<19^k<<10)|0;f[0]=f[0]+h|0;f[1]=f[1]+k|0;f[2]=f[
2]+l|0;f[3]=f[3]+n|0;f[4]=f[4]+m|0;f[5]=f[5]+p|0;f[6]=f[6]+r|0;f[7]=
f[7]+q|0}
sjcl.mode.ccm={name:"ccm",G:[],listenProgress:function(a){sjcl.mode.ccm.G.push(a)},unListenProgress:function(a){a=sjcl
.mode.ccm.G.indexOf(a);-1<a&&sjcl.mode.ccm.G.splice(a,1)},fa:function(a){var b=sjcl.mode.ccm.G.slice(),c;for(c=0;c<
;b.length;c+=1)b[c](a)},encrypt:function(a,b,c,d,e){var f,g=b.slice(0),h=sjcl.bitArray,k=h.bitLength(c)/8,l=h.bitLength(g)/8;e=e
||64;d=d||[];if(7>k)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(f=2;4>f&&l&
gt;>>8*f;f++);f<15-k&&(f=15-k);c=h.clamp(c,
8*(15-f));b=sjcl.mode.ccm.V(a,b,c,d,e,f);g=sjcl.mode.ccm.C(a,g,c,b,e,f);return h.concat(g.data,g.tag)},decrypt:function(a,b,c,d,
e){e=e||64;d=d||[];var f=sjcl.bitArray,g=f.bitLength(c)/8,h=f.bitLength(b),k=f.clamp(b,h-e),l=f.bitSlice(b,h-e),h=(h-e)/8;if(7>
;g)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(b=2;4>b&&h>>>8*b;b++);
b<15-g&&(b=15-g);c=f.clamp(c,8*(15-b));k=sjcl.mode.ccm.C(a,k,c,l,e,b);a=sjcl.mode.ccm.V(a,k.data,c,d,e,b);if(!f.equal
(k.tag,a))throw new sjcl.exception.corrupt("ccm: tag doesn't match");
return k.data},na:function(a,b,c,d,e,f){var g=[],h=sjcl.bitArray,k=h.i;d=[h.partial(8,(b.length?64:0)|d-2<<2|f-1)];d=h.concat
(d,c);d[3]|=e;d=a.encrypt(d);if(b.length)for(c=h.bitLength(b)/8,65279>=c?g=[h.partial
(16,c)]:0xffffffff>=c&&(g=h.concat([h.partial(16,65534)],[c])),g=h.concat(g,b),b=0;b<g.length;b+=4)d=a.encrypt(k(d
,g.slice(b,b+4).concat([0,0,0])));return d},V:function(a,b,c,d,e,f){var g=sjcl.bitArray,h=g.i;e/=8;if(e%2||4>e||16<e)throw
new sjcl.exception.invalid("ccm: invalid tag length");
if(0xffffffff<d.length||0xffffffff<b.length)throw new sjcl.exception.bug("ccm: can't deal with 4GiB or more data
");c=sjcl.mode.ccm.na(a,d,c,e,g.bitLength(b)/8,f);for(d=0;d<b.length;d+=4)c=a.encrypt(h(c,b.slice(d,d+4).concat([0,0,0])));
return g.clamp(c,8*e)},C:function(a,b,c,d,e,f){var g,h=sjcl.bitArray;g=h.i;var k=b.length,l=h.bitLength(b),n=k/50,m=n;c=h.concat
([h.partial(8,f-1)],c).concat([0,0,0]).slice(0,4);d=h.bitSlice(g(d,a.encrypt(c)),0,e);if(!k)return{tag:d,data:[]};for(g=0;g<k
;g+=4)g>n&&(sjcl.mode.ccm.fa(g/
k),n+=m),c[3]++,e=a.encrypt(c),b[g]^=e[0],b[g+1]^=e[1],b[g+2]^=e[2],b[g+3]^=e[3];return{tag:d,data:h.clamp(b,l)}}};
sjcl.mode.ocb2={name:"ocb2",encrypt:function(a,b,c,d,e,f){if(128!==sjcl.bitArray.bitLength(c))throw new sjcl.exception
.invalid("ocb iv must be 128 bits");var g,h=sjcl.mode.ocb2.S,k=sjcl.bitArray,l=k.i,n=[0,0,0,0];c=h(a.encrypt(c));var m
,p=[];d=d||[];e=e||64;for(g=0;g+4<b.length;g+=4)m=b.slice(g,g+4),n=l(n,m),p=p.concat(l(c,a.encrypt(l(c,m)))),c=h(c);m=b.slice
(g);b=k.bitLength(m);g=a.encrypt(l(c,[0,0,0,b]));m=k.clamp(l(m.concat([0,0,0]),g),b);n=l(n,l(m.concat([0,0,0]),g));n=a.encrypt(l
(n,l(c,h(c))));
d.length&&(n=l(n,f?d:sjcl.mode.ocb2.pmac(a,d)));return p.concat(k.concat(m,k.clamp(n,e)))},decrypt:function(a,b,c,d,e,f){
if(128!==sjcl.bitArray.bitLength(c))throw new sjcl.exception.invalid("ocb iv must be 128 bits");e=e||64;var g=sjcl.mode
.ocb2.S,h=sjcl.bitArray,k=h.i,l=[0,0,0,0],n=g(a.encrypt(c)),m,p,r=sjcl.bitArray.bitLength(b)-e,q=[];d=d||[];for(c=0;c+4<r/32;
c+=4)m=k(n,a.decrypt(k(n,b.slice(c,c+4)))),l=k(l,m),q=q.concat(m),n=g(n);p=r-32*c;m=a.encrypt(k(n,[0,0,0,p]));m=k(m,h.clamp(b.slice
(c),p).concat([0,
0,0]));l=k(l,m);l=a.encrypt(k(l,k(n,g(n))));d.length&&(l=k(l,f?d:sjcl.mode.ocb2.pmac(a,d)));if(!h.equal(h.clamp(l,e),h.bitSlice
(b,r)))throw new sjcl.exception.corrupt("ocb: tag doesn't match");return q.concat(h.clamp(m,p))},pmac:function(a,
b){var c,d=sjcl.mode.ocb2.S,e=sjcl.bitArray,f=e.i,g=[0,0,0,0],h=a.encrypt([0,0,0,0]),h=f(h,d(d(h)));for(c=0;c+4<b.length;c+=4
)h=d(h),g=f(g,a.encrypt(f(h,b.slice(c,c+4))));c=b.slice(c);128>e.bitLength(c)&&(h=f(h,d(h)),c=e.concat(c,[-2147483648
,0,0,0]));g=f(g,c);
return a.encrypt(f(d(f(h,d(h))),g))},S:function(a){return[a[0]<<1^a[1]>>>31,a[1]<<1^a[2]>>>31,a[2]&
lt;<1^a[3]>>>31,a[3]<<1^135*(a[0]>>>31)]}};
sjcl.mode.gcm={name:"gcm",encrypt:function(a,b,c,d,e){var f=b.slice(0);b=sjcl.bitArray;d=d||[];a=sjcl.mode.gcm.C(!0,a,
f,d,c,e||128);return b.concat(a.data,a.tag)},decrypt:function(a,b,c,d,e){var f=b.slice(0),g=sjcl.bitArray,h=g.bitLength(f);e=e||
128;d=d||[];e<=h?(b=g.bitSlice(f,h-e),f=g.bitSlice(f,0,h-e)):(b=f,f=[]);a=sjcl.mode.gcm.C(!1,a,f,d,c,e);if(!g.equal(a.tag,b))
throw new sjcl.exception.corrupt("gcm: tag doesn't match");return a.data},ka:function(a,b){var c,d,e,f,g,h=sjcl.bitArray
.i;e=[0,0,
...
function(a){this.toString=function(){return"BUG: "+this.message};this.message=a}
...
16*(e+1))),e+=1;c.splice(0,16*e)}else for(b=512+b-(512+b&0x1ff);b<=a;b+=512)u(this,c.splice(0,16));return this},finalize:
function(){var a,b=this.A,c=this.F,b=sjcl.bitArray.concat(b,[sjcl.bitArray.partial(1,1)]);for(a=b.length+2;a&15;a++)b.push(0
);b.push(Math.floor(this.l/0x100000000));for(b.push(this.l|0);b.length;)u(this,b.splice(0,16));this.reset();return c},Y:[],b:[],
O:function(){function a(a){return 0x100000000*(a-Math.floor(a))|0}for(var b=0,c=2,d,e;64>b;c++){e=!0;for(d=2;d*d<=c;d++)if
(0===c%d){e=
!1;break}e&&(8>b&&(this.Y[b]=a(Math.pow(c,.5))),this.b[b]=a(Math.pow(c,1/3)),b++)}}};
function u(a,b){var c,d,e,f=a.F,g=a.b,h=f[0],k=f[1],l=f[2],n=f[3],m=f[4],p=f[5],r=f[6],q=f[7];for(c=0;64>c;c++)16>c?d=b[c]:(
d=b[c+1&15],e=b[c+14&15],d=b[c&15]=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>
;>17^e>>>19^e>>>10^e<<15^e<<13)+b[c&15]+b[c+9&15]|0),d=d+q+(m>>>6^m>>>
;11^m>>>25^m<<26^m<<21^m<<7)+(r^m&(p^r))+g[c],q=r,r=p,p=m,m=n+d|0,n=l,l=k,k=h,h=d+(k&l^n&(
k^l))+(k>>>2^k>>>13^k>>>22^k<<30^k<<19^k<<10)|0;f[0]=f[0]+h|0;f[1]=f[1]+k|0;f[2]=f[
2]+l|0;f[3]=f[3]+n|0;f[4]=f[4]+m|0;f[5]=f[5]+p|0;f[6]=f[6]+r|0;f[7]=
f[7]+q|0}
sjcl.mode.ccm={name:"ccm",G:[],listenProgress:function(a){sjcl.mode.ccm.G.push(a)},unListenProgress:function(a){a=sjcl
.mode.ccm.G.indexOf(a);-1<a&&sjcl.mode.ccm.G.splice(a,1)},fa:function(a){var b=sjcl.mode.ccm.G.slice(),c;for(c=0;c<
;b.length;c+=1)b[c](a)},encrypt:function(a,b,c,d,e){var f,g=b.slice(0),h=sjcl.bitArray,k=h.bitLength(c)/8,l=h.bitLength(g)/8;e=e
||64;d=d||[];if(7>k)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(f=2;4>f&&l&
gt;>>8*f;f++);f<15-k&&(f=15-k);c=h.clamp(c,
8*(15-f));b=sjcl.mode.ccm.V(a,b,c,d,e,f);g=sjcl.mode.ccm.C(a,g,c,b,e,f);return h.concat(g.data,g.tag)},decrypt:function(a,b,c,d,
e){e=e||64;d=d||[];var f=sjcl.bitArray,g=f.bitLength(c)/8,h=f.bitLength(b),k=f.clamp(b,h-e),l=f.bitSlice(b,h-e),h=(h-e)/8;if(7>
;g)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(b=2;4>b&&h>>>8*b;b++);
b<15-g&&(b=15-g);c=f.clamp(c,8*(15-b));k=sjcl.mode.ccm.C(a,k,c,l,e,b);a=sjcl.mode.ccm.V(a,k.data,c,d,e,b);if(!f.equal
(k.tag,a))throw new sjcl.exception.corrupt("ccm: tag doesn't match");
return k.data},na:function(a,b,c,d,e,f){var g=[],h=sjcl.bitArray,k=h.i;d=[h.partial(8,(b.length?64:0)|d-2<<2|f-1)];d=h.concat
(d,c);d[3]|=e;d=a.encrypt(d);if(b.length)for(c=h.bitLength(b)/8,65279>=c?g=[h.partial(16,c)]:0xffffffff>=c&&(g=h.concat
([h.partial(16,65534)],[c])),g=h.concat(g,b),b=0;b<g.length;b+=4)d=a.encrypt(k(d,g.slice(b,b+4).concat([0,0,0])));return d},V
:function(a,b,c,d,e,f){var g=sjcl.bitArray,h=g.i;e/=8;if(e%2||4>e||16<e)throw new sjcl.exception.invalid("ccm: invalid
tag length");
if(0xffffffff<d.length||0xffffffff<b.length)throw new sjcl.exception.bug("
ccm: can't deal with 4GiB or more data");c=sjcl.mode.ccm.na(a,d,c,e,g.bitLength(b)/8,f);for(d=0;d<b.length;d+=4)c=a
.encrypt(h(c,b.slice(d,d+4).concat([0,0,0])));return g.clamp(c,8*e)},C:function(a,b,c,d,e,f){var g,h=sjcl.bitArray;g=h.i;var k=b
.length,l=h.bitLength(b),n=k/50,m=n;c=h.concat([h.partial(8,f-1)],c).concat([0,0,0]).slice(0,4);d=h.bitSlice(g(d,a.encrypt(c)),0
,e);if(!k)return{tag:d,data:[]};for(g=0;g<k;g+=4)g>n&&(sjcl.mode.ccm.fa(g/
k),n+=m),c[3]++,e=a.encrypt(c),b[g]^=e[0],b[g+1]^=e[1],b[g+2]^=e[2],b[g+3]^=e[3];return{tag:d,data:h.clamp(b,l)}}};
sjcl.mode.ocb2={name:"ocb2",encrypt:function(a,b,c,d,e,f){if(128!==sjcl.bitArray.bitLength(c))throw new sjcl.exception
.invalid("ocb iv must be 128 bits");var g,h=sjcl.mode.ocb2.S,k=sjcl.bitArray,l=k.i,n=[0,0,0,0];c=h(a.encrypt(c));var m
,p=[];d=d||[];e=e||64;for(g=0;g+4<b.length;g+=4)m=b.slice(g,g+4),n=l(n,m),p=p.concat(l(c,a.encrypt(l(c,m)))),c=h(c);m=b.slice
(g);b=k.bitLength(m);g=a.encrypt(l(c,[0,0,0,b]));m=k.clamp(l(m.concat([0,0,0]),g),b);n=l(n,l(m.concat([0,0,0]),g));n=a.encrypt(l
(n,l(c,h(c))));
d.length&&(n=l(n,f?d:sjcl.mode.ocb2.pmac(a,d)));return p.concat(k.concat(m,k.clamp(n,e)))},decrypt:function(a,b,c,d,e,f){
if(128!==sjcl.bitArray.bitLength(c))throw new sjcl.exception.invalid("ocb iv must be 128 bits");e=e||64;var g=sjcl.mode
.ocb2.S,h=sjcl.bitArray,k=h.i,l=[0,0,0,0],n=g(a.encrypt(c)),m,p,r=sjcl.bitArray.bitLength(b)-e,q=[];d=d||[];for(c=0;c+4<r/32;
c+=4)m=k(n,a.decrypt(k(n,b.slice(c,c+4)))),l=k(l,m),q=q.concat(m),n=g(n);p=r-32*c;m=a.encrypt(k(n,[0,0,0,p]));m=k(m,h.clamp(b.slice
(c),p).concat([0,
0,0]));l=k(l,m);l=a.encrypt(k(l,k(n,g(n))));d.length&&(l=k(l,f?d:sjcl.mode.ocb2.pmac(a,d)));if(!h.equal(h.clamp(l,e),h.bitSlice
(b,r)))throw new sjcl.exception.corrupt("ocb: tag doesn't match");return q.concat(h.clamp(m,p))},pmac:function(a,
b){var c,d=sjcl.mode.ocb2.S,e=sjcl.bitArray,f=e.i,g=[0,0,0,0],h=a.encrypt([0,0,0,0]),h=f(h,d(d(h)));for(c=0;c+4<b.length;c+=4
)h=d(h),g=f(g,a.encrypt(f(h,b.slice(c,c+4))));c=b.slice(c);128>e.bitLength(c)&&(h=f(h,d(h)),c=e.concat(c,[-2147483648
,0,0,0]));g=f(g,c);
return a.encrypt(f(d(f(h,d(h))),g))},S:function(a){return[a[0]<<1^a[1]>>>31,a[1]<<1^a[2]>>>31,a[2]&
lt;<1^a[3]>>>31,a[3]<<1^135*(a[0]>>>31)]}};
sjcl.mode.gcm={name:"gcm",encrypt:function(a,b,c,d,e){var f=b.slice(0);b=sjcl.bitArray;d=d||[];a=sjcl.mode.gcm.C(!0,a,
f,d,c,e||128);return b.concat(a.data,a.tag)},decrypt:function(a,b,c,d,e){var f=b.slice(0),g=sjcl.bitArray,h=g.bitLength(f);e=e||
128;d=d||[];e<=h?(b=g.bitSlice(f,h-e),f=g.bitSlice(f,0,h-e)):(b=f,f=[]);a=sjcl.mode.gcm.C(!1,a,f,d,c,e);if(!g.equal(a.tag,b))
throw new sjcl.exception.corrupt("gcm: tag doesn't match");return a.data},ka:function(a,b){var c,d,e,f,g,h=sjcl.bitArray
.i;e=[0,0,
0,0];f=b.slice(0);for(c=0;128>c;c++){(d=0!==(a[Math.floor(c/32)]&1<<31-c%32))&&(e=h(e,f));g=0!==(f[3]&1
);for(d=3;0<d;d--)f[d]=f[d]>>>1|(f[d-1]&1)<<31;f[0]>>>=1;g&&(f[0]^=-0x1f000000)}return e},
j:function(a,b,c){var d,e=c.length;b=b.slice(0);for(d=0;d<e;d+=4)b[0]^=0xffffffff&c[d],b[1]^=0xffffffff&c[d+1],b[2]^=
0xffffffff&c[d+2],b[3]^=0xffffffff&c[d+3],b=sjcl.mode.gcm.ka(b,a);return b},C:function(a,b,c,d,e,f){var g,h,k,l,n,m,p,r,
q=sjcl.bitArray;m=c.length;p=q.bitLength(c);r=q.bitLength(d);h=q.bitLength(e);
...
function(a){this.toString=function(){return"CORRUPT: "+this.message};this.message=a}
...
if(0>h)throw new sjcl.exception.invalid("this isn't base64!");26<e?(e-=26,c.push(g^h>>>e),g=h<&
lt;32-e):(e+=6,g^=h<<32-e)}e&56&&c.push(sjcl.bitArray.partial(e&56,g,1));return c}};sjcl.codec.base64url={
fromBits:function(a){return sjcl.codec.base64.fromBits(a,1,1)},toBits:function(a){return sjcl.codec.base64.toBits(a,1)}};sjcl.hash
.sha256=function(a){this.b[0]||this.O();a?(this.F=a.F.slice(0),this.A=a.A.slice(0),this.l=a.l):this.reset()};sjcl.hash.sha256.hash
=function(a){return(new sjcl.hash.sha256).update(a).finalize()};
sjcl.hash.sha256.prototype={blockSize:512,reset:function(){this.F=this.Y.slice(0);this.A=[];this.l=0;return this},update:function
(a){"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));var b,c=this.A=sjcl.bitArray.concat(this.A,a);b=this
.l;a=this.l=b+sjcl.bitArray.bitLength(a);if(0x1fffffffffffff<a)throw new sjcl.exception.invalid("Cannot hash more than 2
^53 - 1 bits");if("undefined"!==typeof Uint32Array){var d=new Uint32Array(c),e=0;for(b=512+b-(512+b&0x1ff);b&
lt;=a;b+=512)u(this,d.subarray(16*e,
16*(e+1))),e+=1;c.splice(0,16*e)}else for(b=512+b-(512+b&0x1ff);b<=a;b+=512)u(this,c.splice(0,16));return this},finalize:
function(){var a,b=this.A,c=this.F,b=sjcl.bitArray.concat(b,[sjcl.bitArray.partial(1,1)]);for(a=b.length+2;a&15;a++)b.push(0
);b.push(Math.floor(this.l/0x100000000));for(b.push(this.l|0);b.length;)u(this,b.splice(0,16));this.reset();return c},Y:[],b:[],
O:function(){function a(a){return 0x100000000*(a-Math.floor(a))|0}for(var b=0,c=2,d,e;64>b;c++){e=!0;for(d=2;d*d<=c;d++)if
(0===c%d){e=
!1;break}e&&(8>b&&(this.Y[b]=a(Math.pow(c,.5))),this.b[b]=a(Math.pow(c,1/3)),b++)}}};
function u(a,b){var c,d,e,f=a.F,g=a.b,h=f[0],k=f[1],l=f[2],n=f[3],m=f[4],p=f[5],r=f[6],q=f[7];for(c=0;64>c;c++)16>c?d=b[c]:(
d=b[c+1&15],e=b[c+14&15],d=b[c&15]=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>
;>17^e>>>19^e>>>10^e<<15^e<<13)+b[c&15]+b[c+9&15]|0),d=d+q+(m>>>6^m>>>
;11^m>>>25^m<<26^m<<21^m<<7)+(r^m&(p^r))+g[c],q=r,r=p,p=m,m=n+d|0,n=l,l=k,k=h,h=d+(k&l^n&(
k^l))+(k>>>2^k>>>13^k>>>22^k<<30^k<<19^k<<10)|0;f[0]=f[0]+h|0;f[1]=f[1]+k|0;f[2]=f[
2]+l|0;f[3]=f[3]+n|0;f[4]=f[4]+m|0;f[5]=f[5]+p|0;f[6]=f[6]+r|0;f[7]=
f[7]+q|0}
sjcl.mode.ccm={name:"ccm",G:[],listenProgress:function(a){sjcl.mode.ccm.G.push(a)},unListenProgress:function(a){a=sjcl
.mode.ccm.G.indexOf(a);-1<a&&sjcl.mode.ccm.G.splice(a,1)},fa:function(a){var b=sjcl.mode.ccm.G.slice(),c;for(c=0;c<
;b.length;c+=1)b[c](a)},encrypt:function(a,b,c,d,e){var f,g=b.slice(0),h=sjcl.bitArray,k=h.bitLength(c)/8,l=h.bitLength(g)/8;e=e
||64;d=d||[];if(7>k)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(f=2;4>f&&l&
gt;>>8*f;f++);f<15-k&&(f=15-k);c=h.clamp(c,
8*(15-f));b=sjcl.mode.ccm.V(a,b,c,d,e,f);g=sjcl.mode.ccm.C(a,g,c,b,e,f);return h.concat(g.data,g.tag)},decrypt:function(a,b,c,d,
e){e=e||64;d=d||[];var f=sjcl.bitArray,g=f.bitLength(c)/8,h=f.bitLength(b),k=f.clamp(b,h-e),l=f.bitSlice(b,h-e),h=(h-e)/8;if(7>
;g)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(b=2;4>b&&h>>>8*b;b++);
b<15-g&&(b=15-g);c=f.clamp(c,8*(15-b));k=sjcl.mode.ccm.C(a,k,c,l,e,b);a=sjcl.mode.ccm.V(a,k.data,c,d,e,b);if(!f.equal
(k.tag,a))throw new sjcl.exception.corrupt("ccm: tag doesn't match");
return k.data},na:function(a,b,c,d,e,f){var g=[],h=sjcl.bitArray,k=h.i;d=[h.partial(8,(b.length?64:0)|d-2<<2|f-1)];d=h.concat
(d,c);d[3]|=e;d=a.encrypt(d);if(b.length)for(c=h.bitLength(b)/8,65279>=c?g=[h.partial(16,c)]:0xffffffff>=c&&(g=h.concat
([h.partial(16,65534)],[c])),g=h.concat(g,b),b=0;b<g.length;b+=4)d=a.encrypt(k(d,g.slice(b,b+4).concat([0,0,0])));return d},V
:function(a,b,c,d,e,f){var g=sjcl.bitArray,h=g.i;e/=8;if(e%2||4>e||16<e)throw new sjcl.exception.invalid("ccm: invalid
tag length");
if(0xffffffff<d.length||0xffffffff<b.length)throw new sjcl.exception.bug("ccm: can't deal with 4GiB or more data
");c=sjcl.mode.ccm.na(a,d,c,e,g.bitLength(b)/8,f);for(d=0;d<b.length;d+=4)c=a.encrypt(h(c,b.slice(d,d+4).concat([0,0,0])));
return g.clamp(c,8*e)},C:function(a,b,c,d,e,f){var g,h=sjcl.bitArray;g=h.i;var k=b.length,l=h.bitLength(b),n=k/50,m=n;c=h.concat
([h.partial(8,f-1)],c).concat([0,0,0]).slice(0,4);d=h.bitSlice(g(d,a.encrypt(c)),0,e);if(!k)return{tag:d,data:[]};for(g=0;g<k
;g+=4)g>n&&(sjcl.mode.ccm.fa(g/
k),n+=m),c[3]++,e=a.encrypt(c),b[g]^=e[0],b[g+1]^=e[1],b[g+2]^=e[2],b[g+3]^=e[3];return{tag:d,data:h.clamp(b,l)}}};
sjcl.mode.ocb2={name:"ocb2",encrypt:function(a,b,c,d,e,f){if(128!==sjcl.bitArray.bitLength(c))throw new sjcl.exception
.invalid("ocb iv must be 128 bits");var g,h=sjcl.mode.ocb2.S,k=sjcl.bitArray,l=k.i,n=[0,0,0,0];c=h(a.encrypt(c));var m
,p=[];d=d||[];e=e||64;for(g=0;g+4<b.length;g+=4)m=b.slice(g,g+4),n=l(n,m),p=p.concat(l(c,a.encrypt(l(c,m)))),c=h(c);m=b.slice
(g);b=k.bitLength(m);g=a.encrypt(l(c,[0,0,0,b]));m=k.clamp(l(m.concat([0,0,0]),g),b);n=l(n,l(m.concat([0,0,0]),g));n=a.encrypt(l
(n,l(c,h(c))));
d.length&&(n=l(n,f?d:sjcl.mode.ocb2.pmac(a,d)));return p.concat(k.concat(m,k.clamp(n,e)))},decrypt:function(a,b,c,d,e,f){
if(128!==sjcl.bitArray.bitLength(c))throw new sjcl.exception.invalid("ocb iv must be 128 bits");e=e||64;var g=sjcl.mode
.ocb2.S,h=sjcl.bitArray,k=h.i,l=[0,0,0,0],n=g(a.encrypt(c)),m,p,r=sjcl.bitArray.bitLength(b)-e,q=[];d=d||[];for(c=0;c+4<r/32;
c+=4)m=k(n,a.decrypt(k(n,b.slice(c,c+4)))),l=k(l,m),q=q.concat(m),n=g(n);p=r-32*c;m=a.encrypt(k(n,[0,0,0,p]));m=k(m,h.clamp(b.slice
(c),p).concat([0,
0,0]));l=k(l,m);l=a.encrypt(k(l,k(n,g(n))));d.length&&(l=k(l,f?d:sjcl.mode.ocb2.pmac(a,d)));if(!h.equal(h.clamp(l,e),h.bitSlice
(b,r)))throw new sjcl.exception.corrupt("ocb: tag doesn't match");return q.concat(h.clamp(m,p))},pmac:function(a,
b){var c,d=sjcl.mode.ocb2.S,e=sjcl.bitArray,f=e.i,g=[0,0,0,0],h=a.encrypt([0,0,0,0]),h=f(h,d(d(h)));for(c=0;c+4<b.length;c+=4
)h=d(h),g=f(g,a.encrypt(f(h,b.slice(c,c+4))));c=b.slice(c);128>e.bitLength(c)&&(h=f(h,d(h)),c=e.concat(c,[-2147483648
,0,0,0]));g=f(g,c);
return a.encrypt(f(d(f(h,d(h))),g))},S:function(a){return[a[0]<<1^a[1]>>>31,a[1]<<1^a[2]>>>31,a[2]&
lt;<1^a[3]>>>31,a[3]<<1^135*(a[0]>>>31)]}};
...
function(a){this.toString=function(){return"INVALID: "+this.message};this.message=a}
...
file https://github.com/bitwiseshiftleft/sjcl/blob/1.0.8/sjcl.js
shGithubDateCommitted https://github.com/bitwiseshiftleft/sjcl/blob/1.0.8/sjcl.js # 2017-07-04T08:55:03Z
curl https://raw.githubusercontent.com/bitwiseshiftleft/sjcl/1.0.8/sjcl.js > /tmp/aa.js
*/
/* jslint ignore:start */
(function () { var module;
"use strict";var sjcl={cipher:{},hash:{},keyexchange:{},mode:{},misc:{},codec:{},exception:{corrupt:function(a){this.toString
=function(){return"CORRUPT: "+this.message};this.message=a},invalid:function(a){this.toString=function(){return"INVALID
: "+this.message};this.message=a},bug:function(a){this.toString=function(){return"BUG: "+this.message};this.message
=a},notReady:function(a){this.toString=function(){return"NOT READY: "+this.message};this.message=a}}};
sjcl.cipher.aes=function(a){this.s[0][0][0]||this.O();var b,c,d,e,f=this.s[0][4],g=this.s[1];b=a.length;var h=1;if(4!==b&&
;6!==b&&8!==b)throw new sjcl.exception.invalid("invalid aes key size"
;);this.b=[d=a.slice(0),e=[]];for(a=b;a<4*b+28;a++){c=d[a-1];if(0===a%b||8===b&&4===a%b)c=f[c>>>24]<<24
^f[c>>16&255]<<16^f[c>>8&255]<<8^f[c&255],0===a%b&&(c=c<<8^c>>>24^h<
;<24,h=h<<1^283*(h>>7));d[a]=d[a-b]^c}for(b=0;a;b++,a--)c=d[b&3?a:a-4],e[b]=4>=a||4>b?c:g[0][f[c>>
;>24]]^g[1][f[c>>16&255]]^g[2][f[c>>8&255]]^g[3][f[c&
255]]};
sjcl.cipher.aes.prototype={encrypt:function(a){return t(this,a,0)},decrypt:function(a){return t(this,a,1)},s:[[[],[],[],[],[]],[[],[],[],[],[]]],
O:function(){var a=this.s[0],b=this.s[1],c=a[4],d=b[4],e,f,g,h=[],k=[],l,n,m,p;for(e=0;0x100>e;e++)k[(h[e]=e<<1^283*(e&
gt;>7))^e]=e;for(f=g=0;!c[f];f^=l||1,g=k[g]||1)for(m=g^g<<1^g<<2^g<<3^g<<4,m=m>>8^m&255^99,
c[f]=m,d[m]=f,n=h[e=h[l=h[f]]],p=0x1010101*n^0x10001*e^0x101*l^0x1010100*f,n=0x101*h[m]^0x1010100*m,e=0;4>e;e++)a[e][f]=n=n<
;<24^n>>>8,b[e][m]=p=p<<24^p>>>8;for(e=
0;5>e;e++)a[e]=a[e].slice(0),b[e]=b[e].slice(0)}};
function t(a,b,c){if(4!==b.length)throw new sjcl.exception.invalid("invalid aes block size");var d=a.b[c],e=b[0]^d[0],
f=b[c?3:1]^d[1],g=b[2]^d[2];b=b[c?1:3]^d[3];var h,k,l,n=d.length/4-2,m,p=4,r=[0,0,0,0];h=a.s[c];a=h[0];var q=h[1],v=h[2],w=h[3],
x=h[4];for(m=0;m<n;m++)h=a[e>>>24]^q[f>>16&255]^v[g>>8&255]^w[b&255]^d[p],k=a[f>>>24
]^q[g>>16&255]^v[b>>8&255]^w[e&255]^d[p+1],l=a[g>>>24]^q[b>>16&255]^v[e>>8&
255]^w[f&255]^d[p+2],b=a[b>>>24]^q[e>>16&255]^v[f>>8&255]^w[g&255]^d[p+3],p+=4,e=h,f=k,g=l;
for(m=
0;4>m;m++)r[c?3&-m:m]=x[e>>>24]<<24^x[f>>16&255]<<16^x[g>>8&255]<<8^x[b&
;255]^d[p++],h=e,e=f,f=g,g=b,b=h;return r}
sjcl.bitArray={bitSlice:function(a,b,c){a=sjcl.bitArray.$(a.slice(b/32),32-(b&31)).slice(1);return void 0===c?a:sjcl.bitArray
.clamp(a,c-b)},extract:function(a,b,c){var d=Math.floor(-b-c&31);return((b+c-1^b)&-32?a[b/32|0]<<32-d^a[b/32+1|0]&
gt;>>d:a[b/32|0]>>>d)&(1<<c)-1},concat:function(a,b){if(0===a.length||0===b.length)return a.concat(b);var
c=a[a.length-1],d=sjcl.bitArray.getPartial(c);return 32===d?a.concat(b):sjcl.bitArray.$(b,d,c|0,a.slice(0,a.length-1))},bitLength
:function(a){var b=a.length;return 0===
b?0:32*(b-1)+sjcl.bitArray.getPartial(a[b-1])},clamp:function(a,b){if(32*a.length<b)return a;a=a.slice(0,Math.ceil(b/32));var
c=a.length;b=b&31;0<c&&b&&(a[c-1]=sjcl.bitArray.partial(b,a[c-1]&2147483648>>b-1,1));return a},
partial:function(a,b,c){return 32===a?b:(c?b|0:b<<32-a)+0x10000000000*a},getPartial:function(a){return Math.round(a/0x10000000000
)||32},equal:function(a,b){if(sjcl.bitArray.bitLength(a)!==sjcl.bitArray.bitLength(b))return!1;var c=0,d;for(d=0;d<a.length;d
++)c|=a[d]^b[d];return 0===
...
function(a){this.toString=function(){return"NOT READY: "+this.message};this.message=a}
...
sjcl.mode.gcm={name:"gcm",encrypt:function(a,b,c,d,e){var f=b.slice(0);b=sjcl.bitArray;d=d||[];a=sjcl.mode.gcm.C(!0,a,
f,d,c,e||128);return b.concat(a.data,a.tag)},decrypt:function(a,b,c,d,e){var f=b.slice(0),g=sjcl.bitArray,h=g.bitLength(f);e=e||
128;d=d||[];e<=h?(b=g.bitSlice(f,h-e),f=g.bitSlice(f,0,h-e)):(b=f,f=[]);a=sjcl.mode.gcm.C(!1,a,f,d,c,e);if(!g.equal(a.tag,b))
throw new sjcl.exception.corrupt("gcm: tag doesn't match");return a.data},ka:function(a,b){var c,d,e,f,g,h=sjcl.bitArray
.i;e=[0,0,
0,0];f=b.slice(0);for(c=0;128>c;c++){(d=0!==(a[Math.floor(c/32)]&1<<31-c%32))&&(e=h(e,f));g=0!==(f[3]&1
);for(d=3;0<d;d--)f[d]=f[d]>>>1|(f[d-1]&1)<<31;f[0]>>>=1;g&&(f[0]^=-0x1f000000)}return e},
j:function(a,b,c){var d,e=c.length;b=b.slice(0);for(d=0;d<e;d+=4)b[0]^=0xffffffff&c[d],b[1]^=0xffffffff&c[d+1],b[2]^=
0xffffffff&c[d+2],b[3]^=0xffffffff&c[d+3],b=sjcl.mode.gcm.ka(b,a);return b},C:function(a,b,c,d,e,f){var g,h,k,l,n,m,p,r,
q=sjcl.bitArray;m=c.length;p=q.bitLength(c);r=q.bitLength(d);h=q.bitLength(e);
g=b.encrypt([0,0,0,0]);96===h?(e=e.slice(0),e=q.concat(e,[1])):(e=sjcl.mode.gcm.j(g,[0,0,0,0],e),e=sjcl.mode.gcm.j(g,e,[0,0,Math
.floor(h/0x100000000),h&0xffffffff]));h=sjcl.mode.gcm.j(g,[0,0,0,0],d);n=e.slice(0);d=h.slice(0);a||(d=sjcl.mode.gcm.j(g,h,c
));for(l=0;l<m;l+=4)n[3]++,k=b.encrypt(n),c[l]^=k[0],c[l+1]^=k[1],c[l+2]^=k[2],c[l+3]^=k[3];c=q.clamp(c,p);a&&(d=sjcl
.mode.gcm.j(g,h,c));a=[Math.floor(r/0x100000000),r&0xffffffff,Math.floor(p/0x100000000),p&0xffffffff];d=sjcl.mode.gcm.j(
g,d,a);k=b.encrypt(e);
d[0]^=k[0];d[1]^=k[1];d[2]^=k[2];d[3]^=k[3];return{tag:q.bitSlice(d,0,f),data:c}}};sjcl.misc.hmac=function(a,b){this.W=b=b||sjcl
.hash.sha256;var c=[[],[]],d,e=b.prototype.blockSize/32;this.w=[new b,new b];a.length>e&&(a=b.hash(a));for(d=0;d<e
;d++)c[0][d]=a[d]^909522486,c[1][d]=a[d]^1549556828;this.w[0].update(c[0]);this.w[1].update(c[1]);this.R=new b(this.w[0])};
sjcl.misc.hmac.prototype.encrypt=sjcl.misc.hmac.prototype.mac=function(a){if(this.aa)throw new sjcl.exception.invalid("encrypt
on already updated hmac called!");this.update(a);return this.digest(a)};sjcl.misc.hmac.prototype.reset=function(){this.R=new
this.W(this.w[0]);this.aa=!1};sjcl.misc.hmac.prototype.update=function(a){this.aa=!0;this.R.update(a)};sjcl.misc.hmac.prototype
.digest=function(){var a=this.R.finalize(),a=(new this.W(this.w[1])).update(a).finalize();this.reset();return a};
sjcl.misc.pbkdf2=function(a,b,c,d,e){c=c||1E4;if(0>d||0>c)throw new sjcl.exception.invalid("invalid params to pbkdf2&
quot;);"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));"string"===typeof b&&(b=sjcl
.codec.utf8String.toBits(b));e=e||sjcl.misc.hmac;a=new e(a);var f,g,h,k,l=[],n=sjcl.bitArray;for(k=1;32*l.length<(d||1);k++){
e=f=a.encrypt(n.concat(b,[k]));for(g=1;g<c;g++)for(f=a.encrypt(f),h=0;h<f.length;h++)e[h]^=f[h];l=l.concat(e)}d&&(
l=n.clamp(l,d));return l};
sjcl.prng=function(a){this.c=[new sjcl.hash.sha256];this.m=[0];this.P=0;this.H={};this.N=0;this.U={};this.Z=this.f=this.o=this.ha
=0;this.b=[0,0,0,0,0,0,0,0];this.h=[0,0,0,0];this.L=void 0;this.M=a;this.D=!1;this.K={progress:{},seeded:{}};this.u=this.ga=0;this
.I=1;this.J=2;this.ca=0x10000;this.T=[0,48,64,96,128,192,0x100,384,512,768,1024];this.da=3E4;this.ba=80};
sjcl.prng.prototype={randomWords:function(a,b){var c=[],d;d=this.isReady(b);var e;if(d===this.u)throw new sjcl.exception.notReady("generator isn't seeded");if(d&this.J){d=!(d&this.I);e=[];var f=
0,g;this.Z=e[0]=(new Date).valueOf()+this.da;for(g=0;16>g;g++)e.push(0x100000000*Math.random()|0);for(g=0;g<this.c.length&
amp;&(e=e.concat(this.c[g].finalize()),f+=this.m[g],this.m[g]=0,d||!(this.P&1<<g));g++);this.P>=1<<this.c
.length&&(this.c.push(new sjcl.hash.sha256),this.m.push(0));this.f-=f;f>this.o&&(this.o=
f);this.P++;this.b=sjcl.hash.sha256.hash(this.b.concat(e));this.L=new sjcl.cipher.aes(this.b);for(d=0;4>d&&(this.h[d]=
this.h[d]+1|0,!this.h[d]);d++);}for(d=0;d<a;d+=4)0===(d+1)%this.ca&&y(this),e=z(this),c.push(e[0],e[1],e[2],e[3]);y(this
);return c.slice(0,a)},setDefaultParanoia:function(a,b){if(0===a&&"Setting paranoia=0 will ruin your security; use
it only for testing"!==b)throw new sjcl.exception.invalid("Setting paranoia=0 will ruin your security; use it only for
testing");this.M=a},addEntropy:function(a,
b,c){c=c||"user";var d,e,f=(new Date).valueOf(),g=this.H[c],h=this.isReady(),k=0;d=this.U[c];void 0===d&&(d=this
.U[c]=this.ha++);void 0===g&&(g=this.H[c]=0);this.H[c]=(this.H[c]+1)%this.c.length;switch(typeof a){case "number"
;:void 0===b&&(b=1);this.c[g].update([d,this.N++,1,b,f,1,a|0]);break;case "object":c=Object.prototype.toString
.call(a);if("[object Uint32Array]"===c){e=[];for(c=0;c<a.length;c++)e.push(a[c]);a=e}else for("[object Array]&
quot;!==c&&(k=1),c=0;c<a.length&&!k;c++)"number"!==typeof a[c]&&
(k=1);if(!k){if(void 0===b)for(c=b=0;c<a.length;c++)for(e=a[c];0<e;)b++,e=e>>>1;this.c[g].update([d,this.N++,2,b,
f,a.length].concat(a))}break;case "string":void 0===b&&(b=a.length);this.c[g].update([d,this.N++,3,b,f,a.length
]);this.c[g].update(a);break;default:k=1}if(k)throw new sjcl.exception.bug("random: addEntropy only supports number, array
of numbers or string");this.m[g]+=b;this.f+=b;h===this.u&&(this.isReady()!==this.u&&A("seeded",Math
.max(this.o,this.f)),A("progress",this.getProgress()))},
isReady:function(a){a=this.T[void 0!==a?a:this.M];return this.o&&this.o>=a?this.m[0]>this.ba&&(new Date).valueOf
()>this.Z?this.J|this.I:this.I:this.f>=a?this.J|this.u:this.u},getProgress:function(a){a=this.T[a?a:this.M];return this.o&
gt;=a?1:this.f>a?1:this.f/a},startCollectors:function(){if(!this.D){this.a={loadTimeCollector:B(this,this.ma),mouseCollector:
B(this,this.oa),keyboardCollector:B(this,this.la),accelerometerCollector:B(this,this.ea),touchCollector:B(this,this.qa)};if(window
.addEventListener)window.addEventListener("load",
this.a.loadTimeCollector,!1),window.addEventListener("mousemove",this.a.mouseCollector,!1),window.addEventListener("
;keypress",this.a.keyboardCollector,!1),window.addEventListener("devicemotion",this.a.accelerometerCollector,!1),
window.addEventListener("touchmove",this.a.touchCollector,!1);else if(document.attachEvent)document.attachEvent("
onload",this.a.loadTimeCollector),document.attachEvent("onmousemove",this.a.mouseCollector),document.attachEvent(&
quot;keypress",this.a.keyboardCollector);else throw new sjcl.exception.bug("can't attach event");
this.D=!0}},stopCollectors:function(){this.D&&(window.removeEventListener?(window.removeEventListener("load",this
.a.loadTimeCollector,!1),window.removeEventListener("mousemove",this.a.mouseCollector,!1),window.removeEventListener(&
quot;keypress",this.a.keyboardCollector,!1),window.removeEventListener("devicemotion",this.a.accelerometerCollector
,!1),window.removeEventListener("touchmove",this.a.touchCollector,!1)):document.detachEvent&&(document.detachEvent
("onload",this.a.loadTimeCollector),document.detachEvent("onmousemove",
this.a.mouseCollector),document.detachEvent("keypress",this.a.keyboardCollector)),this.D=!1)},addEventListener:function
(a,b){this.K[a][this.ga++]=b},removeEventListener:function(a,b){var c,d,e=this.K[a],f=[];for(d in e)e.hasOwnProperty(d)&&
;e[d]===b&&f.push(d);for(c=0;c<f.length;c++)d=f[c],delete e[d]},la:function(){C(this,1)},oa:function(a){var b,c;try{b
=a.x||a.clientX||a.offsetX||0,c=a.y||a.clientY||a.offsetY||0}catch(d){c=b=0}0!=b&&0!=c&&this.addEntropy([b,c],2,&
quot;mouse");C(this,0)},qa:function(a){a=
...
sha1 = function (hash) { if (hash) { this._h = hash._h.slice(0); this._buffer = hash._buffer.slice(0); this._length = hash._length; } else { this.reset(); } }
...
/**
* Hash a string or an array of words.
* @static
* @param {bitArray|String} data the data to hash.
* @return {bitArray} The hash value, an array of 5 big-endian words.
*/
sjcl.hash.sha1.hash = function (data) {
return (new sjcl.hash.sha1()).update(data).finalize();
};
sjcl.hash.sha1.prototype = {
/**
* The hash's block size, in bits.
* @constant
*/
...
function(a){this.b[0]||this.O();a?(this.F=a.F.slice(0),this.A=a.A.slice(0),this.l=a.l):this.reset()}
n/a
function(n, x) { return (x << n) | (x >>> 32-n); }
...
w = words;
}
a = h[0]; b = h[1]; c = h[2]; d = h[3]; e = h[4];
for (t=0; t<=79; t++) {
if (t >= 16) {
w[t] = this._S(1, w[t-3] ^ w[t-8] ^ w[t-14] ^ w[t-16]);
}
tmp = (this._S(5, a) + this._f(t, b, c, d) + e + w[t] +
this._key[Math.floor(t/20)]) | 0;
e = d;
d = c;
c = this._S(30, b);
b = a;
...
_block = function (words) { var t, tmp, a, b, c, d, e, h = this._h; var w; if (typeof Uint32Array !== 'undefined') { // When words is passed to _block, it has 16 elements. SHA1 _block // function extends words with new elements (at the end there are 80 elements). // The problem is that if we use Uint32Array instead of Array, // the length of Uint32Array cannot be changed. Thus, we replace words with a // normal Array here. w = Array(80); // do not use Uint32Array here as the instantiation is slower for (var j=0; j<16; j++){ w[j] = words[j]; } } else { w = words; } a = h[0]; b = h[1]; c = h[2]; d = h[3]; e = h[4]; for (t=0; t<=79; t++) { if (t >= 16) { w[t] = this._S(1, w[t-3] ^ w[t-8] ^ w[t-14] ^ w[t-16]); } tmp = (this._S(5, a) + this._f(t, b, c, d) + e + w[t] + this._key[Math.floor(t/20)]) | 0; e = d; d = c; c = this._S(30, b); b = a; a = tmp; } h[0] = (h[0]+a) |0; h[1] = (h[1]+b) |0; h[2] = (h[2]+c) |0; h[3] = (h[3]+d) |0; h[4] = (h[4]+e) |0; }
...
}
if (typeof Uint32Array !== 'undefined') {
var c = new Uint32Array(b);
var j = 0;
for (i = this.blockSize+ol - ((this.blockSize+ol) & (this.blockSize-1)); i <= nl;
i+= this.blockSize) {
this._block(c.subarray(16 * j, 16 * (j+1)));
j += 1;
}
b.splice(0, 16 * j);
} else {
for (i = this.blockSize+ol - ((this.blockSize+ol) & (this.blockSize-1)); i <= nl;
i+= this.blockSize) {
this._block(b.splice(0,16));
...
function(t, b, c, d) { if (t <= 19) { return (b & c) | (~b & d); } else if (t <= 39) { return b ^ c ^ d; } else if (t <= 59) { return (b & c) | (b & d) | (c & d); } else if (t <= 79) { return b ^ c ^ d; } }
...
a = h[0]; b = h[1]; c = h[2]; d = h[3]; e = h[4];
for (t=0; t<=79; t++) {
if (t >= 16) {
w[t] = this._S(1, w[t-3] ^ w[t-8] ^ w[t-14] ^ w[t-16]);
}
tmp = (this._S(5, a) + this._f(t, b, c, d) + e + w[t] +
this._key[Math.floor(t/20)]) | 0;
e = d;
d = c;
c = this._S(30, b);
b = a;
a = tmp;
}
...
finalize = function () { var i, b = this._buffer, h = this._h; // Round out and push the buffer b = sjcl.bitArray.concat(b, [sjcl.bitArray.partial(1,1)]); // Round out the buffer to a multiple of 16 words, less the 2 length words. for (i = b.length + 2; i & 15; i++) { b.push(0); } // append the length b.push(Math.floor(this._length / 0x100000000)); b.push(this._length | 0); while (b.length) { this._block(b.splice(0,16)); } this.reset(); return h; }
...
c},$:function(a,b,c,d){var e;e=0;for(void 0===d&&(d=[]);32<=b;b-=32)d.push(c),c=0;if(0===b)return d.concat(a);for(e=0
;e<a.length;e++)d.push(c|a[e]>>>b),c=a[e]<<32-b;e=a.length?a[a.length-1]:0;a=sjcl.bitArray.getPartial(e);d.push
(sjcl.bitArray.partial(b+a&31,32<b+a?c:d.pop(),1));return d},i:function(a,b){return[a[0]^b[0],a[1]^b[1],a[2]^b[2],a[3]^b[
3]]},byteswapM:function(a){var b,c;for(b=0;b<a.length;++b)c=a[b],a[b]=c>>>24|c>>>8&0xff00|(c&0xff00
)<<8|c<<24;return a}};
sjcl.codec.utf8String={fromBits:function(a){var b="",c=sjcl.bitArray.bitLength(a),d,e;for(d=0;d<c/8;d++)0===(d&
3)&&(e=a[d/4]),b+=String.fromCharCode(e>>>8>>>8>>>8),e<<=8;return decodeURIComponent(escape
(b))},toBits:function(a){a=unescape(encodeURIComponent(a));var b=[],c,d=0;for(c=0;c<a.length;c++)d=d<<8|a.charCodeAt(c),
3===(c&3)&&(b.push(d),d=0);c&3&&b.push(sjcl.bitArray.partial(8*(c&3),d));return b}};
sjcl.codec.hex={fromBits:function(a){var b="",c;for(c=0;c<a.length;c++)b+=((a[c]|0)+0xf00000000000).toString(16).substr
(4);return b.substr(0,sjcl.bitArray.bitLength(a)/4)},toBits:function(a){var b,c=[],d;a=a.replace(/\s|0x/g,"");d=a.length;a=a+"00000000";for(b=0;b<a.length;b+=8)c.push(parseInt(a.substr(b,8),16)^0);return sjcl.bitArray.clamp(c,4*d)}};
sjcl.codec.base32={B:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",X:"0123456789ABCDEFGHIJKLMNOPQRSTUV",BITS:32,BASE:5,
REMAINING:27,fromBits:function(a,b,c){var d=sjcl.codec.base32.BASE,e=sjcl.codec.base32.REMAINING,f="",g=0,h=sjcl.codec
.base32.B,k=0,l=sjcl.bitArray.bitLength(a);c&&(h=sjcl.codec.base32.X);for(c=0;f.length*d<l;)f+=h.charAt((k^a[c]>>
;>g)>>>e),g<d?(k=a[c]<<d-g,g+=e,c++):(k<<=d,g-=d);for(;f.length&7&&!b;)f+="=";return
f},toBits:function(a,b){a=a.replace(/\s|=/g,"").toUpperCase();var c=sjcl.codec.base32.BITS,
d=sjcl.codec.base32.BASE,e=sjcl.codec.base32.REMAINING,f=[],g,h=0,k=sjcl.codec.base32.B,l=0,n,m="base32";b&&(k
=sjcl.codec.base32.X,m="base32hex");for(g=0;g<a.length;g++){n=k.indexOf(a.charAt(g));if(0>n){if(!b)try{return sjcl
.codec.base32hex.toBits(a)}catch(p){}throw new sjcl.exception.invalid("this isn't "+m+"!");}h>e?(h-=
e,f.push(l^n>>>h),l=n<<c-h):(h+=d,l^=n<<c-h)}h&56&&f.push(sjcl.bitArray.partial(h&56,l,1));
return f}};
sjcl.codec.base32hex={fromBits:function(a,b){return sjcl.codec.base32.fromBits(a,b,1)},toBits:function(a){return sjcl.codec.base32
.toBits(a,1)}};
sjcl.codec.base64={B:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",fromBits:function(a,b,c){var d
="",e=0,f=sjcl.codec.base64.B,g=0,h=sjcl.bitArray.bitLength(a);c&&(f=f.substr(0,62)+"-_");for(c=0;6*
d.length<h;)d+=f.charAt((g^a[c]>>>e)>>>26),6>e?(g=a[c]<<6-e,e+=26,c++):(g<<=6,e-=6);for(;d.length
&3&&!b;)d+="=";return d},toBits:function(a,b){a=a.replace(/\s|=/g,"");var c=[],d,e=0,f=sjcl.codec.base64.B,g=0,h;b&&(f=f.substr(0,62)+"-_");for(d=0;d<a.length;d++){h=f.indexOf(a.charAt(d));
if(0>h)throw new sjcl.exception.invalid("this isn't base64!");26<e?(e-=26,c.push(g^h>>>e),g=h<&
lt;32-e):(e+=6,g^=h<<32-e)}e&56&&c.push(sjcl.bitArray.partial(e&56,g,1));return c}};sjcl.codec.base64url={
fromBits:function(a){return sjcl.codec.base64.fromBits(a,1,1)},toBits:function(a){return sjcl.codec.base64.toBits(a,1)}};sjcl.hash
.sha256=function(a){this.b[0]||this.O();a?(this.F=a.F.slice(0),this.A=a.A.slice(0),this.l=a.l):this.reset()};sjcl.hash.sha256.hash
=function(a){return(new sjcl.hash.sha256).update(a).finalize()};
sjcl.hash.sha256.prototype={blockSize:512,reset:function(){this.F=this.Y.slice(0);this.A=[];this.l=0;return this},update:function
(a){"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));var b,c=this.A=sjcl.bitArray.concat(this.A,a);b=this
.l;a=this.l=b+sjcl.bitArray.bitLength(a);if(0x1fffffffffffff<a)throw new sjcl.exception.invalid("Cannot hash more than 2
^53 - 1 bits");if("undefined"!==typeof Uint32Array){var d=new Uint32Array(c),e=0;for(b=512+b-(512+b&0x1ff);b&
lt;=a;b+=512)u(this,d.subarray(16*e,
16*(e+1))),e+=1;c.splice(0,16*e)}else for(b=512+b-(512+b&0x1ff);b<=a;b+=512)u(this,c.splice(0,16));return this},finalize:
function(){var a,b=this.A,c=this.F,b=sjcl.bitArray.concat(b,[sjcl.bitArray.partial(1,1)]);for(a=b.length+2;a&15;a++)b.push(0
);b.push(Math.floor(this.l/0x100000000));for(b.push(this.l|0);b.length;)u(this,b.splice(0,16));this.reset();return c},Y:[],b:[],
O:function(){function a(a){return 0x100000000*(a-Math.floor(a))|0}for(var b=0,c=2,d,e;64>b;c++){e=!0;for(d=2;d*d<=c;d++)if
(0===c%d){e=
!1;break}e&&(8>b&&(this.Y[b]=a(Math.pow(c,.5))),this.b[b]=a(Math.pow(c,1/3)),b++)}}};
function u(a,b){var c,d,e,f=a.F,g=a.b,h=f[0],k=f[1],l=f[2],n=f[3],m=f[4],p=f[5],r=f[6],q=f[7];for(c=0;64>c;c++)16>c?d=b[c]:(
d=b[c+1&15],e=b[c+14&15],d=b[c&15]=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>
;>17^e>>>19^e>>>10^e<<15^e<<13)+b[c&15]+b[c+9&15]|0),d=d+q+(m>>>6^m>>>
;11^m>>>25^m<<26^m<<21^m<<7)+(r^m&(p^r))+g[c],q=r,r=p,p=m,m=n+d|0,n=l,l=k,k=h,h=d+(k&l^n&(
k^l))+(k>>>2^k>>>13^k>>>22^k<<30^k<<19^k<<10)|0;f[0]=f[0]+h|0;f[1]=f[1]+k|0;f[2]=f[
2]+l|0;f[3]=f[3]+n|0;f[4]=f[4]+m|0;f[5]=f[5]+p|0;f[6]=f[6]+r|0;f[7]=
f[7]+q|0}
sjcl.mode.ccm={name:"ccm",G:[],listenProgress:function(a){sjcl.mode.ccm.G.push(a)},unListenProgress:function(a){a=sjcl
.mode.ccm.G.indexOf(a);-1<a&&sjcl.mode.ccm.G.splice(a,1)},fa:function(a){var b=sjcl.mode.ccm.G.slice(),c;for(c=0;c<
;b.length;c+=1)b[c](a)},encrypt:function(a,b,c,d,e){var f,g=b.slice(0),h=sjcl.bitArray,k=h.bitLength(c)/8,l=h.bitLength(g)/8;e=e
||64;d=d||[];if(7>k)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(f=2;4>f&&l&
gt;>>8*f;f++);f<15-k&&(f=15-k);c=h.clamp(c,
8*(15-f));b=sjcl.mode.ccm.V(a,b,c,d,e,f);g=sjcl.mode.ccm.C(a,g,c,b,e,f);return h.concat(g.data,g.tag)},decrypt:function(a,b,c,d,
e){e=e||64;d=d||[];var f=sjcl.bitArray,g=f.bitLength(c)/8,h=f.bitLength(b),k=f.clamp(b,h-e),l=f.bitSlice(b,h-e),h=(h-e)/8;if(7>
;g)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(b=2;4>b&&h>>>8*b;b++);
b<15-g&&(b=15-g);c=f.clamp(c,8*(15-b));k=sjcl.mode.ccm.C(a,k,c,l,e,b);a=sjcl.mode.ccm.V(a,k.data,c,d,e,b);if(!f.equal
(k.tag,a))throw new sjcl.exception.corrupt("ccm: tag doesn't match");
...
reset = function () { this._h = this._init.slice(0); this._buffer = []; this._length = 0; return this; }
...
//if it's not valid, use the first character only and reset the reader
if (tt === Tokens.CHAR || tt === Tokens.UNKNOWN) {
if (rule.length > 1) {
tt = Tokens.UNKNOWN_SYM;
} else {
tt = Tokens.CHAR;
rule = first;
reader.reset();
}
}
return this.createToken(tt, rule, startLine, startCol);
},
/**
...
update = function (data) { if (typeof data === "string") { data = sjcl.codec.utf8String.toBits(data); } var i, b = this._buffer = sjcl.bitArray.concat(this._buffer, data), ol = this._length, nl = this._length = ol + sjcl.bitArray.bitLength(data); if (nl > 9007199254740991){ throw new sjcl.exception.invalid("Cannot hash more than 2^53 - 1 bits"); } if (typeof Uint32Array !== 'undefined') { var c = new Uint32Array(b); var j = 0; for (i = this.blockSize+ol - ((this.blockSize+ol) & (this.blockSize-1)); i <= nl; i+= this.blockSize) { this._block(c.subarray(16 * j, 16 * (j+1))); j += 1; } b.splice(0, 16 * j); } else { for (i = this.blockSize+ol - ((this.blockSize+ol) & (this.blockSize-1)); i <= nl; i+= this.blockSize) { this._block(b.splice(0,16)); } } return this; }
...
c},$:function(a,b,c,d){var e;e=0;for(void 0===d&&(d=[]);32<=b;b-=32)d.push(c),c=0;if(0===b)return d.concat(a);for(e=0
;e<a.length;e++)d.push(c|a[e]>>>b),c=a[e]<<32-b;e=a.length?a[a.length-1]:0;a=sjcl.bitArray.getPartial(e);d.push
(sjcl.bitArray.partial(b+a&31,32<b+a?c:d.pop(),1));return d},i:function(a,b){return[a[0]^b[0],a[1]^b[1],a[2]^b[2],a[3]^b[
3]]},byteswapM:function(a){var b,c;for(b=0;b<a.length;++b)c=a[b],a[b]=c>>>24|c>>>8&0xff00|(c&0xff00
)<<8|c<<24;return a}};
sjcl.codec.utf8String={fromBits:function(a){var b="",c=sjcl.bitArray.bitLength(a),d,e;for(d=0;d<c/8;d++)0===(d&
3)&&(e=a[d/4]),b+=String.fromCharCode(e>>>8>>>8>>>8),e<<=8;return decodeURIComponent(escape
(b))},toBits:function(a){a=unescape(encodeURIComponent(a));var b=[],c,d=0;for(c=0;c<a.length;c++)d=d<<8|a.charCodeAt(c),
3===(c&3)&&(b.push(d),d=0);c&3&&b.push(sjcl.bitArray.partial(8*(c&3),d));return b}};
sjcl.codec.hex={fromBits:function(a){var b="",c;for(c=0;c<a.length;c++)b+=((a[c]|0)+0xf00000000000).toString(16).substr
(4);return b.substr(0,sjcl.bitArray.bitLength(a)/4)},toBits:function(a){var b,c=[],d;a=a.replace(/\s|0x/g,"");d=a.length;a=a+"00000000";for(b=0;b<a.length;b+=8)c.push(parseInt(a.substr(b,8),16)^0);return sjcl.bitArray.clamp(c,4*d)}};
sjcl.codec.base32={B:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",X:"0123456789ABCDEFGHIJKLMNOPQRSTUV",BITS:32,BASE:5,
REMAINING:27,fromBits:function(a,b,c){var d=sjcl.codec.base32.BASE,e=sjcl.codec.base32.REMAINING,f="",g=0,h=sjcl.codec
.base32.B,k=0,l=sjcl.bitArray.bitLength(a);c&&(h=sjcl.codec.base32.X);for(c=0;f.length*d<l;)f+=h.charAt((k^a[c]>>
;>g)>>>e),g<d?(k=a[c]<<d-g,g+=e,c++):(k<<=d,g-=d);for(;f.length&7&&!b;)f+="=";return
f},toBits:function(a,b){a=a.replace(/\s|=/g,"").toUpperCase();var c=sjcl.codec.base32.BITS,
d=sjcl.codec.base32.BASE,e=sjcl.codec.base32.REMAINING,f=[],g,h=0,k=sjcl.codec.base32.B,l=0,n,m="base32";b&&(k
=sjcl.codec.base32.X,m="base32hex");for(g=0;g<a.length;g++){n=k.indexOf(a.charAt(g));if(0>n){if(!b)try{return sjcl
.codec.base32hex.toBits(a)}catch(p){}throw new sjcl.exception.invalid("this isn't "+m+"!");}h>e?(h-=
e,f.push(l^n>>>h),l=n<<c-h):(h+=d,l^=n<<c-h)}h&56&&f.push(sjcl.bitArray.partial(h&56,l,1));
return f}};
sjcl.codec.base32hex={fromBits:function(a,b){return sjcl.codec.base32.fromBits(a,b,1)},toBits:function(a){return sjcl.codec.base32
.toBits(a,1)}};
sjcl.codec.base64={B:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",fromBits:function(a,b,c){var d
="",e=0,f=sjcl.codec.base64.B,g=0,h=sjcl.bitArray.bitLength(a);c&&(f=f.substr(0,62)+"-_");for(c=0;6*
d.length<h;)d+=f.charAt((g^a[c]>>>e)>>>26),6>e?(g=a[c]<<6-e,e+=26,c++):(g<<=6,e-=6);for(;d.length
&3&&!b;)d+="=";return d},toBits:function(a,b){a=a.replace(/\s|=/g,"");var c=[],d,e=0,f=sjcl.codec.base64.B,g=0,h;b&&(f=f.substr(0,62)+"-_");for(d=0;d<a.length;d++){h=f.indexOf(a.charAt(d));
if(0>h)throw new sjcl.exception.invalid("this isn't base64!");26<e?(e-=26,c.push(g^h>>>e),g=h<&
lt;32-e):(e+=6,g^=h<<32-e)}e&56&&c.push(sjcl.bitArray.partial(e&56,g,1));return c}};sjcl.codec.base64url={
fromBits:function(a){return sjcl.codec.base64.fromBits(a,1,1)},toBits:function(a){return sjcl.codec.base64.toBits(a,1)}};sjcl.hash
.sha256=function(a){this.b[0]||this.O();a?(this.F=a.F.slice(0),this.A=a.A.slice(0),this.l=a.l):this.reset()};sjcl.hash.sha256.hash
=function(a){return(new sjcl.hash.sha256).update(a).finalize()};
sjcl.hash.sha256.prototype={blockSize:512,reset:function(){this.F=this.Y.slice(0);this.A=[];this.l=0;return this},update:function
(a){"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));var b,c=this.A=sjcl.bitArray.concat(this.A,a);b=this
.l;a=this.l=b+sjcl.bitArray.bitLength(a);if(0x1fffffffffffff<a)throw new sjcl.exception.invalid("Cannot hash more than 2
^53 - 1 bits");if("undefined"!==typeof Uint32Array){var d=new Uint32Array(c),e=0;for(b=512+b-(512+b&0x1ff);b&
lt;=a;b+=512)u(this,d.subarray(16*e,
16*(e+1))),e+=1;c.splice(0,16*e)}else for(b=512+b-(512+b&0x1ff);b<=a;b+=512)u(this,c.splice(0,16));return this},finalize:
function(){var a,b=this.A,c=this.F,b=sjcl.bitArray.concat(b,[sjcl.bitArray.partial(1,1)]);for(a=b.length+2;a&15;a++)b.push(0
);b.push(Math.floor(this.l/0x100000000));for(b.push(this.l|0);b.length;)u(this,b.splice(0,16));this.reset();return c},Y:[],b:[],
O:function(){function a(a){return 0x100000000*(a-Math.floor(a))|0}for(var b=0,c=2,d,e;64>b;c++){e=!0;for(d=2;d*d<=c;d++)if
(0===c%d){e=
!1;break}e&&(8>b&&(this.Y[b]=a(Math.pow(c,.5))),this.b[b]=a(Math.pow(c,1/3)),b++)}}};
function u(a,b){var c,d,e,f=a.F,g=a.b,h=f[0],k=f[1],l=f[2],n=f[3],m=f[4],p=f[5],r=f[6],q=f[7];for(c=0;64>c;c++)16>c?d=b[c]:(
d=b[c+1&15],e=b[c+14&15],d=b[c&15]=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>
;>17^e>>>19^e>>>10^e<<15^e<<13)+b[c&15]+b[c+9&15]|0),d=d+q+(m>>>6^m>>>
;11^m>>>25^m<<26^m<<21^m<<7)+(r^m&(p^r))+g[c],q=r,r=p,p=m,m=n+d|0,n=l,l=k,k=h,h=d+(k&l^n&(
k^l))+(k>>>2^k>>>13^k>>>22^k<<30^k<<19^k<<10)|0;f[0]=f[0]+h|0;f[1]=f[1]+k|0;f[2]=f[
2]+l|0;f[3]=f[3]+n|0;f[4]=f[4]+m|0;f[5]=f[5]+p|0;f[6]=f[6]+r|0;f[7]=
f[7]+q|0}
sjcl.mode.ccm={name:"ccm",G:[],listenProgress:function(a){sjcl.mode.ccm.G.push(a)},unListenProgress:function(a){a=sjcl
.mode.ccm.G.indexOf(a);-1<a&&sjcl.mode.ccm.G.splice(a,1)},fa:function(a){var b=sjcl.mode.ccm.G.slice(),c;for(c=0;c<
;b.length;c+=1)b[c](a)},encrypt:function(a,b,c,d,e){var f,g=b.slice(0),h=sjcl.bitArray,k=h.bitLength(c)/8,l=h.bitLength(g)/8;e=e
||64;d=d||[];if(7>k)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(f=2;4>f&&l&
gt;>>8*f;f++);f<15-k&&(f=15-k);c=h.clamp(c,
8*(15-f));b=sjcl.mode.ccm.V(a,b,c,d,e,f);g=sjcl.mode.ccm.C(a,g,c,b,e,f);return h.concat(g.data,g.tag)},decrypt:function(a,b,c,d,
e){e=e||64;d=d||[];var f=sjcl.bitArray,g=f.bitLength(c)/8,h=f.bitLength(b),k=f.clamp(b,h-e),l=f.bitSlice(b,h-e),h=(h-e)/8;if(7>
;g)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(b=2;4>b&&h>>>8*b;b++);
b<15-g&&(b=15-g);c=f.clamp(c,8*(15-b));k=sjcl.mode.ccm.C(a,k,c,l,e,b);a=sjcl.mode.ccm.V(a,k.data,c,d,e,b);if(!f.equal
(k.tag,a))throw new sjcl.exception.corrupt("ccm: tag doesn't match");
...
function(){function a(a){return 0x100000000*(a-Math.floor(a))|0}for(var b=0,c=2,d,e;64>b;c++){e=!0;for(d=2;d*d<=c;d++)if(0===c%d ){e= !1;break}e&&(8>b&&(this.Y[b]=a(Math.pow(c,.5))),this.b[b]=a(Math.pow(c,1/3)),b++)}}
...
file https://github.com/bitwiseshiftleft/sjcl/blob/1.0.8/sjcl.js
shGithubDateCommitted https://github.com/bitwiseshiftleft/sjcl/blob/1.0.8/sjcl.js # 2017-07-04T08:55:03Z
curl https://raw.githubusercontent.com/bitwiseshiftleft/sjcl/1.0.8/sjcl.js > /tmp/aa.js
*/
/* jslint ignore:start */
(function () { var module;
"use strict";var sjcl={cipher:{},hash:{},keyexchange:{},mode:{},misc:{},codec:{},exception:{corrupt:function(a){this.toString
=function(){return"CORRUPT: "+this.message};this.message=a},invalid:function(a){this.toString=function(){return"INVALID
: "+this.message};this.message=a},bug:function(a){this.toString=function(){return"BUG: "+this.message};this.message
=a},notReady:function(a){this.toString=function(){return"NOT READY: "+this.message};this.message=a}}};
sjcl.cipher.aes=function(a){this.s[0][0][0]||this.O();var b,c,d,e,f=this.s[0][4],g=this
.s[1];b=a.length;var h=1;if(4!==b&&6!==b&&8!==b)throw new sjcl.exception.invalid("invalid aes key size"
;);this.b=[d=a.slice(0),e=[]];for(a=b;a<4*b+28;a++){c=d[a-1];if(0===a%b||8===b&&4===a%b)c=f[c>>>24]<<24
^f[c>>16&255]<<16^f[c>>8&255]<<8^f[c&255],0===a%b&&(c=c<<8^c>>>24^h<
;<24,h=h<<1^283*(h>>7));d[a]=d[a-b]^c}for(b=0;a;b++,a--)c=d[b&3?a:a-4],e[b]=4>=a||4>b?c:g[0][f[c>>
;>24]]^g[1][f[c>>16&255]]^g[2][f[c>>8&255]]^g[3][f[c&
255]]};
sjcl.cipher.aes.prototype={encrypt:function(a){return t(this,a,0)},decrypt:function(a){return t(this,a,1)},s:[[[],[],[],[],[]],[[],[],[],[],[]]],
O:function(){var a=this.s[0],b=this.s[1],c=a[4],d=b[4],e,f,g,h=[],k=[],l,n,m,p;for(e=0;0x100>e;e++)k[(h[e]=e<<1^283*(e&
gt;>7))^e]=e;for(f=g=0;!c[f];f^=l||1,g=k[g]||1)for(m=g^g<<1^g<<2^g<<3^g<<4,m=m>>8^m&255^99,
c[f]=m,d[m]=f,n=h[e=h[l=h[f]]],p=0x1010101*n^0x10001*e^0x101*l^0x1010100*f,n=0x101*h[m]^0x1010100*m,e=0;4>e;e++)a[e][f]=n=n<
;<24^n>>>8,b[e][m]=p=p<<24^p>>>8;for(e=
0;5>e;e++)a[e]=a[e].slice(0),b[e]=b[e].slice(0)}};
function t(a,b,c){if(4!==b.length)throw new sjcl.exception.invalid("invalid aes block size");var d=a.b[c],e=b[0]^d[0],
f=b[c?3:1]^d[1],g=b[2]^d[2];b=b[c?1:3]^d[3];var h,k,l,n=d.length/4-2,m,p=4,r=[0,0,0,0];h=a.s[c];a=h[0];var q=h[1],v=h[2],w=h[3],
x=h[4];for(m=0;m<n;m++)h=a[e>>>24]^q[f>>16&255]^v[g>>8&255]^w[b&255]^d[p],k=a[f>>>24
]^q[g>>16&255]^v[b>>8&255]^w[e&255]^d[p+1],l=a[g>>>24]^q[b>>16&255]^v[e>>8&
255]^w[f&255]^d[p+2],b=a[b>>>24]^q[e>>16&255]^v[f>>8&255]^w[g&255]^d[p+3],p+=4,e=h,f=k,g=l;
for(m=
0;4>m;m++)r[c?3&-m:m]=x[e>>>24]<<24^x[f>>16&255]<<16^x[g>>8&255]<<8^x[b&
;255]^d[p++],h=e,e=f,f=g,g=b,b=h;return r}
sjcl.bitArray={bitSlice:function(a,b,c){a=sjcl.bitArray.$(a.slice(b/32),32-(b&31)).slice(1);return void 0===c?a:sjcl.bitArray
.clamp(a,c-b)},extract:function(a,b,c){var d=Math.floor(-b-c&31);return((b+c-1^b)&-32?a[b/32|0]<<32-d^a[b/32+1|0]&
gt;>>d:a[b/32|0]>>>d)&(1<<c)-1},concat:function(a,b){if(0===a.length||0===b.length)return a.concat(b);var
c=a[a.length-1],d=sjcl.bitArray.getPartial(c);return 32===d?a.concat(b):sjcl.bitArray.$(b,d,c|0,a.slice(0,a.length-1))},bitLength
:function(a){var b=a.length;return 0===
b?0:32*(b-1)+sjcl.bitArray.getPartial(a[b-1])},clamp:function(a,b){if(32*a.length<b)return a;a=a.slice(0,Math.ceil(b/32));var
c=a.length;b=b&31;0<c&&b&&(a[c-1]=sjcl.bitArray.partial(b,a[c-1]&2147483648>>b-1,1));return a},
partial:function(a,b,c){return 32===a?b:(c?b|0:b<<32-a)+0x10000000000*a},getPartial:function(a){return Math.round(a/0x10000000000
)||32},equal:function(a,b){if(sjcl.bitArray.bitLength(a)!==sjcl.bitArray.bitLength(b))return!1;var c=0,d;for(d=0;d<a.length;d
++)c|=a[d]^b[d];return 0===
...
function(){var a,b=this.A,c=this.F,b=sjcl.bitArray.concat(b,[sjcl.bitArray.partial(1,1)]);for(a=b.length+2;a&15;a++)b.push(0);b. push(Math.floor(this.l/0x100000000));for(b.push(this.l|0);b.length;)u(this,b.splice(0,16));this.reset();return c}
...
c},$:function(a,b,c,d){var e;e=0;for(void 0===d&&(d=[]);32<=b;b-=32)d.push(c),c=0;if(0===b)return d.concat(a);for(e=0
;e<a.length;e++)d.push(c|a[e]>>>b),c=a[e]<<32-b;e=a.length?a[a.length-1]:0;a=sjcl.bitArray.getPartial(e);d.push
(sjcl.bitArray.partial(b+a&31,32<b+a?c:d.pop(),1));return d},i:function(a,b){return[a[0]^b[0],a[1]^b[1],a[2]^b[2],a[3]^b[
3]]},byteswapM:function(a){var b,c;for(b=0;b<a.length;++b)c=a[b],a[b]=c>>>24|c>>>8&0xff00|(c&0xff00
)<<8|c<<24;return a}};
sjcl.codec.utf8String={fromBits:function(a){var b="",c=sjcl.bitArray.bitLength(a),d,e;for(d=0;d<c/8;d++)0===(d&
3)&&(e=a[d/4]),b+=String.fromCharCode(e>>>8>>>8>>>8),e<<=8;return decodeURIComponent(escape
(b))},toBits:function(a){a=unescape(encodeURIComponent(a));var b=[],c,d=0;for(c=0;c<a.length;c++)d=d<<8|a.charCodeAt(c),
3===(c&3)&&(b.push(d),d=0);c&3&&b.push(sjcl.bitArray.partial(8*(c&3),d));return b}};
sjcl.codec.hex={fromBits:function(a){var b="",c;for(c=0;c<a.length;c++)b+=((a[c]|0)+0xf00000000000).toString(16).substr
(4);return b.substr(0,sjcl.bitArray.bitLength(a)/4)},toBits:function(a){var b,c=[],d;a=a.replace(/\s|0x/g,"");d=a.length;a=a+"00000000";for(b=0;b<a.length;b+=8)c.push(parseInt(a.substr(b,8),16)^0);return sjcl.bitArray.clamp(c,4*d)}};
sjcl.codec.base32={B:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",X:"0123456789ABCDEFGHIJKLMNOPQRSTUV",BITS:32,BASE:5,
REMAINING:27,fromBits:function(a,b,c){var d=sjcl.codec.base32.BASE,e=sjcl.codec.base32.REMAINING,f="",g=0,h=sjcl.codec
.base32.B,k=0,l=sjcl.bitArray.bitLength(a);c&&(h=sjcl.codec.base32.X);for(c=0;f.length*d<l;)f+=h.charAt((k^a[c]>>
;>g)>>>e),g<d?(k=a[c]<<d-g,g+=e,c++):(k<<=d,g-=d);for(;f.length&7&&!b;)f+="=";return
f},toBits:function(a,b){a=a.replace(/\s|=/g,"").toUpperCase();var c=sjcl.codec.base32.BITS,
d=sjcl.codec.base32.BASE,e=sjcl.codec.base32.REMAINING,f=[],g,h=0,k=sjcl.codec.base32.B,l=0,n,m="base32";b&&(k
=sjcl.codec.base32.X,m="base32hex");for(g=0;g<a.length;g++){n=k.indexOf(a.charAt(g));if(0>n){if(!b)try{return sjcl
.codec.base32hex.toBits(a)}catch(p){}throw new sjcl.exception.invalid("this isn't "+m+"!");}h>e?(h-=
e,f.push(l^n>>>h),l=n<<c-h):(h+=d,l^=n<<c-h)}h&56&&f.push(sjcl.bitArray.partial(h&56,l,1));
return f}};
sjcl.codec.base32hex={fromBits:function(a,b){return sjcl.codec.base32.fromBits(a,b,1)},toBits:function(a){return sjcl.codec.base32
.toBits(a,1)}};
sjcl.codec.base64={B:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",fromBits:function(a,b,c){var d
="",e=0,f=sjcl.codec.base64.B,g=0,h=sjcl.bitArray.bitLength(a);c&&(f=f.substr(0,62)+"-_");for(c=0;6*
d.length<h;)d+=f.charAt((g^a[c]>>>e)>>>26),6>e?(g=a[c]<<6-e,e+=26,c++):(g<<=6,e-=6);for(;d.length
&3&&!b;)d+="=";return d},toBits:function(a,b){a=a.replace(/\s|=/g,"");var c=[],d,e=0,f=sjcl.codec.base64.B,g=0,h;b&&(f=f.substr(0,62)+"-_");for(d=0;d<a.length;d++){h=f.indexOf(a.charAt(d));
if(0>h)throw new sjcl.exception.invalid("this isn't base64!");26<e?(e-=26,c.push(g^h>>>e),g=h<&
lt;32-e):(e+=6,g^=h<<32-e)}e&56&&c.push(sjcl.bitArray.partial(e&56,g,1));return c}};sjcl.codec.base64url={
fromBits:function(a){return sjcl.codec.base64.fromBits(a,1,1)},toBits:function(a){return sjcl.codec.base64.toBits(a,1)}};sjcl.hash
.sha256=function(a){this.b[0]||this.O();a?(this.F=a.F.slice(0),this.A=a.A.slice(0),this.l=a.l):this.reset()};sjcl.hash.sha256.hash
=function(a){return(new sjcl.hash.sha256).update(a).finalize()};
sjcl.hash.sha256.prototype={blockSize:512,reset:function(){this.F=this.Y.slice(0);this.A=[];this.l=0;return this},update:function
(a){"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));var b,c=this.A=sjcl.bitArray.concat(this.A,a);b=this
.l;a=this.l=b+sjcl.bitArray.bitLength(a);if(0x1fffffffffffff<a)throw new sjcl.exception.invalid("Cannot hash more than 2
^53 - 1 bits");if("undefined"!==typeof Uint32Array){var d=new Uint32Array(c),e=0;for(b=512+b-(512+b&0x1ff);b&
lt;=a;b+=512)u(this,d.subarray(16*e,
16*(e+1))),e+=1;c.splice(0,16*e)}else for(b=512+b-(512+b&0x1ff);b<=a;b+=512)u(this,c.splice(0,16));return this},finalize:
function(){var a,b=this.A,c=this.F,b=sjcl.bitArray.concat(b,[sjcl.bitArray.partial(1,1)]);for(a=b.length+2;a&15;a++)b.push(0
);b.push(Math.floor(this.l/0x100000000));for(b.push(this.l|0);b.length;)u(this,b.splice(0,16));this.reset();return c},Y:[],b:[],
O:function(){function a(a){return 0x100000000*(a-Math.floor(a))|0}for(var b=0,c=2,d,e;64>b;c++){e=!0;for(d=2;d*d<=c;d++)if
(0===c%d){e=
!1;break}e&&(8>b&&(this.Y[b]=a(Math.pow(c,.5))),this.b[b]=a(Math.pow(c,1/3)),b++)}}};
function u(a,b){var c,d,e,f=a.F,g=a.b,h=f[0],k=f[1],l=f[2],n=f[3],m=f[4],p=f[5],r=f[6],q=f[7];for(c=0;64>c;c++)16>c?d=b[c]:(
d=b[c+1&15],e=b[c+14&15],d=b[c&15]=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>
;>17^e>>>19^e>>>10^e<<15^e<<13)+b[c&15]+b[c+9&15]|0),d=d+q+(m>>>6^m>>>
;11^m>>>25^m<<26^m<<21^m<<7)+(r^m&(p^r))+g[c],q=r,r=p,p=m,m=n+d|0,n=l,l=k,k=h,h=d+(k&l^n&(
k^l))+(k>>>2^k>>>13^k>>>22^k<<30^k<<19^k<<10)|0;f[0]=f[0]+h|0;f[1]=f[1]+k|0;f[2]=f[
2]+l|0;f[3]=f[3]+n|0;f[4]=f[4]+m|0;f[5]=f[5]+p|0;f[6]=f[6]+r|0;f[7]=
f[7]+q|0}
sjcl.mode.ccm={name:"ccm",G:[],listenProgress:function(a){sjcl.mode.ccm.G.push(a)},unListenProgress:function(a){a=sjcl
.mode.ccm.G.indexOf(a);-1<a&&sjcl.mode.ccm.G.splice(a,1)},fa:function(a){var b=sjcl.mode.ccm.G.slice(),c;for(c=0;c<
;b.length;c+=1)b[c](a)},encrypt:function(a,b,c,d,e){var f,g=b.slice(0),h=sjcl.bitArray,k=h.bitLength(c)/8,l=h.bitLength(g)/8;e=e
||64;d=d||[];if(7>k)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(f=2;4>f&&l&
gt;>>8*f;f++);f<15-k&&(f=15-k);c=h.clamp(c,
8*(15-f));b=sjcl.mode.ccm.V(a,b,c,d,e,f);g=sjcl.mode.ccm.C(a,g,c,b,e,f);return h.concat(g.data,g.tag)},decrypt:function(a,b,c,d,
e){e=e||64;d=d||[];var f=sjcl.bitArray,g=f.bitLength(c)/8,h=f.bitLength(b),k=f.clamp(b,h-e),l=f.bitSlice(b,h-e),h=(h-e)/8;if(7>
;g)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(b=2;4>b&&h>>>8*b;b++);
b<15-g&&(b=15-g);c=f.clamp(c,8*(15-b));k=sjcl.mode.ccm.C(a,k,c,l,e,b);a=sjcl.mode.ccm.V(a,k.data,c,d,e,b);if(!f.equal
(k.tag,a))throw new sjcl.exception.corrupt("ccm: tag doesn't match");
...
function(){this.F=this.Y.slice(0);this.A=[];this.l=0;return this}
...
//if it's not valid, use the first character only and reset the reader
if (tt === Tokens.CHAR || tt === Tokens.UNKNOWN) {
if (rule.length > 1) {
tt = Tokens.UNKNOWN_SYM;
} else {
tt = Tokens.CHAR;
rule = first;
reader.reset();
}
}
return this.createToken(tt, rule, startLine, startCol);
},
/**
...
function(a){"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));var b,c=this.A=sjcl.bitArray.concat(this.A,a);b=this.l;a=this .l=b+sjcl.bitArray.bitLength(a);if(0x1fffffffffffff<a)throw new sjcl.exception.invalid("Cannot hash more than 2^53 - 1 bits");if ("undefined"!==typeof Uint32Array){var d=new Uint32Array(c),e=0;for(b=512+b-(512+b&0x1ff);b<=a;b+=512)u(this,d.subarray(16*e, 16*(e+1))),e+=1;c.splice(0,16*e)}else for(b=512+b-(512+b&0x1ff);b<=a;b+=512)u(this,c.splice(0,16));return this}
...
c},$:function(a,b,c,d){var e;e=0;for(void 0===d&&(d=[]);32<=b;b-=32)d.push(c),c=0;if(0===b)return d.concat(a);for(e=0
;e<a.length;e++)d.push(c|a[e]>>>b),c=a[e]<<32-b;e=a.length?a[a.length-1]:0;a=sjcl.bitArray.getPartial(e);d.push
(sjcl.bitArray.partial(b+a&31,32<b+a?c:d.pop(),1));return d},i:function(a,b){return[a[0]^b[0],a[1]^b[1],a[2]^b[2],a[3]^b[
3]]},byteswapM:function(a){var b,c;for(b=0;b<a.length;++b)c=a[b],a[b]=c>>>24|c>>>8&0xff00|(c&0xff00
)<<8|c<<24;return a}};
sjcl.codec.utf8String={fromBits:function(a){var b="",c=sjcl.bitArray.bitLength(a),d,e;for(d=0;d<c/8;d++)0===(d&
3)&&(e=a[d/4]),b+=String.fromCharCode(e>>>8>>>8>>>8),e<<=8;return decodeURIComponent(escape
(b))},toBits:function(a){a=unescape(encodeURIComponent(a));var b=[],c,d=0;for(c=0;c<a.length;c++)d=d<<8|a.charCodeAt(c),
3===(c&3)&&(b.push(d),d=0);c&3&&b.push(sjcl.bitArray.partial(8*(c&3),d));return b}};
sjcl.codec.hex={fromBits:function(a){var b="",c;for(c=0;c<a.length;c++)b+=((a[c]|0)+0xf00000000000).toString(16).substr
(4);return b.substr(0,sjcl.bitArray.bitLength(a)/4)},toBits:function(a){var b,c=[],d;a=a.replace(/\s|0x/g,"");d=a.length;a=a+"00000000";for(b=0;b<a.length;b+=8)c.push(parseInt(a.substr(b,8),16)^0);return sjcl.bitArray.clamp(c,4*d)}};
sjcl.codec.base32={B:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",X:"0123456789ABCDEFGHIJKLMNOPQRSTUV",BITS:32,BASE:5,
REMAINING:27,fromBits:function(a,b,c){var d=sjcl.codec.base32.BASE,e=sjcl.codec.base32.REMAINING,f="",g=0,h=sjcl.codec
.base32.B,k=0,l=sjcl.bitArray.bitLength(a);c&&(h=sjcl.codec.base32.X);for(c=0;f.length*d<l;)f+=h.charAt((k^a[c]>>
;>g)>>>e),g<d?(k=a[c]<<d-g,g+=e,c++):(k<<=d,g-=d);for(;f.length&7&&!b;)f+="=";return
f},toBits:function(a,b){a=a.replace(/\s|=/g,"").toUpperCase();var c=sjcl.codec.base32.BITS,
d=sjcl.codec.base32.BASE,e=sjcl.codec.base32.REMAINING,f=[],g,h=0,k=sjcl.codec.base32.B,l=0,n,m="base32";b&&(k
=sjcl.codec.base32.X,m="base32hex");for(g=0;g<a.length;g++){n=k.indexOf(a.charAt(g));if(0>n){if(!b)try{return sjcl
.codec.base32hex.toBits(a)}catch(p){}throw new sjcl.exception.invalid("this isn't "+m+"!");}h>e?(h-=
e,f.push(l^n>>>h),l=n<<c-h):(h+=d,l^=n<<c-h)}h&56&&f.push(sjcl.bitArray.partial(h&56,l,1));
return f}};
sjcl.codec.base32hex={fromBits:function(a,b){return sjcl.codec.base32.fromBits(a,b,1)},toBits:function(a){return sjcl.codec.base32
.toBits(a,1)}};
sjcl.codec.base64={B:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",fromBits:function(a,b,c){var d
="",e=0,f=sjcl.codec.base64.B,g=0,h=sjcl.bitArray.bitLength(a);c&&(f=f.substr(0,62)+"-_");for(c=0;6*
d.length<h;)d+=f.charAt((g^a[c]>>>e)>>>26),6>e?(g=a[c]<<6-e,e+=26,c++):(g<<=6,e-=6);for(;d.length
&3&&!b;)d+="=";return d},toBits:function(a,b){a=a.replace(/\s|=/g,"");var c=[],d,e=0,f=sjcl.codec.base64.B,g=0,h;b&&(f=f.substr(0,62)+"-_");for(d=0;d<a.length;d++){h=f.indexOf(a.charAt(d));
if(0>h)throw new sjcl.exception.invalid("this isn't base64!");26<e?(e-=26,c.push(g^h>>>e),g=h<&
lt;32-e):(e+=6,g^=h<<32-e)}e&56&&c.push(sjcl.bitArray.partial(e&56,g,1));return c}};sjcl.codec.base64url={
fromBits:function(a){return sjcl.codec.base64.fromBits(a,1,1)},toBits:function(a){return sjcl.codec.base64.toBits(a,1)}};sjcl.hash
.sha256=function(a){this.b[0]||this.O();a?(this.F=a.F.slice(0),this.A=a.A.slice(0),this.l=a.l):this.reset()};sjcl.hash.sha256.hash
=function(a){return(new sjcl.hash.sha256).update(a).finalize()};
sjcl.hash.sha256.prototype={blockSize:512,reset:function(){this.F=this.Y.slice(0);this.A=[];this.l=0;return this},update:function
(a){"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));var b,c=this.A=sjcl.bitArray.concat(this.A,a);b=this
.l;a=this.l=b+sjcl.bitArray.bitLength(a);if(0x1fffffffffffff<a)throw new sjcl.exception.invalid("Cannot hash more than 2
^53 - 1 bits");if("undefined"!==typeof Uint32Array){var d=new Uint32Array(c),e=0;for(b=512+b-(512+b&0x1ff);b&
lt;=a;b+=512)u(this,d.subarray(16*e,
16*(e+1))),e+=1;c.splice(0,16*e)}else for(b=512+b-(512+b&0x1ff);b<=a;b+=512)u(this,c.splice(0,16));return this},finalize:
function(){var a,b=this.A,c=this.F,b=sjcl.bitArray.concat(b,[sjcl.bitArray.partial(1,1)]);for(a=b.length+2;a&15;a++)b.push(0
);b.push(Math.floor(this.l/0x100000000));for(b.push(this.l|0);b.length;)u(this,b.splice(0,16));this.reset();return c},Y:[],b:[],
O:function(){function a(a){return 0x100000000*(a-Math.floor(a))|0}for(var b=0,c=2,d,e;64>b;c++){e=!0;for(d=2;d*d<=c;d++)if
(0===c%d){e=
!1;break}e&&(8>b&&(this.Y[b]=a(Math.pow(c,.5))),this.b[b]=a(Math.pow(c,1/3)),b++)}}};
function u(a,b){var c,d,e,f=a.F,g=a.b,h=f[0],k=f[1],l=f[2],n=f[3],m=f[4],p=f[5],r=f[6],q=f[7];for(c=0;64>c;c++)16>c?d=b[c]:(
d=b[c+1&15],e=b[c+14&15],d=b[c&15]=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>
;>17^e>>>19^e>>>10^e<<15^e<<13)+b[c&15]+b[c+9&15]|0),d=d+q+(m>>>6^m>>>
;11^m>>>25^m<<26^m<<21^m<<7)+(r^m&(p^r))+g[c],q=r,r=p,p=m,m=n+d|0,n=l,l=k,k=h,h=d+(k&l^n&(
k^l))+(k>>>2^k>>>13^k>>>22^k<<30^k<<19^k<<10)|0;f[0]=f[0]+h|0;f[1]=f[1]+k|0;f[2]=f[
2]+l|0;f[3]=f[3]+n|0;f[4]=f[4]+m|0;f[5]=f[5]+p|0;f[6]=f[6]+r|0;f[7]=
f[7]+q|0}
sjcl.mode.ccm={name:"ccm",G:[],listenProgress:function(a){sjcl.mode.ccm.G.push(a)},unListenProgress:function(a){a=sjcl
.mode.ccm.G.indexOf(a);-1<a&&sjcl.mode.ccm.G.splice(a,1)},fa:function(a){var b=sjcl.mode.ccm.G.slice(),c;for(c=0;c<
;b.length;c+=1)b[c](a)},encrypt:function(a,b,c,d,e){var f,g=b.slice(0),h=sjcl.bitArray,k=h.bitLength(c)/8,l=h.bitLength(g)/8;e=e
||64;d=d||[];if(7>k)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(f=2;4>f&&l&
gt;>>8*f;f++);f<15-k&&(f=15-k);c=h.clamp(c,
8*(15-f));b=sjcl.mode.ccm.V(a,b,c,d,e,f);g=sjcl.mode.ccm.C(a,g,c,b,e,f);return h.concat(g.data,g.tag)},decrypt:function(a,b,c,d,
e){e=e||64;d=d||[];var f=sjcl.bitArray,g=f.bitLength(c)/8,h=f.bitLength(b),k=f.clamp(b,h-e),l=f.bitSlice(b,h-e),h=(h-e)/8;if(7>
;g)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(b=2;4>b&&h>>>8*b;b++);
b<15-g&&(b=15-g);c=f.clamp(c,8*(15-b));k=sjcl.mode.ccm.C(a,k,c,l,e,b);a=sjcl.mode.ccm.V(a,k.data,c,d,e,b);if(!f.equal
(k.tag,a))throw new sjcl.exception.corrupt("ccm: tag doesn't match");
...
function(a){a=a.replace(/\s/g,"");if(!a.match(/^\{.*\}$/))throw new sjcl.exception.invalid("json decode: this isn't json!");a=a. replace(/^\{|\}$/g,"").split(/,/);var b={},c,d;for(c=0;c<a.length;c++){if(!(d=a[c].match(/^\s*(?:(["']?)([a-z][a-z0-9]*)\1)\s*:\s*(?:(-?\d+)|"([a-z0-9+\/%*_.@=\-]*)"|(true|false))$/i)))throw new sjcl.exception.invalid("json decode: this isn't json!"); null!=d[3]?b[d[2]]=parseInt(d[3],10):null!=d[4]?b[d[2]]=d[2].match(/^(ct|adata|salt|iv)$/)?sjcl.codec.base64.toBits(d[4]):unescape (d[4]):null!=d[5]&&(b[d[2]]="true"===d[5])}return b}
...
function B(a,b){return function(){b.apply(a,arguments)}}sjcl.random=new sjcl.prng(6);
a:try{var D,E,F,G;if(G="undefined"!==typeof module&&module.exports){var H;try{H=require("crypto")}catch
(a){H=null}G=E=H}if(G&&E.randomBytes)D=E.randomBytes(128),D=new Uint32Array((new Uint8Array(D)).buffer),sjcl.random.addEntropy
(D,1024,"crypto['randomBytes']");else if("undefined"!==typeof window&&"undefined"
;!==typeof Uint32Array){F=new Uint32Array(32);if(window.crypto&&window.crypto.getRandomValues)window.crypto.getRandomValues
(F);else if(window.msCrypto&&window.msCrypto.getRandomValues)window.msCrypto.getRandomValues(F);
else break a;sjcl.random.addEntropy(F,1024,"crypto['getRandomValues']")}}catch(a){"undefined"!==typeof
window&&window.console&&(console.log("There was an error collecting entropy from the browser:"),console
.log(a))}
sjcl.json={defaults:{v:1,iter:1E4,ks:128,ts:64,mode:"ccm",adata:"",cipher:"aes"},ja:function(a,b,c
,d){c=c||{};d=d||{};var e=sjcl.json,f=e.g({iv:sjcl.random.randomWords(4,0)},e.defaults),g;e.g(f,c);c=f.adata;"string"===
typeof f.salt&&(f.salt=sjcl.codec.base64.toBits(f.salt));"string"===typeof f.iv&&(f.iv=sjcl.codec.base64
.toBits(f.iv));if(!sjcl.mode[f.mode]||!sjcl.cipher[f.cipher]||"string"===typeof a&&100>=f.iter||64!==f.ts&
;&96!==f.ts&&128!==f.ts||128!==f.ks&&192!==f.ks&&0x100!==f.ks||2>f.iv.length||
4<f.iv.length)throw new sjcl.exception.invalid("json encrypt: invalid parameters");"string"===typeof a?(g
=sjcl.misc.cachedPbkdf2(a,f),a=g.key.slice(0,f.ks/32),f.salt=g.salt):sjcl.ecc&&a instanceof sjcl.ecc.elGamal.publicKey&
;&(g=a.kem(),f.kemtag=g.tag,a=g.key.slice(0,f.ks/32));"string"===typeof b&&(b=sjcl.codec.utf8String.toBits
(b));"string"===typeof c&&(f.adata=c=sjcl.codec.utf8String.toBits(c));g=new sjcl.cipher[f.cipher](a);e.g(d,f);
d.key=a;f.ct="ccm"===f.mode&&sjcl.arrayBuffer&&sjcl.arrayBuffer.ccm&&
b instanceof ArrayBuffer?sjcl.arrayBuffer.ccm.encrypt(g,b,f.iv,c,f.ts):sjcl.mode[f.mode].encrypt(g,b,f.iv,c,f.ts);return f},encrypt
:function(a,b,c,d){var e=sjcl.json,f=e.ja.apply(e,arguments);return e.encode(f)},ia:function(a,b,c,d){c=c||{};d=d||{};var e=sjcl
.json;b=e.g(e.g(e.g({},e.defaults),b),c,!0);var f,g;f=b.adata;"string"===typeof b.salt&&(b.salt=sjcl.codec.base64
.toBits(b.salt));"string"===typeof b.iv&&(b.iv=sjcl.codec.base64.toBits(b.iv));if(!sjcl.mode[b.mode]||!sjcl.cipher
[b.cipher]||"string"===
typeof a&&100>=b.iter||64!==b.ts&&96!==b.ts&&128!==b.ts||128!==b.ks&&192!==b.ks&&0x100
!==b.ks||!b.iv||2>b.iv.length||4<b.iv.length)throw new sjcl.exception.invalid("json decrypt: invalid parameters");&
quot;string"===typeof a?(g=sjcl.misc.cachedPbkdf2(a,b),a=g.key.slice(0,b.ks/32),b.salt=g.salt):sjcl.ecc&&a instanceof
sjcl.ecc.elGamal.secretKey&&(a=a.unkem(sjcl.codec.base64.toBits(b.kemtag)).slice(0,b.ks/32));"string"===typeof
f&&(f=sjcl.codec.utf8String.toBits(f));g=new sjcl.cipher[b.cipher](a);f="ccm"===
b.mode&&sjcl.arrayBuffer&&sjcl.arrayBuffer.ccm&&b.ct instanceof ArrayBuffer?sjcl.arrayBuffer.ccm.decrypt
(g,b.ct,b.iv,b.tag,f,b.ts):sjcl.mode[b.mode].decrypt(g,b.ct,b.iv,f,b.ts);e.g(d,b);d.key=a;return 1===c.raw?f:sjcl.codec.utf8String
.fromBits(f)},decrypt:function(a,b,c,d){var e=sjcl.json;return e.ia(a,e.decode(b),c,d
)},encode:function(a){var b,c="{",d="";for(b in a)if(a.hasOwnProperty(b)){if(!b.match(/^[a-z0-9]+$/i))throw
new sjcl.exception.invalid("json encode: invalid property name");c+=d+'"'+
b+'":';d=",";switch(typeof a[b]){case "number":case "boolean":c+=a[b];break;case "
;string":c+='"'+escape(a[b])+'"';break;case "object":c+='"'+sjcl.codec
.base64.fromBits(a[b],0)+'"';break;default:throw new sjcl.exception.bug("json encode: unsupported type");}}
return c+"}"},decode:function(a){a=a.replace(/\s/g,"");if(!a.match(/^\{.*\}$/))throw new sjcl.exception.invalid("json decode: this isn't json!");a=a.replace(/^\{|\}$/g,"").split(/,/);var b={},c,d;for(c=0;c<a.length;c++){if(!(d=a[c].match(/^\s*(?:(["']?)([a-z][a-z0-9]*)\1)\s*:\s*(?:(-?\d+)|"([a-z0-9+\/%*_.@=\-]*)"|(true|false))$/i)))throw new sjcl.exception.invalid("json decode: this isn't json!");
null!=d[3]?b[d[2]]=parseInt(d[3],10):null!=d[4]?b[d[2]]=d[2].match(/^(ct|adata|salt|iv)$/)?sjcl.codec.base64.toBits(d[4]):unescape
(d[4]):null!=d[5]&&(b[d[2]]="true"===d[5])}return b},g:function(a,b,c){void 0===a&&(a={});if(void 0===
b)return a;for(var d in b)if(b.hasOwnProperty(d)){if(c&&void 0!==a[d]&&a[d]!==b[d])throw new sjcl.exception.invalid
("required parameter overridden");a[d]=b[d]}return a},sa:function(a,b){var c={},d;for(d in a)a.hasOwnProperty(d)&&
amp;a[d]!==b[d]&&(c[d]=a[d]);return c},ra:function(a,
b){var c={},d;for(d=0;d<b.length;d++)void 0!==a[b[d]]&&(c[b[d]]=a[b[d]]);return c}};sjcl.encrypt=sjcl.json.encrypt;sjcl
.decrypt=sjcl.json.decrypt;sjcl.misc.pa={};sjcl.misc.cachedPbkdf2=function(a,b){var c=sjcl.misc.pa,d;b=b||{};d=b.iter||1E3;c=c[a
]=c[a]||{};d=c[d]=c[d]||{firstSalt:b.salt&&b.salt.length?b.salt.slice(0):sjcl.random.randomWords(2,0)};c=void 0===b.salt
?d.firstSalt:b.salt;d[c]=d[c]||sjcl.misc.pbkdf2(a,c,b.iter);return{key:d[c].slice(0),salt:c.slice(0)}};
"undefined"!==typeof module&&module.exports&&(module.exports=sjcl);"function"===typeof define
&&define([],function(){return sjcl});
local.sjcl = sjcl;
...
function(a, b, c, d){var e=sjcl.json;return e.ia(a,e.decode(b),c,d)}
...
f[7]+q|0}
sjcl.mode.ccm={name:"ccm",G:[],listenProgress:function(a){sjcl.mode.ccm.G.push(a)},unListenProgress:function(a){a=sjcl
.mode.ccm.G.indexOf(a);-1<a&&sjcl.mode.ccm.G.splice(a,1)},fa:function(a){var b=sjcl.mode.ccm.G.slice(),c;for(c=0;c<
;b.length;c+=1)b[c](a)},encrypt:function(a,b,c,d,e){var f,g=b.slice(0),h=sjcl.bitArray,k=h.bitLength(c)/8,l=h.bitLength(g)/8;e=e
||64;d=d||[];if(7>k)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(f=2;4>f&&l&
gt;>>8*f;f++);f<15-k&&(f=15-k);c=h.clamp(c,
8*(15-f));b=sjcl.mode.ccm.V(a,b,c,d,e,f);g=sjcl.mode.ccm.C(a,g,c,b,e,f);return h.concat(g.data,g.tag)},decrypt:function(a,b,c,d,
e){e=e||64;d=d||[];var f=sjcl.bitArray,g=f.bitLength(c)/8,h=f.bitLength(b),k=f.clamp(b,h-e),l=f.bitSlice(b,h-e),h=(h-e)/8;if(7>
;g)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(b=2;4>b&&h>>>8*b;b++);
b<15-g&&(b=15-g);c=f.clamp(c,8*(15-b));k=sjcl.mode.ccm.C(a,k,c,l,e,b);a=sjcl.mode.ccm.V(a,k.data,c,d,e,b);if(!f.equal
(k.tag,a))throw new sjcl.exception.corrupt("ccm: tag doesn't match");
return k.data},na:function(a,b,c,d,e,f){var g=[],h=sjcl.bitArray,k=h.i;d=[h.partial(8,(b.length?64:0)|d-2<<2|f-1)];d=h.concat
(d,c);d[3]|=e;d=a.encrypt(d);if(b.length)for(c=h.bitLength(b)/8,65279>=c?g=[h.partial(16,c)]:0xffffffff>=c&&(g=h.concat
([h.partial(16,65534)],[c])),g=h.concat(g,b),b=0;b<g.length;b+=4)d=a.encrypt(k(d,g.slice(b,b+4).concat([0,0,0])));return d},V
:function(a,b,c,d,e,f){var g=sjcl.bitArray,h=g.i;e/=8;if(e%2||4>e||16<e)throw new sjcl.exception.invalid("ccm: invalid
tag length");
if(0xffffffff<d.length||0xffffffff<b.length)throw new sjcl.exception.bug("ccm: can't deal with 4GiB or more data
");c=sjcl.mode.ccm.na(a,d,c,e,g.bitLength(b)/8,f);for(d=0;d<b.length;d+=4)c=a.encrypt(h(c,b.slice(d,d+4).concat([0,0,0])));
return g.clamp(c,8*e)},C:function(a,b,c,d,e,f){var g,h=sjcl.bitArray;g=h.i;var k=b.length,l=h.bitLength(b),n=k/50,m=n;c=h.concat
([h.partial(8,f-1)],c).concat([0,0,0]).slice(0,4);d=h.bitSlice(g(d,a.encrypt(c)),0,e);if(!k)return{tag:d,data:[]};for(g=0;g<k
;g+=4)g>n&&(sjcl.mode.ccm.fa(g/
k),n+=m),c[3]++,e=a.encrypt(c),b[g]^=e[0],b[g+1]^=e[1],b[g+2]^=e[2],b[g+3]^=e[3];return{tag:d,data:h.clamp(b,l)}}};
sjcl.mode.ocb2={name:"ocb2",encrypt:function(a,b,c,d,e,f){if(128!==sjcl.bitArray.bitLength(c))throw new sjcl.exception
.invalid("ocb iv must be 128 bits");var g,h=sjcl.mode.ocb2.S,k=sjcl.bitArray,l=k.i,n=[0,0,0,0];c=h(a.encrypt(c));var m
,p=[];d=d||[];e=e||64;for(g=0;g+4<b.length;g+=4)m=b.slice(g,g+4),n=l(n,m),p=p.concat(l(c,a.encrypt(l(c,m)))),c=h(c);m=b.slice
(g);b=k.bitLength(m);g=a.encrypt(l(c,[0,0,0,b]));m=k.clamp(l(m.concat([0,0,0]),g),b);n=l(n,l(m.concat([0,0,0]),g));n=a.encrypt(l
(n,l(c,h(c))));
d.length&&(n=l(n,f?d:sjcl.mode.ocb2.pmac(a,d)));return p.concat(k.concat(m,k.clamp(n,e)))},decrypt:function(a,b,c,d,e,f){
if(128!==sjcl.bitArray.bitLength(c))throw new sjcl.exception.invalid("ocb iv must be 128 bits");e=e||64;var g=sjcl.mode
.ocb2.S,h=sjcl.bitArray,k=h.i,l=[0,0,0,0],n=g(a.encrypt(c)),m,p,r=sjcl.bitArray.bitLength(b)-e,q=[];d=d||[];for(c=0;c+4<r/32;
c+=4)m=k(n,a.decrypt(k(n,b.slice(c,c+4)))),l=k(l,m),q=q.concat(m),n=g(n);p=r-32*c;m=a
.encrypt(k(n,[0,0,0,p]));m=k(m,h.clamp(b.slice(c),p).concat([0,
0,0]));l=k(l,m);l=a.encrypt(k(l,k(n,g(n))));d.length&&(l=k(l,f?d:sjcl.mode.ocb2.pmac(a,d)));if(!h.equal(h.clamp(l,e),h.bitSlice
(b,r)))throw new sjcl.exception.corrupt("ocb: tag doesn't match");return q.concat(h.clamp(m,p))},pmac:function(a,
b){var c,d=sjcl.mode.ocb2.S,e=sjcl.bitArray,f=e.i,g=[0,0,0,0],h=a.encrypt([0,0,0,0]),h=f(h,d(d(h)));for(c=0;c+4<b.length;c+=4
)h=d(h),g=f(g,a.encrypt(f(h,b.slice(c,c+4))));c=b.slice(c);128>e.bitLength(c)&&(h=f(h,d(h)),c=e.concat(c,[-2147483648
,0,0,0]));g=f(g,c);
return a.encrypt(f(d(f(h,d(h))),g))},S:function(a){return[a[0]<<1^a[1]>>>31,a[1]<<1^a[2]>>>31,a[2]&
lt;<1^a[3]>>>31,a[3]<<1^135*(a[0]>>>31)]}};
sjcl.mode.gcm={name:"gcm",encrypt:function(a,b,c,d,e){var f=b.slice(0);b=sjcl.bitArray;d=d||[];a=sjcl.mode.gcm.C(!0,a,
f,d,c,e||128);return b.concat(a.data,a.tag)},decrypt:function(a,b,c,d,e){var f=b.slice(0),g=sjcl.bitArray,h=g.bitLength(f);e=e||
128;d=d||[];e<=h?(b=g.bitSlice(f,h-e),f=g.bitSlice(f,0,h-e)):(b=f,f=[]);a=sjcl.mode.gcm.C(!1,a,f,d,c,e);if(!g.equal(a.tag,b))
throw new sjcl.exception.corrupt("gcm: tag doesn't match");return a.data},ka:function(a,b){var c,d,e,f,g,h=sjcl.bitArray
.i;e=[0,0,
0,0];f=b.slice(0);for(c=0;128>c;c++){(d=0!==(a[Math.floor(c/32)]&1<<31-c%32))&&(e=h(e,f));g=0!==(f[3]&1
);for(d=3;0<d;d--)f[d]=f[d]>>>1|(f[d-1]&1)<<31;f[0]>>>=1;g&&(f[0]^=-0x1f000000)}return e},
j:function(a,b,c){var d,e=c.length;b=b.slice(0);for(d=0;d<e;d+=4)b[0]^=0xffffffff&c[d],b[1]^=0xffffffff&c[d+1],b[2]^=
0xffffffff&c[d+2],b[3]^=0xffffffff&c[d+3],b=sjcl.mode.gcm.ka(b,a);return b},C:function(a,b,c,d,e,f){var g,h,k,l,n,m,p,r,
q=sjcl.bitArray;m=c.length;p=q.bitLength(c);r=q.bitLength(d);h=q.bitLength(e);
g=b.encrypt([0,0,0,0]);96===h?(e=e.slice(0),e=q.concat(e,[1])):(e=sjcl.mode.gcm.j(g,[0,0,0,0],e),e=sjcl.mode.gcm.j(g,e,[0,0,Math
.floor(h/0x100000000),h&0xffffffff]));h=sjcl.mode.gcm.j(g,[0,0,0,0],d);n=e.slice(0);d=h.slice(0);a||(d=sjcl.mode.gcm.j(g,h,c
));for(l=0;l<m;l+=4)n[3]++,k=b.encrypt(n),c[l]^=k[0],c[l+1]^=k[1],c[l+2]^=k[2],c[l+3]^=k[3];c=q.clamp(c,p);a&&(d=sjcl
.mode.gcm.j(g,h,c));a=[Math.floor(r/0x100000000),r&0xffffffff,Math.floor(p/0x100000000),p&0xffffffff];d=sjcl.mode.gcm.j(
g,d,a);k=b.encrypt(e);
d[0]^=k[0];d[1]^=k[1];d[2]^=k[2];d[3]^=k[3];return{tag:q.bitSlice(d,0,f),data:c}}};sjcl.misc.hmac=function(a,b){this.W=b=b||sjcl
.hash.sha256;var c=[[],[]],d,e=b.prototype.blockSize/32;this.w=[new b,new b];a.length>e&&(a=b.hash(a));for(d=0;d<e
;d++)c[0][d]=a[d]^909522486,c[1][d]=a[d]^1549556828;this.w[0].update(c[0]);this.w[1].update(c[1]);this.R=new b(this.w[0])};
sjcl.misc.hmac.prototype.encrypt=sjcl.misc.hmac.prototype.mac=function(a){if(this.aa)throw new sjcl.exception.invalid("encrypt
on already updated hmac called!");this.update(a);return this.digest(a)};sjcl.misc.hmac.prototype.reset=function(){this.R=new
this.W(this.w[0]);this.aa=!1};sjcl.misc.hmac.prototype.update=function(a){this.aa=!0;this.R.update(a)};sjcl.misc.hmac.prototype
.digest=function(){var a=this.R.finalize(),a=(new this.W(this.w[1])).update(a).finalize();this.reset();return a};
...
function(a){var b,c="{",d="";for(b in a)if(a.hasOwnProperty(b)){if(!b.match(/^[a-z0-9]+$/i))throw new sjcl.exception.invalid("json encode: invalid property name");c+=d+'"'+ b+'":';d=",";switch(typeof a[b]){case "number":case "boolean":c+=a[b];break;case "string":c+='"'+escape(a[b])+'"';break;case "object ":c+='"'+sjcl.codec.base64.fromBits(a[b],0)+'"';break;default:throw new sjcl.exception.bug("json encode: unsupported type");}}return c+"}"}
...
a.touches[0]||a.changedTouches[0];this.addEntropy([a.pageX||a.clientX,a.pageY||a.clientY],1,"touch");C(this,0)},ma:function
(){C(this,2)},ea:function(a){a=a.accelerationIncludingGravity.x||a.accelerationIncludingGravity.y||a.accelerationIncludingGravity
.z;if(window.orientation){var b=window.orientation;"number"===typeof b&&this.addEntropy(b,1,"accelerometer
")}a&&this.addEntropy(a,2,"accelerometer");C(this,0)}};
function A(a,b){var c,d=sjcl.random.K[a],e=[];for(c in d)d.hasOwnProperty(c)&&e.push(d[c]);for(c=0;c<e.length;c++)e[c
](b)}function C(a,b){"undefined"!==typeof window&&window.performance&&"function"===typeof window
.performance.now?a.addEntropy(window.performance.now(),b,"loadtime"):a.addEntropy((new Date).valueOf(),b,"loadtime
")}function y(a){a.b=z(a).concat(z(a));a.L=new sjcl.cipher.aes(a.b)}function z(a){for(var b=0;4>b&&(a.h[b]=a.h[b
]+1|0,!a.h[b]);b++);return a.L.encrypt(a.h)}
function B(a,b){return function(){b.apply(a,arguments)}}sjcl.random=new sjcl.prng(6);
a:try{var D,E,F,G;if(G="undefined"!==typeof module&&module.exports){var H;try{H=require("crypto")}catch
(a){H=null}G=E=H}if(G&&E.randomBytes)D=E.randomBytes(128),D=new Uint32Array((new Uint8Array(D)).buffer),sjcl.random.addEntropy
(D,1024,"crypto['randomBytes']");else if("undefined"!==typeof window&&"undefined"
;!==typeof Uint32Array){F=new Uint32Array(32);if(window.crypto&&window.crypto.getRandomValues)window.crypto.getRandomValues
(F);else if(window.msCrypto&&window.msCrypto.getRandomValues)window.msCrypto.getRandomValues(F);
else break a;sjcl.random.addEntropy(F,1024,"crypto['getRandomValues']")}}catch(a){"undefined"!==typeof
window&&window.console&&(console.log("There was an error collecting entropy from the browser:"),console
.log(a))}
sjcl.json={defaults:{v:1,iter:1E4,ks:128,ts:64,mode:"ccm",adata:"",cipher:"aes"},ja:function(a,b,c
,d){c=c||{};d=d||{};var e=sjcl.json,f=e.g({iv:sjcl.random.randomWords(4,0)},e.defaults),g;e.g(f,c);c=f.adata;"string"===
typeof f.salt&&(f.salt=sjcl.codec.base64.toBits(f.salt));"string"===typeof f.iv&&(f.iv=sjcl.codec.base64
.toBits(f.iv));if(!sjcl.mode[f.mode]||!sjcl.cipher[f.cipher]||"string"===typeof a&&100>=f.iter||64!==f.ts&
;&96!==f.ts&&128!==f.ts||128!==f.ks&&192!==f.ks&&0x100!==f.ks||2>f.iv.length||
4<f.iv.length)throw new sjcl.exception.invalid("json encrypt: invalid parameters");"string"===typeof a?(g
=sjcl.misc.cachedPbkdf2(a,f),a=g.key.slice(0,f.ks/32),f.salt=g.salt):sjcl.ecc&&a instanceof sjcl.ecc.elGamal.publicKey&
;&(g=a.kem(),f.kemtag=g.tag,a=g.key.slice(0,f.ks/32));"string"===typeof b&&(b=sjcl.codec.utf8String.toBits
(b));"string"===typeof c&&(f.adata=c=sjcl.codec.utf8String.toBits(c));g=new sjcl.cipher[f.cipher](a);e.g(d,f);
d.key=a;f.ct="ccm"===f.mode&&sjcl.arrayBuffer&&sjcl.arrayBuffer.ccm&&
b instanceof ArrayBuffer?sjcl.arrayBuffer.ccm.encrypt(g,b,f.iv,c,f.ts):sjcl.mode[f.mode].encrypt(g,b,f.iv,c,f.ts);return f},encrypt
:function(a,b,c,d){var e=sjcl.json,f=e.ja.apply(e,arguments);return e.encode(f)},ia:function
(a,b,c,d){c=c||{};d=d||{};var e=sjcl.json;b=e.g(e.g(e.g({},e.defaults),b),c,!0);var f,g;f=b.adata;"string"===typeof b.
salt&&(b.salt=sjcl.codec.base64.toBits(b.salt));"string"===typeof b.iv&&(b.iv=sjcl.codec.base64.toBits
(b.iv));if(!sjcl.mode[b.mode]||!sjcl.cipher[b.cipher]||"string"===
typeof a&&100>=b.iter||64!==b.ts&&96!==b.ts&&128!==b.ts||128!==b.ks&&192!==b.ks&&0x100
!==b.ks||!b.iv||2>b.iv.length||4<b.iv.length)throw new sjcl.exception.invalid("json decrypt: invalid parameters");&
quot;string"===typeof a?(g=sjcl.misc.cachedPbkdf2(a,b),a=g.key.slice(0,b.ks/32),b.salt=g.salt):sjcl.ecc&&a instanceof
sjcl.ecc.elGamal.secretKey&&(a=a.unkem(sjcl.codec.base64.toBits(b.kemtag)).slice(0,b.ks/32));"string"===typeof
f&&(f=sjcl.codec.utf8String.toBits(f));g=new sjcl.cipher[b.cipher](a);f="ccm"===
b.mode&&sjcl.arrayBuffer&&sjcl.arrayBuffer.ccm&&b.ct instanceof ArrayBuffer?sjcl.arrayBuffer.ccm.decrypt
(g,b.ct,b.iv,b.tag,f,b.ts):sjcl.mode[b.mode].decrypt(g,b.ct,b.iv,f,b.ts);e.g(d,b);d.key=a;return 1===c.raw?f:sjcl.codec.utf8String
.fromBits(f)},decrypt:function(a,b,c,d){var e=sjcl.json;return e.ia(a,e.decode(b),c,d)},encode:function(a){var b,c="{",
d="";for(b in a)if(a.hasOwnProperty(b)){if(!b.match(/^[a-z0-9]+$/i))throw new sjcl.exception.invalid("json encode
: invalid property name");c+=d+'"'+
b+'":';d=",";switch(typeof a[b]){case "number":case "boolean":c+=a[b];break;case "
;string":c+='"'+escape(a[b])+'"';break;case "object":c+='"'+sjcl.codec
.base64.fromBits(a[b],0)+'"';break;default:throw new sjcl.exception.bug("json encode: unsupported type");}}
return c+"}"},decode:function(a){a=a.replace(/\s/g,"");if(!a.match(/^\{.*\}$/))throw new sjcl.exception.invalid("json decode: this isn't json!");a=a.replace(/^\{|\}$/g,"").split(/,/);var b={},c,d;for(c=0;c<a.length;c++){if(!(d=a[c].match(/^\s*(?:(["']?)([a-z][a-z0-9]*)\1)\s*:\s*(?:(-?\d+)|"([a-z0-9+\/%*_.@=\-]*)"|(true|false))$/i)))throw new sjcl.exception.invalid("json decode: this isn't json!");
null!=d[3]?b[d[2]]=parseInt(d[3],10):null!=d[4]?b[d[2]]=d[2].match(/^(ct|adata|salt|iv)$/)?sjcl.codec.base64.toBits(d[4]):unescape
(d[4]):null!=d[5]&&(b[d[2]]="true"===d[5])}return b},g:function(a,b,c){void 0===a&&(a={});if(void 0===
b)return a;for(var d in b)if(b.hasOwnProperty(d)){if(c&&void 0!==a[d]&&a[d]!==b[d])throw new sjcl.exception.invalid
("required parameter overridden");a[d]=b[d]}return a},sa:function(a,b){var c={},d;for(d in a)a.hasOwnProperty(d)&&
amp;a[d]!==b[d]&&(c[d]=a[d]);return c},ra:function(a,
b){var c={},d;for(d=0;d<b.length;d++)void 0!==a[b[d]]&&(c[b[d]]=a[b[d]]);return c}};sjcl.encrypt=sjcl.json.encrypt;sjcl
.decrypt=sjcl.json.decrypt;sjcl.misc.pa={};sjcl.misc.cachedPbkdf2=function(a,b){var c=sjcl.misc.pa,d;b=b||{};d=b.iter||1E3;c=c[a
]=c[a]||{};d=c[d]=c[d]||{firstSalt:b.salt&&b.salt.length?b.salt.slice(0):sjcl.random.randomWords(2,0)};c=void 0===b.salt
?d.firstSalt:b.salt;d[c]=d[c]||sjcl.misc.pbkdf2(a,c,b.iter);return{key:d[c].slice(0),salt:c.slice(0)}};
"undefined"!==typeof module&&module.exports&&(module.exports=sjcl);"function"===typeof define
&&define([],function(){return sjcl});
local.sjcl = sjcl;
...
function(a, b, c, d){var e=sjcl.json,f=e.ja.apply(e,arguments);return e.encode(f)}
...
sjcl.hash.sha256.prototype={blockSize:512,reset:function(){this.F=this.Y.slice(0);this.A=[];this.l=0;return this},update:function
(a){"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));var b,c=this.A=sjcl.bitArray.concat(this.A,a);b=this
.l;a=this.l=b+sjcl.bitArray.bitLength(a);if(0x1fffffffffffff<a)throw new sjcl.exception.invalid("Cannot hash more than 2
^53 - 1 bits");if("undefined"!==typeof Uint32Array){var d=new Uint32Array(c),e=0;for(b=512+b-(512+b&0x1ff);b&
lt;=a;b+=512)u(this,d.subarray(16*e,
16*(e+1))),e+=1;c.splice(0,16*e)}else for(b=512+b-(512+b&0x1ff);b<=a;b+=512)u(this,c.splice(0,16));return this},finalize:
function(){var a,b=this.A,c=this.F,b=sjcl.bitArray.concat(b,[sjcl.bitArray.partial(1,1)]);for(a=b.length+2;a&15;a++)b.push(0
);b.push(Math.floor(this.l/0x100000000));for(b.push(this.l|0);b.length;)u(this,b.splice(0,16));this.reset();return c},Y:[],b:[],
O:function(){function a(a){return 0x100000000*(a-Math.floor(a))|0}for(var b=0,c=2,d,e;64>b;c++){e=!0;for(d=2;d*d<=c;d++)if
(0===c%d){e=
!1;break}e&&(8>b&&(this.Y[b]=a(Math.pow(c,.5))),this.b[b]=a(Math.pow(c,1/3)),b++)}}};
function u(a,b){var c,d,e,f=a.F,g=a.b,h=f[0],k=f[1],l=f[2],n=f[3],m=f[4],p=f[5],r=f[6],q=f[7];for(c=0;64>c;c++)16>c?d=b[c]:(
d=b[c+1&15],e=b[c+14&15],d=b[c&15]=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>
;>17^e>>>19^e>>>10^e<<15^e<<13)+b[c&15]+b[c+9&15]|0),d=d+q+(m>>>6^m>>>
;11^m>>>25^m<<26^m<<21^m<<7)+(r^m&(p^r))+g[c],q=r,r=p,p=m,m=n+d|0,n=l,l=k,k=h,h=d+(k&l^n&(
k^l))+(k>>>2^k>>>13^k>>>22^k<<30^k<<19^k<<10)|0;f[0]=f[0]+h|0;f[1]=f[1]+k|0;f[2]=f[
2]+l|0;f[3]=f[3]+n|0;f[4]=f[4]+m|0;f[5]=f[5]+p|0;f[6]=f[6]+r|0;f[7]=
f[7]+q|0}
sjcl.mode.ccm={name:"ccm",G:[],listenProgress:function(a){sjcl.mode.ccm.G.push(a)},unListenProgress:function(a){a=sjcl
.mode.ccm.G.indexOf(a);-1<a&&sjcl.mode.ccm.G.splice(a,1)},fa:function(a){var b=sjcl.mode.ccm.G.slice(),c;for(c=0;c<
;b.length;c+=1)b[c](a)},encrypt:function(a,b,c,d,e){var f,g=b.slice(0),h=sjcl.bitArray,k=h.bitLength(c)/8,l=h.bitLength(g)/8;e=e
||64;d=d||[];if(7>k)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(f=2;4>f&&l&
gt;>>8*f;f++);f<15-k&&(f=15-k);c=h.clamp(c,
8*(15-f));b=sjcl.mode.ccm.V(a,b,c,d,e,f);g=sjcl.mode.ccm.C(a,g,c,b,e,f);return h.concat(g.data,g.tag)},decrypt:function(a,b,c,d,
e){e=e||64;d=d||[];var f=sjcl.bitArray,g=f.bitLength(c)/8,h=f.bitLength(b),k=f.clamp(b,h-e),l=f.bitSlice(b,h-e),h=(h-e)/8;if(7>
;g)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(b=2;4>b&&h>>>8*b;b++);
b<15-g&&(b=15-g);c=f.clamp(c,8*(15-b));k=sjcl.mode.ccm.C(a,k,c,l,e,b);a=sjcl.mode.ccm.V(a,k.data,c,d,e,b);if(!f.equal
(k.tag,a))throw new sjcl.exception.corrupt("ccm: tag doesn't match");
return k.data},na:function(a,b,c,d,e,f){var g=[],h=sjcl.bitArray,k=h.i;d=[h.partial(8,(b.length?64:0)|d-2<<2|f-1)];d=h.concat
(d,c);d[3]|=e;d=a.encrypt(d);if(b.length)for(c=h.bitLength(b)/8,65279>=c?g=[h.partial
(16,c)]:0xffffffff>=c&&(g=h.concat([h.partial(16,65534)],[c])),g=h.concat(g,b),b=0;b<g.length;b+=4)d=a.encrypt(k(d
,g.slice(b,b+4).concat([0,0,0])));return d},V:function(a,b,c,d,e,f){var g=sjcl.bitArray,h=g.i;e/=8;if(e%2||4>e||16<e)throw
new sjcl.exception.invalid("ccm: invalid tag length");
if(0xffffffff<d.length||0xffffffff<b.length)throw new sjcl.exception.bug("ccm: can't deal with 4GiB or more data
");c=sjcl.mode.ccm.na(a,d,c,e,g.bitLength(b)/8,f);for(d=0;d<b.length;d+=4)c=a.encrypt(h(c,b.slice(d,d+4).concat([0,0,0])));
return g.clamp(c,8*e)},C:function(a,b,c,d,e,f){var g,h=sjcl.bitArray;g=h.i;var k=b.length,l=h.bitLength(b),n=k/50,m=n;c=h.concat
([h.partial(8,f-1)],c).concat([0,0,0]).slice(0,4);d=h.bitSlice(g(d,a.encrypt(c)),0,e);if(!k)return{tag:d,data:[]};for(g=0;g<k
;g+=4)g>n&&(sjcl.mode.ccm.fa(g/
k),n+=m),c[3]++,e=a.encrypt(c),b[g]^=e[0],b[g+1]^=e[1],b[g+2]^=e[2],b[g+3]^=e[3];return{tag:d,data:h.clamp(b,l)}}};
sjcl.mode.ocb2={name:"ocb2",encrypt:function(a,b,c,d,e,f){if(128!==sjcl.bitArray.bitLength(c))throw new sjcl.exception
.invalid("ocb iv must be 128 bits");var g,h=sjcl.mode.ocb2.S,k=sjcl.bitArray,l=k.i,n=[0,0,0,0];c=h(a.encrypt(c));var m
,p=[];d=d||[];e=e||64;for(g=0;g+4<b.length;g+=4)m=b.slice(g,g+4),n=l(n,m),p=p.concat(l(c,a.encrypt(l(c,m)))),c=h(c);m=b.slice
(g);b=k.bitLength(m);g=a.encrypt(l(c,[0,0,0,b]));m=k.clamp(l(m.concat([0,0,0]),g),b);n=l(n,l(m.concat([0,0,0]),g));n=a.encrypt(l
(n,l(c,h(c))));
d.length&&(n=l(n,f?d:sjcl.mode.ocb2.pmac(a,d)));return p.concat(k.concat(m,k.clamp(n,e)))},decrypt:function(a,b,c,d,e,f){
if(128!==sjcl.bitArray.bitLength(c))throw new sjcl.exception.invalid("ocb iv must be 128 bits");e=e||64;var g=sjcl.mode
.ocb2.S,h=sjcl.bitArray,k=h.i,l=[0,0,0,0],n=g(a.encrypt(c)),m,p,r=sjcl.bitArray.bitLength(b)-e,q=[];d=d||[];for(c=0;c+4<r/32;
c+=4)m=k(n,a.decrypt(k(n,b.slice(c,c+4)))),l=k(l,m),q=q.concat(m),n=g(n);p=r-32*c;m=a.encrypt(k(n,[0,0,0,p]));m=k(m,h.clamp(b.slice
(c),p).concat([0,
0,0]));l=k(l,m);l=a.encrypt(k(l,k(n,g(n))));d.length&&(l=k(l,f?d:sjcl.mode.ocb2.pmac(a,d)));if(!h.equal(h.clamp(l,e),h.bitSlice
(b,r)))throw new sjcl.exception.corrupt("ocb: tag doesn't match");return q.concat(h.clamp(m,p))},pmac:function(a,
b){var c,d=sjcl.mode.ocb2.S,e=sjcl.bitArray,f=e.i,g=[0,0,0,0],h=a.encrypt([0,0,0,0]),h=f(h,d(d(h)));for(c=0;c+4<b.length;c+=4
)h=d(h),g=f(g,a.encrypt(f(h,b.slice(c,c+4))));c=b.slice(c);128>e.bitLength(c)&&(h=f(h,d(h)),c=e.concat(c,[-2147483648
,0,0,0]));g=f(g,c);
return a.encrypt(f(d(f(h,d(h))),g))},S:function(a){return[a[0]<<1^a[1]>>>31,a[1]<<1^a[2]>>>31,a[2]&
lt;<1^a[3]>>>31,a[3]<<1^135*(a[0]>>>31)]}};
sjcl.mode.gcm={name:"gcm",encrypt:function(a,b,c,d,e){var f=b.slice(0);b=sjcl.bitArray;d=d||[];a=sjcl.mode.gcm.C(!0,a,
f,d,c,e||128);return b.concat(a.data,a.tag)},decrypt:function(a,b,c,d,e){var f=b.slice(0),g=sjcl.bitArray,h=g.bitLength(f);e=e||
128;d=d||[];e<=h?(b=g.bitSlice(f,h-e),f=g.bitSlice(f,0,h-e)):(b=f,f=[]);a=sjcl.mode.gcm.C(!1,a,f,d,c,e);if(!g.equal(a.tag,b))
throw new sjcl.exception.corrupt("gcm: tag doesn't match");return a.data},ka:function(a,b){var c,d,e,f,g,h=sjcl.bitArray
.i;e=[0,0,
...
function(a, b, c){void 0===a&&(a={});if(void 0===b)return a;for(var d in b)if(b.hasOwnProperty(d)){if(c&&void 0!==a[d]&&a[d]!==b[d ])throw new sjcl.exception.invalid("required parameter overridden");a[d]=b[d]}return a}
...
this.D=!0}},stopCollectors:function(){this.D&&(window.removeEventListener?(window.removeEventListener("load",this
.a.loadTimeCollector,!1),window.removeEventListener("mousemove",this.a.mouseCollector,!1),window.removeEventListener(&
quot;keypress",this.a.keyboardCollector,!1),window.removeEventListener("devicemotion",this.a.accelerometerCollector
,!1),window.removeEventListener("touchmove",this.a.touchCollector,!1)):document.detachEvent&&(document.detachEvent
("onload",this.a.loadTimeCollector),document.detachEvent("onmousemove",
this.a.mouseCollector),document.detachEvent("keypress",this.a.keyboardCollector)),this.D=!1)},addEventListener:function
(a,b){this.K[a][this.ga++]=b},removeEventListener:function(a,b){var c,d,e=this.K[a],f=[];for(d in e)e.hasOwnProperty(d)&&
;e[d]===b&&f.push(d);for(c=0;c<f.length;c++)d=f[c],delete e[d]},la:function(){C(this,1)},oa:function(a){var b,c;try{b
=a.x||a.clientX||a.offsetX||0,c=a.y||a.clientY||a.offsetY||0}catch(d){c=b=0}0!=b&&0!=c&&this.addEntropy([b,c],2,&
quot;mouse");C(this,0)},qa:function(a){a=
a.touches[0]||a.changedTouches[0];this.addEntropy([a.pageX||a.clientX,a.pageY||a.clientY],1,"touch");C(this,0)},ma:function
(){C(this,2)},ea:function(a){a=a.accelerationIncludingGravity.x||a.accelerationIncludingGravity.y||a.accelerationIncludingGravity
.z;if(window.orientation){var b=window.orientation;"number"===typeof b&&this.addEntropy(b,1,"accelerometer
")}a&&this.addEntropy(a,2,"accelerometer");C(this,0)}};
function A(a,b){var c,d=sjcl.random.K[a],e=[];for(c in d)d.hasOwnProperty(c)&&e.push(d[c]);for(c=0;c<e.length;c++)e[c
](b)}function C(a,b){"undefined"!==typeof window&&window.performance&&"function"===typeof window
.performance.now?a.addEntropy(window.performance.now(),b,"loadtime"):a.addEntropy((new Date).valueOf(),b,"loadtime
")}function y(a){a.b=z(a).concat(z(a));a.L=new sjcl.cipher.aes(a.b)}function z(a){for(var b=0;4>b&&(a.h[b]=a.h[b
]+1|0,!a.h[b]);b++);return a.L.encrypt(a.h)}
function B(a,b){return function(){b.apply(a,arguments)}}sjcl.random=new sjcl.prng(6);
a:try{var D,E,F,G;if(G="undefined"!==typeof module&&module.exports){var H;try{H=require("crypto")}catch
(a){H=null}G=E=H}if(G&&E.randomBytes)D=E.randomBytes(128),D=new Uint32Array((new Uint8Array(D)).buffer),sjcl.random.addEntropy
(D,1024,"crypto['randomBytes']");else if("undefined"!==typeof window&&"undefined"
;!==typeof Uint32Array){F=new Uint32Array(32);if(window.crypto&&window.crypto.getRandomValues)window.crypto.getRandomValues
(F);else if(window.msCrypto&&window.msCrypto.getRandomValues)window.msCrypto.getRandomValues(F);
else break a;sjcl.random.addEntropy(F,1024,"crypto['getRandomValues']")}}catch(a){"undefined"!==typeof
window&&window.console&&(console.log("There was an error collecting entropy from the browser:"),console
.log(a))}
sjcl.json={defaults:{v:1,iter:1E4,ks:128,ts:64,mode:"ccm",adata:"",cipher:"aes"},ja:function(a,b,c
,d){c=c||{};d=d||{};var e=sjcl.json,f=e.g({iv:sjcl.random.randomWords(4,0)},e.defaults
),g;e.g(f,c);c=f.adata;"string"===typeof f.salt&&(f.salt=sjcl.codec.base64.toBits(f.salt));"string"===
typeof f.iv&&(f.iv=sjcl.codec.base64.toBits(f.iv));if(!sjcl.mode[f.mode]||!sjcl.cipher[f.cipher]||"string"===typeof
a&&100>=f.iter||64!==f.ts&&96!==f.ts&&128!==f.ts||128!==f.ks&&192!==f.ks&&0x100!==f.
ks||2>f.iv.length||
4<f.iv.length)throw new sjcl.exception.invalid("json encrypt: invalid parameters");"string"===typeof a?(g
=sjcl.misc.cachedPbkdf2(a,f),a=g.key.slice(0,f.ks/32),f.salt=g.salt):sjcl.ecc&&a instanceof sjcl.ecc.elGamal.publicKey&
;&(g=a.kem(),f.kemtag=g.tag,a=g.key.slice(0,f.ks/32));"string"===typeof b&&(b=sjcl.codec.utf8String.toBits
(b));"string"===typeof c&&(f.adata=c=sjcl.codec.utf8String.toBits(c));g=new sjcl.cipher[f.cipher](a);e.g(d,f);
d.key=a;f.ct="ccm"===f.mode&&sjcl.arrayBuffer&&sjcl.arrayBuffer.ccm&&
b instanceof ArrayBuffer?sjcl.arrayBuffer.ccm.encrypt(g,b,f.iv,c,f.ts):sjcl.mode[f.mode].encrypt(g,b,f.iv,c,f.ts);return f},encrypt
:function(a,b,c,d){var e=sjcl.json,f=e.ja.apply(e,arguments);return e.encode(f)},ia:function(a,b,c,d){c=c||{};d=d||{};var e=sjcl
.json;b=e.g(e.g(e.g({},e.defaults),b),c,!0);var f,g;f=b.adata;"string"===typeof b.salt&&(b.salt=sjcl.codec.base64
.toBits(b.salt));"string"===typeof b.iv&&(b.iv=sjcl.codec.base64.toBits(b.iv));if(!sjcl.mode[b.mode]||!sjcl.cipher
[b.cipher]||"string"===
typeof a&&100>=b.iter||64!==b.ts&&96!==b.ts&&128!==b.ts||128!==b.ks&&192!==b.ks&&0x100
!==b.ks||!b.iv||2>b.iv.length||4<b.iv.length)throw new sjcl.exception.invalid("json decrypt: invalid parameters");&
quot;string"===typeof a?(g=sjcl.misc.cachedPbkdf2(a,b),a=g.key.slice(0,b.ks/32),b.salt=g.salt):sjcl.ecc&&a instanceof
sjcl.ecc.elGamal.secretKey&&(a=a.unkem(sjcl.codec.base64.toBits(b.kemtag)).slice(0,b.ks/32));"string"===typeof
f&&(f=sjcl.codec.utf8String.toBits(f));g=new sjcl.cipher[b.cipher](a);f="ccm"===
b.mode&&sjcl.arrayBuffer&&sjcl.arrayBuffer.ccm&&b.ct instanceof ArrayBuffer?sjcl.arrayBuffer.ccm.decrypt
(g,b.ct,b.iv,b.tag,f,b.ts):sjcl.mode[b.mode].decrypt(g,b.ct,b.iv,f,b.ts);e.g(d,b);d.key=a;return 1===c.raw?f:sjcl.codec.utf8String
.fromBits(f)},decrypt:function(a,b,c,d){var e=sjcl.json;return e.ia(a,e.decode(b),c,d)},encode:function(a){var b,c="{",
d="";for(b in a)if(a.hasOwnProperty(b)){if(!b.match(/^[a-z0-9]+$/i))throw new sjcl.exception.invalid("json encode
: invalid property name");c+=d+'"'+
b+'":';d=",";switch(typeof a[b]){case "number":case "boolean":c+=a[b];break;case "
;string":c+='"'+escape(a[b])+'"';break;case "object":c+='"'+sjcl.codec
.base64.fromBits(a[b],0)+'"';break;default:throw new sjcl.exception.bug("json encode: unsupported type");}}
return c+"}"},decode:function(a){a=a.replace(/\s/g,"");if(!a.match(/^\{.*\}$/))throw new sjcl.exception.invalid("json decode: this isn't json!");a=a.replace(/^\{|\}$/g,"").split(/,/);var b={},c,d;for(c=0;c<a.length;c++){if(!(d=a[c].match(/^\s*(?:(["']?)([a-z][a-z0-9]*)\1)\s*:\s*(?:(-?\d+)|"([a-z0-9+\/%*_.@=\-]*)"|(true|false))$/i)))throw new sjcl.exception.invalid("json decode: this isn't json!");
null!=d[3]?b[d[2]]=parseInt(d[3],10):null!=d[4]?b[d[2]]=d[2].match(/^(ct|adata|salt|iv)$/)?sjcl.codec.base64.toBits(d[4]):unescape
(d[4]):null!=d[5]&&(b[d[2]]="true"===d[5])}return b},g:function(a,b,c){void 0===a&&(a={});if(void 0===
b)return a;for(var d in b)if(b.hasOwnProperty(d)){if(c&&void 0!==a[d]&&a[d]!==b[d])throw new sjcl.exception.invalid
("required parameter overridden");a[d]=b[d]}return a},sa:function(a,b){var c={},d;for(d in a)a.hasOwnProperty(d)&&
amp;a[d]!==b[d]&&(c[d]=a[d]);return c},ra:function(a,
b){var c={},d;for(d=0;d<b.length;d++)void 0!==a[b[d]]&&(c[b[d]]=a[b[d]]);return c}};sjcl.encrypt=sjcl.json.encrypt;sjcl
.decrypt=sjcl.json.decrypt;sjcl.misc.pa={};sjcl.misc.cachedPbkdf2=function(a,b){var c=sjcl.misc.pa,d;b=b||{};d=b.iter||1E3;c=c[a
]=c[a]||{};d=c[d]=c[d]||{firstSalt:b.salt&&b.salt.length?b.salt.slice(0):sjcl.random.randomWords(2,0)};c=void 0===b.salt
?d.firstSalt:b.salt;d[c]=d[c]||sjcl.misc.pbkdf2(a,c,b.iter);return{key:d[c].slice(0),salt:c.slice(0)}};
...
function(a, b, c, d){c=c||{};d=d||{};var e=sjcl.json;b=e.g(e.g(e.g({},e.defaults),b),c,!0);var f,g;f=b.adata;"string"===typeof b.salt &&(b.salt=sjcl.codec.base64.toBits(b.salt));"string"===typeof b.iv&&(b.iv=sjcl.codec.base64.toBits(b.iv));if(!sjcl.mode[b.mode]||! sjcl.cipher[b.cipher]||"string"=== typeof a&&100>=b.iter||64!==b.ts&&96!==b.ts&&128!==b.ts||128!==b.ks&&192!==b.ks&&0x100!==b.ks||!b.iv||2>b.iv.length||4<b.iv.length )throw new sjcl.exception.invalid("json decrypt: invalid parameters");"string"===typeof a?(g=sjcl.misc.cachedPbkdf2(a,b),a=g.key .slice(0,b.ks/32),b.salt=g.salt):sjcl.ecc&&a instanceof sjcl.ecc.elGamal.secretKey&&(a=a.unkem(sjcl.codec.base64.toBits(b.kemtag )).slice(0,b.ks/32));"string"===typeof f&&(f=sjcl.codec.utf8String.toBits(f));g=new sjcl.cipher[b.cipher](a);f="ccm"=== b.mode&&sjcl.arrayBuffer&&sjcl.arrayBuffer.ccm&&b.ct instanceof ArrayBuffer?sjcl.arrayBuffer.ccm.decrypt(g,b.ct,b.iv,b.tag,f,b.ts ):sjcl.mode[b.mode].decrypt(g,b.ct,b.iv,f,b.ts);e.g(d,b);d.key=a;return 1===c.raw?f:sjcl.codec.utf8String.fromBits(f)}
...
function B(a,b){return function(){b.apply(a,arguments)}}sjcl.random=new sjcl.prng(6);
a:try{var D,E,F,G;if(G="undefined"!==typeof module&&module.exports){var H;try{H=require("crypto")}catch
(a){H=null}G=E=H}if(G&&E.randomBytes)D=E.randomBytes(128),D=new Uint32Array((new Uint8Array(D)).buffer),sjcl.random.addEntropy
(D,1024,"crypto['randomBytes']");else if("undefined"!==typeof window&&"undefined"
;!==typeof Uint32Array){F=new Uint32Array(32);if(window.crypto&&window.crypto.getRandomValues)window.crypto.getRandomValues
(F);else if(window.msCrypto&&window.msCrypto.getRandomValues)window.msCrypto.getRandomValues(F);
else break a;sjcl.random.addEntropy(F,1024,"crypto['getRandomValues']")}}catch(a){"undefined"!==typeof
window&&window.console&&(console.log("There was an error collecting entropy from the browser:"),console
.log(a))}
sjcl.json={defaults:{v:1,iter:1E4,ks:128,ts:64,mode:"ccm",adata:"",cipher:"aes"},ja:function(a,b,c
,d){c=c||{};d=d||{};var e=sjcl.json,f=e.g({iv:sjcl.random.randomWords(4,0)},e.defaults),g;e.g(f,c);c=f.adata;"string"===
typeof f.salt&&(f.salt=sjcl.codec.base64.toBits(f.salt));"string"===typeof f.iv&&(f.iv=sjcl.codec.base64
.toBits(f.iv));if(!sjcl.mode[f.mode]||!sjcl.cipher[f.cipher]||"string"===typeof a&&100>=f.iter||64!==f.ts&
;&96!==f.ts&&128!==f.ts||128!==f.ks&&192!==f.ks&&0x100!==f.ks||2>f.iv.length||
4<f.iv.length)throw new sjcl.exception.invalid("json encrypt: invalid parameters");"string"===typeof a?(g
=sjcl.misc.cachedPbkdf2(a,f),a=g.key.slice(0,f.ks/32),f.salt=g.salt):sjcl.ecc&&a instanceof sjcl.ecc.elGamal.publicKey&
;&(g=a.kem(),f.kemtag=g.tag,a=g.key.slice(0,f.ks/32));"string"===typeof b&&(b=sjcl.codec.utf8String.toBits
(b));"string"===typeof c&&(f.adata=c=sjcl.codec.utf8String.toBits(c));g=new sjcl.cipher[f.cipher](a);e.g(d,f);
d.key=a;f.ct="ccm"===f.mode&&sjcl.arrayBuffer&&sjcl.arrayBuffer.ccm&&
b instanceof ArrayBuffer?sjcl.arrayBuffer.ccm.encrypt(g,b,f.iv,c,f.ts):sjcl.mode[f.mode].encrypt(g,b,f.iv,c,f.ts);return f},encrypt
:function(a,b,c,d){var e=sjcl.json,f=e.ja.apply(e,arguments);return e.encode(f)},ia:function(a,b,c,d){c=c||{};d=d||{};var e=sjcl
.json;b=e.g(e.g(e.g({},e.defaults),b),c,!0);var f,g;f=b.adata;"string"===typeof b.salt&&(b.salt=sjcl.codec.base64
.toBits(b.salt));"string"===typeof b.iv&&(b.iv=sjcl.codec.base64.toBits(b.iv));if(!sjcl.mode[b.mode]||!sjcl.cipher
[b.cipher]||"string"===
typeof a&&100>=b.iter||64!==b.ts&&96!==b.ts&&128!==b.ts||128!==b.ks&&192!==b.ks&&0x100
!==b.ks||!b.iv||2>b.iv.length||4<b.iv.length)throw new sjcl.exception.invalid("json decrypt: invalid parameters");&
quot;string"===typeof a?(g=sjcl.misc.cachedPbkdf2(a,b),a=g.key.slice(0,b.ks/32),b.salt=g.salt):sjcl.ecc&&a instanceof
sjcl.ecc.elGamal.secretKey&&(a=a.unkem(sjcl.codec.base64.toBits(b.kemtag)).slice(0,b.ks/32));"string"===typeof
f&&(f=sjcl.codec.utf8String.toBits(f));g=new sjcl.cipher[b.cipher](a);f="ccm"===
b.mode&&sjcl.arrayBuffer&&sjcl.arrayBuffer.ccm&&b.ct instanceof ArrayBuffer?sjcl.arrayBuffer.ccm.decrypt
(g,b.ct,b.iv,b.tag,f,b.ts):sjcl.mode[b.mode].decrypt(g,b.ct,b.iv,f,b.ts);e.g(d,b);d.key=a;return 1===c.raw?f:sjcl.codec.utf8String
.fromBits(f)},decrypt:function(a,b,c,d){var e=sjcl.json;return e.ia(a,e.decode(b),c,d
)},encode:function(a){var b,c="{",d="";for(b in a)if(a.hasOwnProperty(b)){if(!b.match(/^[a-z0-9]+$/i))throw
new sjcl.exception.invalid("json encode: invalid property name");c+=d+'"'+
b+'":';d=",";switch(typeof a[b]){case "number":case "boolean":c+=a[b];break;case "
;string":c+='"'+escape(a[b])+'"';break;case "object":c+='"'+sjcl.codec
.base64.fromBits(a[b],0)+'"';break;default:throw new sjcl.exception.bug("json encode: unsupported type");}}
return c+"}"},decode:function(a){a=a.replace(/\s/g,"");if(!a.match(/^\{.*\}$/))throw new sjcl.exception.invalid("json decode: this isn't json!");a=a.replace(/^\{|\}$/g,"").split(/,/);var b={},c,d;for(c=0;c<a.length;c++){if(!(d=a[c].match(/^\s*(?:(["']?)([a-z][a-z0-9]*)\1)\s*:\s*(?:(-?\d+)|"([a-z0-9+\/%*_.@=\-]*)"|(true|false))$/i)))throw new sjcl.exception.invalid("json decode: this isn't json!");
null!=d[3]?b[d[2]]=parseInt(d[3],10):null!=d[4]?b[d[2]]=d[2].match(/^(ct|adata|salt|iv)$/)?sjcl.codec.base64.toBits(d[4]):unescape
(d[4]):null!=d[5]&&(b[d[2]]="true"===d[5])}return b},g:function(a,b,c){void 0===a&&(a={});if(void 0===
b)return a;for(var d in b)if(b.hasOwnProperty(d)){if(c&&void 0!==a[d]&&a[d]!==b[d])throw new sjcl.exception.invalid
("required parameter overridden");a[d]=b[d]}return a},sa:function(a,b){var c={},d;for(d in a)a.hasOwnProperty(d)&&
amp;a[d]!==b[d]&&(c[d]=a[d]);return c},ra:function(a,
b){var c={},d;for(d=0;d<b.length;d++)void 0!==a[b[d]]&&(c[b[d]]=a[b[d]]);return c}};sjcl.encrypt=sjcl.json.encrypt;sjcl
.decrypt=sjcl.json.decrypt;sjcl.misc.pa={};sjcl.misc.cachedPbkdf2=function(a,b){var c=sjcl.misc.pa,d;b=b||{};d=b.iter||1E3;c=c[a
]=c[a]||{};d=c[d]=c[d]||{firstSalt:b.salt&&b.salt.length?b.salt.slice(0):sjcl.random.randomWords(2,0)};c=void 0===b.salt
?d.firstSalt:b.salt;d[c]=d[c]||sjcl.misc.pbkdf2(a,c,b.iter);return{key:d[c].slice(0),salt:c.slice(0)}};
"undefined"!==typeof module&&module.exports&&(module.exports=sjcl);"function"===typeof define
&&define([],function(){return sjcl});
local.sjcl = sjcl;
...
function(a, b, c, d){c=c||{};d=d||{};var e=sjcl.json,f=e.g({iv:sjcl.random.randomWords(4,0)},e.defaults),g;e.g(f,c);c=f.adata;"string "===typeof f.salt&&(f.salt=sjcl.codec.base64.toBits(f.salt));"string"===typeof f.iv&&(f.iv=sjcl.codec.base64.toBits(f.iv));if(!sjcl .mode[f.mode]||!sjcl.cipher[f.cipher]||"string"===typeof a&&100>=f.iter||64!==f.ts&&96!==f.ts&&128!==f.ts||128!==f.ks&&192!==f.ks &&0x100!==f.ks||2>f.iv.length|| 4<f.iv.length)throw new sjcl.exception.invalid("json encrypt: invalid parameters");"string"===typeof a?(g=sjcl.misc.cachedPbkdf2 (a,f),a=g.key.slice(0,f.ks/32),f.salt=g.salt):sjcl.ecc&&a instanceof sjcl.ecc.elGamal.publicKey&&(g=a.kem(),f.kemtag=g.tag,a=g.key .slice(0,f.ks/32));"string"===typeof b&&(b=sjcl.codec.utf8String.toBits(b));"string"===typeof c&&(f.adata=c=sjcl.codec.utf8String .toBits(c));g=new sjcl.cipher[f.cipher](a);e.g(d,f);d.key=a;f.ct="ccm"===f.mode&&sjcl.arrayBuffer&&sjcl.arrayBuffer.ccm&& b instanceof ArrayBuffer?sjcl.arrayBuffer.ccm.encrypt(g,b,f.iv,c,f.ts):sjcl.mode[f.mode].encrypt(g,b,f.iv,c,f.ts);return f}
n/a
function(a, b){var c={},d;for(d=0;d<b.length;d++)void 0!==a[b[d]]&&(c[b[d]]=a[b[d]]);return c}
n/a
function(a, b){var c={},d;for(d in a)a.hasOwnProperty(d)&&a[d]!==b[d]&&(c[d]=a[d]);return c}
n/a
function(a, b){var c=sjcl.misc.pa,d;b=b||{};d=b.iter||1E3;c=c[a]=c[a]||{};d=c[d]=c[d]||{firstSalt:b.salt&&b.salt.length?b.salt.slice (0):sjcl.random.randomWords(2,0)};c=void 0===b.salt?d.firstSalt:b.salt;d[c]=d[c]||sjcl.misc.pbkdf2(a,c,b.iter);return{key:d[c].slice (0),salt:c.slice(0)}}
...
this.a.mouseCollector),document.detachEvent("keypress",this.a.keyboardCollector)),this.D=!1)},addEventListener:function
(a,b){this.K[a][this.ga++]=b},removeEventListener:function(a,b){var c,d,e=this.K[a],f=[];for(d in e)e.hasOwnProperty(d)&&
;e[d]===b&&f.push(d);for(c=0;c<f.length;c++)d=f[c],delete e[d]},la:function(){C(this,1)},oa:function(a){var b,c;try{b
=a.x||a.clientX||a.offsetX||0,c=a.y||a.clientY||a.offsetY||0}catch(d){c=b=0}0!=b&&0!=c&&this.addEntropy([b,c],2,&
quot;mouse");C(this,0)},qa:function(a){a=
a.touches[0]||a.changedTouches[0];this.addEntropy([a.pageX||a.clientX,a.pageY||a.clientY],1,"touch");C(this,0)},ma:function
(){C(this,2)},ea:function(a){a=a.accelerationIncludingGravity.x||a.accelerationIncludingGravity.y||a.accelerationIncludingGravity
.z;if(window.orientation){var b=window.orientation;"number"===typeof b&&this.addEntropy(b,1,"accelerometer
")}a&&this.addEntropy(a,2,"accelerometer");C(this,0)}};
function A(a,b){var c,d=sjcl.random.K[a],e=[];for(c in d)d.hasOwnProperty(c)&&e.push(d[c]);for(c=0;c<e.length;c++)e[c
](b)}function C(a,b){"undefined"!==typeof window&&window.performance&&"function"===typeof window
.performance.now?a.addEntropy(window.performance.now(),b,"loadtime"):a.addEntropy((new Date).valueOf(),b,"loadtime
")}function y(a){a.b=z(a).concat(z(a));a.L=new sjcl.cipher.aes(a.b)}function z(a){for(var b=0;4>b&&(a.h[b]=a.h[b
]+1|0,!a.h[b]);b++);return a.L.encrypt(a.h)}
function B(a,b){return function(){b.apply(a,arguments)}}sjcl.random=new sjcl.prng(6);
a:try{var D,E,F,G;if(G="undefined"!==typeof module&&module.exports){var H;try{H=require("crypto")}catch
(a){H=null}G=E=H}if(G&&E.randomBytes)D=E.randomBytes(128),D=new Uint32Array((new Uint8Array(D)).buffer),sjcl.random.addEntropy
(D,1024,"crypto['randomBytes']");else if("undefined"!==typeof window&&"undefined"
;!==typeof Uint32Array){F=new Uint32Array(32);if(window.crypto&&window.crypto.getRandomValues)window.crypto.getRandomValues
(F);else if(window.msCrypto&&window.msCrypto.getRandomValues)window.msCrypto.getRandomValues(F);
else break a;sjcl.random.addEntropy(F,1024,"crypto['getRandomValues']")}}catch(a){"undefined"!==typeof
window&&window.console&&(console.log("There was an error collecting entropy from the browser:"),console
.log(a))}
sjcl.json={defaults:{v:1,iter:1E4,ks:128,ts:64,mode:"ccm",adata:"",cipher:"aes"},ja:function(a,b,c
,d){c=c||{};d=d||{};var e=sjcl.json,f=e.g({iv:sjcl.random.randomWords(4,0)},e.defaults),g;e.g(f,c);c=f.adata;"string"===
typeof f.salt&&(f.salt=sjcl.codec.base64.toBits(f.salt));"string"===typeof f.iv&&(f.iv=sjcl.codec.base64
.toBits(f.iv));if(!sjcl.mode[f.mode]||!sjcl.cipher[f.cipher]||"string"===typeof a&&100>=f.iter||64!==f.ts&
;&96!==f.ts&&128!==f.ts||128!==f.ks&&192!==f.ks&&0x100!==f.ks||2>f.iv.length||
4<f.iv.length)throw new sjcl.exception.invalid("json encrypt: invalid parameters");"string"===typeof a?(g
=sjcl.misc.cachedPbkdf2(a,f),a=g.key.slice(0,f.ks/32),f.salt=g.salt):sjcl.ecc&&
;a instanceof sjcl.ecc.elGamal.publicKey&&(g=a.kem(),f.kemtag=g.tag,a=g.key.slice(0,f.ks/32));"string"===typeof
b&&(b=sjcl.codec.utf8String.toBits(b));"string"===typeof c&&(f.adata=c=sjcl.codec.utf8String.toBits(c
));g=new sjcl.cipher[f.cipher](a);e.g(d,f);d.key=a;f.ct="ccm"===f.mode&&sjcl.arrayBuffer&&sjcl.arrayBuffer
.ccm&&
b instanceof ArrayBuffer?sjcl.arrayBuffer.ccm.encrypt(g,b,f.iv,c,f.ts):sjcl.mode[f.mode].encrypt(g,b,f.iv,c,f.ts);return f},encrypt
:function(a,b,c,d){var e=sjcl.json,f=e.ja.apply(e,arguments);return e.encode(f)},ia:function(a,b,c,d){c=c||{};d=d||{};var e=sjcl
.json;b=e.g(e.g(e.g({},e.defaults),b),c,!0);var f,g;f=b.adata;"string"===typeof b.salt&&(b.salt=sjcl.codec.base64
.toBits(b.salt));"string"===typeof b.iv&&(b.iv=sjcl.codec.base64.toBits(b.iv));if(!sjcl.mode[b.mode]||!sjcl.cipher
[b.cipher]||"string"===
typeof a&&100>=b.iter||64!==b.ts&&96!==b.ts&&128!==b.ts||128!==b.ks&&192!==b.ks&&0x100
!==b.ks||!b.iv||2>b.iv.length||4<b.iv.length)throw new sjcl.exception.invalid("json decrypt: invalid parameters");&
quot;string"===typeof a?(g=sjcl.misc.cachedPbkdf2(a,b),a=g.key.slice(0,b.ks/32),b.salt=g.salt):sjcl.ecc&&a instanceof
sjcl.ecc.elGamal.secretKey&&(a=a.unkem(sjcl.codec.base64.toBits(b.kemtag)).slice(0,b.ks/32));"string"===typeof
f&&(f=sjcl.codec.utf8String.toBits(f));g=new sjcl.cipher[b.cipher](a);f="ccm"===
b.mode&&sjcl.arrayBuffer&&sjcl.arrayBuffer.ccm&&b.ct instanceof ArrayBuffer?sjcl.arrayBuffer.ccm.decrypt
(g,b.ct,b.iv,b.tag,f,b.ts):sjcl.mode[b.mode].decrypt(g,b.ct,b.iv,f,b.ts);e.g(d,b);d.key=a;return 1===c.raw?f:sjcl.codec.utf8String
.fromBits(f)},decrypt:function(a,b,c,d){var e=sjcl.json;return e.ia(a,e.decode(b),c,d)},encode:function(a){var b,c="{",
d="";for(b in a)if(a.hasOwnProperty(b)){if(!b.match(/^[a-z0-9]+$/i))throw new sjcl.exception.invalid("json encode
: invalid property name");c+=d+'"'+
b+'":';d=",";switch(typeof a[b]){case "number":case "boolean":c+=a[b];break;case "
;string":c+='"'+escape(a[b])+'"';break;case "object":c+='"'+sjcl.codec
.base64.fromBits(a[b],0)+'"';break;default:throw new sjcl.exception.bug("json encode: unsupported type");}}
return c+"}"},decode:function(a){a=a.replace(/\s/g,"");if(!a.match(/^\{.*\}$/))throw new sjcl.exception.invalid("json decode: this isn't json!");a=a.replace(/^\{|\}$/g,"").split(/,/);var b={},c,d;for(c=0;c<a.length;c++){if(!(d=a[c].match(/^\s*(?:(["']?)([a-z][a-z0-9]*)\1)\s*:\s*(?:(-?\d+)|"([a-z0-9+\/%*_.@=\-]*)"|(true|false))$/i)))throw new sjcl.exception.invalid("json decode: this isn't json!");
null!=d[3]?b[d[2]]=parseInt(d[3],10):null!=d[4]?b[d[2]]=d[2].match(/^(ct|adata|salt|iv)$/)?sjcl.codec.base64.toBits(d[4]):unescape
(d[4]):null!=d[5]&&(b[d[2]]="true"===d[5])}return b},g:function(a,b,c){void 0===a&&(a={});if(void 0===
b)return a;for(var d in b)if(b.hasOwnProperty(d)){if(c&&void 0!==a[d]&&a[d]!==b[d])throw new sjcl.exception.invalid
("required parameter overridden");a[d]=b[d]}return a},sa:function(a,b){var c={},d;for(d in a)a.hasOwnProperty(d)&&
amp;a[d]!==b[d]&&(c[d]=a[d]);return c},ra:function(a,
b){var c={},d;for(d=0;d<b.length;d++)void 0!==a[b[d]]&&(c[b[d]]=a[b[d]]);return c}};sjcl.encrypt=sjcl.json.encrypt;sjcl
.decrypt=sjcl.json.decrypt;sjcl.misc.pa={};sjcl.misc.cachedPbkdf2=function(a,b){var c=sjcl.misc.pa,d;b=b||{};d=b.iter||1E3;c=c[a
]=c[a]||{};d=c[d]=c[d]||{firstSalt:b.salt&&b.salt.length?b.salt.slice(0):sjcl.random.randomWords(2,0)};c=void 0===b.salt
?d.firstSalt:b.salt;d[c]=d[c]||sjcl.misc.pbkdf2(a,c,b.iter);return{key:d[c].slice(0),salt:c.slice(0)}};
"undefined"!==typeof module&&module.exports&&(module.exports=sjcl);"function"===typeof define
&&define([],function(){return sjcl});
...
function(a, b){this.W=b=b||sjcl.hash.sha256;var c=[[],[]],d,e=b.prototype.blockSize/32;this.w=[new b,new b];a.length>e&&(a=b.hash (a));for(d=0;d<e;d++)c[0][d]=a[d]^909522486,c[1][d]=a[d]^1549556828;this.w[0].update(c[0]);this.w[1].update(c[1]);this.R=new b(this .w[0])}
n/a
function(a, b, c, d, e){c=c||1E4;if(0>d||0>c)throw new sjcl.exception.invalid("invalid params to pbkdf2");"string"===typeof a&&(a=sjcl .codec.utf8String.toBits(a));"string"===typeof b&&(b=sjcl.codec.utf8String.toBits(b));e=e||sjcl.misc.hmac;a=new e(a);var f,g,h,k ,l=[],n=sjcl.bitArray;for(k=1;32*l.length<(d||1);k++){e=f=a.encrypt(n.concat(b,[k]));for(g=1;g<c;g++)for(f=a.encrypt(f),h=0;h<f. length;h++)e[h]^=f[h];l=l.concat(e)}d&&(l=n.clamp(l,d));return l}
...
sjcl.json={defaults:{v:1,iter:1E4,ks:128,ts:64,mode:"ccm",adata:"",cipher:"aes"},ja:function(a,b,c
,d){c=c||{};d=d||{};var e=sjcl.json,f=e.g({iv:sjcl.random.randomWords(4,0)},e.defaults),g;e.g(f,c);c=f.adata;"string"===
typeof f.salt&&(f.salt=sjcl.codec.base64.toBits(f.salt));"string"===typeof f.iv&&(f.iv=sjcl.codec.base64
.toBits(f.iv));if(!sjcl.mode[f.mode]||!sjcl.cipher[f.cipher]||"string"===typeof a&&100>=f.iter||64!==f.ts&
;&96!==f.ts&&128!==f.ts||128!==f.ks&&192!==f.ks&&0x100!==f.ks||2>f.iv.length||
4<f.iv.length)throw new sjcl.exception.invalid("json encrypt: invalid parameters");"string"===typeof a?(g
=sjcl.misc.cachedPbkdf2(a,f),a=g.key.slice(0,f.ks/32),f.salt=g.salt):sjcl.ecc&&a instanceof sjcl.ecc.elGamal.publicKey&
;&(g=a.kem(),f.kemtag=g.tag,a=g.key.slice(0,f.ks/32));"string"===typeof b&&(b=sjcl.codec.utf8String.toBits
(b));"string"===typeof c&&(f.adata=c=sjcl.codec.utf8String.toBits(c));g=new sjcl.cipher[f.cipher](a);e.g(d,f);
d.key=a;f.ct="ccm"===f.mode&&sjcl.arrayBuffer&&sjcl.arrayBuffer.ccm&&
b instanceof ArrayBuffer?sjcl.arrayBuffer.ccm.encrypt(g,b,f.iv,c,f.ts):sjcl.mode[f.mode].encrypt(g,b,f.iv,c,f.ts);return f},encrypt
:function(a,b,c,d){var e=sjcl.json,f=e.ja.apply(e,arguments);return e.encode(f)},ia:function(a,b,c,d){c=c||{};d=d||{};var e=sjcl
.json;b=e.g(e.g(e.g({},e.defaults),b),c,!0);var f,g;f=b.adata;"string"===typeof b.salt&&(b.salt=sjcl.codec.base64
.toBits(b.salt));"string"===typeof b.iv&&(b.iv=sjcl.codec.base64.toBits(b.iv));if(!sjcl.mode[b.mode]||!sjcl.cipher
[b.cipher]||"string"===
typeof a&&100>=b.iter||64!==b.ts&&96!==b.ts&&128!==b.ts||128!==b.ks&&192!==b.ks&&0x100
!==b.ks||!b.iv||2>b.iv.length||4<b.iv.length)throw new sjcl.exception.invalid("json decrypt: invalid parameters");&
quot;string"===typeof a?(g=sjcl.misc.cachedPbkdf2(a,b),a=g.key.slice(0,b.ks/32),b.salt=g.salt):sjcl.ecc&&a instanceof
sjcl.ecc.elGamal.secretKey&&(a=a.unkem(sjcl.codec.base64.toBits(b.kemtag)).slice(0,b.ks/32));"string"===typeof
f&&(f=sjcl.codec.utf8String.toBits(f));g=new sjcl.cipher[b.cipher](a);f="ccm"===
b.mode&&sjcl.arrayBuffer&&sjcl.arrayBuffer.ccm&&b.ct instanceof ArrayBuffer?sjcl.arrayBuffer.ccm.decrypt
(g,b.ct,b.iv,b.tag,f,b.ts):sjcl.mode[b.mode].decrypt(g,b.ct,b.iv,f,b.ts);e.g(d,b);d.key=a;return 1===c.raw?f:sjcl.codec.utf8String
.fromBits(f)},decrypt:function(a,b,c,d){var e=sjcl.json;return e.ia(a,e.decode(b),c,d)},encode:function(a){var b,c="{",
d="";for(b in a)if(a.hasOwnProperty(b)){if(!b.match(/^[a-z0-9]+$/i))throw new sjcl.exception.invalid("json encode
: invalid property name");c+=d+'"'+
b+'":';d=",";switch(typeof a[b]){case "number":case "boolean":c+=a[b];break;case "
;string":c+='"'+escape(a[b])+'"';break;case "object":c+='"'+sjcl.codec
.base64.fromBits(a[b],0)+'"';break;default:throw new sjcl.exception.bug("json encode: unsupported type");}}
return c+"}"},decode:function(a){a=a.replace(/\s/g,"");if(!a.match(/^\{.*\}$/))throw new sjcl.exception.invalid("json decode: this isn't json!");a=a.replace(/^\{|\}$/g,"").split(/,/);var b={},c,d;for(c=0;c<a.length;c++){if(!(d=a[c].match(/^\s*(?:(["']?)([a-z][a-z0-9]*)\1)\s*:\s*(?:(-?\d+)|"([a-z0-9+\/%*_.@=\-]*)"|(true|false))$/i)))throw new sjcl.exception.invalid("json decode: this isn't json!");
null!=d[3]?b[d[2]]=parseInt(d[3],10):null!=d[4]?b[d[2]]=d[2].match(/^(ct|adata|salt|iv)$/)?sjcl.codec.base64.toBits(d[4]):unescape
(d[4]):null!=d[5]&&(b[d[2]]="true"===d[5])}return b},g:function(a,b,c){void 0===a&&(a={});if(void 0===
b)return a;for(var d in b)if(b.hasOwnProperty(d)){if(c&&void 0!==a[d]&&a[d]!==b[d])throw new sjcl.exception.invalid
("required parameter overridden");a[d]=b[d]}return a},sa:function(a,b){var c={},d;for(d in a)a.hasOwnProperty(d)&&
amp;a[d]!==b[d]&&(c[d]=a[d]);return c},ra:function(a,
b){var c={},d;for(d=0;d<b.length;d++)void 0!==a[b[d]]&&(c[b[d]]=a[b[d]]);return c}};sjcl.encrypt=sjcl.json.encrypt;sjcl
.decrypt=sjcl.json.decrypt;sjcl.misc.pa={};sjcl.misc.cachedPbkdf2=function(a,b){var c=sjcl.misc.pa,d;b=b||{};d=b.iter||1E3;c=c[a
]=c[a]||{};d=c[d]=c[d]||{firstSalt:b.salt&&b.salt.length?b.salt.slice(0):sjcl.random.randomWords(2,0)};c=void 0===b.salt
?d.firstSalt:b.salt;d[c]=d[c]||sjcl.misc.pbkdf2(a,c,b.iter);return{key:d[c].slice(0),
salt:c.slice(0)}};
"undefined"!==typeof module&&module.exports&&(module.exports=sjcl);"function"===typeof define
&&define([],function(){return sjcl});
local.sjcl = sjcl;
/*
file https://github.com/bitwiseshiftleft/sjcl/blob/1.0.8/core/sha1.js
...
scrypt = function (password, salt, N, r, p, length, Prff) { var SIZE_MAX = Math.pow(2, 32) - 1, self = sjcl.misc.scrypt; N = N || 16384; r = r || 8; p = p || 1; if (r * p >= Math.pow(2, 30)) { throw sjcl.exception.invalid("The parameters r, p must satisfy r * p < 2^30"); } if ((N < 2) || (N & (N - 1) != 0)) { throw sjcl.exception.invalid("The parameter N must be a power of 2."); } if (N > SIZE_MAX / 128 / r) { throw sjcl.exception.invalid("N too big."); } if (r > SIZE_MAX / 128 / p) { throw sjcl.exception.invalid("r too big."); } var blocks = sjcl.misc.pbkdf2(password, salt, 1, p * 128 * r * 8, Prff), len = blocks.length / p; self.reverse(blocks); for (var i = 0; i < p; i++) { var block = blocks.slice(i * len, (i + 1) * len); self.blockcopy(self.ROMix(block, N), 0, blocks, i * len); } self.reverse(blocks); return sjcl.misc.pbkdf2(password, blocks, 1, length, Prff); }
...
if (!opt[3]) {
opt[3] = local.sjcl.codec.base64.fromBits(
local.sjcl.random.randomWords(4, 0)
);
}
// init hash
opt[4] = local.sjcl.codec.base64.fromBits(
local.sjcl.misc.scrypt(
password || "",
local.sjcl.codec.base64.toBits(opt[3]),
Math.pow(2, parseInt(opt[2].slice(0, 1), 16)),
parseInt(opt[2].slice(1, 2), 16),
parseInt(opt[2].slice(3, 4), 16)
)
);
...
function(){var a=this.R.finalize(),a=(new this.W(this.w[1])).update(a).finalize();this.reset();return a}
...
d.length&&(n=l(n,f?d:sjcl.mode.ocb2.pmac(a,d)));return p.concat(k.concat(m,k.clamp(n,e)))},decrypt:function(a,b,c,d,e,f){
if(128!==sjcl.bitArray.bitLength(c))throw new sjcl.exception.invalid("ocb iv must be 128 bits");e=e||64;var g=sjcl.mode
.ocb2.S,h=sjcl.bitArray,k=h.i,l=[0,0,0,0],n=g(a.encrypt(c)),m,p,r=sjcl.bitArray.bitLength(b)-e,q=[];d=d||[];for(c=0;c+4<r/32;
c+=4)m=k(n,a.decrypt(k(n,b.slice(c,c+4)))),l=k(l,m),q=q.concat(m),n=g(n);p=r-32*c;m=a.encrypt(k(n,[0,0,0,p]));m=k(m,h.clamp(b.slice
(c),p).concat([0,
0,0]));l=k(l,m);l=a.encrypt(k(l,k(n,g(n))));d.length&&(l=k(l,f?d:sjcl.mode.ocb2.pmac(a,d)));if(!h.equal(h.clamp(l,e),h.bitSlice
(b,r)))throw new sjcl.exception.corrupt("ocb: tag doesn't match");return q.concat(h.clamp(m,p))},pmac:function(a,
b){var c,d=sjcl.mode.ocb2.S,e=sjcl.bitArray,f=e.i,g=[0,0,0,0],h=a.encrypt([0,0,0,0]),h=f(h,d(d(h)));for(c=0;c+4<b.length;c+=4
)h=d(h),g=f(g,a.encrypt(f(h,b.slice(c,c+4))));c=b.slice(c);128>e.bitLength(c)&&(h=f(h,d(h)),c=e.concat(c,[-2147483648
,0,0,0]));g=f(g,c);
return a.encrypt(f(d(f(h,d(h))),g))},S:function(a){return[a[0]<<1^a[1]>>>31,a[1]<<1^a[2]>>>31,a[2]&
lt;<1^a[3]>>>31,a[3]<<1^135*(a[0]>>>31)]}};
sjcl.mode.gcm={name:"gcm",encrypt:function(a,b,c,d,e){var f=b.slice(0);b=sjcl.bitArray;d=d||[];a=sjcl.mode.gcm.C(!0,a,
f,d,c,e||128);return b.concat(a.data,a.tag)},decrypt:function(a,b,c,d,e){var f=b.slice(0),g=sjcl.bitArray,h=g.bitLength(f);e=e||
128;d=d||[];e<=h?(b=g.bitSlice(f,h-e),f=g.bitSlice(f,0,h-e)):(b=f,f=[]);a=sjcl.mode.gcm.C(!1,a,f,d,c,e);if(!g.equal(a.tag,b))
throw new sjcl.exception.corrupt("gcm: tag doesn't match");return a.data},ka:function(a,b){var c,d,e,f,g,h=sjcl.bitArray
.i;e=[0,0,
0,0];f=b.slice(0);for(c=0;128>c;c++){(d=0!==(a[Math.floor(c/32)]&1<<31-c%32))&&(e=h(e,f));g=0!==(f[3]&1
);for(d=3;0<d;d--)f[d]=f[d]>>>1|(f[d-1]&1)<<31;f[0]>>>=1;g&&(f[0]^=-0x1f000000)}return e},
j:function(a,b,c){var d,e=c.length;b=b.slice(0);for(d=0;d<e;d+=4)b[0]^=0xffffffff&c[d],b[1]^=0xffffffff&c[d+1],b[2]^=
0xffffffff&c[d+2],b[3]^=0xffffffff&c[d+3],b=sjcl.mode.gcm.ka(b,a);return b},C:function(a,b,c,d,e,f){var g,h,k,l,n,m,p,r,
q=sjcl.bitArray;m=c.length;p=q.bitLength(c);r=q.bitLength(d);h=q.bitLength(e);
g=b.encrypt([0,0,0,0]);96===h?(e=e.slice(0),e=q.concat(e,[1])):(e=sjcl.mode.gcm.j(g,[0,0,0,0],e),e=sjcl.mode.gcm.j(g,e,[0,0,Math
.floor(h/0x100000000),h&0xffffffff]));h=sjcl.mode.gcm.j(g,[0,0,0,0],d);n=e.slice(0);d=h.slice(0);a||(d=sjcl.mode.gcm.j(g,h,c
));for(l=0;l<m;l+=4)n[3]++,k=b.encrypt(n),c[l]^=k[0],c[l+1]^=k[1],c[l+2]^=k[2],c[l+3]^=k[3];c=q.clamp(c,p);a&&(d=sjcl
.mode.gcm.j(g,h,c));a=[Math.floor(r/0x100000000),r&0xffffffff,Math.floor(p/0x100000000),p&0xffffffff];d=sjcl.mode.gcm.j(
g,d,a);k=b.encrypt(e);
d[0]^=k[0];d[1]^=k[1];d[2]^=k[2];d[3]^=k[3];return{tag:q.bitSlice(d,0,f),data:c}}};sjcl.misc.hmac=function(a,b){this.W=b=b||sjcl
.hash.sha256;var c=[[],[]],d,e=b.prototype.blockSize/32;this.w=[new b,new b];a.length>e&&(a=b.hash(a));for(d=0;d<e
;d++)c[0][d]=a[d]^909522486,c[1][d]=a[d]^1549556828;this.w[0].update(c[0]);this.w[1].update(c[1]);this.R=new b(this.w[0])};
sjcl.misc.hmac.prototype.encrypt=sjcl.misc.hmac.prototype.mac=function(a){if(this.aa)throw new sjcl.exception.invalid("encrypt
on already updated hmac called!");this.update(a);return this.digest(a)};sjcl.misc
.hmac.prototype.reset=function(){this.R=new this.W(this.w[0]);this.aa=!1};sjcl.misc.hmac.prototype.update=function(a){this.aa=!0
;this.R.update(a)};sjcl.misc.hmac.prototype.digest=function(){var a=this.R.finalize(),a=(new this.W(this.w[1])).update(a).finalize
();this.reset();return a};
sjcl.misc.pbkdf2=function(a,b,c,d,e){c=c||1E4;if(0>d||0>c)throw new sjcl.exception.invalid("invalid params to pbkdf2&
quot;);"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));"string"===typeof b&&(b=sjcl
.codec.utf8String.toBits(b));e=e||sjcl.misc.hmac;a=new e(a);var f,g,h,k,l=[],n=sjcl.bitArray;for(k=1;32*l.length<(d||1);k++){
e=f=a.encrypt(n.concat(b,[k]));for(g=1;g<c;g++)for(f=a.encrypt(f),h=0;h<f.length;h++)e[h]^=f[h];l=l.concat(e)}d&&(
l=n.clamp(l,d));return l};
sjcl.prng=function(a){this.c=[new sjcl.hash.sha256];this.m=[0];this.P=0;this.H={};this.N=0;this.U={};this.Z=this.f=this.o=this.ha
=0;this.b=[0,0,0,0,0,0,0,0];this.h=[0,0,0,0];this.L=void 0;this.M=a;this.D=!1;this.K={progress:{},seeded:{}};this.u=this.ga=0;this
.I=1;this.J=2;this.ca=0x10000;this.T=[0,48,64,96,128,192,0x100,384,512,768,1024];this.da=3E4;this.ba=80};
sjcl.prng.prototype={randomWords:function(a,b){var c=[],d;d=this.isReady(b);var e;if(d===this.u)throw new sjcl.exception.notReady
("generator isn't seeded");if(d&this.J){d=!(d&this.I);e=[];var f=0,g;this.Z=e[0]=(new Date).valueOf()+this
.da;for(g=0;16>g;g++)e.push(0x100000000*Math.random()|0);for(g=0;g<this.c.length&&(e=e.concat(this.c[g].finalize()),
f+=this.m[g],this.m[g]=0,d||!(this.P&1<<g));g++);this.P>=1<<this.c.length&&(this.c.push(new sjcl.hash
.sha256),this.m.push(0));this.f-=f;f>this.o&&(this.o=
f);this.P++;this.b=sjcl.hash.sha256.hash(this.b.concat(e));this.L=new sjcl.cipher.aes(this.b);for(d=0;4>d&&(this.h[d]=
this.h[d]+1|0,!this.h[d]);d++);}for(d=0;d<a;d+=4)0===(d+1)%this.ca&&y(this),e=z(this),c.push(e[0],e[1],e[2],e[3]);y(this
);return c.slice(0,a)},setDefaultParanoia:function(a,b){if(0===a&&"Setting paranoia=0 will ruin your security; use
it only for testing"!==b)throw new sjcl.exception.invalid("Setting paranoia=0 will ruin your security; use it only for
testing");this.M=a},addEntropy:function(a,
b,c){c=c||"user";var d,e,f=(new Date).valueOf(),g=this.H[c],h=this.isReady(),k=0;d=this.U[c];void 0===d&&(d=this
.U[c]=this.ha++);void 0===g&&(g=this.H[c]=0);this.H[c]=(this.H[c]+1)%this.c.length;switch(typeof a){case "number"
;:void 0===b&&(b=1);this.c[g].update([d,this.N++,1,b,f,1,a|0]);break;case "object":c=Object.prototype.toString
.call(a);if("[object Uint32Array]"===c){e=[];for(c=0;c<a.length;c++)e.push(a[c]);a=e}else for("[object Array]&
quot;!==c&&(k=1),c=0;c<a.length&&!k;c++)"number"!==typeof a[c]&&
(k=1);if(!k){if(void 0===b)for(c=b=0;c<a.length;c++)for(e=a[c];0<e;)b++,e=e>>>1;this.c[g].update([d,this.N++,2,b,
f,a.length].concat(a))}break;case "string":void 0===b&&(b=a.length);this.c[g].update([d,this.N++,3,b,f,a.length
]);this.c[g].update(a);break;default:k=1}if(k)throw new sjcl.exception.bug("random: addEntropy only supports number, array
of numbers or string");this.m[g]+=b;this.f+=b;h===this.u&&(this.isReady()!==this.u&&A("seeded",Math
.max(this.o,this.f)),A("progress",this.getProgress()))},
isReady:function(a){a=this.T[void 0!==a?a:this.M];return this.o&&this.o>=a?this.m[0]>this.ba&&(new Date).valueOf
()>this.Z?this.J|this.I:this.I:this.f>=a?this.J|this.u:this.u},getProgress:function(a){a=this.T[a?a:this.M];return this.o&
gt;=a?1:this.f>a?1:this.f/a},startCollectors:function(){if(!this.D){this.a={loadTimeCollector:B(this,this.ma),mouseCollector:
B(this,this.oa),keyboardCollector:B(this,this.la),accelerometerCollector:B(this,this.ea),touchCollector:B(this,this.qa)};if(window
.addEventListener)window.addEventListener("load",
...
function(a){if(this.aa)throw new sjcl.exception.invalid("encrypt on already updated hmac called!");this.update(a);return this.digest (a)}
...
sjcl.hash.sha256.prototype={blockSize:512,reset:function(){this.F=this.Y.slice(0);this.A=[];this.l=0;return this},update:function
(a){"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));var b,c=this.A=sjcl.bitArray.concat(this.A,a);b=this
.l;a=this.l=b+sjcl.bitArray.bitLength(a);if(0x1fffffffffffff<a)throw new sjcl.exception.invalid("Cannot hash more than 2
^53 - 1 bits");if("undefined"!==typeof Uint32Array){var d=new Uint32Array(c),e=0;for(b=512+b-(512+b&0x1ff);b&
lt;=a;b+=512)u(this,d.subarray(16*e,
16*(e+1))),e+=1;c.splice(0,16*e)}else for(b=512+b-(512+b&0x1ff);b<=a;b+=512)u(this,c.splice(0,16));return this},finalize:
function(){var a,b=this.A,c=this.F,b=sjcl.bitArray.concat(b,[sjcl.bitArray.partial(1,1)]);for(a=b.length+2;a&15;a++)b.push(0
);b.push(Math.floor(this.l/0x100000000));for(b.push(this.l|0);b.length;)u(this,b.splice(0,16));this.reset();return c},Y:[],b:[],
O:function(){function a(a){return 0x100000000*(a-Math.floor(a))|0}for(var b=0,c=2,d,e;64>b;c++){e=!0;for(d=2;d*d<=c;d++)if
(0===c%d){e=
!1;break}e&&(8>b&&(this.Y[b]=a(Math.pow(c,.5))),this.b[b]=a(Math.pow(c,1/3)),b++)}}};
function u(a,b){var c,d,e,f=a.F,g=a.b,h=f[0],k=f[1],l=f[2],n=f[3],m=f[4],p=f[5],r=f[6],q=f[7];for(c=0;64>c;c++)16>c?d=b[c]:(
d=b[c+1&15],e=b[c+14&15],d=b[c&15]=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>
;>17^e>>>19^e>>>10^e<<15^e<<13)+b[c&15]+b[c+9&15]|0),d=d+q+(m>>>6^m>>>
;11^m>>>25^m<<26^m<<21^m<<7)+(r^m&(p^r))+g[c],q=r,r=p,p=m,m=n+d|0,n=l,l=k,k=h,h=d+(k&l^n&(
k^l))+(k>>>2^k>>>13^k>>>22^k<<30^k<<19^k<<10)|0;f[0]=f[0]+h|0;f[1]=f[1]+k|0;f[2]=f[
2]+l|0;f[3]=f[3]+n|0;f[4]=f[4]+m|0;f[5]=f[5]+p|0;f[6]=f[6]+r|0;f[7]=
f[7]+q|0}
sjcl.mode.ccm={name:"ccm",G:[],listenProgress:function(a){sjcl.mode.ccm.G.push(a)},unListenProgress:function(a){a=sjcl
.mode.ccm.G.indexOf(a);-1<a&&sjcl.mode.ccm.G.splice(a,1)},fa:function(a){var b=sjcl.mode.ccm.G.slice(),c;for(c=0;c<
;b.length;c+=1)b[c](a)},encrypt:function(a,b,c,d,e){var f,g=b.slice(0),h=sjcl.bitArray,k=h.bitLength(c)/8,l=h.bitLength(g)/8;e=e
||64;d=d||[];if(7>k)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(f=2;4>f&&l&
gt;>>8*f;f++);f<15-k&&(f=15-k);c=h.clamp(c,
8*(15-f));b=sjcl.mode.ccm.V(a,b,c,d,e,f);g=sjcl.mode.ccm.C(a,g,c,b,e,f);return h.concat(g.data,g.tag)},decrypt:function(a,b,c,d,
e){e=e||64;d=d||[];var f=sjcl.bitArray,g=f.bitLength(c)/8,h=f.bitLength(b),k=f.clamp(b,h-e),l=f.bitSlice(b,h-e),h=(h-e)/8;if(7>
;g)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(b=2;4>b&&h>>>8*b;b++);
b<15-g&&(b=15-g);c=f.clamp(c,8*(15-b));k=sjcl.mode.ccm.C(a,k,c,l,e,b);a=sjcl.mode.ccm.V(a,k.data,c,d,e,b);if(!f.equal
(k.tag,a))throw new sjcl.exception.corrupt("ccm: tag doesn't match");
return k.data},na:function(a,b,c,d,e,f){var g=[],h=sjcl.bitArray,k=h.i;d=[h.partial(8,(b.length?64:0)|d-2<<2|f-1)];d=h.concat
(d,c);d[3]|=e;d=a.encrypt(d);if(b.length)for(c=h.bitLength(b)/8,65279>=c?g=[h.partial
(16,c)]:0xffffffff>=c&&(g=h.concat([h.partial(16,65534)],[c])),g=h.concat(g,b),b=0;b<g.length;b+=4)d=a.encrypt(k(d
,g.slice(b,b+4).concat([0,0,0])));return d},V:function(a,b,c,d,e,f){var g=sjcl.bitArray,h=g.i;e/=8;if(e%2||4>e||16<e)throw
new sjcl.exception.invalid("ccm: invalid tag length");
if(0xffffffff<d.length||0xffffffff<b.length)throw new sjcl.exception.bug("ccm: can't deal with 4GiB or more data
");c=sjcl.mode.ccm.na(a,d,c,e,g.bitLength(b)/8,f);for(d=0;d<b.length;d+=4)c=a.encrypt(h(c,b.slice(d,d+4).concat([0,0,0])));
return g.clamp(c,8*e)},C:function(a,b,c,d,e,f){var g,h=sjcl.bitArray;g=h.i;var k=b.length,l=h.bitLength(b),n=k/50,m=n;c=h.concat
([h.partial(8,f-1)],c).concat([0,0,0]).slice(0,4);d=h.bitSlice(g(d,a.encrypt(c)),0,e);if(!k)return{tag:d,data:[]};for(g=0;g<k
;g+=4)g>n&&(sjcl.mode.ccm.fa(g/
k),n+=m),c[3]++,e=a.encrypt(c),b[g]^=e[0],b[g+1]^=e[1],b[g+2]^=e[2],b[g+3]^=e[3];return{tag:d,data:h.clamp(b,l)}}};
sjcl.mode.ocb2={name:"ocb2",encrypt:function(a,b,c,d,e,f){if(128!==sjcl.bitArray.bitLength(c))throw new sjcl.exception
.invalid("ocb iv must be 128 bits");var g,h=sjcl.mode.ocb2.S,k=sjcl.bitArray,l=k.i,n=[0,0,0,0];c=h(a.encrypt(c));var m
,p=[];d=d||[];e=e||64;for(g=0;g+4<b.length;g+=4)m=b.slice(g,g+4),n=l(n,m),p=p.concat(l(c,a.encrypt(l(c,m)))),c=h(c);m=b.slice
(g);b=k.bitLength(m);g=a.encrypt(l(c,[0,0,0,b]));m=k.clamp(l(m.concat([0,0,0]),g),b);n=l(n,l(m.concat([0,0,0]),g));n=a.encrypt(l
(n,l(c,h(c))));
d.length&&(n=l(n,f?d:sjcl.mode.ocb2.pmac(a,d)));return p.concat(k.concat(m,k.clamp(n,e)))},decrypt:function(a,b,c,d,e,f){
if(128!==sjcl.bitArray.bitLength(c))throw new sjcl.exception.invalid("ocb iv must be 128 bits");e=e||64;var g=sjcl.mode
.ocb2.S,h=sjcl.bitArray,k=h.i,l=[0,0,0,0],n=g(a.encrypt(c)),m,p,r=sjcl.bitArray.bitLength(b)-e,q=[];d=d||[];for(c=0;c+4<r/32;
c+=4)m=k(n,a.decrypt(k(n,b.slice(c,c+4)))),l=k(l,m),q=q.concat(m),n=g(n);p=r-32*c;m=a.encrypt(k(n,[0,0,0,p]));m=k(m,h.clamp(b.slice
(c),p).concat([0,
0,0]));l=k(l,m);l=a.encrypt(k(l,k(n,g(n))));d.length&&(l=k(l,f?d:sjcl.mode.ocb2.pmac(a,d)));if(!h.equal(h.clamp(l,e),h.bitSlice
(b,r)))throw new sjcl.exception.corrupt("ocb: tag doesn't match");return q.concat(h.clamp(m,p))},pmac:function(a,
b){var c,d=sjcl.mode.ocb2.S,e=sjcl.bitArray,f=e.i,g=[0,0,0,0],h=a.encrypt([0,0,0,0]),h=f(h,d(d(h)));for(c=0;c+4<b.length;c+=4
)h=d(h),g=f(g,a.encrypt(f(h,b.slice(c,c+4))));c=b.slice(c);128>e.bitLength(c)&&(h=f(h,d(h)),c=e.concat(c,[-2147483648
,0,0,0]));g=f(g,c);
return a.encrypt(f(d(f(h,d(h))),g))},S:function(a){return[a[0]<<1^a[1]>>>31,a[1]<<1^a[2]>>>31,a[2]&
lt;<1^a[3]>>>31,a[3]<<1^135*(a[0]>>>31)]}};
sjcl.mode.gcm={name:"gcm",encrypt:function(a,b,c,d,e){var f=b.slice(0);b=sjcl.bitArray;d=d||[];a=sjcl.mode.gcm.C(!0,a,
f,d,c,e||128);return b.concat(a.data,a.tag)},decrypt:function(a,b,c,d,e){var f=b.slice(0),g=sjcl.bitArray,h=g.bitLength(f);e=e||
128;d=d||[];e<=h?(b=g.bitSlice(f,h-e),f=g.bitSlice(f,0,h-e)):(b=f,f=[]);a=sjcl.mode.gcm.C(!1,a,f,d,c,e);if(!g.equal(a.tag,b))
throw new sjcl.exception.corrupt("gcm: tag doesn't match");return a.data},ka:function(a,b){var c,d,e,f,g,h=sjcl.bitArray
.i;e=[0,0,
...
function(a){if(this.aa)throw new sjcl.exception.invalid("encrypt on already updated hmac called!");this.update(a);return this.digest (a)}
...
*/
var Hmac;
Hmac = local.sjcl.misc.hmac;
return local.sjcl.codec.base64.fromBits(
(new Hmac(
local.sjcl.codec.utf8String.toBits(key),
local.sjcl.hash.sha1
)).mac(local.sjcl.codec.utf8String.toBits(data))
);
};
local.sjclHmacSha256Create = function (key, data) {
/*
* this function will create a base64-encoded sha256 hmac
* from the string key and string data
...
function(){this.R=new this.W(this.w[0]);this.aa=!1}
...
//if it's not valid, use the first character only and reset the reader
if (tt === Tokens.CHAR || tt === Tokens.UNKNOWN) {
if (rule.length > 1) {
tt = Tokens.UNKNOWN_SYM;
} else {
tt = Tokens.CHAR;
rule = first;
reader.reset();
}
}
return this.createToken(tt, rule, startLine, startCol);
},
/**
...
function(a){this.aa=!0;this.R.update(a)}
...
c},$:function(a,b,c,d){var e;e=0;for(void 0===d&&(d=[]);32<=b;b-=32)d.push(c),c=0;if(0===b)return d.concat(a);for(e=0
;e<a.length;e++)d.push(c|a[e]>>>b),c=a[e]<<32-b;e=a.length?a[a.length-1]:0;a=sjcl.bitArray.getPartial(e);d.push
(sjcl.bitArray.partial(b+a&31,32<b+a?c:d.pop(),1));return d},i:function(a,b){return[a[0]^b[0],a[1]^b[1],a[2]^b[2],a[3]^b[
3]]},byteswapM:function(a){var b,c;for(b=0;b<a.length;++b)c=a[b],a[b]=c>>>24|c>>>8&0xff00|(c&0xff00
)<<8|c<<24;return a}};
sjcl.codec.utf8String={fromBits:function(a){var b="",c=sjcl.bitArray.bitLength(a),d,e;for(d=0;d<c/8;d++)0===(d&
3)&&(e=a[d/4]),b+=String.fromCharCode(e>>>8>>>8>>>8),e<<=8;return decodeURIComponent(escape
(b))},toBits:function(a){a=unescape(encodeURIComponent(a));var b=[],c,d=0;for(c=0;c<a.length;c++)d=d<<8|a.charCodeAt(c),
3===(c&3)&&(b.push(d),d=0);c&3&&b.push(sjcl.bitArray.partial(8*(c&3),d));return b}};
sjcl.codec.hex={fromBits:function(a){var b="",c;for(c=0;c<a.length;c++)b+=((a[c]|0)+0xf00000000000).toString(16).substr
(4);return b.substr(0,sjcl.bitArray.bitLength(a)/4)},toBits:function(a){var b,c=[],d;a=a.replace(/\s|0x/g,"");d=a.length;a=a+"00000000";for(b=0;b<a.length;b+=8)c.push(parseInt(a.substr(b,8),16)^0);return sjcl.bitArray.clamp(c,4*d)}};
sjcl.codec.base32={B:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",X:"0123456789ABCDEFGHIJKLMNOPQRSTUV",BITS:32,BASE:5,
REMAINING:27,fromBits:function(a,b,c){var d=sjcl.codec.base32.BASE,e=sjcl.codec.base32.REMAINING,f="",g=0,h=sjcl.codec
.base32.B,k=0,l=sjcl.bitArray.bitLength(a);c&&(h=sjcl.codec.base32.X);for(c=0;f.length*d<l;)f+=h.charAt((k^a[c]>>
;>g)>>>e),g<d?(k=a[c]<<d-g,g+=e,c++):(k<<=d,g-=d);for(;f.length&7&&!b;)f+="=";return
f},toBits:function(a,b){a=a.replace(/\s|=/g,"").toUpperCase();var c=sjcl.codec.base32.BITS,
d=sjcl.codec.base32.BASE,e=sjcl.codec.base32.REMAINING,f=[],g,h=0,k=sjcl.codec.base32.B,l=0,n,m="base32";b&&(k
=sjcl.codec.base32.X,m="base32hex");for(g=0;g<a.length;g++){n=k.indexOf(a.charAt(g));if(0>n){if(!b)try{return sjcl
.codec.base32hex.toBits(a)}catch(p){}throw new sjcl.exception.invalid("this isn't "+m+"!");}h>e?(h-=
e,f.push(l^n>>>h),l=n<<c-h):(h+=d,l^=n<<c-h)}h&56&&f.push(sjcl.bitArray.partial(h&56,l,1));
return f}};
sjcl.codec.base32hex={fromBits:function(a,b){return sjcl.codec.base32.fromBits(a,b,1)},toBits:function(a){return sjcl.codec.base32
.toBits(a,1)}};
sjcl.codec.base64={B:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",fromBits:function(a,b,c){var d
="",e=0,f=sjcl.codec.base64.B,g=0,h=sjcl.bitArray.bitLength(a);c&&(f=f.substr(0,62)+"-_");for(c=0;6*
d.length<h;)d+=f.charAt((g^a[c]>>>e)>>>26),6>e?(g=a[c]<<6-e,e+=26,c++):(g<<=6,e-=6);for(;d.length
&3&&!b;)d+="=";return d},toBits:function(a,b){a=a.replace(/\s|=/g,"");var c=[],d,e=0,f=sjcl.codec.base64.B,g=0,h;b&&(f=f.substr(0,62)+"-_");for(d=0;d<a.length;d++){h=f.indexOf(a.charAt(d));
if(0>h)throw new sjcl.exception.invalid("this isn't base64!");26<e?(e-=26,c.push(g^h>>>e),g=h<&
lt;32-e):(e+=6,g^=h<<32-e)}e&56&&c.push(sjcl.bitArray.partial(e&56,g,1));return c}};sjcl.codec.base64url={
fromBits:function(a){return sjcl.codec.base64.fromBits(a,1,1)},toBits:function(a){return sjcl.codec.base64.toBits(a,1)}};sjcl.hash
.sha256=function(a){this.b[0]||this.O();a?(this.F=a.F.slice(0),this.A=a.A.slice(0),this.l=a.l):this.reset()};sjcl.hash.sha256.hash
=function(a){return(new sjcl.hash.sha256).update(a).finalize()};
sjcl.hash.sha256.prototype={blockSize:512,reset:function(){this.F=this.Y.slice(0);this.A=[];this.l=0;return this},update:function
(a){"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));var b,c=this.A=sjcl.bitArray.concat(this.A,a);b=this
.l;a=this.l=b+sjcl.bitArray.bitLength(a);if(0x1fffffffffffff<a)throw new sjcl.exception.invalid("Cannot hash more than 2
^53 - 1 bits");if("undefined"!==typeof Uint32Array){var d=new Uint32Array(c),e=0;for(b=512+b-(512+b&0x1ff);b&
lt;=a;b+=512)u(this,d.subarray(16*e,
16*(e+1))),e+=1;c.splice(0,16*e)}else for(b=512+b-(512+b&0x1ff);b<=a;b+=512)u(this,c.splice(0,16));return this},finalize:
function(){var a,b=this.A,c=this.F,b=sjcl.bitArray.concat(b,[sjcl.bitArray.partial(1,1)]);for(a=b.length+2;a&15;a++)b.push(0
);b.push(Math.floor(this.l/0x100000000));for(b.push(this.l|0);b.length;)u(this,b.splice(0,16));this.reset();return c},Y:[],b:[],
O:function(){function a(a){return 0x100000000*(a-Math.floor(a))|0}for(var b=0,c=2,d,e;64>b;c++){e=!0;for(d=2;d*d<=c;d++)if
(0===c%d){e=
!1;break}e&&(8>b&&(this.Y[b]=a(Math.pow(c,.5))),this.b[b]=a(Math.pow(c,1/3)),b++)}}};
function u(a,b){var c,d,e,f=a.F,g=a.b,h=f[0],k=f[1],l=f[2],n=f[3],m=f[4],p=f[5],r=f[6],q=f[7];for(c=0;64>c;c++)16>c?d=b[c]:(
d=b[c+1&15],e=b[c+14&15],d=b[c&15]=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>
;>17^e>>>19^e>>>10^e<<15^e<<13)+b[c&15]+b[c+9&15]|0),d=d+q+(m>>>6^m>>>
;11^m>>>25^m<<26^m<<21^m<<7)+(r^m&(p^r))+g[c],q=r,r=p,p=m,m=n+d|0,n=l,l=k,k=h,h=d+(k&l^n&(
k^l))+(k>>>2^k>>>13^k>>>22^k<<30^k<<19^k<<10)|0;f[0]=f[0]+h|0;f[1]=f[1]+k|0;f[2]=f[
2]+l|0;f[3]=f[3]+n|0;f[4]=f[4]+m|0;f[5]=f[5]+p|0;f[6]=f[6]+r|0;f[7]=
f[7]+q|0}
sjcl.mode.ccm={name:"ccm",G:[],listenProgress:function(a){sjcl.mode.ccm.G.push(a)},unListenProgress:function(a){a=sjcl
.mode.ccm.G.indexOf(a);-1<a&&sjcl.mode.ccm.G.splice(a,1)},fa:function(a){var b=sjcl.mode.ccm.G.slice(),c;for(c=0;c<
;b.length;c+=1)b[c](a)},encrypt:function(a,b,c,d,e){var f,g=b.slice(0),h=sjcl.bitArray,k=h.bitLength(c)/8,l=h.bitLength(g)/8;e=e
||64;d=d||[];if(7>k)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(f=2;4>f&&l&
gt;>>8*f;f++);f<15-k&&(f=15-k);c=h.clamp(c,
8*(15-f));b=sjcl.mode.ccm.V(a,b,c,d,e,f);g=sjcl.mode.ccm.C(a,g,c,b,e,f);return h.concat(g.data,g.tag)},decrypt:function(a,b,c,d,
e){e=e||64;d=d||[];var f=sjcl.bitArray,g=f.bitLength(c)/8,h=f.bitLength(b),k=f.clamp(b,h-e),l=f.bitSlice(b,h-e),h=(h-e)/8;if(7>
;g)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(b=2;4>b&&h>>>8*b;b++);
b<15-g&&(b=15-g);c=f.clamp(c,8*(15-b));k=sjcl.mode.ccm.C(a,k,c,l,e,b);a=sjcl.mode.ccm.V(a,k.data,c,d,e,b);if(!f.equal
(k.tag,a))throw new sjcl.exception.corrupt("ccm: tag doesn't match");
...
function(a){this.c=[new sjcl.hash.sha256];this.m=[0];this.P=0;this.H={};this.N=0;this.U={};this.Z=this.f=this.o=this.ha=0;this.b =[0,0,0,0,0,0,0,0];this.h=[0,0,0,0];this.L=void 0;this.M=a;this.D=!1;this.K={progress:{},seeded:{}};this.u=this.ga=0;this.I=1;this .J=2;this.ca=0x10000;this.T=[0,48,64,96,128,192,0x100,384,512,768,1024];this.da=3E4;this.ba=80}
...
(k=1);if(!k){if(void 0===b)for(c=b=0;c<a.length;c++)for(e=a[c];0<e;)b++,e=e>>>1;this.c[g].update([d,this.N++,2,b,
f,a.length].concat(a))}break;case "string":void 0===b&&(b=a.length);this.c[g].update([d,this.N++,3,b,f,a.length
]);this.c[g].update(a);break;default:k=1}if(k)throw new sjcl.exception.bug("random: addEntropy only supports number, array
of numbers or string");this.m[g]+=b;this.f+=b;h===this.u&&(this.isReady()!==this.u&&A("seeded",Math
.max(this.o,this.f)),A("progress",this.getProgress()))},
isReady:function(a){a=this.T[void 0!==a?a:this.M];return this.o&&this.o>=a?this.m[0]>this.ba&&(new Date).valueOf
()>this.Z?this.J|this.I:this.I:this.f>=a?this.J|this.u:this.u},getProgress:function(a){a=this.T[a?a:this.M];return this.o&
gt;=a?1:this.f>a?1:this.f/a},startCollectors:function(){if(!this.D){this.a={loadTimeCollector:B(this,this.ma),mouseCollector:
B(this,this.oa),keyboardCollector:B(this,this.la),accelerometerCollector:B(this,this.ea),touchCollector:B(this,this.qa)};if(window
.addEventListener)window.addEventListener("load",
this.a.loadTimeCollector,!1),window.addEventListener("mousemove",this.a.mouseCollector,!1),window.addEventListener("
;keypress",this.a.keyboardCollector,!1),window.addEventListener("devicemotion",this.a.accelerometerCollector,!1),
window.addEventListener("touchmove",this.a.touchCollector,!1);else if(document.attachEvent)document.attachEvent("
onload",this.a.loadTimeCollector),document.attachEvent("onmousemove",this.a.mouseCollector),document.attachEvent(&
quot;keypress",this.a.keyboardCollector);else throw new sjcl.exception.bug("can't attach event");
this.D=!0}},stopCollectors:function(){this.D&&(window.removeEventListener?(window.removeEventListener("load",this
.a.loadTimeCollector,!1),window.removeEventListener("mousemove",this.a.mouseCollector,!1),window.removeEventListener(&
quot;keypress",this.a.keyboardCollector,!1),window.removeEventListener("devicemotion",this.a.accelerometerCollector
,!1),window.removeEventListener("touchmove",this.a.touchCollector,!1)):document.detachEvent&&(document.detachEvent
("onload",this.a.loadTimeCollector),document.detachEvent("onmousemove",
this.a.mouseCollector),document.detachEvent("keypress",this.a.keyboardCollector)),this.D=!1)},addEventListener:function
(a,b){this.K[a][this.ga++]=b},removeEventListener:function(a,b){var c,d,e=this.K[a],f=[];for(d in e)e.hasOwnProperty(d)&&
;e[d]===b&&f.push(d);for(c=0;c<f.length;c++)d=f[c],delete e[d]},la:function(){C(this,1)},oa:function(a){var b,c;try{b
=a.x||a.clientX||a.offsetX||0,c=a.y||a.clientY||a.offsetY||0}catch(d){c=b=0}0!=b&&0!=c&&this.addEntropy([b,c],2,&
quot;mouse");C(this,0)},qa:function(a){a=
a.touches[0]||a.changedTouches[0];this.addEntropy([a.pageX||a.clientX,a.pageY||a.clientY],1,"touch");C(this,0)},ma:function
(){C(this,2)},ea:function(a){a=a.accelerationIncludingGravity.x||a.accelerationIncludingGravity.y||a.accelerationIncludingGravity
.z;if(window.orientation){var b=window.orientation;"number"===typeof b&&this.addEntropy(b,1,"accelerometer
")}a&&this.addEntropy(a,2,"accelerometer");C(this,0)}};
function A(a,b){var c,d=sjcl.random.K[a],e=[];for(c in d)d.hasOwnProperty(c)&&e.push(d[c]);for(c=0;c<e.length;c++)e[c
](b)}function C(a,b){"undefined"!==typeof window&&window.performance&&"function"===typeof window
.performance.now?a.addEntropy(window.performance.now(),b,"loadtime"):a.addEntropy((new Date).valueOf(),b,"loadtime
")}function y(a){a.b=z(a).concat(z(a));a.L=new sjcl.cipher.aes(a.b)}function z(a){for(var b=0;4>b&&(a.h[b]=a.h[b
]+1|0,!a.h[b]);b++);return a.L.encrypt(a.h)}
function B(a,b){return function(){b.apply(a,arguments)}}sjcl.random=new sjcl.prng(6);
a:try{var D,E,F,G;if(G="undefined"!==typeof module&&module.exports){var H;try{H=require("crypto")}catch
(a){H=null}G=E=H}if(G&&E.randomBytes)D=E.randomBytes(128),D=new Uint32Array((new Uint8Array(D)).buffer),sjcl.random.addEntropy
(D,1024,"crypto['randomBytes']");else if("undefined"!==typeof window&&"undefined"
;!==typeof Uint32Array){F=new Uint32Array(32);if(window.crypto&&window.crypto.getRandomValues)window.crypto.getRandomValues
(F);else if(window.msCrypto&&window.msCrypto.getRandomValues)window.msCrypto.getRandomValues(F);
else break a;sjcl.random.addEntropy(F,1024,"crypto['getRandomValues']")}}catch(a){"undefined"!==typeof
window&&window.console&&(console.log("There was an error collecting entropy from the browser:"),console
.log(a))}
sjcl.json={defaults:{v:1,iter:1E4,ks:128,ts:64,mode:"ccm",adata:"",cipher:"aes"},ja:function(a,b,c
,d){c=c||{};d=d||{};var e=sjcl.json,f=e.g({iv:sjcl.random.randomWords(4,0)},e.defaults),g;e.g(f,c);c=f.adata;"string"===
typeof f.salt&&(f.salt=sjcl.codec.base64.toBits(f.salt));"string"===typeof f.iv&&(f.iv=sjcl.codec.base64
.toBits(f.iv));if(!sjcl.mode[f.mode]||!sjcl.cipher[f.cipher]||"string"===typeof a&&100>=f.iter||64!==f.ts&
;&96!==f.ts&&128!==f.ts||128!==f.ks&&192!==f.ks&&0x100!==f.ks||2>f.iv.length||
4<f.iv.length)throw new sjcl.exception.invalid("json encrypt: invalid parameters");"string"===typeof a?(g
=sjcl.misc.cachedPbkdf2(a,f),a=g.key.slice(0,f.ks/32),f.salt=g.salt):sjcl.ecc&&a instanceof sjcl.ecc.elGamal.publicKey&
;&(g=a.kem(),f.kemtag=g.tag,a=g.key.slice(0,f.ks/32));"string"===typeof b&&(b=sjcl.codec.utf8String.toBits
(b));"string"===typeof c&&(f.adata=c=sjcl.codec.utf8String.toBits(c));g=new sjcl.cipher[f.cipher](a);e.g(d,f);
d.key=a;f.ct="ccm"===f.mode&&sjcl.arrayBuffer&&sjcl.arrayBuffer.ccm&&
b instanceof ArrayBuffer?sjcl.arrayBuffer.ccm.encrypt(g,b,f.iv,c,f.ts):sjcl.mode[f.mode].encrypt(g,b,f.iv,c,f.ts);return f},encrypt
:function(a,b,c,d){var e=sjcl.json,f=e.ja.apply(e,arguments);return e.encode(f)},ia:function(a,b,c,d){c=c||{};d=d||{};var e=sjcl
.json;b=e.g(e.g(e.g({},e.defaults),b),c,!0);var f,g;f=b.adata;"string"===typeof b.salt&&(b.salt=sjcl.codec.base64
.toBits(b.salt));"string"===typeof b.iv&&(b.iv=sjcl.codec.base64.toBits(b.iv));if(!sjcl.mode[b.mode]||!sjcl.cipher
[b.cipher]||"string"===
typeof a&&100>=b.iter||64!==b.ts&&96!==b.ts&&128!==b.ts||128!==b.ks&&192!==b.ks&&0x100
!==b.ks||!b.iv||2>b.iv.length||4<b.iv.length)throw new sjcl.exception.invalid("json decrypt: invalid parameters");&
quot;string"===typeof a?(g=sjcl.misc.cachedPbkdf2(a,b),a=g.key.slice(0,b.ks/32),b.salt=g.salt):sjcl.ecc&&a instanceof
sjcl.ecc.elGamal.secretKey&&(a=a.unkem(sjcl.codec.base64.toBits(b.kemtag)).slice(0,b.ks/32));"string"===typeof
f&&(f=sjcl.codec.utf8String.toBits(f));g=new sjcl.cipher[b.cipher](a);f="ccm"===
b.mode&&sjcl.arrayBuffer&&sjcl.arrayBuffer.ccm&&b.ct instanceof ArrayBuffer?sjcl.arrayBuffer.ccm.decrypt
(g,b.ct,b.iv,b.tag,f,b.ts):sjcl.mode[b.mode].decrypt(g,b.ct,b.iv,f,b.ts);e.g(d,b);d.key=a;return 1===c.raw?f:sjcl.codec.utf8String
.fromBits(f)},decrypt:function(a,b,c,d){var e=sjcl.json;return e.ia(a,e.decode(b),c,d)},encode:function(a){var b,c="{",
d="";for(b in a)if(a.hasOwnProperty(b)){if(!b.match(/^[a-z0-9]+$/i))throw new sjcl.exception.invalid("json encode
: invalid property name");c+=d+'"'+
...
function(a, b, c){c=c||"user";var d,e,f=(new Date).valueOf(),g=this.H[c],h=this.isReady(),k=0;d=this.U[c];void 0===d&&(d=this.U[c]=this.ha++); void 0===g&&(g=this.H[c]=0);this.H[c]=(this.H[c]+1)%this.c.length;switch(typeof a){case "number":void 0===b&&(b=1);this.c[g].update ([d,this.N++,1,b,f,1,a|0]);break;case "object":c=Object.prototype.toString.call(a);if("[object Uint32Array]"===c){e=[];for(c=0;c <a.length;c++)e.push(a[c]);a=e}else for("[object Array]"!==c&&(k=1),c=0;c<a.length&&!k;c++)"number"!==typeof a[c]&& (k=1);if(!k){if(void 0===b)for(c=b=0;c<a.length;c++)for(e=a[c];0<e;)b++,e=e>>>1;this.c[g].update([d,this.N++,2,b,f,a.length].concat (a))}break;case "string":void 0===b&&(b=a.length);this.c[g].update([d,this.N++,3,b,f,a.length]);this.c[g].update(a);break;default :k=1}if(k)throw new sjcl.exception.bug("random: addEntropy only supports number, array of numbers or string");this.m[g]+=b;this. f+=b;h===this.u&&(this.isReady()!==this.u&&A("seeded",Math.max(this.o,this.f)),A("progress",this.getProgress()))}
...
sjcl.prng.prototype={randomWords:function(a,b){var c=[],d;d=this.isReady(b);var e;if(d===this.u)throw new sjcl.exception.notReady
("generator isn't seeded");if(d&this.J){d=!(d&this.I);e=[];var f=0,g;this.Z=e[0]=(new Date).valueOf()+this
.da;for(g=0;16>g;g++)e.push(0x100000000*Math.random()|0);for(g=0;g<this.c.length&&(e=e.concat(this.c[g].finalize()),
f+=this.m[g],this.m[g]=0,d||!(this.P&1<<g));g++);this.P>=1<<this.c.length&&(this.c.push(new sjcl.hash
.sha256),this.m.push(0));this.f-=f;f>this.o&&(this.o=
f);this.P++;this.b=sjcl.hash.sha256.hash(this.b.concat(e));this.L=new sjcl.cipher.aes(this.b);for(d=0;4>d&&(this.h[d]=
this.h[d]+1|0,!this.h[d]);d++);}for(d=0;d<a;d+=4)0===(d+1)%this.ca&&y(this),e=z(this),c.push(e[0],e[1],e[2],e[3]);y(this
);return c.slice(0,a)},setDefaultParanoia:function(a,b){if(0===a&&"Setting paranoia=0 will ruin your security; use
it only for testing"!==b)throw new sjcl.exception.invalid("Setting paranoia=0 will ruin your security; use it only for
testing");this.M=a},addEntropy:function(a,
b,c){c=c||"user";var d,e,f=(new Date).valueOf(),g=this.H[c],h=this.isReady(),k=0;d=this.U[c];void 0===d&&(d=this
.U[c]=this.ha++);void 0===g&&(g=this.H[c]=0);this.H[c]=(this.H[c]+1)%this.c.length;switch(typeof a){case "number"
;:void 0===b&&(b=1);this.c[g].update([d,this.N++,1,b,f,1,a|0]);break;case "object":c=Object.prototype.toString
.call(a);if("[object Uint32Array]"===c){e=[];for(c=0;c<a.length;c++)e.push(a[c]);a=e}else for("[object Array]&
quot;!==c&&(k=1),c=0;c<a.length&&!k;c++)"number"!==typeof a[c]&&
(k=1);if(!k){if(void 0===b)for(c=b=0;c<a.length;c++)for(e=a[c];0<e;)b++,e=e>>>1;this.c[g].update([d,this.N++,2,b,
f,a.length].concat(a))}break;case "string":void 0===b&&(b=a.length);this.c[g].update([d,this.N++,3,b,f,a.length
]);this.c[g].update(a);break;default:k=1}if(k)throw new sjcl.exception.bug("random: addEntropy only supports number, array
of numbers or string");this.m[g]+=b;this.f+=b;h===this.u&&(this.isReady()!==this.u&&A("seeded",Math
.max(this.o,this.f)),A("progress",this.getProgress()))},
isReady:function(a){a=this.T[void 0!==a?a:this.M];return this.o&&this.o>=a?this.m[0]>this.ba&&(new Date).valueOf
()>this.Z?this.J|this.I:this.I:this.f>=a?this.J|this.u:this.u},getProgress:function(a){a=this.T[a?a:this.M];return this.o&
gt;=a?1:this.f>a?1:this.f/a},startCollectors:function(){if(!this.D){this.a={loadTimeCollector:B(this,this.ma),mouseCollector:
B(this,this.oa),keyboardCollector:B(this,this.la),accelerometerCollector:B(this,this.ea),touchCollector:B(this,this.qa)};if(window
.addEventListener)window.addEventListener("load",
this.a.loadTimeCollector,!1),window.addEventListener("mousemove",this.a.mouseCollector,!1),window.addEventListener("
;keypress",this.a.keyboardCollector,!1),window.addEventListener("devicemotion",this.a.accelerometerCollector,!1),
window.addEventListener("touchmove",this.a.touchCollector,!1);else if(document.attachEvent)document.attachEvent("
onload",this.a.loadTimeCollector),document.attachEvent("onmousemove",this.a.mouseCollector),document.attachEvent(&
quot;keypress",this.a.keyboardCollector);else throw new sjcl.exception.bug("can't attach event");
this.D=!0}},stopCollectors:function(){this.D&&(window.removeEventListener?(window.removeEventListener("load",this
.a.loadTimeCollector,!1),window.removeEventListener("mousemove",this.a.mouseCollector,!1),window.removeEventListener(&
quot;keypress",this.a.keyboardCollector,!1),window.removeEventListener("devicemotion",this.a.accelerometerCollector
,!1),window.removeEventListener("touchmove",this.a.touchCollector,!1)):document.detachEvent&&(document.detachEvent
("onload",this.a.loadTimeCollector),document.detachEvent("onmousemove",
this.a.mouseCollector),document.detachEvent("keypress",this.a.keyboardCollector)),this.D=!1)},addEventListener:function
(a,b){this.K[a][this.ga++]=b},removeEventListener:function(a,b){var c,d,e=this.K[a],f=[];for(d in e)e.hasOwnProperty(d)&&
;e[d]===b&&f.push(d);for(c=0;c<f.length;c++)d=f[c],delete e[d]},la:function(){C(this,1)},oa:function(a){var b,c;try{b
=a.x||a.clientX||a.offsetX||0,c=a.y||a.clientY||a.offsetY||0}catch(d){c=b=0}0!=b&&0!=c&&this.addEntropy([b,c],2,"mouse");C(this,0)},qa:function(a){a=
a.touches[0]||a.changedTouches[0];this.addEntropy([a.pageX||a.clientX,a.pageY||a.clientY],1,"touch");C(this,0)},ma:function
(){C(this,2)},ea:function(a){a=a.accelerationIncludingGravity.x||a.accelerationIncludingGravity.y||a.accelerationIncludingGravity
.z;if(window.orientation){var b=window.orientation;"number"===typeof b&&this.addEntropy(b,1,"accelerometer
")}a&&this.addEntropy(a,2,"accelerometer");C(this,0)}};
function A(a,b){var c,d=sjcl.random.K[a],e=[];for(c in d)d.hasOwnProperty(c)&&e.push(d[c]);for(c=0;c<e.length;c++)e[c
](b)}function C(a,b){"undefined"!==typeof window&&window.performance&&"function"===typeof window
.performance.now?a.addEntropy(window.performance.now(),b,"loadtime"):a.addEntropy((new Date).valueOf(),b,"loadtime
")}function y(a){a.b=z(a).concat(z(a));a.L=new sjcl.cipher.aes(a.b)}function z(a){for(var b=0;4>b&&(a.h[b]=a.h[b
]+1|0,!a.h[b]);b++);return a.L.encrypt(a.h)}
function B(a,b){return function(){b.apply(a,arguments)}}sjcl.random=new sjcl.prng(6);
a:try{var D,E,F,G;if(G="undefined"!==typeof module&&module.exports){var H;try{H=require("crypto")}catch
(a){H=null}G=E=H}if(G&&E.randomBytes)D=E.randomBytes(128),D=new Uint32Array((new Uint8Array(D)).buffer),sjcl.random.addEntropy
(D,1024,"crypto['randomBytes']");else if("undefined"!==typeof window&&"undefined"
;!==typeof Uint32Array){F=new Uint32Array(32);if(window.crypto&&window.crypto.getRandomValues)window.crypto.getRandomValues
(F);else if(window.msCrypto&&window.msCrypto.getRandomValues)window.msCrypto.getRandomValues(F);
else break a;sjcl.random.addEntropy(F,1024,"crypto['getRandomValues']")}}catch(a){"undefined"!==typeof
window&&window.console&&(console.log("There was an error collecting entropy from the browser:"),console
.log(a))}
sjcl.json={defaults:{v:1,iter:1E4,ks:128,ts:64,mode:"ccm",adata:"",cipher:"aes"},ja:function(a,b,c
,d){c=c||{};d=d||{};var e=sjcl.json,f=e.g({iv:sjcl.random.randomWords(4,0)},e.defaults),g;e.g(f,c);c=f.adata;"string"===
typeof f.salt&&(f.salt=sjcl.codec.base64.toBits(f.salt));"string"===typeof f.iv&&(f.iv=sjcl.codec.base64
.toBits(f.iv));if(!sjcl.mode[f.mode]||!sjcl.cipher[f.cipher]||"string"===typeof a&&100>=f.iter||64!==f.ts&
;&96!==f.ts&&128!==f.ts||128!==f.ks&&192!==f.ks&&0x100!==f.ks||2>f.iv.length||
4<f.iv.length)throw new sjcl.exception.invalid("json encrypt: invalid parameters");"string"===typeof a?(g
=sjcl.misc.cachedPbkdf2(a,f),a=g.key.slice(0,f.ks/32),f.salt=g.salt):sjcl.ecc&&a instanceof sjcl.ecc.elGamal.publicKey&
;&(g=a.kem(),f.kemtag=g.tag,a=g.key.slice(0,f.ks/32));"string"===typeof b&&(b=sjcl.codec.utf8String.toBits
(b));"string"===typeof c&&(f.adata=c=sjcl.codec.utf8String.toBits(c));g=new sjcl.cipher[f.cipher](a);e.g(d,f);
d.key=a;f.ct="ccm"===f.mode&&sjcl.arrayBuffer&&sjcl.arrayBuffer.ccm&&
...
function(a, b){this.K[a][this.ga++]=b}
...
break;
case "dbImportInput":
if (evt.type !== "change") {
return;
}
ajaxProgressUpdate();
reader = new FileReader();
reader.addEventListener("load", function () {
local.dbImport(reader.result);
ajaxProgressUpdate();
});
reader.readAsText(evt.target.files[0]);
break;
case "dbReset":
ajaxProgressUpdate();
...
function(a){a=a.accelerationIncludingGravity.x||a.accelerationIncludingGravity.y||a.accelerationIncludingGravity.z;if(window.orientation ){var b=window.orientation;"number"===typeof b&&this.addEntropy(b,1,"accelerometer")}a&&this.addEntropy(a,2,"accelerometer");C(this ,0)}
n/a
function(a){a=this.T[a?a:this.M];return this.o>=a?1:this.f>a?1:this.f/a}
...
d[0]^=k[0];d[1]^=k[1];d[2]^=k[2];d[3]^=k[3];return{tag:q.bitSlice(d,0,f),data:c}}};sjcl.misc.hmac=function(a,b){this.W=b=b||sjcl
.hash.sha256;var c=[[],[]],d,e=b.prototype.blockSize/32;this.w=[new b,new b];a.length>e&&(a=b.hash(a));for(d=0;d<e
;d++)c[0][d]=a[d]^909522486,c[1][d]=a[d]^1549556828;this.w[0].update(c[0]);this.w[1].update(c[1]);this.R=new b(this.w[0])};
sjcl.misc.hmac.prototype.encrypt=sjcl.misc.hmac.prototype.mac=function(a){if(this.aa)throw new sjcl.exception.invalid("encrypt
on already updated hmac called!");this.update(a);return this.digest(a)};sjcl.misc.hmac.prototype.reset=function(){this.R=new
this.W(this.w[0]);this.aa=!1};sjcl.misc.hmac.prototype.update=function(a){this.aa=!0;this.R.update(a)};sjcl.misc.hmac.prototype
.digest=function(){var a=this.R.finalize(),a=(new this.W(this.w[1])).update(a).finalize();this.reset();return a};
sjcl.misc.pbkdf2=function(a,b,c,d,e){c=c||1E4;if(0>d||0>c)throw new sjcl.exception.invalid("invalid params to pbkdf2&
quot;);"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));"string"===typeof b&&(b=sjcl
.codec.utf8String.toBits(b));e=e||sjcl.misc.hmac;a=new e(a);var f,g,h,k,l=[],n=sjcl.bitArray;for(k=1;32*l.length<(d||1);k++){
e=f=a.encrypt(n.concat(b,[k]));for(g=1;g<c;g++)for(f=a.encrypt(f),h=0;h<f.length;h++)e[h]^=f[h];l=l.concat(e)}d&&(
l=n.clamp(l,d));return l};
sjcl.prng=function(a){this.c=[new sjcl.hash.sha256];this.m=[0];this.P=0;this.H={};this.N=0;this.U={};this.Z=this.f=this.o=this.ha
=0;this.b=[0,0,0,0,0,0,0,0];this.h=[0,0,0,0];this.L=void 0;this.M=a;this.D=!1;this.K={progress:{},seeded:{}};this.u=this.ga=0;this
.I=1;this.J=2;this.ca=0x10000;this.T=[0,48,64,96,128,192,0x100,384,512,768,1024];this.da=3E4;this.ba=80};
sjcl.prng.prototype={randomWords:function(a,b){var c=[],d;d=this.isReady(b);var e;if(d===this.u)throw new sjcl.exception.notReady
("generator isn't seeded");if(d&this.J){d=!(d&this.I);e=[];var f=0,g;this.Z=e[0]=(new Date).valueOf()+this
.da;for(g=0;16>g;g++)e.push(0x100000000*Math.random()|0);for(g=0;g<this.c.length&&(e=e.concat(this.c[g].finalize()),
f+=this.m[g],this.m[g]=0,d||!(this.P&1<<g));g++);this.P>=1<<this.c.length&&(this.c.push(new sjcl.hash
.sha256),this.m.push(0));this.f-=f;f>this.o&&(this.o=
f);this.P++;this.b=sjcl.hash.sha256.hash(this.b.concat(e));this.L=new sjcl.cipher.aes(this.b);for(d=0;4>d&&(this.h[d]=
this.h[d]+1|0,!this.h[d]);d++);}for(d=0;d<a;d+=4)0===(d+1)%this.ca&&y(this),e=z(this),c.push(e[0],e[1],e[2],e[3]);y(this
);return c.slice(0,a)},setDefaultParanoia:function(a,b){if(0===a&&"Setting paranoia=0 will ruin your security; use
it only for testing"!==b)throw new sjcl.exception.invalid("Setting paranoia=0 will ruin your security; use it only for
testing");this.M=a},addEntropy:function(a,
b,c){c=c||"user";var d,e,f=(new Date).valueOf(),g=this.H[c],h=this.isReady(),k=0;d=this.U[c];void 0===d&&(d=this
.U[c]=this.ha++);void 0===g&&(g=this.H[c]=0);this.H[c]=(this.H[c]+1)%this.c.length;switch(typeof a){case "number"
;:void 0===b&&(b=1);this.c[g].update([d,this.N++,1,b,f,1,a|0]);break;case "object":c=Object.prototype.toString
.call(a);if("[object Uint32Array]"===c){e=[];for(c=0;c<a.length;c++)e.push(a[c]);a=e}else for("[object Array]&
quot;!==c&&(k=1),c=0;c<a.length&&!k;c++)"number"!==typeof a[c]&&
(k=1);if(!k){if(void 0===b)for(c=b=0;c<a.length;c++)for(e=a[c];0<e;)b++,e=e>>>1;this.c[g].update([d,this.N++,2,b,
f,a.length].concat(a))}break;case "string":void 0===b&&(b=a.length);this.c[g].update([d,this.N++,3,b,f,a.length
]);this.c[g].update(a);break;default:k=1}if(k)throw new sjcl.exception.bug("random: addEntropy only supports number, array
of numbers or string");this.m[g]+=b;this.f+=b;h===this.u&&(this.isReady()!==this.u&&A("seeded",Math
.max(this.o,this.f)),A("progress",this.getProgress()))},
isReady:function(a){a=this.T[void 0!==a?a:this.M];return this.o&&this.o>=a?this.m[0]>this.ba&&(new Date).valueOf
()>this.Z?this.J|this.I:this.I:this.f>=a?this.J|this.u:this.u},getProgress:function(a){a=this.T[a?a:this.M];return this.o&
gt;=a?1:this.f>a?1:this.f/a},startCollectors:function(){if(!this.D){this.a={loadTimeCollector:B(this,this.ma),mouseCollector:
B(this,this.oa),keyboardCollector:B(this,this.la),accelerometerCollector:B(this,this.ea),touchCollector:B(this,this.qa)};if(window
.addEventListener)window.addEventListener("load",
this.a.loadTimeCollector,!1),window.addEventListener("mousemove",this.a.mouseCollector,!1),window.addEventListener("
;keypress",this.a.keyboardCollector,!1),window.addEventListener("devicemotion",this.a.accelerometerCollector,!1),
window.addEventListener("touchmove",this.a.touchCollector,!1);else if(document.attachEvent)document.attachEvent("
onload",this.a.loadTimeCollector),document.attachEvent("onmousemove",this.a.mouseCollector),document.attachEvent(&
quot;keypress",this.a.keyboardCollector);else throw new sjcl.exception.bug("can't attach event");
this.D=!0}},stopCollectors:function(){this.D&&(window.removeEventListener?(window.removeEventListener("load",this
.a.loadTimeCollector,!1),window.removeEventListener("mousemove",this.a.mouseCollector,!1),window.removeEventListener(&
quot;keypress",this.a.keyboardCollector,!1),window.removeEventListener("devicemotion",this.a.accelerometerCollector
,!1),window.removeEventListener("touchmove",this.a.touchCollector,!1)):document.detachEvent&&(document.detachEvent
("onload",this.a.loadTimeCollector),document.detachEvent("onmousemove",
this.a.mouseCollector),document.detachEvent("keypress",this.a.keyboardCollector)),this.D=!1)},addEventListener:function
(a,b){this.K[a][this.ga++]=b},removeEventListener:function(a,b){var c,d,e=this.K[a],f=[];for(d in e)e.hasOwnProperty(d)&&
;e[d]===b&&f.push(d);for(c=0;c<f.length;c++)d=f[c],delete e[d]},la:function(){C(this,1)},oa:function(a){var b,c;try{b
=a.x||a.clientX||a.offsetX||0,c=a.y||a.clientY||a.offsetY||0}catch(d){c=b=0}0!=b&&0!=c&&this.addEntropy([b,c],2,&
quot;mouse");C(this,0)},qa:function(a){a=
a.touches[0]||a.changedTouches[0];this.addEntropy([a.pageX||a.clientX,a.pageY||a.clientY],1,"touch");C(this,0)},ma:function
(){C(this,2)},ea:function(a){a=a.accelerationIncludingGravity.x||a.accelerationIncludingGravity.y||a.accelerationIncludingGravity
.z;if(window.orientation){var b=window.orientation;"number"===typeof b&&this.addEntropy(b,1,"accelerometer
")}a&&this.addEntropy(a,2,"accelerometer");C(this,0)}};
function A(a,b){var c,d=sjcl.random.K[a],e=[];for(c in d)d.hasOwnProperty(c)&&e.push(d[c]);for(c=0;c<e.length;c++)e[c
](b)}function C(a,b){"undefined"!==typeof window&&window.performance&&"function"===typeof window
.performance.now?a.addEntropy(window.performance.now(),b,"loadtime"):a.addEntropy((new Date).valueOf(),b,"loadtime
")}function y(a){a.b=z(a).concat(z(a));a.L=new sjcl.cipher.aes(a.b)}function z(a){for(var b=0;4>b&&(a.h[b]=a.h[b
]+1|0,!a.h[b]);b++);return a.L.encrypt(a.h)}
function B(a,b){return function(){b.apply(a,arguments)}}sjcl.random=new sjcl.prng(6);
...
function(a){a=this.T[void 0!==a?a:this.M];return this.o&&this.o>=a?this.m[0]>this.ba&&(new Date).valueOf()>this.Z?this.J|this.I: this.I:this.f>=a?this.J|this.u:this.u}
...
sjcl.mode.gcm={name:"gcm",encrypt:function(a,b,c,d,e){var f=b.slice(0);b=sjcl.bitArray;d=d||[];a=sjcl.mode.gcm.C(!0,a,
f,d,c,e||128);return b.concat(a.data,a.tag)},decrypt:function(a,b,c,d,e){var f=b.slice(0),g=sjcl.bitArray,h=g.bitLength(f);e=e||
128;d=d||[];e<=h?(b=g.bitSlice(f,h-e),f=g.bitSlice(f,0,h-e)):(b=f,f=[]);a=sjcl.mode.gcm.C(!1,a,f,d,c,e);if(!g.equal(a.tag,b))
throw new sjcl.exception.corrupt("gcm: tag doesn't match");return a.data},ka:function(a,b){var c,d,e,f,g,h=sjcl.bitArray
.i;e=[0,0,
0,0];f=b.slice(0);for(c=0;128>c;c++){(d=0!==(a[Math.floor(c/32)]&1<<31-c%32))&&(e=h(e,f));g=0!==(f[3]&1
);for(d=3;0<d;d--)f[d]=f[d]>>>1|(f[d-1]&1)<<31;f[0]>>>=1;g&&(f[0]^=-0x1f000000)}return e},
j:function(a,b,c){var d,e=c.length;b=b.slice(0);for(d=0;d<e;d+=4)b[0]^=0xffffffff&c[d],b[1]^=0xffffffff&c[d+1],b[2]^=
0xffffffff&c[d+2],b[3]^=0xffffffff&c[d+3],b=sjcl.mode.gcm.ka(b,a);return b},C:function(a,b,c,d,e,f){var g,h,k,l,n,m,p,r,
q=sjcl.bitArray;m=c.length;p=q.bitLength(c);r=q.bitLength(d);h=q.bitLength(e);
g=b.encrypt([0,0,0,0]);96===h?(e=e.slice(0),e=q.concat(e,[1])):(e=sjcl.mode.gcm.j(g,[0,0,0,0],e),e=sjcl.mode.gcm.j(g,e,[0,0,Math
.floor(h/0x100000000),h&0xffffffff]));h=sjcl.mode.gcm.j(g,[0,0,0,0],d);n=e.slice(0);d=h.slice(0);a||(d=sjcl.mode.gcm.j(g,h,c
));for(l=0;l<m;l+=4)n[3]++,k=b.encrypt(n),c[l]^=k[0],c[l+1]^=k[1],c[l+2]^=k[2],c[l+3]^=k[3];c=q.clamp(c,p);a&&(d=sjcl
.mode.gcm.j(g,h,c));a=[Math.floor(r/0x100000000),r&0xffffffff,Math.floor(p/0x100000000),p&0xffffffff];d=sjcl.mode.gcm.j(
g,d,a);k=b.encrypt(e);
d[0]^=k[0];d[1]^=k[1];d[2]^=k[2];d[3]^=k[3];return{tag:q.bitSlice(d,0,f),data:c}}};sjcl.misc.hmac=function(a,b){this.W=b=b||sjcl
.hash.sha256;var c=[[],[]],d,e=b.prototype.blockSize/32;this.w=[new b,new b];a.length>e&&(a=b.hash(a));for(d=0;d<e
;d++)c[0][d]=a[d]^909522486,c[1][d]=a[d]^1549556828;this.w[0].update(c[0]);this.w[1].update(c[1]);this.R=new b(this.w[0])};
sjcl.misc.hmac.prototype.encrypt=sjcl.misc.hmac.prototype.mac=function(a){if(this.aa)throw new sjcl.exception.invalid("encrypt
on already updated hmac called!");this.update(a);return this.digest(a)};sjcl.misc.hmac.prototype.reset=function(){this.R=new
this.W(this.w[0]);this.aa=!1};sjcl.misc.hmac.prototype.update=function(a){this.aa=!0;this.R.update(a)};sjcl.misc.hmac.prototype
.digest=function(){var a=this.R.finalize(),a=(new this.W(this.w[1])).update(a).finalize();this.reset();return a};
sjcl.misc.pbkdf2=function(a,b,c,d,e){c=c||1E4;if(0>d||0>c)throw new sjcl.exception.invalid("invalid params to pbkdf2&
quot;);"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));"string"===typeof b&&(b=sjcl
.codec.utf8String.toBits(b));e=e||sjcl.misc.hmac;a=new e(a);var f,g,h,k,l=[],n=sjcl.bitArray;for(k=1;32*l.length<(d||1);k++){
e=f=a.encrypt(n.concat(b,[k]));for(g=1;g<c;g++)for(f=a.encrypt(f),h=0;h<f.length;h++)e[h]^=f[h];l=l.concat(e)}d&&(
l=n.clamp(l,d));return l};
sjcl.prng=function(a){this.c=[new sjcl.hash.sha256];this.m=[0];this.P=0;this.H={};this.N=0;this.U={};this.Z=this.f=this.o=this.ha
=0;this.b=[0,0,0,0,0,0,0,0];this.h=[0,0,0,0];this.L=void 0;this.M=a;this.D=!1;this.K={progress:{},seeded:{}};this.u=this.ga=0;this
.I=1;this.J=2;this.ca=0x10000;this.T=[0,48,64,96,128,192,0x100,384,512,768,1024];this.da=3E4;this.ba=80};
sjcl.prng.prototype={randomWords:function(a,b){var c=[],d;d=this.isReady(b);var e;if(
d===this.u)throw new sjcl.exception.notReady("generator isn't seeded");if(d&this.J){d=!(d&this.I);e=[];var
f=0,g;this.Z=e[0]=(new Date).valueOf()+this.da;for(g=0;16>g;g++)e.push(0x100000000*Math.random()|0);for(g=0;g<this.c.length
&&(e=e.concat(this.c[g].finalize()),f+=this.m[g],this.m[g]=0,d||!(this.P&1<<g));g++);this.P>=1<<this.
c.length&&(this.c.push(new sjcl.hash.sha256),this.m.push(0));this.f-=f;f>this.o&&(this.o=
f);this.P++;this.b=sjcl.hash.sha256.hash(this.b.concat(e));this.L=new sjcl.cipher.aes(this.b);for(d=0;4>d&&(this.h[d]=
this.h[d]+1|0,!this.h[d]);d++);}for(d=0;d<a;d+=4)0===(d+1)%this.ca&&y(this),e=z(this),c.push(e[0],e[1],e[2],e[3]);y(this
);return c.slice(0,a)},setDefaultParanoia:function(a,b){if(0===a&&"Setting paranoia=0 will ruin your security; use
it only for testing"!==b)throw new sjcl.exception.invalid("Setting paranoia=0 will ruin your security; use it only for
testing");this.M=a},addEntropy:function(a,
b,c){c=c||"user";var d,e,f=(new Date).valueOf(),g=this.H[c],h=this.isReady(),k=0;d=this.U[c];void 0===d&&(d=this
.U[c]=this.ha++);void 0===g&&(g=this.H[c]=0);this.H[c]=(this.H[c]+1)%this.c.length;switch(typeof a){case "number"
;:void 0===b&&(b=1);this.c[g].update([d,this.N++,1,b,f,1,a|0]);break;case "object":c=Object.prototype.toString
.call(a);if("[object Uint32Array]"===c){e=[];for(c=0;c<a.length;c++)e.push(a[c]);a=e}else for("[object Array]&
quot;!==c&&(k=1),c=0;c<a.length&&!k;c++)"number"!==typeof a[c]&&
(k=1);if(!k){if(void 0===b)for(c=b=0;c<a.length;c++)for(e=a[c];0<e;)b++,e=e>>>1;this.c[g].update([d,this.N++,2,b,
f,a.length].concat(a))}break;case "string":void 0===b&&(b=a.length);this.c[g].update([d,this.N++,3,b,f,a.length
]);this.c[g].update(a);break;default:k=1}if(k)throw new sjcl.exception.bug("random: addEntropy only supports number, array
of numbers or string");this.m[g]+=b;this.f+=b;h===this.u&&(this.isReady()!==this.u&&A("seeded",Math
.max(this.o,this.f)),A("progress",this.getProgress()))},
isReady:function(a){a=this.T[void 0!==a?a:this.M];return this.o&&this.o>=a?this.m[0]>this.ba&&(new Date).valueOf
()>this.Z?this.J|this.I:this.I:this.f>=a?this.J|this.u:this.u},getProgress:function(a){a=this.T[a?a:this.M];return this.o&
gt;=a?1:this.f>a?1:this.f/a},startCollectors:function(){if(!this.D){this.a={loadTimeCollector:B(this,this.ma),mouseCollector:
B(this,this.oa),keyboardCollector:B(this,this.la),accelerometerCollector:B(this,this.ea),touchCollector:B(this,this.qa)};if(window
.addEventListener)window.addEventListener("load",
this.a.loadTimeCollector,!1),window.addEventListener("mousemove",this.a.mouseCollector,!1),window.addEventListener("
;keypress",this.a.keyboardCollector,!1),window.addEventListener("devicemotion",this.a.accelerometerCollector,!1),
window.addEventListener("touchmove",this.a.touchCollector,!1);else if(document.attachEvent)document.attachEvent("
onload",this.a.loadTimeCollector),document.attachEvent("onmousemove",this.a.mouseCollector),document.attachEvent(&
quot;keypress",this.a.keyboardCollector);else throw new sjcl.exception.bug("can't attach event");
this.D=!0}},stopCollectors:function(){this.D&&(window.removeEventListener?(window.removeEventListener("load",this
.a.loadTimeCollector,!1),window.removeEventListener("mousemove",this.a.mouseCollector,!1),window.removeEventListener(&
quot;keypress",this.a.keyboardCollector,!1),window.removeEventListener("devicemotion",this.a.accelerometerCollector
,!1),window.removeEventListener("touchmove",this.a.touchCollector,!1)):document.detachEvent&&(document.detachEvent
("onload",this.a.loadTimeCollector),document.detachEvent("onmousemove",
this.a.mouseCollector),document.detachEvent("keypress",this.a.keyboardCollector)),this.D=!1)},addEventListener:function
(a,b){this.K[a][this.ga++]=b},removeEventListener:function(a,b){var c,d,e=this.K[a],f=[];for(d in e)e.hasOwnProperty(d)&&
;e[d]===b&&f.push(d);for(c=0;c<f.length;c++)d=f[c],delete e[d]},la:function(){C(this,1)},oa:function(a){var b,c;try{b
=a.x||a.clientX||a.offsetX||0,c=a.y||a.clientY||a.offsetY||0}catch(d){c=b=0}0!=b&&0!=c&&this.addEntropy([b,c],2,&
quot;mouse");C(this,0)},qa:function(a){a=
...
function(){C(this,1)}
n/a
function(){C(this,2)}
n/a
function(a){var b,c;try{b=a.x||a.clientX||a.offsetX||0,c=a.y||a.clientY||a.offsetY||0}catch(d){c=b=0}0!=b&&0!=c&&this.addEntropy ([b,c],2,"mouse");C(this,0)}
n/a
function(a){a= a.touches[0]||a.changedTouches[0];this.addEntropy([a.pageX||a.clientX,a.pageY||a.clientY],1,"touch");C(this,0)}
n/a
function(a, b){var c=[],d;d=this.isReady(b);var e;if(d===this.u)throw new sjcl.exception.notReady("generator isn't seeded");if(d& this.J){d=!(d&this.I);e=[];var f=0,g;this.Z=e[0]=(new Date).valueOf()+this.da;for(g=0;16>g;g++)e.push(0x100000000*Math.random()| 0);for(g=0;g<this.c.length&&(e=e.concat(this.c[g].finalize()),f+=this.m[g],this.m[g]=0,d||!(this.P&1<<g));g++);this.P>=1<<this.c .length&&(this.c.push(new sjcl.hash.sha256),this.m.push(0));this.f-=f;f>this.o&&(this.o= f);this.P++;this.b=sjcl.hash.sha256.hash(this.b.concat(e));this.L=new sjcl.cipher.aes(this.b);for(d=0;4>d&&(this.h[d]=this.h[d]+ 1|0,!this.h[d]);d++);}for(d=0;d<a;d+=4)0===(d+1)%this.ca&&y(this),e=z(this),c.push(e[0],e[1],e[2],e[3]);y(this);return c.slice(0 ,a)}
...
this.D=!0}},stopCollectors:function(){this.D&&(window.removeEventListener?(window.removeEventListener("load",this
.a.loadTimeCollector,!1),window.removeEventListener("mousemove",this.a.mouseCollector,!1),window.removeEventListener(&
quot;keypress",this.a.keyboardCollector,!1),window.removeEventListener("devicemotion",this.a.accelerometerCollector
,!1),window.removeEventListener("touchmove",this.a.touchCollector,!1)):document.detachEvent&&(document.detachEvent
("onload",this.a.loadTimeCollector),document.detachEvent("onmousemove",
this.a.mouseCollector),document.detachEvent("keypress",this.a.keyboardCollector)),this.D=!1)},addEventListener:function
(a,b){this.K[a][this.ga++]=b},removeEventListener:function(a,b){var c,d,e=this.K[a],f=[];for(d in e)e.hasOwnProperty(d)&&
;e[d]===b&&f.push(d);for(c=0;c<f.length;c++)d=f[c],delete e[d]},la:function(){C(this,1)},oa:function(a){var b,c;try{b
=a.x||a.clientX||a.offsetX||0,c=a.y||a.clientY||a.offsetY||0}catch(d){c=b=0}0!=b&&0!=c&&this.addEntropy([b,c],2,&
quot;mouse");C(this,0)},qa:function(a){a=
a.touches[0]||a.changedTouches[0];this.addEntropy([a.pageX||a.clientX,a.pageY||a.clientY],1,"touch");C(this,0)},ma:function
(){C(this,2)},ea:function(a){a=a.accelerationIncludingGravity.x||a.accelerationIncludingGravity.y||a.accelerationIncludingGravity
.z;if(window.orientation){var b=window.orientation;"number"===typeof b&&this.addEntropy(b,1,"accelerometer
")}a&&this.addEntropy(a,2,"accelerometer");C(this,0)}};
function A(a,b){var c,d=sjcl.random.K[a],e=[];for(c in d)d.hasOwnProperty(c)&&e.push(d[c]);for(c=0;c<e.length;c++)e[c
](b)}function C(a,b){"undefined"!==typeof window&&window.performance&&"function"===typeof window
.performance.now?a.addEntropy(window.performance.now(),b,"loadtime"):a.addEntropy((new Date).valueOf(),b,"loadtime
")}function y(a){a.b=z(a).concat(z(a));a.L=new sjcl.cipher.aes(a.b)}function z(a){for(var b=0;4>b&&(a.h[b]=a.h[b
]+1|0,!a.h[b]);b++);return a.L.encrypt(a.h)}
function B(a,b){return function(){b.apply(a,arguments)}}sjcl.random=new sjcl.prng(6);
a:try{var D,E,F,G;if(G="undefined"!==typeof module&&module.exports){var H;try{H=require("crypto")}catch
(a){H=null}G=E=H}if(G&&E.randomBytes)D=E.randomBytes(128),D=new Uint32Array((new Uint8Array(D)).buffer),sjcl.random.addEntropy
(D,1024,"crypto['randomBytes']");else if("undefined"!==typeof window&&"undefined"
;!==typeof Uint32Array){F=new Uint32Array(32);if(window.crypto&&window.crypto.getRandomValues)window.crypto.getRandomValues
(F);else if(window.msCrypto&&window.msCrypto.getRandomValues)window.msCrypto.getRandomValues(F);
else break a;sjcl.random.addEntropy(F,1024,"crypto['getRandomValues']")}}catch(a){"undefined"!==typeof
window&&window.console&&(console.log("There was an error collecting entropy from the browser:"),console
.log(a))}
sjcl.json={defaults:{v:1,iter:1E4,ks:128,ts:64,mode:"ccm",adata:"",cipher:"aes"},ja:function(a,b,c
,d){c=c||{};d=d||{};var e=sjcl.json,f=e.g({iv:sjcl.random.randomWords(4,0)},e.defaults
),g;e.g(f,c);c=f.adata;"string"===typeof f.salt&&(f.salt=sjcl.codec.base64.toBits(f.salt));"string"===
typeof f.iv&&(f.iv=sjcl.codec.base64.toBits(f.iv));if(!sjcl.mode[f.mode]||!sjcl.cipher[f.cipher]||"string"===typeof
a&&100>=f.iter||64!==f.ts&&96!==f.ts&&128!==f.ts||128!==f.ks&&192!==f.ks&&0x100!==f.
ks||2>f.iv.length||
4<f.iv.length)throw new sjcl.exception.invalid("json encrypt: invalid parameters");"string"===typeof a?(g
=sjcl.misc.cachedPbkdf2(a,f),a=g.key.slice(0,f.ks/32),f.salt=g.salt):sjcl.ecc&&a instanceof sjcl.ecc.elGamal.publicKey&
;&(g=a.kem(),f.kemtag=g.tag,a=g.key.slice(0,f.ks/32));"string"===typeof b&&(b=sjcl.codec.utf8String.toBits
(b));"string"===typeof c&&(f.adata=c=sjcl.codec.utf8String.toBits(c));g=new sjcl.cipher[f.cipher](a);e.g(d,f);
d.key=a;f.ct="ccm"===f.mode&&sjcl.arrayBuffer&&sjcl.arrayBuffer.ccm&&
b instanceof ArrayBuffer?sjcl.arrayBuffer.ccm.encrypt(g,b,f.iv,c,f.ts):sjcl.mode[f.mode].encrypt(g,b,f.iv,c,f.ts);return f},encrypt
:function(a,b,c,d){var e=sjcl.json,f=e.ja.apply(e,arguments);return e.encode(f)},ia:function(a,b,c,d){c=c||{};d=d||{};var e=sjcl
.json;b=e.g(e.g(e.g({},e.defaults),b),c,!0);var f,g;f=b.adata;"string"===typeof b.salt&&(b.salt=sjcl.codec.base64
.toBits(b.salt));"string"===typeof b.iv&&(b.iv=sjcl.codec.base64.toBits(b.iv));if(!sjcl.mode[b.mode]||!sjcl.cipher
[b.cipher]||"string"===
typeof a&&100>=b.iter||64!==b.ts&&96!==b.ts&&128!==b.ts||128!==b.ks&&192!==b.ks&&0x100
!==b.ks||!b.iv||2>b.iv.length||4<b.iv.length)throw new sjcl.exception.invalid("json decrypt: invalid parameters");&
quot;string"===typeof a?(g=sjcl.misc.cachedPbkdf2(a,b),a=g.key.slice(0,b.ks/32),b.salt=g.salt):sjcl.ecc&&a instanceof
sjcl.ecc.elGamal.secretKey&&(a=a.unkem(sjcl.codec.base64.toBits(b.kemtag)).slice(0,b.ks/32));"string"===typeof
f&&(f=sjcl.codec.utf8String.toBits(f));g=new sjcl.cipher[b.cipher](a);f="ccm"===
b.mode&&sjcl.arrayBuffer&&sjcl.arrayBuffer.ccm&&b.ct instanceof ArrayBuffer?sjcl.arrayBuffer.ccm.decrypt
(g,b.ct,b.iv,b.tag,f,b.ts):sjcl.mode[b.mode].decrypt(g,b.ct,b.iv,f,b.ts);e.g(d,b);d.key=a;return 1===c.raw?f:sjcl.codec.utf8String
.fromBits(f)},decrypt:function(a,b,c,d){var e=sjcl.json;return e.ia(a,e.decode(b),c,d)},encode:function(a){var b,c="{",
d="";for(b in a)if(a.hasOwnProperty(b)){if(!b.match(/^[a-z0-9]+$/i))throw new sjcl.exception.invalid("json encode
: invalid property name");c+=d+'"'+
b+'":';d=",";switch(typeof a[b]){case "number":case "boolean":c+=a[b];break;case "
;string":c+='"'+escape(a[b])+'"';break;case "object":c+='"'+sjcl.codec
.base64.fromBits(a[b],0)+'"';break;default:throw new sjcl.exception.bug("json encode: unsupported type");}}
return c+"}"},decode:function(a){a=a.replace(/\s/g,"");if(!a.match(/^\{.*\}$/))throw new sjcl.exception.invalid("json decode: this isn't json!");a=a.replace(/^\{|\}$/g,"").split(/,/);var b={},c,d;for(c=0;c<a.length;c++){if(!(d=a[c].match(/^\s*(?:(["']?)([a-z][a-z0-9]*)\1)\s*:\s*(?:(-?\d+)|"([a-z0-9+\/%*_.@=\-]*)"|(true|false))$/i)))throw new sjcl.exception.invalid("json decode: this isn't json!");
null!=d[3]?b[d[2]]=parseInt(d[3],10):null!=d[4]?b[d[2]]=d[2].match(/^(ct|adata|salt|iv)$/)?sjcl.codec.base64.toBits(d[4]):unescape
(d[4]):null!=d[5]&&(b[d[2]]="true"===d[5])}return b},g:function(a,b,c){void 0===a&&(a={});if(void 0===
b)return a;for(var d in b)if(b.hasOwnProperty(d)){if(c&&void 0!==a[d]&&a[d]!==b[d])throw new sjcl.exception.invalid
("required parameter overridden");a[d]=b[d]}return a},sa:function(a,b){var c={},d;for(d in a)a.hasOwnProperty(d)&&
amp;a[d]!==b[d]&&(c[d]=a[d]);return c},ra:function(a,
b){var c={},d;for(d=0;d<b.length;d++)void 0!==a[b[d]]&&(c[b[d]]=a[b[d]]);return c}};sjcl.encrypt=sjcl.json.encrypt;sjcl
.decrypt=sjcl.json.decrypt;sjcl.misc.pa={};sjcl.misc.cachedPbkdf2=function(a,b){var c=sjcl.misc.pa,d;b=b||{};d=b.iter||1E3;c=c[a
]=c[a]||{};d=c[d]=c[d]||{firstSalt:b.salt&&b.salt.length?b.salt.slice(0):sjcl.random.randomWords(2,0)};c=void 0===b.salt
?d.firstSalt:b.salt;d[c]=d[c]||sjcl.misc.pbkdf2(a,c,b.iter);return{key:d[c].slice(0),salt:c.slice(0)}};
...
function(a, b){var c,d,e=this.K[a],f=[];for(d in e)e.hasOwnProperty(d)&&e[d]===b&&f.push(d);for(c=0;c<f.length;c++)d=f[c],delete e[d]}
...
sjcl.prng=function(a){this.c=[new sjcl.hash.sha256];this.m=[0];this.P=0;this.H={};this.N=0;this.U={};this.Z=this.f=this.o=this.ha
=0;this.b=[0,0,0,0,0,0,0,0];this.h=[0,0,0,0];this.L=void 0;this.M=a;this.D=!1;this.K={progress:{},seeded:{}};this.u=this.ga=0;this
.I=1;this.J=2;this.ca=0x10000;this.T=[0,48,64,96,128,192,0x100,384,512,768,1024];this.da=3E4;this.ba=80};
sjcl.prng.prototype={randomWords:function(a,b){var c=[],d;d=this.isReady(b);var e;if(d===this.u)throw new sjcl.exception.notReady
("generator isn't seeded");if(d&this.J){d=!(d&this.I);e=[];var f=0,g;this.Z=e[0]=(new Date).valueOf()+this
.da;for(g=0;16>g;g++)e.push(0x100000000*Math.random()|0);for(g=0;g<this.c.length&&(e=e.concat(this.c[g].finalize()),
f+=this.m[g],this.m[g]=0,d||!(this.P&1<<g));g++);this.P>=1<<this.c.length&&(this.c.push(new sjcl.hash
.sha256),this.m.push(0));this.f-=f;f>this.o&&(this.o=
f);this.P++;this.b=sjcl.hash.sha256.hash(this.b.concat(e));this.L=new sjcl.cipher.aes(this.b);for(d=0;4>d&&(this.h[d]=
this.h[d]+1|0,!this.h[d]);d++);}for(d=0;d<a;d+=4)0===(d+1)%this.ca&&y(this),e=z(this),c.push(e[0],e[1],e[2],e[3]);y(this
);return c.slice(0,a)},setDefaultParanoia:function(a,b){if(0===a&&"Setting paranoia=0 will ruin your security; use
it only for testing"!==b)throw new sjcl.exception.invalid("Setting paranoia=0 will ruin your security; use it only for
testing");this.M=a},addEntropy:function(a,
b,c){c=c||"user";var d,e,f=(new Date).valueOf(),g=this.H[c],h=this.isReady(),k=0;d=this.U[c];void 0===d&&(d=this
.U[c]=this.ha++);void 0===g&&(g=this.H[c]=0);this.H[c]=(this.H[c]+1)%this.c.length;switch(typeof a){case "number"
;:void 0===b&&(b=1);this.c[g].update([d,this.N++,1,b,f,1,a|0]);break;case "object":c=Object.prototype.toString
.call(a);if("[object Uint32Array]"===c){e=[];for(c=0;c<a.length;c++)e.push(a[c]);a=e}else for("[object Array]&
quot;!==c&&(k=1),c=0;c<a.length&&!k;c++)"number"!==typeof a[c]&&
(k=1);if(!k){if(void 0===b)for(c=b=0;c<a.length;c++)for(e=a[c];0<e;)b++,e=e>>>1;this.c[g].update([d,this.N++,2,b,
f,a.length].concat(a))}break;case "string":void 0===b&&(b=a.length);this.c[g].update([d,this.N++,3,b,f,a.length
]);this.c[g].update(a);break;default:k=1}if(k)throw new sjcl.exception.bug("random: addEntropy only supports number, array
of numbers or string");this.m[g]+=b;this.f+=b;h===this.u&&(this.isReady()!==this.u&&A("seeded",Math
.max(this.o,this.f)),A("progress",this.getProgress()))},
isReady:function(a){a=this.T[void 0!==a?a:this.M];return this.o&&this.o>=a?this.m[0]>this.ba&&(new Date).valueOf
()>this.Z?this.J|this.I:this.I:this.f>=a?this.J|this.u:this.u},getProgress:function(a){a=this.T[a?a:this.M];return this.o&
gt;=a?1:this.f>a?1:this.f/a},startCollectors:function(){if(!this.D){this.a={loadTimeCollector:B(this,this.ma),mouseCollector:
B(this,this.oa),keyboardCollector:B(this,this.la),accelerometerCollector:B(this,this.ea),touchCollector:B(this,this.qa)};if(window
.addEventListener)window.addEventListener("load",
this.a.loadTimeCollector,!1),window.addEventListener("mousemove",this.a.mouseCollector,!1),window.addEventListener("
;keypress",this.a.keyboardCollector,!1),window.addEventListener("devicemotion",this.a.accelerometerCollector,!1),
window.addEventListener("touchmove",this.a.touchCollector,!1);else if(document.attachEvent)document.attachEvent("
onload",this.a.loadTimeCollector),document.attachEvent("onmousemove",this.a.mouseCollector),document.attachEvent(&
quot;keypress",this.a.keyboardCollector);else throw new sjcl.exception.bug("can't attach event");
this.D=!0}},stopCollectors:function(){this.D&&(window.removeEventListener?(window.removeEventListener
("load",this.a.loadTimeCollector,!1),window.removeEventListener("mousemove",this.a.mouseCollector,!1),
window.removeEventListener("keypress",this.a.keyboardCollector,!1),window.removeEventListener("devicemotion",
this.a.accelerometerCollector,!1),window.removeEventListener("touchmove",this.a.touchCollector,!1)):document.detachEvent
&&(document.detachEvent("onload",this.a.loadTimeCollector),document.detachEvent("onmousemove",
this.a.mouseCollector),document.detachEvent("keypress",this.a.keyboardCollector)),this.D=!1)},addEventListener:function
(a,b){this.K[a][this.ga++]=b},removeEventListener:function(a,b){var c,d,e=this.K[a],f=[];for(d in e)e.hasOwnProperty(d)&&
;e[d]===b&&f.push(d);for(c=0;c<f.length;c++)d=f[c],delete e[d]},la:function(){C(this,1)},oa:function(a){var b,c;try{b
=a.x||a.clientX||a.offsetX||0,c=a.y||a.clientY||a.offsetY||0}catch(d){c=b=0}0!=b&&0!=c&&this.addEntropy([b,c],2,&
quot;mouse");C(this,0)},qa:function(a){a=
a.touches[0]||a.changedTouches[0];this.addEntropy([a.pageX||a.clientX,a.pageY||a.clientY],1,"touch");C(this,0)},ma:function
(){C(this,2)},ea:function(a){a=a.accelerationIncludingGravity.x||a.accelerationIncludingGravity.y||a.accelerationIncludingGravity
.z;if(window.orientation){var b=window.orientation;"number"===typeof b&&this.addEntropy(b,1,"accelerometer
")}a&&this.addEntropy(a,2,"accelerometer");C(this,0)}};
function A(a,b){var c,d=sjcl.random.K[a],e=[];for(c in d)d.hasOwnProperty(c)&&e.push(d[c]);for(c=0;c<e.length;c++)e[c
](b)}function C(a,b){"undefined"!==typeof window&&window.performance&&"function"===typeof window
.performance.now?a.addEntropy(window.performance.now(),b,"loadtime"):a.addEntropy((new Date).valueOf(),b,"loadtime
")}function y(a){a.b=z(a).concat(z(a));a.L=new sjcl.cipher.aes(a.b)}function z(a){for(var b=0;4>b&&(a.h[b]=a.h[b
]+1|0,!a.h[b]);b++);return a.L.encrypt(a.h)}
function B(a,b){return function(){b.apply(a,arguments)}}sjcl.random=new sjcl.prng(6);
a:try{var D,E,F,G;if(G="undefined"!==typeof module&&module.exports){var H;try{H=require("crypto")}catch
(a){H=null}G=E=H}if(G&&E.randomBytes)D=E.randomBytes(128),D=new Uint32Array((new Uint8Array(D)).buffer),sjcl.random.addEntropy
(D,1024,"crypto['randomBytes']");else if("undefined"!==typeof window&&"undefined"
;!==typeof Uint32Array){F=new Uint32Array(32);if(window.crypto&&window.crypto.getRandomValues)window.crypto.getRandomValues
(F);else if(window.msCrypto&&window.msCrypto.getRandomValues)window.msCrypto.getRandomValues(F);
else break a;sjcl.random.addEntropy(F,1024,"crypto['getRandomValues']")}}catch(a){"undefined"!==typeof
window&&window.console&&(console.log("There was an error collecting entropy from the browser:"),console
.log(a))}
sjcl.json={defaults:{v:1,iter:1E4,ks:128,ts:64,mode:"ccm",adata:"",cipher:"aes"},ja:function(a,b,c
,d){c=c||{};d=d||{};var e=sjcl.json,f=e.g({iv:sjcl.random.randomWords(4,0)},e.defaults),g;e.g(f,c);c=f.adata;"string"===
typeof f.salt&&(f.salt=sjcl.codec.base64.toBits(f.salt));"string"===typeof f.iv&&(f.iv=sjcl.codec.base64
.toBits(f.iv));if(!sjcl.mode[f.mode]||!sjcl.cipher[f.cipher]||"string"===typeof a&&100>=f.iter||64!==f.ts&
;&96!==f.ts&&128!==f.ts||128!==f.ks&&192!==f.ks&&0x100!==f.ks||2>f.iv.length||
...
function(a, b){if(0===a&&"Setting paranoia=0 will ruin your security; use it only for testing"!==b)throw new sjcl.exception.invalid ("Setting paranoia=0 will ruin your security; use it only for testing");this.M=a}
n/a
function(){if(!this.D){this.a={loadTimeCollector:B(this,this.ma),mouseCollector:B(this,this.oa),keyboardCollector:B(this,this.la ),accelerometerCollector:B(this,this.ea),touchCollector:B(this,this.qa)};if(window.addEventListener)window.addEventListener("load ", this.a.loadTimeCollector,!1),window.addEventListener("mousemove",this.a.mouseCollector,!1),window.addEventListener("keypress",this .a.keyboardCollector,!1),window.addEventListener("devicemotion",this.a.accelerometerCollector,!1),window.addEventListener("touchmove ",this.a.touchCollector,!1);else if(document.attachEvent)document.attachEvent("onload",this.a.loadTimeCollector),document.attachEvent ("onmousemove",this.a.mouseCollector),document.attachEvent("keypress",this.a.keyboardCollector);else throw new sjcl.exception.bug ("can't attach event"); this.D=!0}}
n/a
function(){this.D&&(window.removeEventListener?(window.removeEventListener("load",this.a.loadTimeCollector,!1),window.removeEventListener ("mousemove",this.a.mouseCollector,!1),window.removeEventListener("keypress",this.a.keyboardCollector,!1),window.removeEventListener ("devicemotion",this.a.accelerometerCollector,!1),window.removeEventListener("touchmove",this.a.touchCollector,!1)):document.detachEvent &&(document.detachEvent("onload",this.a.loadTimeCollector),document.detachEvent("onmousemove", this.a.mouseCollector),document.detachEvent("keypress",this.a.keyboardCollector)),this.D=!1)}
n/a
Blob = function (array, opt) {
/*
* this function will create a node-compatible Blob instance
* https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob
*/
this.bff = local.bufferConcat(array.map(function (elem) {
return (
// ternary-operator
(
typeof elem === "string"
|| Object.prototype.toString.call(elem)
=== "[object Uint8Array]"
)
? elem
: String(elem)
);
}));
this.type = opt && opt.type;
}
...
var reader;
var tmp;
var utility2;
utility2 = globalThis.utility2 || {};
ajaxProgressUpdate = utility2.ajaxProgressUpdate || local.nop;
switch (evt.target.dataset.oneventDb) {
case "dbExport":
tmp = URL.createObjectURL(new globalThis.Blob([
local.dbExport()
]));
document.querySelector(
"#dbExportA1"
).href = tmp;
document.querySelector(
"#dbExportA1"
...
FormData = function () {
/*
* this function will create a serverLocal-compatible FormData instance
* The FormData(form) constructor must run these steps:
* 1. Let fd be a new FormData object.
* 2. If form is given, set fd's entries to the result
* of constructing the form data set for form. (not implemented)
* 3. Return fd.
* https://xhr.spec.whatwg.org/#dom-formdata
*/
this.entryList = [];
}
...
swaggerJson: local.swaggerJson
})[0];
// init default
local.objectSetDefault(opt, {
inForm: (
// ternary-operator
that._consumes0 === "multipart/form-data"
? new local.FormData()
: ""
),
inHeader: {},
inPath: that._path.replace((
/#.*?$/
), ""),
inQuery: "",
...
function Module(id = '', parent) { this.id = id; this.path = path.dirname(id); this.exports = {}; this.parent = parent; updateChildren(parent, this, false); this.filename = null; this.loaded = false; this.children = []; }
...
// init example.js
tmp = process.cwd() + "/example.js";
// jslint code
local.jslintAndPrint(code, tmp);
// cover code
code = local.istanbulInstrumentInPackage(code, tmp);
// init module.exports
module = new local.Module(tmp);
require.cache[tmp] = module;
// load code into module
module._compile(code, tmp);
// init exports
module.exports.utility2 = local;
module.exports[local.env.npm_package_nameLib] = (
globalThis.utility2_moduleExports
...
_testCase_buildApidoc_default = function (opt, onError) {
/*
* this function will test buildApidoc's default handling-behavior
*/
if (local.isBrowser) {
onError(null, opt);
return;
}
return local.buildApidoc(opt, onError);
}
...
buildTest: local.nop,
testCase_buildReadme_default: local.nop,
testCase_buildLib_default: local.nop,
testCase_buildTest_default: local.nop
}
]
], function (onError) {
local._testCase_buildApidoc_default(null, local.nop);
local._testCase_buildApp_default(null, local.nop);
local._testCase_buildLib_default(null, local.nop);
local._testCase_buildReadme_default(null, local.nop);
local._testCase_buildTest_default(null, local.nop);
local._testCase_webpage_default(null, local.nop);
local.assetsDict["/"] = "<script src=\"assets.test.js\"></script>";
local._testCase_webpage_default(null, local.nop);
...
_testCase_buildApp_default = function (opt, onError) {
/*
* this function will test buildApp's default handling-behavior
*/
if (local.isBrowser) {
onError(null, opt);
return;
}
globalThis.local.testCase_buildReadme_default(opt, local.onErrorThrow);
globalThis.local.testCase_buildLib_default(opt, local.onErrorThrow);
globalThis.local.testCase_buildTest_default(opt, local.onErrorThrow);
local.buildApp(opt, onError);
}
...
testCase_buildReadme_default: local.nop,
testCase_buildLib_default: local.nop,
testCase_buildTest_default: local.nop
}
]
], function (onError) {
local._testCase_buildApidoc_default(null, local.nop);
local._testCase_buildApp_default(null, local.nop);
local._testCase_buildLib_default(null, local.nop);
local._testCase_buildReadme_default(null, local.nop);
local._testCase_buildTest_default(null, local.nop);
local._testCase_webpage_default(null, local.nop);
local.assetsDict["/"] = "<script src=\"assets.test.js\"></script>";
local._testCase_webpage_default(null, local.nop);
onError(null, opt);
...
_testCase_buildLib_default = function (opt, onError) {
/*
* this function will test buildLib's default handling-behavior
*/
if (local.isBrowser) {
onError(null, opt);
return;
}
return local.buildLib({}, onError);
}
...
testCase_buildLib_default: local.nop,
testCase_buildTest_default: local.nop
}
]
], function (onError) {
local._testCase_buildApidoc_default(null, local.nop);
local._testCase_buildApp_default(null, local.nop);
local._testCase_buildLib_default(null, local.nop);
local._testCase_buildReadme_default(null, local.nop);
local._testCase_buildTest_default(null, local.nop);
local._testCase_webpage_default(null, local.nop);
local.assetsDict["/"] = "<script src=\"assets.test.js\"></script>";
local._testCase_webpage_default(null, local.nop);
onError(null, opt);
}, onError);
...
_testCase_buildReadme_default = function (opt, onError) {
/*
* this function will test buildReadme's default handling-behavior
*/
if (local.isBrowser) {
onError(null, opt);
return;
}
return local.buildReadme({}, onError);
}
...
testCase_buildTest_default: local.nop
}
]
], function (onError) {
local._testCase_buildApidoc_default(null, local.nop);
local._testCase_buildApp_default(null, local.nop);
local._testCase_buildLib_default(null, local.nop);
local._testCase_buildReadme_default(null, local.nop);
local._testCase_buildTest_default(null, local.nop);
local._testCase_webpage_default(null, local.nop);
local.assetsDict["/"] = "<script src=\"assets.test.js\"></script>";
local._testCase_webpage_default(null, local.nop);
onError(null, opt);
}, onError);
};
...
_testCase_buildTest_default = function (opt, onError) {
/*
* this function will test buildTest's default handling-behavior
*/
if (local.isBrowser) {
onError(null, opt);
return;
}
return local.buildTest({}, onError);
}
...
}
]
], function (onError) {
local._testCase_buildApidoc_default(null, local.nop);
local._testCase_buildApp_default(null, local.nop);
local._testCase_buildLib_default(null, local.nop);
local._testCase_buildReadme_default(null, local.nop);
local._testCase_buildTest_default(null, local.nop);
local._testCase_webpage_default(null, local.nop);
local.assetsDict["/"] = "<script src=\"assets.test.js\"></script>";
local._testCase_webpage_default(null, local.nop);
onError(null, opt);
}, onError);
};
...
_testCase_webpage_default = function (opt, onError) {
/*
* this function will test webpage's default handling-behavior
*/
local.domStyleValidate();
if (local.isBrowser) {
onError(null, opt);
return;
}
local.browserTest({
fileScreenshot: (
local.env.npm_config_dir_build
+ "/screenshot." + local.env.MODE_BUILD + ".browser.%2F.png"
),
modeCoverageMerge: true,
url: (
local.assetsDict["/"].indexOf(
"<script src=\"assets.test.js\"></script>"
) >= 0
? local.serverLocalHost + "?modeTest=1&timeoutDefault="
+ local.timeoutDefault
: local.serverLocalHost
+ "/assets.utility2.base.html?modeTest=1&timeoutDefault=1"
) + "&modeTestCase=" + local.modeTestCase.replace((
/_?testCase_webpage_default/
), "")
}, onError);
}
...
]
], function (onError) {
local._testCase_buildApidoc_default(null, local.nop);
local._testCase_buildApp_default(null, local.nop);
local._testCase_buildLib_default(null, local.nop);
local._testCase_buildReadme_default(null, local.nop);
local._testCase_buildTest_default(null, local.nop);
local._testCase_webpage_default(null, local.nop);
local.assetsDict["/"] = "<script src=\"assets.test.js\"></script>";
local._testCase_webpage_default(null, local.nop);
onError(null, opt);
}, onError);
};
local.testCase_childProcessSpawnWithTimeout_default = function (
...
ajax = function (opt, onError) {
/*
* this function will send an ajax-req
* with given <opt>.url and callback <onError>
* with err and timeout handling
* example usage:
local.ajax({
data: "hello world",
header: {"x-header-hello": "world"},
method: "POST",
url: "/index.html"
}, function (err, xhr) {
console.log(xhr.statusCode);
console.log(xhr.responseText);
});
*/
var ajaxProgressUpdate;
var bufferValidateAndCoerce;
var isDone;
var local2;
var onEvent;
var streamCleanup;
var timeout;
var tmp;
var xhr;
var xhrInit;
// init local2
local2 = opt.local2 || local.utility2 || {};
// init function
ajaxProgressUpdate = local2.ajaxProgressUpdate || local.nop;
bufferValidateAndCoerce = local2.bufferValidateAndCoerce || function (
bff,
mode
) {
/*
* this function will validate and coerce/convert <bff> -> Buffer
* (or String if <mode> = "string")
*/
// coerce ArrayBuffer -> Buffer
if (Object.prototype.toString.call(bff) === "[object ArrayBuffer]") {
bff = new Uint8Array(bff);
}
// convert Buffer -> utf8
if (mode === "string" && typeof bff !== "string") {
bff = String(bff);
}
return bff;
};
onEvent = function (evt) {
/*
* this function will handle events
*/
if (Object.prototype.toString.call(evt) === "[object Error]") {
xhr.err = xhr.err || evt;
xhr.onEvent({
type: "error"
});
return;
}
// init statusCode
xhr.statusCode = (xhr.statusCode || xhr.status) | 0;
switch (evt.type) {
case "abort":
case "error":
case "load":
if (isDone) {
return;
}
isDone = true;
// decrement ajaxProgressCounter
local2.ajaxProgressCounter = Math.max(
local2.ajaxProgressCounter - 1,
0
);
ajaxProgressUpdate();
// handle abort or err event
switch (!xhr.err && evt.type) {
case "abort":
case "error":
xhr.err = new Error("ajax - event " + evt.type);
break;
case "load":
if (xhr.statusCode >= 400) {
xhr.err = new Error(
"ajax - statusCode " + xhr.statusCode
);
}
break;
}
// debug statusCode / method / url
if (xhr.err) {
xhr.statusCode = xhr.statusCode || 500;
xhr.err.statusCode = xhr.statusCode;
tmp = (
// ternary-operator
(
local.isBrowser
? "browser"
: "node"
)
+ " - " + xhr.statusCode + " " + xhr.method + " " + xhr.url
+ "\n"
);
xhr.err.message = tmp + xhr.err.message;
xhr.err.stack = tmp + xhr.err.stack;
}
// update resHeaders
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/getAllResponseHeaders
if (xhr.getAllResponseHeaders) {
xhr.getAllResponseHeaders().replace((
/(.*?):\u0020*(.*?)\r\n/g
), function (ignore, match1, match2) {
xhr.resHeaders[match1.toLowerCase()] = match2;
});
}
// debug ajaxResponse
xhr.resContentLeng...
...
/* validateLineSortedReset */
local.ajax = function (opt, onError) {
/*
* this function will send an ajax-req
* with given <opt>.url and callback <onError>
* with err and timeout handling
* example usage:
local.ajax({
data: "hello world",
header: {"x-header-hello": "world"},
method: "POST",
url: "/index.html"
}, function (err, xhr) {
console.log(xhr.statusCode);
console.log(xhr.responseText);
...
ajaxProgressUpdate = function () {
/*
* this function will update ajaxProgress
*/
var ajaxProgressDiv1;
// init state
local.ajaxProgressCounter = local.ajaxProgressCounter || 0;
local.ajaxProgressState = local.ajaxProgressState || 0;
ajaxProgressDiv1 = (local.isBrowser && document.querySelector(
"#ajaxProgressDiv1"
)) || {
style: {
width: ""
}
};
// init ajaxProgressDiv1StyleBackground
local.ajaxProgressDiv1StyleBackground = (
local.ajaxProgressDiv1StyleBackground
|| ajaxProgressDiv1.style.background
);
// show ajaxProgress
ajaxProgressDiv1.style.background = local.ajaxProgressDiv1StyleBackground;
// increment ajaxProgress
if (local.ajaxProgressCounter > 0) {
local.timerIntervalAjaxProgressHide = (
local.timerIntervalAjaxProgressHide
|| setInterval(local.ajaxProgressUpdate, 2000)
);
// this algorithm will indefinitely increment ajaxProgressBar
// with successively smaller increments without ever reaching 100%
if ((ajaxProgressDiv1.style.width.slice(0, -1) | 0) > 95) {
ajaxProgressDiv1.style.width = "0%";
local.ajaxProgressState = 0;
}
local.ajaxProgressState += 1;
ajaxProgressDiv1.style.width = Math.max(
100 - 75 * Math.exp(-0.125 * local.ajaxProgressState),
ajaxProgressDiv1.style.width.slice(0, -1) | 0
) + "%";
} else {
// finish ajaxProgress
ajaxProgressDiv1.style.width = "100%";
}
// cleanup timerTimeout
clearTimeout(local.timerTimeoutAjaxProgressHide);
// hide ajaxProgress
local.timerTimeoutAjaxProgressHide = setTimeout(function () {
ajaxProgressDiv1.style.background = "transparent";
local.ajaxProgressCounter = 0;
local.ajaxProgressState = 0;
// reset ajaxProgress
clearInterval(local.timerIntervalAjaxProgressHide);
local.timerIntervalAjaxProgressHide = null;
setTimeout(function () {
if (!local.ajaxProgressState) {
ajaxProgressDiv1.style.width = "0%";
}
}, 500);
}, (
local.ajaxProgressCounter > 0
? local.timeoutDefault
: 1000
));
}
...
) {
return;
}
// test-run
globalThis.utility2_modeTest += 1;
}
// visual notification - testRun
local.ajaxProgressUpdate();
// mock serverLog
local._testRunConsoleError = local._testRunConsoleError || console.error;
console.error = function (arg0) {
/*
* this function will ignore serverLog-messages during test-run
*/
/* istanbul ignore next */
...
apiAjax = function (that, opt, onError) {
/*
* this function will send a swagger-api ajax-req with the operation that
*/
var tmp;
local.objectSetDefault(opt, {
data: "",
operation: that,
paramDict: {},
url: ""
});
if (opt.modeDefault) {
local.normalizeSwaggerParamDict(opt);
}
// try to validate paramDict
opt.err = local.swaggerValidateDataParameters({
// normalize paramDict
data: local.normalizeSwaggerParamDict({
modeNoDefault: opt.modeNoDefault,
operation: that,
paramDict: local.jsonCopy(opt.paramDict)
}).paramDict,
dataReadonlyRemove: opt.paramDict,
prefix: [
"operation", that._methodPath
],
parameters: that.parameters,
swaggerJson: local.swaggerJson
})[0];
// init default
local.objectSetDefault(opt, {
inForm: (
// ternary-operator
that._consumes0 === "multipart/form-data"
? new local.FormData()
: ""
),
inHeader: {},
inPath: that._path.replace((
/#.*?$/
), ""),
inQuery: "",
headers: {},
method: that._method,
responseType: (
// ternary-operator
that._consumes0.indexOf("application/octet-stream") === 0
? "arraybuffer"
: ""
)
});
// init paramDict
that.parameters.forEach(function (schemaP) {
tmp = opt.paramDict[schemaP.name];
if (local.isNullOrUndefined(tmp)) {
return;
}
// serialize array
if (Array.isArray(tmp) && schemaP.in !== "body") {
switch (
schemaP.collectionFormat || schemaP["x-swgg-collectionFormat"]
) {
case "json":
tmp = JSON.stringify(tmp);
break;
case "multi":
tmp.forEach(function (value) {
opt[(
// ternary-operator
schemaP.in === "formData"
? "inForm"
: "inQuery"
)] += (
"&" + encodeURIComponent(schemaP.name) + "="
+ encodeURIComponent(
local.schemaPItemsType(schemaP) === "string"
? value
: JSON.stringify(value)
)
);
});
return;
case "pipes":
tmp = tmp.join("|");
break;
case "ssv":
tmp = tmp.join(" ");
break;
case "tsv":
tmp = tmp.join("\t");
break;
// default to csv
default:
tmp = tmp.join(",");
}
} else if (
typeof tmp !== "string"
&& !(tmp && tmp.constructor === local.Blob)
) {
tmp = JSON.stringify(tmp);
}
switch (schemaP.in) {
case "body":
opt.inBody = tmp;
break;
case "formData":
switch (that._consumes0) {
case "application/xml":
// init xml header
if (!opt.inForm) {
opt.inForm += "<?xml version=\"1.0\"?>";
}
opt.inForm += (
"\n<" + schemaP.name + ">" + "<![CDATA["
+ tmp.replace((
/\]\]>/g
), "]...
...
}
// update apiDict
that = local.jsonCopy(that);
local.apiDict[key.join(".")] = that;
local.apiDict[that._methodPath] = that;
// init ajax
that.ajax = function (swaggerJson, onError) {
return local.apiAjax(that, swaggerJson, onError);
};
that._ajaxToString = (
that.ajax.toString()
.replace("{", (
"{\n"
+ "/*\n"
+ " * this function will run the api-call "
...
apiUpdate = function (swaggerJson) {
/*
* this function will update the swagger-api dict of api-calls
*/
var pathDict;
var tmp;
swaggerJson = swaggerJson || {};
// normalize swaggerJson
swaggerJson = local.normalizeSwaggerJson(swaggerJson, {
objectSetDescription: function (dict) {
if (typeof dict === "object" && dict && !dict.$ref) {
if (Array.isArray(dict["x-swgg-descriptionLineList"])) {
dict.description = (
dict["x-swgg-descriptionLineList"].join("\n")
);
}
if (!(
dict === swaggerJson.externalDocs
|| dict === swaggerJson.info
)) {
dict.description = dict.description || "no description";
}
}
}
});
// init apiDict
local.apiDict = local.apiDict || {};
// init swaggerJson
local.swaggerJson = local.swaggerJson || {
"basePath": "/api/v0",
"definitions": {
"BuiltinFile": {
"properties": {
"_id": {
"readOnly": true,
"type": "string"
},
"_timeCreated": {
"format": "date-time",
"readOnly": true,
"type": "string"
},
"_timeUpdated": {
"format": "date-time",
"readOnly": true,
"type": "string"
},
"fileBlob": {
"format": "byte",
"type": "string"
},
"fileContentType": {
"type": "string"
},
"fileDescription": {
"type": "string"
},
"fileFilename": {
"type": "string"
},
"fileInputName": {
"type": "string"
},
"fileSize": {
"minimum": 0,
"type": "integer"
},
"fileUrl": {
"type": "string"
},
"id": {
"type": "string"
}
}
},
"BuiltinJsonapiResponse": {
"properties": {
"data": {
"items": {
"type": "object"
},
"type": "array"
},
"errors": {
"items": {
"type": "object"
},
"type": "array"
},
"meta": {
"type": "object"
}
}
},
"BuiltinUser": {
"properties": {
"_id": {
"readOnly": true,...
...
* 2. npm install swgg\n\
* $ npm install swgg\n\
* 3. run code below to initialize nodejs swgg-client\n\
* 4. (optional) edit file swagger.json to suit your needs\n\
*/\n\
var swgg;\n\
swgg = require("swgg");\n\
swgg.apiUpdate(require("./swagger.json"));\n\
console.log("printing currently loaded apis ...");\n\
Object.keys(swgg.apiDict).sort().forEach(function (key) {\n\
console.log("swgg.apiDict[" + JSON.stringify(key) + "].ajax");\n\
});\n\
console.log("initialized nodejs swgg-client");\n\
</pre>\n\
<div class="color777 reset">[ <span>base url</span>: {{basePath}} ]</div>\n\
...
apidocCreate = function (opt) {
/*
* this function will create the apidoc from <opt>.dir
*/
var elemCreate;
var module;
var moduleMain;
var readExample;
var tmp;
var toString;
var trimLeft;
elemCreate = function (module, prefix, key) {
/*
* this function will create the apidoc-elem in given <module>
*/
var elem;
if (opt.modeNoApidoc) {
return elem;
}
elem = {};
elem.moduleName = prefix.split(".");
// handle case where module is a function
if (elem.moduleName.slice(-1)[0] === key) {
elem.moduleName.pop();
}
elem.moduleName = elem.moduleName.join(".");
elem.id = encodeURIComponent("apidoc.elem." + prefix + "." + key);
elem.typeof = typeof module[key];
elem.name = (
elem.typeof + " <span class=\"apidocSignatureSpan\">"
+ elem.moduleName + ".</span>" + key
)
// handle case where module is a function
.replace(">.<", "><");
if (elem.typeof !== "function") {
return elem;
}
// init source
elem.source = local.stringHtmlSafe(
trimLeft(toString(module[key])) || "n/a"
).replace((
/\([\S\s]*?\)/
), function (match0) {
// init signature
elem.signature = match0.replace((
/\u0020*?\/\*[\S\s]*?\*\/\u0020*/g
), "")
.replace((
/,/g
), ", ")
.replace((
/\s+/g
), " ");
return elem.signature;
})
.replace((
/(\u0020*?\/\*[\S\s]*?\*\/\n)/
), "<span class=\"apidocCodeCommentSpan\">$1</span>")
.replace((
/^function\u0020\(/
), key + " = function (");
// init example
opt.exampleList.some(function (example) {
example.replace(
new RegExp("((?:\n.*?){8}\\.)(" + key + ")(\\((?:.*?\n){8})"),
function (ignore, match1, match2, match3) {
elem.example = "..." + trimLeft(
local.stringHtmlSafe(match1)
+ "<span class=\"apidocCodeKeywordSpan\">"
+ local.stringHtmlSafe(match2)
+ "</span>"
+ local.stringHtmlSafe(match3)
).trimRight() + "\n...";
}
);
return elem.example;
});
elem.example = elem.example || "n/a";
return elem;
};
readExample = function (file) {
/*
* this function will read the example from given file
*/
var result;
local.tryCatchOnError(function () {
file = local.path.resolve(opt.dir, file);
console.error("apidocCreate - readExample " + file);
result = "";
result = (
"\n\n\n\n\n\n\n\n"
// bug-workaround - truncate example to manageable size
+ local.fs.readFileSync(file, "utf8").slice(0, 262144)
+ "\n\n\n\n\n\n\n\n"
).replace((
/\r\n*/g
), "\n");
}, console.error);
return result;
};
toString = function (value) {
/*
* this function will try to return the string form of the value
*/
var result;
local.tryCatchOnError(function () {
result = "";
result = String(value);
}, console.error);
return result;
};
trimLeft = function (text) {
/*
* this function will...
...
local.cliDict._default = function () {
/*
* <moduleDirectory>
* will create apidoc from <moduleDirectory>
*/
// jslint files
process.stdout.write(local.apidocCreate({
dir: process.argv[2],
modulePathList: module.paths
}));
};
// run the cli
if (module === require.main && !globalThis.utility2_rollup) {
...
function ok(...args) { innerOk(ok, args.length, ...args); }
...
key = '0123456789abcdef0123456789abcdef';
mode = null;
local.cryptoAesXxxCbcRawEncrypt({
data: data,
key: key,
mode: mode
}, function (err, data) {
console.assert(!err, err);
local.cryptoAesXxxCbcRawDecrypt({
data: data,
key: key,
mode: mode
}, console.log);
});
*/
...
assertJsonEqual = function (aa, bb, message) {
/*
* this function will assert jsonStringifyOrdered(<aa>) === JSON.stringify(<bb>)
*/
aa = local.jsonStringifyOrdered(aa);
bb = JSON.stringify(bb);
local.assertThrow(aa === bb, message || [
aa, bb
]);
}
...
}
}
]
], function (onError) {
// update ajax-progress
local.ajaxProgressUpdate();
// validate data
local.assertJsonEqual(local.ajaxProgressCounter, 0);
local.assertJsonEqual(local.ajaxProgressState, 2);
// update ajax-progress
local.ajaxProgressUpdate();
// validate data
local.assertJsonEqual(local.ajaxProgressCounter, 0);
local.assertJsonEqual(local.ajaxProgressState, 1);
// update ajax-progress
...
assertJsonNotEqual = function (aa, bb, message) {
/*
* this function will assert jsonStringifyOrdered(<aa>) !== JSON.stringify(<bb>)
*/
aa = local.jsonStringifyOrdered(aa);
bb = JSON.stringify(bb);
local.assertThrow(aa !== bb, [
aa
], message || aa);
}
...
"", 0, false, null, undefined
].forEach(function (bb, jj) {
if (ii === jj) {
// test assertJsonEqual's handling-behavior
local.assertJsonEqual(aa, bb);
} else {
// test assertJsonNotEqual's handling-behavior
local.assertJsonNotEqual(aa, bb);
}
});
});
onError(null, opt);
};
local.testCase_base64Xxx_default = function (opt, onError) {
...
assertThrow = function (passed, message) {
/*
* this function will throw err.<message> if <passed> is falsy
*/
var err;
if (passed) {
return;
}
err = (
// ternary-operator
(
message
&& typeof message.message === "string"
&& typeof message.stack === "string"
)
// if message is errObj, then leave as is
? message
: new Error(
typeof message === "string"
// if message is a string, then leave as is
? message
// else JSON.stringify message
: JSON.stringify(message, null, 4)
)
);
throw err;
}
...
argList: (commandList[ii][1] || "").trim(),
command: [
key
],
description: commandList[ii][2]
};
} catch (ignore) {
local.assertThrow(null, new Error(
"cliRun - cannot parse comment in COMMAND "
+ key
+ ":\nnew RegExp("
+ JSON.stringify(opt.rgxComment.source)
+ ").exec(" + JSON.stringify(text).replace((
/\\\\/g
), "\u0000").replace((
...
base64FromBuffer = function (bff) {
/*
* this function will convert Uint8Array <bff> to base64
* https://developer.mozilla.org/en-US/Add-ons/Code_snippets/StringView#The_code
*/
var ii;
var mod3;
var text;
var uint24;
var uint6ToB64;
// convert utf8 -> Uint8Array
if (typeof bff === "string") {
bff = new TextEncoder().encode(bff);
}
bff = bff || [];
text = "";
uint24 = 0;
uint6ToB64 = function (uint6) {
return (
uint6 < 26
? uint6 + 65
: uint6 < 52
? uint6 + 71
: uint6 < 62
? uint6 - 4
: uint6 === 62
? 43
: 47
);
};
ii = 0;
while (ii < bff.length) {
mod3 = ii % 3;
uint24 |= bff[ii] << (16 >>> mod3 & 24);
if (mod3 === 2 || bff.length - ii === 1) {
text += String.fromCharCode(
uint6ToB64(uint24 >>> 18 & 63),
uint6ToB64(uint24 >>> 12 & 63),
uint6ToB64(uint24 >>> 6 & 63),
uint6ToB64(uint24 & 63)
);
uint24 = 0;
}
ii += 1;
}
return text.replace((
/A(?=A$|$)/gm
), "=");
}
...
value = (
opt.modeNotRandom
? "abcd1234"
: ((1 + Math.random()) * 0x10000000000000).toString(36).slice(1)
);
switch (schemaP.format) {
case "byte":
value = local.base64FromBuffer(value);
break;
case "date":
case "date-time":
value = new Date().toISOString();
break;
case "email":
value = value + "@example.com";
...
base64ToBuffer = function (b64, mode) {
/*
* this function will convert <b64> to Uint8Array
* https://gist.github.com/wang-bin/7332335
*/
var bff;
var byte;
var chr;
var ii;
var jj;
var map64;
var mod4;
b64 = b64 || "";
bff = new Uint8Array(b64.length); // 3/4
byte = 0;
jj = 0;
map64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
mod4 = 0;
ii = 0;
while (ii < b64.length) {
chr = map64.indexOf(b64[ii]);
if (chr >= 0) {
mod4 %= 4;
if (mod4 === 0) {
byte = chr;
} else {
byte = byte * 64 + chr;
bff[jj] = 255 & (byte >> ((-2 * (mod4 + 1)) & 6));
jj += 1;
}
mod4 += 1;
}
ii += 1;
}
// optimization - create resized-view of bff
bff = bff.subarray(0, jj);
return local.bufferValidateAndCoerce(bff, mode);
}
...
if (!data) {
local.serverRespondDefault(req, res, 404);
return;
}
local.serverRespondHeadSet(req, res, null, {
"Content-Type": data.fileContentType
});
res.end(local.base64ToBuffer(data.fileBlob));
break;
case "userLogout":
opt.onNext();
break;
default:
opt.onNext(null, data, meta);
}
...
base64ToUtf8 = function (b64) {
/*
* this function will convert <b64> -> utf8
*/
return local.base64ToBuffer(b64, "string");
}
...
// validate signature
local.assertThrow(local.sjcl.codec.base64url.fromBits(
new Hmac(local.sjcl.codec.base64url.toBits(
local.jwtAes256KeyInit(key)
)).encrypt(token[0] + "." + token[1])
) === token[2]);
// return decoded data
token = JSON.parse(local.base64ToUtf8(token[1]));
// https://tools.ietf.org/html/rfc7519#section-4.1
// validate jwt-registered-headers
local.assertThrow(!token.exp || token.exp >= timeNow);
local.assertThrow(!token.nbf || token.nbf <= timeNow);
return token;
}, local.nop) || {};
};
...
blobRead = function (blob, onError) {
/*
* this function will read from <blob>
*/
var isDone;
var reader;
if (blob && blob.constructor && blob.constructor === local.FormData) {
blob.read(onError);
return;
}
if (!local.isBrowser) {
onError(null, local.bufferValidateAndCoerce(blob.bff));
return;
}
reader = new FileReader();
reader.onabort = function (evt) {
if (isDone) {
return;
}
isDone = true;
switch (evt.type) {
case "abort":
case "error":
onError(new Error("blobRead - " + evt.type));
break;
case "load":
onError(
null,
Object.prototype.toString.call(reader.result)
=== "[object ArrayBuffer]"
// convert ArrayBuffer -> Uint8Array
? new Uint8Array(reader.result)
: reader.result
);
break;
}
};
reader.onerror = reader.onabort;
reader.onload = reader.onabort;
reader.readAsArrayBuffer(blob);
}
...
switch ((xhr.data && xhr.data.constructor) || true) {
// Blob
// https://developer.mozilla.org/en-US/docs/Web/API/Blob
case local2.Blob:
// FormData
// https://developer.mozilla.org/en-US/docs/Web/API/FormData
case local2.FormData:
local2.blobRead(xhr.data, function (err, data) {
if (err) {
xhr.onEvent(err);
return;
}
// send data
xhr.send(data);
});
...
browserTest = function (opt, onError) {
/*
* this function will spawn an electron process to test <opt>.url
*/
var isDone;
var isDoneHtml;
var onMessage;
var onParallel;
var timerTimeout;
var window;
window = opt.window || globalThis;
// init utility2_testReport
window.utility2_testReport = window.utility2_testReport || {
coverage: window.__coverage__,
testPlatformList: [
{
name: (
local.isBrowser
? (
"browser - "
+ location.pathname + " - " + navigator.userAgent
)
: "node - " + process.platform + " " + process.version
) + " - " + new Date().toISOString(),
screenshot: local.env && local.env.MODE_BUILD_SCREENSHOT_IMG,
testCaseList: []
}
]
};
window.utility2_testReportSave = (
window.utility2_testReportSave
|| local.nop
);
if (opt.modeTestReportCreate) {
return;
}
onMessage = function (evt, type, data) {
switch (evt && type) {
case "html":
if (isDoneHtml) {
return;
}
isDoneHtml = true;
opt.fs.writeFile(opt.fileScreenshot.replace((
/\.\w+$/
), ".html"), data, onParallel);
return;
case "testReport":
if (opt.isDoneTestReport || opt.modeBrowserTest !== "test") {
return;
}
opt.isDoneTestReport = true;
// save browser-coverage
if (data.coverage) {
onParallel.counter += 1;
opt.fs.writeFile(
opt.fileCoverage,
JSON.stringify(data.coverage),
onParallel
);
data.coverage = null;
}
// save browser-screenshot
data.testPlatformList[0].screenshot = (
opt.fileScreenshot.replace((
/.*\//
), "")
);
// save browser-test-report
onParallel.counter += 1;
opt.fs.writeFile(
opt.fileTestReport,
JSON.stringify(data, null, 4),
onParallel
);
onParallel();
return;
}
};
local.onNext(opt, function (err, data) {
switch (opt.modeNext) {
// node - init
case 1:
// init fileElectronHtml
opt.fileElectronHtml = (
opt.npm_config_dir_tmp
+ "/electron."
+ Date.now().toString(16)
+ Math.random().toString(16)
+ ".html"
);
// init url
if (!(
/^\w+:\/\//
).test(opt.url)) {
opt.url = local.path.resolve(process.cwd(), opt.url);
}
opt.urlParsed = local.urlParse(opt.url);
// init testName
opt.testName = opt.urlParsed.pathname;
if (opt.testName.indexOf(process.cwd()) === 0) {
opt.testName = opt.testName.replace(process.cwd(), "");
}
opt.testName = (
opt.MODE_BUILD + ".browser."
+ encodeURIComponent(opt.testName.replace(
"/build.."
+ opt.CI_BRANCH
+ ".." + opt.CI_HOST,
"/build"
))
);
local.objectSetDefault(opt, {
fileCoverage: (
opt.npm_config_dir_tmp + "/coverage."
+ opt.testName + ".json"
),
fileScreenshot: (...
...
? (
/\s/g
)
: (
/[,\s]/g
)
).filter(local.identity).forEach(function (url) {
local.browserTest({
url
}, local.onErrorDefault);
});
};
local.cliDict["utility2.githubCrudContentDelete"] = function () {
/*
...
bufferConcat = function (bffList) {
/*
* this function will emulate node's Buffer.concat for Uint8Array in browser
*/
var byteLength;
var ii;
var isString;
var jj;
var result;
isString = true;
result = [
""
];
byteLength = 0;
bffList.forEach(function (bff) {
if (bff !== 0 && !(bff && bff.length)) {
return;
}
// optimization - concat string
if (isString && typeof bff === "string") {
result[0] += bff;
return;
}
isString = null;
bff = local.bufferValidateAndCoerce(bff);
byteLength += bff.byteLength;
result.push(bff);
});
// optimization - return string
if (isString) {
return result[0];
}
result[0] = local.bufferValidateAndCoerce(result[0]);
byteLength += result[0].byteLength;
bffList = result;
result = local.bufferValidateAndCoerce(new Uint8Array(byteLength));
ii = 0;
bffList.forEach(function (bff) {
jj = 0;
while (jj < bff.byteLength) {
result[ii] = bff[jj];
ii += 1;
jj += 1;
}
});
return result;
}
...
]);
// init boundary
ii = 0;
jj = local.bufferIndexOfSubBuffer(req.bodyRaw, crlf, ii);
if (jj <= 0) {
break;
}
boundary = local.bufferConcat([
crlf, req.bodyRaw.slice(ii, jj)
]);
ii = jj + 2;
while (true) {
jj = local.bufferIndexOfSubBuffer(
req.bodyRaw,
boundary,
...
bufferIndexOfSubBuffer = function (bff, subBff, fromIndex) {
/*
* this function will search <bff> for <fromIndex> position of <subBff>
*/
var ii;
var jj;
var kk;
if (!subBff.length) {
return 0;
}
ii = fromIndex || 0;
while (ii < bff.length) {
kk = ii;
jj = 0;
while (jj < subBff.length) {
if (subBff[jj] !== bff[kk]) {
break;
}
kk += 1;
jj += 1;
}
if (jj === subBff.length) {
return kk - jj;
}
ii += 1;
}
return -1;
}
...
req.swgg.bodyParsed = {};
req.swgg.bodyMeta = {};
crlf = new Uint8Array([
0x0d, 0x0a
]);
// init boundary
ii = 0;
jj = local.bufferIndexOfSubBuffer(req.bodyRaw, crlf, ii);
if (jj <= 0) {
break;
}
boundary = local.bufferConcat([
crlf, req.bodyRaw.slice(ii, jj)
]);
ii = jj + 2;
...
bufferRandomBytes = function (length) {
/*
* this function will return a Buffer with given <length>,
* filled with cryptographically-strong random-values
*/
return (
// ternary-operator
(
typeof window === "object"
&& window.crypto
&& typeof window.crypto.getRandomValues === "function"
)
? window.crypto.getRandomValues(new Uint8Array(length))
: require("crypto").randomBytes(length)
);
}
...
};
local.jwtAes256KeyCreate = function () {
/*
* this function will create a random, aes-256-base64url-jwt-key
*/
return local.normalizeJwtBase64Url(
local.base64FromBuffer(local.bufferRandomBytes(32))
);
};
local.jwtAes256KeyInit = function (key) {
/*
* this function will init aes-256-base64url-jwt-<key>
* https://jwt.io/
...
bufferToUtf8 = function (bff) {
/*
* this function will convert Uint8Array <bff> -> utf8
*/
return local.bufferValidateAndCoerce(bff, "string");
}
...
var name;
// if req is already parsed, then goto next
if (!req.swgg.operation || !local.isNullOrUndefined(req.swgg.bodyParsed)) {
next();
return;
}
headerParse = function () {
local.bufferToUtf8(req.bodyRaw.slice(ii, ii + 1024)).replace((
/^content-disposition:\u0020?form-data;(.+?)\r\n(?:content-type:\u0020?(.*?)$)?/im
), function (ignore, match1, match2) {
data = {
contentType: match2,
name: ""
};
match1.replace((
...
bufferValidateAndCoerce = function (bff, mode) {
/*
* this function will validate and coerce/convert <bff> -> Buffer
* (or String if <mode> = "string")
*/
// validate not 0
if (bff !== 0) {
bff = bff || "";
}
if (typeof bff === "string" && mode === "string") {
return bff;
}
// convert utf8 -> Uint8Array
if (typeof bff === "string") {
bff = (
local.isBrowser
? new TextEncoder().encode(bff)
: Buffer.from(bff)
);
// validate instanceof Uint8Array
} else if (Object.prototype.toString.call(bff) !== "[object Uint8Array]") {
throw new Error(
"bufferValidateAndCoerce - value is not instanceof "
+ "ArrayBuffer, String, or Uint8Array"
);
}
// convert Uint8Array -> utf8
if (mode === "string") {
return new TextDecoder().decode(bff);
}
// coerce Uint8Array -> Buffer
if (!local.isBrowser && !Buffer.isBuffer(bff)) {
Object.setPrototypeOf(bff, Buffer.prototype);
}
return bff;
}
...
}
mod4 += 1;
}
ii += 1;
}
// optimization - create resized-view of bff
bff = bff.subarray(0, jj);
return local.bufferValidateAndCoerce(bff, mode);
};
local.base64ToUtf8 = function (b64) {
/*
* this function will convert <b64> -> utf8
*/
return local.base64ToBuffer(b64, "string");
...
buildApidoc = function (opt, onError) {
/*
* this function will build apidoc with given <opt>
*/
var result;
// optimization - do not run if $npm_config_mode_coverage = all
if (local.env.npm_config_mode_coverage === "all") {
onError();
return;
}
opt = local.objectSetDefault(opt, {
blacklistDict: local,
require: local.requireInSandbox
});
// save apidoc.html
result = (
local.fsReadFileOrEmptyStringSync("apidoc.html", "utf8")
|| local.apidocCreate(opt)
);
local.fsWriteFileWithMkdirpSync("tmp/build/apidoc.html", result);
console.error(
"created apidoc file " + process.cwd() + "/apidoc.html\n"
);
onError();
}
...
/*
* this function will test buildApidoc's default handling-behavior
*/
if (local.isBrowser) {
onError(null, opt);
return;
}
return local.buildApidoc(opt, onError);
};
local._testCase_buildApp_default = function (opt, onError) {
/*
* this function will test buildApp's default handling-behavior
*/
if (local.isBrowser) {
...
buildApp = function (opt, onError) {
/*
* this function will build app with given <opt>
*/
opt = local.objectSetDefault(opt, {
assetsList: []
});
// build assets
local.fsRmrSync("tmp/build/app");
local.onParallelList({
list: [
{
file: "/LICENSE",
url: "/LICENSE"
}, {
file: "/assets." + local.env.npm_package_nameLib + ".html",
url: "/index.html"
}, {
file: "/assets." + local.env.npm_package_nameLib + ".js",
url: "/assets." + local.env.npm_package_nameLib + ".js"
}, {
file: "/assets.app.js",
url: "/assets.app.js"
}, {
file: "/assets.example.html",
url: "/assets.example.html"
}, {
file: "/assets.example.js",
url: "/assets.example.js"
}, {
file: "/assets.swgg.html",
url: "/assets.swgg.html"
}, {
file: "/assets.swgg.swagger.json",
url: "/assets.swgg.swagger.json"
}, {
file: "/assets.swgg.swagger.petstore.json",
url: "/assets.swgg.swagger.petstore.json"
}, {
file: "/assets.swgg.swagger.server.json",
url: "/assets.swgg.swagger.server.json"
}, {
file: "/assets.test.js",
url: "/assets.test.js"
}, {
file: "/assets.utility2.html",
url: "/assets.utility2.html"
}, {
file: "/assets.utility2.base.html",
url: "/assets.utility2.base.html"
}, {
file: "/assets.utility2.rollup.js",
url: "/assets.utility2.rollup.js"
}, {
file: "/index.html",
url: "/index.html"
}, {
file: "/index.rollup.html",
url: "/index.rollup.html"
}, {
file: "/jsonp.utility2.stateInit",
url: (
"/jsonp.utility2.stateInit"
+ "?callback=window.utility2.stateInit"
)
}
].concat(opt.assetsList)
}, function (option2, onParallel) {
option2 = option2.elem;
onParallel.counter += 1;
local.ajax(option2, function (err, xhr) {
// validate no err occurred
local.assertThrow(!err, err);
// jslint file
local.jslintAndPrint(xhr.responseText, option2.file, {
conditional: true,
coverage: local.env.npm_config_mode_coverage
});
// validate no err occurred
local.assertThrow(
!local.jslint.jslintResult.errText,
local.jslint.jslintResult.errText
);
local.fsWriteFileWithMkdirpSync(
"tmp/build/app" + option2.file,
xhr.response
);
onParallel();
});
}, function (err) {
// validate no err occurred
local.assertThrow(!err, err);
// test standalone assets.app.js
local.fsWriteFileWithMkdirpSync(
"tmp/buildApp/assets.app.js",
local.assetsDict["/assets.app.js"]
);
local.childProcessSpawnWithTimeout("node", [
"assets.app.js"
], {
cwd: "tmp/buildApp",
env: {
PATH: local.env.PATH,...
...
if (local.isBrowser) {
onError(null, opt);
return;
}
globalThis.local.testCase_buildReadme_default(opt, local.onErrorThrow);
globalThis.local.testCase_buildLib_default(opt, local.onErrorThrow);
globalThis.local.testCase_buildTest_default(opt, local.onErrorThrow);
local.buildApp(opt, onError);
};
local._testCase_buildLib_default = function (opt, onError) {
/*
* this function will test buildLib's default handling-behavior
*/
if (local.isBrowser) {
...
buildLib = function (opt, onError) {
/*
* this function will build lib with given <opt>
*/
var result;
local.objectSetDefault(opt, {
customize: local.nop,
dataFrom: local.fsReadFileOrEmptyStringSync(
"lib." + local.env.npm_package_nameLib + ".js",
"utf8"
),
dataTo: local.templateRenderMyApp(
local.assetsDict["/assets.my_app.template.js"],
opt
)
});
// search-and-replace - customize dataTo
[
// customize top-level comment-description
(
/\n\u0020\*\n(?:[\S\s]*?\n)?\u0020\*\/\n/
),
// customize body after /* validateLineSortedReset */
(
/\n\/\*\u0020validateLineSortedReset\u0020\*\/\n[\S\s]*?$/
)
].forEach(function (rgx) {
opt.dataTo = local.stringMerge(opt.dataTo, opt.dataFrom, rgx);
});
// customize local for assets.utility2.rollup.js
if (
local.fs.existsSync("./assets.utility2.rollup.js")
&& local.env.npm_package_nameLib !== "swgg"
) {
opt.dataTo = opt.dataTo.replace(
" // || globalThis.utility2_rollup_old",
" || globalThis.utility2_rollup_old"
).replace(
" // || require(\"./assets.utility2.rollup.js\")",
" || require(\"./assets.utility2.rollup.js\")"
);
}
// save lib
result = opt.dataTo;
local.fsWriteFileWithMkdirpSync(
"lib." + local.env.npm_package_nameLib + ".js",
result,
local.env.npm_config_mode_coverage && local.identity("noWrite")
);
opt.customize(opt);
onError();
return result;
}
...
/*
* this function will test buildLib's default handling-behavior
*/
if (local.isBrowser) {
onError(null, opt);
return;
}
return local.buildLib({}, onError);
};
local._testCase_buildReadme_default = function (opt, onError) {
/*
* this function will test buildReadme's default handling-behavior
*/
if (local.isBrowser) {
...
buildReadme = function (opt, onError) {
/*
* this function will build readme with given <opt> my-app-lite template
*/
var result;
local.objectSetDefault(opt, {
customize: local.nop,
// reset toc
dataFrom: local.fsReadFileOrEmptyStringSync(
"README.md",
"utf8"
).replace((
/\n#\u0020table\u0020of\u0020contents$[\S\s]*?\n\n\n\n/m
), "\n# table of contents\n\n\n\n"),
packageJsonRgx: (
/\n#\u0020package.json\n```json\n([\S\s]*?)\n```\n/
)
});
// render dataTo
opt.dataTo = local.templateRenderMyApp(
local.assetsDict["/assets.readme.template.md"],
opt
);
// init package.json
opt.dataFrom.replace(opt.packageJsonRgx, function (match0, match1) {
// remove null-items from package.json
opt.packageJson = JSON.parse(match1.replace((
/\u0020{4}".*?":\u0020null,?$/gm
), ""));
opt.packageJson.description = opt.dataFrom.split("\n")[1];
local.tryCatchOnError(function () {
local.objectSetDefault(opt.packageJson, {
nameLib: local.fsReadFileOrEmptyStringSync(
"./package.json",
"json"
).nameLib
});
}, local.nop);
opt.packageJson = local.objectSetDefault(opt.packageJson, {
nameLib: opt.packageJson.name.replace((
/\W/g
), "_"),
nameOriginal: opt.packageJson.name
});
opt.packageJson = local.objectSetDefault(
opt.packageJson,
JSON.parse(local.templateRenderMyApp(opt.packageJsonRgx.exec(
local.assetsDict["/assets.readme.template.md"]
)[1], opt)),
2
);
// avoid npm-installing that
delete opt.packageJson.devDependencies[opt.packageJson.name];
// reset scripts
opt.packageJson.scripts = {
"build-ci": "sh ./npm_scripts.sh",
env: "env",
eval: "sh ./npm_scripts.sh",
"heroku-postbuild": "sh ./npm_scripts.sh",
postinstall: "sh ./npm_scripts.sh",
start: "sh ./npm_scripts.sh",
test: "sh ./npm_scripts.sh",
utility2: "sh ./npm_scripts.sh"
};
// save package.json
local.fsWriteFileWithMkdirpSync(
"package.json",
local.jsonStringifyOrdered(opt.packageJson, null, 4) + "\n"
);
// re-render dataTo
opt.dataTo = local.templateRenderMyApp(
local.assetsDict["/assets.readme.template.md"],
opt
);
opt.dataTo = opt.dataTo.replace(
opt.packageJsonRgx,
match0.replace(
match1,
local.jsonStringifyOrdered(opt.packageJson, null, 4)
)
);
});
// search-and-replace - customize dataTo
[
// customize name and description
(
/.*?\n.*?\n/
),
// customize cdn-download
(
/\n#\u0020cdn\u0020download\n[\S\s]*?\n\n\n\n/
),
// customize live-web-demo
(
/\n#\u0020live\u0020web\u0020demo\n[\S\s]*?\n\n\n\n/
),
// customize to-do
(
/\n####\u0020todo\n[\S\s]*?\n\n\n\n/
),
// customize example.js - shared js-env code - init-before
(
/\nglobalThis\.local\u0020=\u0020local;\n[^`]*?\n\/\/\u0020run\u0020browser\u0020js\-env\u0020code\u0020-\u0020init-
test\n/
),
// customize example.js - html-body
(
/\nutility2-comment\u0020-->(?:\\n\\\n){4}[^`]*?^<!--\u0020utility2-comment\\n\\\n/m
),
// customize example.js - testRunBro...
...
/*
* this function will test buildReadme's default handling-behavior
*/
if (local.isBrowser) {
onError(null, opt);
return;
}
return local.buildReadme({}, onError);
};
local._testCase_buildTest_default = function (opt, onError) {
/*
* this function will test buildTest's default handling-behavior
*/
if (local.isBrowser) {
...
buildTest = function (opt, onError) {
/*
* this function will build test with given <opt>
*/
var result;
local.objectSetDefault(opt, {
customize: local.nop,
dataFrom: local.fsReadFileOrEmptyStringSync("test.js", "utf8"),
dataTo: local.templateRenderMyApp(
local.assetsDict["/assets.test.template.js"],
opt
)
});
// search-and-replace - customize dataTo
[
// customize shared js\-env code - function
(
/\n\}\(\)\);\n\n\n\n\/\/\u0020run\u0020shared\u0020js\-env\u0020code\u0020-\u0020function\n[\S\s]*?$/
)
].forEach(function (rgx) {
opt.dataTo = local.stringMerge(opt.dataTo, opt.dataFrom, rgx);
});
// customize require("utility2")
[
"./assets.utility2.rollup.js",
"./lib.utility2.js"
].forEach(function (file) {
if (local.fs.existsSync(file)) {
opt.dataTo = opt.dataTo.replace(
"require(\"utility2\")",
"require(\"" + file + "\")"
);
}
});
opt.customize(opt);
// save test.js
result = opt.dataTo;
local.fs.writeFileSync("test.js", result);
onError();
return result;
}
...
/*
* this function will test buildTest's default handling-behavior
*/
if (local.isBrowser) {
onError(null, opt);
return;
}
return local.buildTest({}, onError);
};
local._testCase_webpage_default = function (opt, onError) {
/*
* this function will test webpage's default handling-behavior
*/
local.domStyleValidate();
...
childProcessSpawnWithTimeout = function (command, args, opt) {
/*
* this function will run like child_process.spawn,
* but with auto-timeout after timeout milliseconds
* example usage:
var child = local.childProcessSpawnWithTimeout(
"/bin/sh",
["-c", "echo hello world"],
{stdio: ["ignore", 1, 2], timeout: 5000}
);
child.on("error", console.error);
child.on("exit", function (exitCode) {
console.error("exitCode " + exitCode);
});
*/
var child;
var child_process;
var timerTimeout;
child_process = require("child_process");
// spawn child
child = child_process.spawn(command, args, opt).on("exit", function () {
// cleanup timerTimeout
try {
process.kill(timerTimeout.pid);
} catch (ignore) {}
});
// init timerTimeout
timerTimeout = child_process.spawn(
// convert timeout to integer seconds with 2 second delay
"sleep "
+ Math.floor(
0.001 * (Number(opt && opt.timeout) || local.timeoutDefault)
+ 2
)
+ "; kill -9 " + child.pid + " 2>/dev/null",
{
shell: true,
stdio: "ignore"
}
);
return child;
}
...
"\nbrowserTest - created fileElectronHtml "
+ opt.fileElectronHtml
+ "\n"
);
// spawn an electron process to test a url
opt.npm_config_time_exit = opt.timeExit;
data.modeNext = 10;
local.childProcessSpawnWithTimeout("electron", [
__filename,
"utility2.browserTest",
opt.url,
"--enable-logging"
], {
env: data,
stdio: (
...
childProcessSpawnWithUtility2 = function (script, onError) {
/*
* this function will run child_process.spawn, with lib.utility2.sh sourced
*/
require("child_process").spawn(
". " + (process.env.npm_config_dir_utility2 || __dirname)
+ "/lib.utility2.sh; " + script,
{
shell: true,
stdio: [
"ignore", 1, 2
]
}
).on("exit", function (exitCode) {
onError(exitCode && Object.assign(new Error(), {
exitCode
}));
});
}
...
// test __dirname handling-behavior
[
process.env, {
npm_config_dir_utility2: ""
}
]
], function (onError) {
local.local.childProcessSpawnWithUtility2("undefined", function (err
) {
// validate err occurred
local.assertThrow(err, err);
});
onError(null, opt);
}, onError);
};
...
cliRun = function (opt) {
/*
* this function will run the cli with given <opt>
*/
local.cliDict._eval = local.cliDict._eval || function () {
/*
* <code>
* will eval <code>
*/
globalThis.local = local;
local.vm.runInThisContext(process.argv[3]);
};
local.cliDict["--eval"] = local.cliDict["--eval"] || local.cliDict._eval;
local.cliDict["-e"] = local.cliDict["-e"] || local.cliDict._eval;
local.cliDict._help = local.cliDict._help || function () {
/*
*
* will print help
*/
var commandList;
var file;
var packageJson;
var text;
var textDict;
commandList = [
{
argList: "<arg2> ...",
description: "usage:",
command: [
"<arg1>"
]
}, {
argList: "'console.log(\"hello world\")'",
description: "example:",
command: [
"--eval"
]
}
];
file = __filename.replace((
/.*\//
), "");
opt = Object.assign({}, opt);
packageJson = require("./package.json");
// validate comment
opt.rgxComment = opt.rgxComment || (
/\)\u0020\{\n(?:|\u0020{4})\/\*\n(?:\u0020|\u0020{5})\*((?:\u0020<[^>]*?>|\u0020\.\.\.)*?)\n(?:\u0020|\u0020{5})\*\u0020
(will\u0020.*?\S)\n(?:\u0020|\u0020{5})\*\/\n(?:\u0020{4}|\u0020{8})\S/
);
textDict = {};
Object.keys(local.cliDict).sort().forEach(function (key, ii) {
if (key[0] === "_" && key !== "_default") {
return;
}
text = String(local.cliDict[key]);
if (key === "_default") {
key = "";
}
textDict[text] = textDict[text] || (ii + 2);
ii = textDict[text];
if (commandList[ii]) {
commandList[ii].command.push(key);
return;
}
try {
commandList[ii] = opt.rgxComment.exec(text);
commandList[ii] = {
argList: (commandList[ii][1] || "").trim(),
command: [
key
],
description: commandList[ii][2]
};
} catch (ignore) {
local.assertThrow(null, new Error(
"cliRun - cannot parse comment in COMMAND "
+ key
+ ":\nnew RegExp("
+ JSON.stringify(opt.rgxComment.source)
+ ").exec(" + JSON.stringify(text).replace((
/\\\\/g
), "\u0000").replace((
/\\n/g
), "\\n\\\n").replace((
/\u0000/g
), "\\\\") + ");"
));
}
});
text = "";
text += packageJson.name + " (" + packageJson.version + ")\n\n";
text += commandList.filter(function (elem) {
return elem;
}).map(function (elem, ii) {
elem.command = elem.command.filter(function (elem) {
return elem;
});
switch (ii) {
case 0:
case 1:
elem.argList = [
elem.argList
];
break;
default:
elem.argList = elem.argList.split(" ");
elem.description = (
"# COMMAND "
+ (elem.command[0] || "<none>") + "\n# &...
...
dir: process.argv[2],
modulePathList: module.paths
}));
};
// run the cli
if (module === require.main && !globalThis.utility2_rollup) {
local.cliRun();
}
}());
}());
...
corsBackendHostInject = function (url, backendHost, rgx, location) {
/*
* this function will if <location>.host is a github site,
* inject <backendHost> into <url> with given <rgx>
*/
location = (
location
|| (typeof window === "object" && window && window.location)
);
if (!(backendHost && location && (
/\bgithub.io$/
).test(location.host))) {
return url;
}
// init github-branch
location.pathname.replace((
/\/build\.\.(alpha|beta|master)\.\.travis-ci\.org\//
), function (ignore, match1) {
backendHost = backendHost.replace("-alpha.", "-" + match1 + ".");
});
return url.replace(rgx || (
/.*?($)/m
), backendHost + "$1");
}
...
};
local.testCase_corsBackendHostInject_default = function (opt, onError) {
/*
* this function will corsBackendHostInject's default handling-behavior
*/
// test null-case handling-behavior
local.assertJsonEqual(local.corsBackendHostInject(), undefined);
// test override-all handling-behavior
local.assertJsonEqual(local.corsBackendHostInject(
"cc.com",
"aa-alpha.bb.com",
null,
{
host: "github.io",
...
corsForwardProxyHostIfNeeded = function (xhr) {
/*
* this function will return xhr.corsForwardProxyHost, if needed
*/
return (
local.isBrowser
&& local.env.npm_package_nameLib
&& (
/^https?:\/\//
).test(xhr.url)
&& xhr.url.indexOf(xhr.location.protocol + "//" + xhr.location.host)
!== 0
&& (
/\.github\.io$/
).test(xhr.location.host)
&& xhr.corsForwardProxyHost !== "disabled"
&& (xhr.corsForwardProxyHost || "https://h1-proxy1.herokuapp.com")
);
}
...
xhr.addEventListener("progress", ajaxProgressUpdate);
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/upload
if (xhr.upload && xhr.upload.addEventListener) {
xhr.upload.addEventListener("progress", ajaxProgressUpdate);
}
// open url - corsForwardProxyHost
if (local.functionOrNop(local2.corsForwardProxyHostIfNeeded)(xhr)) {
xhr.open(xhr.method, local2.corsForwardProxyHostIfNeeded(xhr));
xhr.setRequestHeader(
"forward-proxy-headers",
JSON.stringify(xhr.headers)
);
xhr.setRequestHeader("forward-proxy-url", xhr.url);
// open url - default
} else {
...
cryptoAesXxxCbcRawDecrypt = function (opt, onError) {
/*
* this function will aes-xxx-cbc decrypt with given <opt>
* example usage:
data = new Uint8Array([1,2,3]);
key = '0123456789abcdef0123456789abcdef';
mode = null;
local.cryptoAesXxxCbcRawEncrypt({
data: data,
key: key,
mode: mode
}, function (err, data) {
console.assert(!err, err);
local.cryptoAesXxxCbcRawDecrypt({
data: data,
key: key,
mode: mode
}, console.log);
});
*/
var cipher;
var crypto;
var data;
var ii;
var iv;
var key;
// init key
key = new Uint8Array(0.5 * opt.key.length);
ii = 0;
while (ii < key.byteLength) {
key[ii] = parseInt(opt.key.slice(2 * ii, 2 * ii + 2), 16);
ii += 2;
}
data = opt.data;
// base64
if (opt.mode === "base64") {
data = local.base64ToBuffer(data);
}
// normalize data
if (Object.prototype.toString.call(data) !== "[object Uint8Array]") {
data = new Uint8Array(data);
}
// init iv
iv = data.subarray(0, 16);
// optimization - create resized-view of data
data = data.subarray(16);
crypto = globalThis.crypto;
if (!local.isBrowser) {
setTimeout(function () {
crypto = require("crypto");
cipher = crypto.createDecipheriv(
"aes-" + (8 * key.byteLength) + "-cbc",
key,
iv
);
onError(null, Buffer.concat([
cipher.update(data), cipher.final()
]));
});
return;
}
crypto.subtle.importKey("raw", key, {
name: "AES-CBC"
}, false, [
"decrypt"
]).then(function (key) {
crypto.subtle.decrypt({
iv,
name: "AES-CBC"
}, key, data).then(function (data) {
onError(null, new Uint8Array(data));
}).catch(onError);
}).catch(onError);
}
...
mode = null;
local.cryptoAesXxxCbcRawEncrypt({
data: data,
key: key,
mode: mode
}, function (err, data) {
console.assert(!err, err);
local.cryptoAesXxxCbcRawDecrypt({
data: data,
key: key,
mode: mode
}, console.log);
});
*/
var cipher;
...
cryptoAesXxxCbcRawEncrypt = function (opt, onError) {
/*
* this function will aes-xxx-cbc encrypt with given <opt>
* example usage:
data = new Uint8Array([1,2,3]);
key = '0123456789abcdef0123456789abcdef';
mode = null;
local.cryptoAesXxxCbcRawEncrypt({
data: data,
key: key,
mode: mode
}, function (err, data) {
console.assert(!err, err);
local.cryptoAesXxxCbcRawDecrypt({
data: data,
key: key,
mode: mode
}, console.log);
});
*/
var cipher;
var crypto;
var data;
var ii;
var iv;
var key;
// init key
key = new Uint8Array(0.5 * opt.key.length);
ii = 0;
while (ii < key.byteLength) {
key[ii] = parseInt(opt.key.slice(2 * ii, 2 * ii + 2), 16);
ii += 2;
}
data = opt.data;
// init iv
iv = new Uint8Array((((data.byteLength) >> 4) << 4) + 32);
crypto = globalThis.crypto;
if (!local.isBrowser) {
setTimeout(function () {
crypto = require("crypto");
// init iv
iv.set(crypto.randomBytes(16));
cipher = crypto.createCipheriv(
"aes-" + (8 * key.byteLength) + "-cbc",
key,
iv.subarray(0, 16)
);
data = cipher.update(data);
iv.set(data, 16);
iv.set(cipher.final(), 16 + data.byteLength);
if (opt.mode === "base64") {
iv = local.base64FromBuffer(iv);
iv += "\n";
}
onError(null, iv);
});
return;
}
// init iv
iv.set(crypto.getRandomValues(new Uint8Array(16)));
crypto.subtle.importKey("raw", key, {
name: "AES-CBC"
}, false, [
"encrypt"
]).then(function (key) {
crypto.subtle.encrypt({
iv: iv.subarray(0, 16),
name: "AES-CBC"
}, key, data).then(function (data) {
iv.set(new Uint8Array(data), 16);
// base64
if (opt.mode === "base64") {
iv = local.base64FromBuffer(iv);
iv += "\n";
}
onError(null, iv);
}).catch(onError);
}).catch(onError);
}
...
local.cryptoAesXxxCbcRawDecrypt = function (opt, onError) {
/*
* this function will aes-xxx-cbc decrypt with given <opt>
* example usage:
data = new Uint8Array([1,2,3]);
key = '0123456789abcdef0123456789abcdef';
mode = null;
local.cryptoAesXxxCbcRawEncrypt({
data: data,
key: key,
mode: mode
}, function (err, data) {
console.assert(!err, err);
local.cryptoAesXxxCbcRawDecrypt({
data: data,
...
dateGetWeekOfMonth = function (date) {
/*
* this function will return sunday-based week-of-month from <date>
*/
date = new Date(date.slice(0, 10) + "T00:00:00Z");
return Math.ceil((date.getUTCDate() + new Date(
date.getUTCFullYear(),
date.getUTCMonth(),
1
).getUTCDay()) / 7) - 1;
}
n/a
dateGetWeekOfYear = function (date) {
/*
* this function will return ISO week-of-year from <date>
*
* Based on information at:
*
* http://www.merlyn.demon.co.uk/weekcalc.htm#WNR
*
* Algorithm is to find nearest thursday, it's year
* is the year of the week number. Then get weeks
* between that date and the first day of that year.
*
* Note that dates in one year can be weeks of previous
* or next year, overlap is up to 3 days.
*
* e.g. 2014/12/29 is Monday in week 1 of 2015
* 2012/1/1 is Sunday in week 52 of 2011
*
* https://stackoverflow.com/questions/6117814/get-week-of-year-in-javascript-like-in-php
*/
date = new Date(date.slice(0, 10) + "T00:00:00Z");
// Set to nearest Thursday: current date + 4 - current day number
// Make Sunday's day number 7
date.setUTCDate(date.getUTCDate() + 4 - (date.getUTCDay() || 7));
// Calculate full weeks to nearest Thursday
return Math.ceil((((
date
// Get first day of year
- new Date(Date.UTC(date.getUTCFullYear(), 0, 1))
) / 86400000) + 1) / 7);
}
n/a
dateUtcFromLocal = function (date, timezoneOffset) {
/*
* this function will convert local-<date> to utc-date
*/
if (!date) {
return "";
}
local.assertThrow((
/^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+?)?$/
).test(date), "invalid local-date " + date);
if (!timezoneOffset) {
return new Date(date).toISOString();
}
return new Date(
new Date(date + "Z").getTime() + timezoneOffset * 60000
).toISOString();
}
n/a
dateUtcToLocal = function (date, timezoneOffset) {
/*
* this function will convert utc-<date> to local-date
*/
if (!date) {
return "";
}
local.assertThrow((
/^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+?)?Z$/
).test(date), "invalid utc-date " + date);
timezoneOffset = timezoneOffset || new Date(date).getTimezoneOffset();
return new Date(
new Date(date).getTime() - timezoneOffset * 60000
).toISOString();
}
n/a
dbFieldRandomCreate = function (opt) {
/*
* this function will create a random dbField from <opt>.schemaP
*/
var depth;
var ii;
var max;
var min;
var schemaP;
var value;
depth = (
Number.isFinite(opt.depth)
? opt.depth
: 3
);
schemaP = opt.schemaP;
schemaP = schemaP.schema || schemaP;
if (schemaP.readOnly) {
return;
}
// init default
if (opt.modeNotRandom && !local.isNullOrUndefined(schemaP.default)) {
return local.jsonCopy(schemaP.default);
}
// init enum-value
if (schemaP.enum) {
value = (
opt.modeNotRandom
? schemaP.enum[0]
: local.listGetElementRandom(schemaP.enum)
);
return (
local.schemaPType(schemaP) === "array"
? [
value
]
: value
);
}
// init default
value = null;
switch (local.schemaPType(schemaP)) {
// 5.3. Validation keywords for arrays
case "array":
if (depth <= 0) {
break;
}
value = [];
ii = 0;
while (ii < Math.min(
// 5.3.2. maxItems
schemaP.maxItems || 2,
// 5.3.3. minItems
schemaP.minItems || 2,
// 5.3.4. uniqueItems
schemaP.uniqueItems
? 2
: 1
)) {
// recurse dbFieldRandomCreate
value.push(local.dbFieldRandomCreate({
depth: depth - 1,
modeNotRandom: opt.modeNotRandom,
schemaP: local.schemaPItems(schemaP)
}));
ii += 1;
}
break;
case "boolean":
value = (
opt.modeNotRandom
? false
: Boolean(Math.random() > 0.5)
);
break;
// 5.1. Validation keywords for numeric instances (number and integer)
case "integer":
case "number":
max = schemaP.maximum;
min = schemaP.minimum;
if (opt.modeNotRandom) {
value = (
!(0 < min || max < 0)
? 0
: min || max
);
} else {
if (!(Number.isFinite(max) && Number.isFinite(min))) {
if (!Number.isFinite(max) && !Number.isFinite(min)) {
max = 1000;
min = 0;
} else if (Number.isFinite(max)) {
min = max - 1000;
} else {
max = min + 1000;
}
}
// exclusiveMaximum and exclusiveMinimum for float
value = (
min
+ (max - min) * Math.max(Math.random(), min * 0.000000000000001)
);
if (local.schemaPType(schemaP) === "integer") {
value = Math.round(value);
}
}
max = schemaP.maximum;
min = schemaP.minimum;
// exclusiveMaximum for integer
if (schemaP.exclusiveMaximum && value === max) {
value -= 1;
}
// exclusiveMinimum for integer
if (schemaP.exclusiveMaximum && value === min) {
value += 1;
}
// multipleOf
if (schemaP.multipleOf > 0) {
value = schemaP.multipleOf * Math.floor(value / schemaP.multipleOf);
if (value < min || (schemaP.exclusiveMinimum && value <= min)) {
value += schemaP.multipleOf;
}
}
break;
// 5.2. Validation keywords for strings
case "string":
value = (
opt.modeNotRandom
? "abcd1234"
: ((1 + Math.random()) * 0x10000000000000).toString(36).slice(1)
);
switch (schemaP.format) {
case "byte":
value = local.base64FromBuffer(value);...
...
schemaP.minItems || 2,
// 5.3.4. uniqueItems
schemaP.uniqueItems
? 2
: 1
)) {
// recurse dbFieldRandomCreate
value.push(local.dbFieldRandomCreate({
depth: depth - 1,
modeNotRandom: opt.modeNotRandom,
schemaP: local.schemaPItems(schemaP)
}));
ii += 1;
}
break;
...
dbRowListRandomCreate = function (opt) {
/*
* this function will create a dbRowList of <opt>.length random dbRow's
*/
var ii;
ii = 0;
while (ii < opt.length) {
opt.dbRowList.push(local.dbRowRandomCreate(opt));
ii += 1;
}
return opt.dbRowList;
}
n/a
dbRowRandomCreate = function (opt) {
/*
* this function will create a random dbRow from opt.properties
*/
var dbRow;
var ii;
var properties;
dbRow = {};
opt = local.objectSetDefault(opt, {
override: local.nop,
prefix: [
"dbRow"
]
});
properties = local.swaggerValidateDataSchema({
// dereference property
modeDereference: true,
prefix: opt.prefix,
schema: opt.schema,
swaggerJson: local.swaggerJson
});
properties = local.jsonCopy((properties && properties.properties) || {});
ii = Object.keys(properties).length;
while (ii < (opt.schema && opt.schema.minProperties)) {
properties["property" + ii] = {
type: "string"
};
ii += 1;
}
Object.keys(properties).forEach(function (key) {
dbRow[key] = local.dbFieldRandomCreate({
depth: opt.depth,
modeNotRandom: opt.modeNotRandom,
schemaP: local.swaggerValidateDataSchema({
// dereference property
modeDereference: true,
prefix: opt.prefix.concat([
key
]),
schema: properties[key],
swaggerJson: local.swaggerJson
})
});
});
dbRow = local.jsonCopy(local.objectSetOverride(dbRow, opt.override(opt)));
// try to validate data
local.tryCatchOnError(function () {
local.swaggerValidateDataSchema({
data: dbRow,
prefix: opt.prefix,
schema: opt.schema,
swaggerJson: local.swaggerJson
});
}, local.onErrorDefault);
return dbRow;
}
...
break;
// 5.4. Validation keywords for objects
default:
if (depth <= 0) {
break;
}
// recurse dbRowRandomCreate
value = local.dbRowRandomCreate({
depth: depth - 1,
modeNotRandom: opt.modeNotRandom,
prefix: [
"schema<" + JSON.stringify(schemaP) + ">"
],
schema: schemaP
});
...
domFragmentRender = function (template, dict) {
/*
* this function will return dom-elem rendered from <template>
*/
var tmp;
tmp = document.createElement("template");
tmp.innerHTML = local.templateRender(template, dict);
return tmp.content;
}
...
});
// init uiFragment
swaggerJson.uiFragment = document.createDocumentFragment();
// init resourceDict
Object.keys(swaggerJson.resourceDict).sort().forEach(function (key) {
// templateRender resource
swaggerJson.uiFragment.appendChild(
local.domFragmentRender(
local.templateUiResource,
swaggerJson.resourceDict[key]
)
);
});
Object.keys(swaggerJson.operationDict).sort(function (aa, bb) {
aa = swaggerJson.operationDict[aa];
...
domQuerySelectorAllTagName = function (selector) {
/*
* this function will return all tagName that match <selector>
*/
var set;
set = new Set();
Array.from(document.querySelectorAll(
selector
)).forEach(function (elem) {
set.add(elem.tagName);
});
return Array.from(set).sort();
}
n/a
domSelectOptionValue = function (elem) {
/*
* this function will return <elem>.options[<elem>.selectedIndex].value
*/
elem = elem && elem.options[elem.selectedIndex];
return (elem && elem.value) || "";
}
n/a
domStyleValidate = function () {
/*
* this function will validate <style> tags
*/
var rgx;
var tmp;
rgx = (
/^0\u0020(?:(body\u0020>\u0020)?(?:form\u0020>\u0020)?(?:\.testReportDiv\u0020.+|\.x-istanbul\u0020.+|\.button|\.colorError
|\.readonly|\.textarea|\.uiAnimateShake|\.uiAnimateSlide|a|body|code|div|input|pre|textarea)(?:,|\u0020\{))|^[1-9]\d*?\u0020#/m
);
tmp = [];
Array.from(
// ternary-operator
(
typeof document === "object"
&& document
&& typeof document.querySelector === "function"
)
? document.querySelectorAll(
"style"
)
: []
).map(function (elem, ii) {
elem.innerHTML.replace((
/\/\*[\S\s]*?\*\/|;|\}/g
), "\n").replace((
/^([^\n\u0020@].*?)[,{:].*?$/gm
), function (match0, match1) {
try {
ii = document.querySelectorAll(
match1
).length;
} catch (errCaught) {
console.error(errCaught);
}
if (!(ii > 1)) {
tmp.push(ii + " " + match0);
}
});
});
tmp.filter(function (elem) {
return !rgx.test(elem);
}).sort().reverse().forEach(function (elem, ii, list) {
console.error(
"domStyleValidateUnmatched " + (list.length - ii) + ". " + elem
);
});
}
...
return local.buildTest({}, onError);
};
local._testCase_webpage_default = function (opt, onError) {
/*
* this function will test webpage's default handling-behavior
*/
local.domStyleValidate();
if (local.isBrowser) {
onError(null, opt);
return;
}
local.browserTest({
fileScreenshot: (
local.env.npm_config_dir_build
...
errorMessagePrepend = function (err, message) {
/*
* this function will prepend message to <err>.message and <err>.stack
*/
if (err === local.errDefault) {
return;
}
err.message = message + err.message;
err.stack = message + err.stack;
return err;
}
...
*/
local.onErrorJsonapi(function (err, data) {
local.serverRespondHeadSet(req, res, err && err.statusCode, {
"Content-Type": "application/json"
});
if (err) {
// debug statusCode / method / url
local.errorMessagePrepend(
err,
res.statusCode + " " + req.method + " " + req.url + "\n"
);
// print err.stack to stderr
local.onErrorDefault(err);
}
data = err || data;
...
function EventEmitter() { EventEmitter.init.call(this); }
n/a
exit = function (exitCode, testReport) {
/*
* this function will exit current process with given <exitCode>
*/
local.onErrorDefault(typeof exitCode !== "number" && exitCode);
exitCode = (
(!exitCode || Number(exitCode) === 0)
? 0
: Number(exitCode) || 1
);
if (!local.isBrowser) {
process.exit(exitCode);
return;
}
if (testReport !== globalThis.utility2_testReport) {
return;
}
// update coverage
(document.querySelector(
"#coverageReportDiv1"
) || {}).innerHTML = (
local.istanbulCoverageReportCreate()
);
// save testReport
globalThis.utility2_testReportSave();
}
...
* <fileRemote|dirRemote> <commitMessage>
* will delete from github <fileRemote|dirRemote>
*/
local.github_crud.githubCrudContentDelete({
message: process.argv[4],
url: process.argv[3]
}, function (err) {
process.exit(Boolean(err));
});
};
local.cliDict.get = function () {
/*
* <fileRemote>
* will get from github <fileRemote>
...
fsReadFileOrEmptyStringSync = function (file, opt) {
/*
* this function will try to read file or return empty-string, or
* if <opt> === "json", then try to JSON.parse file or return null
*/
try {
return (
opt === "json"
? JSON.parse(local.fs.readFileSync(file, "utf8"))
: local.fs.readFileSync(file, opt)
);
} catch (ignore) {
return (
opt === "json"
? {}
: ""
);
}
}
...
local.templateSwaggerUiLogoMediumBase64,
"base64"
);
local.assetsDict["/assets.swagger-ui.logo.small.png"] = Buffer.from(
local.templateSwaggerUiLogoSmallBase64,
"base64"
);
local.swgg.apiUpdate(local.fsReadFileOrEmptyStringSync(
local.__dirname + "/assets.swgg.swagger.json",
"json"
));
}());
...
fsRmrSync = function (dir) {
/*
* this function will synchronously "rm -fr" dir
*/
local.child_process.execFileSync(
"rm",
[
"-fr", local.path.resolve(process.cwd(), dir)
],
{
stdio: [
"ignore", 1, 2
]
}
);
}
...
/*
* this function will build app with given <opt>
*/
opt = local.objectSetDefault(opt, {
assetsList: []
});
// build assets
local.fsRmrSync("tmp/build/app");
local.onParallelList({
list: [
{
file: "/LICENSE",
url: "/LICENSE"
}, {
file: "/assets." + local.env.npm_package_nameLib + ".html",
...
fsWriteFileWithMkdirpSync = function (file, data, mode) {
/*
* this function will synchronously "mkdir -p" and write <data> to <file>
*/
try {
if (
mode === "noWrite"
|| typeof require("fs").writeFileSync !== "function"
) {
return;
}
} catch (ignore) {
return;
}
// try to write to file
try {
require("fs").writeFileSync(file, data);
} catch (ignore) {
// mkdir -p
require("child_process").spawnSync(
"mkdir",
[
"-p", require("path").dirname(file)
],
{
stdio: [
"ignore", 1, 2
]
}
);
// re-write to file
require("fs").writeFileSync(file, data);
}
}
...
// 1. print coverage in text-format to stdout
new local.TextReport(opt).writeReport(local.collector);
// 2. write coverage in html-format to filesystem
new local.HtmlReport(opt).writeReport(local.collector);
local.writer.writeFile("", local.nop);
if (!local.isBrowser) {
// write coverage.json
local.fsWriteFileWithMkdirpSync(
opt.dir + "/coverage.json",
JSON.stringify(globalThis.__coverage__)
);
// write coverage.code-dict.json
local.fsWriteFileWithMkdirpSync(
opt.dir + "/coverage.code-dict.json",
JSON.stringify(globalThis.__coverageCodeDict__)
...
functionOrNop = function (fnc) {
/*
* this function will if <fnc> exists,
* them return <fnc>,
* else return <nop>
*/
return fnc || local.nop;
}
...
if (element.isDescending) {
result.reverse();
}
});
// skip
result = result.slice(skip || 0);
// shuffle
local.functionOrNop(shuffle && local.listShuffle)(result);
// limit
result = result.slice(0, limit || Infinity);
return result;
};
local._DbTable.prototype._crudGetOneById = function (idDict) {
/*
...
idDomElementCreate = function (seed) {
/*
* this function will create a deterministic and unique dom-element id
* from <seed> that is both dom-selector and url friendly
*/
local.idDomElementDict[seed] = (local.idDomElementDict[seed] || 0) + 1;
return encodeURIComponent(
seed + "_" + local.idDomElementDict[seed]
).replace((
/\W/g
), "_");
}
...
swaggerJson.resourceDict[tag] || swaggerJson.tagDict[tag],
{
description: "no description",
name: tag
}
);
resource = swaggerJson.resourceDict[tag];
resource.id = resource.id || local.idDomElementCreate(
"swgg_id_" + tag
);
resource.summary = resource.summary || String(
resource.description
).replace((
/\bhttps?:\/\/[^\s<]+[^<.,:;"')\]\s]/g
), "");
...
idNameInit = function (opt) {
/*
* this function will init <opt>.idBackend, <opt>.idName, and <opt>.queryById
*/
var idBackend;
var idName;
// init idName
idName = opt.crudType[1] || "id";
opt.idName = idName;
// init idBackend
idBackend = opt.crudType[2] || opt.idName;
opt.idBackend = idBackend;
// invert queryById
if (opt.modeQueryByIdInvert) {
idBackend = opt.idName;
idName = opt.idBackend;
}
// init queryById
opt.idValue = (opt.data && opt.data[idBackend]) || opt.idValue;
opt.queryById = {};
opt.queryById[idName] = opt.idValue;
return opt;
}
...
that._crudType = that._crudType || key.slice(2);
that._crudType[0] = that._crudType[0] || that.operationId;
// init _fileUploadNumber
that._fileUploadNumber = Number(
that._crudType[0] === "fileUploadManyByForm" && that._crudType[1]
) || 1;
// init _idBackend and _idName
tmp = local.idNameInit({
crudType: that._crudType
});
that._idBackend = tmp.idBackend;
that._idName = tmp.idName;
// init tags
that.tags = that.tags || [];
that.tags[0] = that.tags[0] || key[1];
...
identity = function (value) {
/*
* this function will return <value>
*/
return value;
}
...
local.cliDict.help = local.cliDict.help || local.cliDict._help;
local.cliDict._interactive = local.cliDict._interactive || function () {
/*
*
* will start interactive-mode
*/
globalThis.local = local;
local.identity(local.replStart || require("repl").start)({
useGlobal: true
});
};
local.cliDict["--interactive"] = (
local.cliDict["--interactive"]
|| local.cliDict._interactive
);
...
isNullOrUndefined = function (arg0) {
/*
* this function will test if arg0 is null or undefined
*/
return arg0 === null || arg0 === undefined;
}
...
? "arraybuffer"
: ""
)
});
// init paramDict
that.parameters.forEach(function (schemaP) {
tmp = opt.paramDict[schemaP.name];
if (local.isNullOrUndefined(tmp)) {
return;
}
// serialize array
if (Array.isArray(tmp) && schemaP.in !== "body") {
switch (
schemaP.collectionFormat || schemaP["x-swgg-collectionFormat"]
) {
...
istanbulCoverageMerge = function (coverage1, coverage2) {
/*
* this function will inplace-merge coverage2 into coverage1
*/
var dict1;
var dict2;
coverage1 = coverage1 || {};
coverage2 = coverage2 || {};
Object.keys(coverage2).forEach(function (file) {
if (!coverage2[file]) {
return;
}
// if file is undefined in coverage1, then add it
if (!coverage1[file]) {
coverage1[file] = coverage2[file];
return;
}
// merge file from coverage2 into coverage1
[
"b", "f", "s"
].forEach(function (key) {
dict1 = coverage1[file][key];
dict2 = coverage2[file][key];
switch (key) {
// increment coverage for branch lines
case "b":
Object.keys(dict2).forEach(function (key) {
dict2[key].forEach(function (count, ii) {
dict1[key][ii] += count;
});
});
break;
// increment coverage for function and statement lines
case "f":
case "s":
Object.keys(dict2).forEach(function (key) {
dict1[key] += dict2[key];
});
break;
}
});
});
return coverage1;
}
...
return;
}
// merge browser coverage
data = (
opt.modeCoverageMerge
&& local.fsReadFileOrEmptyStringSync(opt.fileCoverage, "json")
);
local.istanbulCoverageMerge(window.__coverage__, data);
console.error(
"\nbrowserTest - merged coverage from file "
+ opt.fileCoverage
+ "\n"
);
// merge browser test-report
data = local.fsReadFileOrEmptyStringSync(
...
istanbulCoverageReportCreate = function () {
/*
* this function will
* 1. print coverage in text-format to stdout
* 2. write coverage in html-format to filesystem
* 3. return coverage in html-format as single document
*/
var opt;
/* istanbul ignore next */
if (!globalThis.__coverage__) {
return "";
}
opt = {};
opt.dir = process.cwd() + "/tmp/build/coverage.html";
// merge previous coverage
if (!local.isBrowser && process.env.npm_config_mode_coverage_merge) {
console.log("merging file " + opt.dir + "/coverage.json to coverage");
try {
local.coverageMerge(globalThis.__coverage__, JSON.parse(
local.fs.readFileSync(opt.dir + "/coverage.json", "utf8")
));
} catch (ignore) {}
try {
opt.coverageCodeDict = JSON.parse(local.fs.readFileSync(
opt.dir + "/coverage.code-dict.json",
"utf8"
));
Object.keys(opt.coverageCodeDict).forEach(function (key) {
globalThis.__coverageCodeDict__[key] = (
globalThis.__coverageCodeDict__[key]
|| opt.coverageCodeDict[key]
);
});
} catch (ignore) {}
}
// init writer
local.coverageReportHtml = "";
local.coverageReportHtml += (
"<div class=\"coverageReportDiv\">\n"
+ "<h1>coverage-report</h1>\n"
+ "<div style=\""
+ "background: #fff; border: 1px solid #000; margin 0; padding: 0;"
+ "\">\n"
);
local.writerData = "";
opt.sourceStore = {};
opt.writer = local.writer;
// 1. print coverage in text-format to stdout
new local.TextReport(opt).writeReport(local.collector);
// 2. write coverage in html-format to filesystem
new local.HtmlReport(opt).writeReport(local.collector);
local.writer.writeFile("", local.nop);
if (!local.isBrowser) {
// write coverage.json
local.fsWriteFileWithMkdirpSync(
opt.dir + "/coverage.json",
JSON.stringify(globalThis.__coverage__)
);
// write coverage.code-dict.json
local.fsWriteFileWithMkdirpSync(
opt.dir + "/coverage.code-dict.json",
JSON.stringify(globalThis.__coverageCodeDict__)
);
// write coverage.badge.svg
opt.pct = local.coverageReportSummary.root.metrics.lines.pct;
local.fsWriteFileWithMkdirpSync(
local._istanbul_path.dirname(opt.dir) + "/coverage.badge.svg",
local.templateCoverageBadgeSvg
// edit coverage badge percent
.replace((
/100.0/g
), opt.pct)
// edit coverage badge color
.replace((
/0d0/g
), ((
"0" + Math.round((100 - opt.pct) * 2.21).toString(16)
).slice(-2) + (
"0" + Math.round(opt.pct * 2.21).toString(16)
).slice(-2) + "00"))
);
}
console.log("created coverage file " + opt.dir + "/index.html");
// 3. return coverage in html-format as a single document
local.coverageReportHtml += "</div>\n</div>\n";
// write coverage.rollup.html
if (!local.isBrowser) {
local.fsWriteFileWithMkdirpSync(
opt.dir + "/coverage.rollup.html",
local.coverageReportHtml
);
}
return local.coverageReportHtml;
}
...
if (testReport !== globalThis.utility2_testReport) {
return;
}
// update coverage
(document.querySelector(
"#coverageReportDiv1"
) || {}).innerHTML = (
local.istanbulCoverageReportCreate()
);
// save testReport
globalThis.utility2_testReportSave();
};
local.fsReadFileOrEmptyStringSync = function (file, opt) {
/*
...
istanbulInstrumentInPackage = function (code, file) {
/*
* this function will instrument the code
* only if the macro /\* istanbul instrument in package $npm_package_nameLib *\/
* exists in the code
*/
return (
// ternary-operator
(
process.env.npm_config_mode_coverage
&& code.indexOf("/* istanbul ignore all */\n") < 0 && (
process.env.npm_config_mode_coverage === "all"
|| code.indexOf(
"/* istanbul instrument in package "
+ process.env.npm_package_nameLib + " */\n"
) >= 0
|| code.indexOf(
"/* istanbul instrument in package "
+ process.env.npm_config_mode_coverage + " */\n"
) >= 0
)
)
? local.instrumentSync(code, file)
: code
);
}
...
"globalThis.utility2_moduleExports"
);
// init example.js
tmp = process.cwd() + "/example.js";
// jslint code
local.jslintAndPrint(code, tmp);
// cover code
code = local.istanbulInstrumentInPackage(code, tmp);
// init module.exports
module = new local.Module(tmp);
require.cache[tmp] = module;
// load code into module
module._compile(code, tmp);
// init exports
module.exports.utility2 = local;
...
istanbulInstrumentSync = function (code, file) {
/*
* this function will
* 1. normalize the file
* 2. save code to __coverageCodeDict__[file] for future html-report
* 3. return instrumented code
*/
// 1. normalize the file
file = local._istanbul_path.resolve("/", file);
// 2. save code to __coverageCodeDict__[file] for future html-report
globalThis.__coverageCodeDict__[file] = code;
// 3. return instrumented code
return new local.Instrumenter({
embedSource: true,
esModules: true,
noAutoWrap: true
}).instrumentSync(code, file).trimLeft();
}
n/a
jslintAndPrint = function (code, file, opt) {
/*
* this function will jslint / csslint <code> and print any errors to stderr
*/
var tmp;
if (!(opt && opt.modeNext)) {
local.jslintResult = {
modeNext: 0
};
}
code = code || "";
file = file || "undefined";
opt = Object.assign(local.jslintResult, opt || {}, {
code,
file
});
opt.modeNext += 1;
switch (opt.modeNext) {
// jslint - init
case 1:
// cleanup
opt.errList = [];
opt.errText = "";
switch (opt.fileType0) {
// deembed-js - '\\n\\\n...\\n\\\n'
case ".\\n\\":
// rgx - remove \\n\\
code = code.replace((
/\\n\\$|\\(.)/gm
), function (match0) {
return (
match0 === "\\n\\"
? ""
: match0[1]
);
});
break;
// deembed-js - '\n...\n'
case ".sh":
// rgx - convert '"'"' to '
code = code.replace((
/'"'"'/g
), "'");
break;
}
// init
opt = Object.assign(opt, {
".css": (
/^\/\*csslint\b|(^\/\*\u0020jslint\u0020utility2:true\u0020\*\/$)/m
),
".html": (
/^\/\*csslint\b|(^\/\*\u0020jslint\u0020utility2:true\u0020\*\/$)/m
),
".js": (
/^\/\*jslint\b|(^\/\*\u0020jslint\u0020utility2:true\u0020\*\/$)/m
),
".md": (
/(^\/\*\u0020jslint\u0020utility2:true\u0020\*\/$)/m
),
".sh": (
/(^#\u0020jslint\u0020utility2:true$)/m
),
code0: code,
fileType: (
/\.\w+?$|$/m
).exec(file)[0]
});
// jslint - .json
if (
code && (opt.fileType === ".js" || opt.fileType === ".json")
&& !opt.fileType0
) {
try {
tmp = JSON.parse(code);
opt.fileType = ".json";
if (opt.autofix) {
code = JSON.stringify(tmp, null, 4) + "\n";
opt.code0 = code;
}
opt.modeNext = Infinity;
break;
} catch (errCaught) {
if (opt.fileType === ".json") {
opt.errList.push({
column: 0,
evidence: code.slice(0, 100),
line: 0,
message: errCaught.message
});
opt.modeNext = Infinity;
break;
}
}
}
try {
opt.conditionalPassed = opt[opt.fileType].exec(code);
} catch (ignore) {}
opt.utility2 = (
opt.conditionalPassed
&& opt.conditionalPassed[1]
) || opt.autofix;
if (
opt.conditional
&& (!opt.conditionalPassed || opt.coverage)
) {
break;
}
opt.modeNext = 10;
break;
// jslint - autofix
case 11:
code = local.jslintAutofix(code, file, opt);
local.jslintResult = opt;
break;
// jslint - csslint and jslint
case 12:
// restore lineOffset
code = "\n".repeat(opt.lineOffset | 0) + code;
switch (opt.fileType) {
case ".css":
// csslint
Object.assign(opt, local.CSSLint.verify(code));
// init errList
opt.errList = opt.messages.map(function (err) {
err...
...
return;
}
// read file
local.fs.readFile(opt.file, "utf8", opt.onNext);
break;
case 2:
// jslint
local.jslint.jslintAndPrint(data, opt.file);
local.assertThrow(
!local.jslint.jslintResult.errText,
local.jslint.jslintResult.errText.replace((
/\u001b\[\d*m/g
), "")
);
// validate
...
jslintAutofixLocalFunction = function (code, file) {
/*
* this function will jslint-autofix local-function
*/
var code2;
var dictFnc;
var dictProp;
var tmp;
if (local.isBrowser) {
return code;
}
file = file.replace(process.cwd() + "/", "");
switch (file) {
case "README.md":
case "lib." + process.env.npm_package_nameLib + ".js":
case "lib." + process.env.npm_package_nameLib + ".sh":
case "lib.apidoc.js":
case "lib.db.js":
case "lib.github_crud.js":
case "lib.istanbul.js":
case "lib.jslint.js":
case "lib.marked.js":
case "lib.sjcl.js":
case "lib.swgg.js":
case "npm_scripts.sh":
case "test.js":
break;
default:
return code;
}
// autofix - assets.example.begin.js
code = code.replace((
/^\(function\u0020\(globalThis\)\u0020\{\n[\S\s]*?\n\}\(this\)\);\n/m
), local.assetsDict["/assets.example.begin.js"]);
// autofix - assets.my_app.template.js
code = local.stringMerge(
code,
local.assetsDict["/assets.my_app.template.js"].replace((
/my_app/g
), file.split(".")[1]),
file !== "README.md" && local.identity(
/\n\/\*\u0020istanbul\u0020instrument\u0020in\u0020package\u0020[\S\s]*?\n\/\*\u0020validateLineSortedReset\u0020\*\/\n/
)
);
// customize local for assets.utility2.rollup.js
if (
file === "lib." + process.env.npm_package_nameLib + ".js"
&& local.fs.existsSync("./assets.utility2.rollup.js")
&& local.env.npm_package_nameLib !== "swgg"
) {
code = code.replace(
" // || globalThis.utility2_rollup_old",
" || globalThis.utility2_rollup_old"
).replace(
" // || require(\"./assets.utility2.rollup.js\")",
" || require(\"./assets.utility2.rollup.js\")"
);
}
// init functionAllDict and functionBaseDict
[
[
"utility2", "swgg"
], [
"utility2", "apidoc", "db", "github_crud", "swgg"
]
].forEach(function (dictList, ii) {
tmp = (
ii
? "functionAllDict"
: "functionBaseDict"
);
if (local[tmp]) {
return;
}
local[tmp] = {};
dictList.forEach(function (dict) {
dict = local[dict];
Object.keys(dict).forEach(function (key) {
if (
!(
/^[A-Z_]|^testCase_/m
).test(key)
&& typeof dict[key] === "function"
) {
local[tmp][key] = local[tmp][key] || String(dict[key]);
}
});
});
Object.keys(local[tmp]).forEach(function (key) {
if (process.binding("natives")[key]) {
local[tmp][key] = undefined;
}
});
});
// autofix - local-function
dictFnc = {};
dictProp = {};
code = code.replace((
/^local\.(.*?)\u0020=\u0020(function\u0020\([\S\s]*?\n\});\n+/gm
), function (match0, key, match2, match3) {
// local-function - duplicate
if (dictFnc[key]) {
return "";
}
// local-function - normalize
dictFnc[key] = true;
match3 = local.functionAllDict[key] || "";
// make shell-safe
// https://unix.stackexchange.com/questions/57794/shell-escape-characters-for-sh-c
if (file.slice(-3) === ".sh") {
match3 = match3.re...
n/a
jsonCopy = function (obj) {
/*
* this function will deep-copy obj
*/
return (
obj === undefined
? undefined
: JSON.parse(JSON.stringify(obj))
);
}
...
? undefined
// recurse
: normalize(dbRow[key])
);
});
return dbRow;
};
dbRow = local.jsonCopy(local.objectSetOverride(dbRow));
// update timestamp
timeNow = new Date().toISOString();
dbRow._timeCreated = dbRow._timeCreated || timeNow;
if (!local.modeImport) {
dbRow._timeUpdated = timeNow;
}
// normalize
...
jsonStringifyOrdered = function (obj, replacer, space) {
/*
* this function will JSON.stringify <obj>,
* with object-keys sorted and circular-references removed
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Syntax
*/
var circularSet;
var stringify;
var tmp;
stringify = function (obj) {
/*
* this function will recursively JSON.stringify obj,
* with object-keys sorted and circular-references removed
*/
// if obj is not an object or function, then JSON.stringify as normal
if (!(
obj
&& typeof obj === "object"
&& typeof obj.toJSON !== "function"
)) {
return JSON.stringify(obj);
}
// ignore circular-reference
if (circularSet.has(obj)) {
return;
}
circularSet.add(obj);
// if obj is an array, then recurse its items
if (Array.isArray(obj)) {
tmp = "[" + obj.map(function (obj) {
// recurse
tmp = stringify(obj);
return (
typeof tmp === "string"
? tmp
: "null"
);
}).join(",") + "]";
circularSet.delete(obj);
return tmp;
}
// if obj is not an array,
// then recurse its items with object-keys sorted
tmp = "{" + Object.keys(obj).sort().map(function (key) {
// recurse
tmp = stringify(obj[key]);
if (typeof tmp === "string") {
return JSON.stringify(key) + ":" + tmp;
}
}).filter(function (obj) {
return typeof obj === "string";
}).join(",") + "}";
circularSet.delete(obj);
return tmp;
};
circularSet = new Set();
return JSON.stringify((
(typeof obj === "object" && obj)
// recurse
? JSON.parse(stringify(obj))
: obj
), replacer, space);
}
...
}
result = {};
fieldList.forEach(function (key) {
if (key[0] !== "$") {
result[key] = dbRow[key];
}
});
return JSON.parse(local.jsonStringifyOrdered(result));
};
local.dbRowSetId = function (dbRow, idIndex) {
/*
* this function will if does not exist,
* then set a random and unique id into dbRow for given idIndex,
*/
...
jwtAes256GcmDecrypt = function (token, key) {
/*
* this function will use json-web-encryption to
* aes-256-gcm-decrypt <token> with given base64url-encoded <key>
* https://tools.ietf.org/html/rfc7516
*/
return local.tryCatchOnError(function () {
token = token
.replace((
/-/g
), "+")
.replace((
/_/g
), "/")
.split(".");
token = local.sjcl.decrypt(
local.sjcl.codec.base64url.toBits(local.jwtAes256KeyInit(key)),
JSON.stringify({
adata: token[4],
ct: token[3],
iv: token[2],
ks: 256,
mode: "gcm"
})
);
return local.jwtHs256Decode(token, key);
}, local.nop) || {};
}
...
crud = req.swgg.crud;
user = {};
req.swgg.user = user;
user.jwtEncrypted = (
req.headers.authorization
&& req.headers.authorization.replace("Bearer ", "")
);
user.jwtDecrypted = local.jwtAes256GcmDecrypt(user.jwtEncrypted);
switch (crud.crudType[0]) {
// coverage-hack - test err handling-behavior
case "crudErrorLogin":
opt.onNext(local.errDefault);
return;
case "userLoginByPassword":
user.password = req.urlParsed.query.password;
...
jwtAes256GcmEncrypt = function (data, key) {
/*
* this function will use json-web-encryption to
* aes-256-gcm-encrypt <data> with given base64url-encoded <key>
* https://tools.ietf.org/html/rfc7516
*/
var adata;
adata = local.jwtAes256KeyCreate();
data = local.jwtHs256Encode(data, key);
data = JSON.parse(local.sjcl.encrypt(
local.sjcl.codec.base64url.toBits(local.jwtAes256KeyInit(key)),
data,
{
adata: local.sjcl.codec.base64url.toBits(adata),
ks: 256,
mode: "gcm"
}
));
return local.normalizeJwtBase64Url(
"eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4R0NNIn0.."
+ data.iv + "." + data.ct + "." + adata
);
}
...
// init isAuthenticated
user.isAuthenticated = true;
// create JSON Web Token (JWT)
// https://tools.ietf.org/html/rfc7519
user.jwtDecrypted = {};
user.jwtDecrypted.sub = user.data.username;
// update jwtEncrypted in client
user.jwtEncrypted = local.jwtAes256GcmEncrypt(
user.jwtDecrypted
);
local.serverRespondHeadSet(req, res, null, {
"swgg-jwt-encrypted": user.jwtEncrypted
});
// update jwtEncrypted in dbTableUser
local.dbTableUser.crudUpdateOneById({
...
jwtAes256KeyCreate = function () {
/*
* this function will create a random, aes-256-base64url-jwt-key
*/
return local.normalizeJwtBase64Url(
local.base64FromBuffer(local.bufferRandomBytes(32))
);
}
...
local.jwtAes256GcmEncrypt = function (data, key) {
/*
* this function will use json-web-encryption to
* aes-256-gcm-encrypt <data> with given base64url-encoded <key>
* https://tools.ietf.org/html/rfc7516
*/
var adata;
adata = local.jwtAes256KeyCreate();
data = local.jwtHs256Encode(data, key);
data = JSON.parse(local.sjcl.encrypt(
local.sjcl.codec.base64url.toBits(local.jwtAes256KeyInit(key)),
data,
{
adata: local.sjcl.codec.base64url.toBits(adata),
ks: 256,
...
jwtAes256KeyInit = function (key) {
/*
* this function will init aes-256-base64url-jwt-<key>
* https://jwt.io/
*/
// init npm_config_jwtAes256Key
local.env.npm_config_jwtAes256Key = (
local.env.npm_config_jwtAes256Key
|| "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
);
return key || local.env.npm_config_jwtAes256Key;
}
...
/-/g
), "+")
.replace((
/_/g
), "/")
.split(".");
token = local.sjcl.decrypt(
local.sjcl.codec.base64url.toBits(local.jwtAes256KeyInit(key)),
JSON.stringify({
adata: token[4],
ct: token[3],
iv: token[2],
ks: 256,
mode: "gcm"
})
...
jwtHs256Decode = function (token, key) {
/*
* this function will decode json-web-token with given base64-encoded <key>
* https://jwt.io/
*/
var Hmac;
var timeNow;
Hmac = local.sjcl.misc.hmac;
timeNow = Date.now() / 1000;
// try to decode token
return local.tryCatchOnError(function () {
token = token.split(".");
// validate header
local.assertThrow(
token[0] === "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9",
token
);
// validate signature
local.assertThrow(local.sjcl.codec.base64url.fromBits(
new Hmac(local.sjcl.codec.base64url.toBits(
local.jwtAes256KeyInit(key)
)).encrypt(token[0] + "." + token[1])
) === token[2]);
// return decoded data
token = JSON.parse(local.base64ToUtf8(token[1]));
// https://tools.ietf.org/html/rfc7519#section-4.1
// validate jwt-registered-headers
local.assertThrow(!token.exp || token.exp >= timeNow);
local.assertThrow(!token.nbf || token.nbf <= timeNow);
return token;
}, local.nop) || {};
}
...
adata: token[4],
ct: token[3],
iv: token[2],
ks: 256,
mode: "gcm"
})
);
return local.jwtHs256Decode(token, key);
}, local.nop) || {};
};
local.jwtAes256GcmEncrypt = function (data, key) {
/*
* this function will use json-web-encryption to
* aes-256-gcm-encrypt <data> with given base64url-encoded <key>
...
jwtHs256Encode = function (data, key) {
/*
* this function will encode <data> into a json-web-token
* with given base64-encoded <key>
* https://jwt.io/
*/
var Hmac;
Hmac = local.sjcl.misc.hmac;
data = (
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9."
+ local.normalizeJwtBase64Url(
local.base64FromBuffer(JSON.stringify(data))
)
);
return data + "." + local.sjcl.codec.base64url.fromBits(
new Hmac(local.sjcl.codec.base64url.toBits(
local.jwtAes256KeyInit(key)
)).encrypt(data)
);
}
...
/*
* this function will use json-web-encryption to
* aes-256-gcm-encrypt <data> with given base64url-encoded <key>
* https://tools.ietf.org/html/rfc7516
*/
var adata;
adata = local.jwtAes256KeyCreate();
data = local.jwtHs256Encode(data, key);
data = JSON.parse(local.sjcl.encrypt(
local.sjcl.codec.base64url.toBits(local.jwtAes256KeyInit(key)),
data,
{
adata: local.sjcl.codec.base64url.toBits(adata),
ks: 256,
mode: "gcm"
...
listGetElementRandom = function (list) {
/*
* this function will return random elem from <list>
*/
return list[Math.floor(Math.random() * list.length)];
}
...
return local.jsonCopy(schemaP.default);
}
// init enum-value
if (schemaP.enum) {
value = (
opt.modeNotRandom
? schemaP.enum[0]
: local.listGetElementRandom(schemaP.enum)
);
return (
local.schemaPType(schemaP) === "array"
? [
value
]
: value
...
listShuffle = function (list) {
/*
* this function will inplace shuffle <list> using fisher-yates algorithm
* https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
*/
var ii;
var random;
var swap;
ii = list.length;
while (ii > 1) {
ii -= 1;
random = Math.floor(Math.random() * (ii + 1));
swap = list[ii];
list[ii] = list[random];
list[random] = swap;
}
return list;
}
...
opt = {};
// init list
opt.list = "[0,1]";
// shuffle list 100 times
opt.ii = 0;
while (opt.ii < 100) {
opt.listShuffled = JSON.stringify(
local.listShuffle(JSON.parse(opt.list))
);
// validate shuffled list
local.assertJsonEqual(opt.listShuffled.length, opt.list.length);
opt.changed = opt.changed || opt.listShuffled !== opt.list;
opt.ii += 1;
}
// validate list changed at least once during the shuffle
...
localStorageSetItemOrClear = function (key, value) {
/*
* this function will try to set <key>/<value> pair to localStorage,
* or else call localStorage.clear()
*/
try {
localStorage.setItem(key, value);
} catch (ignore) {
localStorage.clear();
}
}
...
);
local.apiKeyValue = localStorage.getItem(local.apiKeyKey) || "";
// save apiKeyValue
} else {
local.apiKeyValue = document.querySelector(
"#swggApiKeyInput1"
).value;
local.localStorageSetItemOrClear(
local.apiKeyKey,
local.apiKeyValue
);
}
// if keyup-event is not return-key, then return
if (
(opt.type === "keyup" && opt.code !== "Enter")
...
function c (e, n, r){if(r||typeof n=="function"){r||(r=n,n=null),n=l({},c.defaults,n||{});var i= n.highlight,u,a,f=0;try{u=t.lex(e,n)}catch(h){return r(h)}a=u.length;var p=function( e){if(e)return n.highlight=i,r(e);var t;try{t=s.parse(u,n)}catch(o){e=o}return n .highlight=i,e?r(e):r(null,t)};if(!i||i.length<3)return p();delete n.highlight;if(! a)return p();for(;f<u.length;f++)(function(e){return e.type!=="code"?--a||p():i( e.text,e.lang,function(t,n){if(t)return p(t);if(n==null||n===e.text)return--a||p ();e.text=n,e.escaped=!0,--a||p()})})(u[f]);return}try{return n&&(n=l({},c.defaults ,n)),s.parse(t.lex(e,n),n)}catch(h){h.message+="\nPlease report this to https://github.com/chjj/marked." ;if((n||c.defaults).silent)return"<p>An error occured:</p><pre>"+o(h.message+"",!0 )+"</pre>";throw h}}
n/a
middlewareAssetsCached = function (req, res, next) {
/*
* this function will run middleware that will serve cached-assets
*/
var opt;
opt = {};
local.onNext(opt, function (err, data) {
opt.result = opt.result || local.assetsDict[req.urlParsed.pathname];
if (opt.result === undefined) {
next(err);
return;
}
switch (opt.modeNext) {
case 1:
// skip gzip
if (
res.headersSent
|| !(
/\bgzip\b/
).test(req.headers["accept-encoding"])
) {
opt.modeNext += 1;
opt.onNext();
return;
}
// gzip and cache result
local.taskCreateCached({
cacheDict: "middlewareAssetsCachedGzip",
key: req.urlParsed.pathname
}, function (onError) {
local.zlib.gzip(opt.result, function (err, data) {
onError(err, !err && data.toString("base64"));
});
}, opt.onNext);
break;
case 2:
// set gzip header
opt.result = local.base64ToBuffer(data);
res.setHeader("Content-Encoding", "gzip");
res.setHeader("Content-Length", opt.result.length);
opt.onNext();
break;
case 3:
local.middlewareCacheControlLastModified(
req,
res,
opt.onNext
);
break;
case 4:
res.end(opt.result);
break;
}
});
opt.modeNext = 0;
opt.onNext();
}
n/a
middlewareBodyParse = function (req, res, next) {
/*
* this function will run middleware that will parse req.bodyRaw
*/
var boundary;
var crlf;
var data;
var headerParse;
var ii;
var jj;
var name;
// if req is already parsed, then goto next
if (!req.swgg.operation || !local.isNullOrUndefined(req.swgg.bodyParsed)) {
next();
return;
}
headerParse = function () {
local.bufferToUtf8(req.bodyRaw.slice(ii, ii + 1024)).replace((
/^content-disposition:\u0020?form-data;(.+?)\r\n(?:content-type:\u0020?(.*?)$)?/im
), function (ignore, match1, match2) {
data = {
contentType: match2,
name: ""
};
match1.replace((
/(\w+)="([^"]+)/g
), function (ignore, match1, match2) {
data[match1.toLowerCase()] = match2;
});
name = data.name;
req.swgg.bodyMeta[name] = data;
});
};
switch (req.swgg.operation._consumes0) {
// parse application/x-www-form-urlencoded, e.g.
// aa=hello%20world&bb=bye%20world
case "application/x-www-form-urlencoded":
req.swgg.bodyParsed = local.bufferToUtf8(req.bodyRaw);
req.swgg.bodyParsed = local.urlParse(
"?" + req.swgg.bodyParsed,
true
).query;
break;
case "application/xml":
req.swgg.bodyParsed = {};
local.bufferToUtf8(req.bodyRaw).replace((
/<(.+?)><!\[CDATA\[([\S\s]+?)\]\]>/g
), function (name, match1, value) {
name = match1;
name = decodeURIComponent(name);
req.swgg.bodyParsed[name] = (
local.schemaPType(
req.swgg.operation._schemaPDict[name]
) === "string"
? value
: JSON.parse(value)
);
});
break;
/*
* parse multipart/form-data, e.g.
* --Boundary\r\n
* Content-Disposition: form-data; name="key"\r\n
* \r\n
* value\r\n
* --Boundary\r\n
* Content-Disposition: form-data; name="input1"; filename="file1.png"\r\n
* Content-Type: image/jpeg\r\n
* \r\n
* <data1>\r\n
* --Boundary\r\n
* Content-Disposition: form-data; name="input2"; filename="file2.png"\r\n
* Content-Type: image/jpeg\r\n
* \r\n
* <data2>\r\n
* --Boundary--\r\n
* https://tools.ietf.org/html/rfc7578
*/
case "multipart/form-data":
req.swgg.bodyParsed = {};
req.swgg.bodyMeta = {};
crlf = new Uint8Array([
0x0d, 0x0a
]);
// init boundary
ii = 0;
jj = local.bufferIndexOfSubBuffer(req.bodyRaw, crlf, ii);
if (jj <= 0) {
break;
}
boundary = local.bufferConcat([
crlf, req.bodyRaw.slice(ii, jj)
]);
ii = jj + 2;
while (true) {
jj = local.bufferIndexOfSubBuffer(
req.bodyRaw,
boundary,
ii
);
if (jj < 0) {
break;
}
headerParse();
ii = local.bufferIndexOfSubBuffer(
req.bodyRaw,
[
0x0d, 0x0a, 0x0d, 0x0a
],
ii + 2
) + 4;
data = req.bodyRaw.slice(ii, jj);
req.swgg.bodyParsed[name] = data;
ii = jj + boundary.length + 2;
}
break;
default:
req.swgg.bodyParsed = local.bufferToUtf8(req.bodyRaw);
// try to JSON.parse the string
local.tryCatchOnError(function () {
req.swgg.bodyParsed = JSON.parse(req.swgg.bodyParsed);
}, local.nop);
}
next(null, req, res);
}
n/a
middlewareBodyRead = function (req, ignore, next) {
/*
* this function will run middleware that will
* read and save the <req>-body to <req>.bodyRaw
*/
// if req is already read, then goto next
if (!req.readable) {
next();
return;
}
local.streamReadAll(req, function (err, data) {
req.bodyRaw = req.bodyRaw || data;
next(err);
});
}
...
/*
* this function will run the test-middleware
*/
switch (req.urlParsed.pathname) {
// test http POST handling-behavior
case "/test.body":
// test req-body-read handling-behavior
local.middlewareBodyRead(req, res, function () {
// test multiple req-body-read handling-behavior
local.middlewareBodyRead(req, res, function () {
res.write(req.bodyRaw);
res.end();
});
});
break;
...
middlewareCacheControlLastModified = function (req, res, next) {
/*
* this function will run middleware that will update res-header last-modified
*/
// do not cache if headers already sent or url has '?' search indicator
if (res.headersSent || req.url.indexOf("?") >= 0) {
next();
return;
}
// init serverResponseHeaderLastModified
local.serverResponseHeaderLastModified = (
local.serverResponseHeaderLastModified
// resolve to 1000 ms
|| new Date(new Date().toUTCString())
);
// respond with 304 If-Modified-Since serverResponseHeaderLastModified
if (
new Date(req.headers["if-modified-since"])
>= local.serverResponseHeaderLastModified
) {
res.statusCode = 304;
res.end();
return;
}
res.setHeader("Cache-Control", "no-cache");
res.setHeader(
"Last-Modified",
local.serverResponseHeaderLastModified.toUTCString()
);
next();
}
...
// set gzip header
opt.result = local.base64ToBuffer(data);
res.setHeader("Content-Encoding", "gzip");
res.setHeader("Content-Length", opt.result.length);
opt.onNext();
break;
case 3:
local.middlewareCacheControlLastModified(
req,
res,
opt.onNext
);
break;
case 4:
res.end(opt.result);
...
middlewareCrudBuiltin = function (req, res, next) {
/*
* this function will run middleware that will
* run the builtin crud-operations backed by db-lite
*/
var crud;
var onParallel;
var opt;
var tmp;
var user;
opt = {};
local.onNext(opt, function (err, data, meta) {
switch (opt.modeNext) {
case 1:
crud = req.swgg.crud;
user = req.swgg.user;
switch (crud.crudType[0]) {
case "crudCountManyByQuery":
crud.dbTable.crudCountManyByQuery(crud.queryWhere, opt.onNext);
break;
case "crudSetManyById":
crud.dbTable.crudSetManyById(crud.body, opt.onNext);
break;
case "crudSetOneById":
// replace idName with idBackend in body
delete crud.body.id;
delete crud.body[crud.idName];
crud.body[crud.idBackend] = crud.data[crud.idName];
crud.dbTable.crudSetOneById(crud.body, opt.onNext);
break;
case "crudUpdateOneById":
// replace idName with idBackend in body
delete crud.body.id;
delete crud.body[crud.idName];
crud.body[crud.idBackend] = crud.data[crud.idName];
crud.dbTable.crudUpdateOneById(crud.body, opt.onNext);
break;
// coverage-hack - test err handling-behavior
case "crudErrorDelete":
case "crudErrorGet":
case "crudErrorHead":
case "crudErrorOptions":
case "crudErrorPatch":
case "crudErrorPost":
case "crudErrorPut":
opt.onNext(local.errDefault);
break;
case "crudGetManyByQuery":
onParallel = local.onParallel(opt.onNext);
onParallel.counter += 1;
crud.dbTable.crudGetManyByQuery({
fieldList: crud.queryFields,
limit: crud.queryLimit,
query: crud.queryWhere,
skip: crud.querySkip,
sort: crud.querySort
}, function (err, data) {
crud.queryData = data;
onParallel(err);
});
onParallel.counter += 1;
crud.dbTable.crudCountAll(function (err, data) {
crud.paginationCountTotal = data;
onParallel(err);
});
break;
case "crudGetOneById":
crud.dbTable.crudGetOneById(crud.queryById, opt.onNext);
break;
case "crudGetOneByQuery":
crud.dbTable.crudGetOneByQuery({
query: crud.queryWhere
}, opt.onNext);
break;
case "crudNullDelete":
case "crudNullGet":
case "crudNullHead":
case "crudNullOptions":
case "crudNullPatch":
case "crudNullPost":
case "crudNullPut":
opt.onNext();
break;
case "crudRemoveManyByQuery":
crud.dbTable.crudRemoveManyByQuery(crud.queryWhere, opt.onNext);
break;
case "crudRemoveOneById":
crud.dbTable.crudRemoveOneById(crud.queryById, opt.onNext);
break;
case "fileGetOneById":
local.dbTableFile = local.db.dbTableCreateOne({
name: "File"
});
crud.dbTable.crudGetOneById(crud.queryById, opt.onNext);
break;
case "fileUploadManyByForm":
local.dbTableFile = local.db.dbTable...
n/a
middlewareCrudEnd = function (req, res, next) {
/*
* this function will run middleware that will end the builtin crud-operations
*/
if (req.swgg.crud.endArgList) {
local.serverRespondJsonapi.apply(null, req.swgg.crud.endArgList);
return;
}
next(null, req, res);
}
n/a
middlewareError = function (err, req, res) {
/*
* this function will run middleware that will handle errors
*/
// default - 404 Not Found
if (!err) {
local.serverRespondDefault(req, res, 404);
return;
}
// http://jsonapi.org/format/#errors
if (local.swgg && typeof local.swgg.serverRespondJsonapi === "function") {
local.swgg.serverRespondJsonapi(req, res, err);
}
// statusCode [400, 600)
local.serverRespondDefault(req, res, (
(err.statusCode >= 400 && err.statusCode < 600)
? err.statusCode
: 500
), err);
}
...
local.middlewareFileServer
];
local.serverLocalReqHandler = function (req, res) {
var that;
that = {};
local.onNext(that, function (err) {
if (err || that.modeNext >= local.middlewareList.length) {
local.middlewareError(err, req, res);
return;
}
// recurse with next middleware in middlewareList
local.middlewareList[that.modeNext](req, res, that.onNext);
});
that.modeNext = -1;
that.onNext();
...
middlewareFileServer = function (req, res, next) {
/*
* this function will run middleware that will serve files
*/
if (req.method !== "GET" || local.isBrowser) {
next();
return;
}
req.urlFile = (process.cwd() + req.urlParsed.pathname
// security - disable parent directory lookup
.replace((
/.*\/\.\.\//g
), "/"))
// replace trailing '/' with '/index.html'
.replace((
/\/$/
), "/index.html");
// serve file from cache
local.taskCreateCached({
cacheDict: "middlewareFileServer",
key: req.urlFile
// run background-task to re-cache file
}, function (onError) {
local.fs.readFile(req.urlFile, function (err, data) {
onError(err, data && local.base64FromBuffer(data));
});
}, function (err, data) {
// default to next
if (err) {
next();
return;
}
// init res-header content-type
local.serverRespondHeadSet(req, res, null, {
"Content-Type": local.contentTypeDict[(
/\.[^.]*?$|$/m
).exec(req.urlParsed.pathname)[0]]
});
// serve file from cache
res.end(local.base64ToBuffer(data));
});
}
...
case "/test.timeout":
setTimeout(function () {
res.end();
}, 2000);
break;
// serve file
default:
local.middlewareFileServer(req, res, next);
}
});
}());
// run node js-env code - init-after
...
middlewareForwardProxy = function (req, res, next) {
/*
* this function will run middleware that will forward-proxy <req>
* to its destination-host
*/
var isDone;
var onError;
var opt;
var timerTimeout;
// handle preflight-cors
if (req.method === "OPTIONS" && (
/forward-proxy-url/
)
.test(req.headers["access-control-request-headers"])) {
local.serverRespondCors(req, res);
res.end();
return;
}
if (!req.headers["forward-proxy-url"]) {
next();
return;
}
local.serverRespondCors(req, res);
// init onError
onError = function (err) {
if (isDone) {
return;
}
isDone = true;
// cleanup timerTimeout
clearTimeout(timerTimeout);
// debug middlewareForwardProxy
console.error("serverLog - " + JSON.stringify({
time: new Date(opt.timeStart).toISOString(),
type: "middlewareForwardProxyResponse",
method: opt.method,
url: opt.url,
statusCode: res.statusCode | 0,
timeElapsed: Date.now() - opt.timeStart,
// extra
headers: opt.headers
}));
if (!err) {
return;
}
// cleanup clientReq and clientRes
local.streamCleanup(opt.clientReq);
local.streamCleanup(opt.clientResponse);
next(err);
};
// init opt
opt = local.urlParse(req.headers["forward-proxy-url"]);
opt.method = req.method;
opt.url = req.headers["forward-proxy-url"];
// init timerTimeout
timerTimeout = local.onTimeout(
onError,
local.timeoutDefault,
"forward-proxy " + opt.method + " " + opt.url
);
// parse headers
opt.headers = {};
local.tryCatchOnError(function () {
opt.headers = JSON.parse(req.headers["forward-proxy-headers"]);
}, local.nop);
// debug opt
local._debugForwardProxy = opt;
opt.clientReq = (
opt.protocol === "https:"
? local.https
: local.http
).request(opt, function (clientResponse) {
opt.clientResponse = clientResponse.on("error", onError);
res.statusCode = opt.clientResponse.statusCode;
// pipe clientResponse to serverResponse
opt.clientResponse.pipe(res);
}).on("error", onError);
opt.timeStart = Date.now();
// init event-handling
req.on("error", onError);
res.on("finish", onError).on("error", onError);
// pipe serverReq to clientReq
req.pipe(opt.clientReq);
}
n/a
middlewareInit = function (req, res, next) {
/*
* this function will run middleware that will init <req> and <res>
*/
// debug req and res
local._debugServerReqRes4 = local._debugServerReqRes3;
local._debugServerReqRes3 = local._debugServerReqRes2;
local._debugServerReqRes2 = local._debugServerReqRes1;
local._debugServerReqRes1 = {
req,
res
};
// init timerTimeout
local.serverRespondTimeoutDefault(req, res, local.timeoutDefault);
// init req.urlParsed
req.urlParsed = local.urlParse(req.url);
// init res-header content-type
local.serverRespondHeadSet(req, res, null, {
"Content-Type": local.contentTypeDict[(
/\.[^.]*?$|$/m
).exec(req.urlParsed.pathname)[0]]
});
// set main-page content-type to text/html
if (req.urlParsed.pathname === "/") {
local.serverRespondHeadSet(req, res, null, {
"Content-Type": "text/html; charset=utf-8"
});
}
// default to next
next();
}
n/a
middlewareJsonpStateInit = function (req, res, next) {
/*
* this function will run middleware that will
* serve the browser-state wrapped in given jsonp-callback
*/
var state;
if (!(req.stateInit || (
req.urlParsed
&& req.urlParsed.pathname === "/jsonp.utility2.stateInit"
))) {
next();
return;
}
state = {
utility2: {
assetsDict: {
"/assets.example.html":
local.assetsDict["/assets.example.html"],
"/assets.example.js": local.assetsDict["/assets.example.js"],
"/assets.swgg.swagger.json":
local.assetsDict["/assets.swgg.swagger.json"],
"/assets.test.js": local.assetsDict["/assets.test.js"],
"/assets.utility2.base.html":
local.assetsDict["/assets.utility2.base.rollup.html"],
"/index.rollup.html": local.assetsDict["/index.rollup.html"]
},
env: {
NODE_ENV: local.env.NODE_ENV,
npm_config_mode_backend: local.env.npm_config_mode_backend,
npm_package_assetsList: local.env.npm_package_assetsList,
npm_package_description: local.env.npm_package_description,
npm_package_homepage: local.env.npm_package_homepage,
npm_package_name: local.env.npm_package_name,
npm_package_nameLib: local.env.npm_package_nameLib,
npm_package_version: local.env.npm_package_version
}
}
};
(local.env.npm_package_assetsList || "").split(" ").forEach(function (
file
) {
local.assetsDict["/" + file] = (
local.assetsDict["/" + file]
|| local.fsReadFileOrEmptyStringSync(file, "utf8")
);
state.utility2.assetsDict["/" + file] = local.assetsDict["/" + file];
});
if (req.stateInit) {
return state;
}
res.end(
req.urlParsed.query.callback + "(" + JSON.stringify(state) + ");"
);
}
...
code += "\n";
code += local.assetsDict[tmp];
break;
case "local.stateInit":
// handle large string-replace
code = local.assetsDict["/assets.utility2.rollup.content.js"]
.split("/* utility2.rollup.js content */");
tmp = local.middlewareJsonpStateInit({
stateInit: true
});
// add extra physical files to assetsDict
local.fs.readdirSync(".").forEach(function (file) {
file = "/" + file;
if (
local.assetsDict[file]
...
middlewareRouter = function (req, res, next) {
/*
* this function will run middleware that will
* map the req's method-path to swagger's tags[0]-crudType
*/
var tmp;
// init swgg object
local.objectSetDefault(req, {
swgg: {
crud: {
crudType: []
},
user: {}
}
}, 3);
// if req.url is not prefixed with swaggerJsonBasePath,
// then default to next
if (req.urlParsed.pathname.indexOf(local.swaggerJsonBasePath) !== 0) {
next();
return;
}
// init methodPath
req.swgg.methodPath = (
req.method + " "
+ req.urlParsed.pathname.replace(local.swaggerJsonBasePath, "")
);
// init operation
while (req.swgg.methodPath !== tmp) {
req.swgg.operation = (
local.apiDict[req.swgg.methodPath]
// handle /foo/{id}/bar case
|| local.apiDict[req.swgg.methodPath.replace((
/\/[^\/]+\/([^\/]*?)$/
), "/{}/$1")]
);
// if operation exists, then break
if (req.swgg.operation) {
req.swgg.operation = local.jsonCopy(req.swgg.operation);
// init crud.crudType
req.swgg.crud.crudType = req.swgg.operation._crudType;
break;
}
tmp = req.swgg.methodPath;
// handle /foo/{id} case
req.swgg.methodPath = req.swgg.methodPath.replace((
/\/[^\/]+?(\/*?)$/
), "/$1{}");
}
next(null, req, res);
}
n/a
middlewareUserLogin = function (req, res, next) {
/*
* this function will run middleware that will handle user login
*/
var crud;
var opt;
var user;
opt = {};
local.onNext(opt, function (err, data) {
switch (opt.modeNext) {
case 1:
local.dbTableUser = local.db.dbTableCreateOne({
name: "User"
});
crud = req.swgg.crud;
user = {};
req.swgg.user = user;
user.jwtEncrypted = (
req.headers.authorization
&& req.headers.authorization.replace("Bearer ", "")
);
user.jwtDecrypted = local.jwtAes256GcmDecrypt(user.jwtEncrypted);
switch (crud.crudType[0]) {
// coverage-hack - test err handling-behavior
case "crudErrorLogin":
opt.onNext(local.errDefault);
return;
case "userLoginByPassword":
user.password = req.urlParsed.query.password;
user.username = req.urlParsed.query.username;
if (user.password && user.username) {
local.dbTableUser.crudGetOneById({
username: user.username
}, opt.onNext);
return;
}
break;
default:
if (user.jwtDecrypted.sub) {
// init username
user.username = user.jwtDecrypted.sub;
local.dbTableUser.crudGetOneById({
username: user.username
}, opt.onNext);
return;
}
}
opt.modeNext = Infinity;
opt.onNext();
break;
case 2:
switch (crud.crudType[0]) {
case "userLoginByPassword":
user.data = data;
if (!local.sjclHashScryptValidate(
user.password,
user.data && user.data.password
)) {
opt.modeNext = Infinity;
opt.onNext();
return;
}
// init isAuthenticated
user.isAuthenticated = true;
// create JSON Web Token (JWT)
// https://tools.ietf.org/html/rfc7519
user.jwtDecrypted = {};
user.jwtDecrypted.sub = user.data.username;
// update jwtEncrypted in client
user.jwtEncrypted = local.jwtAes256GcmEncrypt(
user.jwtDecrypted
);
local.serverRespondHeadSet(req, res, null, {
"swgg-jwt-encrypted": user.jwtEncrypted
});
// update jwtEncrypted in dbTableUser
local.dbTableUser.crudUpdateOneById({
jwtEncrypted: user.jwtEncrypted,
username: user.jwtDecrypted.sub
}, opt.onNext);
return;
default:
data = data || {};
user.data = data;
if (data.jwtEncrypted) {
// init isAuthenticated
user.isAuthenticated = true;
// update jwtEncrypted in client
if (data.jwtEncrypted !== user.jwtEncrypted) {
user.jwtEncrypted = data.jwtEncrypted;
user.jwtDecrypted = local.jwtAes256GcmDecrypt(
user.jwtEncrypted
);
local.serverRespondHeadSet(req, res, null, {
"swgg-jwt-encrypted": user.jwtEncrypted
});
}
}
}
opt.onNext();
break;
default:
next(err);
}
});
opt.modeNext =...
n/a
middlewareValidate = function (req, res, next) {
/*
* this function will run middleware that will validate the swagger-<req>
*/
var crud;
var opt;
var tmp;
opt = {};
local.onNext(opt, function (err) {
switch (opt.modeNext) {
case 1:
if (!req.swgg.operation) {
opt.modeNext = Infinity;
opt.onNext();
return;
}
// init paramDict
req.swgg.paramDict = {};
// parse path param
tmp = req.urlParsed.pathname
.replace(local.swaggerJsonBasePath, "")
.split("/");
req.swgg.operation._path.split("/").forEach(function (key, ii) {
if ((
/^\{\S*?\}$/
).test(key)) {
req.swgg.paramDict[key.slice(1, -1)] = (
decodeURIComponent(tmp[ii])
);
}
});
req.swgg.operation.parameters.forEach(function (schemaP) {
switch (schemaP.in) {
// parse body param
case "body":
req.swgg.paramDict[schemaP.name] = (
req.swgg.bodyParsed
|| undefined
);
break;
// parse formData param
case "formData":
switch (req.swgg.operation._consumes0) {
case "application/x-www-form-urlencoded":
case "application/xml":
req.swgg.paramDict[schemaP.name] = (
req.swgg.bodyParsed[schemaP.name]
);
break;
}
break;
// parse header param
case "header":
req.swgg.paramDict[schemaP.name] = (
req.headers[schemaP.name.toLowerCase()]
);
break;
// parse query param
case "query":
req.swgg.paramDict[schemaP.name] = (
req.urlParsed.query[schemaP.name]
);
break;
}
// parse array-multi
tmp = req.swgg.paramDict[schemaP.name];
if (
tmp
&& local.schemaPType(schemaP) === "array"
&& schemaP.collectionFormat === "multi"
) {
req.swgg.paramDict[schemaP.name] = (
encodeURIComponent(schemaP.name)
+ "=" + (
Array.isArray(tmp)
? tmp
: [
tmp
]
).join("&" + encodeURIComponent(schemaP.name) + "=")
);
}
// init default
if (
local.isNullOrUndefined(req.swgg.paramDict[schemaP.name])
&& schemaP.default !== undefined
) {
req.swgg.paramDict[schemaP.name] = local.jsonCopy(
schemaP.default
);
}
});
// normalize paramDict
local.normalizeSwaggerParamDict(req.swgg);
// validate paramDict
err = local.swaggerValidateDataParameters({
data: req.swgg.paramDict,
prefix: [
"operation", req.swgg.methodPath
],
parameters: req.swgg.operation.parameters,
swaggerJson: local.swaggerJson
})[0];
opt.onNext(err);...
n/a
moduleDirname = function (module, modulePathList) {
/*
* this function will search modulePathList for the module's __dirname
*/
var result;
// search process.cwd()
if (!module || module === "." || module.indexOf("/") >= 0) {
return require("path").resolve(process.cwd(), module || "");
}
// search modulePathList
[
"node_modules"
]
.concat(modulePathList)
.concat(require("module").globalPaths)
.concat([
process.env.HOME + "/node_modules", "/usr/local/lib/node_modules"
])
.some(function (modulePath) {
try {
result = require("path").resolve(
process.cwd(),
modulePath + "/" + module
);
result = require("fs").statSync(result).isDirectory() && result;
return result;
} catch (ignore) {
result = null;
}
return result;
});
return result || "";
}
...
return match0.replace((
/(.{128}(?:\b|\w+))/g
), "$1\n").trimRight();
});
return text;
};
// init opt
opt.dir = local.moduleDirname(
opt.dir,
opt.modulePathList || require("module").paths
);
local.objectSetDefault(opt, {
env: {
npm_package_description: ""
},
...
nop = function () {
/*
* this function will do nothing
*/
return;
}
...
process.stdout._writeDefault = (
process.stdout._writeDefault
|| process.stdout._write
);
process.stdout._write = function (chunk, encoding, callback) {
process.stdout._writeDefault(chunk, encoding, callback);
// coverage-hack - ignore else-statement
local.nop(that.socket.writable && (function () {
that.socket.write(chunk, encoding);
}()));
};
// start serverRepl1
globalThis.utility2_serverRepl1 = require("net").createServer(function (
socket
) {
...
normalizeChunk = function (chunk) {
/*
* this function will normalize the chunk
*/
return chunk || "";
}
...
req.onTimeout,
timeout || local.timeoutDefault,
"server " + req.method + " " + req.url
);
res.contentLength = 0;
res.writeContentLength = res.writeContentLength || res.write;
res.write = function (chunk, encoding, callback) {
chunk = local.normalizeChunk(chunk);
res.contentLength += chunk.length;
res.writeContentLength(chunk, encoding, callback);
};
res.on("error", onError);
res.on("finish", onError);
};
...
normalizeJwt = function (data) {
/*
* this function will normalize the jwt-data with registered-headers
* https://tools.ietf.org/html/rfc7519#section-4.1
*/
var timeNow;
timeNow = Date.now() / 1000;
return local.objectSetDefault(data, {
exp: timeNow + 5 * 60,
iat: timeNow,
jti: Math.random().toString(16).slice(2),
nbf: timeNow
});
}
...
local.testCase_jwtAes256GcmXxx_default = function (opt, onError) {
/*
* this function will test jwtAes256GcmXxx's default handling-behavior
*/
opt = {};
opt.key = local.jwtAes256KeyCreate();
// use canonical example at https://jwt.io/
opt.data = JSON.parse(local.jsonStringifyOrdered(local.normalizeJwt({
sub: "1234567890",
name: "John Doe",
admin: true
})));
// encrypt token
opt.token = local.jwtAes256GcmEncrypt(opt.data, opt.key);
// validate encrypted-token
...
normalizeJwtBase64Url = function (b64) {
/*
* this function will normlize <b64> to base64url format
*/
return b64
.replace((
/\=/g
), "")
.replace((
/\+/g
), "-")
.replace((
/\//g
), "_");
}
...
data,
{
adata: local.sjcl.codec.base64url.toBits(adata),
ks: 256,
mode: "gcm"
}
));
return local.normalizeJwtBase64Url(
"eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4R0NNIn0.."
+ data.iv + "." + data.ct + "." + adata
);
};
local.jwtAes256KeyCreate = function () {
/*
...
normalizeSwaggerJson = function (swaggerJson, opt) {
/*
* this function will normalize swaggerJson and filter $npm_package_swggTags0
*/
var pathDict;
var tmp;
opt = local.objectSetDefault(opt, {
objectSetDescription: function (dict) {
if (
dict
&& dict.description
&& Array.isArray(dict["x-swgg-descriptionLineList"])
) {
delete dict.description;
}
}
});
local.objectSetDefault(swaggerJson, {
paths: {},
tags: []
});
// fix err - semanticPaths2
pathDict = {};
Object.keys(swaggerJson.paths).forEach(function (path) {
tmp = path.replace((
/\{.*?\}/g
), "{}");
pathDict[tmp] = pathDict[tmp] || {};
pathDict[tmp][path] = true;
});
Object.keys(pathDict).forEach(function (key) {
Object.keys(pathDict[key]).sort().forEach(function (path, ii) {
// fix err.semanticUniquePath
if (ii && swaggerJson["x-swgg-fixErrorSemanticUniquePath"]) {
swaggerJson.paths[path + "#" + ii] = swaggerJson.paths[path];
delete swaggerJson.paths[path];
}
});
});
Object.keys(swaggerJson.paths).forEach(function (path) {
Object.keys(swaggerJson.paths[path]).forEach(function (method) {
tmp = swaggerJson.paths[path][method];
// auto-create operationId from path
if (
swaggerJson["x-swgg-operationIdFromPath"]
|| tmp["x-swgg-operationIdFromPath"]
|| !tmp.operationId
) {
tmp.operationId = local.operationIdFromAjax({
method,
url: path
});
}
// normalize parameter.required
(tmp.parameters || []).forEach(function (schemaP) {
if (schemaP.required === false) {
delete schemaP.required;
}
});
});
});
// override tag.description with x-swgg-tags0-override
if (swaggerJson["x-swgg-tags0-override"]) {
swaggerJson.tags.forEach(function (tag) {
tmp = local.objectSetDefault(
swaggerJson["x-swgg-tags0-override"][tag.name],
{
description: tag.description,
"x-swgg-descriptionLineList": (
tag["x-swgg-descriptionLineList"]
)
}
);
tag.description = tmp.description;
tag["x-swgg-descriptionLineList"] = (
tmp["x-swgg-descriptionLineList"]
);
// objectSetDescription
opt.objectSetDescription(tmp);
opt.objectSetDescription(tag);
});
}
// apply opt.objectSetDescription
([
swaggerJson.externalDocs, swaggerJson.info
]).forEach(opt.objectSetDescription);
([
swaggerJson.definitions, swaggerJson.parameters, swaggerJson.responses
]).forEach(function (dict) {
Object.keys(dict || {}).forEach(function (key) {
tmp = dict[key];
if (dict === swaggerJson.definitions) {
tmp = tmp.properties || {};
Object.keys(tmp).forEach(function (key) {
opt.objectSetDescription(tmp[key]);
});
return;
}
opt.objectSetDescription(tmp);
});
});
Object.keys(swaggerJson.paths).forEach(function (path) {
Object.keys(swaggerJson.paths[path]).forEach(function (method) {
tmp = swaggerJson.paths[path][method];
opt.objectSetDescription(tmp);
(tmp.parameters || []).forEach(opt.objectSetDescription);
Object.keys(tmp.responses || {}).forEach(function (key...
...
/*
* this function will update the swagger-api dict of api-calls
*/
var pathDict;
var tmp;
swaggerJson = swaggerJson || {};
// normalize swaggerJson
swaggerJson = local.normalizeSwaggerJson(swaggerJson, {
objectSetDescription: function (dict) {
if (typeof dict === "object" && dict && !dict.$ref) {
if (Array.isArray(dict["x-swgg-descriptionLineList"])) {
dict.description = (
dict["x-swgg-descriptionLineList"].join("\n")
);
}
...
normalizeSwaggerParamDict = function (opt) {
/*
* this function will parse the <opt> according to <opt>.operation.parameters
*/
var tmp;
opt.operation.parameters.forEach(function (schemaP) {
tmp = opt.paramDict[schemaP.name];
// init default
if (
!opt.modeNoDefault
&& (opt.modeDefault || schemaP.required)
&& local.isNullOrUndefined(tmp)
) {
tmp = local.jsonCopy(schemaP.default);
}
if (opt.modeDefault && local.isNullOrUndefined(tmp)) {
tmp = local.dbFieldRandomCreate({
modeNotRandom: true,
schemaP
});
}
// parse array
if (local.schemaPType(schemaP) === "array" && schemaP.in !== "body") {
if (typeof tmp === "string") {
switch (
schemaP.collectionFormat
|| schemaP["x-swgg-collectionFormat"]
) {
case "json":
local.tryCatchOnError(function () {
tmp = JSON.parse(tmp);
}, local.nop);
opt.paramDict[schemaP.name] = tmp;
return;
case "multi":
tmp = local.urlParse("?" + tmp, true).query[schemaP.name];
if (!Array.isArray(tmp)) {
tmp = [
tmp
];
}
break;
case "pipes":
tmp = tmp.split("|");
break;
case "ssv":
tmp = tmp.split(" ");
break;
case "tsv":
tmp = tmp.split("\t");
break;
// default to csv
default:
tmp = tmp.split(",");
}
if (local.schemaPItemsType(schemaP) !== "string") {
// try to JSON.parse the string
local.tryCatchOnError(function () {
tmp = tmp.map(function (element) {
return JSON.parse(element);
});
}, local.nop);
}
}
// JSON.parse paramDict
} else if (
local.schemaPType(schemaP) !== "file"
&& local.schemaPType(schemaP) !== "string"
&& (
typeof tmp === "string"
|| Object.prototype.toString.call(tmp) === "[object Uint8Array]"
)
) {
// try to JSON.parse the string
local.tryCatchOnError(function () {
tmp = JSON.parse(local.bufferToUtf8(tmp));
}, local.nop);
}
opt.paramDict[schemaP.name] = tmp;
});
return opt;
}
...
local.objectSetDefault(opt, {
data: "",
operation: that,
paramDict: {},
url: ""
});
if (opt.modeDefault) {
local.normalizeSwaggerParamDict(opt);
}
// try to validate paramDict
opt.err = local.swaggerValidateDataParameters({
// normalize paramDict
data: local.normalizeSwaggerParamDict({
modeNoDefault: opt.modeNoDefault,
operation: that,
...
numberToRomanNumerals = function (num) {
/*
* this function will convert num to a roman-numeral
* https://stackoverflow.com/questions/9083037/convert-a-number-into-a-roman-numeral-in-javascript
*/
var digits;
var ii;
var key;
var roman;
digits = String(num).split("");
key = [
"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM",
"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC",
"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"
];
roman = "";
ii = 3;
while (ii) {
ii -= 1;
roman = (key[Number(digits.pop()) + (ii * 10)] || "") + roman;
}
return new Array(Number(digits.join("") + 1)).join("M") + roman;
}
...
"XCVIII",
"XCIX",
"C"
];
opt.ii = 0;
while (opt.ii < 10) {
local.assertJsonEqual(
local.numberToRomanNumerals(opt.ii),
opt.list[opt.ii]
);
opt.ii += 1;
}
onError(null, opt);
};
...
objectAssignDefault = function (target, source) {
/*
* this function will if items from <target> are
* null, undefined, or empty-string,
* then overwrite them with items from <source>
*/
target = target || {};
Object.keys(source || {}).forEach(function (key) {
if (
target[key] === null
|| target[key] === undefined
|| target[key] === ""
) {
target[key] = target[key] || source[key];
}
});
return target;
}
...
if (key[0] !== "_") {
xhr[key] = opt[key];
}
});
// init timeout
timeout = xhr.timeout || local2.timeoutDefault || 30000;
// init default
local.objectAssignDefault(xhr, {
corsForwardProxyHost: local2.corsForwardProxyHost,
headers: {},
location: (local.isBrowser && location) || {},
method: "GET",
responseType: ""
});
// init headers
...
objectSetDefault = function (dict, defaults, depth) {
/*
* this function will recursively set defaults for undefined-items in dict
*/
dict = dict || {};
defaults = defaults || {};
Object.keys(defaults).forEach(function (key) {
var defaults2;
var dict2;
dict2 = dict[key];
// handle misbehaving getter
try {
defaults2 = defaults[key];
} catch (ignore) {}
if (defaults2 === undefined) {
return;
}
// init dict[key] to default value defaults[key]
switch (dict2) {
case "":
case null:
case undefined:
dict[key] = defaults2;
return;
}
// if dict2 and defaults2 are both non-null and non-array objects,
// then recurse with dict2 and defaults2
if (
depth > 1
// dict2 is a non-null and non-array object
&& typeof dict2 === "object" && dict2 && !Array.isArray(dict2)
// defaults2 is a non-null and non-array object
&& typeof defaults2 === "object" && defaults2
&& !Array.isArray(defaults2)
) {
// recurse
local.objectSetDefault(dict2, defaults2, depth - 1);
}
});
return dict;
}
...
// dict2 is a non-null and non-array object
&& typeof dict2 === "object" && dict2 && !Array.isArray(dict2)
// defaults2 is a non-null and non-array object
&& typeof defaults2 === "object" && defaults2
&& !Array.isArray(defaults2)
) {
// recurse
local.objectSetDefault(dict2, defaults2, depth - 1);
}
});
return dict;
};
local.stringHtmlSafe = function (text) {
/*
...
objectSetOverride = function (dict, overrides, depth, env) {
/*
* this function will recursively set overrides for items in dict
*/
dict = dict || {};
env = env || (typeof process === "object" && process.env) || {};
overrides = overrides || {};
Object.keys(overrides).forEach(function (key) {
var dict2;
var overrides2;
dict2 = dict[key];
overrides2 = overrides[key];
if (overrides2 === undefined) {
return;
}
// if both dict2 and overrides2 are non-null and non-array objects,
// then recurse with dict2 and overrides2
if (
depth > 1
// dict2 is a non-null and non-array object
&& typeof dict2 === "object" && dict2 && !Array.isArray(dict2)
// overrides2 is a non-null and non-array object
&& typeof overrides2 === "object" && overrides2
&& !Array.isArray(overrides2)
) {
local.objectSetOverride(dict2, overrides2, depth - 1, env);
return;
}
// else set dict[key] with overrides[key]
dict[key] = (
dict === env
// if dict is env, then overrides falsy-value with empty-string
? overrides2 || ""
: overrides2
);
});
return dict;
}
...
depth > 1
// dict2 is a non-null and non-array object
&& typeof dict2 === "object" && dict2 && !Array.isArray(dict2)
// overrides2 is a non-null and non-array object
&& typeof overrides2 === "object" && overrides2
&& !Array.isArray(overrides2)
) {
local.objectSetOverride(dict2, overrides2, depth - 1, env);
return;
}
// else set dict[key] with overrides[key]
dict[key] = (
dict === env
// if dict is env, then overrides falsy-value with empty-string
? overrides2 || ""
...
onErrorDefault = function (err) {
/*
* this function will if <err> exists, then print it to stderr
*/
if (err) {
console.error(err);
}
return err;
}
...
dbTable = local.dbTableCreateOne({
isLoaded: true,
name: match1
});
dbTable.sortDefault = JSON.parse(match3);
break;
default:
local.onErrorDefault(new Error(
"db - dbImport - invalid operation - " + match0
));
}
});
Object.keys(dbTableDict).forEach(function (name) {
console.error("db - importing dbTable " + name + " ...");
});
...
onErrorJsonapi = function (onError) {
/*
* this function will normalize err and data to jsonapi format,
* and pass them to onError
* http://jsonapi.org/format/#errors
* http://jsonapi.org/format/#document-structure-resource-objects
*/
return function (err, data, meta) {
data = [
err, data
].map(function (data, ii) {
// if no err occurred, then return
if (
(ii === 0 && !data)
// if data is already normalized, then return it
|| (data && data.meta && data.meta.isJsonapiResponse)
) {
return data;
}
// normalize data-list
if (!Array.isArray(data)) {
data = [
data
];
}
// normalize errList to contain non-null objects
if (!ii) {
data = data.errList || data;
// normalize errList to be non-empty
if (!data.length) {
data.push(null);
}
data = data.map(function (element) {
if (!(typeof element === "object" && element)) {
element = {
message: String(element)
};
}
// normalize errObj to plain json-object
return {
message: element.message,
name: element.name,
stack: element.stack,
statusCode: Number(element.statusCode) || 500
};
});
err = local.jsonCopy(data[0]);
err.errors = data;
return err;
}
return {
data
};
});
// init data.meta
data.forEach(function (data, ii) {
if (!data) {
return;
}
data.meta = local.jsonCopy(meta || {});
data.meta.isJsonapiResponse = true;
if (ii) {
data.meta.dataLength = data.data.length;
} else {
data.meta.errorsLength = data.errors.length;
}
data.meta.statusCode = (
Number(data.meta.statusCode)
|| Number(data.statusCode)
|| 0
);
});
onError(data[0], data[1]);
};
}
...
local.serverRespondJsonapi = function (req, res, err, data, meta) {
/*
* this function will respond in jsonapi format
* http://jsonapi.org/format/#errors
* http://jsonapi.org/format/#document-structure-resource-objects
*/
local.onErrorJsonapi(function (err, data) {
local.serverRespondHeadSet(req, res, err && err.statusCode, {
"Content-Type": "application/json"
});
if (err) {
// debug statusCode / method / url
local.errorMessagePrepend(
err,
...
onErrorThrow = function (err) {
/*
* this function will if <err> exists, then throw it
*/
if (err) {
throw err;
}
return err;
}
...
};
local.testCase_onErrorThrow_err = function (opt, onError) {
/*
* this function will test onErrorThrow's err handling-behavior
*/
local.tryCatchOnError(function () {
local.onErrorThrow(local.errDefault);
}, function (err) {
// validate err occurred
local.assertThrow(err, err);
onError(null, opt);
});
};
...
onErrorWithStack = function (onError) {
/*
* this function will create wrapper around <onError>
* that will append current-stack to err.stack
*/
var onError2;
var stack;
stack = new Error().stack.replace((
/(.*?)\n.*?$/m
), "$1");
onError2 = function (err, data, meta) {
if (
err
&& typeof err.stack === "string"
&& err !== local.errDefault
&& String(err.stack).indexOf(stack.split("\n")[2]) < 0
) {
// append current-stack to err.stack
err.stack += "\n" + stack;
}
onError(err, data, meta);
};
// debug onError
onError2.toString = function () {
return String(onError);
};
return onError2;
}
...
local.onParallel = function (onError, onEach, onRetry) {
/*
* this function will create a function that will
* 1. run async tasks in parallel
* 2. if counter === 0 or err occurred, then call onError(err)
*/
var onParallel;
onError = local.onErrorWithStack(onError);
onEach = onEach || local.nop;
onRetry = onRetry || local.nop;
onParallel = function (err, data) {
if (onRetry(err, data)) {
return;
}
// decrement counter
...
onFileModifiedRestart = function (file) {
/*
* this function will watch the file, and if modified, then restart the process
*/
if (
local.env.npm_config_mode_auto_restart
&& local.fs.existsSync(file)
&& local.fs.statSync(file).isFile()
) {
local.fs.watchFile(file, {
interval: 1000,
persistent: false
}, function (stat2, stat1) {
if (stat2.mtime > stat1.mtime) {
console.error("file modified - " + file);
setTimeout(function () {
local.exit(77);
}, 1000);
}
});
}
}
...
[
__dirname + "/lib.jslint.js",
__filename,
"undefined"
].forEach(function (file) {
local.fs.exists(file, function (exists) {
if (exists) {
local.onFileModifiedRestart(file);
}
});
});
local.fs.readdirSync(process.cwd()).forEach(function (file) {
file = process.cwd() + "/" + file;
// if the file is modified, then restart the process
local.onFileModifiedRestart(file);
...
onNext = function (opt, onError) {
/*
* this function will wrap onError inside recursive-function <opt>.onNext,
* and append the current-stack to any err
*/
opt.onNext = local.onErrorWithStack(function (err, data, meta) {
try {
opt.modeNext += (
(err && !opt.modeErrorIgnore)
? 1000
: 1
);
if (opt.modeDebug) {
console.error("onNext - " + JSON.stringify({
modeNext: opt.modeNext,
errorMessage: err && err.message
}));
if (err && err.stack) {
console.error(err.stack);
}
}
onError(err, data, meta);
} catch (errCaught) {
// throw errCaught to break infinite recursion-loop
if (opt.errCaught) {
local.assertThrow(null, opt.errCaught);
}
opt.errCaught = errCaught;
opt.onNext(errCaught, data, meta);
}
});
return opt;
}
...
onError(err, data, meta);
} catch (errCaught) {
// throw errCaught to break infinite recursion-loop
if (opt.errCaught) {
local.assertThrow(null, opt.errCaught);
}
opt.errCaught = errCaught;
opt.onNext(errCaught, data, meta);
}
});
return opt;
};
local.onParallel = function (onError, onEach, onRetry) {
/*
...
onParallel = function (onError, onEach, onRetry) {
/*
* this function will create a function that will
* 1. run async tasks in parallel
* 2. if counter === 0 or err occurred, then call onError(err)
*/
var onParallel;
onError = local.onErrorWithStack(onError);
onEach = onEach || local.nop;
onRetry = onRetry || local.nop;
onParallel = function (err, data) {
if (onRetry(err, data)) {
return;
}
// decrement counter
onParallel.counter -= 1;
// validate counter
if (!(onParallel.counter >= 0 || err || onParallel.err)) {
err = new Error(
"invalid onParallel.counter = " + onParallel.counter
);
// ensure onError is run only once
} else if (onParallel.counter < 0) {
return;
}
// handle err
if (err) {
onParallel.err = err;
// ensure counter <= 0
onParallel.counter = -Math.abs(onParallel.counter);
}
// call onError when isDone
if (onParallel.counter <= 0) {
onError(err, data);
return;
}
onEach();
};
// init counter
onParallel.counter = 0;
// return callback
return onParallel;
}
...
};
local.dbCrudRemoveAll = function (onError) {
/*
* this function will remove all dbRow's from the db
*/
var onParallel;
onParallel = local.onParallel(function (err) {
local.setTimeoutOnError(onError, 0, err);
});
onParallel.counter += 1;
Object.keys(local.dbTableDict).forEach(function (key) {
onParallel.counter += 1;
local.dbTableDict[key].crudRemoveAll(onParallel);
});
...
onParallelList = function (opt, onEach, onError) {
/*
* this function will
* 1. async-run onEach in parallel,
* with given <opt>.rateLimit and <opt>.retryLimit
* 2. call <onError> when onParallel.ii + 1 === <opt>.list.length
*/
var isListEnd;
var onEach2;
var onParallel;
opt.list = opt.list || [];
onEach2 = function () {
while (true) {
if (!(onParallel.ii + 1 < opt.list.length)) {
isListEnd = true;
return;
}
if (!(onParallel.counter < opt.rateLimit + 1)) {
return;
}
onParallel.ii += 1;
onEach({
elem: opt.list[onParallel.ii],
ii: onParallel.ii,
list: opt.list,
retry: 0
}, onParallel);
}
};
onParallel = local.onParallel(onError, onEach2, function (err, data) {
if (err && data && data.retry < opt.retryLimit) {
local.onErrorDefault(err);
data.retry += 1;
setTimeout(function () {
onParallel.counter -= 1;
onEach(data, onParallel);
}, 1000);
return true;
}
// restart if opt.list has grown
if (isListEnd && (onParallel.ii + 1 < opt.list.length)) {
isListEnd = null;
onEach2();
}
});
onParallel.ii = -1;
opt.rateLimit = Number(opt.rateLimit) || 6;
opt.rateLimit = Math.max(opt.rateLimit, 1);
opt.retryLimit = Number(opt.retryLimit) || 2;
onParallel.counter += 1;
onEach2();
onParallel();
}
...
method: "DELETE",
sha: data.sha,
url: opt.url
}, opt.onNext);
return;
}
// delete tree
local.onParallelList({
list: data
}, function (option2, onParallel) {
onParallel.counter += 1;
// recurse
local.githubCrudContentDelete({
httpReq: opt.httpReq,
message: opt.message,
...
onTimeout = function (onError, timeout, message) {
/*
* this function will create a timeout-err-handler,
* that appends current-stack to any err encountered
*/
onError = local.onErrorWithStack(onError);
// create timerTimeout
return setTimeout(function () {
onError(new Error(
"onTimeout - errTimeout - " + timeout + " ms - " + message
));
// coerce to finite integer
}, timeout);
}
...
+ ".json"
),
modeBrowserTest: "test",
timeExit: Date.now() + opt.timeoutDefault,
timeoutScreenshot: opt.timeoutScreenshot || 15000
}, 1);
// init timerTimeout
timerTimeout = local.onTimeout(
opt.onNext,
opt.timeoutDefault,
opt.testName
).unref();
data = {};
Object.keys(opt).forEach(function (key) {
if (typeof opt[key] !== "object") {
...
operationIdFromAjax = function (opt) {
/*
* this function will create a sortable operationId
* from given ajax-<opt>
*/
var urlParsed;
urlParsed = local.urlParseWithBraket(opt.url);
return encodeURIComponent(
urlParsed.pathname + urlParsed.hash + " " + opt.method.toUpperCase()
).replace((
/[^\w\-.]/g
), "_");
}
...
tmp = swaggerJson.paths[path][method];
// auto-create operationId from path
if (
swaggerJson["x-swgg-operationIdFromPath"]
|| tmp["x-swgg-operationIdFromPath"]
|| !tmp.operationId
) {
tmp.operationId = local.operationIdFromAjax({
method,
url: path
});
}
// normalize parameter.required
(tmp.parameters || []).forEach(function (schemaP) {
if (schemaP.required === false) {
...
profile = function (fnc, onError) {
/*
* this function will profile async <fnc> in milliseconds
* with callback <onError>
*/
var timeStart;
timeStart = Date.now();
// run async fnc
fnc(function (err) {
// call onError with difference in milliseconds
// between Date.now() and timeStart
onError(err, Date.now() - timeStart);
});
}
...
});
// validate timeElapsed
local.assertThrow(
0 <= opt.timeElapsed && opt.timeElapsed < 1000,
opt.timeElapsed
);
// test profile's async handling-behavior
local.profile(function (onError) {
setTimeout(onError);
}, function (err, timeElapsed) {
// validate no err occurred
local.assertThrow(!err, err);
opt.timeElapsed = timeElapsed;
// validate timeElapsed
local.assertThrow((
...
profileSync = function (fnc) {
/*
* this function will profile sync <fnc> in milliseconds
*/
var timeStart;
timeStart = Date.now();
// run sync fnc
fnc();
// return difference in milliseconds between Date.now() and timeStart
return Date.now() - timeStart;
}
...
local.testCase_profileXxx_default = function (opt, onError) {
/*
* this function will test profileXxx's default handling-behavior
*/
opt = {};
// test profileSync's handling-behavior
opt.timeElapsed = local.profileSync(function () {
return;
});
// validate timeElapsed
local.assertThrow(
0 <= opt.timeElapsed && opt.timeElapsed < 1000,
opt.timeElapsed
);
...
replStart = function () {
/*
* this function will start the repl-debugger
*/
var that;
if (globalThis.utility2_repl1) {
return;
}
// start repl
that = require("repl").start({
useGlobal: true
});
globalThis.utility2_repl1 = that;
that.onError = function (err) {
/*
* this function will debug repl-err
*/
globalThis.utility2_debugReplError = err;
console.error(err);
};
// save eval-function
that.evalDefault = that.eval;
// hook custom-eval-function
that.eval = function (script, context, file, onError) {
var onError2;
onError2 = function (err, data) {
// debug err
globalThis.utility2_debugReplError = (
err || globalThis.utility2_debugReplError
);
onError(err, data);
};
script.replace((
/^(\S+)\u0020(.*?)\n/
), function (ignore, match1, match2) {
switch (match1) {
// syntax-sugar - run async shell-command
case "$":
switch (match2) {
// syntax-sugar - run git diff
case "git diff":
match2 = "git diff --color | cat";
break;
// syntax-sugar - run git log
case "git log":
match2 = "git log -n 4 | cat";
break;
// syntax-sugar - run git log
case "ll":
match2 = "ls -Fal";
break;
}
// source lib.utility2.sh
if (
process.platform !== "win32"
&& process.env.npm_config_dir_utility2 && (match2 !== ":")
) {
match2 = (
". " + process.env.npm_config_dir_utility2
+ "/lib.utility2.sh;" + match2
);
}
// run async shell-command
require("child_process").spawn(match2, {
shell: true,
stdio: [
"ignore", 1, 2
]
// on shell exit, print return prompt
}).on("exit", function (exitCode) {
console.error("exit-code " + exitCode);
that.evalDefault(
"\n",
context,
file,
onError2
);
});
script = "\n";
break;
// syntax-sugar - map text with charCodeAt
case "charCode":
console.error(
match2.split("").map(function (chr) {
return (
"\\u"
+ chr.charCodeAt(0).toString(16).padStart(4, 0)
);
}).join("")
);
script = "\n";
break;
// syntax-sugar - sort chr
case "charSort":
console.error(JSON.stringify(match2.split("").sort().join("")));
script = "\n";
break;
// syntax-sugar - grep current dir
case "grep":
// run async shell-command
require("child_process").spawn((
"find . -type f | grep -v -E "
/* jslint ignore:start */
+ '"\
/\\.|(\\b|_)(\\.\\d|\
archive|artifact|\
bower_component|build|\
coverage|\
doc|\
external|\
fixture|\
git_module|\
jquery|\
log|\
min|misc|mock|\
node_module|\
raw|\rollup|\
swp|\
tmp|\
v...
...
local.cliDict["utility2.start"] = function () {
/*
* <port>
* will start utility2 http-server on given <port> (default 8081)
*/
local.env.PORT = process.argv[3] || local.env.PORT;
globalThis.local = local;
local.replStart();
local.testRunServer({});
};
local.cliDict["utility2.swaggerValidateFile"] = function () {
/*
* <file/url>
* will swagger-validate file/url
...
requireInSandbox = function (file) {
/*
* this function will require the file in a sandbox-lite env
*/
var exports;
var mockDict;
var mockList;
var tmp;
mockList = [
[
globalThis, {
setImmediate: local.nop,
setInterval: local.nop,
setTimeout: local.nop
}
]
];
[
[
local, "child_process"
], [
local, "cluster"
], [
local, "http"
], [
local, "https"
], [
local, "net"
], [
local, "repl"
], [
local.events, "prototype"
], [
globalThis, "process"
], [
local.stream, "prototype"
], [
process, "stdin"
]
].forEach(function (elem) {
tmp = elem[0][elem[1]];
mockDict = {};
Object.keys(tmp).forEach(function (key) {
if (
typeof tmp[key] === "function"
&& !(
/^(?:fs\.Read|fs\.read|process\.binding|process\.dlopen)/
)
.test(elem[1] + "." + key)
) {
mockDict[key] = function () {
return;
};
// coverage-hack
mockDict[key]();
}
});
mockList.push([
tmp, mockDict
]);
});
local.testMock(mockList, function (onError) {
local.tryCatchOnError(function () {
exports = require(file);
}, local.onErrorDefault);
onError();
}, local.onErrorThrow);
return exports;
}
n/a
requireReadme = function () {
/*
* this function will require and export example.js embedded in README.md
*/
var code;
var module;
var tmp;
// init module.exports
module = {};
if (local.isBrowser) {
module.exports = local.objectSetDefault(
globalThis.utility2_rollup || globalThis.local,
local
);
return module.exports;
}
// start repl-debugger
local.replStart();
// debug dir
[
__dirname + "/lib.jslint.js",
__filename,
"undefined"
].forEach(function (file) {
local.fs.exists(file, function (exists) {
if (exists) {
local.onFileModifiedRestart(file);
}
});
});
local.fs.readdirSync(process.cwd()).forEach(function (file) {
file = process.cwd() + "/" + file;
// if the file is modified, then restart the process
local.onFileModifiedRestart(file);
switch (local.path.basename(file)) {
// swagger-validate assets.swgg.swagger.json
case "assets.swgg.swagger.json":
local.fs.readFile(file, "utf8", function (err, data) {
local.tryCatchOnError(function () {
// validate no err occurred
local.assertThrow(!err, err);
local.swgg.swaggerValidate(JSON.parse(data));
}, local.onErrorDefault);
});
break;
}
});
// jslint process.cwd()
if (!local.env.npm_config_mode_library) {
local.child_process.spawn("node", [
"-e", (
"require("
+ JSON.stringify(__filename)
+ ").jslint.jslintAndPrintDir("
+ JSON.stringify(process.cwd())
+ ", {autofix:true,conditional:true}, process.exit);"
)
], {
env: local.objectAssignDefault({
npm_config_mode_library: "1"
}, local.env),
stdio: [
"ignore", "ignore", 2
]
});
}
if (globalThis.utility2_rollup || local.env.npm_config_mode_start) {
// init assets
local.assetsDict["/index.html"] = (
local.fsReadFileOrEmptyStringSync("index.html")
|| local.assetsDict["/index.rollup.html"] || ""
);
local.assetsDict["/"] = local.assetsDict["/index.html"];
local.assetsDict["/assets.app.js"] = local.fs.readFileSync(
__filename,
"utf8"
).replace((
/^#!\//
), "// ");
// init exports
local[local.env.npm_package_nameLib] = local;
module.exports = local;
return module.exports;
}
// init file $npm_package_main
globalThis.utility2_moduleExports = require(
process.cwd() + "/" + local.env.npm_package_main
);
globalThis.utility2_moduleExports.globalThis = globalThis;
// read code from README.md
code = local.templateRenderMyApp(
local.assetsDict["/assets.example.template.js"],
{}
);
local.tryCatchOnError(function () {
tmp = (
/```\w*?(\n[\W\s]*?example\.js[\n"][\S\s]*?)\n```/
).exec(
local.fs.readFileSync("README.md", "utf8")
);
code = tmp.input.slice(0, tmp.index).replace((
/.+/g
), "") + tmp[1];
}, local.nop);
code = code
// alias require($npm_package_name) to utility2_moduleExports;
.replace(
new RegExp("require\\(." + local.env.npm_package_name + ".\\)"),
"globalThis.utility2_moduleExports"
)
.replace(
new RegExp("require\\(." + local.env.npm_package_nameOriginal + ".\\)")...
...
\n\
\n\
// run shared js\-env code - init-before\n\
(function () {\n\
// init local\n\
local = (\n\
globalThis.utility2 || require("utility2")\n\
).requireReadme();\n\
globalThis.local = local;\n\
// init test\n\
local.testRunDefault(local);\n\
}());\n\
\n\
\n\
\n\
...
schemaPItems = function (schemaP) {
/*
* this function will return schemaP.items
*/
return schemaP["x-swgg-items"] || schemaP.items;
}
...
? 2
: 1
)) {
// recurse dbFieldRandomCreate
value.push(local.dbFieldRandomCreate({
depth: depth - 1,
modeNotRandom: opt.modeNotRandom,
schemaP: local.schemaPItems(schemaP)
}));
ii += 1;
}
break;
case "boolean":
value = (
opt.modeNotRandom
...
schemaPItemsType = function (schemaP) {
/*
* this function will return schemaP.items.type
*/
return local.schemaPType(local.schemaPItems(schemaP) || {});
}
...
// ternary-operator
schemaP.in === "formData"
? "inForm"
: "inQuery"
)] += (
"&" + encodeURIComponent(schemaP.name) + "="
+ encodeURIComponent(
local.schemaPItemsType(schemaP) === "string"
? value
: JSON.stringify(value)
)
);
});
return;
case "pipes":
...
schemaPType = function (schemaP) {
/*
* this function will return schemaP.type
*/
return schemaP && (schemaP["x-swgg-type"] || schemaP.type);
}
...
delete schemaP.$ref;
});
// init _idName.format and _idName.type
if (that._schemaName && schemaP.name === that._idName) {
schemaP.format = swaggerJson.definitions[
that._schemaName
].properties[that._idBackend].format;
schemaP.type = local.schemaPType(
swaggerJson.definitions[
that._schemaName
].properties[that._idBackend]
);
}
// init _schemaPDict
that._schemaPDict[schemaP.name] = schemaP;
...
semverCompare = function (aa, bb) {
/*
* this function will compare semver versions aa ? bb and return
* -1 if aa < bb
* 0 if aa = bb
* 1 if aa > bb
* https://semver.org/#spec-item-11
*/
return [
aa, bb
].map(function (aa) {
aa = aa.split("-");
return [
aa[0], aa.slice(1).join("-") || "\u00ff"
].map(function (aa) {
return aa.split(".").map(function (aa) {
return ("0000000000000000" + aa).slice(-16);
}).join(".");
}).join("-");
}).reduce(function (aa, bb) {
return (
aa === bb
? 0
: aa < bb
? -1
: 1
);
});
}
...
), "."));
bb = (process.argv[2] || "0.0.0").replace((
/^(\d+?\.\d+?\.)(\d+)(\.*?)$/
), function (ignore, match1, match2, match3) {
return match1 + (Number(match2) + 1) + match3;
});
packageJson.version = (
local.semverCompare(aa, bb) === 1
? aa
: bb
);
console.error([
aa, bb, packageJson.version
]);
// update package.json
...
serverRespondCors = function (req, res) {
/*
* this function will enable cors for the req
* http://en.wikipedia.org/wiki/Cross-origin_resource_sharing
*/
local.serverRespondHeadSet(req, res, null, local.jsonCopy({
"access-control-allow-headers":
req.headers["access-control-request-headers"],
"access-control-allow-methods":
req.headers["access-control-request-method"],
"access-control-allow-origin": "*"
}));
}
...
var opt;
var timerTimeout;
// handle preflight-cors
if (req.method === "OPTIONS" && (
/forward-proxy-url/
)
.test(req.headers["access-control-request-headers"])) {
local.serverRespondCors(req, res);
res.end();
return;
}
if (!req.headers["forward-proxy-url"]) {
next();
return;
}
...
serverRespondDefault = function (req, res, statusCode, err) {
/*
* this function will respond with a default message,
* or <err>.stack for given statusCode
*/
// init statusCode and contentType
local.serverRespondHeadSet(
req,
res,
statusCode,
{
"Content-Type": "text/plain; charset=utf-8"
}
);
if (err) {
// debug statusCode / method / url
local.errorMessagePrepend(
err,
res.statusCode + " " + req.method + " " + req.url
+ "\n"
);
// print err.stack to stderr
local.onErrorDefault(err);
// end res with err.stack
res.end(err.stack);
return;
}
// end res with default statusCode message
res.end(
statusCode + " " + local.http.STATUS_CODES[statusCode]
);
}
...
opt.onNext(null, data, meta);
}
break;
case 3:
switch (crud.crudType[0]) {
case "fileGetOneById":
if (!data) {
local.serverRespondDefault(req, res, 404);
return;
}
local.serverRespondHeadSet(req, res, null, {
"Content-Type": data.fileContentType
});
res.end(local.base64ToBuffer(data.fileBlob));
break;
...
serverRespondEcho = function (req, res) {
/*
* this function will respond with debug info
*/
res.write(
req.method + " " + req.url
+ " HTTP/" + req.httpVersion + "\r\n"
+ Object.keys(req.headers).map(function (key) {
return key + ": " + req.headers[key] + "\r\n";
}).join("") + "\r\n"
);
req.pipe(res);
}
...
break;
// test http POST handling-behavior
case "/test.echo":
// test res-header handling-behavior
local.serverRespondHeadSet(req, res, null, {
"X-Res-Header-Test": "bb"
});
local.serverRespondEcho(req, res);
break;
// test 500-internal-server-error handling-behavior
case "/test.err-500":
// test multiple-callback serverRespondHeadSet handling-behavior
local.serverRespondHeadSet(req, res, null, {});
next(local.errDefault);
// test multiple-callback-error handling-behavior
...
serverRespondHeadSet = function (ignore, res, statusCode, headers) {
/*
* this function will set the <res> object's <statusCode> and <headers>
*/
if (res.headersSent) {
return;
}
// init res.statusCode
if (Number(statusCode)) {
res.statusCode = Number(statusCode);
}
Object.keys(headers).forEach(function (key) {
if (headers[key]) {
res.setHeader(key, headers[key]);
}
});
return true;
}
...
});
local.dbTableFile.crudSetManyById(crud.body, opt.onNext);
break;
case "userLoginByPassword":
case "userLogout":
// respond with 401 Unauthorized
if (!user.isAuthenticated) {
local.serverRespondHeadSet(req, res, 401, {});
req.swgg.crud.endArgList = [
req, res
];
opt.modeNext = Infinity;
opt.onNext();
return;
}
...
serverRespondJsonapi = function (req, res, err, data, meta) {
/*
* this function will respond in jsonapi format
* http://jsonapi.org/format/#errors
* http://jsonapi.org/format/#document-structure-resource-objects
*/
local.onErrorJsonapi(function (err, data) {
local.serverRespondHeadSet(req, res, err && err.statusCode, {
"Content-Type": "application/json"
});
if (err) {
// debug statusCode / method / url
local.errorMessagePrepend(
err,
res.statusCode + " " + req.method + " " + req.url + "\n"
);
// print err.stack to stderr
local.onErrorDefault(err);
}
data = err || data;
res.statusCode = data.meta.statusCode || res.statusCode;
data.meta.statusCode = res.statusCode;
res.end(JSON.stringify(data));
})(err, data, meta);
}
...
// default - 404 Not Found
if (!err) {
local.serverRespondDefault(req, res, 404);
return;
}
// http://jsonapi.org/format/#errors
if (local.swgg && typeof local.swgg.serverRespondJsonapi === "function") {
local.swgg.serverRespondJsonapi(req, res, err);
}
// statusCode [400, 600)
local.serverRespondDefault(req, res, (
(err.statusCode >= 400 && err.statusCode < 600)
? err.statusCode
: 500
), err);
...
serverRespondTimeoutDefault = function (req, res, timeout) {
/*
* this function will create a timeout-err-handler for server-<req>
*/
var isDone;
var onError;
onError = function () {
if (isDone) {
return;
}
isDone = true;
// debug serverResponse
console.error("serverLog - " + JSON.stringify({
time: new Date(req.timeStart).toISOString(),
type: "serverResponse",
method: req.method,
url: req.url,
statusCode: res.statusCode | 0,
timeElapsed: Date.now() - req.timeStart,
// extra
requestContentLength: req.dataLength || 0,
resContentLength: res.contentLength,
requestHeaderXForwardedFor:
req.headers["x-forwarded-for"] || "",
requestHeaderOrigin: req.headers.origin || "",
requestHeaderReferer: req.headers.referer || "",
requestHeaderUserAgent: req.headers["user-agent"]
}));
// cleanup timerTimeout
clearTimeout(req.timerTimeout);
};
req.timeStart = Date.now();
req.onTimeout = req.onTimeout || function (err) {
local.serverRespondDefault(req, res, 500, err);
setTimeout(function () {
// cleanup <req> and <res>
local.streamCleanup(req);
local.streamCleanup(res);
}, 1000);
};
// init timerTimeout
req.timerTimeout = local.onTimeout(
req.onTimeout,
timeout || local.timeoutDefault,
"server " + req.method + " " + req.url
);
res.contentLength = 0;
res.writeContentLength = res.writeContentLength || res.write;
res.write = function (chunk, encoding, callback) {
chunk = local.normalizeChunk(chunk);
res.contentLength += chunk.length;
res.writeContentLength(chunk, encoding, callback);
};
res.on("error", onError);
res.on("finish", onError);
}
...
local._debugServerReqRes3 = local._debugServerReqRes2;
local._debugServerReqRes2 = local._debugServerReqRes1;
local._debugServerReqRes1 = {
req,
res
};
// init timerTimeout
local.serverRespondTimeoutDefault(req, res, local.timeoutDefault);
// init req.urlParsed
req.urlParsed = local.urlParse(req.url);
// init res-header content-type
local.serverRespondHeadSet(req, res, null, {
"Content-Type": local.contentTypeDict[(
/\.[^.]*?$|$/m
).exec(req.urlParsed.pathname)[0]]
...
setTimeoutOnError = function (onError, timeout, err, data) {
/*
* this function will after timeout has passed,
* then call <onError>(<err>, <data>)
*/
if (typeof onError === "function") {
setTimeout(function () {
onError(err, data);
}, timeout);
}
return data;
}
...
};
local._DbTable.prototype.crudCountAll = function (onError) {
/*
* this function will count all of dbRow's in dbTable
*/
this._cleanup();
return local.setTimeoutOnError(onError, 0, null, this.dbRowList.length);
};
local._DbTable.prototype.crudCountManyByQuery = function (query, onError) {
/*
* this function will count the number of dbRow's in dbTable with given query
*/
this._cleanup();
...
sjclHashScryptCreate = function (password, opt) {
/*
* this function will create a scrypt-hash of the password
* with given <opt> (default = $s0$10801)
* e.g.
* $s0$e0801$epIxT/h6HbbwHaehFnh/bw==$7H0vs
* XlY8UxxyW/BWx/9GuY7jEvGjT71GFd6O4SZND0=
* https://github.com/wg/scrypt
*/
// init opt
opt = (opt || "$s0$10801").split("$");
// init salt
if (!opt[3]) {
opt[3] = local.sjcl.codec.base64.fromBits(
local.sjcl.random.randomWords(4, 0)
);
}
// init hash
opt[4] = local.sjcl.codec.base64.fromBits(
local.sjcl.misc.scrypt(
password || "",
local.sjcl.codec.base64.toBits(opt[3]),
Math.pow(2, parseInt(opt[2].slice(0, 1), 16)),
parseInt(opt[2].slice(1, 2), 16),
parseInt(opt[2].slice(3, 4), 16)
)
);
return opt.slice(0, 5).join("$");
}
...
};
local.sjclHashScryptValidate = function (password, hash) {
/*
* this function will validate the password against the scrypt-hash
* https://github.com/wg/scrypt
*/
return local.sjclHashScryptCreate(password, hash) === hash;
};
local.sjclHashSha1Create = function (data) {
/*
* this function will create a base64-encoded sha1 hash of the string data
*/
return local.sjcl.codec.base64.fromBits(local.sjcl.hash.sha1.hash(data));
...
sjclHashScryptValidate = function (password, hash) {
/*
* this function will validate the password against the scrypt-hash
* https://github.com/wg/scrypt
*/
return local.sjclHashScryptCreate(password, hash) === hash;
}
...
opt.modeNext = Infinity;
opt.onNext();
break;
case 2:
switch (crud.crudType[0]) {
case "userLoginByPassword":
user.data = data;
if (!local.sjclHashScryptValidate(
user.password,
user.data && user.data.password
)) {
opt.modeNext = Infinity;
opt.onNext();
return;
}
...
sjclHashSha1Create = function (data) {
/*
* this function will create a base64-encoded sha1 hash of the string data
*/
return local.sjcl.codec.base64.fromBits(local.sjcl.hash.sha1.hash(data));
}
...
};
local.testCase_sjclHashShaXxxCreate_default = function (opt, onError) {
/*
* this function will test sjclHashShaXxxCreate's default handling-behavior
*/
local.assertJsonEqual(
local.sjclHashSha1Create("aa"),
"4MkDWJjdUvxlxBRUzsnE0mEb+zc="
);
local.assertJsonEqual(
local.sjclHashSha256Create("aa"),
"lhtt0+3jy47LqsvWjeBAzXjrLtWIkTDM60xJJo6k1QY="
);
onError(null, opt);
...
sjclHashSha256Create = function (data) {
/*
* this function will create a base64-encoded sha256 hash of the string data
*/
return local.sjcl.codec.base64.fromBits(local.sjcl.hash.sha256.hash(data));
}
...
* this function will test sjclHashShaXxxCreate's default handling-behavior
*/
local.assertJsonEqual(
local.sjclHashSha1Create("aa"),
"4MkDWJjdUvxlxBRUzsnE0mEb+zc="
);
local.assertJsonEqual(
local.sjclHashSha256Create("aa"),
"lhtt0+3jy47LqsvWjeBAzXjrLtWIkTDM60xJJo6k1QY="
);
onError(null, opt);
};
local.testCase_sjclHmacShaXxx_default = function (opt, onError) {
/*
...
sjclHmacSha1Create = function (key, data) {
/*
* this function will create a base64-encoded sha1 hmac
* from the string key and string data
*/
var Hmac;
Hmac = local.sjcl.misc.hmac;
return local.sjcl.codec.base64.fromBits(
(new Hmac(
local.sjcl.codec.utf8String.toBits(key),
local.sjcl.hash.sha1
)).mac(local.sjcl.codec.utf8String.toBits(data))
);
}
...
};
local.testCase_sjclHmacShaXxx_default = function (opt, onError) {
/*
* this function will test sjclHmacShaXxx's default handling-behavior
*/
local.assertJsonEqual(
local.sjclHmacSha1Create("aa", "bb"),
"15pOinCz63A+qZoxnv+mJB6UF1k="
);
local.assertJsonEqual(
local.sjclHmacSha256Create("aa", "bb"),
"94Xv3VdPHA+ohKyjkM1pb0W5ZVAuMVcmIAAI2AqNRCQ="
);
onError(null, opt);
...
sjclHmacSha256Create = function (key, data) {
/*
* this function will create a base64-encoded sha256 hmac
* from the string key and string data
*/
var Hmac;
Hmac = local.sjcl.misc.hmac;
return local.sjcl.codec.base64.fromBits(
(new Hmac(
local.sjcl.codec.utf8String.toBits(key),
local.sjcl.hash.sha256
)).mac(local.sjcl.codec.utf8String.toBits(data))
);
}
...
* this function will test sjclHmacShaXxx's default handling-behavior
*/
local.assertJsonEqual(
local.sjclHmacSha1Create("aa", "bb"),
"15pOinCz63A+qZoxnv+mJB6UF1k="
);
local.assertJsonEqual(
local.sjclHmacSha256Create("aa", "bb"),
"94Xv3VdPHA+ohKyjkM1pb0W5ZVAuMVcmIAAI2AqNRCQ="
);
onError(null, opt);
};
local.testCase_stringHtmlSafe_default = function (opt, onError) {
/*
...
stateInit = function (opt) {
/*
* this function will init state <opt>
*/
local.objectSetOverride(local, opt, 10);
// init swgg
local.swgg.apiUpdate(local.swgg.swaggerJson);
}
...
local.fsReadFileOrEmptyStringSync("assets.swgg.swagger.json")
|| local.assetsDict["/assets.swgg.swagger.json"]
|| local.assetsDict["/assets.swgg.swagger.petstore.json"]
);
// coverage-hack - re-run test-server
local.testRunServer(local);
// coverage-hack - stateInit
local.stateInit({});
// init test-middleware
local.middlewareList.push(function (req, res, next) {
/*
* this function will run the test-middleware
*/
switch (req.urlParsed.pathname) {
// test http POST handling-behavior
...
function Stream() { EE.call(this); }
n/a
streamCleanup = function (stream) {
/*
* this function will try to end or destroy the stream
*/
var err;
// try to end the stream
try {
stream.end();
} catch (errCaught) {
err = errCaught;
}
// if err, then try to destroy the stream
if (err) {
try {
stream.destroy();
} catch (ignore) {}
}
}
...
// extra
headers: opt.headers
}));
if (!err) {
return;
}
// cleanup clientReq and clientRes
local.streamCleanup(opt.clientReq);
local.streamCleanup(opt.clientResponse);
next(err);
};
// init opt
opt = local.urlParse(req.headers["forward-proxy-url"]);
opt.method = req.method;
opt.url = req.headers["forward-proxy-url"];
...
streamReadAll = function (stream, onError) {
/*
* this function will concat data from <stream>
* and pass to <onError> when finished reading
*/
var chunkList;
chunkList = [];
stream.dataLength = 0;
// on event-data, push buffer-chunk to chunkList
stream.on("data", function (chunk) {
chunk = local.normalizeChunk(chunk);
chunkList.push(chunk);
stream.dataLength += chunk.length;
// on event-end, pass concatenated-buffer to onError
}).on("end", function () {
onError(
null,
local.isBrowser
? chunkList[0]
: local.bufferConcat(chunkList)
);
// on event-error, pass error to onError
}).on("error", onError);
}
...
* read and save the <req>-body to <req>.bodyRaw
*/
// if req is already read, then goto next
if (!req.readable) {
next();
return;
}
local.streamReadAll(req, function (err, data) {
req.bodyRaw = req.bodyRaw || data;
next(err);
});
};
local.middlewareCacheControlLastModified = function (req, res, next) {
/*
...
stringHtmlSafe = function (text) {
/*
* this function will make the text html-safe
* https://stackoverflow.com/questions/7381974/which-characters-need-to-be-escaped-on-html
*/
return text
.replace((
/&/g
), "&")
.replace((
/"/g
), """)
.replace((
/'/g
), "'")
.replace((
/</g
), "<")
.replace((
/>/g
), ">")
.replace((
/&(amp;|apos;|gt;|lt;|quot;)/ig
), "&$1");
}
...
)
// handle case where module is a function
.replace(">.<", "><");
if (elem.typeof !== "function") {
return elem;
}
// init source
elem.source = local.stringHtmlSafe(
trimLeft(toString(module[key])) || "n/a"
).replace((
/\([\S\s]*?\)/
), function (match0) {
// init signature
elem.signature = match0.replace((
/\u0020*?\/\*[\S\s]*?\*\/\u0020*/g
...
stringMerge = function (str1, str2, rgx) {
/*
* this function will merge <str2> into <str1>,
* for sections where both match <rgx>
*/
str2.replace(rgx, function (match2) {
str1.replace(rgx, function (match1) {
str1 = str1.replace(match1, function () {
return match2;
});
});
});
return str1;
}
...
/\n\u0020\*\n(?:[\S\s]*?\n)?\u0020\*\/\n/
),
// customize body after /* validateLineSortedReset */
(
/\n\/\*\u0020validateLineSortedReset\u0020\*\/\n[\S\s]*?$/
)
].forEach(function (rgx) {
opt.dataTo = local.stringMerge(opt.dataTo, opt.dataFrom, rgx);
});
// customize local for assets.utility2.rollup.js
if (
local.fs.existsSync("./assets.utility2.rollup.js")
&& local.env.npm_package_nameLib !== "swgg"
) {
opt.dataTo = opt.dataTo.replace(
...
stringQuotedToAscii = function (str) {
/*
* this function will replace non-ascii-chr to unicode-escaped-ascii-chr
* in quoted-<str>
*/
return str
.replace((
/\r/g
), "\\r")
.replace((
/\t/g
), "\\t")
.replace((
/[^\n\u0020-\u007e]/g
), function (chr) {
return "\\u" + ("0000" + chr.charCodeAt(0).toString(16)).slice(-4);
});
}
...
};
local.testCase_stringQuotedToAscii_default = function (opt, onError) {
/*
* this function will test stringQuotedToAscii's default handling-behavior
*/
local.assertJsonEqual(
local.stringQuotedToAscii(local.stringHelloEmoji),
"hello \\ud83d\\ude01\n"
);
onError(null, opt);
};
local.testCase_stringRegexpEscape_default = function (opt, onError) {
/*
...
stringRegexpEscape = function (text) {
/*
* this function will regexp-escape text
* https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
*/
return text.replace((
/[\-\/\\\^$*+?.()|\[\]{}]/g
), "\\$&");
}
...
};
local.testCase_stringRegexpEscape_default = function (opt, onError) {
/*
* this function will test stringRegexpEscape's default handling-behavior
*/
local.assertJsonEqual(
local.stringRegexpEscape(local.stringCharsetAscii),
(
"\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007"
+ "\b\t\n\u000b\f\r\u000e\u000f"
+ "\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017"
+ "\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f"
+ " !\"#\\$%&'\\(\\)\\*\\+,\\-\\.\\/0123456789:;<=>\\?@"
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ\\[\\\\\\]\\^_`"
...
stringTruncate = function (text, maxLength) {
/*
* this function will truncate text to given maxLength
*/
return (
text.length > maxLength
? text.slice(0, maxLength - 3).trimRight() + "..."
: text
);
}
...
].forEach(function (ii) {
opt["prefix" + ii] = opt.prefix[ii] + opt.prefix.slice(
ii + 1
).map(function (element) {
return "[" + JSON.stringify(element) + "]";
}).join("");
});
opt.prefix0 += " = " + local.stringTruncate(
JSON.stringify(opt.data) || "undefined",
100
);
opt.schema2 = local.stringTruncate(
JSON.stringify(opt.schema) || "undefined",
500
);
...
stringUniqueKey = function (text) {
/*
* this function will return a string-key that is unique in given text
*/
var key;
// seed the key with the least frequent letters in the english-language
// https://en.wikipedia.org/wiki/Letter_frequency
key = "zqxj";
do {
key += ((1 + Math.random()) * 0x10000000000000).toString(36).slice(1);
} while (text.indexOf(key) >= 0);
return key;
}
...
var arg;
var argList;
var doubleBackslash;
var opt;
var quote;
arg = "";
argList = [];
doubleBackslash = local.stringUniqueKey(text);
// parse doubleBackslash
text = text.replace((
/\\\\/g
), doubleBackslash);
// parse line-continuation
text = text.replace((
/\\\n/g
...
swaggerJsonFromAjax = function (swaggerJson, opt) {
/*
* this function will update swaggerJson
* with definitions and paths created from given ajax-<opt>
*/
var data;
var isArray;
var operation;
var pathDict;
var type;
var upsertSchemaP;
var urlParsed;
upsertSchemaP = function (schemaP) {
if (!operation.parameters.some(function (element) {
if (element.in === schemaP.in && element.name === schemaP.name) {
[
"default", "items", "schema"
].forEach(function (key) {
if (!local.isNullOrUndefined(schemaP[key])) {
element[key] = schemaP[key];
}
});
return true;
}
})) {
operation.parameters.push(schemaP);
}
};
// init swaggerJson
swaggerJson = local.objectSetDefault(swaggerJson, {
basePath: "/",
definitions: {},
info: {
title: "",
version: ""
},
paths: {},
swagger: "2.0"
});
// init opt
opt = local.objectSetDefault(opt, {
headers: {},
method: "GET"
});
// init urlParsed
urlParsed = local.urlParseWithBraket(opt.url);
// init operation
operation = {
operationId: opt.operationId || local.operationIdFromAjax(opt),
parameters: [],
responses: {
default: {
description: "default response"
}
},
tags: opt.tags || [
"undefined"
],
"x-swgg-tags0": opt["x-swgg-tags0"]
};
if ((
/^(?:http|https):\/\//
).test(opt.url)) {
operation["x-swgg-host"] = urlParsed.host;
operation["x-swgg-schemes"] = [
urlParsed.protocol.slice(0, -1)
];
}
pathDict = {};
pathDict[urlParsed.pathname + urlParsed.hash] = {};
pathDict[urlParsed.pathname + urlParsed.hash][
opt.method.toLowerCase()
] = operation;
local.objectSetDefault(swaggerJson, {
paths: pathDict
}, 3);
// init param in header
Object.keys(opt.headers).forEach(function (key) {
upsertSchemaP({
default: opt.headers[key],
in: "header",
name: key,
type: "string"
});
});
// init param in path
urlParsed.pathname.replace((
/\{[^}]+?\}/g
), function (match0) {
match0 = match0.slice(1, -1);
upsertSchemaP({
default: match0,
in: "path",
name: match0,
required: true,
type: "string"
});
});
// init param in query
Object.keys(urlParsed.query).forEach(function (key) {
upsertSchemaP({
default: urlParsed.query[key],
in: "query",
name: key,
type: "string"
});
});
data = opt.data;
if (!data) {
return swaggerJson;
}
// init param in body - text-data
upsertSchemaP({
in: "body",
name: "body",
schema: {
type: "string"
}
});
local.tryCatchOnError(function () {
data = JSON.parse(data);
}, local.nop);
if (typeof data !== "object") {
return swaggerJson;
}
// init param in body - json-data
isArray = Array.isArray(data);
type = local.swaggerJsonFromPostBody(swaggerJson, {
data: (
// ternary-operator
isArray
? data[0]
: data
),
depth: 2,
key: "body",
prefix: operation.operationId,
"x-swgg-tags0": opt["x-swgg-tags0"]
});
upsertSchemaP({
in: "body",...
...
case "-X":
opt.method = arg;
return;
}
if (arg === "curl") {
if (opt) {
opt.url = opt.url || argList[ii - 1];
swaggerJson = local.swaggerJsonFromAjax(swaggerJson, opt);
}
opt = {
headers: {},
method: "GET"
};
}
if ((
...
swaggerJsonFromCurl = function (swaggerJson, text) {
/*
* this function will update swaggerJson
* with definitions and paths created from given curl-command-text
*/
var arg;
var argList;
var doubleBackslash;
var opt;
var quote;
arg = "";
argList = [];
doubleBackslash = local.stringUniqueKey(text);
// parse doubleBackslash
text = text.replace((
/\\\\/g
), doubleBackslash);
// parse line-continuation
text = text.replace((
/\\\n/g
), "");
// parse quotes
text.replace((
/(\s*?)(\S+)/g
), function (match0, line, word) {
line = match0;
word.replace((
/^(["']?).*?(?:\\")?(["']?)$/
), function (quote1, match1, quote2) {
quote1 = match1;
if (quote) {
arg += line;
} else {
arg = word;
quote = quote1;
}
if (!quote || quote === quote2) {
switch (quote) {
// parse escapes in single-quotes
case "'":
arg = arg.replace((
/'"'"'/g
), "'");
arg = arg.slice(1, -1);
break;
// parse escapes in double-quotes
// https://www.gnu.org/software/bash/manual/html_node/Double-Quotes.html
case "\"":
arg = arg.replace((
/\\([$`"\n])/g
), "$1");
arg = arg.slice(1, -1);
break;
}
argList.push(arg);
arg = "";
quote = "";
}
});
});
// un-parse doubleBackslash
argList = argList.map(function (arg) {
return arg.replace(new RegExp(doubleBackslash, "g"), "\\\\");
});
argList.push("curl");
argList.forEach(function (arg, ii) {
switch (argList[ii - 1]) {
case "--data":
case "--data-ascii":
case "--data-binary":
case "--data-raw":
case "-d":
opt.data = arg;
return;
case "--header":
case "-H":
arg = arg.split(":");
arg[1] = arg.slice(1).join(":").trim();
opt.headers[arg[0].toLowerCase()] = arg[1];
return;
case "--request":
case "-X":
opt.method = arg;
return;
}
if (arg === "curl") {
if (opt) {
opt.url = opt.url || argList[ii - 1];
swaggerJson = local.swaggerJsonFromAjax(swaggerJson, opt);
}
opt = {
headers: {},
method: "GET"
};
}
if ((
/^(?:http|https):\/\//
).test(arg)) {
opt.url = arg;
}
});
return swaggerJson;
}
n/a
swaggerJsonFromPostBody = function (swaggerJson, opt) {
/*
* this function will update swaggerJson
* with definitions created from the post-body-data
*/
var definition;
var isArray;
var prefix;
var schemaP;
var type;
var value;
prefix = opt.prefix + "." + encodeURIComponent(opt.key);
definition = {
properties: {},
"x-swgg-tags0": opt["x-swgg-tags0"]
};
swaggerJson.definitions[prefix] = definition;
Object.keys(opt.data).forEach(function (key) {
value = opt.data[key];
isArray = Array.isArray(value);
if (isArray) {
value = value[0];
}
type = (
local.isNullOrUndefined(value)
? "string"
: typeof value
);
schemaP = (
isArray
? {
default: opt.data[key],
items: {
type
},
type: "array"
}
: {
default: value,
type
}
);
definition.properties[key] = schemaP;
if (!(type === "object" && opt.depth > 1)) {
return;
}
// recurse
type = local.swaggerJsonFromPostBody(swaggerJson, {
data: value,
depth: opt.depth - 1,
key,
prefix,
"x-swgg-tags0": opt["x-swgg-tags0"]
});
if (isArray) {
schemaP.items = type;
} else {
definition.properties[key] = type;
}
});
return {
$ref: "#/definitions/" + prefix
};
}
...
data = JSON.parse(data);
}, local.nop);
if (typeof data !== "object") {
return swaggerJson;
}
// init param in body - json-data
isArray = Array.isArray(data);
type = local.swaggerJsonFromPostBody(swaggerJson, {
data: (
// ternary-operator
isArray
? data[0]
: data
),
depth: 2,
...
swaggerValidate = function (swaggerJson) {
/*
* this function will validate the json-object swaggerJson
*/
var operation;
var operationIdDict;
var pathDict;
var prefix;
var test;
var tmp;
operationIdDict = {};
swaggerJson = swaggerJson || {};
local.swaggerValidateDataSchema({
data: swaggerJson,
modeSchema: true,
prefix: [
"swaggerJson"
],
schema: local.swaggerSchemaJson,
swaggerJson
});
pathDict = {};
Object.keys(swaggerJson.paths).forEach(function (path) {
prefix = [
"swaggerJson", "paths", path
];
// validate semanticPaths1
test = path.indexOf("?") < 0;
local.throwSwaggerError(!test && {
errorType: "semanticPaths1",
prefix
});
tmp = path.replace((
/\{.*?\}/g
), "{}");
// validate semanticPaths2
test = !pathDict[tmp];
local.throwSwaggerError(!test && {
errorType: "semanticPaths2",
pathList: [
pathDict[tmp], path
],
prefix
});
pathDict[tmp] = path;
// validate semanticPaths3
tmp = {};
path.replace((
/\{.*?\}/g
), function (match0) {
test = !tmp[match0];
local.throwSwaggerError(!test && {
errorType: "semanticPaths3",
name: match0,
prefix
});
tmp[match0] = true;
});
// validate semanticPaths5
test = path.indexOf("{}") < 0;
local.throwSwaggerError(!test && {
errorType: "semanticPaths5",
prefix
});
});
// validate swaggerJson.definitions[key].properties[ii].default
Object.keys(swaggerJson.definitions || {}).forEach(function (schemaName) {
tmp = local.swaggerValidateDataSchema({
// dereference definition
modeDereference: true,
prefix: [
"swaggerJson", "definitions", schemaName
],
schema: swaggerJson.definitions[schemaName],
swaggerJson
});
Object.keys(tmp.properties || {}).forEach(function (key) {
local.swaggerValidateDataSchema({
modeDefault: true,
prefix: [
"swaggerJson", "definitions", schemaName, "properties", key
],
schema: tmp.properties[key],
swaggerJson
});
});
});
// validate swaggerJson.parameters[key].default
Object.keys(swaggerJson.parameters || []).forEach(function (key) {
local.swaggerValidateDataSchema({
modeDefault: true,
prefix: [
"swaggerJson", "parameters", key
],
schema: swaggerJson.parameters[key],
swaggerJson
});
});
// validate swaggerJson.paths[key][key].parameters[ii].default
Object.keys(swaggerJson.paths).forEach(function (path) {
Object.keys(swaggerJson.paths[path]).forEach(function (method) {
prefix = [
"swaggerJson", "paths", path, method
];
operation = local.swaggerValidateDataSchema({
// dereference operation
modeDereference: true,
prefix,
schema: swaggerJson.paths[path][method],
swaggerJson
});
// validate semanticOperationIds1
test = !operationIdDict[operation.operationId];
local.throwSwaggerError(!test && {
data: operation.operationId,
errorType: "semanticOperationIds1",
prefix: prefix.conc...
...
paths: pathDict
}, 3);
});
// normalize swaggerJson
local.swaggerJson = JSON.parse(local.jsonStringifyOrdered(swaggerJson));
// try to validate swaggerJson
local.tryCatchOnError(function () {
local.swaggerValidate(local.swaggerJson);
}, local.onErrorDefault);
// init corsForwardProxyHost
local.corsForwardProxyHost = (
local.corsForwardProxyHost
|| local.swaggerJson["x-swgg-corsForwardProxyHost"]
);
// init assets.swgg.swagger.server.json
...
swaggerValidateDataParameters = function (opt) {
/*
* this function will validate the items in <opt>.paramDict
* against the schemaP's in <opt>.parameters
*/
var errList;
errList = [];
opt.parameters.forEach(function (schemaP) {
local.tryCatchOnError(function () {
local.swaggerValidateDataSchema({
data: opt.data[schemaP.name],
dataReadonlyRemove: [
opt.dataReadonlyRemove || {},
schemaP.name,
opt.dataReadonlyRemove
&& opt.dataReadonlyRemove[schemaP.name]
],
prefix: opt.prefix.concat([
schemaP.name
]),
schema: schemaP,
swaggerJson: local.swaggerJson
});
}, function (errCaught) {
console.error(errCaught.message);
errList.push(errCaught);
errCaught.errList = errList;
});
});
return errList;
}
...
paramDict: {},
url: ""
});
if (opt.modeDefault) {
local.normalizeSwaggerParamDict(opt);
}
// try to validate paramDict
opt.err = local.swaggerValidateDataParameters({
// normalize paramDict
data: local.normalizeSwaggerParamDict({
modeNoDefault: opt.modeNoDefault,
operation: that,
paramDict: local.jsonCopy(opt.paramDict)
}).paramDict,
dataReadonlyRemove: opt.paramDict,
...
swaggerValidateDataSchema = function (opt) {
/*
* this function will validate <opt>.data against the swagger <opt>.schema
* http://json-schema.org/draft-04/json-schema-validation.html#rfc.section.5
*/
var $ref;
var circularSet;
var data;
var dataReadonlyRemove2;
var ii;
var list;
var oneOf;
var schema;
var test;
var tmp;
if (!opt.schema) {
return;
}
data = opt.data;
opt.dataReadonlyRemove = opt.dataReadonlyRemove || [
{}, "", null
];
dataReadonlyRemove2 = opt.dataReadonlyRemove[2] || {};
schema = opt.schema;
circularSet = new Set();
while (true) {
// dereference schema.schema
while (schema.schema) {
schema = schema.schema;
}
// dereference schema.oneOf
oneOf = (data && schema.oneOf) || [];
ii = 0;
while (ii < oneOf.length) {
tmp = String(oneOf[ii] && oneOf[ii].$ref)
.replace("http://json-schema.org/draft-04/schema#", "#");
switch (
tmp + " " + (!local.isNullOrUndefined(data.$ref) || data.in)
) {
case "#/definitions/bodyParameter body":
case "#/definitions/formDataParameterSubSchema formData":
case "#/definitions/headerParameterSubSchema header":
case "#/definitions/jsonReference true":
case "#/definitions/pathParameterSubSchema path":
case "#/definitions/queryParameterSubSchema query":
schema = local.swaggerSchemaJson.definitions[tmp.split("/")[2]];
break;
default:
switch (tmp) {
case "#/definitions/bodyParameter":
case "#/definitions/jsonReference":
schema = oneOf[ii ^ 1];
break;
}
}
if (!schema.oneOf) {
break;
}
ii += 1;
}
// dereference schema.$ref
$ref = schema && schema.$ref;
if (!$ref) {
break;
}
test = !circularSet.has($ref);
local.throwSwaggerError(!test && {
data,
errorType: "schemaDereferenceCircular",
prefix: opt.prefix,
schema
});
circularSet.add($ref);
// validate semanticWalker6
test = (
$ref.indexOf("#/") === 0
|| $ref.indexOf("http://json-schema.org/draft-04/schema#/") === 0
);
local.throwSwaggerError(!test && {
data: $ref,
errorType: "semanticWalker6",
prefix: opt.prefix.concat([
"$ref"
])
});
switch (opt.modeSchema && $ref) {
case "http://json-schema.org/draft-04/schema#/definitions/parameter":
// validate semanticFormData1
test = data.in !== "formdata";
local.throwSwaggerError(!test && {
data: data.in,
errorType: "semanticFormData1",
prefix: opt.prefix.concat([
"in"
])
});
// validate semanticFormData3
test = data.type !== "file" || data.in === "formData";
local.throwSwaggerError(!test && {
data,
errorType: "semanticFormData3",
prefix: opt.prefix
});
// validate semanticParameters2
test = data.in === "body" || !local.isNullOrUndefined(data.type);
local.throwSwaggerError(!test && {
data,
errorType: "semanticParameters2",
prefix: o...
...
local.swaggerJsonBasePath = (
local.swaggerJson.basePath === "/"
? ""
: local.swaggerJson.basePath
);
Object.keys(swaggerJson.definitions).forEach(function (schemaName) {
swaggerJson.definitions[schemaName] = local.jsonCopy(
local.swaggerValidateDataSchema({
// dereference definition
modeDereference: true,
prefix: [
"swaggerJson", "definitions", schemaName
],
schema: swaggerJson.definitions[schemaName],
swaggerJson: local.swaggerJson
...
swaggerValidateFile = function (opt, onError) {
/*
* this function will validate the json-file <opt>.file
*/
local.onNext(opt, function (err, data) {
switch (opt.modeNext) {
case 1:
if (typeof opt.data === "string") {
opt.onNext(null, opt.data);
return;
}
// fetch url
if ((
/^(?:http|https):\/\//
).test(opt.file)) {
local.ajax({
url: opt.file
}, function (err, xhr) {
opt.onNext(err, xhr && xhr.responseText);
});
return;
}
// read file
local.fs.readFile(opt.file, "utf8", opt.onNext);
break;
case 2:
// jslint
local.jslint.jslintAndPrint(data, opt.file);
local.assertThrow(
!local.jslint.jslintResult.errText,
local.jslint.jslintResult.errText.replace((
/\u001b\[\d*m/g
), "")
);
// validate
local.swgg.swaggerValidate(JSON.parse(data));
opt.onNext();
break;
default:
console.error(
err
? "\u001b[31mswagger-validate - failed - " + opt.file + "\n"
+ err.message + "\u001b[39m"
: "swagger-validate - passed - " + opt.file
);
onError(err);
}
});
opt.modeNext = 0;
opt.onNext();
}
...
local.cliDict["utility2.swaggerValidateFile"] = function () {
/*
* <file/url>
* will swagger-validate file/url
*/
setTimeout(function () {
local.swgg.swaggerValidateFile({
file: process.argv[3]
}, function (err, data) {
console.error(data);
process.exit(err);
});
});
};
...
taskCreate = function (opt, onTask, onError) {
/*
* this function will create the task onTask named <opt>.key,
* if it does not exist, and push onError to its onErrorList
*/
var task;
// init task
local.taskOnTaskDict[opt.key] = (
local.taskOnTaskDict[opt.key]
|| {
onErrorList: []
}
);
task = local.taskOnTaskDict[opt.key];
// push callback onError to the task
if (onError) {
onError = local.onErrorWithStack(onError);
task.onErrorList.push(onError);
}
// if task exists, then return it
if (!onTask || task.onTask) {
return task;
}
task.onDone = function (err, data, meta) {
// if isDone, then do nothing
if (task.isDone) {
return;
}
task.isDone = true;
// cleanup timerTimeout
clearTimeout(task.timerTimeout);
// cleanup task
delete local.taskOnTaskDict[opt.key];
// preserve err.message and err.stack
task.result = JSON.stringify([
(
(err && err.stack)
? Object.assign(local.jsonCopy(err), {
message: err.message,
name: err.name,
stack: err.stack
})
: err
), data, meta
]);
// pass result to callbacks in onErrorList
task.onErrorList.forEach(function (onError) {
onError.apply(null, JSON.parse(task.result));
});
};
// init timerTimeout
task.timerTimeout = local.onTimeout(
task.onDone,
opt.timeout || local.timeoutDefault,
"taskCreate " + opt.key
);
task.onTask = onTask;
// run onTask
task.onTask(task.onDone);
return task;
}
...
}
}
// run background-task with lower priority for cache-hit
setTimeout(opt.onNext, opt.modeCacheHit && opt.cacheTtl);
break;
// 2. run onTask in background to update cache
case 2:
local.taskCreate(opt, onTask, opt.onNext);
break;
default:
// 3. save onTask's result to cache
// JSON.stringify data to prevent side-effects on cache
opt.cacheValue = JSON.stringify(data);
if (!err && opt.cacheValue) {
local.cacheDict[opt.cacheDict][opt.key] = opt.cacheValue;
...
taskCreateCached = function (opt, onTask, onError) {
/*
* this function will
* 1. if cache-hit, then call onError with cacheValue
* 2. run onTask in background to update cache
* 3. save onTask's result to cache
* 4. if cache-miss, then call onError with onTask's result
*/
local.onNext(opt, function (err, data) {
switch (opt.modeNext) {
// 1. if cache-hit, then call onError with cacheValue
case 1:
// read cacheValue from memory-cache
local.cacheDict[opt.cacheDict] = (
local.cacheDict[opt.cacheDict]
|| {}
);
opt.cacheValue = local.cacheDict[opt.cacheDict][opt.key];
if (opt.cacheValue) {
// call onError with cacheValue
opt.modeCacheHit = true;
onError(null, JSON.parse(opt.cacheValue));
if (!opt.modeCacheUpdate) {
break;
}
}
// run background-task with lower priority for cache-hit
setTimeout(opt.onNext, opt.modeCacheHit && opt.cacheTtl);
break;
// 2. run onTask in background to update cache
case 2:
local.taskCreate(opt, onTask, opt.onNext);
break;
default:
// 3. save onTask's result to cache
// JSON.stringify data to prevent side-effects on cache
opt.cacheValue = JSON.stringify(data);
if (!err && opt.cacheValue) {
local.cacheDict[opt.cacheDict][opt.key] = opt.cacheValue;
}
// 4. if cache-miss, then call onError with onTask's result
if (!opt.modeCacheHit) {
onError(err, opt.cacheValue && JSON.parse(opt.cacheValue));
}
local.functionOrNop(opt.onCacheWrite)();
}
});
opt.modeNext = 0;
opt.onNext();
}
...
).test(req.headers["accept-encoding"])
) {
opt.modeNext += 1;
opt.onNext();
return;
}
// gzip and cache result
local.taskCreateCached({
cacheDict: "middlewareAssetsCachedGzip",
key: req.urlParsed.pathname
}, function (onError) {
local.zlib.gzip(opt.result, function (err, data) {
onError(err, !err && data.toString("base64"));
});
}, opt.onNext);
...
templateRender = function (template, dict, opt) {
/*
* this function will render the template with given dict
*/
var argList;
var getValue;
var match;
var renderPartial;
var rgx;
var skip;
var value;
dict = dict || {};
opt = opt || {};
getValue = function (key) {
argList = key.split(" ");
value = dict;
if (argList[0] === "#this/") {
return;
}
// iteratively lookup nested values in the dict
argList[0].split(".").forEach(function (key) {
value = value && value[key];
});
return value;
};
renderPartial = function (match0, helper, key, partial) {
switch (helper) {
case "each":
case "eachTrimRightComma":
value = getValue(key);
value = (
Array.isArray(value)
? value.map(function (dict) {
// recurse with partial
return local.templateRender(partial, dict, opt);
}).join("")
: ""
);
// remove trailing-comma from last elem
if (helper === "eachTrimRightComma") {
value = value.trimRight().replace((
/,$/
), "");
}
return value;
case "if":
partial = partial.split("{{#unless " + key + "}}");
partial = (
getValue(key)
? partial[0]
// handle 'unless' case
: partial.slice(1).join("{{#unless " + key + "}}")
);
// recurse with partial
return local.templateRender(partial, dict, opt);
case "unless":
return (
getValue(key)
? ""
// recurse with partial
: local.templateRender(partial, dict, opt)
);
default:
// recurse with partial
return match0[0] + local.templateRender(match0.slice(1), dict, opt);
}
};
// render partials
rgx = (
/\{\{#(\w+)\u0020([^}]+?)\}\}/g
);
template = template || "";
match = rgx.exec(template);
while (match) {
rgx.lastIndex += 1 - match[0].length;
template = template.replace(
new RegExp(
"\\{\\{#(" + match[1] + ") (" + match[2]
+ ")\\}\\}([\\S\\s]*?)\\{\\{/" + match[1] + " " + match[2]
+ "\\}\\}"
),
renderPartial
);
match = rgx.exec(template);
}
// search for keys in the template
return template.replace((
/\{\{[^}]+?\}\}/g
), function (match0) {
var markdownToHtml;
var notHtmlSafe;
notHtmlSafe = opt.notHtmlSafe;
try {
getValue(match0.slice(2, -2));
if (value === undefined) {
return match0;
}
argList.slice(1).forEach(function (arg0, ii, list) {
switch (arg0) {
case "alphanumeric":
value = value.replace((
/\W/g
), "_");
break;
case "decodeURIComponent":
value = decodeURIComponent(value);
break;
case "encodeURIComponent":
value = encodeURIComponent(value);
break;
case "jsonStringify":
value = JSON.stringify(value);
break;
case "jsonStringify4":
value = JSON.stringify(value, null, 4);
break;
case "markdownSafe&qu...
...
case "each":
case "eachTrimRightComma":
value = getValue(key);
value = (
Array.isArray(value)
? value.map(function (dict) {
// recurse with partial
return local.templateRender(partial, dict, opt);
}).join("")
: ""
);
// remove trailing-comma from last elem
if (helper === "eachTrimRightComma") {
value = value.trimRight().replace((
/,$/
...
templateRenderMyApp = function (template, opt) {
/*
* this function will render my-app-lite template with given <opt>.packageJson
*/
opt.packageJson = local.fsReadFileOrEmptyStringSync("package.json", "json");
local.objectSetDefault(opt.packageJson, {
nameLib: opt.packageJson.name.replace((
/\W/g
), "_"),
repository: {
url: (
"https://github.com/kaizhu256/node-"
+ opt.packageJson.name
+ ".git"
)
}
}, 2);
opt.githubRepo = opt.packageJson.repository.url.replace((
/\.git$/
), "").split("/").slice(-2);
template = template.replace((
/kaizhu256(\.github\.io\/|%252F|\/)/g
), opt.githubRepo[0] + ("$1"));
template = template.replace((
/node-my-app-lite/g
), opt.githubRepo[1]);
template = template.replace((
/\bh1-my-app\b/g
), (
opt.packageJson.nameHeroku
|| ("h1-" + opt.packageJson.nameLib.replace((
/_/g
), "-"))
));
template = template.replace((
/my-app-lite/g
), opt.packageJson.name);
template = template.replace((
/my_app/g
), opt.packageJson.nameLib);
template = template.replace((
/\{\{packageJson\.(\S+)\}\}/g
), function (ignore, match1) {
return opt.packageJson[match1];
});
return template;
}
...
var result;
local.objectSetDefault(opt, {
customize: local.nop,
dataFrom: local.fsReadFileOrEmptyStringSync(
"lib." + local.env.npm_package_nameLib + ".js",
"utf8"
),
dataTo: local.templateRenderMyApp(
local.assetsDict["/assets.my_app.template.js"],
opt
)
});
// search-and-replace - customize dataTo
[
// customize top-level comment-description
...
testMock = function (mockList, onTestCase, onError) {
/*
* this function will mock the objects in mockList while running the onTestCase
*/
var onError2;
onError2 = function (err) {
// restore mock[0] from mock[2]
mockList.reverse().forEach(function (mock) {
Object.keys(mock[2]).forEach(function (key) {
mock[0][key] = mock[2][key];
});
});
onError(err);
};
// suppress console.error and console.log
if (!(mockList[0] && mockList[0][0] === console)) {
mockList.unshift([
console, {}
]);
}
local.objectSetDefault(mockList[0][1], {
error: local.nop,
log: local.nop
});
// mock-objects
mockList.forEach(function (mock) {
mock[2] = {};
// backup mock[0] into mock[2]
Object.keys(mock[1]).forEach(function (key) {
mock[2][key] = (
// ternary-operator
(
typeof process === "object"
&& process.env === mock[0]
&& mock[0][key] === undefined
)
// handle process.env
? ""
: mock[0][key]
);
});
// override mock[0] with mock[1]
Object.keys(mock[1]).forEach(function (key) {
mock[0][key] = mock[1][key];
});
});
// try to call onError with mock-objects
local.tryCatchOnError(function () {
// run onTestCase
onTestCase(onError2);
}, onError2);
}
...
mockDict[key]();
}
});
mockList.push([
tmp, mockDict
]);
});
local.testMock(mockList, function (onError) {
local.tryCatchOnError(function () {
exports = require(file);
}, local.onErrorDefault);
onError();
}, local.onErrorThrow);
return exports;
};
...
testReportCreate = function (testReport) {
/*
* this function will create test-report artifacts
*/
testReport = local.objectSetDefault(testReport, {
testPlatformList: []
});
// print test-report summary
console.error(
"\n" + new Array(56).join("-")
+ "\n" + testReport.testPlatformList.filter(function (testPlatform) {
// if testPlatform has no tests, then filter it out
return testPlatform.testCaseList.length;
}).map(function (testPlatform) {
return (
"| test-report - " + testPlatform.name + "\n|"
+ (" " + testPlatform.timeElapsed + " ms ")
.slice(-16)
+ (" " + testPlatform.testsFailed + " failed ")
.slice(-16)
+ (" " + testPlatform.testsPassed + " passed ")
.slice(-16) + " |\n" + new Array(56).join("-")
);
}).join("\n") + "\n"
);
// create test-report.html
local.fs.writeFileSync(
"tmp/build/test-report.html",
local.testReportMerge(testReport, {})
);
// create build.badge.svg
local.fs.writeFileSync(
"tmp/build/build.badge.svg",
local.assetsDict["/assets.buildBadge.template.svg"].replace((
/0000-00-00\u002000:00:00\u0020UTC\u0020-\u0020master\u0020-\u0020aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/g
), (
new Date().toISOString().slice(0, 19).replace("T", " ")
+ " - " + local.env.CI_BRANCH + " - " + local.env.CI_COMMIT_ID
))
);
// create test-report.badge.svg
local.fs.writeFileSync(
"tmp/build/test-report.badge.svg",
local.assetsDict["/assets.testReportBadge.template.svg"]
// edit number of tests failed
.replace((
/999/g
), testReport.testsFailed)
// edit badge color
.replace((
/d00/g
), (
testReport.testsFailed
? "d00"
: "0d0"
))
);
console.error(
"created test-report file "
+ process.cwd() + "/tmp/build/test-report.html\n"
);
// if any test failed, then exit with non-zero exit-code
console.error(
"\n" + local.env.MODE_BUILD
+ " - " + testReport.testsFailed + " failed tests\n"
);
// print failed testCase
testReport.testPlatformList.forEach(function (testPlatform) {
testPlatform.testCaseList.forEach(function (testCase) {
if (testCase.status !== "passed") {
console.error(JSON.stringify(testCase, null, 4));
}
});
});
return testReport;
}
...
local.cliDict["utility2.testReportCreate"] = function () {
/*
*
* will create test-report
*/
local.exit(
local.testReportCreate(
JSON.parse(local.fs.readFileSync(
local.env.npm_config_dir_build + "/test-report.json"
))
).testsFailed
);
};
}());
...
testReportMerge = function (testReport1, testReport2) {
/*
* this function will
* 1. merge testReport2 into testReport1
* 2. return testReport1 in html-format
*/
var errorStackList;
var testCaseNumber;
var testReport;
testReport2 = testReport2 || {};
// 1. merge testReport2 into testReport1
[
testReport1, testReport2
].forEach(function (testReport, ii) {
ii += 1;
local.objectSetDefault(testReport, {
date: new Date().toISOString(),
errorStackList: [],
testPlatformList: [],
timeElapsed: 0
}, 8);
// security - handle malformed testReport
local.assertThrow(
typeof testReport === "object" && testReport,
ii + " invalid testReport " + typeof testReport
);
// validate timeElapsed
local.assertThrow(
typeof testReport.timeElapsed === "number",
ii + " invalid testReport.timeElapsed "
+ typeof testReport.timeElapsed
);
// security - handle malformed testReport.testPlatformList
testReport.testPlatformList.forEach(function (testPlatform) {
local.objectSetDefault(testPlatform, {
name: "undefined",
testCaseList: [],
timeElapsed: 0
}, 8);
local.assertThrow(
typeof testPlatform.name === "string",
ii + " invalid testPlatform.name " + typeof testPlatform.name
);
// insert $MODE_BUILD into testPlatform.name
if (local.env.MODE_BUILD) {
testPlatform.name = testPlatform.name.replace((
/^(browser|node)\b/
), local.env.MODE_BUILD + " - $1");
}
// validate timeElapsed
local.assertThrow(
typeof testPlatform.timeElapsed === "number",
(
ii + " invalid testPlatform.timeElapsed "
+ typeof testPlatform.timeElapsed
)
);
// security - handle malformed testPlatform.testCaseList
testPlatform.testCaseList.forEach(function (testCase) {
local.objectSetDefault(testCase, {
errorStack: "",
name: "undefined",
timeElapsed: 0
}, 8);
local.assertThrow(
typeof testCase.errorStack === "string",
ii + " invalid testCase.errorStack "
+ typeof testCase.errorStack
);
local.assertThrow(
typeof testCase.name === "string",
ii + " invalid testCase.name " + typeof testCase.name
);
// validate timeElapsed
local.assertThrow(
typeof testCase.timeElapsed === "number",
(
ii + " invalid testCase.timeElapsed "
+ typeof testCase.timeElapsed
)
);
});
});
});
// merge testReport2.testPlatformList into testReport1.testPlatformList
testReport2.testPlatformList.forEach(function (testPlatform2) {
// add testPlatform2 to testReport1.testPlatformList
testReport1.testPlatformList.push(testPlatform2);
});
testReport = testReport1;
testReport.testsFailed = 0;
testReport.testsPassed = 0;
testReport.testsPending = 0;
testReport.testPlatformList.forEach(function (testPlatform) {
testPlatform.testsFailed = 0;
testPlatform.testsPassed = 0;
testPlatform.testsPending = 0;
testPlatform.testCaseList.forEach(function (testCase) {
switch (testCase.status) {
//...
...
+ "\n"
);
// merge browser test-report
data = local.fsReadFileOrEmptyStringSync(
opt.fileTestReport,
"json"
);
local.testReportMerge(
window.utility2_testReport,
!opt.modeSilent && data
);
console.error(
"\nbrowserTest - merged test-report from file "
+ opt.fileTestReport
+ "\n"
...
testRunDefault = function (opt) {
/*
* this function will run the tests in testPlatform.testCaseList
*/
var processExit;
var testPlatform;
var testReport;
var testReportDiv1;
var timerInterval;
// run-server
if (!local.isBrowser) {
local.testRunServer(opt);
}
globalThis.utility2_modeTest = Number(
globalThis.utility2_modeTest
|| opt.modeTest
|| local.modeTest
|| local.env.npm_config_mode_test
);
switch (globalThis.utility2_modeTest) {
// init
case 1:
globalThis.utility2_modeTest += 1;
// reset db
if (local.db && typeof local.db.dbReset === "function") {
local.db.dbReset(
globalThis.utility2_dbSeedList,
local.onErrorThrow
);
}
globalThis.utility2_onReadyAfter(function () {
local.testRunDefault(opt);
});
return;
// test-run
default:
// test-ignore
if (
globalThis.utility2_onReadyBefore.counter
|| !globalThis.utility2_modeTest
|| globalThis.utility2_modeTest > 2
) {
return;
}
// test-run
globalThis.utility2_modeTest += 1;
}
// visual notification - testRun
local.ajaxProgressUpdate();
// mock serverLog
local._testRunConsoleError = local._testRunConsoleError || console.error;
console.error = function (arg0) {
/*
* this function will ignore serverLog-messages during test-run
*/
/* istanbul ignore next */
if (!globalThis.__coverage__ && !(
/^serverLog\u0020-\u0020\{/
).test(arg0)) {
local._testRunConsoleError.apply(console, arguments); // jslint ignore:line
}
};
if (!local.isBrowser) {
// mock proces.exit
processExit = process.exit;
process.exit = local.nop;
}
// init modeTestCase
local.modeTestCase = (
local.modeTestCase
|| local.env.npm_config_mode_test_case || ""
);
// init testReport
testReport = globalThis.utility2_testReport;
// init testReport timer
local.timeElapsedStart(testReport);
// init testPlatform
testPlatform = testReport.testPlatformList[0];
// init testPlatform timer
local.timeElapsedStart(testPlatform);
// reset testPlatform.testCaseList
testPlatform.testCaseList.length = 0;
// add tests into testPlatform.testCaseList
Object.keys(opt).forEach(function (key) {
// add testCase opt[key] to testPlatform.testCaseList
if (
typeof opt[key] === "function" && (
local.modeTestCase
? local.modeTestCase.split(
/[,\s]/g
).indexOf(key) >= 0
: key.indexOf("testCase_") === 0
)
) {
testPlatform.testCaseList.push({
isBrowser: local.isBrowser,
name: key,
status: "pending",
onTestCase: opt[key]
});
}
});
// visual notification - update test-progress until isDone
// init testReportDiv1 elem
if (local.isBrowser) {
testReportDiv1 = document.querySelector(
"#testReportDiv1"
);
}
testReportDiv1 = testReportDiv1 || {
style: {}
};
local.uiAnimateSlideDown(testReportDiv1);
testReportDiv1.innerHTML = local.testReportMerge(testReport, {});
// update test-report status every 1000 ms until isDone
timerInterval = setInterval(function () {
// update testPlatform.timeElapsed
local.timeElapsedPoll(testPlatform);
// update testReportDiv1 in browser
testReportDiv1.innerHTML = local.testReportMerge(testReport, {});
if (!testReport.testsPending) {
// cleanup timerInterval
clearInterval(timerInterval);
}
// notify of...
...
local.uiAnimateSlideDown(document.querySelector(\n\
"#testReportDiv1"\n\
));\n\
document.querySelector(\n\
"#testRunButton1"\n\
).textContent = "hide internal test";\n\
local.modeTest = 1;\n\
local.testRunDefault(local);\n\
return;\n\
}\n\
// hide browser-tests\n\
local.uiAnimateSlideUp(document.querySelector(\n\
"#testReportDiv1"\n\
));\n\
document.querySelector(\n\
...
testRunServer = function (opt) {
/*
* this function will
* 1. create server from local.middlewareList
* 2. start server on local.env.PORT
* 3. run tests
*/
if (globalThis.utility2_serverHttp1) {
return;
}
globalThis.utility2_onReadyBefore.counter += 1;
// 1. create server from local.middlewareList
local.middlewareList = local.middlewareList || [
local.middlewareInit,
local.middlewareForwardProxy,
local.middlewareAssetsCached,
local.middlewareJsonpStateInit,
local.middlewareFileServer
];
local.serverLocalReqHandler = function (req, res) {
var that;
that = {};
local.onNext(that, function (err) {
if (err || that.modeNext >= local.middlewareList.length) {
local.middlewareError(err, req, res);
return;
}
// recurse with next middleware in middlewareList
local.middlewareList[that.modeNext](req, res, that.onNext);
});
that.modeNext = -1;
that.onNext();
};
globalThis.utility2_serverHttp1 = local.http.createServer(
local.serverLocalReqHandler
);
// 2. start server on local.env.PORT
if (local.env.npm_config_mode_library) {
globalThis.utility2_onReadyBefore();
return;
}
console.error("http-server listening on port " + local.env.PORT);
globalThis.utility2_onReadyBefore.counter += 1;
globalThis.utility2_serverHttp1.listen(
local.env.PORT,
globalThis.utility2_onReadyBefore
);
// 3. run tests
local.testRunDefault(opt);
globalThis.utility2_onReadyBefore();
}
...
/*
* <port>
* will start utility2 http-server on given <port> (default 8081)
*/
local.env.PORT = process.argv[3] || local.env.PORT;
globalThis.local = local;
local.replStart();
local.testRunServer({});
};
local.cliDict["utility2.swaggerValidateFile"] = function () {
/*
* <file/url>
* will swagger-validate file/url
*/
...
throwError = function () {
/*
* this function will throw new err
*/
throw new Error();
}
...
};
local.testCase_throwError_default = function (opt, onError) {
/*
* this function will test throwError's default handling-behavior
*/
local.tryCatchOnError(function () {
local.throwError();
}, function (err) {
// validate err occurred
local.assertThrow(err, err);
onError(null, opt);
});
};
...
throwSwaggerError = function (opt) {
/*
* this function will throw a swaggerError with given <opt>.errorType
*/
var err;
if (!opt) {
return;
}
[
0, 2
].forEach(function (ii) {
opt["prefix" + ii] = opt.prefix[ii] + opt.prefix.slice(
ii + 1
).map(function (element) {
return "[" + JSON.stringify(element) + "]";
}).join("");
});
opt.prefix0 += " = " + local.stringTruncate(
JSON.stringify(opt.data) || "undefined",
100
);
opt.schema2 = local.stringTruncate(
JSON.stringify(opt.schema) || "undefined",
500
);
opt.type2 = (opt.schema && local.schemaPType(opt.schema)) || "object";
if (opt.schema && opt.schema.format) {
opt.type2 += " (" + opt.schema.format + ")";
}
err = new Error("error." + opt.errorType + " - " + local.templateRender(
local.swaggerErrorTypeDict[opt.errorType],
opt,
{
notHtmlSafe: true
}
));
err.messageShort = local.templateRender(
local.swaggerErrorTypeDict[opt.errorType].replace(
"{{prefix0}}",
"{{prefix2}}"
),
opt,
{
notHtmlSafe: true
}
);
err.opt = opt;
err.statusCode = 400;
throw err;
}
...
pathDict = {};
Object.keys(swaggerJson.paths).forEach(function (path) {
prefix = [
"swaggerJson", "paths", path
];
// validate semanticPaths1
test = path.indexOf("?") < 0;
local.throwSwaggerError(!test && {
errorType: "semanticPaths1",
prefix
});
tmp = path.replace((
/\{.*?\}/g
), "{}");
// validate semanticPaths2
...
timeElapsedPoll = function (opt) {
/*
* this function will poll <opt>.timeElapsed
*/
opt = local.timeElapsedStart(opt);
opt.timeElapsed = Date.now() - opt.timeStart;
return opt;
}
...
> bb.status.replace("passed", "z") + bb.name
? 1
: -1
);
});
// stop testReport timer
if (!testReport.testsPending) {
local.timeElapsedPoll(testReport);
}
// 2. return testReport1 in html-format
// json-copy testReport that will be modified for html templating
testReport = local.jsonCopy(testReport1);
// update timeElapsed
local.timeElapsedPoll(testReport);
testReport.testPlatformList.forEach(function (testPlatform) {
...
timeElapsedStart = function (opt, timeStart) {
/*
* this function will start <opt>.timeElapsed
*/
opt = opt || {};
opt.timeStart = timeStart || opt.timeStart || Date.now();
return opt;
}
...
local.modeTestCase = (
local.modeTestCase
|| local.env.npm_config_mode_test_case || ""
);
// init testReport
testReport = globalThis.utility2_testReport;
// init testReport timer
local.timeElapsedStart(testReport);
// init testPlatform
testPlatform = testReport.testPlatformList[0];
// init testPlatform timer
local.timeElapsedStart(testPlatform);
// reset testPlatform.testCaseList
testPlatform.testCaseList.length = 0;
// add tests into testPlatform.testCaseList
...
tryCatchOnError = function (fnc, onError) {
/*
* this function will run the fnc in a tryCatch block,
* else call onError with errCaught
*/
var result;
// validate onError
local.assertThrow(typeof onError === "function", typeof onError);
try {
// reset errCaught
local._debugTryCatchError = null;
result = fnc();
local._debugTryCatchError = null;
return result;
} catch (errCaught) {
// debug errCaught
local._debugTryCatchError = errCaught;
return onError(errCaught);
}
}
...
return elem;
};
readExample = function (file) {
/*
* this function will read the example from given file
*/
var result;
local.tryCatchOnError(function () {
file = local.path.resolve(opt.dir, file);
console.error("apidocCreate - readExample " + file);
result = "";
result = (
"\n\n\n\n\n\n\n\n"
// bug-workaround - truncate example to manageable size
+ local.fs.readFileSync(file, "utf8").slice(0, 262144)
...
uiAnimateShake = function (elem, onError) {
/*
* this function will shake dom-<elem>
*/
if (!elem || elem.classList.contains("uiAnimateShake")) {
local.setTimeoutOnError(onError);
return;
}
elem.classList.add("uiAnimateShake");
setTimeout(function () {
elem.classList.remove("uiAnimateShake");
local.setTimeoutOnError(onError);
}, 500);
}
...
if (!elem) {
local.setTimeoutOnError(onError);
return;
}
hasError = elem.classList.contains("hasError");
if (err && !hasError) {
elem.classList.add("hasError");
local.uiAnimateShake(elem, onError);
return;
}
if (!err && hasError) {
elem.classList.remove("hasError");
}
local.setTimeoutOnError(onError);
};
...
uiAnimateShakeIfError = function (err, elem, onError) {
/*
* this function will shake dom-<elem> if <err> occurred
*/
var hasError;
if (!elem) {
local.setTimeoutOnError(onError);
return;
}
hasError = elem.classList.contains("hasError");
if (err && !hasError) {
elem.classList.add("hasError");
local.uiAnimateShake(elem, onError);
return;
}
if (!err && hasError) {
elem.classList.remove("hasError");
}
local.setTimeoutOnError(onError);
}
...
errorDict[err.opt.prefix[2]] = err;
});
// shake input on err
Array.from(opt.targetOnEvent.querySelectorAll(
".schemaP[data-name]"
)).forEach(function (element) {
tmp = errorDict[element.dataset.name];
local.uiAnimateShakeIfError(tmp, element.querySelector(
".input"
));
element.querySelector(
".colorError"
).textContent = (
tmp
? tmp.messageShort
...
uiAnimateSlideAccordian = function (elem, elemList, onError) {
/*
* this function will slideDown <elem>, but slideUp elements in <elemList>
*/
elemList.forEach(function (elem2) {
if (elem2 !== elem) {
local.uiAnimateSlideUp(elem2);
}
});
setTimeout(function () {
local.uiAnimateSlideDown(elem, onError);
}, 250);
}
...
// show parent resource
local.uiAnimateSlideDown(element.closest(
".resource"
).querySelector(
".operationList"
));
// show the operation, but hide all other operations
local.uiAnimateSlideAccordian(
element.querySelector(
".operation > form"
),
Array.from(element.closest(
".operationList"
).querySelectorAll(
".operation > form"
...
uiAnimateSlideDown = function (elem, onError) {
/*
* this function will slideDown dom-<elem>
*/
onError = onError || local.nop;
if (!(
elem
&& elem.style && elem.style.maxHeight !== "100%"
&& elem.classList && elem.classList.contains("uiAnimateSlide")
)) {
onError();
return;
}
elem.style.borderBottom = "";
elem.style.borderTop = "";
elem.style.marginBottom = "";
elem.style.marginTop = "";
elem.style.maxHeight = 1.5 * globalThis.innerHeight + "px";
elem.style.paddingBottom = "";
elem.style.paddingTop = "";
setTimeout(function () {
elem.style.maxHeight = "100%";
onError();
}, 250);
}
...
".operation"
);
location.hash = "!" + element.id;
element.closest(
".resource"
).classList.remove("expanded");
// show parent resource
local.uiAnimateSlideDown(element.closest(
".resource"
).querySelector(
".operationList"
));
// show the operation, but hide all other operations
local.uiAnimateSlideAccordian(
element.querySelector(
...
uiAnimateSlideUp = function (elem, onError) {
/*
* this function will slideUp dom-<elem>
*/
if (!(
elem
&& elem.style && elem.style.maxHeight !== "0px"
&& elem.classList && elem.classList.contains("uiAnimateSlide")
)) {
local.setTimeoutOnError(onError);
return;
}
elem.style.borderBottom = "0";
elem.style.borderTop = "0";
elem.style.marginBottom = "0";
elem.style.marginTop = "0";
elem.style.maxHeight = "0";
elem.style.paddingBottom = "0";
elem.style.paddingTop = "0";
local.setTimeoutOnError(onError, 250);
}
...
);
// collapse all operations in the resource
if (evt.currentTarget.classList.contains("expanded")) {
evt.currentTarget.classList.remove("expanded");
Array.from(evt.currentTarget.querySelectorAll(
".operation > form"
)).forEach(function (element) {
local.uiAnimateSlideUp(element);
});
// expand all operations in the resource
} else {
evt.currentTarget.classList.add("expanded");
Array.from(evt.currentTarget.querySelectorAll(
".operation > form"
)).forEach(function (element) {
...
uiEventDelegate = function (event) { // filter non-input keyup-event event.targetOnEvent = event.target.closest( "[data-onevent]" ); if (!event.targetOnEvent) { return; } // rate-limit keyup if (event.type === "keyup") { local.uiEventDelegateKeyupEvent = event; if (local.uiEventDelegateKeyupTimerTimeout !== 2) { local.uiEventDelegateKeyupTimerTimeout = ( local.uiEventDelegateKeyupTimerTimeout || setTimeout(function () { local.uiEventDelegateKeyupTimerTimeout = 2; local.uiEventDelegate(local.uiEventDelegateKeyupEvent); }, 100) ); return; } local.uiEventDelegateKeyupTimerTimeout = null; if (!event.target.closest( "input, option, select, textarea" )) { return; } } switch (event.targetOnEvent.tagName) { case "BUTTON": case "FORM": event.preventDefault(); break; } event.stopPropagation(); local.uiEventListenerDict[event.targetOnEvent.dataset.onevent](event); }
...
if (event.type === "keyup") {
local.uiEventDelegateKeyupEvent = event;
if (local.uiEventDelegateKeyupTimerTimeout !== 2) {
local.uiEventDelegateKeyupTimerTimeout = (
local.uiEventDelegateKeyupTimerTimeout
|| setTimeout(function () {
local.uiEventDelegateKeyupTimerTimeout = 2;
local.uiEventDelegate(local.uiEventDelegateKeyupEvent);
}, 100)
);
return;
}
local.uiEventDelegateKeyupTimerTimeout = null;
if (!event.target.closest(
"input, option, select, textarea"
...
uiRenderSchemaP = function (schemaP) {
/*
* this function will render schemaP
*/
// init schemaP.id
schemaP.id = local.idDomElementCreate("swgg_id_" + schemaP.name);
// init enum
schemaP.enum2 = (
schemaP.enum
|| (local.schemaPItems(schemaP) || {}).enum
|| (local.schemaPType(schemaP) === "boolean" && [
false, true
])
);
// init input - file
if (local.schemaPType(schemaP) === "file") {
schemaP.isFile = true;
// init input - textarea
} else if (schemaP.in === "body") {
schemaP.isTextarea = true;
// init input - select
} else if (schemaP.enum2) {
// init enumDefault
schemaP.enumDefault = [];
if (schemaP.required && schemaP.default !== undefined) {
schemaP.enumDefault = (
local.schemaPType(schemaP) === "array"
? schemaP.default
: [
schemaP.default
]
);
}
schemaP.isSelectMultiple = local.schemaPType(schemaP) === "array";
schemaP.selectOptionList = schemaP.enum2.map(function (element) {
// init hasDefault
schemaP.hasDefault = (
schemaP.hasDefault
|| schemaP.enumDefault.indexOf(element) >= 0
);
return {
id: local.idDomElementCreate("swgg_id_" + schemaP.name),
selected: (
// ternary-operator
schemaP.enumDefault.indexOf(element) >= 0
? "selected"
: ""
),
type: (
local.schemaPItemsType(schemaP)
|| local.schemaPType(schemaP)
),
placeholder: (
// ternary-operator
typeof element === "string"
? element
: JSON.stringify(element)
),
valueSelectOption: element
};
});
// init 'undefined' value
if (!schemaP.required && !schemaP.hasDefault) {
schemaP.selectOptionList.unshift({
id: local.idDomElementCreate("swgg_id_" + schemaP.name),
selected: "selected",
type: local.schemaPType(schemaP),
placeholder: "<none>",
valueSelectOption: "$swggUndefined"
});
}
// select at least one value
schemaP.selectOptionList.some(function (element, ii) {
if (ii === 0 || element.selected) {
element.selected = "selected";
if (ii !== 0) {
schemaP.selectOptionList[0].selected = "";
return true;
}
}
});
// init input - textarea
} else if (local.schemaPType(schemaP) === "array" || (
schemaP.format === "json"
&& local.schemaPType(schemaP) === "string"
)) {
schemaP.isTextarea = true;
// init input - number
} else if (schemaP.type === "integer" || schemaP.type === "number") {
schemaP.isInputNumber = true;
// init input - text
} else {
schemaP.isInputText = true;
}
// init format2 / type2
([
schemaP, schemaP.schema || {}
]).some(function (element) {
local.objectSetDefault(schemaP, {
format2: local.schemaPItemsType(element) || element.format,
type2: local.schemaPType(element)
});
return schemaP.type2;
});
schemaP.type2 = schemaP.type2 || "object";
// init schema2
([
schemaP,
local.schemaPItems(schemaP),
schemaP.schema,
schemaP.schema &...
n/a
urlJoin = function (aa, bb) {
/*
* this function will if bb is relative, url-join aa with bb
*/
// bb is absolute-url
if ((
/^\w+?:\/\//
).test(bb)) {
return bb;
}
// bb is absolute-url without protocol
if (bb.slice(0, 2) === "//") {
return aa.split("/")[0] + bb;
}
// bb is absolute-url without host
if (bb[0] === "/") {
return aa.split("/").slice(0, 3).join("/") + bb;
}
// bb is relative-url
if (aa.split("/").length < 4) {
aa += "/";
}
return aa.replace((
/[?#].*?$/
), "").replace((
/[^\/]*?$/
), "") + bb;
}
...
onError(null, opt);
};
local.testCase_urlJoin_default = function (opt, onError) {
/*
* this function will test urlJoin's default handling-behavior
*/
local.assertJsonEqual(local.urlJoin("", ""), "/");
local.assertJsonEqual(local.urlJoin("http://aa/bb", "zz"), "http://aa/zz");
local.assertJsonEqual(
local.urlJoin("http://aa/bb/", "zz"),
"http://aa/bb/zz"
);
local.assertJsonEqual(
local.urlJoin("http://aa/bb/", "/zz"),
...
urlParse = function (url) {
/*
* this function will parse <url> according to below spec, plus a query param
* https://developer.mozilla.org/en-US/docs/Web/API/URL
*/
var urlParsed;
urlParsed = {};
// try to parse url
local.tryCatchOnError(function () {
// resolve host-less url
if (local.isBrowser) {
local.serverLocalHost = (
local.serverLocalHost
|| location.protocol + "//" + location.host
);
// resolve absolute path
if (url[0] === "/") {
url = local.serverLocalHost + url;
// resolve relative path
} else if (!(
/^\w+?:\/\//
).test(url)) {
url = (
local.serverLocalHost
+ location.pathname.replace((
/\/[^\/]*?$/
), "") + "/" + url
);
}
urlParsed = new globalThis.URL(url);
urlParsed.path = "/" + urlParsed.href
.split("/")
.slice(3)
.join("/")
.split("#")[0];
} else {
local.env.PORT = local.env.PORT || "8081";
local.serverLocalHost = (
local.serverLocalHost
|| ("http://127.0.0.1:" + local.env.PORT)
);
// resolve absolute path
if (url[0] === "/") {
url = local.serverLocalHost + url;
// resolve relative path
} else if (!(
/^\w+?:\/\//
).test(url)) {
url = local.serverLocalHost + "/" + url;
}
urlParsed = local.url.parse(url);
}
// init query
urlParsed.query = {};
(urlParsed.search || "").slice(1).replace((
/[^&]+/g
), function (item) {
item = item.split("=");
item[0] = decodeURIComponent(item[0]);
item[1] = decodeURIComponent(item.slice(1).join("="));
// parse repeating query-param as an array
if (urlParsed.query[item[0]]) {
if (!Array.isArray(urlParsed.query[item[0]])) {
urlParsed.query[item[0]] = [
urlParsed.query[item[0]]
];
}
urlParsed.query[item[0]].push(item[1]);
} else {
urlParsed.query[item[0]] = item[1];
}
});
urlParsed.basename = urlParsed.pathname.replace((
/^.*\//
), "");
}, local.nop);
// https://developer.mozilla.org/en/docs/Web/API/URL#Properties
return {
basename: urlParsed.basename || "",
hash: urlParsed.hash || "",
host: urlParsed.host || "",
hostname: urlParsed.hostname || "",
href: urlParsed.href || "",
path: urlParsed.path || "",
pathname: urlParsed.pathname || "",
port: urlParsed.port || "",
protocol: urlParsed.protocol || "",
query: urlParsed.query || {},
search: urlParsed.search || ""
};
}
...
);
}
// init url
opt.url = "";
opt.url += (
local.identity(
that["x-swgg-schemes"] || local.swaggerJson.schemes || []
)[0] || local.urlParse("").protocol.slice(0, -1)
);
opt.url += "://";
opt.url += (
that["x-swgg-host"]
|| local.swaggerJson.host
|| local.urlParse("").host
);
...
urlParseWithBraket = function (url) {
/*
* this function will urlParse the url with curly-brackets preserved
*/
var tmp;
tmp = local.stringUniqueKey(url);
return JSON.parse(JSON.stringify(
local.urlParse(url.replace((
/\{/g
), tmp + 1).replace((
/\}/g
), tmp + 2))
).replace(
new RegExp(tmp + 1, "g"),
"{"
).replace(
new RegExp(tmp + 2, "g"),
"}"
));
}
...
local.operationIdFromAjax = function (opt) {
/*
* this function will create a sortable operationId
* from given ajax-<opt>
*/
var urlParsed;
urlParsed = local.urlParseWithBraket(opt.url);
return encodeURIComponent(
urlParsed.pathname + urlParsed.hash + " " + opt.method.toUpperCase()
).replace((
/[^\w\-.]/g
), "_");
};
...
userLoginByPassword = function (opt, onError) {
/*
* this function will send a login-by-password req
*/
local.apiDict["GET /user/userLoginByPassword"].ajax({
paramDict: {
password: opt.password,
username: opt.username
}
}, onError);
}
n/a
userLogout = function (opt, onError) {
/*
* this function will send a logout req
*/
local.apiDict["GET /user/userLogout"].ajax(opt, onError);
}
n/a
uuid4Create = function () {
/*
* this function will create a random uuid,
* with format 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
*/
// code derived from http://jsperf.com/uuid4
var id;
var ii;
id = "";
ii = 0;
while (ii < 32) {
switch (ii) {
case 8:
case 20:
id += "-";
// coerce to finite integer
id += ((Math.random() * 16) | 0).toString(16);
break;
case 12:
id += "-";
id += "4";
break;
case 16:
id += "-";
id += ((Math.random() * 4) | 8).toString(16);
break;
default:
// coerce to finite integer
id += ((Math.random() * 16) | 0).toString(16);
}
ii += 1;
}
return id;
}
...
};
local.testCase_uuid4Create_default = function (opt, onError) {
/*
* this function will test uuid4Create's default handling-behavior
*/
local.assertThrow(
local.regexpValidateUuid.test(local.uuid4Create()),
local.uuid4Create()
);
onError(null, opt);
};
local.testCase_webpage_err = function (opt, onError) {
/*
...
onEventDomDb = function (evt) {
/*
* this function will handle db dom-events
*/
var ajaxProgressUpdate;
var reader;
var tmp;
var utility2;
utility2 = globalThis.utility2 || {};
ajaxProgressUpdate = utility2.ajaxProgressUpdate || local.nop;
switch (evt.target.dataset.oneventDb) {
case "dbExport":
tmp = URL.createObjectURL(new globalThis.Blob([
local.dbExport()
]));
document.querySelector(
"#dbExportA1"
).href = tmp;
document.querySelector(
"#dbExportA1"
).click();
setTimeout(function () {
URL.revokeObjectURL(tmp);
}, 30000);
break;
case "dbImport":
document.querySelector(
"[data-onevent-db='dbImportInput']"
).click();
break;
case "dbImportInput":
if (evt.type !== "change") {
return;
}
ajaxProgressUpdate();
reader = new FileReader();
reader.addEventListener("load", function () {
local.dbImport(reader.result);
ajaxProgressUpdate();
});
reader.readAsText(evt.target.files[0]);
break;
case "dbReset":
ajaxProgressUpdate();
local.dbReset(globalThis.utility2_dbSeedList, function (err) {
local.onErrorDefault(err);
if (
utility2.uiEventListenerDict
&& typeof utility2.uiEventListenerDict[".onEventUiReload"]
=== "function"
) {
utility2.uiEventListenerDict[".onEventUiReload"]();
}
});
break;
}
}
n/a
onEventInputTextareaChange = function (evt) {
/*
* this function will show/hide the textarea's multiline placeholder
*/
var isTransparent;
var value;
isTransparent = evt.targetOnEvent.style.background.indexOf(
"transparent"
) >= 0;
value = evt.targetOnEvent.value;
if (value && isTransparent) {
evt.targetOnEvent.style.background = "";
}
if (!value && !isTransparent) {
evt.targetOnEvent.style.background = "transparent";
}
local.uiEventListenerDict.onEventInputValidateAndAjax({
targetOnEvent: evt.targetOnEvent
});
}
...
".swggUiContainer [data-value-text]"
)).forEach(function (element) {
// render valueText
element.value = decodeURIComponent(element.dataset.valueText);
delete element.dataset.valueText;
// init textarea's multiline placeholder
if (element.tagName === "TEXTAREA") {
local.uiEventListenerDict.onEventInputTextareaChange({
targetOnEvent: element
});
}
});
// init event-handling
[
"Change", "Click", "Keyup", "Submit"
...
onEventInputValidateAndAjax = function ( opt, onError ) {
/*
* this function will validate the input parameters
* against the schemas in <opt>.parameters
*/
var errorDict;
var jsonParse;
var tmp;
jsonParse = function (text) {
/*
* this function will try to JSON.parse(text)
*/
return local.tryCatchOnError(function () {
return JSON.parse(text);
}, function () {
return text;
});
};
// jslint-hack
opt.targetOnEvent = opt.targetOnEvent.closest(
".operation"
);
opt.api = local.apiDict[opt.targetOnEvent.dataset._methodPath];
opt.headers = {};
opt.modeAjax = opt.modeAjax || "validate";
opt.modeNoDefault = true;
opt.paramDict = {};
opt.url = "";
opt.api.parameters.forEach(function (schemaP) {
tmp = opt.targetOnEvent.querySelector(
".schemaP[data-name=" + JSON.stringify(schemaP.name) + "] .input"
);
switch (tmp.tagName) {
case "INPUT":
// parse file
if (local.schemaPType(tmp) === "file") {
tmp = tmp.files && tmp.files[0];
break;
}
tmp = tmp.value;
if (!tmp) {
return;
}
// parse string
if (local.schemaPType(schemaP) !== "string") {
tmp = jsonParse(tmp);
}
break;
case "SELECT":
tmp = Array.from(tmp.options)
.filter(function (element) {
return element.selected;
})
.map(function (element) {
return jsonParse(decodeURIComponent(
element.dataset.valueSelectOption
));
});
if (!tmp.length || tmp[0] === "$swggUndefined") {
return;
}
if (local.schemaPType(schemaP) !== "array") {
tmp = tmp[0];
}
break;
case "TEXTAREA":
tmp = tmp.value;
if (!tmp) {
return;
}
// ignore string (json)
if (
schemaP.format === "json"
&& local.schemaPType(schemaP) === "string"
) {
break;
}
if (
schemaP.schema
&& local.schemaPType(schemaP.schema) === "string"
&& typeof tmp === "string"
) {
break;
}
// parse schema
if (schemaP.in === "body") {
tmp = jsonParse(tmp);
break;
}
// parse array
tmp = tmp.split("\n").map(function (element) {
return (
local.schemaPItemsType(schemaP) === "string"
? element
: jsonParse(element)
);
});
break;
}
opt.paramDict[schemaP.name] = tmp;
});
opt.api.ajax(opt, onError || local.nop);
// init errorDict
errorDict = {};
((opt.err && opt.err.errList) || []).forEach(function (err) {
errorDict[err.opt.prefix[2]] = err;
});
// shake input on err
Array.from(opt.targetOnEvent.querySelectorAll(
".schemaP[data-name]"
)).forEach(function (element) {
tmp = errorDict[element.dataset.name];
local.uiAnimateShakeIfError(tmp, element.querySelector(
".input"
));
element.querySelector(
".colorError"
).textContent = (
tmp
? tmp.messageShort
: ""
);
});
// shake submit-button on err
local.uiAnimateShakeIfError(
opt.err,...
...
value = evt.targetOnEvent.value;
if (value && isTransparent) {
evt.targetOnEvent.style.background = "";
}
if (!value && !isTransparent) {
evt.targetOnEvent.style.background = "transparent";
}
local.uiEventListenerDict.onEventInputValidateAndAjax({
targetOnEvent: evt.targetOnEvent
});
};
local.uiEventListenerDict.onEventInputValidateAndAjax = function (
opt,
onError
...
onEventOperationAjax = function (opt) {
/*
* this function will submit the operation to the backend
*/
// ensure opt is stateless
opt = {
targetOnEvent: opt.targetOnEvent.closest(
".operation"
)
};
local.onNext(opt, function (err, data) {
switch (opt.modeNext) {
case 1:
// force ajax
opt.modeAjax = "ajax";
// validate input
local.uiEventListenerDict.onEventInputValidateAndAjax(
opt,
opt.onNext
);
// reset res output
Array.from(opt.targetOnEvent.querySelectorAll(
".resBody, .resHeaders, .resStatusCode"
)).forEach(function (element) {
element.classList.remove("hasError");
element.textContent = "loading ...";
});
opt.targetOnEvent.querySelector(
".resMedia"
).innerHTML = "";
// scrollTo res
opt.targetOnEvent.querySelector(
".resStatusCode"
).focus();
break;
default:
local.onErrorDefault(err);
data = local.objectSetDefault(data, {
contentType: "undefined",
statusCode: "undefined"
});
// init resStatusCode
opt.targetOnEvent.querySelector(
".resStatusCode"
).textContent = (
data.statusCode
);
// init resHeaders
opt.targetOnEvent.querySelector(
".resHeaders"
).textContent = Object.keys(data.resHeaders).map(function (key) {
return key + ": " + data.resHeaders[key] + "\r\n";
}).join("");
// init resBody
opt.targetOnEvent.querySelector(
".resHeaders"
).textContent.replace((
/^content-type:(.*?)$/im
), function (ignore, match1) {
data.contentType = match1.trim();
});
data.mediaType = data.contentType.split("/")[0].replace(
"image",
"img"
);
switch (data.mediaType) {
case "audio":
case "img":
case "video":
opt.targetOnEvent.querySelector(
".resBody"
).textContent = (
data.contentType
);
opt.targetOnEvent.querySelector(
".resMedia"
).innerHTML = (
"<" + data.mediaType
+ " class=\"domOnEventMediaHotkeysInit\""
+ " controls src=\"data:"
+ data.contentType
+ ";base64," + local.base64FromBuffer(data.resBuffer)
+ "\"></" + data.mediaType + ">"
);
globalThis.domOnEventMediaHotkeys("init");
break;
default:
opt.targetOnEvent.querySelector(
".resBody"
).textContent = (
data.responseJson
? JSON.stringify(data.responseJson, null, 4)
: data.response
);
}
// shake res on err
Array.from(opt.targetOnEvent.querySelectorAll(
".resBody, .resHeaders, .resStatusCode"
)).forEach(function (element) {
local.uiAnimateShakeIfError(data.statusCode >= 400, element);
});
}
});
opt.modeNext = 0;
opt.onNext();
}
n/a
onEventOperationDisplayShow = function ( evt, onError ) {
/*
* this function will toggle the display of the operation
*/
var element;
element = evt.targetOnEvent;
element = element.querySelector(
".operation"
) || element.closest(
".operation"
);
location.hash = "!" + element.id;
element.closest(
".resource"
).classList.remove("expanded");
// show parent resource
local.uiAnimateSlideDown(element.closest(
".resource"
).querySelector(
".operationList"
));
// show the operation, but hide all other operations
local.uiAnimateSlideAccordian(
element.querySelector(
".operation > form"
),
Array.from(element.closest(
".operationList"
).querySelectorAll(
".operation > form"
)),
function () {
// scrollTo operation
element.querySelector(
"[tabIndex]"
).blur();
element.querySelector(
"[tabIndex]"
).focus();
// validate input
local.uiEventListenerDict.onEventInputValidateAndAjax({
targetOnEvent: element
});
local.setTimeoutOnError(onError, 0, null, element);
}
);
}
...
".operationList"
),
Array.from(document.querySelectorAll(
".swggUiContainer .operationList"
))
);
// show at least one operation in the resource
local.uiEventListenerDict.onEventOperationDisplayShow({
targetOnEvent: evt.currentTarget.querySelector(
".operation .uiAnimateSlide[style*=\"max-height: 100%\"]"
) || evt.currentTarget.querySelector(
".operation"
)
});
return true;
...
onEventResourceDisplayAction = function (evt) {
/*
* this function will toggle the display of the resource
*/
location.hash = "!" + evt.currentTarget.id;
evt.targetOnEvent.className.split(" ").some(function (className) {
switch (className) {
case "td1":
// show the resource, but hide all other resources
local.uiAnimateSlideAccordian(
evt.currentTarget.querySelector(
".operationList"
),
Array.from(document.querySelectorAll(
".swggUiContainer .operationList"
))
);
// show at least one operation in the resource
local.uiEventListenerDict.onEventOperationDisplayShow({
targetOnEvent: evt.currentTarget.querySelector(
".operation .uiAnimateSlide[style*=\"max-height: 100%\"]"
) || evt.currentTarget.querySelector(
".operation"
)
});
return true;
case "td2":
// show the resource, but hide all other resources
local.uiAnimateSlideAccordian(
evt.currentTarget.querySelector(
".operationList"
),
Array.from(document.querySelectorAll(
".swggUiContainer .operationList"
))
);
// collapse all operations in the resource
if (evt.currentTarget.classList.contains("expanded")) {
evt.currentTarget.classList.remove("expanded");
Array.from(evt.currentTarget.querySelectorAll(
".operation > form"
)).forEach(function (element) {
local.uiAnimateSlideUp(element);
});
// expand all operations in the resource
} else {
evt.currentTarget.classList.add("expanded");
Array.from(evt.currentTarget.querySelectorAll(
".operation > form"
)).forEach(function (element) {
local.uiAnimateSlideDown(element);
// validate input
local.uiEventListenerDict.onEventInputValidateAndAjax({
targetOnEvent: element
});
});
}
return true;
}
});
}
n/a
onEventUiReload = function (opt, onError) {
/*
* this function will reload the ui
*/
var resource;
var swaggerJson;
opt = opt || {};
swaggerJson = opt;
local.onNext(opt, function (err, data) {
switch (opt.modeNext) {
case 1:
if (
event
&& event.targetOnEvent
&& !event.targetOnEvent.classList.contains(
"eventDelegate"
+ event.type[0].toUpperCase()
+ event.type.slice(1)
)
) {
return;
}
opt.inputUrl = document.querySelector(
".swggUiContainer > .thead > .td2"
);
// clear all apiKeyValue's from localStorage
if (
opt.targetOnEvent
&& opt.targetOnEvent.id === "swggApiKeyClearButton1"
) {
local.apiKeyValue = "";
Object.keys(localStorage).forEach(function (key) {
if (key.indexOf("utility2_swgg_apiKeyKey_") === 0) {
localStorage.removeItem(key);
}
});
// restore apiKeyValue
} else if (opt.swggInit) {
local.apiKeyKey = (
"utility2_swgg_apiKeyKey_" + encodeURIComponent(
local.urlParse(opt.inputUrl.value.replace((
/^\//
), "")).href
)
);
local.apiKeyValue = localStorage.getItem(local.apiKeyKey) || "";
// save apiKeyValue
} else {
local.apiKeyValue = document.querySelector(
"#swggApiKeyInput1"
).value;
local.localStorageSetItemOrClear(
local.apiKeyKey,
local.apiKeyValue
);
}
// if keyup-event is not return-key, then return
if (
(opt.type === "keyup" && opt.code !== "Enter")
// do not reload ui during test
|| globalThis.utility2_modeTest >= 4
) {
opt.modeNext = Infinity;
opt.onNext();
return;
}
// reset ui
document.querySelector(
"#swggUiReloadErrorDiv1"
).textContent = "";
Array.from(document.querySelectorAll(
".swggUiContainer > .reset"
)).forEach(function (element) {
element.remove();
});
// normalize swaggerJsonUrl
opt.inputUrl.value = local.urlParse(
opt.inputUrl.value.replace((
/^\//
), "")
).href;
document.querySelector(
"#swggAjaxProgressDiv1 span"
).innerHTML = (
"loading swagger.json"
);
opt.onNext();
break;
case 2:
// fetch swagger.json file
local.ajax({
url: opt.inputUrl.value
}, opt.onNext);
break;
case 3:
// JSON.parse swagger.json string
local.tryCatchOnError(function () {
opt.onNext(null, JSON.parse(data.responseText));
}, opt.onNext);
break;
case 4:
// reset state
local.apiDict = null;
local.swaggerJson = null;
// apiUpdate swagger.json object
local.apiUpdate(data);
swaggerJson = local.jsonCopy(local.swaggerJson);
local.uiState = swaggerJson;
// init ajaxProgressText
swaggerJson.ajaxProgressText = &qu...
...
/\\bmodeSwaggerJsonUrl=([^&]+)|$/gm\n\
).exec(location.search)[1] || "assets.swgg.swagger.json");\n\
</script>\n\
<script src="assets.utility2.rollup.js"></script>\n\
<script>\n\
/* jslint utility2:true */\n\
window.local = window.local || window.swgg;\n\
window.swgg.uiEventListenerDict.onEventUiReload({\n\
swggInit: true\n\
});\n\
</script>\n\
<!-- swgg-script-extra-begin -->\n\
<!-- swgg-script-extra-end -->\n\
</body>\n\
</html>\n\
...
_onTimeout = function () { ajaxProgressDiv1.style.background = "transparent"; local.ajaxProgressCounter = 0; local.ajaxProgressState = 0; // reset ajaxProgress clearInterval(local.timerIntervalAjaxProgressHide); local.timerIntervalAjaxProgressHide = null; setTimeout(function () { if (!local.ajaxProgressState) { ajaxProgressDiv1.style.width = "0%"; } }, 500); }
n/a
_onTimeout = function () { // update testPlatform.timeElapsed local.timeElapsedPoll(testPlatform); // update testReportDiv1 in browser testReportDiv1.innerHTML = local.testReportMerge(testReport, {}); if (!testReport.testsPending) { // cleanup timerInterval clearInterval(timerInterval); } // notify of remaining tests if (testPlatform.timeElapsed % 5000 < 1000) { local._testRunConsoleError( "testRunDefault - " + testPlatform.timeElapsed + " ms - testCase pending - " + testPlatform.testCaseList .filter(function (testCase) { return testCase.status === "pending"; }) .slice(0, 4) .map(function (testCase) { return testCase.name; }).join(", ") + " ..." ); } }
n/a