mcp-node-mssql
Version:
MCP Server for SQL Server using node-mssql
1,671 lines (1,651 loc) • 2.99 MB
JavaScript
#!/usr/bin/env node
import { createRequire } from "node:module";
var __create = Object.create;
var __getProtoOf = Object.getPrototypeOf;
var __defProp = Object.defineProperty;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __toESM = (mod, isNodeMode, target) => {
target = mod != null ? __create(__getProtoOf(mod)) : {};
const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
for (let key of __getOwnPropNames(mod))
if (!__hasOwnProp.call(to, key))
__defProp(to, key, {
get: () => mod[key],
enumerable: true
});
return to;
};
var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, {
get: all[name],
enumerable: true,
configurable: true,
set: (newValue) => all[name] = () => newValue
});
};
var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
var __require = /* @__PURE__ */ createRequire(import.meta.url);
// node_modules/ms/index.js
var require_ms = __commonJS((exports, module) => {
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var w = d * 7;
var y = d * 365.25;
module.exports = function(val, options) {
options = options || {};
var type = typeof val;
if (type === "string" && val.length > 0) {
return parse(val);
} else if (type === "number" && isFinite(val)) {
return options.long ? fmtLong(val) : fmtShort(val);
}
throw new Error("val is not a non-empty string or a valid number. val=" + JSON.stringify(val));
};
function parse(str) {
str = String(str);
if (str.length > 100) {
return;
}
var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str);
if (!match) {
return;
}
var n = parseFloat(match[1]);
var type = (match[2] || "ms").toLowerCase();
switch (type) {
case "years":
case "year":
case "yrs":
case "yr":
case "y":
return n * y;
case "weeks":
case "week":
case "w":
return n * w;
case "days":
case "day":
case "d":
return n * d;
case "hours":
case "hour":
case "hrs":
case "hr":
case "h":
return n * h;
case "minutes":
case "minute":
case "mins":
case "min":
case "m":
return n * m;
case "seconds":
case "second":
case "secs":
case "sec":
case "s":
return n * s;
case "milliseconds":
case "millisecond":
case "msecs":
case "msec":
case "ms":
return n;
default:
return;
}
}
function fmtShort(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return Math.round(ms / d) + "d";
}
if (msAbs >= h) {
return Math.round(ms / h) + "h";
}
if (msAbs >= m) {
return Math.round(ms / m) + "m";
}
if (msAbs >= s) {
return Math.round(ms / s) + "s";
}
return ms + "ms";
}
function fmtLong(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return plural(ms, msAbs, d, "day");
}
if (msAbs >= h) {
return plural(ms, msAbs, h, "hour");
}
if (msAbs >= m) {
return plural(ms, msAbs, m, "minute");
}
if (msAbs >= s) {
return plural(ms, msAbs, s, "second");
}
return ms + " ms";
}
function plural(ms, msAbs, n, name2) {
var isPlural = msAbs >= n * 1.5;
return Math.round(ms / n) + " " + name2 + (isPlural ? "s" : "");
}
});
// node_modules/debug/src/common.js
var require_common = __commonJS((exports, module) => {
function setup(env) {
createDebug.debug = createDebug;
createDebug.default = createDebug;
createDebug.coerce = coerce2;
createDebug.disable = disable;
createDebug.enable = enable;
createDebug.enabled = enabled;
createDebug.humanize = require_ms();
createDebug.destroy = destroy;
Object.keys(env).forEach((key) => {
createDebug[key] = env[key];
});
createDebug.names = [];
createDebug.skips = [];
createDebug.formatters = {};
function selectColor(namespace) {
let hash = 0;
for (let i = 0;i < namespace.length; i++) {
hash = (hash << 5) - hash + namespace.charCodeAt(i);
hash |= 0;
}
return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
}
createDebug.selectColor = selectColor;
function createDebug(namespace) {
let prevTime;
let enableOverride = null;
let namespacesCache;
let enabledCache;
function debug(...args) {
if (!debug.enabled) {
return;
}
const self2 = debug;
const curr = Number(new Date);
const ms = curr - (prevTime || curr);
self2.diff = ms;
self2.prev = prevTime;
self2.curr = curr;
prevTime = curr;
args[0] = createDebug.coerce(args[0]);
if (typeof args[0] !== "string") {
args.unshift("%O");
}
let index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
if (match === "%%") {
return "%";
}
index++;
const formatter = createDebug.formatters[format];
if (typeof formatter === "function") {
const val = args[index];
match = formatter.call(self2, val);
args.splice(index, 1);
index--;
}
return match;
});
createDebug.formatArgs.call(self2, args);
const logFn = self2.log || createDebug.log;
logFn.apply(self2, args);
}
debug.namespace = namespace;
debug.useColors = createDebug.useColors();
debug.color = createDebug.selectColor(namespace);
debug.extend = extend;
debug.destroy = createDebug.destroy;
Object.defineProperty(debug, "enabled", {
enumerable: true,
configurable: false,
get: () => {
if (enableOverride !== null) {
return enableOverride;
}
if (namespacesCache !== createDebug.namespaces) {
namespacesCache = createDebug.namespaces;
enabledCache = createDebug.enabled(namespace);
}
return enabledCache;
},
set: (v) => {
enableOverride = v;
}
});
if (typeof createDebug.init === "function") {
createDebug.init(debug);
}
return debug;
}
function extend(namespace, delimiter) {
const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace);
newDebug.log = this.log;
return newDebug;
}
function enable(namespaces) {
createDebug.save(namespaces);
createDebug.namespaces = namespaces;
createDebug.names = [];
createDebug.skips = [];
const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(" ", ",").split(",").filter(Boolean);
for (const ns of split) {
if (ns[0] === "-") {
createDebug.skips.push(ns.slice(1));
} else {
createDebug.names.push(ns);
}
}
}
function matchesTemplate(search, template) {
let searchIndex = 0;
let templateIndex = 0;
let starIndex = -1;
let matchIndex = 0;
while (searchIndex < search.length) {
if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) {
if (template[templateIndex] === "*") {
starIndex = templateIndex;
matchIndex = searchIndex;
templateIndex++;
} else {
searchIndex++;
templateIndex++;
}
} else if (starIndex !== -1) {
templateIndex = starIndex + 1;
matchIndex++;
searchIndex = matchIndex;
} else {
return false;
}
}
while (templateIndex < template.length && template[templateIndex] === "*") {
templateIndex++;
}
return templateIndex === template.length;
}
function disable() {
const namespaces = [
...createDebug.names,
...createDebug.skips.map((namespace) => "-" + namespace)
].join(",");
createDebug.enable("");
return namespaces;
}
function enabled(name2) {
for (const skip of createDebug.skips) {
if (matchesTemplate(name2, skip)) {
return false;
}
}
for (const ns of createDebug.names) {
if (matchesTemplate(name2, ns)) {
return true;
}
}
return false;
}
function coerce2(val) {
if (val instanceof Error) {
return val.stack || val.message;
}
return val;
}
function destroy() {
console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
}
createDebug.enable(createDebug.load());
return createDebug;
}
module.exports = setup;
});
// node_modules/debug/src/browser.js
var require_browser = __commonJS((exports, module) => {
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = localstorage();
exports.destroy = (() => {
let warned = false;
return () => {
if (!warned) {
warned = true;
console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
}
};
})();
exports.colors = [
"#0000CC",
"#0000FF",
"#0033CC",
"#0033FF",
"#0066CC",
"#0066FF",
"#0099CC",
"#0099FF",
"#00CC00",
"#00CC33",
"#00CC66",
"#00CC99",
"#00CCCC",
"#00CCFF",
"#3300CC",
"#3300FF",
"#3333CC",
"#3333FF",
"#3366CC",
"#3366FF",
"#3399CC",
"#3399FF",
"#33CC00",
"#33CC33",
"#33CC66",
"#33CC99",
"#33CCCC",
"#33CCFF",
"#6600CC",
"#6600FF",
"#6633CC",
"#6633FF",
"#66CC00",
"#66CC33",
"#9900CC",
"#9900FF",
"#9933CC",
"#9933FF",
"#99CC00",
"#99CC33",
"#CC0000",
"#CC0033",
"#CC0066",
"#CC0099",
"#CC00CC",
"#CC00FF",
"#CC3300",
"#CC3333",
"#CC3366",
"#CC3399",
"#CC33CC",
"#CC33FF",
"#CC6600",
"#CC6633",
"#CC9900",
"#CC9933",
"#CCCC00",
"#CCCC33",
"#FF0000",
"#FF0033",
"#FF0066",
"#FF0099",
"#FF00CC",
"#FF00FF",
"#FF3300",
"#FF3333",
"#FF3366",
"#FF3399",
"#FF33CC",
"#FF33FF",
"#FF6600",
"#FF6633",
"#FF9900",
"#FF9933",
"#FFCC00",
"#FFCC33"
];
function useColors() {
if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) {
return true;
}
if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
return false;
}
let m;
return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
}
function formatArgs(args) {
args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module.exports.humanize(this.diff);
if (!this.useColors) {
return;
}
const c = "color: " + this.color;
args.splice(1, 0, c, "color: inherit");
let index = 0;
let lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, (match) => {
if (match === "%%") {
return;
}
index++;
if (match === "%c") {
lastC = index;
}
});
args.splice(lastC, 0, c);
}
exports.log = console.debug || console.log || (() => {});
function save(namespaces) {
try {
if (namespaces) {
exports.storage.setItem("debug", namespaces);
} else {
exports.storage.removeItem("debug");
}
} catch (error) {}
}
function load() {
let r;
try {
r = exports.storage.getItem("debug");
} catch (error) {}
if (!r && typeof process !== "undefined" && "env" in process) {
r = process.env.DEBUG;
}
return r;
}
function localstorage() {
try {
return localStorage;
} catch (error) {}
}
module.exports = require_common()(exports);
var { formatters } = module.exports;
formatters.j = function(v) {
try {
return JSON.stringify(v);
} catch (error) {
return "[UnexpectedJSONParseError]: " + error.message;
}
};
});
// node_modules/debug/src/node.js
var require_node = __commonJS((exports, module) => {
var tty = __require("tty");
var util2 = __require("util");
exports.init = init;
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.destroy = util2.deprecate(() => {}, "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
exports.colors = [6, 2, 3, 4, 5, 1];
try {
const supportsColor = (()=>{throw new Error("Cannot require module "+"supports-color");})();
if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
exports.colors = [
20,
21,
26,
27,
32,
33,
38,
39,
40,
41,
42,
43,
44,
45,
56,
57,
62,
63,
68,
69,
74,
75,
76,
77,
78,
79,
80,
81,
92,
93,
98,
99,
112,
113,
128,
129,
134,
135,
148,
149,
160,
161,
162,
163,
164,
165,
166,
167,
168,
169,
170,
171,
172,
173,
178,
179,
184,
185,
196,
197,
198,
199,
200,
201,
202,
203,
204,
205,
206,
207,
208,
209,
214,
215,
220,
221
];
}
} catch (error) {}
exports.inspectOpts = Object.keys(process.env).filter((key) => {
return /^debug_/i.test(key);
}).reduce((obj, key) => {
const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k) => {
return k.toUpperCase();
});
let val = process.env[key];
if (/^(yes|on|true|enabled)$/i.test(val)) {
val = true;
} else if (/^(no|off|false|disabled)$/i.test(val)) {
val = false;
} else if (val === "null") {
val = null;
} else {
val = Number(val);
}
obj[prop] = val;
return obj;
}, {});
function useColors() {
return "colors" in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(process.stderr.fd);
}
function formatArgs(args) {
const { namespace: name2, useColors: useColors2 } = this;
if (useColors2) {
const c = this.color;
const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c);
const prefix = ` ${colorCode};1m${name2} \x1B[0m`;
args[0] = prefix + args[0].split(`
`).join(`
` + prefix);
args.push(colorCode + "m+" + module.exports.humanize(this.diff) + "\x1B[0m");
} else {
args[0] = getDate() + name2 + " " + args[0];
}
}
function getDate() {
if (exports.inspectOpts.hideDate) {
return "";
}
return new Date().toISOString() + " ";
}
function log(...args) {
return process.stderr.write(util2.formatWithOptions(exports.inspectOpts, ...args) + `
`);
}
function save(namespaces) {
if (namespaces) {
process.env.DEBUG = namespaces;
} else {
delete process.env.DEBUG;
}
}
function load() {
return process.env.DEBUG;
}
function init(debug) {
debug.inspectOpts = {};
const keys = Object.keys(exports.inspectOpts);
for (let i = 0;i < keys.length; i++) {
debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
}
}
module.exports = require_common()(exports);
var { formatters } = module.exports;
formatters.o = function(v) {
this.inspectOpts.colors = this.useColors;
return util2.inspect(v, this.inspectOpts).split(`
`).map((str) => str.trim()).join(" ");
};
formatters.O = function(v) {
this.inspectOpts.colors = this.useColors;
return util2.inspect(v, this.inspectOpts);
};
});
// node_modules/debug/src/index.js
var require_src = __commonJS((exports, module) => {
if (typeof process === "undefined" || process.type === "renderer" || false || process.__nwjs) {
module.exports = require_browser();
} else {
module.exports = require_node();
}
});
// node_modules/@tediousjs/connection-string/lib/parser/connection-string.js
var require_connection_string = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
var CollectionMode;
(function(CollectionMode2) {
CollectionMode2[CollectionMode2["key"] = 0] = "key";
CollectionMode2[CollectionMode2["value"] = 1] = "value";
})(CollectionMode || (CollectionMode = {}));
var CONFIG = Object.freeze({
key: {
terminator: "=",
quotes: {}
},
value: {
terminator: ";",
quotes: {
'"': '"',
"'": "'",
"{": "}"
}
}
});
function connectionStringParser(connectionString, parserConfig = CONFIG) {
const parsed = {};
let collectionMode = CollectionMode.key;
let started = false;
let finished = false;
let quoted = false;
let quote = "";
let buffer = "";
let currentKey = "";
let pointer = 0;
function start() {
started = true;
}
function finish() {
finished = true;
}
function reset() {
started = false;
finished = false;
quoted = false;
quote = "";
buffer = "";
}
function config() {
return collectionMode === CollectionMode.key ? parserConfig.key : parserConfig.value;
}
function isTerminator(char) {
return config().terminator === char;
}
function isStartQuote(char) {
return Object.keys(config().quotes).some((val) => char === val);
}
function isEndQuote(char) {
return quoted && char === config().quotes[quote];
}
function push(char) {
buffer += char;
}
function collect() {
if (!quoted) {
buffer = buffer.trim();
}
switch (collectionMode) {
case CollectionMode.key:
currentKey = buffer.toLowerCase();
collectionMode = CollectionMode.value;
break;
case CollectionMode.value:
collectionMode = CollectionMode.key;
parsed[currentKey] = buffer;
currentKey = "";
break;
}
reset();
}
while (pointer < connectionString.length) {
const current = connectionString.charAt(pointer);
if (!finished) {
if (!started) {
if (current.trim()) {
start();
if (isStartQuote(current)) {
quoted = true;
quote = current;
} else {
push(current);
}
}
} else {
if (quoted && isEndQuote(current)) {
const next = connectionString.charAt(pointer + 1);
if (current === next) {
push(current);
pointer++;
} else {
finish();
}
} else if (!quoted && isTerminator(current)) {
const next = connectionString.charAt(pointer + 1);
if (current === next) {
push(current);
pointer++;
} else {
collect();
}
} else {
push(current);
}
}
} else if (isTerminator(current)) {
collect();
} else if (current.trim()) {
throw new Error("Malformed connection string");
}
pointer++;
}
if (quoted && !finished) {
throw new Error("Connection string terminated unexpectedly");
} else {
collect();
}
return parsed;
}
exports.default = connectionStringParser;
});
// node_modules/@tediousjs/connection-string/lib/parser/sql-connection-string.js
var require_sql_connection_string = __commonJS((exports) => {
var __importDefault = exports && exports.__importDefault || function(mod) {
return mod && mod.__esModule ? mod : { default: mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SCHEMA = exports.SchemaTypes = undefined;
var connection_string_1 = __importDefault(require_connection_string());
var SchemaTypes;
(function(SchemaTypes2) {
SchemaTypes2[SchemaTypes2["BOOL"] = 0] = "BOOL";
SchemaTypes2[SchemaTypes2["STRING"] = 1] = "STRING";
SchemaTypes2[SchemaTypes2["NUMBER"] = 2] = "NUMBER";
})(SchemaTypes = exports.SchemaTypes || (exports.SchemaTypes = {}));
exports.SCHEMA = {
"Application Name": {
type: SchemaTypes.STRING,
aliases: ["App"],
validator(val) {
return typeof val === "string" && val.length <= 128;
}
},
ApplicationIntent: {
type: SchemaTypes.STRING,
allowedValues: ["ReadOnly", "ReadWrite"],
default: "ReadWrite"
},
"Asynchronous Processing": {
type: SchemaTypes.BOOL,
default: false,
aliases: ["Async"]
},
AttachDBFilename: {
type: SchemaTypes.STRING,
aliases: ["Extended Properties", "Initial File Name"]
},
Authentication: {
type: SchemaTypes.STRING,
allowedValues: ["Active Directory Integrated", "Active Directory Password", "Sql Password"]
},
"Column Encryption Setting": {
type: SchemaTypes.STRING
},
"Connection Timeout": {
type: SchemaTypes.NUMBER,
aliases: ["Connect Timeout", "Timeout"],
default: 15
},
"Connection Lifetime": {
type: SchemaTypes.NUMBER,
aliases: ["Load Balance Timeout"],
default: 0
},
ConnectRetryCount: {
type: SchemaTypes.NUMBER,
default: 1,
validator(val) {
return val > 0 && val <= 255;
}
},
ConnectRetryInterval: {
type: SchemaTypes.NUMBER,
default: 10
},
"Context Connection": {
type: SchemaTypes.BOOL,
default: false
},
"Current Language": {
aliases: ["Language"],
type: SchemaTypes.STRING,
validator(val) {
return typeof val === "string" && val.length <= 128;
}
},
"Data Source": {
aliases: ["Addr", "Address", "Server", "Network Address"],
type: SchemaTypes.STRING
},
Encrypt: {
type: SchemaTypes.BOOL,
default: false
},
Enlist: {
type: SchemaTypes.BOOL,
default: true
},
"Failover Partner": {
type: SchemaTypes.STRING
},
"Initial Catalog": {
type: SchemaTypes.STRING,
aliases: ["Database"],
validator(val) {
return typeof val === "string" && val.length <= 128;
}
},
"Integrated Security": {
type: SchemaTypes.BOOL,
aliases: ["Trusted_Connection"],
coerce(val) {
return val === "sspi" || null;
}
},
"Max Pool Size": {
type: SchemaTypes.NUMBER,
default: 100,
validator(val) {
return val >= 1;
}
},
"Min Pool Size": {
type: SchemaTypes.NUMBER,
default: 0,
validator(val) {
return val >= 0;
}
},
MultipleActiveResultSets: {
type: SchemaTypes.BOOL,
default: false
},
MultiSubnetFailover: {
type: SchemaTypes.BOOL,
default: false
},
"Network Library": {
type: SchemaTypes.STRING,
aliases: ["Network", "Net"],
allowedValues: ["dbnmpntw", "dbmsrpcn", "dbmsadsn", "dbmsgnet", "dbmslpcn", "dbmsspxn", "dbmssocn", "Dbmsvinn"]
},
"Packet Size": {
type: SchemaTypes.NUMBER,
default: 8000,
validator(val) {
return val >= 512 && val <= 32768;
}
},
Password: {
type: SchemaTypes.STRING,
aliases: ["PWD"],
validator(val) {
return typeof val === "string" && val.length <= 128;
}
},
"Persist Security Info": {
type: SchemaTypes.BOOL,
aliases: ["PersistSecurityInfo"],
default: false
},
PoolBlockingPeriod: {
type: SchemaTypes.NUMBER,
default: 0,
coerce(val) {
if (typeof val !== "string") {
return null;
}
switch (val.toLowerCase()) {
case "alwaysblock":
return 1;
case "auto":
return 0;
case "neverblock":
return 2;
}
return null;
}
},
Pooling: {
type: SchemaTypes.BOOL,
default: true
},
Replication: {
type: SchemaTypes.BOOL,
default: false
},
"Transaction Binding": {
type: SchemaTypes.STRING,
allowedValues: ["Implicit Unbind", "Explicit Unbind"],
default: "Implicit Unbind"
},
TransparentNetworkIPResolution: {
type: SchemaTypes.BOOL,
default: true
},
TrustServerCertificate: {
type: SchemaTypes.BOOL,
default: false
},
"Type System Version": {
type: SchemaTypes.STRING,
allowedValues: ["SQL Server 2012", "SQL Server 2008", "SQL Server 2005", "Latest"]
},
"User ID": {
type: SchemaTypes.STRING,
aliases: ["UID"],
validator(val) {
return typeof val === "string" && val.length <= 128;
}
},
"User Instance": {
type: SchemaTypes.BOOL,
default: false
},
"Workstation ID": {
type: SchemaTypes.STRING,
aliases: ["WSID"],
validator(val) {
return typeof val === "string" && val.length <= 128;
}
}
};
function guessType(value) {
if (value.trim() === "") {
return SchemaTypes.STRING;
}
const asNum = parseInt(value, 10);
if (!Number.isNaN(asNum) && asNum.toString() === value) {
return SchemaTypes.NUMBER;
}
if (["true", "false", "yes", "no"].includes(value.toLowerCase())) {
return SchemaTypes.BOOL;
}
return SchemaTypes.STRING;
}
function coerce2(value, type, coercer) {
if (coercer) {
const coerced = coercer(value);
if (coerced !== null) {
return coerced;
}
}
switch (type) {
case SchemaTypes.BOOL:
if (["true", "yes", "1"].includes(value.toLowerCase())) {
return true;
}
if (["false", "no", "0"].includes(value.toLowerCase())) {
return false;
}
return value;
case SchemaTypes.NUMBER:
return parseInt(value, 10);
}
return value;
}
function validate(value, allowedValues, validator) {
let valid = true;
if (validator) {
valid = validator(value);
}
if (valid) {
valid = (allowedValues === null || allowedValues === undefined ? undefined : allowedValues.includes(value)) || false;
}
return valid;
}
function parseSqlConnectionString(connectionString, canonicalProps = false, allowUnknown = false, strict = false, schema = exports.SCHEMA) {
const flattenedSchema = Object.entries(schema).reduce((flattened, [key, item]) => {
var _a;
Object.assign(flattened, {
[key.toLowerCase()]: item
});
return ((_a = item.aliases) === null || _a === undefined ? undefined : _a.reduce((accum, alias) => {
return Object.assign(accum, {
[alias.toLowerCase()]: {
...item,
canonical: key.toLowerCase()
}
});
}, flattened)) || flattened;
}, {});
return Object.entries((0, connection_string_1.default)(connectionString)).reduce((config, [prop, value]) => {
if (!Object.prototype.hasOwnProperty.call(flattenedSchema, prop)) {
return Object.assign(config, {
[prop]: coerce2(value, guessType(value))
});
}
let coercedValue = coerce2(value, flattenedSchema[prop].type, flattenedSchema[prop].coerce);
if (strict && !validate(coercedValue, flattenedSchema[prop].allowedValues, flattenedSchema[prop].validator)) {
coercedValue = flattenedSchema[prop].default;
}
const propName = canonicalProps ? flattenedSchema[prop].canonical || prop : prop;
return Object.assign(config, {
[propName]: coercedValue
});
}, {});
}
exports.default = parseSqlConnectionString;
});
// node_modules/@tediousjs/connection-string/lib/builder/index.js
var require_builder = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildConnectionString = undefined;
function isQuoted(val) {
if (val[0] !== "{") {
return false;
}
for (let i = 1;i < val.length; i++) {
if (val[i] === "}") {
if (i + 1 === val.length) {
return true;
} else if (val[i + 1] !== "}") {
return false;
} else {
i++;
}
}
}
return false;
}
function needsQuotes(val) {
var _a;
return !isQuoted(val) && !!((_a = val.match(/\[|]|{|}|\|\(|\)|,|;|\?|\*|=|!|@/)) === null || _a === undefined ? undefined : _a.length);
}
function encodeTuple(key, value) {
if (value === null || value === undefined) {
return [key, ""];
}
switch (typeof value) {
case "boolean":
return [key, value ? "Yes" : "No"];
default: {
const strVal = value.toString();
if (needsQuotes(strVal)) {
return [key, `{${strVal.replace(/}/g, "}}")}}`];
}
return [key, strVal];
}
}
}
function buildConnectionString(data) {
return Object.entries(data).map(([key, value]) => {
return encodeTuple(key.trim(), value).join("=");
}).join(";");
}
exports.buildConnectionString = buildConnectionString;
});
// node_modules/@tediousjs/connection-string/lib/index.js
var require_lib = __commonJS((exports) => {
var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
if (k2 === undefined)
k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m[k];
} };
}
Object.defineProperty(o, k2, desc);
} : function(o, m, k, k2) {
if (k2 === undefined)
k2 = k;
o[k2] = m[k];
});
var __exportStar = exports && exports.__exportStar || function(m, exports2) {
for (var p in m)
if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p))
__createBinding(exports2, m, p);
};
var __importDefault = exports && exports.__importDefault || function(mod) {
return mod && mod.__esModule ? mod : { default: mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseSqlConnectionString = exports.parseConnectionString = undefined;
var connection_string_1 = __importDefault(require_connection_string());
exports.parseConnectionString = connection_string_1.default;
var sql_connection_string_1 = __importDefault(require_sql_connection_string());
exports.parseSqlConnectionString = sql_connection_string_1.default;
__exportStar(require_builder(), exports);
});
// node_modules/tarn/dist/TimeoutError.js
var require_TimeoutError = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
class TimeoutError extends Error {
}
exports.TimeoutError = TimeoutError;
});
// node_modules/tarn/dist/PromiseInspection.js
var require_PromiseInspection = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
class PromiseInspection {
constructor(args) {
this._value = args.value;
this._error = args.error;
}
value() {
return this._value;
}
reason() {
return this._error;
}
isRejected() {
return !!this._error;
}
isFulfilled() {
return !!this._value;
}
}
exports.PromiseInspection = PromiseInspection;
});
// node_modules/tarn/dist/utils.js
var require_utils = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
var PromiseInspection_1 = require_PromiseInspection();
function defer() {
let resolve = null;
let reject = null;
const promise2 = new Promise((resolver, rejecter) => {
resolve = resolver;
reject = rejecter;
});
return {
promise: promise2,
resolve,
reject
};
}
exports.defer = defer;
function now() {
return Date.now();
}
exports.now = now;
function duration(t1, t2) {
return Math.abs(t2 - t1);
}
exports.duration = duration;
function checkOptionalTime(time) {
if (typeof time === "undefined") {
return true;
}
return checkRequiredTime(time);
}
exports.checkOptionalTime = checkOptionalTime;
function checkRequiredTime(time) {
return typeof time === "number" && time === Math.round(time) && time > 0;
}
exports.checkRequiredTime = checkRequiredTime;
function delay(millis) {
return new Promise((resolve) => setTimeout(resolve, millis));
}
exports.delay = delay;
function reflect(promise2) {
return promise2.then((value) => {
return new PromiseInspection_1.PromiseInspection({ value });
}).catch((error) => {
return new PromiseInspection_1.PromiseInspection({ error });
});
}
exports.reflect = reflect;
function tryPromise(cb) {
try {
const result = cb();
return Promise.resolve(result);
} catch (err) {
return Promise.reject(err);
}
}
exports.tryPromise = tryPromise;
});
// node_modules/tarn/dist/PendingOperation.js
var require_PendingOperation = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
var TimeoutError_1 = require_TimeoutError();
var utils_1 = require_utils();
class PendingOperation {
constructor(timeoutMillis) {
this.timeoutMillis = timeoutMillis;
this.deferred = utils_1.defer();
this.possibleTimeoutCause = null;
this.isRejected = false;
this.promise = timeout(this.deferred.promise, timeoutMillis).catch((err) => {
if (err instanceof TimeoutError_1.TimeoutError) {
if (this.possibleTimeoutCause) {
err = new TimeoutError_1.TimeoutError(this.possibleTimeoutCause.message);
} else {
err = new TimeoutError_1.TimeoutError("operation timed out for an unknown reason");
}
}
this.isRejected = true;
return Promise.reject(err);
});
}
abort() {
this.reject(new Error("aborted"));
}
reject(err) {
this.deferred.reject(err);
}
resolve(value) {
this.deferred.resolve(value);
}
}
exports.PendingOperation = PendingOperation;
function timeout(promise2, time) {
return new Promise((resolve, reject) => {
const timeoutHandle = setTimeout(() => reject(new TimeoutError_1.TimeoutError), time);
promise2.then((result) => {
clearTimeout(timeoutHandle);
resolve(result);
}).catch((err) => {
clearTimeout(timeoutHandle);
reject(err);
});
});
}
});
// node_modules/tarn/dist/Resource.js
var require_Resource = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
var utils_1 = require_utils();
class Resource {
constructor(resource) {
this.resource = resource;
this.resource = resource;
this.timestamp = utils_1.now();
this.deferred = utils_1.defer();
}
get promise() {
return this.deferred.promise;
}
resolve() {
this.deferred.resolve(undefined);
return new Resource(this.resource);
}
}
exports.Resource = Resource;
});
// node_modules/tarn/dist/Pool.js
var require_Pool = __commonJS((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
var PendingOperation_1 = require_PendingOperation();
var Resource_1 = require_Resource();
var utils_1 = require_utils();
var events_1 = __require("events");
var timers_1 = __require("timers");
class Pool {
constructor(opt) {
this.destroyed = false;
this.emitter = new events_1.EventEmitter;
opt = opt || {};
if (!opt.create) {
throw new Error("Tarn: opt.create function most be provided");
}
if (!opt.destroy) {
throw new Error("Tarn: opt.destroy function most be provided");
}
if (typeof opt.min !== "number" || opt.min < 0 || opt.min !== Math.round(opt.min)) {
throw new Error("Tarn: opt.min must be an integer >= 0");
}
if (typeof opt.max !== "number" || opt.max <= 0 || opt.max !== Math.round(opt.max)) {
throw new Error("Tarn: opt.max must be an integer > 0");
}
if (opt.min > opt.max) {
throw new Error("Tarn: opt.max is smaller than opt.min");
}
if (!utils_1.checkOptionalTime(opt.acquireTimeoutMillis)) {
throw new Error("Tarn: invalid opt.acquireTimeoutMillis " + JSON.stringify(opt.acquireTimeoutMillis));
}
if (!utils_1.checkOptionalTime(opt.createTimeoutMillis)) {
throw new Error("Tarn: invalid opt.createTimeoutMillis " + JSON.stringify(opt.createTimeoutMillis));
}
if (!utils_1.checkOptionalTime(opt.destroyTimeoutMillis)) {
throw new Error("Tarn: invalid opt.destroyTimeoutMillis " + JSON.stringify(opt.destroyTimeoutMillis));
}
if (!utils_1.checkOptionalTime(opt.idleTimeoutMillis)) {
throw new Error("Tarn: invalid opt.idleTimeoutMillis " + JSON.stringify(opt.idleTimeoutMillis));
}
if (!utils_1.checkOptionalTime(opt.reapIntervalMillis)) {
throw new Error("Tarn: invalid opt.reapIntervalMillis " + JSON.stringify(opt.reapIntervalMillis));
}
if (!utils_1.checkOptionalTime(opt.createRetryIntervalMillis)) {
throw new Error("Tarn: invalid opt.createRetryIntervalMillis " + JSON.stringify(opt.createRetryIntervalMillis));
}
const allowedKeys = {
create: true,
validate: true,
destroy: true,
log: true,
min: true,
max: true,
acquireTimeoutMillis: true,
createTimeoutMillis: true,
destroyTimeoutMillis: true,
idleTimeoutMillis: true,
reapIntervalMillis: true,
createRetryIntervalMillis: true,
propagateCreateError: true
};
for (const key of Object.keys(opt)) {
if (!allowedKeys[key]) {
throw new Error(`Tarn: unsupported option opt.${key}`);
}
}
this.creator = opt.create;
this.destroyer = opt.destroy;
this.validate = typeof opt.validate === "function" ? opt.validate : () => true;
this.log = opt.log || (() => {});
this.acquireTimeoutMillis = opt.acquireTimeoutMillis || 30000;
this.createTimeoutMillis = opt.createTimeoutMillis || 30000;
this.destroyTimeoutMillis = opt.destroyTimeoutMillis || 5000;
this.idleTimeoutMillis = opt.idleTimeoutMillis || 30000;
this.reapIntervalMillis = opt.reapIntervalMillis || 1000;
this.createRetryIntervalMillis = opt.createRetryIntervalMillis || 200;
this.propagateCreateError = !!opt.propagateCreateError;
this.min = opt.min;
this.max = opt.max;
this.used = [];
this.free = [];
this.pendingCreates = [];
this.pendingAcquires = [];
this.pendingDestroys = [];
this.pendingValidations = [];
this.destroyed = false;
this.interval = null;
this.eventId = 1;
}
numUsed() {
return this.used.length;
}
numFree() {
return this.free.length;
}
numPendingAcquires() {
return this.pendingAcquires.length;
}
numPendingValidations() {
return this.pendingValidations.length;
}
numPendingCreates() {
return this.pendingCreates.length;
}
acquire() {
const eventId = this.eventId++;
this._executeEventHandlers("acquireRequest", eventId);
const pendingAcquire = new PendingOperation_1.PendingOperation(this.acquireTimeoutMillis);
this.pendingAcquires.push(pendingAcquire);
pendingAcquire.promise = pendingAcquire.promise.then((resource) => {
this._executeEventHandlers("acquireSuccess", eventId, resource);
return resource;
}).catch((err) => {
this._executeEventHandlers("acquireFail", eventId, err);
remove(this.pendingAcquires, pendingAcquire);
return Promise.reject(err);
});
this._tryAcquireOrCreate();
return pendingAcquire;
}
release(resource) {
this._executeEventHandlers("release", resource);
for (let i = 0, l = this.used.length;i < l; ++i) {
const used = this.used[i];
if (used.resource === resource) {
this.used.splice(i, 1);
this.free.push(used.resolve());
this._tryAcquireOrCreate();
return true;
}
}
return false;
}
isEmpty() {
return [
this.numFree(),
this.numUsed(),
this.numPendingAcquires(),
this.numPendingValidations(),
this.numPendingCreates()
].reduce((total, value) => total + value) === 0;
}
check() {
const timestamp = utils_1.now();
const newFree = [];
const minKeep = this.min - this.used.length;
const maxDestroy = this.free.length - minKeep;
let numDestroyed = 0;
this.free.forEach((free) => {
if (utils_1.duration(timestamp, free.timestamp) >= this.idleTimeoutMillis && numDestroyed < maxDestroy) {
numDestroyed++;
this._destroy(free.resource);
} else {
newFree.push(free);
}
});
this.free = newFree;
if (this.isEmpty()) {
this._stopReaping();
}
}
destroy() {
const eventId = this.eventId++;
this._executeEventHandlers("poolDestroyRequest", eventId);
this._stopReaping();
this.destroyed = true;
return utils_1.reflect(Promise.all(this.pendingCreates.map((create) => utils_1.reflect(create.promise))).then(() => {
return new Promise((resolve, reject) => {
if (this.numPendingValidations() === 0) {
resolve();
return;
}
const interval = setInterval(() => {
if (this.numPendingValidations() === 0) {
timers_1.clearInterval(interval);
resolve();
}
}, 100);
});
}).then(() => {
return Promise.all(this.used.map((used) => utils_1.reflect(used.promise)));
}).then(() => {
return Promise.all(this.pendingAcquires.map((acquire) => {
acquire.abort();
return utils_1.reflect(acquire.promise);
}));
}).then(() => {
return Promise.all(this.free.map((free) => utils_1.reflect(this._destroy(free.resource))));
}).then(() => {
return Promise.all(this.pendingDestroys.map((pd) => pd.promise));
}).then(() => {
this.free = [];
this.pendingAcquires = [];
})).then((res) => {
this._executeEventHandlers("poolDestroySuccess", eventId);
this.emitter.removeAllListeners();
return res;
});
}
on(event, listener) {
this.emitter.on(event, listener);
}
removeListener(event, listener) {
this.emitter.removeListener(event, listener);
}
removeAllListeners(event) {
this.emitter.removeAllListeners(event);
}
_tryAcquireOrCreate() {
if (this.destroyed) {
return;
}
if (this._hasFreeResources()) {
this._doAcquire();
} else if (this._shouldCreateMoreResources()) {
this._doCreate();
}
}
_hasFreeResources() {
return this.free.length > 0;
}
_doAcquire() {
while (this._canAcquire()) {
const pendingAcquire = this.pendingAcquires.shift();
const free = this.free.pop();
if (free === undefined || pendingAcquire === undefined) {
const errMessage = "this.free was empty while trying to acquire resource";
this.log(`Tarn: ${errMessage}`, "warn");
throw new Error(`Internal error, should never happen. ${errMessage}`);
}
this.pendingValidations.push(pendingAcquire);
this.used.push(free);
const abortAbleValidation = new PendingOperation_1.PendingOperation(this.acquireTimeoutMillis);
pendingAcquire.promise.catch((err) => {
abortAbleValidation.abort();
});
abortAbleValidation.promise.catch((err) => {
this.log("Tarn: resource validator threw an exception " + err.stack, "warn");
return false;
}).then((validationSuccess) => {
try {
if (validationSuccess && !pendingAcquire.isRejected) {
this._startReaping();
pendingAcquire.resolve(free.resource);
} else {
remove(this.used, free);
if (!validationSuccess) {
this._destroy(free.resource);
setTimeout(() => {
this._tryAcquireOrCreate();
}, 0);
} else {
this.free.push(free);
}
if (!pendingAcquire.isRejected) {
this.pendingAcquires.unshift(pendingAcquire);
}
}
} finally {
remove(this.pendingValidations, pendingAcquire);
}
});
this._validateResource(free.resource).then((validationSuccess) => {
abortAbleValidation.resolve(validationSuccess);
}).catch((err) => {
abortAbleValidation.reject(err);
});
}
}
_canAcquire() {
return this.free.length > 0 && this.pendingAcquires.length > 0;
}
_validateResource(resource) {
try {
return Promise.resolve(this.validate(resource));
} catch (err) {
return Promise.reject(err);
}
}
_shouldCreateMoreResources() {
return this.used.length + this.pendingCreates.length < this.max && this.pendingCreates.length < this.pendingAcquires.length;
}
_doCreate() {
const pendingAcquiresBeforeCreate = this.pendingAcquires.slice();
const pendingCreate = this._create();
pendingCreate.promise.then(() => {
this._tryAcquireOrCreate();
return null;
}).catch((err) => {
if (this.propagateCreateError && this.pendingAcquires.length !== 0) {
this.pendingAcquires[0].reject(err);
}
pendingAcquiresBeforeCreate.forEach((pendingAcquire) => {
pendingAcquire.possibleTimeoutCause = err;
});
utils_1.delay(this.createRetryIntervalMillis).then(() => this._tryAcquireOrCreate());
});
}
_create() {
const eventId = this.eventId++;
this._executeEventHandlers("createRequest", eventId);
const pendingCreate = new PendingOperation_1.PendingOperation(this.createTimeoutMillis);
pendingCreate.promise = pendingCreate.promise.catch((err) => {
if (remove(this.pendingCreates, pendingCreate)) {
this._executeEventHandlers("createFail", eventId, err);
}
throw err;
});
this.pendingCreates.push(pendingCreate);
callbackOrPromise(this.creator).then((resource) => {
if (pendingCreate.isRejected) {
this.destroyer(resource);
return null;
}
remove(this.pendingCreates, pendingCreate);
this.free.push(new Resource_1.Resource(resource));
pendingCreate.resolve(resource);
this._executeEventHandlers("createSuccess", eventId, resource);
return null;
}).catch((err) => {
if (pendingCreate.isRejected) {
return null;
}
if (remove(this.pendingCreates, pendingCreate)) {
this._executeEventHandlers("createFail", eventId, err);
}
pendingCreate.reject(err);
return null;
});
return pendingCreate;
}
_destroy(resource) {
const eventId = this.eventId++;
this._executeEventHandlers("destroyRequest", eventId, resource);
const pendingDestroy = new PendingOperation_1.PendingOperation(this.destroyTimeoutMillis);
const retVal = Promise.resolve().then(() => this.destroyer(resource));
retVal.then(() => {
pendingDestroy.resolve(resource);
}).catch((err) => {
pendingDestroy.reject(err);
});
this.pendingDestroys.push(pendingDestroy);
return pendingDestroy.promise.then((res) => {
this._executeEventHandlers("destroySuccess", eventId, resource);
return res;
}).catch((err) => this._logDestroyerError(eventId, resource, err)).then((res) => {
const index = this.pendingDestroys.findIndex((pd) => pd === pendingD