function Module(id = '', parent) { this.id = id; this.path = path.dirname(id); this.exports = {}; moduleParentCache.set(this, parent); updateChildren(parent, this, false); this.filename = null; this.loaded = false; this.children = []; }
...
// init example.js
tmp = require("path").resolve("example.js");
// jslint code
local.jslintAndPrint(code, tmp);
// instrument code
code = local.istanbulInstrumentInPackage(code, tmp);
// init module.exports
module = new local.Module(tmp);
require.cache[tmp] = module;
module._compile(code, tmp);
// init exports
module.exports.utility2 = local;
module.exports[env.npm_package_nameLib] = (
globalThis.utility2_moduleExports
);
...
_testCase_buildApidoc_default = function (opt, onError) {
/*
* this function will test buildApidoc's default handling-behavior
*/
let require2;
if (local.isBrowser) {
onError(undefined, opt);
return;
}
require2 = function (file) {
/*
* this function will require <file> in sandbox-env
*/
let exports;
let mockDict;
let mockList;
let noop;
noop = function () {
/*
* this function will do nothing
*/
return;
};
// coverage-hack
noop();
mockList = [
[
globalThis, {
setImmediate: noop,
setInterval: noop,
setTimeout: noop
}
]
];
// disable io and side-effect
[
process,
process.stdin,
process.stdout,
require("child_process"),
require("cluster"),
require("crypto"),
require("dgram"),
require("dns"),
require("domain"),
require("events").prototype,
require("http"),
require("https"),
require("net"),
require("os"),
require("readline"),
require("repl"),
require("stream").prototype,
require("timers"),
require("tls"),
require("tty"),
require("util"),
require("v8"),
require("vm"),
{
// coverage-hack
"__zjqx1234__": noop
}
].forEach(function (dict) {
mockDict = {};
Object.keys(dict).forEach(function (key) {
if (typeof dict[key] === "function" && (
process.env.npm_config_mode_test_case
=== "testCase_buildApidoc_default"
// coverage-hack
|| key === "__zjqx1234__"
)) {
mockDict[key] = noop;
}
});
mockList.push([
dict, mockDict
]);
});
local.testMock(mockList, function (onError) {
try {
exports = require(file);
} catch (errCaught) {
console.error(errCaught);
}
onError();
}, local.onErrorThrow);
return exports;
};
// coverage-hack
require2();
// save apidoc.html
local.fsWriteFileWithMkdirp(".tmp/build/apidoc.html", local.apidocCreate(
Object.assign({
blacklistDict: local,
modeNoop: (
process.env.npm_config_mode_test_case
!== "testCase_buildApidoc_default"
),
require: require2
}, opt)
), onError);
}
...
onError(undefined, opt);
};
local.testCase_buildApidoc_default = function (opt, onError) {
/*
* this function will test buildApidoc's default handling-behavior
*/
local._testCase_buildApidoc_default({
blacklistDict: {}
}, onError, opt);
};
local.testCase_buildApp_default = function (opt, onError) {
/*
* this function will test buildApp's default handling-behavior
...
_testCase_buildApp_default = function (opt, onError) {
/*
* this function will test buildApp's default handling-behavior
*/
if (local.isBrowser) {
onError(undefined, opt);
return;
}
local.buildApp(opt, onError);
}
...
}, onError, opt);
};
local.testCase_buildApp_default = function (opt, onError) {
/*
* this function will test buildApp's default handling-behavior
*/
local._testCase_buildApp_default({
assetsList: [
{
file: "/assets.hello.txt",
url: "/assets.hello.txt"
}, {
file: "/assets.script_only.html",
url: "/assets.script_only.html"
...
_testCase_webpage_default = function (opt, onError) {
/*
* this function will test webpage's default handling-behavior
*/
local.domQuerySelectorAllTagName("html");
local.domStyleValidate();
if (local.isBrowser) {
onError(undefined, opt);
return;
}
local.browserTest({
fileScreenshot: (
process.env.npm_config_dir_build
+ "/screenshot." + process.env.MODE_BUILD + ".browser.%2F.png"
),
url: (
local.serverLocalHost
+ "/?modeTest=1&timeoutDefault=" + local.timeoutDefault
+ "&modeTestCase=" + local.modeTestCase.replace((
/_?testCase_webpage_default/
), "")
)
}, onError);
}
...
local.testMock([
[
local, {
browserTest: local.noop
}
]
], function (onError) {
local._testCase_webpage_default({}, local.noop);
onError(undefined, opt);
}, onError);
};
local.testCase_chromeDevtoolsClient_processPlatform = function (opt, onError) {
/*
* this function will test chromeDevtoolsClient's processPlatform
...
ajax = function (opt, onError) {
/*
* this function will send an ajax-req
* with given <opt>.url and callback <onError>
* with err and timeout handling
* example use:
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);
});
*/
let ajaxProgressUpdate;
let bufferValidateAndCoerce;
let isDone;
let local2;
let onError2;
let onEvent;
let stack;
let streamCleanup;
let timeout;
let tmp;
let xhr;
let xhrInit;
// init local2
local2 = opt.local2 || local.utility2 || {};
// init function
ajaxProgressUpdate = local2.ajaxProgressUpdate || function () {
return;
};
bufferValidateAndCoerce = local2.bufferValidateAndCoerce || function (
buf,
mode
) {
/*
* this function will validate and coerce/convert
* <buf> to Buffer/Uint8Array, or String if <mode> = "string"
*/
// coerce ArrayBuffer to Buffer
if (Object.prototype.toString.call(buf) === "[object ArrayBuffer]") {
buf = new Uint8Array(buf);
}
// convert Buffer to utf8
if (mode === "string" && typeof buf !== "string") {
buf = String(buf);
}
return buf;
};
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 cnt
ajaxProgressUpdate.cnt = Math.max(
ajaxProgressUpdate.cnt - 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 = (
(
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, key, val) {
xhr.resHeaders[key.toLowerCase()] = val;
});
}
// debug ajaxResponse
xhr.resContentLength = (...
...
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 use:
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 () { return; }
...
) {
return;
}
// test-run
globalThis.utility2_modeTest += 1;
}
// visual notification - testRun
local.ajaxProgressUpdate();
// mock console.error
consoleError = console.error;
isCoverage = (
typeof globalThis.__coverage__ === "object" && globalThis.__coverage__
&& Object.keys(globalThis.__coverage__).length
);
console.error = function (...argList) {
...
apidocCreate = function (opt) {
/*
* this function will create the apidoc from <opt>.dir
*/
let elemCreate;
let module;
let moduleMain;
let readExample;
let tmp;
let toString;
let trimStart;
if (opt.modeNoop) {
return "";
}
elemCreate = function (module, prefix, key) {
/*
* this function will create the apidoc-elem in given <module>
*/
let 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
elem.name = elem.name.replace(">.<", "><");
if (elem.typeof !== "function") {
return elem;
}
// init source
elem.source = local.stringHtmlSafe(
trimStart(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 = "..." + trimStart(
local.stringHtmlSafe(match1)
+ "<span class=\"apidocCodeKeywordSpan\">"
+ local.stringHtmlSafe(match2)
+ "</span>"
+ local.stringHtmlSafe(match3)
).trimEnd() + "\n...";
return "";
}
);
return elem.example;
});
elem.example = elem.example || "n/a";
return elem;
};
readExample = function (file) {
/*
* this function will read the example from given file
*/
let result;
local.tryCatchOnError(function () {
file = require("path").resolve(opt.dir, file);
console.error("apidocCreate - readExample " + file);
result = "";
result = local.identity(
"\n\n\n\n\n\n\n\n"
// bug-workaround - truncate example to manageable size
+ require("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
*/
let result;
local.tryCatchOnError(function () {
result = "";
result = String(value);...
...
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 assertJsonEqual(aa, bb) {
/*
* this function will assert JSON.stringify(<aa>) === JSON.stringify(<bb>)
*/
aa = JSON.stringify(objectDeepCopyWithKeysSorted(aa));
bb = JSON.stringify(objectDeepCopyWithKeysSorted(bb));
if (aa !== bb) {
throw new Error(JSON.stringify(aa) + " !== " + JSON.stringify(bb));
}
}
n/a
function assertOrThrow(passed, msg) {
/*
* this function will throw <msg> if <passed> is falsy
*/
if (passed) {
return;
}
throw (
(
msg
&& typeof msg.message === "string"
&& typeof msg.stack === "string"
)
// if msg is err, then leave as is
? msg
: new Error(
typeof msg === "string"
// if msg is string, then leave as is
? msg
// else JSON.stringify(msg)
: JSON.stringify(msg, undefined, 4)
)
);
}
...
strDict[str] = strDict[str] || (ii + 2);
ii = strDict[str];
if (commandList[ii]) {
commandList[ii].command.push(key);
return;
}
commandList[ii] = rgxComment.exec(str);
local.assertOrThrow(commandList[ii], (
"cliRun - cannot parse comment in COMMAND "
+ key
+ ":\nnew RegExp("
+ JSON.stringify(rgxComment.source)
+ ").exec(" + JSON.stringify(str).replace((
/\\\\/g
), "\u0000").replace((
...
browserTest = function ({ modeSilent, modeTestReportCreate, url }, onError) {
/*
* this function will spawn google-chrome-process to test <url>
*/
let chromeClient;
let fileScreenshot;
let isDone;
let promiseList;
let testId;
let testName;
function onError2(err) {
// cleanup chromeClient
chromeClient.destroy();
onError(err);
}
// init utility2_testReport
globalThis.utility2_testReport = globalThis.utility2_testReport || {
coverage: globalThis.__coverage__,
testPlatformList: [
{
name: (
local.isBrowser
? (
"browser - "
+ location.pathname + " - " + navigator.userAgent
)
: "node - " + process.platform + " " + process.version
) + " - " + new Date().toISOString(),
testCaseList: []
}
]
};
if (modeTestReportCreate) {
return;
}
Promise.resolve().then(function () {
// node - init
url = url.replace("{{timeExit}}", Date.now() + local.timeoutDefault);
testId = Math.random().toString(16);
testName = process.env.MODE_BUILD + ".browser." + encodeURIComponent(
require("url").parse(url).pathname.replace(
"/build.." + process.env.CI_BRANCH + ".." + process.env.CI_HOST,
"/build"
)
);
fileScreenshot = (
process.env.npm_config_dir_build
+ "/screenshot." + testName + ".png"
);
return local.chromeDevtoolsClientCreate({
modeSilent,
timeout: local.timeoutDefault,
url
});
}).then(function (data) {
chromeClient = data;
return chromeClient.navigate({
url
});
}).then(function () {
promiseList = [];
promiseList.push(chromeClient.screenshot({
delay: 100,
file: fileScreenshot
}));
chromeClient.evaluate(
// coverage-hack
"console.timeStamp();\n"
+ "window.utility2_testId=\"" + testId + "\";\n"
+ "if(!window.utility2_modeTest){\n"
+ "console.timeStamp(window.utility2_testId);\n"
+ "}\n"
);
return new Promise(function (resolve) {
chromeClient.on("Performance.metrics", function ({
title
}) {
if (isDone || title !== testId) {
return;
}
isDone = true;
resolve(chromeClient.evaluate(
"JSON.stringify(\n"
+ "window.utility2_testReport\n"
+ "||{testPlatformList:[{}]}\n"
+ ");\n"
));
});
});
}).then(function (data) {
data = JSON.parse(data);
// merge browser-screenshot
data.testPlatformList[0].screenshot = fileScreenshot.replace((
/.*\//
), "");
// merge browser-coverage
local.istanbulCoverageMerge(globalThis.__coverage__, data.coverage);
// merge browser-test-report
local.testReportMerge(globalThis.utility2_testReport, data);
// save test-report.json
promiseList.push(new Promise(function (resolve) {
require("fs").writeFile(
require("path").resolve(
process.env.npm_config_dir_build + "/test-report.json"
),
JSON.stringify(globalThis.utility2_testReport),
function (err) {
local.onErrorThrow(err);...
...
local.cliDict = {};
local.cliDict["utility2.browserTest"] = function () {
/*
* <urlList> <mode>
* will browser-test in parallel, comma-separated <urlList> with given <mode>
*/
local.browserTest({
url: process.argv[3]
}, function (err) {
if (err) {
console.log(err);
}
});
};
...
bufferConcat = function (bufList) {
/*
* this function will emulate in browser, node's Buffer.concat
*/
let byteLength;
let ii;
let isString;
let jj;
let result;
isString = true;
result = [
""
];
byteLength = 0;
bufList.forEach(function (buf) {
if (buf !== 0 && !(buf && buf.length)) {
return;
}
// optimization - concat string
if (isString && typeof buf === "string") {
result[0] += buf;
return;
}
isString = null;
buf = local.bufferValidateAndCoerce(buf);
byteLength += buf.byteLength;
result.push(buf);
});
// optimization - return string
if (isString) {
return result[0];
}
result[0] = local.bufferValidateAndCoerce(result[0]);
byteLength += result[0].byteLength;
bufList = result;
result = local.bufferValidateAndCoerce(new Uint8Array(byteLength));
ii = 0;
bufList.forEach(function (buf) {
jj = 0;
while (jj < buf.byteLength) {
result[ii] = buf[jj];
ii += 1;
jj += 1;
}
});
return result;
}
...
}
res._isDone = true;
bufList.push(data);
// notify server res is finished
res.emit("finish");
// pass res to client
onResponse(res);
res.emit("data", local.bufferConcat(bufList));
res.emit("end");
},
on: function (type, onEvent) {
handler.addEventListener("res." + type, function (evt) {
onEvent(evt.detail);
});
return res;
...
bufferToUtf8 = function (buf) {
/*
* this function will convert Uint8Array <buf> to utf8
*/
return local.bufferValidateAndCoerce(buf, "string");
}
n/a
bufferValidateAndCoerce = function (buf, mode) {
/*
* this function will validate and coerce/convert
* <buf> to Buffer/Uint8Array, or String if <mode> = "string"
*/
// validate not 0
if (buf !== 0) {
buf = buf || "";
}
if (typeof buf === "string" && mode === "string") {
return buf;
}
// convert utf8 to Uint8Array
if (typeof buf === "string") {
buf = new TextEncoder().encode(buf);
// validate instanceof Uint8Array
} else if (Object.prototype.toString.call(buf) !== "[object Uint8Array]") {
throw new Error(
"bufferValidateAndCoerce - value is not instanceof "
+ "ArrayBuffer, String, or Uint8Array"
);
}
// convert Uint8Array to utf8
if (mode === "string") {
return new TextDecoder().decode(buf);
}
// coerce Uint8Array to Buffer
if (globalThis.Buffer && Buffer.isBuffer && !Buffer.isBuffer(buf)) {
Object.setPrototypeOf(buf, Buffer.prototype);
}
return buf;
}
...
}
// optimization - concat string
if (isString && typeof buf === "string") {
result[0] += buf;
return;
}
isString = null;
buf = local.bufferValidateAndCoerce(buf);
byteLength += buf.byteLength;
result.push(buf);
});
// optimization - return string
if (isString) {
return result[0];
}
...
buildApp = function ({ assetsList = [], customizeReadmeList = [] }, onError) {
/*
* this function will build app
*/
let buildAppAssets;
let buildAppStandalone;
let buildLib;
let buildReadme;
let buildTest;
let fileDict;
let packageJson;
let packageNameLib;
let port;
let promiseList;
let src;
let tgt;
let tgtReplaceConditional;
let writeFile;
let writeFileLog;
tgtReplaceConditional = function (condition, replaceList) {
/*
* this function will conditionally replace <tgt> with replacements in
* <replaceList>
*/
replaceList.forEach(function ({
aa,
bb,
merge
}) {
let isMatch;
if (!condition) {
aa = aa || merge;
console.error(
"buildApp - replace-skipped - "
+ JSON.stringify((aa && aa.source) || aa)
);
return;
}
if (aa) {
if (!tgt.match(aa)) {
console.error(
"buildApp - replace-unmatched - "
+ JSON.stringify((aa && aa.source) || aa)
);
return;
}
tgt = tgt.replace(aa, bb);
return;
}
src.replace(merge, function (match2) {
tgt.replace(merge, function (match1) {
isMatch = true;
// disable $-escape in replacement-string
tgt = tgt.replace(match1, function () {
return match2;
});
return "";
});
return "";
});
if (!isMatch) {
console.error(
"buildApp - replace-unmatched - "
+ JSON.stringify(merge.source)
);
}
});
};
writeFile = function (file, data, resolve) {
/*
* this function will write <data> to <file> with notification
*/
require("fs").writeFile(file, data, function (err) {
local.onErrorThrow(err);
writeFileLog(file);
resolve();
});
};
writeFileLog = function (file) {
/*
* this function will notify <file> written
*/
console.error("buildApp - wrote - " + require("path").resolve(file));
};
buildAppAssets = function (resolve) {
let promiseList2;
promiseList2 = [];
// fetch assets
[
{
url: "/LICENSE"
}, {
file: "/assets." + packageNameLib + ".html",
url: "/index.html"
}, {
url: "/assets." + packageNameLib + ".css"
}, {
url: "/assets." + packageNameLib + ".js"
}, {
url: "/assets.app.js"
}, {
url: "/assets.example.html"
}, {
url: "/assets.example.js"
}, {
url: "/assets.test.js"
}, {
url: "/assets.utility2.html"
}, {
url: "/assets.utility2.lib.jslint.js"
}, {
url: "/assets.utility2.rollup.js"
}, {
url: "/index.html"
}, {
url: "/index.rollup.html"
}, {
url: "/utility2.state.init.js"
}
].concat(assetsList).forEach(function (elem) {
promiseList2.push(new Promise(function (resolve) {
require("http").request((
"http...
...
/*
* this function will test buildApp's default handling-behavior
*/
if (local.isBrowser) {
onError(undefined, opt);
return;
}
local.buildApp(opt, onError);
};
local._testCase_webpage_default = function (opt, onError) {
/*
* this function will test webpage's default handling-behavior
*/
local.domQuerySelectorAllTagName("html");
...
chromeDevtoolsClientCreate = function ({ chromeBin, modeMockProcessPlatform, modeSilent, processPlatform, timeout }) {
/*
* this function with create chrome-devtools-client from <chromeBin>
*/
let chromeCleanup;
let chromeClient;
let chromeProcess;
let chromeSessionId;
let chromeUserDataDir;
let websocket;
let wsReader;
return Promise.resolve().then(function () {
/*
* this function will init <chromeCleanup> and <chromeClient>
*/
let callbackDict;
let callbackId;
let timerTimeout;
callbackDict = {};
callbackId = 0;
chromeCleanup = function () {
/*
* this function will
* kill <chromeProcess>
* rm -rf <chromeUserDataDir>
* destroy <chromeClient>, <websocket>, <wsReader>
*/
// cleanup timerTimeout
clearTimeout(timerTimeout);
// kill <chromeProcess>
try {
if (processPlatform === "win32") {
require("child_process").spawnSync("taskkill", [
"/pid", chromeProcess.pid, "/T", "/F"
], {
stdio: "ignore"
});
} else {
// kill child process tree with ".kill(-pid)" command.
process.kill(-chromeProcess.pid, "SIGKILL");
}
} catch (ignore) {}
// rm -rf <chromeUserDataDir>
require("fs").rmdirSync(chromeUserDataDir, {
recursive: true
});
// destroy <chromeClient>, <websocket>, <wsReader>
chromeClient.destroy();
try {
websocket.destroy();
} catch (ignore) {}
wsReader.destroy();
};
// init timerTimeout
timeout = timeout || 30000;
timerTimeout = setTimeout(function () {
chromeCleanup();
chromeClient.emit("error", new Error(
"chrome-devtools - timeout " + timeout + " ms"
));
}, timeout);
function ChromeClient() {
/*
* this function will construct <chromeClient>
*/
require("stream").Duplex.call(this);
}
require("util").inherits(ChromeClient, require("stream").Duplex);
chromeClient = new ChromeClient();
chromeClient.__proto__._destroy = chromeCleanup;
chromeClient.__proto__._read = function () {
/*
* this function will implement stream.Duplex.prototype._read
*/
if (websocket && websocket.readable) {
websocket.resume();
}
};
chromeClient.__proto__._write = function (payload, ignore, callback) {
/*
* this function will implement stream.Duplex.prototype._write
*/
// console.error("SEND \u25ba " + payload.slice(0, 256).toString());
let header;
let maskKey;
let result;
// init header
header = Buffer.alloc(2 + 8 + 4);
// init fin = true
header[0] |= 0x80;
// init opcode = text-frame
header[0] |= 1;
// init mask = true
header[1] |= 0x80;
// init payload.length
if (payload.length < 126) {
header = header.slice(0, 2 + 0 + 4);
header[1] |= payload.length;
// } else if (payload.length < 65536) {
} else {
local.assertOrThrow(
payload.length < 65536,
"chrome-devtools - "
+ "payload-length must be less than 65536 bytes, not "...
...
"/build"
)
);
fileScreenshot = (
process.env.npm_config_dir_build
+ "/screenshot." + testName + ".png"
);
return local.chromeDevtoolsClientCreate({
modeSilent,
timeout: local.timeoutDefault,
url
});
}).then(function (data) {
chromeClient = data;
return chromeClient.navigate({
...
cliRun = function ({ rgxComment }) {
/*
* this function will run cli
*/
let cliDict;
cliDict = local.cliDict;
cliDict._eval = cliDict._eval || function () {
/*
* <code>
* will eval <code>
*/
globalThis.local = local;
require("vm").runInThisContext(process.argv[3]);
};
cliDict._help = cliDict._help || function () {
/*
*
* will print help
*/
let commandList;
let file;
let packageJson;
let str;
let strDict;
commandList = [
{
argList: "<arg2> ...",
description: "usage:",
command: [
"<arg1>"
]
}, {
argList: "'console.log(\"hello world\")'",
description: "example:",
command: [
"--eval"
]
}
];
file = __filename.replace((
/.*\//
), "");
packageJson = require("./package.json");
// validate comment
rgxComment = 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/
);
strDict = {};
Object.keys(cliDict).sort().forEach(function (key, ii) {
if (key[0] === "_" && key !== "_default") {
return;
}
str = String(cliDict[key]);
if (key === "_default") {
key = "";
}
strDict[str] = strDict[str] || (ii + 2);
ii = strDict[str];
if (commandList[ii]) {
commandList[ii].command.push(key);
return;
}
commandList[ii] = rgxComment.exec(str);
local.assertOrThrow(commandList[ii], (
"cliRun - cannot parse comment in COMMAND "
+ key
+ ":\nnew RegExp("
+ JSON.stringify(rgxComment.source)
+ ").exec(" + JSON.stringify(str).replace((
/\\\\/g
), "\u0000").replace((
/\\n/g
), "\\n\\\n").replace((
/\u0000/g
), "\\\\") + ");"
));
commandList[ii] = {
argList: local.coalesce(commandList[ii][1], "").trim(),
command: [
key
],
description: commandList[ii][2]
};
});
str = "";
str += packageJson.name + " (" + packageJson.version + ")\n\n";
str += 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# "
+ elem.description
);
}
return (
elem.description + "\n " + file
+ " " + elem.command.sort().join("|") + " "
+ elem.argList.join(" ")
);
}).join("\n\n");
console.log(str);...
...
dir: process.argv[2],
modulePathList: module.paths
}));
};
// run the cli
if (module === require.main && !globalThis.utility2_rollup) {
local.cliRun({});
}
}());
}());
...
function coalesce(...argList) {
/*
* this function will coalesce null, undefined, or "" in <argList>
*/
let arg;
let ii;
ii = 0;
while (ii < argList.length) {
arg = argList[ii];
if (arg !== undefined && arg !== null && arg !== "") {
return arg;
}
ii += 1;
}
return arg;
}
...
), "\u0000").replace((
/\\n/g
), "\\n\\\n").replace((
/\u0000/g
), "\\\\") + ");"
));
commandList[ii] = {
argList: local.coalesce(commandList[ii][1], "").trim(),
command: [
key
],
description: commandList[ii][2]
};
});
str = "";
...
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")
);
}
...
// 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 (
local2.corsForwardProxyHostIfNeeded
&& 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);
...
domFragmentRender = function (template, dict) {
/*
* this function will return dom-elem rendered from <template>
*/
let tmp;
tmp = document.createElement("template");
tmp.innerHTML = local.templateRender(template, dict);
return tmp.content;
}
...
/*
* this function will test domFragmentRender's default handling-behavior
*/
if (!local.isBrowser) {
onError(undefined, opt);
return;
}
assertJsonEqual(local.domFragmentRender("<div>{{value}}</div>"
;, {
value: "aa"
}).children[0].outerHTML, "<div>aa</div>");
onError(undefined, opt);
};
local.testCase_eventListenerXxx_default = function (opt, onError) {
/*
...
domQuerySelectorAllTagName = function (selector) {
/*
* this function will return list of tagName matching <selector>
*/
let set;
try {
document.getElementById("undefined");
} catch (ignore) {
return [];
}
set = new Set();
document.querySelectorAll(selector).forEach(function (elem) {
set.add(elem.tagName);
});
return Array.from(set).sort();
}
...
local.buildApp(opt, onError);
};
local._testCase_webpage_default = function (opt, onError) {
/*
* this function will test webpage's default handling-behavior
*/
local.domQuerySelectorAllTagName("html");
local.domStyleValidate();
if (local.isBrowser) {
onError(undefined, opt);
return;
}
local.browserTest({
fileScreenshot: (
...
domStyleValidate = function () {
/*
* this function will validate <style> tags
*/
let rgx;
let tmp;
try {
document.getElementById("undefined");
} catch (ignore) {
return;
}
rgx = (
/^0\u0020(?:(body\u0020>\u0020)?(?:\.testReportDiv\u0020.+|\.x-istanbul\u0020.+|\.button|\.colorError|\.readonly|\.textarea
|\.uiAnimateSlide|a|body|code|div|input|pre|textarea)(?:,|\u0020\{))|^[1-9]\d*?\u0020#/m
);
tmp = [];
Array.from(
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
);
});
}
...
};
local._testCase_webpage_default = function (opt, onError) {
/*
* this function will test webpage's default handling-behavior
*/
local.domQuerySelectorAllTagName("html");
local.domStyleValidate();
if (local.isBrowser) {
onError(undefined, opt);
return;
}
local.browserTest({
fileScreenshot: (
process.env.npm_config_dir_build
...
eventListenerAdd = function (type, listener, opt = {}) {
/*
* this function will listen evt <type> with <listener>
*/
localEventListenerId = (localEventListenerId + 1) | 0;
localEventListenerDict[localEventListenerId] = {
listener,
once: opt.once,
type
};
}
...
local.timeoutDefault = Number(local.timeoutDefault) || 30000;
globalThis.utility2_onReadyAfter = (
globalThis.utility2_onReadyAfter || function (onError) {
/*
* this function will call onError when utility2_onReadyBefore.cnt === 0
*/
globalThis.utility2_onReadyBefore.cnt += 1;
local.eventListenerAdd("utility2_onReadyAfter", onError, {
once: true
});
setTimeout(globalThis.utility2_onReadyBefore);
return onError;
}
);
globalThis.utility2_onReadyBefore = (
...
eventListenerEmit = function (type, msg) {
/*
* this function will emit evt <type> with <msg>
*/
Object.entries(localEventListenerDict).forEach(function ([
id, elem
]) {
if (elem.type === type) {
if (elem.once) {
delete localEventListenerDict[id];
}
elem.listener(msg);
}
});
}
...
consoleError(...argList);
}
};
// mock proces.exit
if (!local.isBrowser) {
processExit = process.exit;
process.exit = function (exitCode) {
local.eventListenerEmit(
"utility2.testRunMock.process.exit",
exitCode | 0
);
};
}
// init modeTestCase
local.modeTestCase = (
...
eventListenerRemove = function (listener) {
/*
* this function will emit evt <type> with <msg>
*/
Object.entries(localEventListenerDict).forEach(function ([
id, elem
]) {
if (elem.listener === listener) {
delete localEventListenerDict[id];
}
});
}
...
};
local.eventListenerAdd("aa", listener);
local.eventListenerAdd("aa", listener, {
once: true
});
local.eventListenerEmit("aa", "bb");
local.eventListenerEmit("aa", "bb");
local.eventListenerRemove(listener);
onError(undefined, opt);
};
local.testCase_libUtility2Js_standalone = function (opt, onError) {
/*
* this function will test lib.utility2.js's standalone handling-behavior
*/
...
fsReadFileOrDefaultSync = function (pathname, type, dflt) {
/*
* this function will sync-read <pathname> with given <type> and <dflt>
*/
let fs;
// do nothing if module not exists
try {
fs = require("fs");
pathname = require("path").resolve(pathname);
} catch (ignore) {
return dflt;
}
// try to read pathname
try {
return (
type === "json"
? JSON.parse(fs.readFileSync(pathname, "utf8"))
: fs.readFileSync(pathname, type)
);
} catch (ignore) {
return dflt;
}
}
...
stdio: [
"ignore", 1, 2
]
});
if (globalThis.utility2_rollup || env.npm_config_mode_start) {
// init assets index.html
local.assetsDict["/index.html"] = (
local.fsReadFileOrDefaultSync("index.html", "utf8", "
;")
|| local.assetsDict["/index.rollup.html"] || ""
);
local.assetsDict["/"] = local.assetsDict["/index.html"];
local.assetsDict["/assets.app.js"] = require("fs").readFileSync(
__filename,
"utf8"
).replace((
...
fsRmrfSync = function (pathname) {
/*
* this function will sync "rm -rf" <pathname>
*/
let child_process;
// do nothing if module not exists
try {
child_process = require("child_process");
} catch (ignore) {
return;
}
pathname = require("path").resolve(pathname);
if (process.platform !== "win32") {
child_process.spawnSync("rm", [
"-rf", pathname
], {
stdio: [
"ignore", 1, 2
]
});
return;
}
try {
child_process.spawnSync("rd", [
"/s", "/q", pathname
], {
stdio: [
"ignore", 1, 2
]
});
} catch (ignore) {}
}
n/a
fsWriteFileWithMkdirp = function (pathname, data, onError) {
/*
* this function will async write <data> to <pathname> with "mkdir -p"
*/
let fs;
// do nothing if module not exists
try {
fs = require("fs");
pathname = require("path").resolve(pathname);
} catch (ignore) {
onError();
}
// write pathname
fs.writeFile(pathname, data, function (err) {
if (!err) {
console.error("fsWriteFileWithMkdirp - " + pathname);
onError(undefined, true);
return;
}
// mkdir -p
fs.mkdir(require("path").dirname(pathname), {
recursive: true
}, function (ignore) {
// re-write pathname
fs.writeFile(pathname, data, function (err) {
if (err) {
throw err;
}
console.error("fsWriteFileWithMkdirp - " + pathname);
onError(undefined, true);
});
});
});
}
...
onError();
}, local.onErrorThrow);
return exports;
};
// coverage-hack
require2();
// save apidoc.html
local.fsWriteFileWithMkdirp(".tmp/build/apidoc.html", local.apidocCreate(
Object.assign({
blacklistDict: local,
modeNoop: (
process.env.npm_config_mode_test_case
!== "testCase_buildApidoc_default"
),
require: require2
...
fsWriteFileWithMkdirpSync = function (pathname, data) {
/*
* this function will sync write <data> to <pathname> with "mkdir -p"
*/
let fs;
// do nothing if module not exists
try {
fs = require("fs");
pathname = require("path").resolve(pathname);
} catch (ignore) {
return;
}
// try to write pathname
try {
fs.writeFileSync(pathname, data);
} catch (ignore) {
// mkdir -p
fs.mkdirSync(require("path").dirname(pathname), {
recursive: true
});
// re-write pathname
fs.writeFileSync(pathname, data);
}
console.error("fsWriteFileWithMkdirpSync - " + pathname);
return true;
}
...
testPlatform.testsPassed + " passed "
).padStart(16, " ")
+ " |\n" + new Array(56).join("-")
);
}).join("\n") + "\n"
);
// create test-report.html
local.fsWriteFileWithMkdirpSync(
".tmp/build/test-report.html",
local.testReportMerge(testReport)
);
// create build.badge.svg
local.fsWriteFileWithMkdirpSync(
".tmp/build/build.badge.svg",
local.assetsDict["/assets.buildBadge.template.svg"].replace((
...
gotoNext = function (opt, onError) {
/*
* this function will wrap onError inside recursive-function <opt>.gotoNext,
* and append current-stack to any err
*/
opt.gotoNext = function (err, data, meta) {
try {
opt.gotoState += (
(err && !opt.modeErrorIgnore)
? 1000
: 1
);
if (opt.modeDebug) {
console.error("gotoNext - " + JSON.stringify({
gotoState: opt.gotoState,
errMsg: 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.assertOrThrow(undefined, opt.errCaught);
}
opt.errCaught = errCaught;
opt.gotoNext(errCaught, data, meta);
}
};
return opt;
}
...
onError(err, data, meta);
} catch (errCaught) {
// throw errCaught to break infinite recursion-loop
if (opt.errCaught) {
local.assertOrThrow(undefined, opt.errCaught);
}
opt.errCaught = errCaught;
opt.gotoNext(errCaught, data, meta);
}
};
return opt;
};
local.testCase_ajax_cache = function (opt, onError) {
/*
...
function identity(val) {
/*
* this function will return <val>
*/
return val;
}
...
cliDict.help = cliDict.help || cliDict._help;
cliDict._interactive = cliDict._interactive || function () {
/*
*
* will start interactive-mode
*/
globalThis.local = local;
local.identity(local.replStart || require("repl").start)({
useGlobal: true
});
};
cliDict["--interactive"] = cliDict["--interactive"] || cliDict._interactive;
cliDict["-i"] = cliDict["-i"] || cliDict._interactive;
cliDict._version = cliDict._version || function () {
/*
...
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
istanbulCoverageMerge = function (coverage1 = {}, coverage2 = {}) {
/*
* this function will inplace-merge <coverage2> into <coverage1>
*/
let dict1;
let dict2;
Object.keys(coverage2).forEach(function (file) {
// if coverage1[file] is undefined, then override it
if (!coverage1[file]) {
coverage1[file] = coverage2[file];
return;
}
// merge 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 (cnt, ii) {
dict1[key][ii] += cnt;
});
});
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;
}
...
}).then(function (data) {
data = JSON.parse(data);
// merge browser-screenshot
data.testPlatformList[0].screenshot = fileScreenshot.replace((
/.*\//
), "");
// merge browser-coverage
local.istanbulCoverageMerge(globalThis.__coverage__, data.coverage);
// merge browser-test-report
local.testReportMerge(globalThis.utility2_testReport, data);
// save test-report.json
promiseList.push(new Promise(function (resolve) {
require("fs").writeFile(
require("path").resolve(
process.env.npm_config_dir_build + "/test-report.json"
...
istanbulCoverageReportCreate = function ({ coverage, coverageInclude }) {
/*
* this function will
// 1. merge previous <dirCoverage>/coverage.json into <coverage>
// 2. convert <coverage> to <summaryDict>
// 3. convert <summaryDict> to <nodeRoot>
// 4. convert <nodeRoot> to text-report <dirCoverage>/coverage.txt
// 5. convert <nodeRoot> to html-report <dirCoverage>/\*
// 6. return coverage-report in html-format as single document
*/
let dirCoverage;
let filePrefix;
let htmlAll;
let nodeChildAdd;
let nodeCreate;
let nodeDict;
let nodeNormalize;
let nodeRoot;
let summaryDict;
let tmp;
// init function
nodeChildAdd = function (node, child) {
/*
* this function will add <child> to <node>
*/
node.children.push(child);
child.parent = node;
};
nodeCreate = function (pathname) {
/*
* this function will create a tree-node
*/
return {
children: [],
pathname,
metrics: {
branches: {
total: 0,
covered: 0,
skipped: 0,
pct: "Unknown"
},
functions: {
total: 0,
covered: 0,
skipped: 0,
pct: "Unknown"
},
lines: {
total: 0,
covered: 0,
skipped: 0,
pct: "Unknown"
},
statements: {
total: 0,
covered: 0,
skipped: 0,
pct: "Unknown"
}
},
name: pathname
};
};
nodeNormalize = function (node, level, filePrefix, parent) {
/*
* this function will recursively normalize <node> and its children
*/
let metric;
// init name
if (node.name.indexOf(filePrefix) === 0) {
node.name = node.name.slice(filePrefix.length);
}
if (node.name[0] === path.sep) {
node.name = node.name.slice(1);
}
// init relativeName
node.relativeName = (
parent
? (
parent.name !== "__root__/"
? node.name.slice(parent.name.length)
: node.name
)
: node.name.slice(filePrefix.length)
);
// init nameOrAllFiles
node.nameOrAllFiles = node.name || "All files";
// init relativeNameOrAllFiles
node.relativeNameOrAllFiles = node.relativeName || "All files";
// init href
node.href = node.relativeName.split(path.sep).join("/") + (
node.isFile
? ".html"
: "index.html"
);
// recurse
node.children.forEach(function (child) {
nodeNormalize(child, level + 1, filePrefix, node);
});
// sort children by name
node.children.sort(function (aa, bb) {
return (
aa.name > bb.name
? 1
: -1
);
});
// init metrics
if (!node.isFile) {
node.children.forEach(function (child) {
[
"lines", "statements", "branches", "functions"
].forEach(function (key) {
metric = node.metrics[key];
metric.total += child.metrics[key].total;
metric.covered += child.metrics[key].covered;
metric.skipped += child.metrics[key].skipped;
});
});
}
// calculate pct and score
[
"lines", "s...
n/a
istanbulInstrumentInPackage = function (code, file) {
/*
* this function will instrument <code>
* if macro /\* istanbul instrument in package $npm_package_nameLib *\/
* exists in <code>
*/
return (
(
process.env.npm_config_mode_coverage
&& code.indexOf("/* istanbul ignore all */\n") < 0 && (
process.env.npm_config_mode_coverage === "all"
|| process.env.npm_config_mode_coverage === "node_modules"
|| 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 = require("path").resolve("example.js");
// jslint code
local.jslintAndPrint(code, tmp);
// instrument code
code = local.istanbulInstrumentInPackage(code, tmp);
// init module.exports
module = new local.Module(tmp);
require.cache[tmp] = module;
module._compile(code, tmp);
// init exports
module.exports.utility2 = local;
module.exports[env.npm_package_nameLib] = (
...
istanbulInstrumentSync = function (code, file) {
/*
* this function will
// 1. normalize <file>
// 2. save <code> to __coverageInclude__[<file>] for future html-report
// 3. return instrumented-code
*/
// 1. normalize <file>
file = path.resolve(file);
// 2. save <code> to __coverageInclude__[<file>] for future html-report
// 3. return instrumented-code
return (
"globalThis.__coverageInclude__ = globalThis.__coverageInclude__ || {};"
+ "globalThis.__coverageInclude__[" + JSON.stringify(file) + "] = 1;\n"
) + new local.Instrumenter({
embedSource: true,
esModules: true,
noAutoWrap: true
}).instrumentSync(code, file).trimStart();
}
n/a
jslintAndPrint = function (code, file = "undefined", opt = {}) {
/*
* this function will jslint-autofix <code>
*/
return jslintRecurse(code, file, opt, {});
}
...
).replace(
new RegExp("require\\(." + env.npm_package_nameOriginal + ".\\)"),
"globalThis.utility2_moduleExports"
);
// init example.js
tmp = require("path").resolve("example.js");
// jslint code
local.jslintAndPrint(code, tmp);
// instrument code
code = local.istanbulInstrumentInPackage(code, tmp);
// init module.exports
module = new local.Module(tmp);
require.cache[tmp] = module;
module._compile(code, tmp);
// init exports
...
jslintAutofixLocalFunction = function (code, file) {
/*
* this function will jslint-autofix local-function
*/
let code2;
let dictFnc;
let dictProp;
if (local.isBrowser) {
return code;
}
// make file relative
file = require("path").resolve(file);
if (file.indexOf(process.cwd() + require("path").sep) === 0) {
file = file.replace(process.cwd() + require("path").sep, "");
}
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.istanbul.js":
case "lib.jslint.js":
case "lib.marked.js":
case "npm_scripts.sh":
case "test.js":
break;
default:
return code;
}
// autofix - assets.utility2.header.js
code = code.replace((
/\n\/\/\u0020assets.utility2\.header\.js\u0020-\u0020start\n[\S\s]*?\n\/\/\u0020assets.utility2\.header\.js\u0020-\u0020end\n/
), "\n" + local.assetsDict["/assets.utility2.header.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"
&& require("fs").existsSync("./assets.utility2.rollup.js")
) {
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"
], [
"utility2", "apidoc"
]
].forEach(function (dictList, ii) {
dictFnc = (
ii
? "functionAllDict"
: "functionBaseDict"
);
if (local[dictFnc]) {
return;
}
local[dictFnc] = {};
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[dictFnc][key] = (
local[dictFnc][key] || String(dict[key])
);
}
});
});
Object.keys(local[dictFnc]).forEach(function (key) {
if (process.binding("natives")[key]) {
local[dictFnc][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) ===...
n/a
listShuffle = function (list) {
/*
* this function will inplace shuffle <list> using fisher-yates algorithm
* https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
*/
let ii;
let random;
let 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
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 shuffle
...
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 to serve cached-assets
*/
if (!local.assetsDict.hasOwnProperty(req.urlParsed.pathname)) {
next();
return;
}
// do not cache if headers already sent or url has '?' search indicator
if (!(res.headersSent || req.url.indexOf("?") >= 0)) {
// init serverResponseHeaderLastModified
local.serverResponseHeaderLastModified = (
local.serverResponseHeaderLastModified
// resolve to 1000 ms
|| new Date()
);
// 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()
);
}
res.end(local.assetsDict[req.urlParsed.pathname]);
}
n/a
middlewareBodyRead = function (req, ignore, next) {
/*
* this function will run middleware to
* read and save <req> body to <req>.bodyRaw
*/
// if req is already read, then goto next
if (!req.readable) {
next();
return;
}
let bufList;
bufList = [];
req.on("data", function (buf) {
bufList.push(buf);
}).on("end", function () {
req.bodyRaw = (
local.isBrowser
? bufList[0]
: Buffer.concat(bufList)
);
next();
// on event-error, pass error to onError
}).on("error", next);
}
...
/*
* this function will run 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;
...
middlewareError = function (err, req, res) {
/*
* this function will run middleware to handle <err>
*/
// default - 404 Not Found
if (!err) {
local.serverRespondDefault(req, res, 404);
return;
}
// statusCode [400, 600)
local.serverRespondDefault(req, res, (
(err.statusCode >= 400 && err.statusCode < 600)
? err.statusCode
: 500
), err);
}
...
let gotoState;
let isDone;
gotoState = -1;
(function gotoNext(err) {
try {
gotoState += 1;
if (err || gotoState >= local.middlewareList.length) {
local.middlewareError(err, req, res);
return;
}
// recurse with next middleware in middlewareList
local.middlewareList[gotoState](req, res, gotoNext);
} catch (errCaught) {
// throw errCaught to break infinite recursion-loop
local.assertOrThrow(!isDone, errCaught);
...
middlewareFileServer = function (req, res, next) {
/*
* this function will run middleware to serve files
*/
let file;
if (req.method !== "GET" || local.isBrowser) {
next();
return;
}
// resolve file
file = require("path").resolve(
// replace trailing "/" with "/index.html"
require("url").parse(req.url).pathname.slice(1).replace((
/\/$/
), "/index.html")
);
// security - disable parent-directory lookup
if (file.indexOf(process.cwd() + require("path").sep) !== 0) {
next();
return;
}
require("fs").readFile(file, function (err, data) {
// default to next
if (err) {
next();
return;
}
// respond with data
res.end(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
/* istanbul ignore next */
...
middlewareForwardProxy = function (req, res, next) {
/*
* this function will run middleware to forward-proxy <req>
* to its destination-host
*/
let clientHeaders;
let clientReq;
let clientRes;
let clientUrl;
let isDone;
let onError;
let timeStart;
let timerTimeout;
// handle preflight-cors
if (req.method === "OPTIONS" && (
/forward-proxy-url/
).test(req.headers["access-control-request-headers"])) {
local.serverRespondHeadSet(req, res, undefined, {
"access-control-allow-headers": "*",
"access-control-allow-methods": "*",
"access-control-allow-origin": "*"
});
res.end();
return;
}
if (!req.headers["forward-proxy-url"]) {
next();
return;
}
local.serverRespondHeadSet(req, res, undefined, {
"access-control-allow-headers": "*",
"access-control-allow-methods": "*",
"access-control-allow-origin": "*"
});
// init onError
onError = function (err) {
if (isDone) {
return;
}
isDone = true;
// cleanup timerTimeout
clearTimeout(timerTimeout);
// debug middlewareForwardProxy
console.error("serverLog - " + JSON.stringify({
time: new Date(timeStart).toISOString(),
type: "middlewareForwardProxyResponse",
method: req.method,
clientUrl,
statusCode: res.statusCode | 0,
timeElapsed: Date.now() - timeStart,
// extra
headers: clientHeaders
}) + "\n");
if (!err) {
return;
}
// cleanup clientReq and clientRes
local.streamCleanup(clientReq);
local.streamCleanup(clientRes);
next(err);
};
// init timerTimeout
timerTimeout = setTimeout(
onError,
local.timeoutDefault,
new Error(
"timeout - " + local.timeoutDefault + " ms - "
+ "forward-proxy " + req.method + " " + clientUrl
)
);
// init client
clientUrl = local.urlParse(req.headers["forward-proxy-url"]).href;
try {
clientHeaders = {};
clientHeaders = JSON.parse(req.headers["forward-proxy-headers"]);
} catch (ignore) {}
clientReq = require(
clientUrl.indexOf("http:") === 0
? "http"
: "https"
).request(clientUrl, {
headers: clientHeaders
}, function (arg) {
clientRes = arg;
clientRes.on("error", onError);
res.statusCode = clientRes.statusCode;
// pipe clientRes to res
clientRes.pipe(res);
}).on("error", onError);
timeStart = Date.now();
// handle evt
req.on("error", onError);
res.on("finish", onError).on("error", onError);
// pipe req to clientReq
req.pipe(clientReq);
}
n/a
middlewareInit = function (req, res, next) {
/*
* this function will run middleware to init <req> and <res>
*/
let contentType;
// init timerTimeout
local.serverRespondTimeoutDefault(req, res, local.timeoutDefault);
// init req.urlParsed
req.urlParsed = local.urlParse(req.url);
// set reponse-header "content-type"
contentType = {
// application
".js": "application/javascript; charset=utf-8",
".json": "application/json; charset=utf-8",
".mjs": "application/javascript; charset=utf-8",
".pdf": "application/pdf",
".wasm": "application/wasm",
".xml": "application/xml; charset=utf-8",
// image
".bmp": "image/bmp",
".gif": "image/gif",
".jpe": "image/jpeg",
".jpeg": "image/jpeg",
".jpg": "image/jpeg",
".png": "image/png",
".svg": "image/svg+xml; charset=utf-8",
// text
"/": "text/html; charset=utf-8",
".css": "text/css; charset=utf-8",
".htm": "text/html; charset=utf-8",
".html": "text/html; charset=utf-8",
".md": "text/markdown; charset=utf-8",
".txt": "text/plain; charset=utf-8"
};
contentType = contentType[(
/^\/$|\.[^.]*?$|$/m
).exec(req.urlParsed.pathname)[0]];
if (contentType) {
res.setHeader("content-type", contentType);
}
// default to next
next();
}
n/a
middlewareUtility2StateInit = function (req, res, next) {
/*
* this function will run middleware to
* serve browser-state wrapped in given jsonp-callback
*/
let state;
if (!(req.stateInit || (
req.urlParsed
&& req.urlParsed.pathname === "/utility2.state.init.js"
))) {
next();
return;
}
state = {
assetsDict: {
"/assets.example.html":
local.assetsDict["/assets.example.html"],
"/assets.example.js": local.assetsDict["/assets.example.js"],
"/assets.test.js": local.assetsDict["/assets.test.js"],
"/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_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
},
init: (
"(function (state) {\n"
+ "let utility2 = globalThis.utility2;\n"
+ "utility2.assetsDict = utility2.assetsDict || {};\n"
+ "utility2.env = utility2.env || {};\n"
+ "Object.assign(utility2.assetsDict, state.assetsDict);\n"
+ "Object.assign(utility2.env, state.env);\n"
+ "}({}));\n"
)
};
if (req.stateInit) {
return state;
}
// disable $-escape in replacement-string
res.end(state.init.replace("({})", function () {
return "(\n" + JSON.stringify(state) + "\n)";
}));
}
...
), "\\\\")
+ ");\n"
+ local.assetsDict[tmp]
);
});
break;
case "local.stateInit":
tmp = local.middlewareUtility2StateInit({
stateInit: true
});
// add extra physical files to assetsDict
require("fs").readdirSync(".").forEach(function (file) {
file = "/" + file;
if (
local.assetsDict[file]
...
function noop() {
/*
* this function will do nothing
*/
return;
}
...
local.isBrowser
? {
env: {},
stdout: {}
}
: globalThis.process
);
local.noop(escodegen, esprima, estraverse, esutils);
/*
repo https://github.com/acornjs/acorn/tree/6.4.1
committed 2020-03-09T10:38:41Z
*/
...
function objectAssignDefault(tgt = {}, src = {}, depth = 0) {
/*
* this function will if items from <tgt> are null, undefined, or "",
* then overwrite them with items from <src>
*/
let recurse;
recurse = function (tgt, src, depth) {
Object.entries(src).forEach(function ([
key, bb
]) {
let aa;
aa = tgt[key];
if (aa === undefined || aa === null || aa === "") {
tgt[key] = bb;
return;
}
if (
depth !== 0
&& typeof aa === "object" && aa && !Array.isArray(aa)
&& typeof bb === "object" && bb && !Array.isArray(bb)
) {
recurse(aa, bb, depth - 1);
}
});
};
recurse(tgt, src, depth | 0);
return tgt;
}
...
return str;
};
// init opt
opt.dir = local.moduleDirname(
opt.dir,
opt.modulePathList || require("module").paths
);
local.objectAssignDefault(opt, {
env: {
npm_package_description: ""
},
packageJson: JSON.parse(readExample("package.json")),
require: function (file) {
return local.tryCatchOnError(function () {
return require(file);
...
function objectDeepCopyWithKeysSorted(obj) {
/*
* this function will recursively deep-copy <obj> with keys sorted
*/
let sorted;
if (typeof obj !== "object" || !obj) {
return obj;
}
// recursively deep-copy list with child-keys sorted
if (Array.isArray(obj)) {
return obj.map(objectDeepCopyWithKeysSorted);
}
// recursively deep-copy obj with keys sorted
sorted = {};
Object.keys(obj).sort().forEach(function (key) {
sorted[key] = objectDeepCopyWithKeysSorted(obj[key]);
});
return sorted;
}
...
start: "./npm_scripts.sh",
test: "./npm_scripts.sh",
utility2: "./npm_scripts.sh"
};
// write package.json
require("fs").writeFileSync(
"package.json",
JSON.stringify(local.objectDeepCopyWithKeysSorted(
packageJson
), undefined, 4) + "\n"
);
writeFileLog("package.json");
// re-render README.md
tgt = local.templateRenderMyApp(
local.assetsDict["/assets.readme.template.md"]
...
function onErrorThrow(err) {
/*
* this function will throw <err> if exists
*/
if (err) {
throw err;
}
}
...
promiseList.push(new Promise(function (resolve) {
require("fs").writeFile(
require("path").resolve(
process.env.npm_config_dir_build + "/test-report.json"
),
JSON.stringify(globalThis.utility2_testReport),
function (err) {
local.onErrorThrow(err);
console.error(
"\nbrowserTest - merged test-report "
+ process.env.npm_config_dir_build + "/test-report.json"
+ "\n"
);
resolve();
}
...
onParallel = function (onError, onEach, onRetry) {
/*
* this function will create function that will
* 1. run async tasks in parallel
* 2. if cnt === 0 or err occurred, then call onError(err)
*/
let onParallel;
onEach = onEach || local.noop;
onRetry = onRetry || local.noop;
onParallel = function (err, data) {
if (onRetry(err, data)) {
return;
}
// decrement cnt
onParallel.cnt -= 1;
// validate cnt
if (!(onParallel.cnt >= 0 || err || onParallel.err)) {
err = new Error(
"invalid onParallel.cnt = " + onParallel.cnt
);
// ensure onError is run only once
} else if (onParallel.cnt < 0) {
return;
}
// handle err
if (err) {
onParallel.err = err;
// ensure cnt <= 0
onParallel.cnt = -Math.abs(onParallel.cnt);
}
// call onError when isDone
if (onParallel.cnt <= 0) {
onError(err, data);
return;
}
onEach();
};
// init cnt
onParallel.cnt = 0;
// return callback
return onParallel;
}
...
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) {
console.error(err);
data.retry += 1;
setTimeout(function () {
onParallel.cnt -= 1;
onEach(data, onParallel);
}, 1000);
...
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
*/
let isListEnd;
let onEach2;
let onParallel;
opt.list = opt.list || [];
onEach2 = function () {
while (true) {
if (!(onParallel.ii + 1 < opt.list.length)) {
isListEnd = true;
return;
}
if (!(onParallel.cnt < 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) {
console.error(err);
data.retry += 1;
setTimeout(function () {
onParallel.cnt -= 1;
onEach(data, onParallel);
}, 1000);
return true;
}
// restart if opt.list has grown
if (isListEnd && (onParallel.ii + 1 < opt.list.length)) {
isListEnd = undefined;
onEach2();
}
});
onParallel.ii = -1;
opt.rateLimit = Number(opt.rateLimit) || 6;
opt.rateLimit = Math.max(opt.rateLimit, 1);
opt.retryLimit = Number(opt.retryLimit) || 2;
onParallel.cnt += 1;
onEach2();
onParallel();
}
...
return testCase.name;
}).join(", ") + " ..."
);
}
}, 2000);
// shallow-copy testPlatform.testCaseList to prevent side-effects
// from in-place sort from testReportMerge
local.onParallelList({
list: testPlatform.testCaseList.slice()
}, function (testCase, onParallel) {
let onError;
let timerTimeout;
onError = function (err) {
// update testPlatform.timeElapsed
local.timeElapsedPoll(testPlatform);
...
replStart = function () {
/*
* this function will start repl-debugger
*/
let that;
if (globalThis.utility2_repl1) {
return;
}
// start repl
that = require("repl").start({
useGlobal: true
});
globalThis.utility2_repl1 = that;
// save eval-function
that.evalDefault = that.eval;
// hook custom-eval-function
that.eval = function (script, context, file, onError) {
script.replace((
/^(\S+)\u0020(.*?)\n/
), function (ignore, match1, match2) {
switch (match1) {
// syntax-sugar - run shell-command
case "$":
match2 = match2.replace((
/^git\b/
), "git --no-pager");
switch (match2) {
// syntax-sugar - run git diff
case "git --no-pager diff":
match2 = "git diff --color";
break;
// syntax-sugar - run git log
case "git --no-pager log":
match2 = "git log -n 4";
break;
// syntax-sugar - run ll
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 shell-command
require("child_process").spawn(match2, {
shell: true,
stdio: [
"ignore", 1, 2
]
// print exitCode
}).on("exit", function (exitCode) {
console.error("exitCode " + exitCode);
that.evalDefault("\n", context, file, onError);
});
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 shell-command
require("child_process").spawn((
"find . -type f | grep -v -E "
/* jslint ignore:start */
+ '"\
/\\.|~\$|/(obj|release)/|(\\b|_)(\\.\\d|\
archive|artifact|\
bower_component|build|\
coverage|\
doc|\
external|\
fixture|\
git_module|\
jquery|\
log|\
min|misc|mock|\
node_module|\
old|\
raw|\rollup|\
swp|\
tmp|\
vendor)s{0,1}(\\b|_)\
" '
/* jslint ignore:end */
+ "| tr \"\\n\" \"\\000\" | xargs -0 grep -HIin -E \""
+ match2 + "\""
), {
shell: true,
stdio: [
"ignore", 1, 2
]
}).on("exit", function (exitCode) {...
...
local.cliDict["utility2.start"] = function () {
/*
* <port>
* will start utility2 http-server on given <port> (default 8081)
*/
globalThis.local = local;
local.replStart();
local.testRunServer({});
if (process.env.npm_config_runme) {
require(require("path").resolve(process.env.npm_config_runme));
}
};
local.cliDict["utility2.testReportCreate"] = function () {
...
requireReadme = function () {
/*
* this function will require and export example.js embedded in README.md
*/
let code;
let env;
let module;
let tmp;
// init env
env = (typeof process === "object" && process && process.env) || {};
// library-mode
if (env.npm_config_mode_lib) {
local.testRunDefault = local.noop;
return local;
}
// init module.exports
module = {};
// if file is modified, then restart process
if (env.npm_config_mode_auto_restart) {
require("fs").readdir(".", function (ignore, fileList) {
fileList.concat(__filename).forEach(function (file) {
require("fs").stat(file, function (err, data) {
local.onErrorThrow(err);
if (!data.isFile()) {
return;
}
require("fs").watchFile(file, {
interval: 1000,
persistent: false
}, function () {
console.error("file modified - " + file);
setTimeout(function () {
process.exit(77);
}, 1000);
});
});
});
});
}
if (local.isBrowser) {
module.exports = local.objectAssignDefault(
globalThis.utility2_rollup || globalThis.local,
local
);
return module.exports;
}
// start repl-debugger
local.replStart();
// jslint process.cwd()
require("child_process").spawn("node", [
"-e", (
"require(" + JSON.stringify(__filename)
+ ").jslint.jslintAndPrintDir(" + JSON.stringify(process.cwd())
+ ", {autofix:" + (!env.npm_config_mode_test)
+ ",conditional:true});"
)
], {
env: Object.assign({}, env, {
npm_config_mode_lib: "1"
}),
stdio: [
"ignore", 1, 2
]
});
if (globalThis.utility2_rollup || env.npm_config_mode_start) {
// init assets index.html
local.assetsDict["/index.html"] = (
local.fsReadFileOrDefaultSync("index.html", "utf8", "")
|| local.assetsDict["/index.rollup.html"] || ""
);
local.assetsDict["/"] = local.assetsDict["/index.html"];
local.assetsDict["/assets.app.js"] = require("fs").readFileSync(
__filename,
"utf8"
).replace((
/^#!\//
), "// ");
// init exports
local[env.npm_package_nameLib] = local;
module.exports = local;
return module.exports;
}
// init file $npm_package_main
globalThis.utility2_moduleExports = require(
require("path").resolve(env.npm_package_main)
);
globalThis.utility2_moduleExports.globalThis = globalThis;
// read code from README.md
code = local.templateRenderMyApp(
local.assetsDict["/assets.example.template.js"]
);
local.fsReadFileOrDefaultSync("README.md", "utf8", "").replace((
/\n```javascript(\n\/\*\nexample\.js\n[\S\s]*?\n)```\n/
), function (ignore, match1, ii, input) {
// preserve lineno
code = input.slice(0, ii).replace((
/.+/g
), "") + "\n" + match1;
return "";
});
// alias require($npm_package_name) to utility2_moduleExports;
code = code.replace(
new RegExp("require\\(." + env.npm_package_name + ".\\)"),
"globalThis.utility2_moduleExports"
).replace(
new RegExp("require\\(." + env.npm_package_nameOrig...
...
\n\
\n\
/* istanbul ignore next */\n\
// run shared js\-env code - init-before\n\
(function () {\n\
// init local\n\
local = globalThis.utility2 || require("utility2");\n\
local = local.requireReadme();\n\
globalThis.local = local;\n\
// init test\n\
local.testRunDefault(local);\n\
}());\n\
\n\
\n\
// run shared js\-env code - function\n\
...
serverLocalReqHandler = function (req, res) {
/*
* this function will emulate express-like middleware-chaining
*/
let gotoState;
let isDone;
gotoState = -1;
(function gotoNext(err) {
try {
gotoState += 1;
if (err || gotoState >= local.middlewareList.length) {
local.middlewareError(err, req, res);
return;
}
// recurse with next middleware in middlewareList
local.middlewareList[gotoState](req, res, gotoNext);
} catch (errCaught) {
// throw errCaught to break infinite recursion-loop
local.assertOrThrow(!isDone, errCaught);
isDone = true;
gotoNext(errCaught);
}
}());
}
...
if (isDone) {
return;
}
isDone = true;
data = _data;
// async send req from client to server
setTimeout(function () {
local.serverLocalReqHandler(req, res);
});
},
headers: xhr.headers,
method: xhr.method,
on: function () {
return xhr;
},
...
serverLocalUrlTest = function (url) {
/*
* this function will test if <url> is local
*/
url = local.urlParse(url).pathname;
return local.isBrowser && !local.env.npm_config_mode_backend && (
/^\/test\./
).test(url);
}
...
xhr.resHeaders = {};
xhr.timeStart = xhr.timeStart || Date.now();
};
// 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();
...
serverRespondDefault = function (req, res, statusCode, err) {
/*
* this function will respond with default http <statusCode> and message,
* or <err>.stack for given statusCode
*/
let msg;
// init statusCode and contentType
local.serverRespondHeadSet(req, res, statusCode, {
"Content-Type": "text/plain; charset=utf-8"
});
if (err) {
// debug statusCode / method / url
err.message = (
res.statusCode + " " + req.method + " " + req.url + "\n"
+ err.message
);
// print err.stack to stderr
console.error(err);
// end res with err.stack
res.end(err.stack);
return;
}
// end res with default statusCode and http-message
msg = {
"100": "Continue",
"101": "Switching Protocols",
"102": "Processing",
"103": "Early Hints",
"200": "OK",
"201": "Created",
"202": "Accepted",
"203": "Non-Authoritative Information",
"204": "No Content",
"205": "Reset Content",
"206": "Partial Content",
"207": "Multi-Status",
"208": "Already Reported",
"226": "IM Used",
"300": "Multiple Choices",
"301": "Moved Permanently",
"302": "Found",
"303": "See Other",
"304": "Not Modified",
"305": "Use Proxy",
"307": "Temporary Redirect",
"308": "Permanent Redirect",
"400": "Bad Request",
"401": "Unauthorized",
"402": "Payment Required",
"403": "Forbidden",
"404": "Not Found",
"405": "Method Not Allowed",
"406": "Not Acceptable",
"407": "Proxy Authentication Required",
"408": "Request Timeout",
"409": "Conflict",
"410": "Gone",
"411": "Length Required",
"412": "Precondition Failed",
"413": "Payload Too Large",
"414": "URI Too Long",
"415": "Unsupported Media Type",
"416": "Range Not Satisfiable",
"417": "Expectation Failed",
"418": "I'm a Teapot",
"421": "Misdirected Request",
"422": "Unprocessable Entity",
"423": "Locked",
"424": "Failed Dependency",
"425": "Unordered Collection",
"426": "Upgrade Required",
"428": "Precondition Required",
"429": "Too Many Requests",
"431": "Request Header Fields Too Large",
"451": "Unavailable For Legal Reasons",
"500": "Internal Server Error",
"501": "Not Implemented",
"502": "Bad Gateway",
"503": "Service Unavailable",
"504": "Gateway Timeout",
"505": "HTTP Version Not Supported",
"506": "Variant Also Negotiates",
"507": "Insufficient Storage",
"508": "...
...
local.middlewareError = function (err, req, res) {
/*
* this function will run middleware to handle <err>
*/
// default - 404 Not Found
if (!err) {
local.serverRespondDefault(req, res, 404);
return;
}
// statusCode [400, 600)
local.serverRespondDefault(req, res, (
(err.statusCode >= 400 && err.statusCode < 600)
? err.statusCode
: 500
...
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(new Error());
//!! // test multiple-callback-error handling-behavior
...
serverRespondHeadSet = function (ignore, res, statusCode, headers) {
/*
* this function will set <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) {
res.setHeader(key, headers[key]);
});
return true;
}
...
let onError;
let timeStart;
let timerTimeout;
// handle preflight-cors
if (req.method === "OPTIONS" && (
/forward-proxy-url/
).test(req.headers["access-control-request-headers"])) {
local.serverRespondHeadSet(req, res, undefined, {
"access-control-allow-headers": "*",
"access-control-allow-methods": "*",
"access-control-allow-origin": "*"
});
res.end();
return;
}
...
serverRespondTimeoutDefault = function (req, res, timeout) {
/*
* this function will create <timeout>-handler for server-<req>
*/
let isDone;
let onError;
onError = function () {
if (isDone) {
return;
}
isDone = true;
// debug res
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
reqContentLength: req.dataLength || 0,
resContentLength: res.contentLength,
reqHeaderXForwardedFor: req.headers["x-forwarded-for"] || "",
reqHeaderOrigin: req.headers.origin || "",
reqHeaderReferer: req.headers.referer || "",
reqHeaderUserAgent: req.headers["user-agent"]
}) + "\n");
// 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
timeout = timeout || local.timeoutDefault;
req.timerTimeout = setTimeout(
req.onTimeout,
timeout,
new Error(
"timeout - " + timeout + " ms - "
+ "server " + req.method + " " + req.url
)
);
res.contentLength = 0;
res.writeContentLength = res.writeContentLength || res.write;
res.write = function (buf, encoding, callback) {
buf = local.bufferValidateAndCoerce(buf, typeof buf);
res.contentLength += buf.length;
res.writeContentLength(buf, encoding, callback);
};
res.on("error", onError);
res.on("finish", onError);
}
...
local.middlewareInit = function (req, res, next) {
/*
* this function will run middleware to init <req> and <res>
*/
let contentType;
// init timerTimeout
local.serverRespondTimeoutDefault(req, res, local.timeoutDefault);
// init req.urlParsed
req.urlParsed = local.urlParse(req.url);
// set reponse-header "content-type"
contentType = {
// application
".js": "application/javascript; charset=utf-8",
".json": "application/json; charset=utf-8",
...
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;
}
...
* 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";
...
stateInit = function (opt) {
/*
* this function will init state <opt>
*/
[
opt, local
].forEach(function (dict) {
local.objectAssignDefault(dict, {
utility2: {
assetsDict: {},
env: {}
}
}, -1);
});
Object.assign(local.utility2.assetsDict, opt.utility2.assetsDict);
Object.assign(local.utility2.env, opt.utility2.env);
}
...
// run shared js-env code - init-after
(function () {
// hack-coverage - test testRunServer's multiple-call handling-behavior
local.testRunServer(local);
// hack-coverage - stateInit
local.stateInit({});
// init test-middleware
local.middlewareList.push(function (req, res, next) {
/*
* this function will run test-middleware
*/
switch (req.urlParsed.pathname) {
// test http POST handling-behavior
...
streamCleanup = function (stream) {
/*
* this function will try to end or destroy <stream>
*/
let err;
// try to end stream
try {
stream.end();
} catch (errCaught) {
err = errCaught;
}
// if err, then try to destroy stream
if (err) {
try {
stream.destroy();
} catch (ignore) {}
}
}
...
// extra
headers: clientHeaders
}) + "\n");
if (!err) {
return;
}
// cleanup clientReq and clientRes
local.streamCleanup(clientReq);
local.streamCleanup(clientRes);
next(err);
};
// init timerTimeout
timerTimeout = setTimeout(
onError,
local.timeoutDefault,
...
stringHtmlSafe = function (str) {
/*
* this function will make <str> html-safe
* https://stackoverflow.com/questions/7381974/which-characters-need-to-be-escaped-on-html
*/
return str.replace((
/&/gu
), "&").replace((
/"/gu
), """).replace((
/'/gu
), "'").replace((
/</gu
), "<").replace((
/>/gu
), ">").replace((
/&(amp;|apos;|gt;|lt;|quot;)/igu
), "&$1");
}
...
);
// handle case where module is a function
elem.name = elem.name.replace(">.<", "><");
if (elem.typeof !== "function") {
return elem;
}
// init source
elem.source = local.stringHtmlSafe(
trimStart(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> with no magic
*/
str2.replace(rgx, function (match2) {
str1.replace(rgx, function (match1) {
str1 = str1.replace(match1, function () {
return match2;
});
return "";
});
return "";
});
return str1;
}
...
return code;
}
// autofix - assets.utility2.header.js
code = code.replace((
/\n\/\/\u0020assets.utility2\.header\.js\u0020-\u0020start\n[\S\s]*?\n\/\/\u0020assets.utility2\.header\.js\u0020-\u0020end\
n/
), "\n" + local.assetsDict["/assets.utility2.header.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/
)
...
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
*/
assertJsonEqual(
local.stringQuotedToAscii(local.stringHelloEmoji),
"hello \\ud83d\\ude01\n"
);
onError(undefined, opt);
};
local.testCase_stringRegexpEscape_default = function (opt, onError) {
/*
...
stringRegexpEscape = function (str) {
/*
* this function will regexp-escape <str>
* https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
*/
return str.replace((
/[\-\/\\\^$*+?.()|\[\]{}]/g
), "\\$&");
}
...
};
local.testCase_stringRegexpEscape_default = function (opt, onError) {
/*
* this function will test stringRegexpEscape's default handling-behavior
*/
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\\[\\\\\\]\\^_`"
...
templateRender = function (template, dict, opt = {}, ii = 0) {
/*
* this function will render <template> with given <dict>
*/
let argList;
let getVal;
let match;
let renderPartial;
let rgx;
let skip;
let val;
if (dict === null || dict === undefined) {
dict = {};
}
getVal = function (key) {
argList = key.split(" ");
val = dict;
if (argList[0] === "#this/") {
return val;
}
if (argList[0] === "#ii/") {
return ii;
}
// iteratively lookup nested val in dict
argList[0].split(".").forEach(function (key) {
val = val && val[key];
});
return val;
};
renderPartial = function (match0, helper, key, partial) {
switch (helper) {
case "each":
case "eachTrimEndComma":
val = getVal(key);
val = (
Array.isArray(val)
? val.map(function (dict, ii) {
// recurse with partial
return local.templateRender(partial, dict, opt, ii);
}).join("")
: ""
);
// remove trailing-comma from last elem
if (helper === "eachTrimEndComma") {
val = val.trimEnd().replace((
/,$/
), "");
}
return val;
case "if":
partial = partial.split("{{#unless " + key + "}}");
partial = (
getVal(key)
? partial[0]
// handle "unless" case
: partial.slice(1).join("{{#unless " + key + "}}")
);
// recurse with partial
return local.templateRender(partial, dict, opt);
case "unless":
return (
getVal(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 template
return template.replace((
/\{\{[^}]+?\}\}/g
), function (match0) {
let markdownToHtml;
let notHtmlSafe;
notHtmlSafe = opt.notHtmlSafe;
try {
val = getVal(match0.slice(2, -2));
if (val === undefined) {
return match0;
}
argList.slice(1).forEach(function (fmt, ii, list) {
switch (fmt) {
case "*":
case "+":
case "-":
case "/":
skip = ii + 1;
val = String(
fmt === "*"
? Number(val) * Number(list[skip])
: fmt === "+"
? Number(val) + Number(list[skip])
: fmt === "-"
? Number(val) - Number(list[skip])
: Number(val) / Number(list[skip])
);
break;
case "a...
...
case "each":
case "eachTrimEndComma":
val = getVal(key);
val = (
Array.isArray(val)
? val.map(function (dict, ii) {
// recurse with partial
return local.templateRender(partial, dict, opt, ii);
}).join("")
: ""
);
// remove trailing-comma from last elem
if (helper === "eachTrimEndComma") {
val = val.trimEnd().replace((
/,$/
...
templateRenderMyApp = function (template) {
/*
* this function will render my-app-lite template
*/
let githubRepo;
let packageJson;
packageJson = JSON.parse(
require("fs").readFileSync("package.json", "utf8")
);
local.objectAssignDefault(packageJson, {
nameLib: packageJson.name.replace((
/\W/g
), "_"),
repository: {
url: (
"https://github.com/kaizhu256/node-" + packageJson.name
)
}
}, 2);
githubRepo = packageJson.repository.url.replace((
/\.git$/
), "").split("/").slice(-2);
template = template.replace((
/kaizhu256(\.github\.io\/|%252F|\/)/g
), githubRepo[0] + ("$1"));
template = template.replace((
/node-my-app-lite/g
), githubRepo[1]);
template = template.replace((
/\bh1-my-app\b/g
), (
packageJson.nameHeroku
|| ("h1-" + packageJson.nameLib.replace((
/_/g
), "-"))
));
template = template.replace((
/my-app-lite/g
), packageJson.name);
template = template.replace((
/my_app/g
), packageJson.nameLib);
template = template.replace((
/\{\{packageJson\.(\S+)\}\}/g
), function (ignore, match1) {
return packageJson[match1];
});
return template;
}
...
});
});
});
};
buildLib = function (resolve) {
src = fileDict["lib." + packageNameLib + ".js"];
// render lib.xxx.js
tgt = local.templateRenderMyApp(
local.assetsDict["/assets.my_app.template.js"]
);
tgtReplaceConditional(true, [
{
// customize top-level comment-description
merge: (
/\n\u0020\*\n(?:[\S\s]*?\n)?\u0020\*\/\n/
...
testMock = function (mockList, onTestCase, onError) {
/*
* this function will mock objects in <mockList> when running <onTestCase>
*/
let onError2;
onError2 = function (err) {
// restore mock[0] from mock[2]
mockList.reverse().forEach(function (mock) {
Object.keys(mock[2]).forEach(function (key) {
try {
mock[0][key] = mock[2][key];
} catch (errCaught) {
console.error(errCaught);
}
});
});
onError(err);
};
// suppress console.error and console.log
mockList.unshift([
console, {}
]);
local.objectAssignDefault(mockList[0][1], {
error: local.noop,
log: local.noop
});
// mock mock[0]
mockList.forEach(function (mock) {
mock[2] = {};
// backup mock[0] into mock[2]
Object.keys(mock[1]).forEach(function (key) {
mock[2][key] = mock[0][key];
});
// override mock[0] with mock[1]
Object.keys(mock[1]).forEach(function (key) {
try {
mock[0][key] = mock[1][key];
} catch (errCaught) {
console.error(errCaught);
}
});
});
// try to run onTestCase with mock[0]
try {
// run onTestCase
onTestCase(onError2);
} catch (errCaught) {
onError2(errCaught);
}
}
...
mockDict[key] = noop;
}
});
mockList.push([
dict, mockDict
]);
});
local.testMock(mockList, function (onError) {
try {
exports = require(file);
} catch (errCaught) {
console.error(errCaught);
}
onError();
}, local.onErrorThrow);
...
testReportCreate = function (testReport) {
/*
* this function will create test-report artifacts
*/
testReport = local.objectAssignDefault(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|"
+ String(
testPlatform.timeElapsed + " ms "
).padStart(16, " ")
+ String(
testPlatform.testsFailed + " failed "
).padStart(16, " ")
+ String(
testPlatform.testsPassed + " passed "
).padStart(16, " ")
+ " |\n" + new Array(56).join("-")
);
}).join("\n") + "\n"
);
// create test-report.html
local.fsWriteFileWithMkdirpSync(
".tmp/build/test-report.html",
local.testReportMerge(testReport)
);
// create build.badge.svg
local.fsWriteFileWithMkdirpSync(
".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", " ")
+ " - " + process.env.CI_BRANCH + " - " + process.env.CI_COMMIT_ID
))
);
// create test-report.badge.svg
local.fsWriteFileWithMkdirpSync(
".tmp/build/test-report.badge.svg",
local.assetsDict["/assets.testReportBadge.template.svg"].replace((
// edit number of tests failed
/999/g
), testReport.testsFailed).replace((
// edit badge color
/d00/g
), (
testReport.testsFailed
? "d00"
: "0d0"
))
);
// if any test failed, then exit with non-zero exitCode
console.error(
"\n" + process.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, undefined, 4));
}
});
});
return testReport;
}
...
local.cliDict["utility2.testReportCreate"] = function () {
/*
*
* will create test-report
*/
process.exit(
local.testReportCreate(
JSON.parse(
require("fs").readFileSync(
require("path").resolve(
process.env.npm_config_dir_build + "/test-report.json"
),
"utf8"
)
...
testReportMerge = function (testReport1, testReport2 = {}) {
/*
* this function will
* 1. merge testReport2 into testReport1
* 2. return testReport1 in html-format
*/
let errStackList;
let testCaseNumber;
let testReport;
// 1. merge testReport2 into testReport1
[
testReport1, testReport2
].forEach(function (testReport, ii) {
ii += 1;
local.objectAssignDefault(testReport, {
date: new Date().toISOString(),
errStackList: [],
testPlatformList: [],
timeElapsed: 0
}, -1);
// security - handle malformed testReport
local.assertOrThrow(
typeof testReport === "object" && testReport,
ii + " invalid testReport " + typeof testReport
);
// validate timeElapsed
local.assertOrThrow(
typeof testReport.timeElapsed === "number",
ii + " invalid testReport.timeElapsed "
+ typeof testReport.timeElapsed
);
// security - handle malformed testReport.testPlatformList
testReport.testPlatformList.forEach(function (testPlatform) {
local.objectAssignDefault(testPlatform, {
name: "undefined",
testCaseList: [],
timeElapsed: 0
}, -1);
local.assertOrThrow(
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.assertOrThrow(
typeof testPlatform.timeElapsed === "number",
(
ii + " invalid testPlatform.timeElapsed "
+ typeof testPlatform.timeElapsed
)
);
// security - handle malformed testPlatform.testCaseList
testPlatform.testCaseList.forEach(function (testCase) {
local.objectAssignDefault(testCase, {
errStack: "",
name: "undefined",
timeElapsed: 0
}, -1);
local.assertOrThrow(
typeof testCase.errStack === "string",
ii + " invalid testCase.errStack "
+ typeof testCase.errStack
);
local.assertOrThrow(
typeof testCase.name === "string",
ii + " invalid testCase.name " + typeof testCase.name
);
// validate timeElapsed
local.assertOrThrow(
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) {
// update failed test...
...
// merge browser-screenshot
data.testPlatformList[0].screenshot = fileScreenshot.replace((
/.*\//
), "");
// merge browser-coverage
local.istanbulCoverageMerge(globalThis.__coverage__, data.coverage);
// merge browser-test-report
local.testReportMerge(globalThis.utility2_testReport, data);
// save test-report.json
promiseList.push(new Promise(function (resolve) {
require("fs").writeFile(
require("path").resolve(
process.env.npm_config_dir_build + "/test-report.json"
),
JSON.stringify(globalThis.utility2_testReport),
...
testRunBrowser = function () {
/*
* this function will run browser-tests
*/
// hide browser-tests
if (document.querySelector("#htmlTestReport1").style.maxHeight !== "0px") {
local.uiAnimateSlideUp(document.querySelector("#htmlTestReport1"));
document.querySelector(
"#buttonTestRun1"
).textContent = "run browser-tests";
return;
}
// show browser-tests
local.uiAnimateSlideDown(document.querySelector("#htmlTestReport1"));
document.querySelector(
"#buttonTestRun1"
).textContent = "hide browser-tests";
local.modeTest = 1;
local.testRunDefault(globalThis.local);
// reset output
document.querySelectorAll(".onevent-reset-output").forEach(function (elem) {
elem.textContent = "";
});
}
n/a
testRunDefault = function (opt) {
/*
* this function will run tests in testPlatform.testCaseList
*/
let consoleError;
let isCoverage;
let processExit;
let testPlatform;
let testReport;
let 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
globalThis.utility2_onReadyAfter(function () {
local.testRunDefault(opt);
});
return;
// test-run
default:
// test-ignore
if (
globalThis.utility2_onReadyBefore.cnt
|| !globalThis.utility2_modeTest
|| globalThis.utility2_modeTest > 2
) {
return;
}
// test-run
globalThis.utility2_modeTest += 1;
}
// visual notification - testRun
local.ajaxProgressUpdate();
// mock console.error
consoleError = console.error;
isCoverage = (
typeof globalThis.__coverage__ === "object" && globalThis.__coverage__
&& Object.keys(globalThis.__coverage__).length
);
console.error = function (...argList) {
/*
* this function will ignore serverLog-msg during test-run
*/
if (!isCoverage && !(
/^serverLog\u0020-\u0020\{/
).test(argList[0])) {
consoleError(...argList);
}
};
// mock proces.exit
if (!local.isBrowser) {
processExit = process.exit;
process.exit = function (exitCode) {
local.eventListenerEmit(
"utility2.testRunMock.process.exit",
exitCode | 0
);
};
}
// init modeTestCase
local.modeTestCase = (
local.modeTestCase
|| local.env.npm_config_mode_test_case || ""
);
// init testReport
testReport = globalThis.utility2_testReport;
// init testReport timer
local.timeElapsedPoll(testReport);
// init testPlatform
testPlatform = testReport.testPlatformList[0];
// init testPlatform timer
local.timeElapsedPoll(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]
});
}
});
local.testReportMerge(testReport);
if (local.isBrowser) {
document.querySelectorAll("#htmlTestReport1").forEach(function (elem) {
local.uiAnimateSlideDown(elem);
elem.innerHTML = local.testReportMerge(testReport);
});
}
local.eventListenerEmit("utility2.testRunStart", testReport);
// testRunProgressUpdate every 2000 ms until isDone
timerInterval = setInterval(function () {
// update testPlatform.timeElapsed
local.timeElapsedPoll(testPlatform);
if (local.isBrowser) {
document.querySelector(
"#htmlTestReport1"
).innerHTML = local.testReportMerge(testReport);
}
local.eventListenerEmit("utility2.testRunProgressUpdate", testReport);
// cleanup timerInterval
if (!tes...
...
// run shared js\-env code - init-before\n\
(function () {\n\
// init local\n\
local = globalThis.utility2 || require("utility2");\n\
local = local.requireReadme();\n\
globalThis.local = local;\n\
// init test\n\
local.testRunDefault(local);\n\
}());\n\
\n\
\n\
// run shared js\-env code - function\n\
(function () {\n\
return;\n\
}());\n\
...
testRunServer = function (opt) {
/*
* this function will
* 1. create server from local.middlewareList
* 2. start server on local.env.PORT
* 3. run tests
*/
// 1. create server from local.middlewareList
local.middlewareList = local.middlewareList || [
local.middlewareInit,
local.middlewareForwardProxy,
local.middlewareAssetsCached,
local.middlewareUtility2StateInit,
local.middlewareFileServer
];
if (globalThis.utility2_serverHttp1 || (
typeof process === "object"
&& process
&& process.env.npm_config_mode_lib
)) {
return;
}
globalThis.utility2_onReadyBefore.cnt += 1;
local.serverLocalReqHandler = function (req, res) {
/*
* this function will emulate express-like middleware-chaining
*/
let gotoState;
let isDone;
gotoState = -1;
(function gotoNext(err) {
try {
gotoState += 1;
if (err || gotoState >= local.middlewareList.length) {
local.middlewareError(err, req, res);
return;
}
// recurse with next middleware in middlewareList
local.middlewareList[gotoState](req, res, gotoNext);
} catch (errCaught) {
// throw errCaught to break infinite recursion-loop
local.assertOrThrow(!isDone, errCaught);
isDone = true;
gotoNext(errCaught);
}
}());
};
globalThis.utility2_serverHttp1 = local.http.createServer(
local.serverLocalReqHandler
);
// 2. start server on local.env.PORT
console.error("http-server listening on port " + local.env.PORT);
globalThis.utility2_onReadyBefore.cnt += 1;
globalThis.utility2_serverHttp1.listen(
local.env.PORT,
globalThis.utility2_onReadyBefore
);
// 3. run tests
local.testRunDefault(opt);
globalThis.utility2_onReadyBefore();
}
...
local.cliDict["utility2.start"] = function () {
/*
* <port>
* will start utility2 http-server on given <port> (default 8081)
*/
globalThis.local = local;
local.replStart();
local.testRunServer({});
if (process.env.npm_config_runme) {
require(require("path").resolve(process.env.npm_config_runme));
}
};
local.cliDict["utility2.testReportCreate"] = function () {
/*
...
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) {
// handle err
assertOrThrow(err, err);
onError(undefined, opt);
});
};
...
timeElapsedPoll = function (opt) {
/*
* this function will poll (Date.now() - <opt>.timeStart)
*/
opt.timeStart = opt.timeStart || Date.now();
opt.timeElapsed = Date.now() - opt.timeStart;
}
...
> bb.status.replace("passed", "z") + bb.name
? 1
: -1
);
});
// stop testReport timer
if (!testReport.testsPending) {
local.timeElapsedPoll(testReport);
}
// 2. return testReport1 in html-format
// deepcopy testReport that will be modified for html templating
testReport = JSON.parse(JSON.stringify(testReport1));
// update timeElapsed
local.timeElapsedPoll(testReport);
testReport.testPlatformList.forEach(function (testPlatform) {
...
tryCatchOnError = function (fnc, onError) {
/*
* this function will run <fnc> in tryCatch block,
* else call onError with errCaught
*/
let result;
// validate onError
local.assertOrThrow(typeof onError === "function", typeof onError);
try {
// reset errCaught
delete local._debugTryCatchError;
result = fnc();
delete local._debugTryCatchError;
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
*/
let result;
local.tryCatchOnError(function () {
file = require("path").resolve(opt.dir, file);
console.error("apidocCreate - readExample " + file);
result = "";
result = local.identity(
"\n\n\n\n\n\n\n\n"
// bug-workaround - truncate example to manageable size
+ require("fs").readFileSync(file, "utf8").slice(0, 262144)
...
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);
}
...
assertOrThrow(
opt.style.maxHeight.indexOf("px") >= 0,
opt.style.maxHeight
);
local.uiAnimateSlideUp(opt);
assertJsonEqual(opt.style.maxHeight, "0px");
// test uiAnimateSlideAccordian handling-behavior
local.uiAnimateSlideAccordian(
opt,
[
opt, document.createElement("div")
]
);
onError(undefined, opt);
};
...
uiAnimateSlideDown = function (elem, onError) {
/*
* this function will slideDown dom-<elem>
*/
onError = onError || local.noop;
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);
}
...
local.uiAnimateSlideUp(document.querySelector("#htmlTestReport1"));
document.querySelector(
"#buttonTestRun1"
).textContent = "run browser-tests";
return;
}
// show browser-tests
local.uiAnimateSlideDown(document.querySelector("#htmlTestReport1"));
document.querySelector(
"#buttonTestRun1"
).textContent = "hide browser-tests";
local.modeTest = 1;
local.testRunDefault(globalThis.local);
// reset output
document.querySelectorAll(".onevent-reset-output").forEach(function (elem) {
...
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);
}
...
local.testRunBrowser = function () {
/*
* this function will run browser-tests
*/
// hide browser-tests
if (document.querySelector("#htmlTestReport1").style.maxHeight !== "0px") {
local.uiAnimateSlideUp(document.querySelector("#htmlTestReport1"));
document.querySelector(
"#buttonTestRun1"
).textContent = "run browser-tests";
return;
}
// show browser-tests
local.uiAnimateSlideDown(document.querySelector("#htmlTestReport1"));
...
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(undefined, opt);
};
local.testCase_urlJoin_default = function (opt, onError) {
/*
* this function will test urlJoin's default handling-behavior
*/
assertJsonEqual(local.urlJoin("", ""), "/");
assertJsonEqual(local.urlJoin("http://aa/bb", "zz"), "http://aa/zz");
assertJsonEqual(
local.urlJoin("http://aa/bb/", "zz"),
"http://aa/bb/zz"
);
assertJsonEqual(
local.urlJoin("http://aa/bb/", "/zz"),
...
urlParse = function (url) {
/*
* this function will parse <url> according to below spec,
* with additional query-property
* https://developer.mozilla.org/en-US/docs/Web/API/URL
*/
let 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 {
process.env.PORT = process.env.PORT || "8081";
local.serverLocalHost = (
local.serverLocalHost
|| ("http://127.0.0.1:" + process.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 = require("url").parse(url);
}
// init query
urlParsed.query = {};
local.coalesce(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];
}
return "";
});
urlParsed.basename = urlParsed.pathname.replace((
/^.*\//
), "");
}, local.noop);
// 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 || ""
};
}
...
local.timeoutDefault,
new Error(
"timeout - " + local.timeoutDefault + " ms - "
+ "forward-proxy " + req.method + " " + clientUrl
)
);
// init client
clientUrl = local.urlParse(req.headers["forward-proxy-url"]).href;
try {
clientHeaders = {};
clientHeaders = JSON.parse(req.headers["forward-proxy-headers"]);
} catch (ignore) {}
clientReq = require(
clientUrl.indexOf("http:") === 0
? "http"
...
uuid4Create = function () {
/*
* this function will create random uuid,
* with format 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
*/
// code derived from http://jsperf.com/uuid4
let id;
let ii;
id = "";
ii = 0;
while (ii < 32) {
switch (ii) {
case 8:
case 20:
id += "-";
// coerce to finite integer
id += local.identity((Math.random() * 16) | 0).toString(16);
break;
case 12:
id += "-";
id += "4";
break;
case 16:
id += "-";
id += local.identity((Math.random() * 4) | 8).toString(16);
break;
default:
// coerce to finite integer
id += local.identity((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
*/
assertOrThrow(
local.regexpValidateUuid.test(local.uuid4Create()),
local.uuid4Create()
);
onError(undefined, opt);
};
local.testCase_webpage_err = function (opt, onError) {
/*
...
function Module(id = '', parent) { this.id = id; this.path = path.dirname(id); this.exports = {}; moduleParentCache.set(this, parent); updateChildren(parent, this, false); this.filename = null; this.loaded = false; this.children = []; }
...
// init example.js
tmp = require("path").resolve("example.js");
// jslint code
local.jslintAndPrint(code, tmp);
// instrument code
code = local.istanbulInstrumentInPackage(code, tmp);
// init module.exports
module = new local.Module(tmp);
require.cache[tmp] = module;
module._compile(code, tmp);
// init exports
module.exports.utility2 = local;
module.exports[env.npm_package_nameLib] = (
globalThis.utility2_moduleExports
);
...
class SourceMap {
#payload;
#mappings = [];
#sources = {};
#sourceContentByURL = {};
/**
* @constructor
* @param {SourceMapV3} payload
*/
constructor(payload) {
if (!base64Map) {
const base64Digits =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
base64Map = {};
for (let i = 0; i < base64Digits.length; ++i)
base64Map[base64Digits[i]] = i;
}
this.#payload = cloneSourceMapV3(payload);
this.#parseMappingPayload();
}
/**
* @return {Object} raw source map v3 payload.
*/
get payload() {
return cloneSourceMapV3(this.#payload);
}
/**
* @param {SourceMapV3} mappingPayload
*/
#parseMappingPayload = () => {
if (this.#payload.sections) {
this.#parseSections(this.#payload.sections);
} else {
this.#parseMap(this.#payload, 0, 0);
}
this.#mappings.sort(compareSourceMapEntry);
}
/**
* @param {Array.<SourceMapV3.Section>} sections
*/
#parseSections = (sections) => {
for (let i = 0; i < sections.length; ++i) {
const section = sections[i];
this.#parseMap(section.map, section.offset.line, section.offset.column);
}
}
/**
* @param {number} lineNumber in compiled resource
* @param {number} columnNumber in compiled resource
* @return {?Array}
*/
findEntry(lineNumber, columnNumber) {
let first = 0;
let count = this.#mappings.length;
while (count > 1) {
const step = count >> 1;
const middle = first + step;
const mapping = this.#mappings[middle];
if (lineNumber < mapping[0] ||
(lineNumber === mapping[0] && columnNumber < mapping[1])) {
count = step;
} else {
first = middle;
count -= step;
}
}
const entry = this.#mappings[first];
if (!first && entry && (lineNumber < entry[0] ||
(lineNumber === entry[0] && columnNumber < entry[1]))) {
return {};
} else if (!entry) {
return {};
}
return {
generatedLine: entry[0],
generatedColumn: entry[1],
originalSource: entry[2],
originalLine: entry[3],
originalColumn: entry[4]
};
}
/**
* @override
*/
#parseMap = (map, lineNumber, columnNumber) => {
let sourceIndex = 0;
let sourceLineNumber = 0;
let sourceColumnNumber = 0;
const sources = [];
const originalToCanonicalURLMap = {};
for (let i = 0; i < map.sources.length; ++i) {
const url = map.sources[i];
originalToCanonicalURLMap[url] = url;
sources.push(url);
this.#sources[url] = true;
if (map.sourcesContent && map.sourcesContent[i])
this.#sourceContentByURL[url] = map.sourcesContent[i];
}
const stringCharIterator = new StringCharIterator(map.mappings);
let sourceURL = sources[sourceIndex];
while (true) {
if (stringCharIterator.peek() === ',')
stringCharIterator.next();
else {
while (stringCharIterator.peek() === ';') {
lineNumber += 1;
columnNumber = 0;
stringCharIterator.next();
}
if (!stringCharIterator.hasNext())
break;
}
columnNumber += decodeVLQ(stringCharIterator);
if (isSeparator(stringCharIterator.peek())) {
this.#mappings.push([lineNumber, columnNumber]);
continue;
}
const sourceIndexDelta = decodeVLQ(stringCharIterator);
if (sourceIndexDelta) {
sourceIndex += sourceIndexDelta;
sourceURL = sources[sourceIndex];
}
sourceLineNumber += decodeVLQ(stringCharIterator);
sourceColumnNumber += decodeVLQ(stringCharIterator);
if (!isSeparator(stringCharIterator.peek()))
// Unused index into the names list.
decodeVLQ(stringCharIterator);
this.#mappings.push([lineNumber, columnNumber, sourceURL,
sourceLineNumber, sourceColumnNumber])...
n/a
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 ReflectConstruct(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' + ArrayPrototypeJoin(paths, '\x00'); const entry = Module._pathCache[cacheKey]; if (entry) return entry; let exts; let trailingSlash = request.length > 0 && StringPrototypeCharCodeAt(request, request.length - 1) === CHAR_FORWARD_SLASH; if (!trailingSlash) { trailingSlash = RegExpPrototypeTest(trailingSlashRegex, request); } // For each path for (let 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; if (!absoluteRequest) { const exportsResolved = resolveExports(curPath, request); if (exportsResolved) return exportsResolved; } const basePath = path.resolve(curPath, request); let filename; const 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 = ObjectKeys(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 = ObjectKeys(Module._extensions); filename = tryPackage(basePath, exts, isMain, request); } if (filename) { Module._pathCache[cacheKey] = filename; return filename; } } return false; }
n/a
function() { const homeDir = isWindows ? process.env.USERPROFILE : safeGetenv('HOME'); const nodePath = isWindows ? process.env.NODE_PATH : safeGetenv('NODE_PATH'); // process.execPath is $PREFIX/bin/node except on Windows where it is // $PREFIX\node.exe where $PREFIX is the root of the Node.js installation. const prefixDir = isWindows ? path.resolve(process.execPath, '..') : path.resolve(process.execPath, '..', '..'); let 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 = ArrayPrototypeConcat(ArrayPrototypeFilter( StringPrototypeSplit(nodePath, path.delimiter), Boolean ), paths); } modulePaths = paths; // Clone as a shallow copy, for introspection. Module.globalPaths = ArrayPrototypeSlice(modulePaths); }
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);
if (!cachedModule.loaded)
return getExportsForCircularRequire(cachedModule);
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);
if (!cachedModule.loaded) {
const parseCachedModule = cjsParseCache.get(cachedModule);
if (!parseCachedModule || parseCachedModule.loaded)
return getExportsForCircularRequire(cachedModule);
parseCachedModule.loaded = true;
} else {
return cachedModule.exports;
}
}
const mod = loadNativeModule(filename, request);
if (mod && mod.canBeRequiredByUsers) return mod.exports;
// Don't call updateChildren(), Module constructor already does.
const module = cachedModule || 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 {
// Intercept exceptions that occur during the first tick and rekey them
// on error instance rather than module instance (which will immediately be
// garbage collected).
if (getSourceMapsEnabled()) {
try {
module.load(filename);
} catch (err) {
rekeySourceMap(Module._cache[filename], err);
throw err; /* node-do-not-add-exception-line */
}
} else {
module.load(filename);
}
threw = false;
} finally {
if (threw) {
delete Module._cache[filename];
if (parent !== undefined) {
delete relativeResolveCache[relResolveCacheIdentifier];
const children = parent && parent.children;
if (ArrayIsArray(children)) {
const index = ArrayPrototypeIndexOf(children, module);
if (index !== -1) {
ArrayPrototypeSplice(children, index, 1);
}
}
}
} else if (module.exports &&
!isProxy(module.exports) &&
ObjectGetPrototypeOf(module.exports) ===
CircularRequirePrototypeWarningProxy) {
ObjectSetPrototypeOf(module.exports, ObjectPrototype);
}
}
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 = []; for (let i = from.length - 1, p = 0, last = from.length; i >= 0; --i) { const code = StringPrototypeCharCodeAt(from, i); if (code === CHAR_FORWARD_SLASH) { if (p !== nmLen) ArrayPrototypePush( paths, StringPrototypeSlice(from, 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. ArrayPrototypePush(paths, '/node_modules'); return paths; }
n/a
function(requests) { if (!ArrayIsArray(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 (let n = 0; n < requests.length; n++) parent.require(requests[n]); }
n/a
function(request, parent, isMain, options) { if (NativeModule.canBeRequiredByUsers(request)) { return request; } let paths; if (typeof options === 'object' && options !== null) { if (ArrayIsArray(options.paths)) { const isRelative = StringPrototypeStartsWith(request, './') || StringPrototypeStartsWith(request, '../') || ((isWindows && StringPrototypeStartsWith(request, '.\\')) || StringPrototypeStartsWith(request, '..\\')); if (isRelative) { paths = options.paths; } else { const fakeParent = new Module('', null); paths = []; for (let i = 0; i < options.paths.length; i++) { const path = options.paths[i]; fakeParent.paths = Module._nodeModulePaths(path); const lookupPaths = Module._resolveLookupPaths(request, fakeParent); for (let j = 0; j < lookupPaths.length; j++) { if (!ArrayPrototypeIncludes(paths, lookupPaths[j])) ArrayPrototypePush(paths, lookupPaths[j]); } } } } else if (options.paths === undefined) { paths = Module._resolveLookupPaths(request, parent); } else { throw new ERR_INVALID_ARG_VALUE('options.paths', options.paths); } } else { paths = Module._resolveLookupPaths(request, parent); } if (parent && parent.filename) { if (request[0] === '#') { const pkg = readPackageScope(parent.filename) || {}; if (pkg.data && pkg.data.imports !== null && pkg.data.imports !== undefined) { try { return finalizeEsmResolution( packageImportsResolve(request, pathToFileURL(parent.filename), cjsConditions), request, parent.filename, pkg.path); } catch (e) { if (e.code === 'ERR_MODULE_NOT_FOUND') throw createEsmNotFoundErr(request); throw e; } } } } // Try module self resoultion first const parentPath = trySelfParentPath(parent); const selfResolved = trySelf(parentPath, request); if (selfResolved) { const cacheKey = request + '\x00' + (paths.length === 1 ? paths[0] : ArrayPrototypeJoin(paths, '\x00')); Module._pathCache[cacheKey] = selfResolved; return selfResolved; } // Look up the filename first, since that's the cache key. const filename = Module._findPath(request, paths, isMain, false); if (filename) return filename; const requireStack = []; for (let cursor = parent; cursor; cursor = moduleParentCache.get(cursor)) { ArrayPrototypePush(requireStack, cursor.filename || cursor.id); } let message = `Cannot find module '${request}'`; if (requireStack.length > 0) { message = message + '\nRequire stack:\n- ' + ArrayPrototypeJoin(requireStack, '\n- '); } // eslint-disable-next-line no-restricted-syntax const err = new Error(message); err.code = 'MODULE_NOT_FOUND'; err.requireStack = requireStack; throw err; }
n/a
function(request, parent) { if (NativeModule.canBeRequiredByUsers(request)) { debug('looking for %j in []', request); return null; } // Check for node modules paths. if (StringPrototypeCharAt(request, 0) !== '.' || (request.length > 1 && StringPrototypeCharAt(request, 1) !== '.' && StringPrototypeCharAt(request, 1) !== '/' && (!isWindows || StringPrototypeCharAt(request, 1) !== '\\'))) { let paths = modulePaths; if (parent != null && parent.paths && parent.paths.length) { paths = ArrayPrototypeConcat(parent.paths, paths); } debug('looking for %j in %j', request, paths); return paths.length > 0 ? paths : null; } // In REPL, 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 in REPL there is no filename const mainPaths = ['.']; 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 (isURLInstance(filename) || (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 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 ReflectConstruct(fn, args, new.target); } return fn.apply(this, args); }
n/a
function findSourceMap(sourceURL) { if (!RegExpPrototypeTest(/^\w+:\/\//, sourceURL)) { sourceURL = pathToFileURL(sourceURL).href; } if (!SourceMap) { SourceMap = require('internal/source_map/source_map').SourceMap; } let sourceMap = esmSourceMapCache.get(sourceURL); if (sourceMap === undefined) { for (const value of cjsSourceMapCache) { const filename = ObjectGetValueSafe(value, 'filename'); if (sourceURL === filename) { sourceMap = { data: ObjectGetValueSafe(value, 'data') }; } } } if (sourceMap && sourceMap.data) { return new SourceMap(sourceMap.data); } return undefined; }
n/a
function executeUserEntryPoint(main = process.argv[1]) { const resolvedMain = resolveMainPath(main); const useESMLoader = shouldUseESMLoader(resolvedMain); if (useESMLoader) { runMainESM(resolvedMain || main); } else { // Module._load is the monkey-patchable CJS module loader. Module._load(main, 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] = require("path").resolve(process.argv[1]);
local.Module.runMain();
}
// runme
if (process.env.npm_config_runme) {
require(require("path").resolve(process.env.npm_config_runme));
}
}());
}());
...
function syncBuiltinESMExports() { for (const mod of NativeModule.map.values()) { if (mod.canBeRequiredByUsers) { mod.syncExports(); } } }
n/a
function(content, filename) { let moduleURL; let redirects; if (policy?.manifest) { moduleURL = pathToFileURL(filename); redirects = policy.manifest.getDependencyMapper(moduleURL); policy.manifest.assertIntegrity(moduleURL, content); } maybeCacheSourceMap(filename, content, this); const compiledWrapper = wrapSafe(filename, content, this); let 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]) { try { resolvedArgv = Module._resolveFilename(process.argv[1], null, false); } catch { // We only expect this codepath to be reached in the case of a // preloaded module (it will fail earlier with the main entry) assert(ArrayIsArray(getOptionValue('--require'))); } } else { resolvedArgv = 'repl'; } } // Set breakpoint on module start if (resolvedArgv && !hasPausedEntry && filename === resolvedArgv) { hasPausedEntry = true; inspectorWrapper = internalBinding('inspector').callAndPauseOnStart; } } const dirname = path.dirname(filename); const require = makeRequireFunction(this, redirects); let result; const exports = this.exports; const thisValue = exports; const module = this; if (requireDepth === 0) statCache = new SafeMap(); if (inspectorWrapper) { result = inspectorWrapper(compiledWrapper, thisValue, exports, require, module, filename, dirname); } else { result = ReflectApply(compiledWrapper, thisValue, [exports, require, module, filename, dirname]); } hasLoadedAnyUserCJSModule = true; if (requireDepth === 0) statCache = null; return result; }
...
// jslint code
local.jslintAndPrint(code, tmp);
// instrument code
code = local.istanbulInstrumentInPackage(code, tmp);
// init module.exports
module = new local.Module(tmp);
require.cache[tmp] = module;
module._compile(code, tmp);
// init exports
module.exports.utility2 = local;
module.exports[env.npm_package_nameLib] = (
globalThis.utility2_moduleExports
);
// init assets lib.xxx.js
[
...
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); // allow .mjs to be overridden if (StringPrototypeEndsWith(filename, '.mjs') && !Module._extensions['.mjs']) throw new ERR_REQUIRE_ESM(filename); Module._extensions[extension](this, filename); this.loaded = true; const ESMLoader = asyncESM.ESMLoader; // Create module entry at load time to snapshot exports correctly const exports = this.exports; // Preemptively cache if ((module?.module === undefined || module.module.getStatus() < kEvaluated) && !ESMLoader.cjsCache.has(this)) ESMLoader.cjsCache.set(this, 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);
...
createServer = function () {
/*
* this function will emulate in browser, node's http.createServer function
* https://nodejs.org/dist/v0.12.18/docs/api/all.html#all_http_createserver_requestlistener
*/
return {
listen: function (port, onError) {
onError(undefined, port);
}
};
}
...
}\n\
// start server\n\
if (globalThis.utility2_serverHttp1) {\n\
return;\n\
}\n\
process.env.PORT = process.env.PORT || "8081";\n\
console.error("http-server listening on port " + process.env.PORT);\n\
require("http").createServer(function (req, res) {\n\
let data;\n\
data = local.assetsDict[require("url").parse(req.url).pathname];\n\
if (data !== undefined) {\n\
res.end(data);\n\
return;\n\
}\n\
res.statusCode = 404;\n\
...
request = function (xhr, onResponse) {
/*
* this function will emulate in browser, node's http.request function
* https://nodejs.org/dist/v0.12.18/docs/api/all.html#all_http_request_options_callback
*/
let bufList;
let data;
let handler;
let isDone;
let req;
let res;
xhr = {
end: function (_data) {
if (isDone) {
return;
}
isDone = true;
data = _data;
// async send req from client to server
setTimeout(function () {
local.serverLocalReqHandler(req, res);
});
},
headers: xhr.headers,
method: xhr.method,
on: function () {
return xhr;
},
timeout: xhr.timeout,
url: xhr.href
};
bufList = [];
handler = new globalThis.EventTarget();
req = {
emit: function (type, data) {
handler.dispatchEvent(new globalThis.CustomEvent("req." + type, {
detail: data
}));
},
headers: xhr.headers,
httpVersion: "1.1",
method: xhr.method,
on: function (type, onEvent) {
handler.addEventListener("req." + type, function (evt) {
onEvent(evt.detail);
});
if (req.readable && type === "end") {
req.readable = null;
req.emit("data", data);
req.emit("end");
}
return req;
},
pipe: function (writable) {
req.on("data", function (buf) {
writable.write(buf);
});
req.on("end", function () {
writable.end();
});
return writable;
},
readable: true,
url: xhr.url
};
res = {
emit: function (type, data) {
handler.dispatchEvent(new globalThis.CustomEvent("res." + type, {
detail: data
}));
},
end: function (data) {
if (res._isDone) {
return;
}
res._isDone = true;
bufList.push(data);
// notify server res is finished
res.emit("finish");
// pass res to client
onResponse(res);
res.emit("data", local.bufferConcat(bufList));
res.emit("end");
},
on: function (type, onEvent) {
handler.addEventListener("res." + type, function (evt) {
onEvent(evt.detail);
});
return res;
},
setHeader: function (key, val) {
xhr.resHeaders[key.toLowerCase()] = val;
},
statusCode: 200,
write: function (data) {
bufList.push(data);
}
};
return xhr;
}
...
}, {
url: "/index.rollup.html"
}, {
url: "/utility2.state.init.js"
}
].concat(assetsList).forEach(function (elem) {
promiseList2.push(new Promise(function (resolve) {
require("http").request((
"http://127.0.0.1:" + process.env.PORT + elem.url
), function (res) {
let file;
file = ".tmp/build/app/" + (elem.file || elem.url);
res.pipe(require("fs").createWriteStream(
file
).on("close", function () {
...
apidocCreate = function (opt) {
/*
* this function will create the apidoc from <opt>.dir
*/
let elemCreate;
let module;
let moduleMain;
let readExample;
let tmp;
let toString;
let trimStart;
if (opt.modeNoop) {
return "";
}
elemCreate = function (module, prefix, key) {
/*
* this function will create the apidoc-elem in given <module>
*/
let 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
elem.name = elem.name.replace(">.<", "><");
if (elem.typeof !== "function") {
return elem;
}
// init source
elem.source = local.stringHtmlSafe(
trimStart(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 = "..." + trimStart(
local.stringHtmlSafe(match1)
+ "<span class=\"apidocCodeKeywordSpan\">"
+ local.stringHtmlSafe(match2)
+ "</span>"
+ local.stringHtmlSafe(match3)
).trimEnd() + "\n...";
return "";
}
);
return elem.example;
});
elem.example = elem.example || "n/a";
return elem;
};
readExample = function (file) {
/*
* this function will read the example from given file
*/
let result;
local.tryCatchOnError(function () {
file = require("path").resolve(opt.dir, file);
console.error("apidocCreate - readExample " + file);
result = "";
result = local.identity(
"\n\n\n\n\n\n\n\n"
// bug-workaround - truncate example to manageable size
+ require("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
*/
let result;
local.tryCatchOnError(function () {
result = "";
result = String(value);...
...
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
*/
let isModule;
let objectKeys;
let 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.noop);
});
};
[
"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 = Array.from([
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 moduleExtraDict
opt.moduleExtraDict[opt.env.npm_package_name] = (
opt.moduleExtraDict[opt.env.npm_package_name] || {}
);
module = opt.moduleExtraDict[opt.env.npm_package_name];
([
1, 2, 3, 4
...
function assertJsonEqual(aa, bb) {
/*
* this function will assert JSON.stringify(<aa>) === JSON.stringify(<bb>)
*/
aa = JSON.stringify(objectDeepCopyWithKeysSorted(aa));
bb = JSON.stringify(objectDeepCopyWithKeysSorted(bb));
if (aa !== bb) {
throw new Error(JSON.stringify(aa) + " !== " + JSON.stringify(bb));
}
}
n/a
function assertOrThrow(passed, msg) {
/*
* this function will throw <msg> if <passed> is falsy
*/
if (passed) {
return;
}
throw (
(
msg
&& typeof msg.message === "string"
&& typeof msg.stack === "string"
)
// if msg is err, then leave as is
? msg
: new Error(
typeof msg === "string"
// if msg is string, then leave as is
? msg
// else JSON.stringify(msg)
: JSON.stringify(msg, undefined, 4)
)
);
}
...
strDict[str] = strDict[str] || (ii + 2);
ii = strDict[str];
if (commandList[ii]) {
commandList[ii].command.push(key);
return;
}
commandList[ii] = rgxComment.exec(str);
local.assertOrThrow(commandList[ii], (
"cliRun - cannot parse comment in COMMAND "
+ key
+ ":\nnew RegExp("
+ JSON.stringify(rgxComment.source)
+ ").exec(" + JSON.stringify(str).replace((
/\\\\/g
), "\u0000").replace((
...
cliRun = function ({ rgxComment }) {
/*
* this function will run cli
*/
let cliDict;
cliDict = local.cliDict;
cliDict._eval = cliDict._eval || function () {
/*
* <code>
* will eval <code>
*/
globalThis.local = local;
require("vm").runInThisContext(process.argv[3]);
};
cliDict._help = cliDict._help || function () {
/*
*
* will print help
*/
let commandList;
let file;
let packageJson;
let str;
let strDict;
commandList = [
{
argList: "<arg2> ...",
description: "usage:",
command: [
"<arg1>"
]
}, {
argList: "'console.log(\"hello world\")'",
description: "example:",
command: [
"--eval"
]
}
];
file = __filename.replace((
/.*\//
), "");
packageJson = require("./package.json");
// validate comment
rgxComment = 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/
);
strDict = {};
Object.keys(cliDict).sort().forEach(function (key, ii) {
if (key[0] === "_" && key !== "_default") {
return;
}
str = String(cliDict[key]);
if (key === "_default") {
key = "";
}
strDict[str] = strDict[str] || (ii + 2);
ii = strDict[str];
if (commandList[ii]) {
commandList[ii].command.push(key);
return;
}
commandList[ii] = rgxComment.exec(str);
local.assertOrThrow(commandList[ii], (
"cliRun - cannot parse comment in COMMAND "
+ key
+ ":\nnew RegExp("
+ JSON.stringify(rgxComment.source)
+ ").exec(" + JSON.stringify(str).replace((
/\\\\/g
), "\u0000").replace((
/\\n/g
), "\\n\\\n").replace((
/\u0000/g
), "\\\\") + ");"
));
commandList[ii] = {
argList: local.coalesce(commandList[ii][1], "").trim(),
command: [
key
],
description: commandList[ii][2]
};
});
str = "";
str += packageJson.name + " (" + packageJson.version + ")\n\n";
str += 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# "
+ elem.description
);
}
return (
elem.description + "\n " + file
+ " " + elem.command.sort().join("|") + " "
+ elem.argList.join(" ")
);
}).join("\n\n");
console.log(str);...
...
dir: process.argv[2],
modulePathList: module.paths
}));
};
// run the cli
if (module === require.main && !globalThis.utility2_rollup) {
local.cliRun({});
}
}());
}());
...
function coalesce(...argList) {
/*
* this function will coalesce null, undefined, or "" in <argList>
*/
let arg;
let ii;
ii = 0;
while (ii < argList.length) {
arg = argList[ii];
if (arg !== undefined && arg !== null && arg !== "") {
return arg;
}
ii += 1;
}
return arg;
}
...
), "\u0000").replace((
/\\n/g
), "\\n\\\n").replace((
/\u0000/g
), "\\\\") + ");"
));
commandList[ii] = {
argList: local.coalesce(commandList[ii][1], "").trim(),
command: [
key
],
description: commandList[ii][2]
};
});
str = "";
...
function identity(val) {
/*
* this function will return <val>
*/
return val;
}
...
cliDict.help = cliDict.help || cliDict._help;
cliDict._interactive = cliDict._interactive || function () {
/*
*
* will start interactive-mode
*/
globalThis.local = local;
local.identity(local.replStart || require("repl").start)({
useGlobal: true
});
};
cliDict["--interactive"] = cliDict["--interactive"] || cliDict._interactive;
cliDict["-i"] = cliDict["-i"] || cliDict._interactive;
cliDict._version = cliDict._version || function () {
/*
...
moduleDirname = function (module, pathList) {
/*
* this function will search <pathList> for <module>'s __dirname
*/
let result;
// search "."
if (!module || module === "." || module.indexOf("/") >= 0) {
return require("path").resolve(module || "");
}
// search pathList
[].concat(
pathList,
require("module").globalPaths,
[
process.env.HOME + "/node_modules", "/usr/local/lib/node_modules"
]
).some(function (path) {
try {
result = require("path").resolve(path + "/" + module);
result = require("fs").statSync(result).isDirectory() && result;
return result;
} catch (ignore) {
result = "";
}
});
return result;
}
...
return match0.replace((
/(.{128}(?:\b|\w+))/g
), "$1\n").trimEnd();
});
return str;
};
// init opt
opt.dir = local.moduleDirname(
opt.dir,
opt.modulePathList || require("module").paths
);
local.objectAssignDefault(opt, {
env: {
npm_package_description: ""
},
...
function noop() {
/*
* this function will do nothing
*/
return;
}
...
local.isBrowser
? {
env: {},
stdout: {}
}
: globalThis.process
);
local.noop(escodegen, esprima, estraverse, esutils);
/*
repo https://github.com/acornjs/acorn/tree/6.4.1
committed 2020-03-09T10:38:41Z
*/
...
function objectAssignDefault(tgt = {}, src = {}, depth = 0) {
/*
* this function will if items from <tgt> are null, undefined, or "",
* then overwrite them with items from <src>
*/
let recurse;
recurse = function (tgt, src, depth) {
Object.entries(src).forEach(function ([
key, bb
]) {
let aa;
aa = tgt[key];
if (aa === undefined || aa === null || aa === "") {
tgt[key] = bb;
return;
}
if (
depth !== 0
&& typeof aa === "object" && aa && !Array.isArray(aa)
&& typeof bb === "object" && bb && !Array.isArray(bb)
) {
recurse(aa, bb, depth - 1);
}
});
};
recurse(tgt, src, depth | 0);
return tgt;
}
...
return str;
};
// init opt
opt.dir = local.moduleDirname(
opt.dir,
opt.modulePathList || require("module").paths
);
local.objectAssignDefault(opt, {
env: {
npm_package_description: ""
},
packageJson: JSON.parse(readExample("package.json")),
require: function (file) {
return local.tryCatchOnError(function () {
return require(file);
...
function objectDeepCopyWithKeysSorted(obj) {
/*
* this function will recursively deep-copy <obj> with keys sorted
*/
let sorted;
if (typeof obj !== "object" || !obj) {
return obj;
}
// recursively deep-copy list with child-keys sorted
if (Array.isArray(obj)) {
return obj.map(objectDeepCopyWithKeysSorted);
}
// recursively deep-copy obj with keys sorted
sorted = {};
Object.keys(obj).sort().forEach(function (key) {
sorted[key] = objectDeepCopyWithKeysSorted(obj[key]);
});
return sorted;
}
...
start: "./npm_scripts.sh",
test: "./npm_scripts.sh",
utility2: "./npm_scripts.sh"
};
// write package.json
require("fs").writeFileSync(
"package.json",
JSON.stringify(local.objectDeepCopyWithKeysSorted(
packageJson
), undefined, 4) + "\n"
);
writeFileLog("package.json");
// re-render README.md
tgt = local.templateRenderMyApp(
local.assetsDict["/assets.readme.template.md"]
...
function onErrorThrow(err) {
/*
* this function will throw <err> if exists
*/
if (err) {
throw err;
}
}
...
promiseList.push(new Promise(function (resolve) {
require("fs").writeFile(
require("path").resolve(
process.env.npm_config_dir_build + "/test-report.json"
),
JSON.stringify(globalThis.utility2_testReport),
function (err) {
local.onErrorThrow(err);
console.error(
"\nbrowserTest - merged test-report "
+ process.env.npm_config_dir_build + "/test-report.json"
+ "\n"
);
resolve();
}
...
stringHtmlSafe = function (str) {
/*
* this function will make <str> html-safe
* https://stackoverflow.com/questions/7381974/which-characters-need-to-be-escaped-on-html
*/
return str.replace((
/&/gu
), "&").replace((
/"/gu
), """).replace((
/'/gu
), "'").replace((
/</gu
), "<").replace((
/>/gu
), ">").replace((
/&(amp;|apos;|gt;|lt;|quot;)/igu
), "&$1");
}
...
);
// handle case where module is a function
elem.name = elem.name.replace(">.<", "><");
if (elem.typeof !== "function") {
return elem;
}
// init source
elem.source = local.stringHtmlSafe(
trimStart(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 = {}, ii = 0) {
/*
* this function will render <template> with given <dict>
*/
let argList;
let getVal;
let match;
let renderPartial;
let rgx;
let skip;
let val;
if (dict === null || dict === undefined) {
dict = {};
}
getVal = function (key) {
argList = key.split(" ");
val = dict;
if (argList[0] === "#this/") {
return val;
}
if (argList[0] === "#ii/") {
return ii;
}
// iteratively lookup nested val in dict
argList[0].split(".").forEach(function (key) {
val = val && val[key];
});
return val;
};
renderPartial = function (match0, helper, key, partial) {
switch (helper) {
case "each":
case "eachTrimEndComma":
val = getVal(key);
val = (
Array.isArray(val)
? val.map(function (dict, ii) {
// recurse with partial
return local.templateRender(partial, dict, opt, ii);
}).join("")
: ""
);
// remove trailing-comma from last elem
if (helper === "eachTrimEndComma") {
val = val.trimEnd().replace((
/,$/
), "");
}
return val;
case "if":
partial = partial.split("{{#unless " + key + "}}");
partial = (
getVal(key)
? partial[0]
// handle "unless" case
: partial.slice(1).join("{{#unless " + key + "}}")
);
// recurse with partial
return local.templateRender(partial, dict, opt);
case "unless":
return (
getVal(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 template
return template.replace((
/\{\{[^}]+?\}\}/g
), function (match0) {
let markdownToHtml;
let notHtmlSafe;
notHtmlSafe = opt.notHtmlSafe;
try {
val = getVal(match0.slice(2, -2));
if (val === undefined) {
return match0;
}
argList.slice(1).forEach(function (fmt, ii, list) {
switch (fmt) {
case "*":
case "+":
case "-":
case "/":
skip = ii + 1;
val = String(
fmt === "*"
? Number(val) * Number(list[skip])
: fmt === "+"
? Number(val) + Number(list[skip])
: fmt === "-"
? Number(val) - Number(list[skip])
: Number(val) / Number(list[skip])
);
break;
case "a...
...
case "each":
case "eachTrimEndComma":
val = getVal(key);
val = (
Array.isArray(val)
? val.map(function (dict, ii) {
// recurse with partial
return local.templateRender(partial, dict, opt, ii);
}).join("")
: ""
);
// remove trailing-comma from last elem
if (helper === "eachTrimEndComma") {
val = val.trimEnd().replace((
/,$/
...
tryCatchOnError = function (fnc, onError) {
/*
* this function will run <fnc> in tryCatch block,
* else call onError with errCaught
*/
let result;
// validate onError
local.assertOrThrow(typeof onError === "function", typeof onError);
try {
// reset errCaught
delete local._debugTryCatchError;
result = fnc();
delete local._debugTryCatchError;
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
*/
let result;
local.tryCatchOnError(function () {
file = require("path").resolve(opt.dir, file);
console.error("apidocCreate - readExample " + file);
result = "";
result = local.identity(
"\n\n\n\n\n\n\n\n"
// bug-workaround - truncate example to manageable size
+ require("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
}));
}
...
cliDict._help();
return;
}
if (cliDict[process.argv[2]]) {
cliDict[process.argv[2]]();
return;
}
cliDict._default();
};
local.moduleDirname = function (module, pathList) {
/*
* this function will search <pathList> for <module>'s __dirname
*/
let result;
...
utility2.browserTest = function () {
/*
* <urlList> <mode>
* will browser-test in parallel, comma-separated <urlList> with given <mode>
*/
local.browserTest({
url: process.argv[3]
}, function (err) {
if (err) {
console.log(err);
}
});
}
n/a
utility2.start = function () {
/*
* <port>
* will start utility2 http-server on given <port> (default 8081)
*/
globalThis.local = local;
local.replStart();
local.testRunServer({});
if (process.env.npm_config_runme) {
require(require("path").resolve(process.env.npm_config_runme));
}
}
n/a
utility2.testReportCreate = function () {
/*
*
* will create test-report
*/
process.exit(
local.testReportCreate(
JSON.parse(
require("fs").readFileSync(
require("path").resolve(
process.env.npm_config_dir_build + "/test-report.json"
),
"utf8"
)
)
).testsFailed !== 0
);
}
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 assertJsonEqual(aa, bb) {
/*
* this function will assert JSON.stringify(<aa>) === JSON.stringify(<bb>)
*/
aa = JSON.stringify(objectDeepCopyWithKeysSorted(aa));
bb = JSON.stringify(objectDeepCopyWithKeysSorted(bb));
if (aa !== bb) {
throw new Error(JSON.stringify(aa) + " !== " + JSON.stringify(bb));
}
}
n/a
function assertOrThrow(passed, msg) {
/*
* this function will throw <msg> if <passed> is falsy
*/
if (passed) {
return;
}
throw (
(
msg
&& typeof msg.message === "string"
&& typeof msg.stack === "string"
)
// if msg is err, then leave as is
? msg
: new Error(
typeof msg === "string"
// if msg is string, then leave as is
? msg
// else JSON.stringify(msg)
: JSON.stringify(msg, undefined, 4)
)
);
}
...
strDict[str] = strDict[str] || (ii + 2);
ii = strDict[str];
if (commandList[ii]) {
commandList[ii].command.push(key);
return;
}
commandList[ii] = rgxComment.exec(str);
local.assertOrThrow(commandList[ii], (
"cliRun - cannot parse comment in COMMAND "
+ key
+ ":\nnew RegExp("
+ JSON.stringify(rgxComment.source)
+ ").exec(" + JSON.stringify(str).replace((
/\\\\/g
), "\u0000").replace((
...
cliRun = function ({ rgxComment }) {
/*
* this function will run cli
*/
let cliDict;
cliDict = local.cliDict;
cliDict._eval = cliDict._eval || function () {
/*
* <code>
* will eval <code>
*/
globalThis.local = local;
require("vm").runInThisContext(process.argv[3]);
};
cliDict._help = cliDict._help || function () {
/*
*
* will print help
*/
let commandList;
let file;
let packageJson;
let str;
let strDict;
commandList = [
{
argList: "<arg2> ...",
description: "usage:",
command: [
"<arg1>"
]
}, {
argList: "'console.log(\"hello world\")'",
description: "example:",
command: [
"--eval"
]
}
];
file = __filename.replace((
/.*\//
), "");
packageJson = require("./package.json");
// validate comment
rgxComment = 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/
);
strDict = {};
Object.keys(cliDict).sort().forEach(function (key, ii) {
if (key[0] === "_" && key !== "_default") {
return;
}
str = String(cliDict[key]);
if (key === "_default") {
key = "";
}
strDict[str] = strDict[str] || (ii + 2);
ii = strDict[str];
if (commandList[ii]) {
commandList[ii].command.push(key);
return;
}
commandList[ii] = rgxComment.exec(str);
local.assertOrThrow(commandList[ii], (
"cliRun - cannot parse comment in COMMAND "
+ key
+ ":\nnew RegExp("
+ JSON.stringify(rgxComment.source)
+ ").exec(" + JSON.stringify(str).replace((
/\\\\/g
), "\u0000").replace((
/\\n/g
), "\\n\\\n").replace((
/\u0000/g
), "\\\\") + ");"
));
commandList[ii] = {
argList: local.coalesce(commandList[ii][1], "").trim(),
command: [
key
],
description: commandList[ii][2]
};
});
str = "";
str += packageJson.name + " (" + packageJson.version + ")\n\n";
str += 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# "
+ elem.description
);
}
return (
elem.description + "\n " + file
+ " " + elem.command.sort().join("|") + " "
+ elem.argList.join(" ")
);
}).join("\n\n");
console.log(str);...
...
dir: process.argv[2],
modulePathList: module.paths
}));
};
// run the cli
if (module === require.main && !globalThis.utility2_rollup) {
local.cliRun({});
}
}());
}());
...
function coalesce(...argList) {
/*
* this function will coalesce null, undefined, or "" in <argList>
*/
let arg;
let ii;
ii = 0;
while (ii < argList.length) {
arg = argList[ii];
if (arg !== undefined && arg !== null && arg !== "") {
return arg;
}
ii += 1;
}
return arg;
}
...
), "\u0000").replace((
/\\n/g
), "\\n\\\n").replace((
/\u0000/g
), "\\\\") + ");"
));
commandList[ii] = {
argList: local.coalesce(commandList[ii][1], "").trim(),
command: [
key
],
description: commandList[ii][2]
};
});
str = "";
...
coverageMerge = function (coverage1 = {}, coverage2 = {}) {
/*
* this function will inplace-merge <coverage2> into <coverage1>
*/
let dict1;
let dict2;
Object.keys(coverage2).forEach(function (file) {
// if coverage1[file] is undefined, then override it
if (!coverage1[file]) {
coverage1[file] = coverage2[file];
return;
}
// merge 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 (cnt, ii) {
dict1[key][ii] += cnt;
});
});
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;
}
n/a
coverageReportCreate = function ({ coverage, coverageInclude }) {
/*
* this function will
// 1. merge previous <dirCoverage>/coverage.json into <coverage>
// 2. convert <coverage> to <summaryDict>
// 3. convert <summaryDict> to <nodeRoot>
// 4. convert <nodeRoot> to text-report <dirCoverage>/coverage.txt
// 5. convert <nodeRoot> to html-report <dirCoverage>/\*
// 6. return coverage-report in html-format as single document
*/
let dirCoverage;
let filePrefix;
let htmlAll;
let nodeChildAdd;
let nodeCreate;
let nodeDict;
let nodeNormalize;
let nodeRoot;
let summaryDict;
let tmp;
// init function
nodeChildAdd = function (node, child) {
/*
* this function will add <child> to <node>
*/
node.children.push(child);
child.parent = node;
};
nodeCreate = function (pathname) {
/*
* this function will create a tree-node
*/
return {
children: [],
pathname,
metrics: {
branches: {
total: 0,
covered: 0,
skipped: 0,
pct: "Unknown"
},
functions: {
total: 0,
covered: 0,
skipped: 0,
pct: "Unknown"
},
lines: {
total: 0,
covered: 0,
skipped: 0,
pct: "Unknown"
},
statements: {
total: 0,
covered: 0,
skipped: 0,
pct: "Unknown"
}
},
name: pathname
};
};
nodeNormalize = function (node, level, filePrefix, parent) {
/*
* this function will recursively normalize <node> and its children
*/
let metric;
// init name
if (node.name.indexOf(filePrefix) === 0) {
node.name = node.name.slice(filePrefix.length);
}
if (node.name[0] === path.sep) {
node.name = node.name.slice(1);
}
// init relativeName
node.relativeName = (
parent
? (
parent.name !== "__root__/"
? node.name.slice(parent.name.length)
: node.name
)
: node.name.slice(filePrefix.length)
);
// init nameOrAllFiles
node.nameOrAllFiles = node.name || "All files";
// init relativeNameOrAllFiles
node.relativeNameOrAllFiles = node.relativeName || "All files";
// init href
node.href = node.relativeName.split(path.sep).join("/") + (
node.isFile
? ".html"
: "index.html"
);
// recurse
node.children.forEach(function (child) {
nodeNormalize(child, level + 1, filePrefix, node);
});
// sort children by name
node.children.sort(function (aa, bb) {
return (
aa.name > bb.name
? 1
: -1
);
});
// init metrics
if (!node.isFile) {
node.children.forEach(function (child) {
[
"lines", "statements", "branches", "functions"
].forEach(function (key) {
metric = node.metrics[key];
metric.total += child.metrics[key].total;
metric.covered += child.metrics[key].covered;
metric.skipped += child.metrics[key].skipped;
});
});
}
// calculate pct and score
[
"lines", "statement...
...
break;\n\
}\n\
};\n\
// handle evt\n\
local.eventListenerAdd("utility2.testRunEnd", function () {\n\
document.querySelector(\n\
"#htmlCoverageReport1"\n\
).innerHTML = local.istanbul.coverageReportCreate({\n\
coverage: globalThis.__coverage__\n\
});\n\
});\n\
local.eventListenerAdd("utility2.testRunProgressUpdate", function (testReport) {\n\
document.querySelector(\n\
"#htmlTestReport2"\n\
).innerHTML = local.testReportMerge(testReport, {});\n\
...
fsReadFileOrDefaultSync = function (pathname, type, dflt) {
/*
* this function will sync-read <pathname> with given <type> and <dflt>
*/
let fs;
// do nothing if module not exists
try {
fs = require("fs");
pathname = require("path").resolve(pathname);
} catch (ignore) {
return dflt;
}
// try to read pathname
try {
return (
type === "json"
? JSON.parse(fs.readFileSync(pathname, "utf8"))
: fs.readFileSync(pathname, type)
);
} catch (ignore) {
return dflt;
}
}
...
stdio: [
"ignore", 1, 2
]
});
if (globalThis.utility2_rollup || env.npm_config_mode_start) {
// init assets index.html
local.assetsDict["/index.html"] = (
local.fsReadFileOrDefaultSync("index.html", "utf8", "
;")
|| local.assetsDict["/index.rollup.html"] || ""
);
local.assetsDict["/"] = local.assetsDict["/index.html"];
local.assetsDict["/assets.app.js"] = require("fs").readFileSync(
__filename,
"utf8"
).replace((
...
fsWriteFileWithMkdirpSync = function (pathname, data) {
/*
* this function will sync write <data> to <pathname> with "mkdir -p"
*/
let fs;
// do nothing if module not exists
try {
fs = require("fs");
pathname = require("path").resolve(pathname);
} catch (ignore) {
return;
}
// try to write pathname
try {
fs.writeFileSync(pathname, data);
} catch (ignore) {
// mkdir -p
fs.mkdirSync(require("path").dirname(pathname), {
recursive: true
});
// re-write pathname
fs.writeFileSync(pathname, data);
}
console.error("fsWriteFileWithMkdirpSync - " + pathname);
return true;
}
...
testPlatform.testsPassed + " passed "
).padStart(16, " ")
+ " |\n" + new Array(56).join("-")
);
}).join("\n") + "\n"
);
// create test-report.html
local.fsWriteFileWithMkdirpSync(
".tmp/build/test-report.html",
local.testReportMerge(testReport)
);
// create build.badge.svg
local.fsWriteFileWithMkdirpSync(
".tmp/build/build.badge.svg",
local.assetsDict["/assets.buildBadge.template.svg"].replace((
...
function identity(val) {
/*
* this function will return <val>
*/
return val;
}
...
cliDict.help = cliDict.help || cliDict._help;
cliDict._interactive = cliDict._interactive || function () {
/*
*
* will start interactive-mode
*/
globalThis.local = local;
local.identity(local.replStart || require("repl").start)({
useGlobal: true
});
};
cliDict["--interactive"] = cliDict["--interactive"] || cliDict._interactive;
cliDict["-i"] = cliDict["-i"] || cliDict._interactive;
cliDict._version = cliDict._version || function () {
/*
...
instrumentInPackage = function (code, file) {
/*
* this function will instrument <code>
* if macro /\* istanbul instrument in package $npm_package_nameLib *\/
* exists in <code>
*/
return (
(
process.env.npm_config_mode_coverage
&& code.indexOf("/* istanbul ignore all */\n") < 0 && (
process.env.npm_config_mode_coverage === "all"
|| process.env.npm_config_mode_coverage === "node_modules"
|| 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 <file>
// 2. save <code> to __coverageInclude__[<file>] for future html-report
// 3. return instrumented-code
*/
// 1. normalize <file>
file = path.resolve(file);
// 2. save <code> to __coverageInclude__[<file>] for future html-report
// 3. return instrumented-code
return (
"globalThis.__coverageInclude__ = globalThis.__coverageInclude__ || {};"
+ "globalThis.__coverageInclude__[" + JSON.stringify(file) + "] = 1;\n"
) + new local.Instrumenter({
embedSource: true,
esModules: true,
noAutoWrap: true
}).instrumentSync(code, file).trimStart();
}
...
try {\n\
delete globalThis.__coverage__["/inputTextarea1.js"];\n\
} catch (ignore) {}\n\
// try to cover and eval #inputTextarea1\n\
try {\n\
document.querySelector(\n\
"#outputTextarea1"\n\
).value = local.istanbul.instrumentSync(\n\
document.querySelector("#inputTextarea1").value,\n\
"/inputTextarea1.js"\n\
);\n\
eval( // jslint ignore:line\n\
document.querySelector("#outputTextarea1").value\n\
);\n\
} catch (errCaught) {\n\
...
function noop() {
/*
* this function will do nothing
*/
return;
}
...
local.isBrowser
? {
env: {},
stdout: {}
}
: globalThis.process
);
local.noop(escodegen, esprima, estraverse, esutils);
/*
repo https://github.com/acornjs/acorn/tree/6.4.1
committed 2020-03-09T10:38:41Z
*/
...
function objectAssignDefault(tgt = {}, src = {}, depth = 0) {
/*
* this function will if items from <tgt> are null, undefined, or "",
* then overwrite them with items from <src>
*/
let recurse;
recurse = function (tgt, src, depth) {
Object.entries(src).forEach(function ([
key, bb
]) {
let aa;
aa = tgt[key];
if (aa === undefined || aa === null || aa === "") {
tgt[key] = bb;
return;
}
if (
depth !== 0
&& typeof aa === "object" && aa && !Array.isArray(aa)
&& typeof bb === "object" && bb && !Array.isArray(bb)
) {
recurse(aa, bb, depth - 1);
}
});
};
recurse(tgt, src, depth | 0);
return tgt;
}
...
return str;
};
// init opt
opt.dir = local.moduleDirname(
opt.dir,
opt.modulePathList || require("module").paths
);
local.objectAssignDefault(opt, {
env: {
npm_package_description: ""
},
packageJson: JSON.parse(readExample("package.json")),
require: function (file) {
return local.tryCatchOnError(function () {
return require(file);
...
function objectDeepCopyWithKeysSorted(obj) {
/*
* this function will recursively deep-copy <obj> with keys sorted
*/
let sorted;
if (typeof obj !== "object" || !obj) {
return obj;
}
// recursively deep-copy list with child-keys sorted
if (Array.isArray(obj)) {
return obj.map(objectDeepCopyWithKeysSorted);
}
// recursively deep-copy obj with keys sorted
sorted = {};
Object.keys(obj).sort().forEach(function (key) {
sorted[key] = objectDeepCopyWithKeysSorted(obj[key]);
});
return sorted;
}
...
start: "./npm_scripts.sh",
test: "./npm_scripts.sh",
utility2: "./npm_scripts.sh"
};
// write package.json
require("fs").writeFileSync(
"package.json",
JSON.stringify(local.objectDeepCopyWithKeysSorted(
packageJson
), undefined, 4) + "\n"
);
writeFileLog("package.json");
// re-render README.md
tgt = local.templateRenderMyApp(
local.assetsDict["/assets.readme.template.md"]
...
function onErrorThrow(err) {
/*
* this function will throw <err> if exists
*/
if (err) {
throw err;
}
}
...
promiseList.push(new Promise(function (resolve) {
require("fs").writeFile(
require("path").resolve(
process.env.npm_config_dir_build + "/test-report.json"
),
JSON.stringify(globalThis.utility2_testReport),
function (err) {
local.onErrorThrow(err);
console.error(
"\nbrowserTest - merged test-report "
+ process.env.npm_config_dir_build + "/test-report.json"
+ "\n"
);
resolve();
}
...
templateRender = function (template, dict, opt = {}, ii = 0) {
/*
* this function will render <template> with given <dict>
*/
let argList;
let getVal;
let match;
let renderPartial;
let rgx;
let skip;
let val;
if (dict === null || dict === undefined) {
dict = {};
}
getVal = function (key) {
argList = key.split(" ");
val = dict;
if (argList[0] === "#this/") {
return val;
}
if (argList[0] === "#ii/") {
return ii;
}
// iteratively lookup nested val in dict
argList[0].split(".").forEach(function (key) {
val = val && val[key];
});
return val;
};
renderPartial = function (match0, helper, key, partial) {
switch (helper) {
case "each":
case "eachTrimEndComma":
val = getVal(key);
val = (
Array.isArray(val)
? val.map(function (dict, ii) {
// recurse with partial
return local.templateRender(partial, dict, opt, ii);
}).join("")
: ""
);
// remove trailing-comma from last elem
if (helper === "eachTrimEndComma") {
val = val.trimEnd().replace((
/,$/
), "");
}
return val;
case "if":
partial = partial.split("{{#unless " + key + "}}");
partial = (
getVal(key)
? partial[0]
// handle "unless" case
: partial.slice(1).join("{{#unless " + key + "}}")
);
// recurse with partial
return local.templateRender(partial, dict, opt);
case "unless":
return (
getVal(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 template
return template.replace((
/\{\{[^}]+?\}\}/g
), function (match0) {
let markdownToHtml;
let notHtmlSafe;
notHtmlSafe = opt.notHtmlSafe;
try {
val = getVal(match0.slice(2, -2));
if (val === undefined) {
return match0;
}
argList.slice(1).forEach(function (fmt, ii, list) {
switch (fmt) {
case "*":
case "+":
case "-":
case "/":
skip = ii + 1;
val = String(
fmt === "*"
? Number(val) * Number(list[skip])
: fmt === "+"
? Number(val) + Number(list[skip])
: fmt === "-"
? Number(val) - Number(list[skip])
: Number(val) / Number(list[skip])
);
break;
case "a...
...
case "each":
case "eachTrimEndComma":
val = getVal(key);
val = (
Array.isArray(val)
? val.map(function (dict, ii) {
// recurse with partial
return local.templateRender(partial, dict, opt, ii);
}).join("")
: ""
);
// remove trailing-comma from last elem
if (helper === "eachTrimEndComma") {
val = val.trimEnd().replace((
/,$/
...
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
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; // hack-istanbul - 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 { // hack-istanbul - inline acorn-opt let opt = { locations: true, onComment: [], onToken: this.opts.preserveComments, ranges: true, sourceType: this.opts.esModules ? 'module' : 'script' }; program = ESP.parse(code, opt); program.comments = opt.onComment } 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); }
...
try {\n\
delete globalThis.__coverage__["/inputTextarea1.js"];\n\
} catch (ignore) {}\n\
// try to cover and eval #inputTextarea1\n\
try {\n\
document.querySelector(\n\
"#outputTextarea1"\n\
).value = local.istanbul.instrumentSync(\n\
document.querySelector("#inputTextarea1").value,\n\
"/inputTextarea1.js"\n\
);\n\
eval( // jslint ignore:line\n\
document.querySelector("#outputTextarea1").value\n\
);\n\
} catch (errCaught) {\n\
...
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); }
...
Reference.prototype.replace = function replace(node) {
this.parent[this.key] = node;
};
Reference.prototype.remove = function remove() {
if (isArray(this.parent)) {
this.parent.splice(this.key, 1);
return true;
} else {
this.replace(null);
return false;
}
};
...
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
cover = function () {
/*
* <script>
* will run and cover <script>
*/
let moduleExtensionsJs;
let tmp;
try {
tmp = JSON.parse(require("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
tmp = require("module");
moduleExtensionsJs = tmp._extensions[".js"];
tmp._extensions[".js"] = function (module, file) {
if (typeof file === "string" && (
file.indexOf(process.cwd() + require("path").sep) === 0 && (
process.env.npm_config_mode_coverage === "node_modules"
|| file.indexOf(
require("path").resolve("node_modules")
+ require("path").sep
) !== 0
)
)) {
module._compile(local.instrumentInPackage(
require("fs").readFileSync(file, "utf8"),
file
), file);
return;
}
moduleExtensionsJs(module, file);
};
// init process.argv
process.argv.splice(1, 2);
process.argv[1] = require("path").resolve(process.argv[1]);
console.error("\nistanbul - covering $ " + process.argv.join(" "));
// create coverage on exit
process.on("exit", function () {
local.coverageReportCreate({
coverage: globalThis.__coverage__
});
});
// re-init cli
tmp.runMain();
}
n/a
instrument = function () {
/*
* <script>
* will instrument <script> and print result to stdout
*/
process.argv[3] = require("path").resolve(process.argv[3]);
process.stdout.write(local.instrumentSync(
require("fs").readFileSync(process.argv[3], "utf8"),
process.argv[3]
));
}
n/a
report = function () {
/*
* <coverageJson>
* will create coverage-report from file <coverageJson>
*/
process.argv[3] = require("path").resolve(process.argv[3]);
globalThis.__coverage__ = JSON.parse(
require("fs").readFileSync(process.argv[3])
);
globalThis.__coverageInclude__ = {};
Object.keys(globalThis.__coverage__).forEach(function (file) {
globalThis.__coverageInclude__[file] = 1;
});
local.coverageReportCreate({
coverage: globalThis.__coverage__
});
}
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] = require("path").resolve(process.argv[1]);
// re-init cli
require("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);
...
function assertJsonEqual(aa, bb) {
/*
* this function will assert JSON.stringify(<aa>) === JSON.stringify(<bb>)
*/
aa = JSON.stringify(objectDeepCopyWithKeysSorted(aa));
bb = JSON.stringify(objectDeepCopyWithKeysSorted(bb));
if (aa !== bb) {
throw new Error(JSON.stringify(aa) + " !== " + JSON.stringify(bb));
}
}
n/a
function assertOrThrow(passed, msg) {
/*
* this function will throw <msg> if <passed> is falsy
*/
if (passed) {
return;
}
throw (
(
msg
&& typeof msg.message === "string"
&& typeof msg.stack === "string"
)
// if msg is err, then leave as is
? msg
: new Error(
typeof msg === "string"
// if msg is string, then leave as is
? msg
// else JSON.stringify(msg)
: JSON.stringify(msg, undefined, 4)
)
);
}
...
strDict[str] = strDict[str] || (ii + 2);
ii = strDict[str];
if (commandList[ii]) {
commandList[ii].command.push(key);
return;
}
commandList[ii] = rgxComment.exec(str);
local.assertOrThrow(commandList[ii], (
"cliRun - cannot parse comment in COMMAND "
+ key
+ ":\nnew RegExp("
+ JSON.stringify(rgxComment.source)
+ ").exec(" + JSON.stringify(str).replace((
/\\\\/g
), "\u0000").replace((
...
cliRun = function ({ rgxComment }) {
/*
* this function will run cli
*/
let cliDict;
cliDict = local.cliDict;
cliDict._eval = cliDict._eval || function () {
/*
* <code>
* will eval <code>
*/
globalThis.local = local;
require("vm").runInThisContext(process.argv[3]);
};
cliDict._help = cliDict._help || function () {
/*
*
* will print help
*/
let commandList;
let file;
let packageJson;
let str;
let strDict;
commandList = [
{
argList: "<arg2> ...",
description: "usage:",
command: [
"<arg1>"
]
}, {
argList: "'console.log(\"hello world\")'",
description: "example:",
command: [
"--eval"
]
}
];
file = __filename.replace((
/.*\//
), "");
packageJson = require("./package.json");
// validate comment
rgxComment = 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/
);
strDict = {};
Object.keys(cliDict).sort().forEach(function (key, ii) {
if (key[0] === "_" && key !== "_default") {
return;
}
str = String(cliDict[key]);
if (key === "_default") {
key = "";
}
strDict[str] = strDict[str] || (ii + 2);
ii = strDict[str];
if (commandList[ii]) {
commandList[ii].command.push(key);
return;
}
commandList[ii] = rgxComment.exec(str);
local.assertOrThrow(commandList[ii], (
"cliRun - cannot parse comment in COMMAND "
+ key
+ ":\nnew RegExp("
+ JSON.stringify(rgxComment.source)
+ ").exec(" + JSON.stringify(str).replace((
/\\\\/g
), "\u0000").replace((
/\\n/g
), "\\n\\\n").replace((
/\u0000/g
), "\\\\") + ");"
));
commandList[ii] = {
argList: local.coalesce(commandList[ii][1], "").trim(),
command: [
key
],
description: commandList[ii][2]
};
});
str = "";
str += packageJson.name + " (" + packageJson.version + ")\n\n";
str += 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# "
+ elem.description
);
}
return (
elem.description + "\n " + file
+ " " + elem.command.sort().join("|") + " "
+ elem.argList.join(" ")
);
}).join("\n\n");
console.log(str);...
...
dir: process.argv[2],
modulePathList: module.paths
}));
};
// run the cli
if (module === require.main && !globalThis.utility2_rollup) {
local.cliRun({});
}
}());
}());
...
function coalesce(...argList) {
/*
* this function will coalesce null, undefined, or "" in <argList>
*/
let arg;
let ii;
ii = 0;
while (ii < argList.length) {
arg = argList[ii];
if (arg !== undefined && arg !== null && arg !== "") {
return arg;
}
ii += 1;
}
return arg;
}
...
), "\u0000").replace((
/\\n/g
), "\\n\\\n").replace((
/\u0000/g
), "\\\\") + ");"
));
commandList[ii] = {
argList: local.coalesce(commandList[ii][1], "").trim(),
command: [
key
],
description: commandList[ii][2]
};
});
str = "";
...
function identity(val) {
/*
* this function will return <val>
*/
return val;
}
...
cliDict.help = cliDict.help || cliDict._help;
cliDict._interactive = cliDict._interactive || function () {
/*
*
* will start interactive-mode
*/
globalThis.local = local;
local.identity(local.replStart || require("repl").start)({
useGlobal: true
});
};
cliDict["--interactive"] = cliDict["--interactive"] || cliDict._interactive;
cliDict["-i"] = cliDict["-i"] || cliDict._interactive;
cliDict._version = cliDict._version || function () {
/*
...
jslint0 = function ( source = "", option_object = empty(), global_array = [] ) { // hack-jslint - init lines_extra line_ignore = undefined; lines = ( Array.isArray(source) ? source : source.split( /\n|\r\n?/ ) ); lines_extra = lines.map(function () { return {}; }); try { warnings = []; option = Object.assign(empty(), option_object); anon = "anonymous"; block_stack = []; declared_globals = empty(); directive_mode = true; directives = []; early_stop = true; exports = empty(); froms = []; fudge = ( option.fudge ? 1 : 0 ); functions = []; global = { id: "(global)", body: true, context: empty(), from: 0, level: 0, line: 0, live: [], loop: 0, switch: 0, thru: 0 }; blockage = global; functionage = global; json_mode = false; mega_mode = false; module_mode = false; next_token = global; property = empty(); shebang = false; stack = []; tenure = undefined; token = global; token_nr = 0; var_mode = undefined; populate(standard, declared_globals, false); populate(global_array, declared_globals, false); Object.keys(option).forEach(function (name) { if (option[name] === true) { const allowed = allowed_option[name]; if (Array.isArray(allowed)) { populate(allowed, declared_globals, false); } } }); tokenize(source); advance(); if (json_mode) { tree = json_value(); advance("(end)"); } else { // Because browsers encourage combining of script files, the first token might // be a semicolon to defend against a missing semicolon in the preceding file. if (option.browser) { if (next_token.id === ";") { advance(";"); } } else { // If we are not in a browser, then the file form of strict pragma may be used. if ( next_token.value === "use strict" ) { advance("(string)"); advance(";"); } } tree = statements(); advance("(end)"); functionage = global; walk_statement(tree); if (warnings.length === 0) { uninitialized_and_unused(); if (!option.white) { whitage(); } } } if (!option.browser) { directives.forEach(function (comment) { if (comment.directive === "global") { warn("missing_browser", comment); } }); } early_stop = false; // hack-jslint - throw_error if (option.throw_error) { throw new Error(); } } catch (e) { // hack-jslint - early_stop e.early_stop = true; e.column = e.column || -1; e.line = e.line || -1; if (e.name !== "JSLintError") { warnings.push(e); } } // hack-jslint - autofix warnings = warnings.filter(function (warning) { let aa; let bb; let tmp; if (!lines_extra[warning.line]) { return true; } aa = lines_extra[warning.line].source; warning.a = warning.a || aa.trim(); switch (option.autofix && warning.code) { // expected_a_at_b_c: "Expected '{a}' at column {b}, not column {c}.", case "expected_a_at_b_c&quo...
n/a
jslintAndPrint = function (code, file = "undefined", opt = {}) {
/*
* this function will jslint-autofix <code>
*/
return jslintRecurse(code, file, opt, {});
}
...
).replace(
new RegExp("require\\(." + env.npm_package_nameOriginal + ".\\)"),
"globalThis.utility2_moduleExports"
);
// init example.js
tmp = require("path").resolve("example.js");
// jslint code
local.jslintAndPrint(code, tmp);
// instrument code
code = local.istanbulInstrumentInPackage(code, tmp);
// init module.exports
module = new local.Module(tmp);
require.cache[tmp] = module;
module._compile(code, tmp);
// init exports
...
jslintAndPrintDir = function (dir, opt, onError) {
/*
* this function will jslint files in <dir>
*/
let errCnt;
errCnt = 0;
onError = onError || function (err) {
process.exit(Math.min((err && err.message) | 0, 127));
};
dir = require("path").resolve(dir) + require("path").sep;
require("fs").readdir(dir, function (err, fileList) {
local.onErrorThrow(err);
Promise.all(fileList.map(function (file) {
return new Promise(function (resolve) {
let timeStart;
timeStart = Date.now();
file = dir + 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)) {
resolve();
return;
}
// jslint file
require("fs").readFile(file, "utf8", function (err, data) {
if (err) {
return;
}
local.jslintAndPrint(data, file, opt);
errCnt += local.jslintResult.errList.length;
console.error(
"jslint - " + (Date.now() - timeStart) + "ms - "
+ file
);
resolve();
});
return;
}
resolve();
});
})).then(function () {
onError(errCnt && new Error(errCnt));
});
});
}
...
}
// start repl-debugger
local.replStart();
// jslint process.cwd()
require("child_process").spawn("node", [
"-e", (
"require(" + JSON.stringify(__filename)
+ ").jslint.jslintAndPrintDir(" + JSON.stringify(process.cwd())
+ ", {autofix:" + (!env.npm_config_mode_test)
+ ",conditional:true});"
)
], {
env: Object.assign({}, env, {
npm_config_mode_lib: "1"
}),
...
function noop() {
/*
* this function will do nothing
*/
return;
}
...
local.isBrowser
? {
env: {},
stdout: {}
}
: globalThis.process
);
local.noop(escodegen, esprima, estraverse, esutils);
/*
repo https://github.com/acornjs/acorn/tree/6.4.1
committed 2020-03-09T10:38:41Z
*/
...
function objectAssignDefault(tgt = {}, src = {}, depth = 0) {
/*
* this function will if items from <tgt> are null, undefined, or "",
* then overwrite them with items from <src>
*/
let recurse;
recurse = function (tgt, src, depth) {
Object.entries(src).forEach(function ([
key, bb
]) {
let aa;
aa = tgt[key];
if (aa === undefined || aa === null || aa === "") {
tgt[key] = bb;
return;
}
if (
depth !== 0
&& typeof aa === "object" && aa && !Array.isArray(aa)
&& typeof bb === "object" && bb && !Array.isArray(bb)
) {
recurse(aa, bb, depth - 1);
}
});
};
recurse(tgt, src, depth | 0);
return tgt;
}
...
return str;
};
// init opt
opt.dir = local.moduleDirname(
opt.dir,
opt.modulePathList || require("module").paths
);
local.objectAssignDefault(opt, {
env: {
npm_package_description: ""
},
packageJson: JSON.parse(readExample("package.json")),
require: function (file) {
return local.tryCatchOnError(function () {
return require(file);
...
function objectDeepCopyWithKeysSorted(obj) {
/*
* this function will recursively deep-copy <obj> with keys sorted
*/
let sorted;
if (typeof obj !== "object" || !obj) {
return obj;
}
// recursively deep-copy list with child-keys sorted
if (Array.isArray(obj)) {
return obj.map(objectDeepCopyWithKeysSorted);
}
// recursively deep-copy obj with keys sorted
sorted = {};
Object.keys(obj).sort().forEach(function (key) {
sorted[key] = objectDeepCopyWithKeysSorted(obj[key]);
});
return sorted;
}
...
start: "./npm_scripts.sh",
test: "./npm_scripts.sh",
utility2: "./npm_scripts.sh"
};
// write package.json
require("fs").writeFileSync(
"package.json",
JSON.stringify(local.objectDeepCopyWithKeysSorted(
packageJson
), undefined, 4) + "\n"
);
writeFileLog("package.json");
// re-render README.md
tgt = local.templateRenderMyApp(
local.assetsDict["/assets.readme.template.md"]
...
function onErrorThrow(err) {
/*
* this function will throw <err> if exists
*/
if (err) {
throw err;
}
}
...
promiseList.push(new Promise(function (resolve) {
require("fs").writeFile(
require("path").resolve(
process.env.npm_config_dir_build + "/test-report.json"
),
JSON.stringify(globalThis.utility2_testReport),
function (err) {
local.onErrorThrow(err);
console.error(
"\nbrowserTest - merged test-report "
+ process.env.npm_config_dir_build + "/test-report.json"
+ "\n"
);
resolve();
}
...
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 = api.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 = api.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
*/
let result;
local.tryCatchOnError(function () {
file = require("path").resolve(opt.dir, file);
console.error("apidocCreate - readExample " + file);
result = "";
result = local.identity(
"\n\n\n\n\n\n\n\n"
// bug-workaround - truncate example to manageable size
+ require("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; }
...
}
// init module.exports
module = {};
// if file is modified, then restart process
if (env.npm_config_mode_auto_restart) {
require("fs").readdir(".", function (ignore, fileList) {
fileList.concat(__filename).forEach(function (file) {
require("fs").stat(file, function (err, data) {
local.onErrorThrow(err);
if (!data.isFile()) {
return;
}
require("fs").watchFile(file, {
interval: 1000,
persistent: false
...
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(
require("fs").readFileSync(require("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));
}
...
cliDict._help();
return;
}
if (cliDict[process.argv[2]]) {
cliDict[process.argv[2]]();
return;
}
cliDict._default();
};
local.moduleDirname = function (module, pathList) {
/*
* this function will search <pathList> for <module>'s __dirname
*/
let 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
});
}
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.objectAssignDefault(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.objectAssignDefault(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()}
...
};
// Predicate that tests whether the next token is of the given
// type, and if yes, consumes it as a side effect.
pp.eat = function(type) {
if (this.type === type) {
this.next();
return true
} else {
return false
}
};
// Tests whether parsed token is a contextual keyword.
...
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.objectAssignDefault(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.
...