Project Files
test-output.js
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// node_modules/color-name/index.js
var require_color_name = __commonJS({
"node_modules/color-name/index.js"(exports2, module2) {
"use strict";
module2.exports = {
"aliceblue": [240, 248, 255],
"antiquewhite": [250, 235, 215],
"aqua": [0, 255, 255],
"aquamarine": [127, 255, 212],
"azure": [240, 255, 255],
"beige": [245, 245, 220],
"bisque": [255, 228, 196],
"black": [0, 0, 0],
"blanchedalmond": [255, 235, 205],
"blue": [0, 0, 255],
"blueviolet": [138, 43, 226],
"brown": [165, 42, 42],
"burlywood": [222, 184, 135],
"cadetblue": [95, 158, 160],
"chartreuse": [127, 255, 0],
"chocolate": [210, 105, 30],
"coral": [255, 127, 80],
"cornflowerblue": [100, 149, 237],
"cornsilk": [255, 248, 220],
"crimson": [220, 20, 60],
"cyan": [0, 255, 255],
"darkblue": [0, 0, 139],
"darkcyan": [0, 139, 139],
"darkgoldenrod": [184, 134, 11],
"darkgray": [169, 169, 169],
"darkgreen": [0, 100, 0],
"darkgrey": [169, 169, 169],
"darkkhaki": [189, 183, 107],
"darkmagenta": [139, 0, 139],
"darkolivegreen": [85, 107, 47],
"darkorange": [255, 140, 0],
"darkorchid": [153, 50, 204],
"darkred": [139, 0, 0],
"darksalmon": [233, 150, 122],
"darkseagreen": [143, 188, 143],
"darkslateblue": [72, 61, 139],
"darkslategray": [47, 79, 79],
"darkslategrey": [47, 79, 79],
"darkturquoise": [0, 206, 209],
"darkviolet": [148, 0, 211],
"deeppink": [255, 20, 147],
"deepskyblue": [0, 191, 255],
"dimgray": [105, 105, 105],
"dimgrey": [105, 105, 105],
"dodgerblue": [30, 144, 255],
"firebrick": [178, 34, 34],
"floralwhite": [255, 250, 240],
"forestgreen": [34, 139, 34],
"fuchsia": [255, 0, 255],
"gainsboro": [220, 220, 220],
"ghostwhite": [248, 248, 255],
"gold": [255, 215, 0],
"goldenrod": [218, 165, 32],
"gray": [128, 128, 128],
"green": [0, 128, 0],
"greenyellow": [173, 255, 47],
"grey": [128, 128, 128],
"honeydew": [240, 255, 240],
"hotpink": [255, 105, 180],
"indianred": [205, 92, 92],
"indigo": [75, 0, 130],
"ivory": [255, 255, 240],
"khaki": [240, 230, 140],
"lavender": [230, 230, 250],
"lavenderblush": [255, 240, 245],
"lawngreen": [124, 252, 0],
"lemonchiffon": [255, 250, 205],
"lightblue": [173, 216, 230],
"lightcoral": [240, 128, 128],
"lightcyan": [224, 255, 255],
"lightgoldenrodyellow": [250, 250, 210],
"lightgray": [211, 211, 211],
"lightgreen": [144, 238, 144],
"lightgrey": [211, 211, 211],
"lightpink": [255, 182, 193],
"lightsalmon": [255, 160, 122],
"lightseagreen": [32, 178, 170],
"lightskyblue": [135, 206, 250],
"lightslategray": [119, 136, 153],
"lightslategrey": [119, 136, 153],
"lightsteelblue": [176, 196, 222],
"lightyellow": [255, 255, 224],
"lime": [0, 255, 0],
"limegreen": [50, 205, 50],
"linen": [250, 240, 230],
"magenta": [255, 0, 255],
"maroon": [128, 0, 0],
"mediumaquamarine": [102, 205, 170],
"mediumblue": [0, 0, 205],
"mediumorchid": [186, 85, 211],
"mediumpurple": [147, 112, 219],
"mediumseagreen": [60, 179, 113],
"mediumslateblue": [123, 104, 238],
"mediumspringgreen": [0, 250, 154],
"mediumturquoise": [72, 209, 204],
"mediumvioletred": [199, 21, 133],
"midnightblue": [25, 25, 112],
"mintcream": [245, 255, 250],
"mistyrose": [255, 228, 225],
"moccasin": [255, 228, 181],
"navajowhite": [255, 222, 173],
"navy": [0, 0, 128],
"oldlace": [253, 245, 230],
"olive": [128, 128, 0],
"olivedrab": [107, 142, 35],
"orange": [255, 165, 0],
"orangered": [255, 69, 0],
"orchid": [218, 112, 214],
"palegoldenrod": [238, 232, 170],
"palegreen": [152, 251, 152],
"paleturquoise": [175, 238, 238],
"palevioletred": [219, 112, 147],
"papayawhip": [255, 239, 213],
"peachpuff": [255, 218, 185],
"peru": [205, 133, 63],
"pink": [255, 192, 203],
"plum": [221, 160, 221],
"powderblue": [176, 224, 230],
"purple": [128, 0, 128],
"rebeccapurple": [102, 51, 153],
"red": [255, 0, 0],
"rosybrown": [188, 143, 143],
"royalblue": [65, 105, 225],
"saddlebrown": [139, 69, 19],
"salmon": [250, 128, 114],
"sandybrown": [244, 164, 96],
"seagreen": [46, 139, 87],
"seashell": [255, 245, 238],
"sienna": [160, 82, 45],
"silver": [192, 192, 192],
"skyblue": [135, 206, 235],
"slateblue": [106, 90, 205],
"slategray": [112, 128, 144],
"slategrey": [112, 128, 144],
"snow": [255, 250, 250],
"springgreen": [0, 255, 127],
"steelblue": [70, 130, 180],
"tan": [210, 180, 140],
"teal": [0, 128, 128],
"thistle": [216, 191, 216],
"tomato": [255, 99, 71],
"turquoise": [64, 224, 208],
"violet": [238, 130, 238],
"wheat": [245, 222, 179],
"white": [255, 255, 255],
"whitesmoke": [245, 245, 245],
"yellow": [255, 255, 0],
"yellowgreen": [154, 205, 50]
};
}
});
// node_modules/color-convert/conversions.js
var require_conversions = __commonJS({
"node_modules/color-convert/conversions.js"(exports2, module2) {
var cssKeywords = require_color_name();
var reverseKeywords = {};
for (const key of Object.keys(cssKeywords)) {
reverseKeywords[cssKeywords[key]] = key;
}
var convert = {
rgb: { channels: 3, labels: "rgb" },
hsl: { channels: 3, labels: "hsl" },
hsv: { channels: 3, labels: "hsv" },
hwb: { channels: 3, labels: "hwb" },
cmyk: { channels: 4, labels: "cmyk" },
xyz: { channels: 3, labels: "xyz" },
lab: { channels: 3, labels: "lab" },
lch: { channels: 3, labels: "lch" },
hex: { channels: 1, labels: ["hex"] },
keyword: { channels: 1, labels: ["keyword"] },
ansi16: { channels: 1, labels: ["ansi16"] },
ansi256: { channels: 1, labels: ["ansi256"] },
hcg: { channels: 3, labels: ["h", "c", "g"] },
apple: { channels: 3, labels: ["r16", "g16", "b16"] },
gray: { channels: 1, labels: ["gray"] }
};
module2.exports = convert;
for (const model of Object.keys(convert)) {
if (!("channels" in convert[model])) {
throw new Error("missing channels property: " + model);
}
if (!("labels" in convert[model])) {
throw new Error("missing channel labels property: " + model);
}
if (convert[model].labels.length !== convert[model].channels) {
throw new Error("channel and label counts mismatch: " + model);
}
const { channels, labels } = convert[model];
delete convert[model].channels;
delete convert[model].labels;
Object.defineProperty(convert[model], "channels", { value: channels });
Object.defineProperty(convert[model], "labels", { value: labels });
}
convert.rgb.hsl = function(rgb) {
const r = rgb[0] / 255;
const g = rgb[1] / 255;
const b = rgb[2] / 255;
const min = Math.min(r, g, b);
const max = Math.max(r, g, b);
const delta = max - min;
let h;
let s;
if (max === min) {
h = 0;
} else if (r === max) {
h = (g - b) / delta;
} else if (g === max) {
h = 2 + (b - r) / delta;
} else if (b === max) {
h = 4 + (r - g) / delta;
}
h = Math.min(h * 60, 360);
if (h < 0) {
h += 360;
}
const l = (min + max) / 2;
if (max === min) {
s = 0;
} else if (l <= 0.5) {
s = delta / (max + min);
} else {
s = delta / (2 - max - min);
}
return [h, s * 100, l * 100];
};
convert.rgb.hsv = function(rgb) {
let rdif;
let gdif;
let bdif;
let h;
let s;
const r = rgb[0] / 255;
const g = rgb[1] / 255;
const b = rgb[2] / 255;
const v = Math.max(r, g, b);
const diff = v - Math.min(r, g, b);
const diffc = function(c) {
return (v - c) / 6 / diff + 1 / 2;
};
if (diff === 0) {
h = 0;
s = 0;
} else {
s = diff / v;
rdif = diffc(r);
gdif = diffc(g);
bdif = diffc(b);
if (r === v) {
h = bdif - gdif;
} else if (g === v) {
h = 1 / 3 + rdif - bdif;
} else if (b === v) {
h = 2 / 3 + gdif - rdif;
}
if (h < 0) {
h += 1;
} else if (h > 1) {
h -= 1;
}
}
return [
h * 360,
s * 100,
v * 100
];
};
convert.rgb.hwb = function(rgb) {
const r = rgb[0];
const g = rgb[1];
let b = rgb[2];
const h = convert.rgb.hsl(rgb)[0];
const w = 1 / 255 * Math.min(r, Math.min(g, b));
b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
return [h, w * 100, b * 100];
};
convert.rgb.cmyk = function(rgb) {
const r = rgb[0] / 255;
const g = rgb[1] / 255;
const b = rgb[2] / 255;
const k = Math.min(1 - r, 1 - g, 1 - b);
const c = (1 - r - k) / (1 - k) || 0;
const m = (1 - g - k) / (1 - k) || 0;
const y = (1 - b - k) / (1 - k) || 0;
return [c * 100, m * 100, y * 100, k * 100];
};
function comparativeDistance(x, y) {
return (x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2 + (x[2] - y[2]) ** 2;
}
convert.rgb.keyword = function(rgb) {
const reversed = reverseKeywords[rgb];
if (reversed) {
return reversed;
}
let currentClosestDistance = Infinity;
let currentClosestKeyword;
for (const keyword of Object.keys(cssKeywords)) {
const value = cssKeywords[keyword];
const distance = comparativeDistance(rgb, value);
if (distance < currentClosestDistance) {
currentClosestDistance = distance;
currentClosestKeyword = keyword;
}
}
return currentClosestKeyword;
};
convert.keyword.rgb = function(keyword) {
return cssKeywords[keyword];
};
convert.rgb.xyz = function(rgb) {
let r = rgb[0] / 255;
let g = rgb[1] / 255;
let b = rgb[2] / 255;
r = r > 0.04045 ? ((r + 0.055) / 1.055) ** 2.4 : r / 12.92;
g = g > 0.04045 ? ((g + 0.055) / 1.055) ** 2.4 : g / 12.92;
b = b > 0.04045 ? ((b + 0.055) / 1.055) ** 2.4 : b / 12.92;
const x = r * 0.4124 + g * 0.3576 + b * 0.1805;
const y = r * 0.2126 + g * 0.7152 + b * 0.0722;
const z = r * 0.0193 + g * 0.1192 + b * 0.9505;
return [x * 100, y * 100, z * 100];
};
convert.rgb.lab = function(rgb) {
const xyz = convert.rgb.xyz(rgb);
let x = xyz[0];
let y = xyz[1];
let z = xyz[2];
x /= 95.047;
y /= 100;
z /= 108.883;
x = x > 8856e-6 ? x ** (1 / 3) : 7.787 * x + 16 / 116;
y = y > 8856e-6 ? y ** (1 / 3) : 7.787 * y + 16 / 116;
z = z > 8856e-6 ? z ** (1 / 3) : 7.787 * z + 16 / 116;
const l = 116 * y - 16;
const a = 500 * (x - y);
const b = 200 * (y - z);
return [l, a, b];
};
convert.hsl.rgb = function(hsl) {
const h = hsl[0] / 360;
const s = hsl[1] / 100;
const l = hsl[2] / 100;
let t2;
let t3;
let val;
if (s === 0) {
val = l * 255;
return [val, val, val];
}
if (l < 0.5) {
t2 = l * (1 + s);
} else {
t2 = l + s - l * s;
}
const t1 = 2 * l - t2;
const rgb = [0, 0, 0];
for (let i = 0; i < 3; i++) {
t3 = h + 1 / 3 * -(i - 1);
if (t3 < 0) {
t3++;
}
if (t3 > 1) {
t3--;
}
if (6 * t3 < 1) {
val = t1 + (t2 - t1) * 6 * t3;
} else if (2 * t3 < 1) {
val = t2;
} else if (3 * t3 < 2) {
val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
} else {
val = t1;
}
rgb[i] = val * 255;
}
return rgb;
};
convert.hsl.hsv = function(hsl) {
const h = hsl[0];
let s = hsl[1] / 100;
let l = hsl[2] / 100;
let smin = s;
const lmin = Math.max(l, 0.01);
l *= 2;
s *= l <= 1 ? l : 2 - l;
smin *= lmin <= 1 ? lmin : 2 - lmin;
const v = (l + s) / 2;
const sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s);
return [h, sv * 100, v * 100];
};
convert.hsv.rgb = function(hsv) {
const h = hsv[0] / 60;
const s = hsv[1] / 100;
let v = hsv[2] / 100;
const hi = Math.floor(h) % 6;
const f = h - Math.floor(h);
const p = 255 * v * (1 - s);
const q = 255 * v * (1 - s * f);
const t = 255 * v * (1 - s * (1 - f));
v *= 255;
switch (hi) {
case 0:
return [v, t, p];
case 1:
return [q, v, p];
case 2:
return [p, v, t];
case 3:
return [p, q, v];
case 4:
return [t, p, v];
case 5:
return [v, p, q];
}
};
convert.hsv.hsl = function(hsv) {
const h = hsv[0];
const s = hsv[1] / 100;
const v = hsv[2] / 100;
const vmin = Math.max(v, 0.01);
let sl;
let l;
l = (2 - s) * v;
const lmin = (2 - s) * vmin;
sl = s * vmin;
sl /= lmin <= 1 ? lmin : 2 - lmin;
sl = sl || 0;
l /= 2;
return [h, sl * 100, l * 100];
};
convert.hwb.rgb = function(hwb) {
const h = hwb[0] / 360;
let wh = hwb[1] / 100;
let bl = hwb[2] / 100;
const ratio = wh + bl;
let f;
if (ratio > 1) {
wh /= ratio;
bl /= ratio;
}
const i = Math.floor(6 * h);
const v = 1 - bl;
f = 6 * h - i;
if ((i & 1) !== 0) {
f = 1 - f;
}
const n = wh + f * (v - wh);
let r;
let g;
let b;
switch (i) {
default:
case 6:
case 0:
r = v;
g = n;
b = wh;
break;
case 1:
r = n;
g = v;
b = wh;
break;
case 2:
r = wh;
g = v;
b = n;
break;
case 3:
r = wh;
g = n;
b = v;
break;
case 4:
r = n;
g = wh;
b = v;
break;
case 5:
r = v;
g = wh;
b = n;
break;
}
return [r * 255, g * 255, b * 255];
};
convert.cmyk.rgb = function(cmyk) {
const c = cmyk[0] / 100;
const m = cmyk[1] / 100;
const y = cmyk[2] / 100;
const k = cmyk[3] / 100;
const r = 1 - Math.min(1, c * (1 - k) + k);
const g = 1 - Math.min(1, m * (1 - k) + k);
const b = 1 - Math.min(1, y * (1 - k) + k);
return [r * 255, g * 255, b * 255];
};
convert.xyz.rgb = function(xyz) {
const x = xyz[0] / 100;
const y = xyz[1] / 100;
const z = xyz[2] / 100;
let r;
let g;
let b;
r = x * 3.2406 + y * -1.5372 + z * -0.4986;
g = x * -0.9689 + y * 1.8758 + z * 0.0415;
b = x * 0.0557 + y * -0.204 + z * 1.057;
r = r > 31308e-7 ? 1.055 * r ** (1 / 2.4) - 0.055 : r * 12.92;
g = g > 31308e-7 ? 1.055 * g ** (1 / 2.4) - 0.055 : g * 12.92;
b = b > 31308e-7 ? 1.055 * b ** (1 / 2.4) - 0.055 : b * 12.92;
r = Math.min(Math.max(0, r), 1);
g = Math.min(Math.max(0, g), 1);
b = Math.min(Math.max(0, b), 1);
return [r * 255, g * 255, b * 255];
};
convert.xyz.lab = function(xyz) {
let x = xyz[0];
let y = xyz[1];
let z = xyz[2];
x /= 95.047;
y /= 100;
z /= 108.883;
x = x > 8856e-6 ? x ** (1 / 3) : 7.787 * x + 16 / 116;
y = y > 8856e-6 ? y ** (1 / 3) : 7.787 * y + 16 / 116;
z = z > 8856e-6 ? z ** (1 / 3) : 7.787 * z + 16 / 116;
const l = 116 * y - 16;
const a = 500 * (x - y);
const b = 200 * (y - z);
return [l, a, b];
};
convert.lab.xyz = function(lab) {
const l = lab[0];
const a = lab[1];
const b = lab[2];
let x;
let y;
let z;
y = (l + 16) / 116;
x = a / 500 + y;
z = y - b / 200;
const y2 = y ** 3;
const x2 = x ** 3;
const z2 = z ** 3;
y = y2 > 8856e-6 ? y2 : (y - 16 / 116) / 7.787;
x = x2 > 8856e-6 ? x2 : (x - 16 / 116) / 7.787;
z = z2 > 8856e-6 ? z2 : (z - 16 / 116) / 7.787;
x *= 95.047;
y *= 100;
z *= 108.883;
return [x, y, z];
};
convert.lab.lch = function(lab) {
const l = lab[0];
const a = lab[1];
const b = lab[2];
let h;
const hr = Math.atan2(b, a);
h = hr * 360 / 2 / Math.PI;
if (h < 0) {
h += 360;
}
const c = Math.sqrt(a * a + b * b);
return [l, c, h];
};
convert.lch.lab = function(lch) {
const l = lch[0];
const c = lch[1];
const h = lch[2];
const hr = h / 360 * 2 * Math.PI;
const a = c * Math.cos(hr);
const b = c * Math.sin(hr);
return [l, a, b];
};
convert.rgb.ansi16 = function(args, saturation = null) {
const [r, g, b] = args;
let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation;
value = Math.round(value / 50);
if (value === 0) {
return 30;
}
let ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255));
if (value === 2) {
ansi += 60;
}
return ansi;
};
convert.hsv.ansi16 = function(args) {
return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
};
convert.rgb.ansi256 = function(args) {
const r = args[0];
const g = args[1];
const b = args[2];
if (r === g && g === b) {
if (r < 8) {
return 16;
}
if (r > 248) {
return 231;
}
return Math.round((r - 8) / 247 * 24) + 232;
}
const ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5);
return ansi;
};
convert.ansi16.rgb = function(args) {
let color = args % 10;
if (color === 0 || color === 7) {
if (args > 50) {
color += 3.5;
}
color = color / 10.5 * 255;
return [color, color, color];
}
const mult = (~~(args > 50) + 1) * 0.5;
const r = (color & 1) * mult * 255;
const g = (color >> 1 & 1) * mult * 255;
const b = (color >> 2 & 1) * mult * 255;
return [r, g, b];
};
convert.ansi256.rgb = function(args) {
if (args >= 232) {
const c = (args - 232) * 10 + 8;
return [c, c, c];
}
args -= 16;
let rem;
const r = Math.floor(args / 36) / 5 * 255;
const g = Math.floor((rem = args % 36) / 6) / 5 * 255;
const b = rem % 6 / 5 * 255;
return [r, g, b];
};
convert.rgb.hex = function(args) {
const integer = ((Math.round(args[0]) & 255) << 16) + ((Math.round(args[1]) & 255) << 8) + (Math.round(args[2]) & 255);
const string = integer.toString(16).toUpperCase();
return "000000".substring(string.length) + string;
};
convert.hex.rgb = function(args) {
const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
if (!match) {
return [0, 0, 0];
}
let colorString = match[0];
if (match[0].length === 3) {
colorString = colorString.split("").map((char) => {
return char + char;
}).join("");
}
const integer = parseInt(colorString, 16);
const r = integer >> 16 & 255;
const g = integer >> 8 & 255;
const b = integer & 255;
return [r, g, b];
};
convert.rgb.hcg = function(rgb) {
const r = rgb[0] / 255;
const g = rgb[1] / 255;
const b = rgb[2] / 255;
const max = Math.max(Math.max(r, g), b);
const min = Math.min(Math.min(r, g), b);
const chroma = max - min;
let grayscale;
let hue;
if (chroma < 1) {
grayscale = min / (1 - chroma);
} else {
grayscale = 0;
}
if (chroma <= 0) {
hue = 0;
} else if (max === r) {
hue = (g - b) / chroma % 6;
} else if (max === g) {
hue = 2 + (b - r) / chroma;
} else {
hue = 4 + (r - g) / chroma;
}
hue /= 6;
hue %= 1;
return [hue * 360, chroma * 100, grayscale * 100];
};
convert.hsl.hcg = function(hsl) {
const s = hsl[1] / 100;
const l = hsl[2] / 100;
const c = l < 0.5 ? 2 * s * l : 2 * s * (1 - l);
let f = 0;
if (c < 1) {
f = (l - 0.5 * c) / (1 - c);
}
return [hsl[0], c * 100, f * 100];
};
convert.hsv.hcg = function(hsv) {
const s = hsv[1] / 100;
const v = hsv[2] / 100;
const c = s * v;
let f = 0;
if (c < 1) {
f = (v - c) / (1 - c);
}
return [hsv[0], c * 100, f * 100];
};
convert.hcg.rgb = function(hcg) {
const h = hcg[0] / 360;
const c = hcg[1] / 100;
const g = hcg[2] / 100;
if (c === 0) {
return [g * 255, g * 255, g * 255];
}
const pure = [0, 0, 0];
const hi = h % 1 * 6;
const v = hi % 1;
const w = 1 - v;
let mg = 0;
switch (Math.floor(hi)) {
case 0:
pure[0] = 1;
pure[1] = v;
pure[2] = 0;
break;
case 1:
pure[0] = w;
pure[1] = 1;
pure[2] = 0;
break;
case 2:
pure[0] = 0;
pure[1] = 1;
pure[2] = v;
break;
case 3:
pure[0] = 0;
pure[1] = w;
pure[2] = 1;
break;
case 4:
pure[0] = v;
pure[1] = 0;
pure[2] = 1;
break;
default:
pure[0] = 1;
pure[1] = 0;
pure[2] = w;
}
mg = (1 - c) * g;
return [
(c * pure[0] + mg) * 255,
(c * pure[1] + mg) * 255,
(c * pure[2] + mg) * 255
];
};
convert.hcg.hsv = function(hcg) {
const c = hcg[1] / 100;
const g = hcg[2] / 100;
const v = c + g * (1 - c);
let f = 0;
if (v > 0) {
f = c / v;
}
return [hcg[0], f * 100, v * 100];
};
convert.hcg.hsl = function(hcg) {
const c = hcg[1] / 100;
const g = hcg[2] / 100;
const l = g * (1 - c) + 0.5 * c;
let s = 0;
if (l > 0 && l < 0.5) {
s = c / (2 * l);
} else if (l >= 0.5 && l < 1) {
s = c / (2 * (1 - l));
}
return [hcg[0], s * 100, l * 100];
};
convert.hcg.hwb = function(hcg) {
const c = hcg[1] / 100;
const g = hcg[2] / 100;
const v = c + g * (1 - c);
return [hcg[0], (v - c) * 100, (1 - v) * 100];
};
convert.hwb.hcg = function(hwb) {
const w = hwb[1] / 100;
const b = hwb[2] / 100;
const v = 1 - b;
const c = v - w;
let g = 0;
if (c < 1) {
g = (v - c) / (1 - c);
}
return [hwb[0], c * 100, g * 100];
};
convert.apple.rgb = function(apple) {
return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255];
};
convert.rgb.apple = function(rgb) {
return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535];
};
convert.gray.rgb = function(args) {
return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
};
convert.gray.hsl = function(args) {
return [0, 0, args[0]];
};
convert.gray.hsv = convert.gray.hsl;
convert.gray.hwb = function(gray) {
return [0, 100, gray[0]];
};
convert.gray.cmyk = function(gray) {
return [0, 0, 0, gray[0]];
};
convert.gray.lab = function(gray) {
return [gray[0], 0, 0];
};
convert.gray.hex = function(gray) {
const val = Math.round(gray[0] / 100 * 255) & 255;
const integer = (val << 16) + (val << 8) + val;
const string = integer.toString(16).toUpperCase();
return "000000".substring(string.length) + string;
};
convert.rgb.gray = function(rgb) {
const val = (rgb[0] + rgb[1] + rgb[2]) / 3;
return [val / 255 * 100];
};
}
});
// node_modules/color-convert/route.js
var require_route = __commonJS({
"node_modules/color-convert/route.js"(exports2, module2) {
var conversions2 = require_conversions();
function buildGraph() {
const graph = {};
const models = Object.keys(conversions2);
for (let len = models.length, i = 0; i < len; i++) {
graph[models[i]] = {
// http://jsperf.com/1-vs-infinity
// micro-opt, but this is simple.
distance: -1,
parent: null
};
}
return graph;
}
function deriveBFS(fromModel) {
const graph = buildGraph();
const queue = [fromModel];
graph[fromModel].distance = 0;
while (queue.length) {
const current2 = queue.pop();
const adjacents = Object.keys(conversions2[current2]);
for (let len = adjacents.length, i = 0; i < len; i++) {
const adjacent = adjacents[i];
const node = graph[adjacent];
if (node.distance === -1) {
node.distance = graph[current2].distance + 1;
node.parent = current2;
queue.unshift(adjacent);
}
}
}
return graph;
}
function link(from, to) {
return function(args) {
return to(from(args));
};
}
function wrapConversion(toModel, graph) {
const path4 = [graph[toModel].parent, toModel];
let fn = conversions2[graph[toModel].parent][toModel];
let cur = graph[toModel].parent;
while (graph[cur].parent) {
path4.unshift(graph[cur].parent);
fn = link(conversions2[graph[cur].parent][cur], fn);
cur = graph[cur].parent;
}
fn.conversion = path4;
return fn;
}
module2.exports = function(fromModel) {
const graph = deriveBFS(fromModel);
const conversion = {};
const models = Object.keys(graph);
for (let len = models.length, i = 0; i < len; i++) {
const toModel = models[i];
const node = graph[toModel];
if (node.parent === null) {
continue;
}
conversion[toModel] = wrapConversion(toModel, graph);
}
return conversion;
};
}
});
// node_modules/color-convert/index.js
var require_color_convert = __commonJS({
"node_modules/color-convert/index.js"(exports2, module2) {
var conversions2 = require_conversions();
var route2 = require_route();
var convert = {};
var models = Object.keys(conversions2);
function wrapRaw(fn) {
const wrappedFn = function(...args) {
const arg0 = args[0];
if (arg0 === void 0 || arg0 === null) {
return arg0;
}
if (arg0.length > 1) {
args = arg0;
}
return fn(args);
};
if ("conversion" in fn) {
wrappedFn.conversion = fn.conversion;
}
return wrappedFn;
}
function wrapRounded(fn) {
const wrappedFn = function(...args) {
const arg0 = args[0];
if (arg0 === void 0 || arg0 === null) {
return arg0;
}
if (arg0.length > 1) {
args = arg0;
}
const result = fn(args);
if (typeof result === "object") {
for (let len = result.length, i = 0; i < len; i++) {
result[i] = Math.round(result[i]);
}
}
return result;
};
if ("conversion" in fn) {
wrappedFn.conversion = fn.conversion;
}
return wrappedFn;
}
models.forEach((fromModel) => {
convert[fromModel] = {};
Object.defineProperty(convert[fromModel], "channels", { value: conversions2[fromModel].channels });
Object.defineProperty(convert[fromModel], "labels", { value: conversions2[fromModel].labels });
const routes = route2(fromModel);
const routeModels = Object.keys(routes);
routeModels.forEach((toModel) => {
const fn = routes[toModel];
convert[fromModel][toModel] = wrapRounded(fn);
convert[fromModel][toModel].raw = wrapRaw(fn);
});
});
module2.exports = convert;
}
});
// node_modules/ansi-styles/index.js
var require_ansi_styles = __commonJS({
"node_modules/ansi-styles/index.js"(exports2, module2) {
"use strict";
var wrapAnsi16 = (fn, offset) => (...args) => {
const code = fn(...args);
return `\x1B[${code + offset}m`;
};
var wrapAnsi256 = (fn, offset) => (...args) => {
const code = fn(...args);
return `\x1B[${38 + offset};5;${code}m`;
};
var wrapAnsi16m = (fn, offset) => (...args) => {
const rgb = fn(...args);
return `\x1B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
};
var ansi2ansi = (n) => n;
var rgb2rgb = (r, g, b) => [r, g, b];
var setLazyProperty = (object, property, get3) => {
Object.defineProperty(object, property, {
get: () => {
const value = get3();
Object.defineProperty(object, property, {
value,
enumerable: true,
configurable: true
});
return value;
},
enumerable: true,
configurable: true
});
};
var colorConvert2;
var makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => {
if (colorConvert2 === void 0) {
colorConvert2 = require_color_convert();
}
const offset = isBackground ? 10 : 0;
const styles = {};
for (const [sourceSpace, suite] of Object.entries(colorConvert2)) {
const name = sourceSpace === "ansi16" ? "ansi" : sourceSpace;
if (sourceSpace === targetSpace) {
styles[name] = wrap(identity, offset);
} else if (typeof suite === "object") {
styles[name] = wrap(suite[targetSpace], offset);
}
}
return styles;
};
function assembleStyles() {
const codes = /* @__PURE__ */ new Map();
const styles = {
modifier: {
reset: [0, 0],
// 21 isn't widely supported and 22 does the same thing
bold: [1, 22],
dim: [2, 22],
italic: [3, 23],
underline: [4, 24],
inverse: [7, 27],
hidden: [8, 28],
strikethrough: [9, 29]
},
color: {
black: [30, 39],
red: [31, 39],
green: [32, 39],
yellow: [33, 39],
blue: [34, 39],
magenta: [35, 39],
cyan: [36, 39],
white: [37, 39],
// Bright color
blackBright: [90, 39],
redBright: [91, 39],
greenBright: [92, 39],
yellowBright: [93, 39],
blueBright: [94, 39],
magentaBright: [95, 39],
cyanBright: [96, 39],
whiteBright: [97, 39]
},
bgColor: {
bgBlack: [40, 49],
bgRed: [41, 49],
bgGreen: [42, 49],
bgYellow: [43, 49],
bgBlue: [44, 49],
bgMagenta: [45, 49],
bgCyan: [46, 49],
bgWhite: [47, 49],
// Bright color
bgBlackBright: [100, 49],
bgRedBright: [101, 49],
bgGreenBright: [102, 49],
bgYellowBright: [103, 49],
bgBlueBright: [104, 49],
bgMagentaBright: [105, 49],
bgCyanBright: [106, 49],
bgWhiteBright: [107, 49]
}
};
styles.color.gray = styles.color.blackBright;
styles.bgColor.bgGray = styles.bgColor.bgBlackBright;
styles.color.grey = styles.color.blackBright;
styles.bgColor.bgGrey = styles.bgColor.bgBlackBright;
for (const [groupName, group] of Object.entries(styles)) {
for (const [styleName, style] of Object.entries(group)) {
styles[styleName] = {
open: `\x1B[${style[0]}m`,
close: `\x1B[${style[1]}m`
};
group[styleName] = styles[styleName];
codes.set(style[0], style[1]);
}
Object.defineProperty(styles, groupName, {
value: group,
enumerable: false
});
}
Object.defineProperty(styles, "codes", {
value: codes,
enumerable: false
});
styles.color.close = "\x1B[39m";
styles.bgColor.close = "\x1B[49m";
setLazyProperty(styles.color, "ansi", () => makeDynamicStyles(wrapAnsi16, "ansi16", ansi2ansi, false));
setLazyProperty(styles.color, "ansi256", () => makeDynamicStyles(wrapAnsi256, "ansi256", ansi2ansi, false));
setLazyProperty(styles.color, "ansi16m", () => makeDynamicStyles(wrapAnsi16m, "rgb", rgb2rgb, false));
setLazyProperty(styles.bgColor, "ansi", () => makeDynamicStyles(wrapAnsi16, "ansi16", ansi2ansi, true));
setLazyProperty(styles.bgColor, "ansi256", () => makeDynamicStyles(wrapAnsi256, "ansi256", ansi2ansi, true));
setLazyProperty(styles.bgColor, "ansi16m", () => makeDynamicStyles(wrapAnsi16m, "rgb", rgb2rgb, true));
return styles;
}
Object.defineProperty(module2, "exports", {
enumerable: true,
get: assembleStyles
});
}
});
// node_modules/has-flag/index.js
var require_has_flag = __commonJS({
"node_modules/has-flag/index.js"(exports2, module2) {
"use strict";
module2.exports = (flag, argv = process.argv) => {
const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
const position = argv.indexOf(prefix + flag);
const terminatorPosition = argv.indexOf("--");
return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
};
}
});
// node_modules/supports-color/index.js
var require_supports_color = __commonJS({
"node_modules/supports-color/index.js"(exports2, module2) {
"use strict";
var os2 = require("os");
var tty = require("tty");
var hasFlag = require_has_flag();
var { env } = process;
var forceColor;
if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
forceColor = 0;
} else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
forceColor = 1;
}
if ("FORCE_COLOR" in env) {
if (env.FORCE_COLOR === "true") {
forceColor = 1;
} else if (env.FORCE_COLOR === "false") {
forceColor = 0;
} else {
forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);
}
}
function translateLevel(level) {
if (level === 0) {
return false;
}
return {
level,
hasBasic: true,
has256: level >= 2,
has16m: level >= 3
};
}
function supportsColor(haveStream, streamIsTTY) {
if (forceColor === 0) {
return 0;
}
if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
return 3;
}
if (hasFlag("color=256")) {
return 2;
}
if (haveStream && !streamIsTTY && forceColor === void 0) {
return 0;
}
const min = forceColor || 0;
if (env.TERM === "dumb") {
return min;
}
if (process.platform === "win32") {
const osRelease = os2.release().split(".");
if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
return Number(osRelease[2]) >= 14931 ? 3 : 2;
}
return 1;
}
if ("CI" in env) {
if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
return 1;
}
return min;
}
if ("TEAMCITY_VERSION" in env) {
return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
}
if (env.COLORTERM === "truecolor") {
return 3;
}
if ("TERM_PROGRAM" in env) {
const version = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
switch (env.TERM_PROGRAM) {
case "iTerm.app":
return version >= 3 ? 3 : 2;
case "Apple_Terminal":
return 2;
}
}
if (/-256(color)?$/i.test(env.TERM)) {
return 2;
}
if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
return 1;
}
if ("COLORTERM" in env) {
return 1;
}
return min;
}
function getSupportLevel(stream) {
const level = supportsColor(stream, stream && stream.isTTY);
return translateLevel(level);
}
module2.exports = {
supportsColor: getSupportLevel,
stdout: translateLevel(supportsColor(true, tty.isatty(1))),
stderr: translateLevel(supportsColor(true, tty.isatty(2)))
};
}
});
// node_modules/chalk/source/util.js
var require_util = __commonJS({
"node_modules/chalk/source/util.js"(exports2, module2) {
"use strict";
var stringReplaceAll = (string, substring, replacer) => {
let index = string.indexOf(substring);
if (index === -1) {
return string;
}
const substringLength = substring.length;
let endIndex = 0;
let returnValue = "";
do {
returnValue += string.substr(endIndex, index - endIndex) + substring + replacer;
endIndex = index + substringLength;
index = string.indexOf(substring, endIndex);
} while (index !== -1);
returnValue += string.substr(endIndex);
return returnValue;
};
var stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => {
let endIndex = 0;
let returnValue = "";
do {
const gotCR = string[index - 1] === "\r";
returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
endIndex = index + 1;
index = string.indexOf("\n", endIndex);
} while (index !== -1);
returnValue += string.substr(endIndex);
return returnValue;
};
module2.exports = {
stringReplaceAll,
stringEncaseCRLFWithFirstIndex
};
}
});
// node_modules/chalk/source/templates.js
var require_templates = __commonJS({
"node_modules/chalk/source/templates.js"(exports2, module2) {
"use strict";
var TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
var STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
var STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
var ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi;
var ESCAPES = /* @__PURE__ */ new Map([
["n", "\n"],
["r", "\r"],
["t", " "],
["b", "\b"],
["f", "\f"],
["v", "\v"],
["0", "\0"],
["\\", "\\"],
["e", "\x1B"],
["a", "\x07"]
]);
function unescape(c) {
const u = c[0] === "u";
const bracket = c[1] === "{";
if (u && !bracket && c.length === 5 || c[0] === "x" && c.length === 3) {
return String.fromCharCode(parseInt(c.slice(1), 16));
}
if (u && bracket) {
return String.fromCodePoint(parseInt(c.slice(2, -1), 16));
}
return ESCAPES.get(c) || c;
}
function parseArguments(name, arguments_) {
const results = [];
const chunks = arguments_.trim().split(/\s*,\s*/g);
let matches;
for (const chunk of chunks) {
const number = Number(chunk);
if (!Number.isNaN(number)) {
results.push(number);
} else if (matches = chunk.match(STRING_REGEX)) {
results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape(escape) : character));
} else {
throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
}
}
return results;
}
function parseStyle(style) {
STYLE_REGEX.lastIndex = 0;
const results = [];
let matches;
while ((matches = STYLE_REGEX.exec(style)) !== null) {
const name = matches[1];
if (matches[2]) {
const args = parseArguments(name, matches[2]);
results.push([name].concat(args));
} else {
results.push([name]);
}
}
return results;
}
function buildStyle(chalk2, styles) {
const enabled = {};
for (const layer of styles) {
for (const style of layer.styles) {
enabled[style[0]] = layer.inverse ? null : style.slice(1);
}
}
let current2 = chalk2;
for (const [styleName, styles2] of Object.entries(enabled)) {
if (!Array.isArray(styles2)) {
continue;
}
if (!(styleName in current2)) {
throw new Error(`Unknown Chalk style: ${styleName}`);
}
current2 = styles2.length > 0 ? current2[styleName](...styles2) : current2[styleName];
}
return current2;
}
module2.exports = (chalk2, temporary) => {
const styles = [];
const chunks = [];
let chunk = [];
temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => {
if (escapeCharacter) {
chunk.push(unescape(escapeCharacter));
} else if (style) {
const string = chunk.join("");
chunk = [];
chunks.push(styles.length === 0 ? string : buildStyle(chalk2, styles)(string));
styles.push({ inverse, styles: parseStyle(style) });
} else if (close) {
if (styles.length === 0) {
throw new Error("Found extraneous } in Chalk template literal");
}
chunks.push(buildStyle(chalk2, styles)(chunk.join("")));
chunk = [];
styles.pop();
} else {
chunk.push(character);
}
});
chunks.push(chunk.join(""));
if (styles.length > 0) {
const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? "" : "s"} (\`}\`)`;
throw new Error(errMessage);
}
return chunks.join("");
};
}
});
// node_modules/chalk/source/index.js
var require_source = __commonJS({
"node_modules/chalk/source/index.js"(exports2, module2) {
"use strict";
var ansiStyles2 = require_ansi_styles();
var { stdout: stdoutColor, stderr: stderrColor } = require_supports_color();
var {
stringReplaceAll,
stringEncaseCRLFWithFirstIndex
} = require_util();
var { isArray: isArray2 } = Array;
var levelMapping = [
"ansi",
"ansi",
"ansi256",
"ansi16m"
];
var styles = /* @__PURE__ */ Object.create(null);
var applyOptions = (object, options = {}) => {
if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
throw new Error("The `level` option should be an integer from 0 to 3");
}
const colorLevel = stdoutColor ? stdoutColor.level : 0;
object.level = options.level === void 0 ? colorLevel : options.level;
};
var ChalkClass = class {
constructor(options) {
return chalkFactory(options);
}
};
var chalkFactory = (options) => {
const chalk3 = {};
applyOptions(chalk3, options);
chalk3.template = (...arguments_) => chalkTag(chalk3.template, ...arguments_);
Object.setPrototypeOf(chalk3, Chalk.prototype);
Object.setPrototypeOf(chalk3.template, chalk3);
chalk3.template.constructor = () => {
throw new Error("`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.");
};
chalk3.template.Instance = ChalkClass;
return chalk3.template;
};
function Chalk(options) {
return chalkFactory(options);
}
for (const [styleName, style] of Object.entries(ansiStyles2)) {
styles[styleName] = {
get() {
const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty);
Object.defineProperty(this, styleName, { value: builder });
return builder;
}
};
}
styles.visible = {
get() {
const builder = createBuilder(this, this._styler, true);
Object.defineProperty(this, "visible", { value: builder });
return builder;
}
};
var usedModels = ["rgb", "hex", "keyword", "hsl", "hsv", "hwb", "ansi", "ansi256"];
for (const model of usedModels) {
styles[model] = {
get() {
const { level } = this;
return function(...arguments_) {
const styler = createStyler(ansiStyles2.color[levelMapping[level]][model](...arguments_), ansiStyles2.color.close, this._styler);
return createBuilder(this, styler, this._isEmpty);
};
}
};
}
for (const model of usedModels) {
const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
styles[bgModel] = {
get() {
const { level } = this;
return function(...arguments_) {
const styler = createStyler(ansiStyles2.bgColor[levelMapping[level]][model](...arguments_), ansiStyles2.bgColor.close, this._styler);
return createBuilder(this, styler, this._isEmpty);
};
}
};
}
var proto = Object.defineProperties(() => {
}, {
...styles,
level: {
enumerable: true,
get() {
return this._generator.level;
},
set(level) {
this._generator.level = level;
}
}
});
var createStyler = (open, close, parent) => {
let openAll;
let closeAll;
if (parent === void 0) {
openAll = open;
closeAll = close;
} else {
openAll = parent.openAll + open;
closeAll = close + parent.closeAll;
}
return {
open,
close,
openAll,
closeAll,
parent
};
};
var createBuilder = (self, _styler, _isEmpty) => {
const builder = (...arguments_) => {
if (isArray2(arguments_[0]) && isArray2(arguments_[0].raw)) {
return applyStyle(builder, chalkTag(builder, ...arguments_));
}
return applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
};
Object.setPrototypeOf(builder, proto);
builder._generator = self;
builder._styler = _styler;
builder._isEmpty = _isEmpty;
return builder;
};
var applyStyle = (self, string) => {
if (self.level <= 0 || !string) {
return self._isEmpty ? "" : string;
}
let styler = self._styler;
if (styler === void 0) {
return string;
}
const { openAll, closeAll } = styler;
if (string.indexOf("\x1B") !== -1) {
while (styler !== void 0) {
string = stringReplaceAll(string, styler.close, styler.open);
styler = styler.parent;
}
}
const lfIndex = string.indexOf("\n");
if (lfIndex !== -1) {
string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
}
return openAll + string + closeAll;
};
var template;
var chalkTag = (chalk3, ...strings) => {
const [firstString] = strings;
if (!isArray2(firstString) || !isArray2(firstString.raw)) {
return strings.join(" ");
}
const arguments_ = strings.slice(1);
const parts = [firstString.raw[0]];
for (let i = 1; i < firstString.length; i++) {
parts.push(
String(arguments_[i - 1]).replace(/[{}\\]/g, "\\$&"),
String(firstString.raw[i])
);
}
if (template === void 0) {
template = require_templates();
}
return template(chalk3, parts.join(""));
};
Object.defineProperties(Chalk.prototype, styles);
var chalk2 = Chalk();
chalk2.supportsColor = stdoutColor;
chalk2.stderr = Chalk({ level: stderrColor ? stderrColor.level : 0 });
chalk2.stderr.supportsColor = stderrColor;
module2.exports = chalk2;
}
});
// node_modules/@lmstudio/lms-isomorphic/dist/cjs/index/generateRandomBase64.js
var require_generateRandomBase64 = __commonJS({
"node_modules/@lmstudio/lms-isomorphic/dist/cjs/index/generateRandomBase64.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.generateRandomBase64 = generateRandomBase642;
var crypto_1 = require("crypto");
function generateRandomBase642(bytesOfRandomness = 18) {
const randomBytesBuffer = (0, crypto_1.randomBytes)(bytesOfRandomness);
return randomBytesBuffer.toString("base64");
}
}
});
// node_modules/@lmstudio/lms-isomorphic/dist/cjs/index/readFileAsBase64.js
var require_readFileAsBase64 = __commonJS({
"node_modules/@lmstudio/lms-isomorphic/dist/cjs/index/readFileAsBase64.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.readFileAsBase64 = readFileAsBase642;
var promises_1 = require("fs/promises");
async function readFileAsBase642(path4) {
return { success: true, base64: await (0, promises_1.readFile)(path4, "base64") };
}
}
});
// node_modules/@lmstudio/lms-isomorphic/dist/cjs/index/terminalSize.js
var require_terminalSize = __commonJS({
"node_modules/@lmstudio/lms-isomorphic/dist/cjs/index/terminalSize.js"(exports2) {
"use strict";
var __importDefault = exports2 && exports2.__importDefault || function(mod) {
return mod && mod.__esModule ? mod : { "default": mod };
};
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.terminalSize = terminalSize2;
var child_process_1 = require("child_process");
var fs_1 = __importDefault(require("fs"));
var process_1 = __importDefault(require("process"));
var tty_1 = __importDefault(require("tty"));
var defaultColumns = 80;
var defaultRows = 24;
var exec = (command, arguments_, { shell, env } = {}) => (0, child_process_1.execFileSync)(command, arguments_, {
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
timeout: 500,
shell,
env
}).trim();
var create = (columns, rows) => ({
columns: Number.parseInt(columns, 10),
rows: Number.parseInt(rows, 10)
});
var createIfNotDefault = (maybeColumns, maybeRows) => {
const { columns, rows } = create(maybeColumns, maybeRows);
if (Number.isNaN(columns) || Number.isNaN(rows)) {
return;
}
if (columns === defaultColumns && rows === defaultRows) {
return;
}
return { columns, rows };
};
function terminalSize2() {
const { env, stdout, stderr } = process_1.default;
if (stdout?.columns && stdout?.rows) {
return create(stdout.columns, stdout.rows);
}
if (stderr?.columns && stderr?.rows) {
return create(stderr.columns, stderr.rows);
}
if (env.COLUMNS && env.LINES) {
return create(env.COLUMNS, env.LINES);
}
const fallback = {
columns: defaultColumns,
rows: defaultRows
};
if (process_1.default.platform === "win32") {
return tput() ?? fallback;
}
if (process_1.default.platform === "darwin") {
return devTty() ?? tput() ?? fallback;
}
return devTty() ?? tput() ?? resize() ?? fallback;
}
var devTty = () => {
try {
const flags = process_1.default.platform === "darwin" ? fs_1.default.constants.O_EVTONLY | fs_1.default.constants.O_NONBLOCK : fs_1.default.constants.O_NONBLOCK;
const { columns, rows } = tty_1.default.WriteStream(fs_1.default.openSync("/dev/tty", flags));
return { columns, rows };
} catch {
}
};
var tput = () => {
try {
const columns = exec("tput", ["cols"], { env: { TERM: "dumb", ...process_1.default.env } });
const rows = exec("tput", ["lines"], { env: { TERM: "dumb", ...process_1.default.env } });
if (columns && rows) {
return createIfNotDefault(columns, rows);
}
} catch {
}
};
var resize = () => {
try {
const size = exec("resize", ["-u"]).match(/\d+/g);
if (size.length === 2) {
return createIfNotDefault(size[0], size[1]);
}
} catch {
}
};
}
});
// node_modules/ws/lib/constants.js
var require_constants = __commonJS({
"node_modules/ws/lib/constants.js"(exports2, module2) {
"use strict";
var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
var hasBlob = typeof Blob !== "undefined";
if (hasBlob) BINARY_TYPES.push("blob");
module2.exports = {
BINARY_TYPES,
CLOSE_TIMEOUT: 3e4,
EMPTY_BUFFER: Buffer.alloc(0),
GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
hasBlob,
kForOnEventAttribute: /* @__PURE__ */ Symbol("kIsForOnEventAttribute"),
kListener: /* @__PURE__ */ Symbol("kListener"),
kStatusCode: /* @__PURE__ */ Symbol("status-code"),
kWebSocket: /* @__PURE__ */ Symbol("websocket"),
NOOP: () => {
}
};
}
});
// node_modules/ws/lib/buffer-util.js
var require_buffer_util = __commonJS({
"node_modules/ws/lib/buffer-util.js"(exports2, module2) {
"use strict";
var { EMPTY_BUFFER } = require_constants();
var FastBuffer = Buffer[Symbol.species];
function concat(list, totalLength) {
if (list.length === 0) return EMPTY_BUFFER;
if (list.length === 1) return list[0];
const target = Buffer.allocUnsafe(totalLength);
let offset = 0;
for (let i = 0; i < list.length; i++) {
const buf = list[i];
target.set(buf, offset);
offset += buf.length;
}
if (offset < totalLength) {
return new FastBuffer(target.buffer, target.byteOffset, offset);
}
return target;
}
function _mask(source, mask, output, offset, length) {
for (let i = 0; i < length; i++) {
output[offset + i] = source[i] ^ mask[i & 3];
}
}
function _unmask(buffer, mask) {
for (let i = 0; i < buffer.length; i++) {
buffer[i] ^= mask[i & 3];
}
}
function toArrayBuffer(buf) {
if (buf.length === buf.buffer.byteLength) {
return buf.buffer;
}
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
}
function toBuffer(data) {
toBuffer.readOnly = true;
if (Buffer.isBuffer(data)) return data;
let buf;
if (data instanceof ArrayBuffer) {
buf = new FastBuffer(data);
} else if (ArrayBuffer.isView(data)) {
buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
} else {
buf = Buffer.from(data);
toBuffer.readOnly = false;
}
return buf;
}
module2.exports = {
concat,
mask: _mask,
toArrayBuffer,
toBuffer,
unmask: _unmask
};
if (!process.env.WS_NO_BUFFER_UTIL) {
try {
const bufferUtil = require("bufferutil");
module2.exports.mask = function(source, mask, output, offset, length) {
if (length < 48) _mask(source, mask, output, offset, length);
else bufferUtil.mask(source, mask, output, offset, length);
};
module2.exports.unmask = function(buffer, mask) {
if (buffer.length < 32) _unmask(buffer, mask);
else bufferUtil.unmask(buffer, mask);
};
} catch (e) {
}
}
}
});
// node_modules/ws/lib/limiter.js
var require_limiter = __commonJS({
"node_modules/ws/lib/limiter.js"(exports2, module2) {
"use strict";
var kDone = /* @__PURE__ */ Symbol("kDone");
var kRun = /* @__PURE__ */ Symbol("kRun");
var Limiter = class {
/**
* Creates a new `Limiter`.
*
* @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
* to run concurrently
*/
constructor(concurrency) {
this[kDone] = () => {
this.pending--;
this[kRun]();
};
this.concurrency = concurrency || Infinity;
this.jobs = [];
this.pending = 0;
}
/**
* Adds a job to the queue.
*
* @param {Function} job The job to run
* @public
*/
add(job) {
this.jobs.push(job);
this[kRun]();
}
/**
* Removes a job from the queue and runs it if possible.
*
* @private
*/
[kRun]() {
if (this.pending === this.concurrency) return;
if (this.jobs.length) {
const job = this.jobs.shift();
this.pending++;
job(this[kDone]);
}
}
};
module2.exports = Limiter;
}
});
// node_modules/ws/lib/permessage-deflate.js
var require_permessage_deflate = __commonJS({
"node_modules/ws/lib/permessage-deflate.js"(exports2, module2) {
"use strict";
var zlib = require("zlib");
var bufferUtil = require_buffer_util();
var Limiter = require_limiter();
var { kStatusCode } = require_constants();
var FastBuffer = Buffer[Symbol.species];
var TRAILER = Buffer.from([0, 0, 255, 255]);
var kPerMessageDeflate = /* @__PURE__ */ Symbol("permessage-deflate");
var kTotalLength = /* @__PURE__ */ Symbol("total-length");
var kCallback = /* @__PURE__ */ Symbol("callback");
var kBuffers = /* @__PURE__ */ Symbol("buffers");
var kError = /* @__PURE__ */ Symbol("error");
var zlibLimiter;
var PerMessageDeflate = class {
/**
* Creates a PerMessageDeflate instance.
*
* @param {Object} [options] Configuration options
* @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
* for, or request, a custom client window size
* @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
* acknowledge disabling of client context takeover
* @param {Number} [options.concurrencyLimit=10] The number of concurrent
* calls to zlib
* @param {Boolean} [options.isServer=false] Create the instance in either
* server or client mode
* @param {Number} [options.maxPayload=0] The maximum allowed message length
* @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
* use of a custom server window size
* @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
* disabling of server context takeover
* @param {Number} [options.threshold=1024] Size (in bytes) below which
* messages should not be compressed if context takeover is disabled
* @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
* deflate
* @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
* inflate
*/
constructor(options) {
this._options = options || {};
this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
this._maxPayload = this._options.maxPayload | 0;
this._isServer = !!this._options.isServer;
this._deflate = null;
this._inflate = null;
this.params = null;
if (!zlibLimiter) {
const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
zlibLimiter = new Limiter(concurrency);
}
}
/**
* @type {String}
*/
static get extensionName() {
return "permessage-deflate";
}
/**
* Create an extension negotiation offer.
*
* @return {Object} Extension parameters
* @public
*/
offer() {
const params = {};
if (this._options.serverNoContextTakeover) {
params.server_no_context_takeover = true;
}
if (this._options.clientNoContextTakeover) {
params.client_no_context_takeover = true;
}
if (this._options.serverMaxWindowBits) {
params.server_max_window_bits = this._options.serverMaxWindowBits;
}
if (this._options.clientMaxWindowBits) {
params.client_max_window_bits = this._options.clientMaxWindowBits;
} else if (this._options.clientMaxWindowBits == null) {
params.client_max_window_bits = true;
}
return params;
}
/**
* Accept an extension negotiation offer/response.
*
* @param {Array} configurations The extension negotiation offers/reponse
* @return {Object} Accepted configuration
* @public
*/
accept(configurations) {
configurations = this.normalizeParams(configurations);
this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
return this.params;
}
/**
* Releases all resources used by the extension.
*
* @public
*/
cleanup() {
if (this._inflate) {
this._inflate.close();
this._inflate = null;
}
if (this._deflate) {
const callback = this._deflate[kCallback];
this._deflate.close();
this._deflate = null;
if (callback) {
callback(
new Error(
"The deflate stream was closed while data was being processed"
)
);
}
}
}
/**
* Accept an extension negotiation offer.
*
* @param {Array} offers The extension negotiation offers
* @return {Object} Accepted configuration
* @private
*/
acceptAsServer(offers) {
const opts = this._options;
const accepted = offers.find((params) => {
if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) {
return false;
}
return true;
});
if (!accepted) {
throw new Error("None of the extension offers can be accepted");
}
if (opts.serverNoContextTakeover) {
accepted.server_no_context_takeover = true;
}
if (opts.clientNoContextTakeover) {
accepted.client_no_context_takeover = true;
}
if (typeof opts.serverMaxWindowBits === "number") {
accepted.server_max_window_bits = opts.serverMaxWindowBits;
}
if (typeof opts.clientMaxWindowBits === "number") {
accepted.client_max_window_bits = opts.clientMaxWindowBits;
} else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
delete accepted.client_max_window_bits;
}
return accepted;
}
/**
* Accept the extension negotiation response.
*
* @param {Array} response The extension negotiation response
* @return {Object} Accepted configuration
* @private
*/
acceptAsClient(response) {
const params = response[0];
if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
throw new Error('Unexpected parameter "client_no_context_takeover"');
}
if (!params.client_max_window_bits) {
if (typeof this._options.clientMaxWindowBits === "number") {
params.client_max_window_bits = this._options.clientMaxWindowBits;
}
} else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
throw new Error(
'Unexpected or invalid parameter "client_max_window_bits"'
);
}
return params;
}
/**
* Normalize parameters.
*
* @param {Array} configurations The extension negotiation offers/reponse
* @return {Array} The offers/response with normalized parameters
* @private
*/
normalizeParams(configurations) {
configurations.forEach((params) => {
Object.keys(params).forEach((key) => {
let value = params[key];
if (value.length > 1) {
throw new Error(`Parameter "${key}" must have only a single value`);
}
value = value[0];
if (key === "client_max_window_bits") {
if (value !== true) {
const num = +value;
if (!Number.isInteger(num) || num < 8 || num > 15) {
throw new TypeError(
`Invalid value for parameter "${key}": ${value}`
);
}
value = num;
} else if (!this._isServer) {
throw new TypeError(
`Invalid value for parameter "${key}": ${value}`
);
}
} else if (key === "server_max_window_bits") {
const num = +value;
if (!Number.isInteger(num) || num < 8 || num > 15) {
throw new TypeError(
`Invalid value for parameter "${key}": ${value}`
);
}
value = num;
} else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
if (value !== true) {
throw new TypeError(
`Invalid value for parameter "${key}": ${value}`
);
}
} else {
throw new Error(`Unknown parameter "${key}"`);
}
params[key] = value;
});
});
return configurations;
}
/**
* Decompress data. Concurrency limited.
*
* @param {Buffer} data Compressed data
* @param {Boolean} fin Specifies whether or not this is the last fragment
* @param {Function} callback Callback
* @public
*/
decompress(data, fin, callback) {
zlibLimiter.add((done) => {
this._decompress(data, fin, (err, result) => {
done();
callback(err, result);
});
});
}
/**
* Compress data. Concurrency limited.
*
* @param {(Buffer|String)} data Data to compress
* @param {Boolean} fin Specifies whether or not this is the last fragment
* @param {Function} callback Callback
* @public
*/
compress(data, fin, callback) {
zlibLimiter.add((done) => {
this._compress(data, fin, (err, result) => {
done();
callback(err, result);
});
});
}
/**
* Decompress data.
*
* @param {Buffer} data Compressed data
* @param {Boolean} fin Specifies whether or not this is the last fragment
* @param {Function} callback Callback
* @private
*/
_decompress(data, fin, callback) {
const endpoint = this._isServer ? "client" : "server";
if (!this._inflate) {
const key = `${endpoint}_max_window_bits`;
const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
this._inflate = zlib.createInflateRaw({
...this._options.zlibInflateOptions,
windowBits
});
this._inflate[kPerMessageDeflate] = this;
this._inflate[kTotalLength] = 0;
this._inflate[kBuffers] = [];
this._inflate.on("error", inflateOnError);
this._inflate.on("data", inflateOnData);
}
this._inflate[kCallback] = callback;
this._inflate.write(data);
if (fin) this._inflate.write(TRAILER);
this._inflate.flush(() => {
const err = this._inflate[kError];
if (err) {
this._inflate.close();
this._inflate = null;
callback(err);
return;
}
const data2 = bufferUtil.concat(
this._inflate[kBuffers],
this._inflate[kTotalLength]
);
if (this._inflate._readableState.endEmitted) {
this._inflate.close();
this._inflate = null;
} else {
this._inflate[kTotalLength] = 0;
this._inflate[kBuffers] = [];
if (fin && this.params[`${endpoint}_no_context_takeover`]) {
this._inflate.reset();
}
}
callback(null, data2);
});
}
/**
* Compress data.
*
* @param {(Buffer|String)} data Data to compress
* @param {Boolean} fin Specifies whether or not this is the last fragment
* @param {Function} callback Callback
* @private
*/
_compress(data, fin, callback) {
const endpoint = this._isServer ? "server" : "client";
if (!this._deflate) {
const key = `${endpoint}_max_window_bits`;
const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
this._deflate = zlib.createDeflateRaw({
...this._options.zlibDeflateOptions,
windowBits
});
this._deflate[kTotalLength] = 0;
this._deflate[kBuffers] = [];
this._deflate.on("data", deflateOnData);
}
this._deflate[kCallback] = callback;
this._deflate.write(data);
this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
if (!this._deflate) {
return;
}
let data2 = bufferUtil.concat(
this._deflate[kBuffers],
this._deflate[kTotalLength]
);
if (fin) {
data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
}
this._deflate[kCallback] = null;
this._deflate[kTotalLength] = 0;
this._deflate[kBuffers] = [];
if (fin && this.params[`${endpoint}_no_context_takeover`]) {
this._deflate.reset();
}
callback(null, data2);
});
}
};
module2.exports = PerMessageDeflate;
function deflateOnData(chunk) {
this[kBuffers].push(chunk);
this[kTotalLength] += chunk.length;
}
function inflateOnData(chunk) {
this[kTotalLength] += chunk.length;
if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
this[kBuffers].push(chunk);
return;
}
this[kError] = new RangeError("Max payload size exceeded");
this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
this[kError][kStatusCode] = 1009;
this.removeListener("data", inflateOnData);
this.reset();
}
function inflateOnError(err) {
this[kPerMessageDeflate]._inflate = null;
if (this[kError]) {
this[kCallback](this[kError]);
return;
}
err[kStatusCode] = 1007;
this[kCallback](err);
}
}
});
// node_modules/ws/lib/validation.js
var require_validation = __commonJS({
"node_modules/ws/lib/validation.js"(exports2, module2) {
"use strict";
var { isUtf8 } = require("buffer");
var { hasBlob } = require_constants();
var tokenChars = [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
// 0 - 15
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
// 16 - 31
0,
1,
0,
1,
1,
1,
1,
1,
0,
0,
1,
1,
0,
1,
1,
0,
// 32 - 47
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
// 48 - 63
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
// 64 - 79
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
1,
1,
// 80 - 95
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
// 96 - 111
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
1,
0,
1,
0
// 112 - 127
];
function isValidStatusCode(code) {
return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
}
function _isValidUTF8(buf) {
const len = buf.length;
let i = 0;
while (i < len) {
if ((buf[i] & 128) === 0) {
i++;
} else if ((buf[i] & 224) === 192) {
if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
return false;
}
i += 2;
} else if ((buf[i] & 240) === 224) {
if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong
buf[i] === 237 && (buf[i + 1] & 224) === 160) {
return false;
}
i += 3;
} else if ((buf[i] & 248) === 240) {
if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || // Overlong
buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
return false;
}
i += 4;
} else {
return false;
}
}
return true;
}
function isBlob(value) {
return hasBlob && typeof value === "object" && typeof value.arrayBuffer === "function" && typeof value.type === "string" && typeof value.stream === "function" && (value[Symbol.toStringTag] === "Blob" || value[Symbol.toStringTag] === "File");
}
module2.exports = {
isBlob,
isValidStatusCode,
isValidUTF8: _isValidUTF8,
tokenChars
};
if (isUtf8) {
module2.exports.isValidUTF8 = function(buf) {
return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
};
} else if (!process.env.WS_NO_UTF_8_VALIDATE) {
try {
const isValidUTF8 = require("utf-8-validate");
module2.exports.isValidUTF8 = function(buf) {
return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
};
} catch (e) {
}
}
}
});
// node_modules/ws/lib/receiver.js
var require_receiver = __commonJS({
"node_modules/ws/lib/receiver.js"(exports2, module2) {
"use strict";
var { Writable } = require("stream");
var PerMessageDeflate = require_permessage_deflate();
var {
BINARY_TYPES,
EMPTY_BUFFER,
kStatusCode,
kWebSocket
} = require_constants();
var { concat, toArrayBuffer, unmask } = require_buffer_util();
var { isValidStatusCode, isValidUTF8 } = require_validation();
var FastBuffer = Buffer[Symbol.species];
var GET_INFO = 0;
var GET_PAYLOAD_LENGTH_16 = 1;
var GET_PAYLOAD_LENGTH_64 = 2;
var GET_MASK = 3;
var GET_DATA = 4;
var INFLATING = 5;
var DEFER_EVENT = 6;
var Receiver = class extends Writable {
/**
* Creates a Receiver instance.
*
* @param {Object} [options] Options object
* @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
* any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
* multiple times in the same tick
* @param {String} [options.binaryType=nodebuffer] The type for binary data
* @param {Object} [options.extensions] An object containing the negotiated
* extensions
* @param {Boolean} [options.isServer=false] Specifies whether to operate in
* client or server mode
* @param {Number} [options.maxBufferedChunks=0] The maximum number of
* buffered data chunks
* @param {Number} [options.maxFragments=0] The maximum number of message
* fragments
* @param {Number} [options.maxPayload=0] The maximum allowed message length
* @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
* not to skip UTF-8 validation for text and close messages
*/
constructor(options = {}) {
super();
this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
this._binaryType = options.binaryType || BINARY_TYPES[0];
this._extensions = options.extensions || {};
this._isServer = !!options.isServer;
this._maxBufferedChunks = options.maxBufferedChunks | 0;
this._maxFragments = options.maxFragments | 0;
this._maxPayload = options.maxPayload | 0;
this._skipUTF8Validation = !!options.skipUTF8Validation;
this[kWebSocket] = void 0;
this._bufferedBytes = 0;
this._buffers = [];
this._compressed = false;
this._payloadLength = 0;
this._mask = void 0;
this._fragmented = 0;
this._masked = false;
this._fin = false;
this._opcode = 0;
this._totalPayloadLength = 0;
this._messageLength = 0;
this._fragments = [];
this._errored = false;
this._loop = false;
this._state = GET_INFO;
}
/**
* Implements `Writable.prototype._write()`.
*
* @param {Buffer} chunk The chunk of data to write
* @param {String} encoding The character encoding of `chunk`
* @param {Function} cb Callback
* @private
*/
_write(chunk, encoding, cb) {
if (this._opcode === 8 && this._state == GET_INFO) return cb();
if (this._maxBufferedChunks > 0 && this._buffers.length >= this._maxBufferedChunks) {
cb(
this.createError(
RangeError,
"Too many buffered chunks",
false,
1008,
"WS_ERR_TOO_MANY_BUFFERED_PARTS"
)
);
return;
}
this._bufferedBytes += chunk.length;
this._buffers.push(chunk);
this.startLoop(cb);
}
/**
* Consumes `n` bytes from the buffered data.
*
* @param {Number} n The number of bytes to consume
* @return {Buffer} The consumed bytes
* @private
*/
consume(n) {
this._bufferedBytes -= n;
if (n === this._buffers[0].length) return this._buffers.shift();
if (n < this._buffers[0].length) {
const buf = this._buffers[0];
this._buffers[0] = new FastBuffer(
buf.buffer,
buf.byteOffset + n,
buf.length - n
);
return new FastBuffer(buf.buffer, buf.byteOffset, n);
}
const dst = Buffer.allocUnsafe(n);
do {
const buf = this._buffers[0];
const offset = dst.length - n;
if (n >= buf.length) {
dst.set(this._buffers.shift(), offset);
} else {
dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
this._buffers[0] = new FastBuffer(
buf.buffer,
buf.byteOffset + n,
buf.length - n
);
}
n -= buf.length;
} while (n > 0);
return dst;
}
/**
* Starts the parsing loop.
*
* @param {Function} cb Callback
* @private
*/
startLoop(cb) {
this._loop = true;
do {
switch (this._state) {
case GET_INFO:
this.getInfo(cb);
break;
case GET_PAYLOAD_LENGTH_16:
this.getPayloadLength16(cb);
break;
case GET_PAYLOAD_LENGTH_64:
this.getPayloadLength64(cb);
break;
case GET_MASK:
this.getMask();
break;
case GET_DATA:
this.getData(cb);
break;
case INFLATING:
case DEFER_EVENT:
this._loop = false;
return;
}
} while (this._loop);
if (!this._errored) cb();
}
/**
* Reads the first two bytes of a frame.
*
* @param {Function} cb Callback
* @private
*/
getInfo(cb) {
if (this._bufferedBytes < 2) {
this._loop = false;
return;
}
const buf = this.consume(2);
if ((buf[0] & 48) !== 0) {
const error = this.createError(
RangeError,
"RSV2 and RSV3 must be clear",
true,
1002,
"WS_ERR_UNEXPECTED_RSV_2_3"
);
cb(error);
return;
}
const compressed = (buf[0] & 64) === 64;
if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
const error = this.createError(
RangeError,
"RSV1 must be clear",
true,
1002,
"WS_ERR_UNEXPECTED_RSV_1"
);
cb(error);
return;
}
this._fin = (buf[0] & 128) === 128;
this._opcode = buf[0] & 15;
this._payloadLength = buf[1] & 127;
if (this._opcode === 0) {
if (compressed) {
const error = this.createError(
RangeError,
"RSV1 must be clear",
true,
1002,
"WS_ERR_UNEXPECTED_RSV_1"
);
cb(error);
return;
}
if (!this._fragmented) {
const error = this.createError(
RangeError,
"invalid opcode 0",
true,
1002,
"WS_ERR_INVALID_OPCODE"
);
cb(error);
return;
}
this._opcode = this._fragmented;
} else if (this._opcode === 1 || this._opcode === 2) {
if (this._fragmented) {
const error = this.createError(
RangeError,
`invalid opcode ${this._opcode}`,
true,
1002,
"WS_ERR_INVALID_OPCODE"
);
cb(error);
return;
}
this._compressed = compressed;
} else if (this._opcode > 7 && this._opcode < 11) {
if (!this._fin) {
const error = this.createError(
RangeError,
"FIN must be set",
true,
1002,
"WS_ERR_EXPECTED_FIN"
);
cb(error);
return;
}
if (compressed) {
const error = this.createError(
RangeError,
"RSV1 must be clear",
true,
1002,
"WS_ERR_UNEXPECTED_RSV_1"
);
cb(error);
return;
}
if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
const error = this.createError(
RangeError,
`invalid payload length ${this._payloadLength}`,
true,
1002,
"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
);
cb(error);
return;
}
} else {
const error = this.createError(
RangeError,
`invalid opcode ${this._opcode}`,
true,
1002,
"WS_ERR_INVALID_OPCODE"
);
cb(error);
return;
}
if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
this._masked = (buf[1] & 128) === 128;
if (this._isServer) {
if (!this._masked) {
const error = this.createError(
RangeError,
"MASK must be set",
true,
1002,
"WS_ERR_EXPECTED_MASK"
);
cb(error);
return;
}
} else if (this._masked) {
const error = this.createError(
RangeError,
"MASK must be clear",
true,
1002,
"WS_ERR_UNEXPECTED_MASK"
);
cb(error);
return;
}
if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
else this.haveLength(cb);
}
/**
* Gets extended payload length (7+16).
*
* @param {Function} cb Callback
* @private
*/
getPayloadLength16(cb) {
if (this._bufferedBytes < 2) {
this._loop = false;
return;
}
this._payloadLength = this.consume(2).readUInt16BE(0);
this.haveLength(cb);
}
/**
* Gets extended payload length (7+64).
*
* @param {Function} cb Callback
* @private
*/
getPayloadLength64(cb) {
if (this._bufferedBytes < 8) {
this._loop = false;
return;
}
const buf = this.consume(8);
const num = buf.readUInt32BE(0);
if (num > Math.pow(2, 53 - 32) - 1) {
const error = this.createError(
RangeError,
"Unsupported WebSocket frame: payload length > 2^53 - 1",
false,
1009,
"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
);
cb(error);
return;
}
this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
this.haveLength(cb);
}
/**
* Payload length has been read.
*
* @param {Function} cb Callback
* @private
*/
haveLength(cb) {
if (this._payloadLength && this._opcode < 8) {
this._totalPayloadLength += this._payloadLength;
if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
const error = this.createError(
RangeError,
"Max payload size exceeded",
false,
1009,
"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
);
cb(error);
return;
}
}
if (this._masked) this._state = GET_MASK;
else this._state = GET_DATA;
}
/**
* Reads mask bytes.
*
* @private
*/
getMask() {
if (this._bufferedBytes < 4) {
this._loop = false;
return;
}
this._mask = this.consume(4);
this._state = GET_DATA;
}
/**
* Reads data bytes.
*
* @param {Function} cb Callback
* @private
*/
getData(cb) {
let data = EMPTY_BUFFER;
if (this._payloadLength) {
if (this._bufferedBytes < this._payloadLength) {
this._loop = false;
return;
}
data = this.consume(this._payloadLength);
if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
unmask(data, this._mask);
}
}
if (this._opcode > 7) {
this.controlMessage(data, cb);
return;
}
if (this._compressed) {
this._state = INFLATING;
this.decompress(data, cb);
return;
}
if (data.length) {
if (this._maxFragments > 0 && this._fragments.length >= this._maxFragments) {
const error = this.createError(
RangeError,
"Too many message fragments",
false,
1008,
"WS_ERR_TOO_MANY_BUFFERED_PARTS"
);
cb(error);
return;
}
this._messageLength = this._totalPayloadLength;
this._fragments.push(data);
}
this.dataMessage(cb);
}
/**
* Decompresses data.
*
* @param {Buffer} data Compressed data
* @param {Function} cb Callback
* @private
*/
decompress(data, cb) {
const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
perMessageDeflate.decompress(data, this._fin, (err, buf) => {
if (err) return cb(err);
if (buf.length) {
this._messageLength += buf.length;
if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
const error = this.createError(
RangeError,
"Max payload size exceeded",
false,
1009,
"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
);
cb(error);
return;
}
if (this._maxFragments > 0 && this._fragments.length >= this._maxFragments) {
const error = this.createError(
RangeError,
"Too many message fragments",
false,
1008,
"WS_ERR_TOO_MANY_BUFFERED_PARTS"
);
cb(error);
return;
}
this._fragments.push(buf);
}
this.dataMessage(cb);
if (this._state === GET_INFO) this.startLoop(cb);
});
}
/**
* Handles a data message.
*
* @param {Function} cb Callback
* @private
*/
dataMessage(cb) {
if (!this._fin) {
this._state = GET_INFO;
return;
}
const messageLength = this._messageLength;
const fragments = this._fragments;
this._totalPayloadLength = 0;
this._messageLength = 0;
this._fragmented = 0;
this._fragments = [];
if (this._opcode === 2) {
let data;
if (this._binaryType === "nodebuffer") {
data = concat(fragments, messageLength);
} else if (this._binaryType === "arraybuffer") {
data = toArrayBuffer(concat(fragments, messageLength));
} else if (this._binaryType === "blob") {
data = new Blob(fragments);
} else {
data = fragments;
}
if (this._allowSynchronousEvents) {
this.emit("message", data, true);
this._state = GET_INFO;
} else {
this._state = DEFER_EVENT;
setImmediate(() => {
this.emit("message", data, true);
this._state = GET_INFO;
this.startLoop(cb);
});
}
} else {
const buf = concat(fragments, messageLength);
if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
const error = this.createError(
Error,
"invalid UTF-8 sequence",
true,
1007,
"WS_ERR_INVALID_UTF8"
);
cb(error);
return;
}
if (this._state === INFLATING || this._allowSynchronousEvents) {
this.emit("message", buf, false);
this._state = GET_INFO;
} else {
this._state = DEFER_EVENT;
setImmediate(() => {
this.emit("message", buf, false);
this._state = GET_INFO;
this.startLoop(cb);
});
}
}
}
/**
* Handles a control message.
*
* @param {Buffer} data Data to handle
* @return {(Error|RangeError|undefined)} A possible error
* @private
*/
controlMessage(data, cb) {
if (this._opcode === 8) {
if (data.length === 0) {
this._loop = false;
this.emit("conclude", 1005, EMPTY_BUFFER);
this.end();
} else {
const code = data.readUInt16BE(0);
if (!isValidStatusCode(code)) {
const error = this.createError(
RangeError,
`invalid status code ${code}`,
true,
1002,
"WS_ERR_INVALID_CLOSE_CODE"
);
cb(error);
return;
}
const buf = new FastBuffer(
data.buffer,
data.byteOffset + 2,
data.length - 2
);
if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
const error = this.createError(
Error,
"invalid UTF-8 sequence",
true,
1007,
"WS_ERR_INVALID_UTF8"
);
cb(error);
return;
}
this._loop = false;
this.emit("conclude", code, buf);
this.end();
}
this._state = GET_INFO;
return;
}
if (this._allowSynchronousEvents) {
this.emit(this._opcode === 9 ? "ping" : "pong", data);
this._state = GET_INFO;
} else {
this._state = DEFER_EVENT;
setImmediate(() => {
this.emit(this._opcode === 9 ? "ping" : "pong", data);
this._state = GET_INFO;
this.startLoop(cb);
});
}
}
/**
* Builds an error object.
*
* @param {function(new:Error|RangeError)} ErrorCtor The error constructor
* @param {String} message The error message
* @param {Boolean} prefix Specifies whether or not to add a default prefix to
* `message`
* @param {Number} statusCode The status code
* @param {String} errorCode The exposed error code
* @return {(Error|RangeError)} The error
* @private
*/
createError(ErrorCtor, message, prefix, statusCode, errorCode) {
this._loop = false;
this._errored = true;
const err = new ErrorCtor(
prefix ? `Invalid WebSocket frame: ${message}` : message
);
Error.captureStackTrace(err, this.createError);
err.code = errorCode;
err[kStatusCode] = statusCode;
return err;
}
};
module2.exports = Receiver;
}
});
// node_modules/ws/lib/sender.js
var require_sender = __commonJS({
"node_modules/ws/lib/sender.js"(exports2, module2) {
"use strict";
var { Duplex } = require("stream");
var { randomFillSync } = require("crypto");
var {
types: { isUint8Array }
} = require("util");
var PerMessageDeflate = require_permessage_deflate();
var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
var { isBlob, isValidStatusCode } = require_validation();
var { mask: applyMask, toBuffer } = require_buffer_util();
var kByteLength = /* @__PURE__ */ Symbol("kByteLength");
var maskBuffer = Buffer.alloc(4);
var RANDOM_POOL_SIZE = 8 * 1024;
var randomPool;
var randomPoolPointer = RANDOM_POOL_SIZE;
var DEFAULT = 0;
var DEFLATING = 1;
var GET_BLOB_DATA = 2;
var Sender = class _Sender {
/**
* Creates a Sender instance.
*
* @param {Duplex} socket The connection socket
* @param {Object} [extensions] An object containing the negotiated extensions
* @param {Function} [generateMask] The function used to generate the masking
* key
*/
constructor(socket, extensions, generateMask) {
this._extensions = extensions || {};
if (generateMask) {
this._generateMask = generateMask;
this._maskBuffer = Buffer.alloc(4);
}
this._socket = socket;
this._firstFragment = true;
this._compress = false;
this._bufferedBytes = 0;
this._queue = [];
this._state = DEFAULT;
this.onerror = NOOP;
this[kWebSocket] = void 0;
}
/**
* Frames a piece of data according to the HyBi WebSocket protocol.
*
* @param {(Buffer|String)} data The data to frame
* @param {Object} options Options object
* @param {Boolean} [options.fin=false] Specifies whether or not to set the
* FIN bit
* @param {Function} [options.generateMask] The function used to generate the
* masking key
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
* `data`
* @param {Buffer} [options.maskBuffer] The buffer used to store the masking
* key
* @param {Number} options.opcode The opcode
* @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
* modified
* @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
* RSV1 bit
* @return {(Buffer|String)[]} The framed data
* @public
*/
static frame(data, options) {
let mask;
let merge = false;
let offset = 2;
let skipMasking = false;
if (options.mask) {
mask = options.maskBuffer || maskBuffer;
if (options.generateMask) {
options.generateMask(mask);
} else {
if (randomPoolPointer === RANDOM_POOL_SIZE) {
if (randomPool === void 0) {
randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
}
randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
randomPoolPointer = 0;
}
mask[0] = randomPool[randomPoolPointer++];
mask[1] = randomPool[randomPoolPointer++];
mask[2] = randomPool[randomPoolPointer++];
mask[3] = randomPool[randomPoolPointer++];
}
skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
offset = 6;
}
let dataLength;
if (typeof data === "string") {
if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) {
dataLength = options[kByteLength];
} else {
data = Buffer.from(data);
dataLength = data.length;
}
} else {
dataLength = data.length;
merge = options.mask && options.readOnly && !skipMasking;
}
let payloadLength = dataLength;
if (dataLength >= 65536) {
offset += 8;
payloadLength = 127;
} else if (dataLength > 125) {
offset += 2;
payloadLength = 126;
}
const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
target[0] = options.fin ? options.opcode | 128 : options.opcode;
if (options.rsv1) target[0] |= 64;
target[1] = payloadLength;
if (payloadLength === 126) {
target.writeUInt16BE(dataLength, 2);
} else if (payloadLength === 127) {
target[2] = target[3] = 0;
target.writeUIntBE(dataLength, 4, 6);
}
if (!options.mask) return [target, data];
target[1] |= 128;
target[offset - 4] = mask[0];
target[offset - 3] = mask[1];
target[offset - 2] = mask[2];
target[offset - 1] = mask[3];
if (skipMasking) return [target, data];
if (merge) {
applyMask(data, mask, target, offset, dataLength);
return [target];
}
applyMask(data, mask, data, 0, dataLength);
return [target, data];
}
/**
* Sends a close message to the other peer.
*
* @param {Number} [code] The status code component of the body
* @param {(String|Buffer)} [data] The message component of the body
* @param {Boolean} [mask=false] Specifies whether or not to mask the message
* @param {Function} [cb] Callback
* @public
*/
close(code, data, mask, cb) {
let buf;
if (code === void 0) {
buf = EMPTY_BUFFER;
} else if (typeof code !== "number" || !isValidStatusCode(code)) {
throw new TypeError("First argument must be a valid error code number");
} else if (data === void 0 || !data.length) {
buf = Buffer.allocUnsafe(2);
buf.writeUInt16BE(code, 0);
} else {
const length = Buffer.byteLength(data);
if (length > 123) {
throw new RangeError("The message must not be greater than 123 bytes");
}
buf = Buffer.allocUnsafe(2 + length);
buf.writeUInt16BE(code, 0);
if (typeof data === "string") {
buf.write(data, 2);
} else if (isUint8Array(data)) {
buf.set(data, 2);
} else {
throw new TypeError("Second argument must be a string or a Uint8Array");
}
}
const options = {
[kByteLength]: buf.length,
fin: true,
generateMask: this._generateMask,
mask,
maskBuffer: this._maskBuffer,
opcode: 8,
readOnly: false,
rsv1: false
};
if (this._state !== DEFAULT) {
this.enqueue([this.dispatch, buf, false, options, cb]);
} else {
this.sendFrame(_Sender.frame(buf, options), cb);
}
}
/**
* Sends a ping message to the other peer.
*
* @param {*} data The message to send
* @param {Boolean} [mask=false] Specifies whether or not to mask `data`
* @param {Function} [cb] Callback
* @public
*/
ping(data, mask, cb) {
let byteLength;
let readOnly;
if (typeof data === "string") {
byteLength = Buffer.byteLength(data);
readOnly = false;
} else if (isBlob(data)) {
byteLength = data.size;
readOnly = false;
} else {
data = toBuffer(data);
byteLength = data.length;
readOnly = toBuffer.readOnly;
}
if (byteLength > 125) {
throw new RangeError("The data size must not be greater than 125 bytes");
}
const options = {
[kByteLength]: byteLength,
fin: true,
generateMask: this._generateMask,
mask,
maskBuffer: this._maskBuffer,
opcode: 9,
readOnly,
rsv1: false
};
if (isBlob(data)) {
if (this._state !== DEFAULT) {
this.enqueue([this.getBlobData, data, false, options, cb]);
} else {
this.getBlobData(data, false, options, cb);
}
} else if (this._state !== DEFAULT) {
this.enqueue([this.dispatch, data, false, options, cb]);
} else {
this.sendFrame(_Sender.frame(data, options), cb);
}
}
/**
* Sends a pong message to the other peer.
*
* @param {*} data The message to send
* @param {Boolean} [mask=false] Specifies whether or not to mask `data`
* @param {Function} [cb] Callback
* @public
*/
pong(data, mask, cb) {
let byteLength;
let readOnly;
if (typeof data === "string") {
byteLength = Buffer.byteLength(data);
readOnly = false;
} else if (isBlob(data)) {
byteLength = data.size;
readOnly = false;
} else {
data = toBuffer(data);
byteLength = data.length;
readOnly = toBuffer.readOnly;
}
if (byteLength > 125) {
throw new RangeError("The data size must not be greater than 125 bytes");
}
const options = {
[kByteLength]: byteLength,
fin: true,
generateMask: this._generateMask,
mask,
maskBuffer: this._maskBuffer,
opcode: 10,
readOnly,
rsv1: false
};
if (isBlob(data)) {
if (this._state !== DEFAULT) {
this.enqueue([this.getBlobData, data, false, options, cb]);
} else {
this.getBlobData(data, false, options, cb);
}
} else if (this._state !== DEFAULT) {
this.enqueue([this.dispatch, data, false, options, cb]);
} else {
this.sendFrame(_Sender.frame(data, options), cb);
}
}
/**
* Sends a data message to the other peer.
*
* @param {*} data The message to send
* @param {Object} options Options object
* @param {Boolean} [options.binary=false] Specifies whether `data` is binary
* or text
* @param {Boolean} [options.compress=false] Specifies whether or not to
* compress `data`
* @param {Boolean} [options.fin=false] Specifies whether the fragment is the
* last one
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
* `data`
* @param {Function} [cb] Callback
* @public
*/
send(data, options, cb) {
const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
let opcode = options.binary ? 2 : 1;
let rsv1 = options.compress;
let byteLength;
let readOnly;
if (typeof data === "string") {
byteLength = Buffer.byteLength(data);
readOnly = false;
} else if (isBlob(data)) {
byteLength = data.size;
readOnly = false;
} else {
data = toBuffer(data);
byteLength = data.length;
readOnly = toBuffer.readOnly;
}
if (this._firstFragment) {
this._firstFragment = false;
if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
rsv1 = byteLength >= perMessageDeflate._threshold;
}
this._compress = rsv1;
} else {
rsv1 = false;
opcode = 0;
}
if (options.fin) this._firstFragment = true;
const opts = {
[kByteLength]: byteLength,
fin: options.fin,
generateMask: this._generateMask,
mask: options.mask,
maskBuffer: this._maskBuffer,
opcode,
readOnly,
rsv1
};
if (isBlob(data)) {
if (this._state !== DEFAULT) {
this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
} else {
this.getBlobData(data, this._compress, opts, cb);
}
} else if (this._state !== DEFAULT) {
this.enqueue([this.dispatch, data, this._compress, opts, cb]);
} else {
this.dispatch(data, this._compress, opts, cb);
}
}
/**
* Gets the contents of a blob as binary data.
*
* @param {Blob} blob The blob
* @param {Boolean} [compress=false] Specifies whether or not to compress
* the data
* @param {Object} options Options object
* @param {Boolean} [options.fin=false] Specifies whether or not to set the
* FIN bit
* @param {Function} [options.generateMask] The function used to generate the
* masking key
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
* `data`
* @param {Buffer} [options.maskBuffer] The buffer used to store the masking
* key
* @param {Number} options.opcode The opcode
* @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
* modified
* @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
* RSV1 bit
* @param {Function} [cb] Callback
* @private
*/
getBlobData(blob, compress, options, cb) {
this._bufferedBytes += options[kByteLength];
this._state = GET_BLOB_DATA;
blob.arrayBuffer().then((arrayBuffer) => {
if (this._socket.destroyed) {
const err = new Error(
"The socket was closed while the blob was being read"
);
process.nextTick(callCallbacks, this, err, cb);
return;
}
this._bufferedBytes -= options[kByteLength];
const data = toBuffer(arrayBuffer);
if (!compress) {
this._state = DEFAULT;
this.sendFrame(_Sender.frame(data, options), cb);
this.dequeue();
} else {
this.dispatch(data, compress, options, cb);
}
}).catch((err) => {
process.nextTick(onError, this, err, cb);
});
}
/**
* Dispatches a message.
*
* @param {(Buffer|String)} data The message to send
* @param {Boolean} [compress=false] Specifies whether or not to compress
* `data`
* @param {Object} options Options object
* @param {Boolean} [options.fin=false] Specifies whether or not to set the
* FIN bit
* @param {Function} [options.generateMask] The function used to generate the
* masking key
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
* `data`
* @param {Buffer} [options.maskBuffer] The buffer used to store the masking
* key
* @param {Number} options.opcode The opcode
* @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
* modified
* @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
* RSV1 bit
* @param {Function} [cb] Callback
* @private
*/
dispatch(data, compress, options, cb) {
if (!compress) {
this.sendFrame(_Sender.frame(data, options), cb);
return;
}
const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
this._bufferedBytes += options[kByteLength];
this._state = DEFLATING;
perMessageDeflate.compress(data, options.fin, (_, buf) => {
if (this._socket.destroyed) {
const err = new Error(
"The socket was closed while data was being compressed"
);
callCallbacks(this, err, cb);
return;
}
this._bufferedBytes -= options[kByteLength];
this._state = DEFAULT;
options.readOnly = false;
this.sendFrame(_Sender.frame(buf, options), cb);
this.dequeue();
});
}
/**
* Executes queued send operations.
*
* @private
*/
dequeue() {
while (this._state === DEFAULT && this._queue.length) {
const params = this._queue.shift();
this._bufferedBytes -= params[3][kByteLength];
Reflect.apply(params[0], this, params.slice(1));
}
}
/**
* Enqueues a send operation.
*
* @param {Array} params Send operation parameters.
* @private
*/
enqueue(params) {
this._bufferedBytes += params[3][kByteLength];
this._queue.push(params);
}
/**
* Sends a frame.
*
* @param {(Buffer | String)[]} list The frame to send
* @param {Function} [cb] Callback
* @private
*/
sendFrame(list, cb) {
if (list.length === 2) {
this._socket.cork();
this._socket.write(list[0]);
this._socket.write(list[1], cb);
this._socket.uncork();
} else {
this._socket.write(list[0], cb);
}
}
};
module2.exports = Sender;
function callCallbacks(sender, err, cb) {
if (typeof cb === "function") cb(err);
for (let i = 0; i < sender._queue.length; i++) {
const params = sender._queue[i];
const callback = params[params.length - 1];
if (typeof callback === "function") callback(err);
}
}
function onError(sender, err, cb) {
callCallbacks(sender, err, cb);
sender.onerror(err);
}
}
});
// node_modules/ws/lib/event-target.js
var require_event_target = __commonJS({
"node_modules/ws/lib/event-target.js"(exports2, module2) {
"use strict";
var { kForOnEventAttribute, kListener } = require_constants();
var kCode = /* @__PURE__ */ Symbol("kCode");
var kData = /* @__PURE__ */ Symbol("kData");
var kError = /* @__PURE__ */ Symbol("kError");
var kMessage = /* @__PURE__ */ Symbol("kMessage");
var kReason = /* @__PURE__ */ Symbol("kReason");
var kTarget = /* @__PURE__ */ Symbol("kTarget");
var kType = /* @__PURE__ */ Symbol("kType");
var kWasClean = /* @__PURE__ */ Symbol("kWasClean");
var Event2 = class {
/**
* Create a new `Event`.
*
* @param {String} type The name of the event
* @throws {TypeError} If the `type` argument is not specified
*/
constructor(type) {
this[kTarget] = null;
this[kType] = type;
}
/**
* @type {*}
*/
get target() {
return this[kTarget];
}
/**
* @type {String}
*/
get type() {
return this[kType];
}
};
Object.defineProperty(Event2.prototype, "target", { enumerable: true });
Object.defineProperty(Event2.prototype, "type", { enumerable: true });
var CloseEvent = class extends Event2 {
/**
* Create a new `CloseEvent`.
*
* @param {String} type The name of the event
* @param {Object} [options] A dictionary object that allows for setting
* attributes via object members of the same name
* @param {Number} [options.code=0] The status code explaining why the
* connection was closed
* @param {String} [options.reason=''] A human-readable string explaining why
* the connection was closed
* @param {Boolean} [options.wasClean=false] Indicates whether or not the
* connection was cleanly closed
*/
constructor(type, options = {}) {
super(type);
this[kCode] = options.code === void 0 ? 0 : options.code;
this[kReason] = options.reason === void 0 ? "" : options.reason;
this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
}
/**
* @type {Number}
*/
get code() {
return this[kCode];
}
/**
* @type {String}
*/
get reason() {
return this[kReason];
}
/**
* @type {Boolean}
*/
get wasClean() {
return this[kWasClean];
}
};
Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
var ErrorEvent = class extends Event2 {
/**
* Create a new `ErrorEvent`.
*
* @param {String} type The name of the event
* @param {Object} [options] A dictionary object that allows for setting
* attributes via object members of the same name
* @param {*} [options.error=null] The error that generated this event
* @param {String} [options.message=''] The error message
*/
constructor(type, options = {}) {
super(type);
this[kError] = options.error === void 0 ? null : options.error;
this[kMessage] = options.message === void 0 ? "" : options.message;
}
/**
* @type {*}
*/
get error() {
return this[kError];
}
/**
* @type {String}
*/
get message() {
return this[kMessage];
}
};
Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
var MessageEvent = class extends Event2 {
/**
* Create a new `MessageEvent`.
*
* @param {String} type The name of the event
* @param {Object} [options] A dictionary object that allows for setting
* attributes via object members of the same name
* @param {*} [options.data=null] The message content
*/
constructor(type, options = {}) {
super(type);
this[kData] = options.data === void 0 ? null : options.data;
}
/**
* @type {*}
*/
get data() {
return this[kData];
}
};
Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
var EventTarget = {
/**
* Register an event listener.
*
* @param {String} type A string representing the event type to listen for
* @param {(Function|Object)} handler The listener to add
* @param {Object} [options] An options object specifies characteristics about
* the event listener
* @param {Boolean} [options.once=false] A `Boolean` indicating that the
* listener should be invoked at most once after being added. If `true`,
* the listener would be automatically removed when invoked.
* @public
*/
addEventListener(type, handler, options = {}) {
for (const listener of this.listeners(type)) {
if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
return;
}
}
let wrapper;
if (type === "message") {
wrapper = function onMessage(data, isBinary) {
const event = new MessageEvent("message", {
data: isBinary ? data : data.toString()
});
event[kTarget] = this;
callListener(handler, this, event);
};
} else if (type === "close") {
wrapper = function onClose(code, message) {
const event = new CloseEvent("close", {
code,
reason: message.toString(),
wasClean: this._closeFrameReceived && this._closeFrameSent
});
event[kTarget] = this;
callListener(handler, this, event);
};
} else if (type === "error") {
wrapper = function onError(error) {
const event = new ErrorEvent("error", {
error,
message: error.message
});
event[kTarget] = this;
callListener(handler, this, event);
};
} else if (type === "open") {
wrapper = function onOpen() {
const event = new Event2("open");
event[kTarget] = this;
callListener(handler, this, event);
};
} else {
return;
}
wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
wrapper[kListener] = handler;
if (options.once) {
this.once(type, wrapper);
} else {
this.on(type, wrapper);
}
},
/**
* Remove an event listener.
*
* @param {String} type A string representing the event type to remove
* @param {(Function|Object)} handler The listener to remove
* @public
*/
removeEventListener(type, handler) {
for (const listener of this.listeners(type)) {
if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
this.removeListener(type, listener);
break;
}
}
}
};
module2.exports = {
CloseEvent,
ErrorEvent,
Event: Event2,
EventTarget,
MessageEvent
};
function callListener(listener, thisArg, event) {
if (typeof listener === "object" && listener.handleEvent) {
listener.handleEvent.call(listener, event);
} else {
listener.call(thisArg, event);
}
}
}
});
// node_modules/ws/lib/extension.js
var require_extension = __commonJS({
"node_modules/ws/lib/extension.js"(exports2, module2) {
"use strict";
var { tokenChars } = require_validation();
function push(dest, name, elem) {
if (dest[name] === void 0) dest[name] = [elem];
else dest[name].push(elem);
}
function parse2(header) {
const offers = /* @__PURE__ */ Object.create(null);
let params = /* @__PURE__ */ Object.create(null);
let mustUnescape = false;
let isEscaping = false;
let inQuotes = false;
let extensionName;
let paramName;
let start = -1;
let code = -1;
let end = -1;
let i = 0;
for (; i < header.length; i++) {
code = header.charCodeAt(i);
if (extensionName === void 0) {
if (end === -1 && tokenChars[code] === 1) {
if (start === -1) start = i;
} else if (i !== 0 && (code === 32 || code === 9)) {
if (end === -1 && start !== -1) end = i;
} else if (code === 59 || code === 44) {
if (start === -1) {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
if (end === -1) end = i;
const name = header.slice(start, end);
if (code === 44) {
push(offers, name, params);
params = /* @__PURE__ */ Object.create(null);
} else {
extensionName = name;
}
start = end = -1;
} else {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
} else if (paramName === void 0) {
if (end === -1 && tokenChars[code] === 1) {
if (start === -1) start = i;
} else if (code === 32 || code === 9) {
if (end === -1 && start !== -1) end = i;
} else if (code === 59 || code === 44) {
if (start === -1) {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
if (end === -1) end = i;
push(params, header.slice(start, end), true);
if (code === 44) {
push(offers, extensionName, params);
params = /* @__PURE__ */ Object.create(null);
extensionName = void 0;
}
start = end = -1;
} else if (code === 61 && start !== -1 && end === -1) {
paramName = header.slice(start, i);
start = end = -1;
} else {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
} else {
if (isEscaping) {
if (tokenChars[code] !== 1) {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
if (start === -1) start = i;
else if (!mustUnescape) mustUnescape = true;
isEscaping = false;
} else if (inQuotes) {
if (tokenChars[code] === 1) {
if (start === -1) start = i;
} else if (code === 34 && start !== -1) {
inQuotes = false;
end = i;
} else if (code === 92) {
isEscaping = true;
} else {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
} else if (code === 34 && header.charCodeAt(i - 1) === 61) {
inQuotes = true;
} else if (end === -1 && tokenChars[code] === 1) {
if (start === -1) start = i;
} else if (start !== -1 && (code === 32 || code === 9)) {
if (end === -1) end = i;
} else if (code === 59 || code === 44) {
if (start === -1) {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
if (end === -1) end = i;
let value = header.slice(start, end);
if (mustUnescape) {
value = value.replace(/\\/g, "");
mustUnescape = false;
}
push(params, paramName, value);
if (code === 44) {
push(offers, extensionName, params);
params = /* @__PURE__ */ Object.create(null);
extensionName = void 0;
}
paramName = void 0;
start = end = -1;
} else {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
}
}
if (start === -1 || inQuotes || code === 32 || code === 9) {
throw new SyntaxError("Unexpected end of input");
}
if (end === -1) end = i;
const token = header.slice(start, end);
if (extensionName === void 0) {
push(offers, token, params);
} else {
if (paramName === void 0) {
push(params, token, true);
} else if (mustUnescape) {
push(params, paramName, token.replace(/\\/g, ""));
} else {
push(params, paramName, token);
}
push(offers, extensionName, params);
}
return offers;
}
function format(extensions) {
return Object.keys(extensions).map((extension) => {
let configurations = extensions[extension];
if (!Array.isArray(configurations)) configurations = [configurations];
return configurations.map((params) => {
return [extension].concat(
Object.keys(params).map((k) => {
let values = params[k];
if (!Array.isArray(values)) values = [values];
return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
})
).join("; ");
}).join(", ");
}).join(", ");
}
module2.exports = { format, parse: parse2 };
}
});
// node_modules/ws/lib/websocket.js
var require_websocket = __commonJS({
"node_modules/ws/lib/websocket.js"(exports2, module2) {
"use strict";
var EventEmitter = require("events");
var https = require("https");
var http = require("http");
var net = require("net");
var tls = require("tls");
var { randomBytes, createHash } = require("crypto");
var { Duplex, Readable } = require("stream");
var { URL: URL2 } = require("url");
var PerMessageDeflate = require_permessage_deflate();
var Receiver = require_receiver();
var Sender = require_sender();
var { isBlob } = require_validation();
var {
BINARY_TYPES,
CLOSE_TIMEOUT,
EMPTY_BUFFER,
GUID,
kForOnEventAttribute,
kListener,
kStatusCode,
kWebSocket,
NOOP
} = require_constants();
var {
EventTarget: { addEventListener, removeEventListener }
} = require_event_target();
var { format, parse: parse2 } = require_extension();
var { toBuffer } = require_buffer_util();
var kAborted = /* @__PURE__ */ Symbol("kAborted");
var protocolVersions = [8, 13];
var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
var WebSocket2 = class _WebSocket extends EventEmitter {
/**
* Create a new `WebSocket`.
*
* @param {(String|URL)} address The URL to which to connect
* @param {(String|String[])} [protocols] The subprotocols
* @param {Object} [options] Connection options
*/
constructor(address, protocols, options) {
super();
this._binaryType = BINARY_TYPES[0];
this._closeCode = 1006;
this._closeFrameReceived = false;
this._closeFrameSent = false;
this._closeMessage = EMPTY_BUFFER;
this._closeTimer = null;
this._errorEmitted = false;
this._extensions = {};
this._paused = false;
this._protocol = "";
this._readyState = _WebSocket.CONNECTING;
this._receiver = null;
this._sender = null;
this._socket = null;
if (address !== null) {
this._bufferedAmount = 0;
this._isServer = false;
this._redirects = 0;
if (protocols === void 0) {
protocols = [];
} else if (!Array.isArray(protocols)) {
if (typeof protocols === "object" && protocols !== null) {
options = protocols;
protocols = [];
} else {
protocols = [protocols];
}
}
initAsClient(this, address, protocols, options);
} else {
this._autoPong = options.autoPong;
this._closeTimeout = options.closeTimeout;
this._isServer = true;
}
}
/**
* For historical reasons, the custom "nodebuffer" type is used by the default
* instead of "blob".
*
* @type {String}
*/
get binaryType() {
return this._binaryType;
}
set binaryType(type) {
if (!BINARY_TYPES.includes(type)) return;
this._binaryType = type;
if (this._receiver) this._receiver._binaryType = type;
}
/**
* @type {Number}
*/
get bufferedAmount() {
if (!this._socket) return this._bufferedAmount;
return this._socket._writableState.length + this._sender._bufferedBytes;
}
/**
* @type {String}
*/
get extensions() {
return Object.keys(this._extensions).join();
}
/**
* @type {Boolean}
*/
get isPaused() {
return this._paused;
}
/**
* @type {Function}
*/
/* istanbul ignore next */
get onclose() {
return null;
}
/**
* @type {Function}
*/
/* istanbul ignore next */
get onerror() {
return null;
}
/**
* @type {Function}
*/
/* istanbul ignore next */
get onopen() {
return null;
}
/**
* @type {Function}
*/
/* istanbul ignore next */
get onmessage() {
return null;
}
/**
* @type {String}
*/
get protocol() {
return this._protocol;
}
/**
* @type {Number}
*/
get readyState() {
return this._readyState;
}
/**
* @type {String}
*/
get url() {
return this._url;
}
/**
* Set up the socket and the internal resources.
*
* @param {Duplex} socket The network socket between the server and client
* @param {Buffer} head The first packet of the upgraded stream
* @param {Object} options Options object
* @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
* any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
* multiple times in the same tick
* @param {Function} [options.generateMask] The function used to generate the
* masking key
* @param {Number} [options.maxBufferedChunks=0] The maximum number of
* buffered data chunks
* @param {Number} [options.maxFragments=0] The maximum number of message
* fragments
* @param {Number} [options.maxPayload=0] The maximum allowed message size
* @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
* not to skip UTF-8 validation for text and close messages
* @private
*/
setSocket(socket, head, options) {
const receiver = new Receiver({
allowSynchronousEvents: options.allowSynchronousEvents,
binaryType: this.binaryType,
extensions: this._extensions,
isServer: this._isServer,
maxBufferedChunks: options.maxBufferedChunks,
maxFragments: options.maxFragments,
maxPayload: options.maxPayload,
skipUTF8Validation: options.skipUTF8Validation
});
const sender = new Sender(socket, this._extensions, options.generateMask);
this._receiver = receiver;
this._sender = sender;
this._socket = socket;
receiver[kWebSocket] = this;
sender[kWebSocket] = this;
socket[kWebSocket] = this;
receiver.on("conclude", receiverOnConclude);
receiver.on("drain", receiverOnDrain);
receiver.on("error", receiverOnError);
receiver.on("message", receiverOnMessage);
receiver.on("ping", receiverOnPing);
receiver.on("pong", receiverOnPong);
sender.onerror = senderOnError;
if (socket.setTimeout) socket.setTimeout(0);
if (socket.setNoDelay) socket.setNoDelay();
if (head.length > 0) socket.unshift(head);
socket.on("close", socketOnClose);
socket.on("data", socketOnData);
socket.on("end", socketOnEnd);
socket.on("error", socketOnError);
this._readyState = _WebSocket.OPEN;
this.emit("open");
}
/**
* Emit the `'close'` event.
*
* @private
*/
emitClose() {
if (!this._socket) {
this._readyState = _WebSocket.CLOSED;
this.emit("close", this._closeCode, this._closeMessage);
return;
}
if (this._extensions[PerMessageDeflate.extensionName]) {
this._extensions[PerMessageDeflate.extensionName].cleanup();
}
this._receiver.removeAllListeners();
this._readyState = _WebSocket.CLOSED;
this.emit("close", this._closeCode, this._closeMessage);
}
/**
* Start a closing handshake.
*
* +----------+ +-----------+ +----------+
* - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
* | +----------+ +-----------+ +----------+ |
* +----------+ +-----------+ |
* CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
* +----------+ +-----------+ |
* | | | +---+ |
* +------------------------+-->|fin| - - - -
* | +---+ | +---+
* - - - - -|fin|<---------------------+
* +---+
*
* @param {Number} [code] Status code explaining why the connection is closing
* @param {(String|Buffer)} [data] The reason why the connection is
* closing
* @public
*/
close(code, data) {
if (this.readyState === _WebSocket.CLOSED) return;
if (this.readyState === _WebSocket.CONNECTING) {
const msg = "WebSocket was closed before the connection was established";
abortHandshake(this, this._req, msg);
return;
}
if (this.readyState === _WebSocket.CLOSING) {
if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
this._socket.end();
}
return;
}
this._readyState = _WebSocket.CLOSING;
this._sender.close(code, data, !this._isServer, (err) => {
if (err) return;
this._closeFrameSent = true;
if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
this._socket.end();
}
});
setCloseTimer(this);
}
/**
* Pause the socket.
*
* @public
*/
pause() {
if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
return;
}
this._paused = true;
this._socket.pause();
}
/**
* Send a ping.
*
* @param {*} [data] The data to send
* @param {Boolean} [mask] Indicates whether or not to mask `data`
* @param {Function} [cb] Callback which is executed when the ping is sent
* @public
*/
ping(data, mask, cb) {
if (this.readyState === _WebSocket.CONNECTING) {
throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
}
if (typeof data === "function") {
cb = data;
data = mask = void 0;
} else if (typeof mask === "function") {
cb = mask;
mask = void 0;
}
if (typeof data === "number") data = data.toString();
if (this.readyState !== _WebSocket.OPEN) {
sendAfterClose(this, data, cb);
return;
}
if (mask === void 0) mask = !this._isServer;
this._sender.ping(data || EMPTY_BUFFER, mask, cb);
}
/**
* Send a pong.
*
* @param {*} [data] The data to send
* @param {Boolean} [mask] Indicates whether or not to mask `data`
* @param {Function} [cb] Callback which is executed when the pong is sent
* @public
*/
pong(data, mask, cb) {
if (this.readyState === _WebSocket.CONNECTING) {
throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
}
if (typeof data === "function") {
cb = data;
data = mask = void 0;
} else if (typeof mask === "function") {
cb = mask;
mask = void 0;
}
if (typeof data === "number") data = data.toString();
if (this.readyState !== _WebSocket.OPEN) {
sendAfterClose(this, data, cb);
return;
}
if (mask === void 0) mask = !this._isServer;
this._sender.pong(data || EMPTY_BUFFER, mask, cb);
}
/**
* Resume the socket.
*
* @public
*/
resume() {
if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
return;
}
this._paused = false;
if (!this._receiver._writableState.needDrain) this._socket.resume();
}
/**
* Send a data message.
*
* @param {*} data The message to send
* @param {Object} [options] Options object
* @param {Boolean} [options.binary] Specifies whether `data` is binary or
* text
* @param {Boolean} [options.compress] Specifies whether or not to compress
* `data`
* @param {Boolean} [options.fin=true] Specifies whether the fragment is the
* last one
* @param {Boolean} [options.mask] Specifies whether or not to mask `data`
* @param {Function} [cb] Callback which is executed when data is written out
* @public
*/
send(data, options, cb) {
if (this.readyState === _WebSocket.CONNECTING) {
throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
}
if (typeof options === "function") {
cb = options;
options = {};
}
if (typeof data === "number") data = data.toString();
if (this.readyState !== _WebSocket.OPEN) {
sendAfterClose(this, data, cb);
return;
}
const opts = {
binary: typeof data !== "string",
mask: !this._isServer,
compress: true,
fin: true,
...options
};
if (!this._extensions[PerMessageDeflate.extensionName]) {
opts.compress = false;
}
this._sender.send(data || EMPTY_BUFFER, opts, cb);
}
/**
* Forcibly close the connection.
*
* @public
*/
terminate() {
if (this.readyState === _WebSocket.CLOSED) return;
if (this.readyState === _WebSocket.CONNECTING) {
const msg = "WebSocket was closed before the connection was established";
abortHandshake(this, this._req, msg);
return;
}
if (this._socket) {
this._readyState = _WebSocket.CLOSING;
this._socket.destroy();
}
}
};
Object.defineProperty(WebSocket2, "CONNECTING", {
enumerable: true,
value: readyStates.indexOf("CONNECTING")
});
Object.defineProperty(WebSocket2.prototype, "CONNECTING", {
enumerable: true,
value: readyStates.indexOf("CONNECTING")
});
Object.defineProperty(WebSocket2, "OPEN", {
enumerable: true,
value: readyStates.indexOf("OPEN")
});
Object.defineProperty(WebSocket2.prototype, "OPEN", {
enumerable: true,
value: readyStates.indexOf("OPEN")
});
Object.defineProperty(WebSocket2, "CLOSING", {
enumerable: true,
value: readyStates.indexOf("CLOSING")
});
Object.defineProperty(WebSocket2.prototype, "CLOSING", {
enumerable: true,
value: readyStates.indexOf("CLOSING")
});
Object.defineProperty(WebSocket2, "CLOSED", {
enumerable: true,
value: readyStates.indexOf("CLOSED")
});
Object.defineProperty(WebSocket2.prototype, "CLOSED", {
enumerable: true,
value: readyStates.indexOf("CLOSED")
});
[
"binaryType",
"bufferedAmount",
"extensions",
"isPaused",
"protocol",
"readyState",
"url"
].forEach((property) => {
Object.defineProperty(WebSocket2.prototype, property, { enumerable: true });
});
["open", "error", "close", "message"].forEach((method) => {
Object.defineProperty(WebSocket2.prototype, `on${method}`, {
enumerable: true,
get() {
for (const listener of this.listeners(method)) {
if (listener[kForOnEventAttribute]) return listener[kListener];
}
return null;
},
set(handler) {
for (const listener of this.listeners(method)) {
if (listener[kForOnEventAttribute]) {
this.removeListener(method, listener);
break;
}
}
if (typeof handler !== "function") return;
this.addEventListener(method, handler, {
[kForOnEventAttribute]: true
});
}
});
});
WebSocket2.prototype.addEventListener = addEventListener;
WebSocket2.prototype.removeEventListener = removeEventListener;
module2.exports = WebSocket2;
function initAsClient(websocket, address, protocols, options) {
const opts = {
allowSynchronousEvents: true,
autoPong: true,
closeTimeout: CLOSE_TIMEOUT,
protocolVersion: protocolVersions[1],
maxBufferedChunks: 1024 * 1024,
maxFragments: 128 * 1024,
maxPayload: 100 * 1024 * 1024,
skipUTF8Validation: false,
perMessageDeflate: true,
followRedirects: false,
maxRedirects: 10,
...options,
socketPath: void 0,
hostname: void 0,
protocol: void 0,
timeout: void 0,
method: "GET",
host: void 0,
path: void 0,
port: void 0
};
websocket._autoPong = opts.autoPong;
websocket._closeTimeout = opts.closeTimeout;
if (!protocolVersions.includes(opts.protocolVersion)) {
throw new RangeError(
`Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
);
}
let parsedUrl;
if (address instanceof URL2) {
parsedUrl = address;
} else {
try {
parsedUrl = new URL2(address);
} catch {
throw new SyntaxError(`Invalid URL: ${address}`);
}
}
if (parsedUrl.protocol === "http:") {
parsedUrl.protocol = "ws:";
} else if (parsedUrl.protocol === "https:") {
parsedUrl.protocol = "wss:";
}
websocket._url = parsedUrl.href;
const isSecure = parsedUrl.protocol === "wss:";
const isIpcUrl = parsedUrl.protocol === "ws+unix:";
let invalidUrlMessage;
if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;
} else if (isIpcUrl && !parsedUrl.pathname) {
invalidUrlMessage = "The URL's pathname is empty";
} else if (parsedUrl.hash) {
invalidUrlMessage = "The URL contains a fragment identifier";
}
if (invalidUrlMessage) {
const err = new SyntaxError(invalidUrlMessage);
if (websocket._redirects === 0) {
throw err;
} else {
emitErrorAndClose(websocket, err);
return;
}
}
const defaultPort = isSecure ? 443 : 80;
const key = randomBytes(16).toString("base64");
const request = isSecure ? https.request : http.request;
const protocolSet = /* @__PURE__ */ new Set();
let perMessageDeflate;
opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
opts.defaultPort = opts.defaultPort || defaultPort;
opts.port = parsedUrl.port || defaultPort;
opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
opts.headers = {
...opts.headers,
"Sec-WebSocket-Version": opts.protocolVersion,
"Sec-WebSocket-Key": key,
Connection: "Upgrade",
Upgrade: "websocket"
};
opts.path = parsedUrl.pathname + parsedUrl.search;
opts.timeout = opts.handshakeTimeout;
if (opts.perMessageDeflate) {
perMessageDeflate = new PerMessageDeflate({
...opts.perMessageDeflate,
isServer: false,
maxPayload: opts.maxPayload
});
opts.headers["Sec-WebSocket-Extensions"] = format({
[PerMessageDeflate.extensionName]: perMessageDeflate.offer()
});
}
if (protocols.length) {
for (const protocol of protocols) {
if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
throw new SyntaxError(
"An invalid or duplicated subprotocol was specified"
);
}
protocolSet.add(protocol);
}
opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
}
if (opts.origin) {
if (opts.protocolVersion < 13) {
opts.headers["Sec-WebSocket-Origin"] = opts.origin;
} else {
opts.headers.Origin = opts.origin;
}
}
if (parsedUrl.username || parsedUrl.password) {
opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
}
if (isIpcUrl) {
const parts = opts.path.split(":");
opts.socketPath = parts[0];
opts.path = parts[1];
}
let req;
if (opts.followRedirects) {
if (websocket._redirects === 0) {
websocket._originalIpc = isIpcUrl;
websocket._originalSecure = isSecure;
websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
const headers = options && options.headers;
options = { ...options, headers: {} };
if (headers) {
for (const [key2, value] of Object.entries(headers)) {
options.headers[key2.toLowerCase()] = value;
}
}
} else if (websocket.listenerCount("redirect") === 0) {
const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
if (!isSameHost || websocket._originalSecure && !isSecure) {
delete opts.headers.authorization;
delete opts.headers.cookie;
if (!isSameHost) delete opts.headers.host;
opts.auth = void 0;
}
}
if (opts.auth && !options.headers.authorization) {
options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
}
req = websocket._req = request(opts);
if (websocket._redirects) {
websocket.emit("redirect", websocket.url, req);
}
} else {
req = websocket._req = request(opts);
}
if (opts.timeout) {
req.on("timeout", () => {
abortHandshake(websocket, req, "Opening handshake has timed out");
});
}
req.on("error", (err) => {
if (req === null || req[kAborted]) return;
req = websocket._req = null;
emitErrorAndClose(websocket, err);
});
req.on("response", (res) => {
const location = res.headers.location;
const statusCode = res.statusCode;
if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
if (++websocket._redirects > opts.maxRedirects) {
abortHandshake(websocket, req, "Maximum redirects exceeded");
return;
}
req.abort();
let addr;
try {
addr = new URL2(location, address);
} catch (e) {
const err = new SyntaxError(`Invalid URL: ${location}`);
emitErrorAndClose(websocket, err);
return;
}
initAsClient(websocket, addr, protocols, options);
} else if (!websocket.emit("unexpected-response", req, res)) {
abortHandshake(
websocket,
req,
`Unexpected server response: ${res.statusCode}`
);
}
});
req.on("upgrade", (res, socket, head) => {
websocket.emit("upgrade", res);
if (websocket.readyState !== WebSocket2.CONNECTING) return;
req = websocket._req = null;
const upgrade = res.headers.upgrade;
if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
abortHandshake(websocket, socket, "Invalid Upgrade header");
return;
}
const digest = createHash("sha1").update(key + GUID).digest("base64");
if (res.headers["sec-websocket-accept"] !== digest) {
abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
return;
}
const serverProt = res.headers["sec-websocket-protocol"];
let protError;
if (serverProt !== void 0) {
if (!protocolSet.size) {
protError = "Server sent a subprotocol but none was requested";
} else if (!protocolSet.has(serverProt)) {
protError = "Server sent an invalid subprotocol";
}
} else if (protocolSet.size) {
protError = "Server sent no subprotocol";
}
if (protError) {
abortHandshake(websocket, socket, protError);
return;
}
if (serverProt) websocket._protocol = serverProt;
const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
if (secWebSocketExtensions !== void 0) {
if (!perMessageDeflate) {
const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
abortHandshake(websocket, socket, message);
return;
}
let extensions;
try {
extensions = parse2(secWebSocketExtensions);
} catch (err) {
const message = "Invalid Sec-WebSocket-Extensions header";
abortHandshake(websocket, socket, message);
return;
}
const extensionNames = Object.keys(extensions);
if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) {
const message = "Server indicated an extension that was not requested";
abortHandshake(websocket, socket, message);
return;
}
try {
perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
} catch (err) {
const message = "Invalid Sec-WebSocket-Extensions header";
abortHandshake(websocket, socket, message);
return;
}
websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
}
websocket.setSocket(socket, head, {
allowSynchronousEvents: opts.allowSynchronousEvents,
generateMask: opts.generateMask,
maxBufferedChunks: opts.maxBufferedChunks,
maxFragments: opts.maxFragments,
maxPayload: opts.maxPayload,
skipUTF8Validation: opts.skipUTF8Validation
});
});
if (opts.finishRequest) {
opts.finishRequest(req, websocket);
} else {
req.end();
}
}
function emitErrorAndClose(websocket, err) {
websocket._readyState = WebSocket2.CLOSING;
websocket._errorEmitted = true;
websocket.emit("error", err);
websocket.emitClose();
}
function netConnect(options) {
options.path = options.socketPath;
return net.connect(options);
}
function tlsConnect(options) {
options.path = void 0;
if (!options.servername && options.servername !== "") {
options.servername = net.isIP(options.host) ? "" : options.host;
}
return tls.connect(options);
}
function abortHandshake(websocket, stream, message) {
websocket._readyState = WebSocket2.CLOSING;
const err = new Error(message);
Error.captureStackTrace(err, abortHandshake);
if (stream.setHeader) {
stream[kAborted] = true;
stream.abort();
if (stream.socket && !stream.socket.destroyed) {
stream.socket.destroy();
}
process.nextTick(emitErrorAndClose, websocket, err);
} else {
stream.destroy(err);
stream.once("error", websocket.emit.bind(websocket, "error"));
stream.once("close", websocket.emitClose.bind(websocket));
}
}
function sendAfterClose(websocket, data, cb) {
if (data) {
const length = isBlob(data) ? data.size : toBuffer(data).length;
if (websocket._socket) websocket._sender._bufferedBytes += length;
else websocket._bufferedAmount += length;
}
if (cb) {
const err = new Error(
`WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
);
process.nextTick(cb, err);
}
}
function receiverOnConclude(code, reason) {
const websocket = this[kWebSocket];
websocket._closeFrameReceived = true;
websocket._closeMessage = reason;
websocket._closeCode = code;
if (websocket._socket[kWebSocket] === void 0) return;
websocket._socket.removeListener("data", socketOnData);
process.nextTick(resume, websocket._socket);
if (code === 1005) websocket.close();
else websocket.close(code, reason);
}
function receiverOnDrain() {
const websocket = this[kWebSocket];
if (!websocket.isPaused) websocket._socket.resume();
}
function receiverOnError(err) {
const websocket = this[kWebSocket];
if (websocket._socket[kWebSocket] !== void 0) {
websocket._socket.removeListener("data", socketOnData);
process.nextTick(resume, websocket._socket);
websocket.close(err[kStatusCode]);
}
if (!websocket._errorEmitted) {
websocket._errorEmitted = true;
websocket.emit("error", err);
}
}
function receiverOnFinish() {
this[kWebSocket].emitClose();
}
function receiverOnMessage(data, isBinary) {
this[kWebSocket].emit("message", data, isBinary);
}
function receiverOnPing(data) {
const websocket = this[kWebSocket];
if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
websocket.emit("ping", data);
}
function receiverOnPong(data) {
this[kWebSocket].emit("pong", data);
}
function resume(stream) {
stream.resume();
}
function senderOnError(err) {
const websocket = this[kWebSocket];
if (websocket.readyState === WebSocket2.CLOSED) return;
if (websocket.readyState === WebSocket2.OPEN) {
websocket._readyState = WebSocket2.CLOSING;
setCloseTimer(websocket);
}
this._socket.end();
if (!websocket._errorEmitted) {
websocket._errorEmitted = true;
websocket.emit("error", err);
}
}
function setCloseTimer(websocket) {
websocket._closeTimer = setTimeout(
websocket._socket.destroy.bind(websocket._socket),
websocket._closeTimeout
);
}
function socketOnClose() {
const websocket = this[kWebSocket];
this.removeListener("close", socketOnClose);
this.removeListener("data", socketOnData);
this.removeListener("end", socketOnEnd);
websocket._readyState = WebSocket2.CLOSING;
if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
const chunk = this.read(this._readableState.length);
websocket._receiver.write(chunk);
}
websocket._receiver.end();
this[kWebSocket] = void 0;
clearTimeout(websocket._closeTimer);
if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
websocket.emitClose();
} else {
websocket._receiver.on("error", receiverOnFinish);
websocket._receiver.on("finish", receiverOnFinish);
}
}
function socketOnData(chunk) {
if (!this[kWebSocket]._receiver.write(chunk)) {
this.pause();
}
}
function socketOnEnd() {
const websocket = this[kWebSocket];
websocket._readyState = WebSocket2.CLOSING;
websocket._receiver.end();
this.end();
}
function socketOnError() {
const websocket = this[kWebSocket];
this.removeListener("error", socketOnError);
this.on("error", NOOP);
if (websocket) {
websocket._readyState = WebSocket2.CLOSING;
this.destroy();
}
}
}
});
// node_modules/ws/lib/stream.js
var require_stream = __commonJS({
"node_modules/ws/lib/stream.js"(exports2, module2) {
"use strict";
var WebSocket2 = require_websocket();
var { Duplex } = require("stream");
function emitClose(stream) {
stream.emit("close");
}
function duplexOnEnd() {
if (!this.destroyed && this._writableState.finished) {
this.destroy();
}
}
function duplexOnError(err) {
this.removeListener("error", duplexOnError);
this.destroy();
if (this.listenerCount("error") === 0) {
this.emit("error", err);
}
}
function createWebSocketStream(ws, options) {
let terminateOnDestroy = true;
const duplex = new Duplex({
...options,
autoDestroy: false,
emitClose: false,
objectMode: false,
writableObjectMode: false
});
ws.on("message", function message(msg, isBinary) {
const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
if (!duplex.push(data)) ws.pause();
});
ws.once("error", function error(err) {
if (duplex.destroyed) return;
terminateOnDestroy = false;
duplex.destroy(err);
});
ws.once("close", function close() {
if (duplex.destroyed) return;
duplex.push(null);
});
duplex._destroy = function(err, callback) {
if (ws.readyState === ws.CLOSED) {
callback(err);
process.nextTick(emitClose, duplex);
return;
}
let called = false;
ws.once("error", function error(err2) {
called = true;
callback(err2);
});
ws.once("close", function close() {
if (!called) callback(err);
process.nextTick(emitClose, duplex);
});
if (terminateOnDestroy) ws.terminate();
};
duplex._final = function(callback) {
if (ws.readyState === ws.CONNECTING) {
ws.once("open", function open() {
duplex._final(callback);
});
return;
}
if (ws._socket === null) return;
if (ws._socket._writableState.finished) {
callback();
if (duplex._readableState.endEmitted) duplex.destroy();
} else {
ws._socket.once("finish", function finish() {
callback();
});
ws.close();
}
};
duplex._read = function() {
if (ws.isPaused) ws.resume();
};
duplex._write = function(chunk, encoding, callback) {
if (ws.readyState === ws.CONNECTING) {
ws.once("open", function open() {
duplex._write(chunk, encoding, callback);
});
return;
}
ws.send(chunk, callback);
};
duplex.on("end", duplexOnEnd);
duplex.on("error", duplexOnError);
return duplex;
}
module2.exports = createWebSocketStream;
}
});
// node_modules/ws/lib/subprotocol.js
var require_subprotocol = __commonJS({
"node_modules/ws/lib/subprotocol.js"(exports2, module2) {
"use strict";
var { tokenChars } = require_validation();
function parse2(header) {
const protocols = /* @__PURE__ */ new Set();
let start = -1;
let end = -1;
let i = 0;
for (i; i < header.length; i++) {
const code = header.charCodeAt(i);
if (end === -1 && tokenChars[code] === 1) {
if (start === -1) start = i;
} else if (i !== 0 && (code === 32 || code === 9)) {
if (end === -1 && start !== -1) end = i;
} else if (code === 44) {
if (start === -1) {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
if (end === -1) end = i;
const protocol2 = header.slice(start, end);
if (protocols.has(protocol2)) {
throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
}
protocols.add(protocol2);
start = end = -1;
} else {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
}
if (start === -1 || end !== -1) {
throw new SyntaxError("Unexpected end of input");
}
const protocol = header.slice(start, i);
if (protocols.has(protocol)) {
throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
}
protocols.add(protocol);
return protocols;
}
module2.exports = { parse: parse2 };
}
});
// node_modules/ws/lib/websocket-server.js
var require_websocket_server = __commonJS({
"node_modules/ws/lib/websocket-server.js"(exports2, module2) {
"use strict";
var EventEmitter = require("events");
var http = require("http");
var { Duplex } = require("stream");
var { createHash } = require("crypto");
var extension = require_extension();
var PerMessageDeflate = require_permessage_deflate();
var subprotocol = require_subprotocol();
var WebSocket2 = require_websocket();
var { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
var RUNNING = 0;
var CLOSING = 1;
var CLOSED = 2;
var WebSocketServer = class extends EventEmitter {
/**
* Create a `WebSocketServer` instance.
*
* @param {Object} options Configuration options
* @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
* any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
* multiple times in the same tick
* @param {Boolean} [options.autoPong=true] Specifies whether or not to
* automatically send a pong in response to a ping
* @param {Number} [options.backlog=511] The maximum length of the queue of
* pending connections
* @param {Boolean} [options.clientTracking=true] Specifies whether or not to
* track clients
* @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
* wait for the closing handshake to finish after `websocket.close()` is
* called
* @param {Function} [options.handleProtocols] A hook to handle protocols
* @param {String} [options.host] The hostname where to bind the server
* @param {Number} [options.maxBufferedChunks=1048576] The maximum number of
* buffered data chunks
* @param {Number} [options.maxFragments=131072] The maximum number of message
* fragments
* @param {Number} [options.maxPayload=104857600] The maximum allowed message
* size
* @param {Boolean} [options.noServer=false] Enable no server mode
* @param {String} [options.path] Accept only connections matching this path
* @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
* permessage-deflate
* @param {Number} [options.port] The port where to bind the server
* @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
* server to use
* @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
* not to skip UTF-8 validation for text and close messages
* @param {Function} [options.verifyClient] A hook to reject connections
* @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
* class to use. It must be the `WebSocket` class or class that extends it
* @param {Function} [callback] A listener for the `listening` event
*/
constructor(options, callback) {
super();
options = {
allowSynchronousEvents: true,
autoPong: true,
maxBufferedChunks: 1024 * 1024,
maxFragments: 128 * 1024,
maxPayload: 100 * 1024 * 1024,
skipUTF8Validation: false,
perMessageDeflate: false,
handleProtocols: null,
clientTracking: true,
closeTimeout: CLOSE_TIMEOUT,
verifyClient: null,
noServer: false,
backlog: null,
// use default (511 as implemented in net.js)
server: null,
host: null,
path: null,
port: null,
WebSocket: WebSocket2,
...options
};
if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
throw new TypeError(
'One and only one of the "port", "server", or "noServer" options must be specified'
);
}
if (options.port != null) {
this._server = http.createServer((req, res) => {
const body = http.STATUS_CODES[426];
res.writeHead(426, {
"Content-Length": body.length,
"Content-Type": "text/plain"
});
res.end(body);
});
this._server.listen(
options.port,
options.host,
options.backlog,
callback
);
} else if (options.server) {
this._server = options.server;
}
if (this._server) {
const emitConnection = this.emit.bind(this, "connection");
this._removeListeners = addListeners(this._server, {
listening: this.emit.bind(this, "listening"),
error: this.emit.bind(this, "error"),
upgrade: (req, socket, head) => {
this.handleUpgrade(req, socket, head, emitConnection);
}
});
}
if (options.perMessageDeflate === true) options.perMessageDeflate = {};
if (options.clientTracking) {
this.clients = /* @__PURE__ */ new Set();
this._shouldEmitClose = false;
}
this.options = options;
this._state = RUNNING;
}
/**
* Returns the bound address, the address family name, and port of the server
* as reported by the operating system if listening on an IP socket.
* If the server is listening on a pipe or UNIX domain socket, the name is
* returned as a string.
*
* @return {(Object|String|null)} The address of the server
* @public
*/
address() {
if (this.options.noServer) {
throw new Error('The server is operating in "noServer" mode');
}
if (!this._server) return null;
return this._server.address();
}
/**
* Stop the server from accepting new connections and emit the `'close'` event
* when all existing connections are closed.
*
* @param {Function} [cb] A one-time listener for the `'close'` event
* @public
*/
close(cb) {
if (this._state === CLOSED) {
if (cb) {
this.once("close", () => {
cb(new Error("The server is not running"));
});
}
process.nextTick(emitClose, this);
return;
}
if (cb) this.once("close", cb);
if (this._state === CLOSING) return;
this._state = CLOSING;
if (this.options.noServer || this.options.server) {
if (this._server) {
this._removeListeners();
this._removeListeners = this._server = null;
}
if (this.clients) {
if (!this.clients.size) {
process.nextTick(emitClose, this);
} else {
this._shouldEmitClose = true;
}
} else {
process.nextTick(emitClose, this);
}
} else {
const server = this._server;
this._removeListeners();
this._removeListeners = this._server = null;
server.close(() => {
emitClose(this);
});
}
}
/**
* See if a given request should be handled by this server instance.
*
* @param {http.IncomingMessage} req Request object to inspect
* @return {Boolean} `true` if the request is valid, else `false`
* @public
*/
shouldHandle(req) {
if (this.options.path) {
const index = req.url.indexOf("?");
const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
if (pathname !== this.options.path) return false;
}
return true;
}
/**
* Handle a HTTP Upgrade request.
*
* @param {http.IncomingMessage} req The request object
* @param {Duplex} socket The network socket between the server and client
* @param {Buffer} head The first packet of the upgraded stream
* @param {Function} cb Callback
* @public
*/
handleUpgrade(req, socket, head, cb) {
socket.on("error", socketOnError);
const key = req.headers["sec-websocket-key"];
const upgrade = req.headers.upgrade;
const version = +req.headers["sec-websocket-version"];
if (req.method !== "GET") {
const message = "Invalid HTTP method";
abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
return;
}
if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
const message = "Invalid Upgrade header";
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
return;
}
if (key === void 0 || !keyRegex.test(key)) {
const message = "Missing or invalid Sec-WebSocket-Key header";
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
return;
}
if (version !== 13 && version !== 8) {
const message = "Missing or invalid Sec-WebSocket-Version header";
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
"Sec-WebSocket-Version": "13, 8"
});
return;
}
if (!this.shouldHandle(req)) {
abortHandshake(socket, 400);
return;
}
const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
let protocols = /* @__PURE__ */ new Set();
if (secWebSocketProtocol !== void 0) {
try {
protocols = subprotocol.parse(secWebSocketProtocol);
} catch (err) {
const message = "Invalid Sec-WebSocket-Protocol header";
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
return;
}
}
const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
const extensions = {};
if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
const perMessageDeflate = new PerMessageDeflate({
...this.options.perMessageDeflate,
isServer: true,
maxPayload: this.options.maxPayload
});
try {
const offers = extension.parse(secWebSocketExtensions);
if (offers[PerMessageDeflate.extensionName]) {
perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
}
} catch (err) {
const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
return;
}
}
if (this.options.verifyClient) {
const info = {
origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
secure: !!(req.socket.authorized || req.socket.encrypted),
req
};
if (this.options.verifyClient.length === 2) {
this.options.verifyClient(info, (verified, code, message, headers) => {
if (!verified) {
return abortHandshake(socket, code || 401, message, headers);
}
this.completeUpgrade(
extensions,
key,
protocols,
req,
socket,
head,
cb
);
});
return;
}
if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
}
this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
}
/**
* Upgrade the connection to WebSocket.
*
* @param {Object} extensions The accepted extensions
* @param {String} key The value of the `Sec-WebSocket-Key` header
* @param {Set} protocols The subprotocols
* @param {http.IncomingMessage} req The request object
* @param {Duplex} socket The network socket between the server and client
* @param {Buffer} head The first packet of the upgraded stream
* @param {Function} cb Callback
* @throws {Error} If called more than once with the same socket
* @private
*/
completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
if (!socket.readable || !socket.writable) return socket.destroy();
if (socket[kWebSocket]) {
throw new Error(
"server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
);
}
if (this._state > RUNNING) return abortHandshake(socket, 503);
const digest = createHash("sha1").update(key + GUID).digest("base64");
const headers = [
"HTTP/1.1 101 Switching Protocols",
"Upgrade: websocket",
"Connection: Upgrade",
`Sec-WebSocket-Accept: ${digest}`
];
const ws = new this.options.WebSocket(null, void 0, this.options);
if (protocols.size) {
const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
if (protocol) {
headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
ws._protocol = protocol;
}
}
if (extensions[PerMessageDeflate.extensionName]) {
const params = extensions[PerMessageDeflate.extensionName].params;
const value = extension.format({
[PerMessageDeflate.extensionName]: [params]
});
headers.push(`Sec-WebSocket-Extensions: ${value}`);
ws._extensions = extensions;
}
this.emit("headers", headers, req);
socket.write(headers.concat("\r\n").join("\r\n"));
socket.removeListener("error", socketOnError);
ws.setSocket(socket, head, {
allowSynchronousEvents: this.options.allowSynchronousEvents,
maxBufferedChunks: this.options.maxBufferedChunks,
maxFragments: this.options.maxFragments,
maxPayload: this.options.maxPayload,
skipUTF8Validation: this.options.skipUTF8Validation
});
if (this.clients) {
this.clients.add(ws);
ws.on("close", () => {
this.clients.delete(ws);
if (this._shouldEmitClose && !this.clients.size) {
process.nextTick(emitClose, this);
}
});
}
cb(ws, req);
}
};
module2.exports = WebSocketServer;
function addListeners(server, map) {
for (const event of Object.keys(map)) server.on(event, map[event]);
return function removeListeners() {
for (const event of Object.keys(map)) {
server.removeListener(event, map[event]);
}
};
}
function emitClose(server) {
server._state = CLOSED;
server.emit("close");
}
function socketOnError() {
this.destroy();
}
function abortHandshake(socket, code, message, headers) {
message = message || http.STATUS_CODES[code];
headers = {
Connection: "close",
"Content-Type": "text/html",
"Content-Length": Buffer.byteLength(message),
...headers
};
socket.once("finish", socket.destroy);
socket.end(
`HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
);
}
function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
if (server.listenerCount("wsClientError")) {
const err = new Error(message);
Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
server.emit("wsClientError", err, socket, req);
} else {
abortHandshake(socket, code, message, headers);
}
}
}
});
// node_modules/ws/index.js
var require_ws = __commonJS({
"node_modules/ws/index.js"(exports2, module2) {
"use strict";
var createWebSocketStream = require_stream();
var extension = require_extension();
var PerMessageDeflate = require_permessage_deflate();
var Receiver = require_receiver();
var Sender = require_sender();
var subprotocol = require_subprotocol();
var WebSocket2 = require_websocket();
var WebSocketServer = require_websocket_server();
WebSocket2.createWebSocketStream = createWebSocketStream;
WebSocket2.extension = extension;
WebSocket2.PerMessageDeflate = PerMessageDeflate;
WebSocket2.Receiver = Receiver;
WebSocket2.Sender = Sender;
WebSocket2.Server = WebSocketServer;
WebSocket2.subprotocol = subprotocol;
WebSocket2.WebSocket = WebSocket2;
WebSocket2.WebSocketServer = WebSocketServer;
module2.exports = WebSocket2;
}
});
// node_modules/@lmstudio/lms-isomorphic/dist/cjs/index/WebSocket.js
var require_WebSocket = __commonJS({
"node_modules/@lmstudio/lms-isomorphic/dist/cjs/index/WebSocket.js"(exports2) {
"use strict";
var __importDefault = exports2 && exports2.__importDefault || function(mod) {
return mod && mod.__esModule ? mod : { "default": mod };
};
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.WebSocket = void 0;
var ws_1 = __importDefault(require_ws());
exports2.WebSocket = ws_1.default;
}
});
// node_modules/@lmstudio/lms-isomorphic/dist/cjs/index.js
var require_cjs = __commonJS({
"node_modules/@lmstudio/lms-isomorphic/dist/cjs/index.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.WebSocket = exports2.terminalSize = exports2.readFileAsBase64 = exports2.generateRandomBase64 = void 0;
var generateRandomBase64_js_1 = require_generateRandomBase64();
Object.defineProperty(exports2, "generateRandomBase64", { enumerable: true, get: function() {
return generateRandomBase64_js_1.generateRandomBase64;
} });
var readFileAsBase64_js_1 = require_readFileAsBase64();
Object.defineProperty(exports2, "readFileAsBase64", { enumerable: true, get: function() {
return readFileAsBase64_js_1.readFileAsBase64;
} });
var terminalSize_js_1 = require_terminalSize();
Object.defineProperty(exports2, "terminalSize", { enumerable: true, get: function() {
return terminalSize_js_1.terminalSize;
} });
var WebSocket_js_1 = require_WebSocket();
Object.defineProperty(exports2, "WebSocket", { enumerable: true, get: function() {
return WebSocket_js_1.WebSocket;
} });
}
});
// src/index.ts
var index_exports = {};
__export(index_exports, {
main: () => main
});
module.exports = __toCommonJS(index_exports);
// src/config.ts
var import_node_path = __toESM(require("node:path"), 1);
var import_node_os = __toESM(require("node:os"), 1);
var import_promises = __toESM(require("node:fs/promises"), 1);
var import_node_fs = require("node:fs");
var DEFAULT_CONFIG = {
dataRoot: "~/.lmstudio/plugins/data-plugin/data",
csv: {
delimiter: ",",
encoding: "utf-8",
bom: true,
quoteChar: '"',
escapeChar: '"'
},
ui: {
locale: "en",
dateFormat: "ISO"
},
performance: {
cacheSize: 10,
maxRowsPerPage: 100,
maxBatchInsert: 1e3
}
};
var _cachedConfig = null;
function resolvePath(p) {
if (p.startsWith("~/")) {
return import_node_path.default.join(import_node_os.default.homedir(), p.slice(2));
}
return import_node_path.default.resolve(p);
}
function dataRootParentDir(dataRoot) {
return import_node_path.default.dirname(resolvePath(dataRoot));
}
function configFilePath(dataRoot) {
return import_node_path.default.join(dataRootParentDir(dataRoot), "data-plugin.config.json");
}
async function loadConfigFromFile() {
try {
const filePath = configFilePath(DEFAULT_CONFIG.dataRoot);
const raw = await import_promises.default.readFile(filePath, "utf-8");
return JSON.parse(raw);
} catch {
return null;
}
}
async function loadConfig() {
const file = await loadConfigFromFile();
if (!file) return { ...DEFAULT_CONFIG };
return {
...DEFAULT_CONFIG,
...file,
csv: { ...DEFAULT_CONFIG.csv, ...file.csv ?? {} },
ui: { ...DEFAULT_CONFIG.ui, ...file.ui ?? {} },
performance: { ...DEFAULT_CONFIG.performance, ...file.performance ?? {} }
};
}
function getConfig() {
if (!_cachedConfig) {
_cachedConfig = { ...DEFAULT_CONFIG };
}
return _cachedConfig;
}
async function saveConfig(config) {
const filePath = configFilePath(config.dataRoot);
const dir = import_node_path.default.dirname(filePath);
if (!(0, import_node_fs.existsSync)(dir)) {
await import_promises.default.mkdir(dir, { recursive: true });
}
await import_promises.default.writeFile(filePath, JSON.stringify(config, null, 2), "utf-8");
_cachedConfig = config;
}
function getDataRoot() {
return resolvePath(getConfig().dataRoot);
}
async function initDataRoot(dataRoot) {
const resolved = resolvePath(dataRoot);
const databasesDir2 = import_node_path.default.join(resolved, "databases");
if (!(0, import_node_fs.existsSync)(resolved)) {
await import_promises.default.mkdir(resolved, { recursive: true });
}
if (!(0, import_node_fs.existsSync)(databasesDir2)) {
await import_promises.default.mkdir(databasesDir2, { recursive: true });
}
}
// node_modules/zod/v3/external.js
var external_exports = {};
__export(external_exports, {
BRAND: () => BRAND,
DIRTY: () => DIRTY,
EMPTY_PATH: () => EMPTY_PATH,
INVALID: () => INVALID,
NEVER: () => NEVER,
OK: () => OK,
ParseStatus: () => ParseStatus,
Schema: () => ZodType,
ZodAny: () => ZodAny,
ZodArray: () => ZodArray,
ZodBigInt: () => ZodBigInt,
ZodBoolean: () => ZodBoolean,
ZodBranded: () => ZodBranded,
ZodCatch: () => ZodCatch,
ZodDate: () => ZodDate,
ZodDefault: () => ZodDefault,
ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
ZodEffects: () => ZodEffects,
ZodEnum: () => ZodEnum,
ZodError: () => ZodError,
ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
ZodFunction: () => ZodFunction,
ZodIntersection: () => ZodIntersection,
ZodIssueCode: () => ZodIssueCode,
ZodLazy: () => ZodLazy,
ZodLiteral: () => ZodLiteral,
ZodMap: () => ZodMap,
ZodNaN: () => ZodNaN,
ZodNativeEnum: () => ZodNativeEnum,
ZodNever: () => ZodNever,
ZodNull: () => ZodNull,
ZodNullable: () => ZodNullable,
ZodNumber: () => ZodNumber,
ZodObject: () => ZodObject,
ZodOptional: () => ZodOptional,
ZodParsedType: () => ZodParsedType,
ZodPipeline: () => ZodPipeline,
ZodPromise: () => ZodPromise,
ZodReadonly: () => ZodReadonly,
ZodRecord: () => ZodRecord,
ZodSchema: () => ZodType,
ZodSet: () => ZodSet,
ZodString: () => ZodString,
ZodSymbol: () => ZodSymbol,
ZodTransformer: () => ZodEffects,
ZodTuple: () => ZodTuple,
ZodType: () => ZodType,
ZodUndefined: () => ZodUndefined,
ZodUnion: () => ZodUnion,
ZodUnknown: () => ZodUnknown,
ZodVoid: () => ZodVoid,
addIssueToContext: () => addIssueToContext,
any: () => anyType,
array: () => arrayType,
bigint: () => bigIntType,
boolean: () => booleanType,
coerce: () => coerce,
custom: () => custom,
date: () => dateType,
datetimeRegex: () => datetimeRegex,
defaultErrorMap: () => en_default,
discriminatedUnion: () => discriminatedUnionType,
effect: () => effectsType,
enum: () => enumType,
function: () => functionType,
getErrorMap: () => getErrorMap,
getParsedType: () => getParsedType,
instanceof: () => instanceOfType,
intersection: () => intersectionType,
isAborted: () => isAborted,
isAsync: () => isAsync,
isDirty: () => isDirty,
isValid: () => isValid,
late: () => late,
lazy: () => lazyType,
literal: () => literalType,
makeIssue: () => makeIssue,
map: () => mapType,
nan: () => nanType,
nativeEnum: () => nativeEnumType,
never: () => neverType,
null: () => nullType,
nullable: () => nullableType,
number: () => numberType,
object: () => objectType,
objectUtil: () => objectUtil,
oboolean: () => oboolean,
onumber: () => onumber,
optional: () => optionalType,
ostring: () => ostring,
pipeline: () => pipelineType,
preprocess: () => preprocessType,
promise: () => promiseType,
quotelessJson: () => quotelessJson,
record: () => recordType,
set: () => setType,
setErrorMap: () => setErrorMap,
strictObject: () => strictObjectType,
string: () => stringType,
symbol: () => symbolType,
transformer: () => effectsType,
tuple: () => tupleType,
undefined: () => undefinedType,
union: () => unionType,
unknown: () => unknownType,
util: () => util,
void: () => voidType
});
// node_modules/zod/v3/helpers/util.js
var util;
(function(util2) {
util2.assertEqual = (_) => {
};
function assertIs(_arg) {
}
util2.assertIs = assertIs;
function assertNever(_x) {
throw new Error();
}
util2.assertNever = assertNever;
util2.arrayToEnum = (items) => {
const obj = {};
for (const item of items) {
obj[item] = item;
}
return obj;
};
util2.getValidEnumValues = (obj) => {
const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
const filtered = {};
for (const k of validKeys) {
filtered[k] = obj[k];
}
return util2.objectValues(filtered);
};
util2.objectValues = (obj) => {
return util2.objectKeys(obj).map(function(e) {
return obj[e];
});
};
util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
const keys = [];
for (const key in object) {
if (Object.prototype.hasOwnProperty.call(object, key)) {
keys.push(key);
}
}
return keys;
};
util2.find = (arr, checker) => {
for (const item of arr) {
if (checker(item))
return item;
}
return void 0;
};
util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
function joinValues(array, separator = " | ") {
return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
}
util2.joinValues = joinValues;
util2.jsonStringifyReplacer = (_, value) => {
if (typeof value === "bigint") {
return value.toString();
}
return value;
};
})(util || (util = {}));
var objectUtil;
(function(objectUtil2) {
objectUtil2.mergeShapes = (first, second) => {
return {
...first,
...second
// second overwrites first
};
};
})(objectUtil || (objectUtil = {}));
var ZodParsedType = util.arrayToEnum([
"string",
"nan",
"number",
"integer",
"float",
"boolean",
"date",
"bigint",
"symbol",
"function",
"undefined",
"null",
"array",
"object",
"unknown",
"promise",
"void",
"never",
"map",
"set"
]);
var getParsedType = (data) => {
const t = typeof data;
switch (t) {
case "undefined":
return ZodParsedType.undefined;
case "string":
return ZodParsedType.string;
case "number":
return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
case "boolean":
return ZodParsedType.boolean;
case "function":
return ZodParsedType.function;
case "bigint":
return ZodParsedType.bigint;
case "symbol":
return ZodParsedType.symbol;
case "object":
if (Array.isArray(data)) {
return ZodParsedType.array;
}
if (data === null) {
return ZodParsedType.null;
}
if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
return ZodParsedType.promise;
}
if (typeof Map !== "undefined" && data instanceof Map) {
return ZodParsedType.map;
}
if (typeof Set !== "undefined" && data instanceof Set) {
return ZodParsedType.set;
}
if (typeof Date !== "undefined" && data instanceof Date) {
return ZodParsedType.date;
}
return ZodParsedType.object;
default:
return ZodParsedType.unknown;
}
};
// node_modules/zod/v3/ZodError.js
var ZodIssueCode = util.arrayToEnum([
"invalid_type",
"invalid_literal",
"custom",
"invalid_union",
"invalid_union_discriminator",
"invalid_enum_value",
"unrecognized_keys",
"invalid_arguments",
"invalid_return_type",
"invalid_date",
"invalid_string",
"too_small",
"too_big",
"invalid_intersection_types",
"not_multiple_of",
"not_finite"
]);
var quotelessJson = (obj) => {
const json = JSON.stringify(obj, null, 2);
return json.replace(/"([^"]+)":/g, "$1:");
};
var ZodError = class _ZodError extends Error {
get errors() {
return this.issues;
}
constructor(issues) {
super();
this.issues = [];
this.addIssue = (sub) => {
this.issues = [...this.issues, sub];
};
this.addIssues = (subs = []) => {
this.issues = [...this.issues, ...subs];
};
const actualProto = new.target.prototype;
if (Object.setPrototypeOf) {
Object.setPrototypeOf(this, actualProto);
} else {
this.__proto__ = actualProto;
}
this.name = "ZodError";
this.issues = issues;
}
format(_mapper) {
const mapper = _mapper || function(issue) {
return issue.message;
};
const fieldErrors = { _errors: [] };
const processError = (error) => {
for (const issue of error.issues) {
if (issue.code === "invalid_union") {
issue.unionErrors.map(processError);
} else if (issue.code === "invalid_return_type") {
processError(issue.returnTypeError);
} else if (issue.code === "invalid_arguments") {
processError(issue.argumentsError);
} else if (issue.path.length === 0) {
fieldErrors._errors.push(mapper(issue));
} else {
let curr = fieldErrors;
let i = 0;
while (i < issue.path.length) {
const el = issue.path[i];
const terminal = i === issue.path.length - 1;
if (!terminal) {
curr[el] = curr[el] || { _errors: [] };
} else {
curr[el] = curr[el] || { _errors: [] };
curr[el]._errors.push(mapper(issue));
}
curr = curr[el];
i++;
}
}
}
};
processError(this);
return fieldErrors;
}
static assert(value) {
if (!(value instanceof _ZodError)) {
throw new Error(`Not a ZodError: ${value}`);
}
}
toString() {
return this.message;
}
get message() {
return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
}
get isEmpty() {
return this.issues.length === 0;
}
flatten(mapper = (issue) => issue.message) {
const fieldErrors = {};
const formErrors = [];
for (const sub of this.issues) {
if (sub.path.length > 0) {
const firstEl = sub.path[0];
fieldErrors[firstEl] = fieldErrors[firstEl] || [];
fieldErrors[firstEl].push(mapper(sub));
} else {
formErrors.push(mapper(sub));
}
}
return { formErrors, fieldErrors };
}
get formErrors() {
return this.flatten();
}
};
ZodError.create = (issues) => {
const error = new ZodError(issues);
return error;
};
// node_modules/zod/v3/locales/en.js
var errorMap = (issue, _ctx) => {
let message;
switch (issue.code) {
case ZodIssueCode.invalid_type:
if (issue.received === ZodParsedType.undefined) {
message = "Required";
} else {
message = `Expected ${issue.expected}, received ${issue.received}`;
}
break;
case ZodIssueCode.invalid_literal:
message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
break;
case ZodIssueCode.unrecognized_keys:
message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
break;
case ZodIssueCode.invalid_union:
message = `Invalid input`;
break;
case ZodIssueCode.invalid_union_discriminator:
message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
break;
case ZodIssueCode.invalid_enum_value:
message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
break;
case ZodIssueCode.invalid_arguments:
message = `Invalid function arguments`;
break;
case ZodIssueCode.invalid_return_type:
message = `Invalid function return type`;
break;
case ZodIssueCode.invalid_date:
message = `Invalid date`;
break;
case ZodIssueCode.invalid_string:
if (typeof issue.validation === "object") {
if ("includes" in issue.validation) {
message = `Invalid input: must include "${issue.validation.includes}"`;
if (typeof issue.validation.position === "number") {
message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
}
} else if ("startsWith" in issue.validation) {
message = `Invalid input: must start with "${issue.validation.startsWith}"`;
} else if ("endsWith" in issue.validation) {
message = `Invalid input: must end with "${issue.validation.endsWith}"`;
} else {
util.assertNever(issue.validation);
}
} else if (issue.validation !== "regex") {
message = `Invalid ${issue.validation}`;
} else {
message = "Invalid";
}
break;
case ZodIssueCode.too_small:
if (issue.type === "array")
message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
else if (issue.type === "string")
message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
else if (issue.type === "number")
message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
else if (issue.type === "bigint")
message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
else if (issue.type === "date")
message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
else
message = "Invalid input";
break;
case ZodIssueCode.too_big:
if (issue.type === "array")
message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
else if (issue.type === "string")
message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
else if (issue.type === "number")
message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
else if (issue.type === "bigint")
message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
else if (issue.type === "date")
message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
else
message = "Invalid input";
break;
case ZodIssueCode.custom:
message = `Invalid input`;
break;
case ZodIssueCode.invalid_intersection_types:
message = `Intersection results could not be merged`;
break;
case ZodIssueCode.not_multiple_of:
message = `Number must be a multiple of ${issue.multipleOf}`;
break;
case ZodIssueCode.not_finite:
message = "Number must be finite";
break;
default:
message = _ctx.defaultError;
util.assertNever(issue);
}
return { message };
};
var en_default = errorMap;
// node_modules/zod/v3/errors.js
var overrideErrorMap = en_default;
function setErrorMap(map) {
overrideErrorMap = map;
}
function getErrorMap() {
return overrideErrorMap;
}
// node_modules/zod/v3/helpers/parseUtil.js
var makeIssue = (params) => {
const { data, path: path4, errorMaps, issueData } = params;
const fullPath = [...path4, ...issueData.path || []];
const fullIssue = {
...issueData,
path: fullPath
};
if (issueData.message !== void 0) {
return {
...issueData,
path: fullPath,
message: issueData.message
};
}
let errorMessage = "";
const maps = errorMaps.filter((m) => !!m).slice().reverse();
for (const map of maps) {
errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
}
return {
...issueData,
path: fullPath,
message: errorMessage
};
};
var EMPTY_PATH = [];
function addIssueToContext(ctx, issueData) {
const overrideMap = getErrorMap();
const issue = makeIssue({
issueData,
data: ctx.data,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
// contextual error map is first priority
ctx.schemaErrorMap,
// then schema-bound map if available
overrideMap,
// then global override map
overrideMap === en_default ? void 0 : en_default
// then global default map
].filter((x) => !!x)
});
ctx.common.issues.push(issue);
}
var ParseStatus = class _ParseStatus {
constructor() {
this.value = "valid";
}
dirty() {
if (this.value === "valid")
this.value = "dirty";
}
abort() {
if (this.value !== "aborted")
this.value = "aborted";
}
static mergeArray(status, results) {
const arrayValue = [];
for (const s of results) {
if (s.status === "aborted")
return INVALID;
if (s.status === "dirty")
status.dirty();
arrayValue.push(s.value);
}
return { status: status.value, value: arrayValue };
}
static async mergeObjectAsync(status, pairs) {
const syncPairs = [];
for (const pair of pairs) {
const key = await pair.key;
const value = await pair.value;
syncPairs.push({
key,
value
});
}
return _ParseStatus.mergeObjectSync(status, syncPairs);
}
static mergeObjectSync(status, pairs) {
const finalObject = {};
for (const pair of pairs) {
const { key, value } = pair;
if (key.status === "aborted")
return INVALID;
if (value.status === "aborted")
return INVALID;
if (key.status === "dirty")
status.dirty();
if (value.status === "dirty")
status.dirty();
if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
finalObject[key.value] = value.value;
}
}
return { status: status.value, value: finalObject };
}
};
var INVALID = Object.freeze({
status: "aborted"
});
var DIRTY = (value) => ({ status: "dirty", value });
var OK = (value) => ({ status: "valid", value });
var isAborted = (x) => x.status === "aborted";
var isDirty = (x) => x.status === "dirty";
var isValid = (x) => x.status === "valid";
var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
// node_modules/zod/v3/helpers/errorUtil.js
var errorUtil;
(function(errorUtil2) {
errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
})(errorUtil || (errorUtil = {}));
// node_modules/zod/v3/types.js
var ParseInputLazyPath = class {
constructor(parent, value, path4, key) {
this._cachedPath = [];
this.parent = parent;
this.data = value;
this._path = path4;
this._key = key;
}
get path() {
if (!this._cachedPath.length) {
if (Array.isArray(this._key)) {
this._cachedPath.push(...this._path, ...this._key);
} else {
this._cachedPath.push(...this._path, this._key);
}
}
return this._cachedPath;
}
};
var handleResult = (ctx, result) => {
if (isValid(result)) {
return { success: true, data: result.value };
} else {
if (!ctx.common.issues.length) {
throw new Error("Validation failed but no issues detected.");
}
return {
success: false,
get error() {
if (this._error)
return this._error;
const error = new ZodError(ctx.common.issues);
this._error = error;
return this._error;
}
};
}
};
function processCreateParams(params) {
if (!params)
return {};
const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
if (errorMap2 && (invalid_type_error || required_error)) {
throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
}
if (errorMap2)
return { errorMap: errorMap2, description };
const customMap = (iss, ctx) => {
const { message } = params;
if (iss.code === "invalid_enum_value") {
return { message: message ?? ctx.defaultError };
}
if (typeof ctx.data === "undefined") {
return { message: message ?? required_error ?? ctx.defaultError };
}
if (iss.code !== "invalid_type")
return { message: ctx.defaultError };
return { message: message ?? invalid_type_error ?? ctx.defaultError };
};
return { errorMap: customMap, description };
}
var ZodType = class {
get description() {
return this._def.description;
}
_getType(input) {
return getParsedType(input.data);
}
_getOrReturnCtx(input, ctx) {
return ctx || {
common: input.parent.common,
data: input.data,
parsedType: getParsedType(input.data),
schemaErrorMap: this._def.errorMap,
path: input.path,
parent: input.parent
};
}
_processInputParams(input) {
return {
status: new ParseStatus(),
ctx: {
common: input.parent.common,
data: input.data,
parsedType: getParsedType(input.data),
schemaErrorMap: this._def.errorMap,
path: input.path,
parent: input.parent
}
};
}
_parseSync(input) {
const result = this._parse(input);
if (isAsync(result)) {
throw new Error("Synchronous parse encountered promise.");
}
return result;
}
_parseAsync(input) {
const result = this._parse(input);
return Promise.resolve(result);
}
parse(data, params) {
const result = this.safeParse(data, params);
if (result.success)
return result.data;
throw result.error;
}
safeParse(data, params) {
const ctx = {
common: {
issues: [],
async: params?.async ?? false,
contextualErrorMap: params?.errorMap
},
path: params?.path || [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data)
};
const result = this._parseSync({ data, path: ctx.path, parent: ctx });
return handleResult(ctx, result);
}
"~validate"(data) {
const ctx = {
common: {
issues: [],
async: !!this["~standard"].async
},
path: [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data)
};
if (!this["~standard"].async) {
try {
const result = this._parseSync({ data, path: [], parent: ctx });
return isValid(result) ? {
value: result.value
} : {
issues: ctx.common.issues
};
} catch (err) {
if (err?.message?.toLowerCase()?.includes("encountered")) {
this["~standard"].async = true;
}
ctx.common = {
issues: [],
async: true
};
}
}
return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
value: result.value
} : {
issues: ctx.common.issues
});
}
async parseAsync(data, params) {
const result = await this.safeParseAsync(data, params);
if (result.success)
return result.data;
throw result.error;
}
async safeParseAsync(data, params) {
const ctx = {
common: {
issues: [],
contextualErrorMap: params?.errorMap,
async: true
},
path: params?.path || [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data)
};
const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
return handleResult(ctx, result);
}
refine(check, message) {
const getIssueProperties = (val) => {
if (typeof message === "string" || typeof message === "undefined") {
return { message };
} else if (typeof message === "function") {
return message(val);
} else {
return message;
}
};
return this._refinement((val, ctx) => {
const result = check(val);
const setError = () => ctx.addIssue({
code: ZodIssueCode.custom,
...getIssueProperties(val)
});
if (typeof Promise !== "undefined" && result instanceof Promise) {
return result.then((data) => {
if (!data) {
setError();
return false;
} else {
return true;
}
});
}
if (!result) {
setError();
return false;
} else {
return true;
}
});
}
refinement(check, refinementData) {
return this._refinement((val, ctx) => {
if (!check(val)) {
ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
return false;
} else {
return true;
}
});
}
_refinement(refinement) {
return new ZodEffects({
schema: this,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect: { type: "refinement", refinement }
});
}
superRefine(refinement) {
return this._refinement(refinement);
}
constructor(def) {
this.spa = this.safeParseAsync;
this._def = def;
this.parse = this.parse.bind(this);
this.safeParse = this.safeParse.bind(this);
this.parseAsync = this.parseAsync.bind(this);
this.safeParseAsync = this.safeParseAsync.bind(this);
this.spa = this.spa.bind(this);
this.refine = this.refine.bind(this);
this.refinement = this.refinement.bind(this);
this.superRefine = this.superRefine.bind(this);
this.optional = this.optional.bind(this);
this.nullable = this.nullable.bind(this);
this.nullish = this.nullish.bind(this);
this.array = this.array.bind(this);
this.promise = this.promise.bind(this);
this.or = this.or.bind(this);
this.and = this.and.bind(this);
this.transform = this.transform.bind(this);
this.brand = this.brand.bind(this);
this.default = this.default.bind(this);
this.catch = this.catch.bind(this);
this.describe = this.describe.bind(this);
this.pipe = this.pipe.bind(this);
this.readonly = this.readonly.bind(this);
this.isNullable = this.isNullable.bind(this);
this.isOptional = this.isOptional.bind(this);
this["~standard"] = {
version: 1,
vendor: "zod",
validate: (data) => this["~validate"](data)
};
}
optional() {
return ZodOptional.create(this, this._def);
}
nullable() {
return ZodNullable.create(this, this._def);
}
nullish() {
return this.nullable().optional();
}
array() {
return ZodArray.create(this);
}
promise() {
return ZodPromise.create(this, this._def);
}
or(option) {
return ZodUnion.create([this, option], this._def);
}
and(incoming) {
return ZodIntersection.create(this, incoming, this._def);
}
transform(transform2) {
return new ZodEffects({
...processCreateParams(this._def),
schema: this,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect: { type: "transform", transform: transform2 }
});
}
default(def) {
const defaultValueFunc = typeof def === "function" ? def : () => def;
return new ZodDefault({
...processCreateParams(this._def),
innerType: this,
defaultValue: defaultValueFunc,
typeName: ZodFirstPartyTypeKind.ZodDefault
});
}
brand() {
return new ZodBranded({
typeName: ZodFirstPartyTypeKind.ZodBranded,
type: this,
...processCreateParams(this._def)
});
}
catch(def) {
const catchValueFunc = typeof def === "function" ? def : () => def;
return new ZodCatch({
...processCreateParams(this._def),
innerType: this,
catchValue: catchValueFunc,
typeName: ZodFirstPartyTypeKind.ZodCatch
});
}
describe(description) {
const This = this.constructor;
return new This({
...this._def,
description
});
}
pipe(target) {
return ZodPipeline.create(this, target);
}
readonly() {
return ZodReadonly.create(this);
}
isOptional() {
return this.safeParse(void 0).success;
}
isNullable() {
return this.safeParse(null).success;
}
};
var cuidRegex = /^c[^\s-]{8,}$/i;
var cuid2Regex = /^[0-9a-z]+$/;
var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
var nanoidRegex = /^[a-z0-9_-]{21}$/i;
var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
var emojiRegex;
var ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
var ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
var dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
var dateRegex = new RegExp(`^${dateRegexSource}$`);
function timeRegexSource(args) {
let secondsRegexSource = `[0-5]\\d`;
if (args.precision) {
secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
} else if (args.precision == null) {
secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
}
const secondsQuantifier = args.precision ? "+" : "?";
return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
}
function timeRegex(args) {
return new RegExp(`^${timeRegexSource(args)}$`);
}
function datetimeRegex(args) {
let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
const opts = [];
opts.push(args.local ? `Z?` : `Z`);
if (args.offset)
opts.push(`([+-]\\d{2}:?\\d{2})`);
regex = `${regex}(${opts.join("|")})`;
return new RegExp(`^${regex}$`);
}
function isValidIP(ip, version) {
if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
return true;
}
if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
return true;
}
return false;
}
function isValidJWT(jwt, alg) {
if (!jwtRegex.test(jwt))
return false;
try {
const [header] = jwt.split(".");
if (!header)
return false;
const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
const decoded = JSON.parse(atob(base64));
if (typeof decoded !== "object" || decoded === null)
return false;
if ("typ" in decoded && decoded?.typ !== "JWT")
return false;
if (!decoded.alg)
return false;
if (alg && decoded.alg !== alg)
return false;
return true;
} catch {
return false;
}
}
function isValidCidr(ip, version) {
if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
return true;
}
if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
return true;
}
return false;
}
var ZodString = class _ZodString extends ZodType {
_parse(input) {
if (this._def.coerce) {
input.data = String(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.string) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.string,
received: ctx2.parsedType
});
return INVALID;
}
const status = new ParseStatus();
let ctx = void 0;
for (const check of this._def.checks) {
if (check.kind === "min") {
if (input.data.length < check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "string",
inclusive: true,
exact: false,
message: check.message
});
status.dirty();
}
} else if (check.kind === "max") {
if (input.data.length > check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "string",
inclusive: true,
exact: false,
message: check.message
});
status.dirty();
}
} else if (check.kind === "length") {
const tooBig = input.data.length > check.value;
const tooSmall = input.data.length < check.value;
if (tooBig || tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
if (tooBig) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "string",
inclusive: true,
exact: true,
message: check.message
});
} else if (tooSmall) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "string",
inclusive: true,
exact: true,
message: check.message
});
}
status.dirty();
}
} else if (check.kind === "email") {
if (!emailRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "email",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "emoji") {
if (!emojiRegex) {
emojiRegex = new RegExp(_emojiRegex, "u");
}
if (!emojiRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "emoji",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "uuid") {
if (!uuidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "uuid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "nanoid") {
if (!nanoidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "nanoid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "cuid") {
if (!cuidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "cuid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "cuid2") {
if (!cuid2Regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "cuid2",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "ulid") {
if (!ulidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "ulid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "url") {
try {
new URL(input.data);
} catch {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "url",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "regex") {
check.regex.lastIndex = 0;
const testResult = check.regex.test(input.data);
if (!testResult) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "regex",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "trim") {
input.data = input.data.trim();
} else if (check.kind === "includes") {
if (!input.data.includes(check.value, check.position)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { includes: check.value, position: check.position },
message: check.message
});
status.dirty();
}
} else if (check.kind === "toLowerCase") {
input.data = input.data.toLowerCase();
} else if (check.kind === "toUpperCase") {
input.data = input.data.toUpperCase();
} else if (check.kind === "startsWith") {
if (!input.data.startsWith(check.value)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { startsWith: check.value },
message: check.message
});
status.dirty();
}
} else if (check.kind === "endsWith") {
if (!input.data.endsWith(check.value)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { endsWith: check.value },
message: check.message
});
status.dirty();
}
} else if (check.kind === "datetime") {
const regex = datetimeRegex(check);
if (!regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "datetime",
message: check.message
});
status.dirty();
}
} else if (check.kind === "date") {
const regex = dateRegex;
if (!regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "date",
message: check.message
});
status.dirty();
}
} else if (check.kind === "time") {
const regex = timeRegex(check);
if (!regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "time",
message: check.message
});
status.dirty();
}
} else if (check.kind === "duration") {
if (!durationRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "duration",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "ip") {
if (!isValidIP(input.data, check.version)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "ip",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "jwt") {
if (!isValidJWT(input.data, check.alg)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "jwt",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "cidr") {
if (!isValidCidr(input.data, check.version)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "cidr",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "base64") {
if (!base64Regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "base64",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "base64url") {
if (!base64urlRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "base64url",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else {
util.assertNever(check);
}
}
return { status: status.value, value: input.data };
}
_regex(regex, validation, message) {
return this.refinement((data) => regex.test(data), {
validation,
code: ZodIssueCode.invalid_string,
...errorUtil.errToObj(message)
});
}
_addCheck(check) {
return new _ZodString({
...this._def,
checks: [...this._def.checks, check]
});
}
email(message) {
return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
}
url(message) {
return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
}
emoji(message) {
return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
}
uuid(message) {
return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
}
nanoid(message) {
return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
}
cuid(message) {
return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
}
cuid2(message) {
return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
}
ulid(message) {
return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
}
base64(message) {
return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
}
base64url(message) {
return this._addCheck({
kind: "base64url",
...errorUtil.errToObj(message)
});
}
jwt(options) {
return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
}
ip(options) {
return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
}
cidr(options) {
return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
}
datetime(options) {
if (typeof options === "string") {
return this._addCheck({
kind: "datetime",
precision: null,
offset: false,
local: false,
message: options
});
}
return this._addCheck({
kind: "datetime",
precision: typeof options?.precision === "undefined" ? null : options?.precision,
offset: options?.offset ?? false,
local: options?.local ?? false,
...errorUtil.errToObj(options?.message)
});
}
date(message) {
return this._addCheck({ kind: "date", message });
}
time(options) {
if (typeof options === "string") {
return this._addCheck({
kind: "time",
precision: null,
message: options
});
}
return this._addCheck({
kind: "time",
precision: typeof options?.precision === "undefined" ? null : options?.precision,
...errorUtil.errToObj(options?.message)
});
}
duration(message) {
return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
}
regex(regex, message) {
return this._addCheck({
kind: "regex",
regex,
...errorUtil.errToObj(message)
});
}
includes(value, options) {
return this._addCheck({
kind: "includes",
value,
position: options?.position,
...errorUtil.errToObj(options?.message)
});
}
startsWith(value, message) {
return this._addCheck({
kind: "startsWith",
value,
...errorUtil.errToObj(message)
});
}
endsWith(value, message) {
return this._addCheck({
kind: "endsWith",
value,
...errorUtil.errToObj(message)
});
}
min(minLength, message) {
return this._addCheck({
kind: "min",
value: minLength,
...errorUtil.errToObj(message)
});
}
max(maxLength, message) {
return this._addCheck({
kind: "max",
value: maxLength,
...errorUtil.errToObj(message)
});
}
length(len, message) {
return this._addCheck({
kind: "length",
value: len,
...errorUtil.errToObj(message)
});
}
/**
* Equivalent to `.min(1)`
*/
nonempty(message) {
return this.min(1, errorUtil.errToObj(message));
}
trim() {
return new _ZodString({
...this._def,
checks: [...this._def.checks, { kind: "trim" }]
});
}
toLowerCase() {
return new _ZodString({
...this._def,
checks: [...this._def.checks, { kind: "toLowerCase" }]
});
}
toUpperCase() {
return new _ZodString({
...this._def,
checks: [...this._def.checks, { kind: "toUpperCase" }]
});
}
get isDatetime() {
return !!this._def.checks.find((ch) => ch.kind === "datetime");
}
get isDate() {
return !!this._def.checks.find((ch) => ch.kind === "date");
}
get isTime() {
return !!this._def.checks.find((ch) => ch.kind === "time");
}
get isDuration() {
return !!this._def.checks.find((ch) => ch.kind === "duration");
}
get isEmail() {
return !!this._def.checks.find((ch) => ch.kind === "email");
}
get isURL() {
return !!this._def.checks.find((ch) => ch.kind === "url");
}
get isEmoji() {
return !!this._def.checks.find((ch) => ch.kind === "emoji");
}
get isUUID() {
return !!this._def.checks.find((ch) => ch.kind === "uuid");
}
get isNANOID() {
return !!this._def.checks.find((ch) => ch.kind === "nanoid");
}
get isCUID() {
return !!this._def.checks.find((ch) => ch.kind === "cuid");
}
get isCUID2() {
return !!this._def.checks.find((ch) => ch.kind === "cuid2");
}
get isULID() {
return !!this._def.checks.find((ch) => ch.kind === "ulid");
}
get isIP() {
return !!this._def.checks.find((ch) => ch.kind === "ip");
}
get isCIDR() {
return !!this._def.checks.find((ch) => ch.kind === "cidr");
}
get isBase64() {
return !!this._def.checks.find((ch) => ch.kind === "base64");
}
get isBase64url() {
return !!this._def.checks.find((ch) => ch.kind === "base64url");
}
get minLength() {
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
}
return min;
}
get maxLength() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return max;
}
};
ZodString.create = (params) => {
return new ZodString({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodString,
coerce: params?.coerce ?? false,
...processCreateParams(params)
});
};
function floatSafeRemainder(val, step) {
const valDecCount = (val.toString().split(".")[1] || "").length;
const stepDecCount = (step.toString().split(".")[1] || "").length;
const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
return valInt % stepInt / 10 ** decCount;
}
var ZodNumber = class _ZodNumber extends ZodType {
constructor() {
super(...arguments);
this.min = this.gte;
this.max = this.lte;
this.step = this.multipleOf;
}
_parse(input) {
if (this._def.coerce) {
input.data = Number(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.number) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.number,
received: ctx2.parsedType
});
return INVALID;
}
let ctx = void 0;
const status = new ParseStatus();
for (const check of this._def.checks) {
if (check.kind === "int") {
if (!util.isInteger(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: "integer",
received: "float",
message: check.message
});
status.dirty();
}
} else if (check.kind === "min") {
const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
if (tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "number",
inclusive: check.inclusive,
exact: false,
message: check.message
});
status.dirty();
}
} else if (check.kind === "max") {
const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
if (tooBig) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "number",
inclusive: check.inclusive,
exact: false,
message: check.message
});
status.dirty();
}
} else if (check.kind === "multipleOf") {
if (floatSafeRemainder(input.data, check.value) !== 0) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_multiple_of,
multipleOf: check.value,
message: check.message
});
status.dirty();
}
} else if (check.kind === "finite") {
if (!Number.isFinite(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_finite,
message: check.message
});
status.dirty();
}
} else {
util.assertNever(check);
}
}
return { status: status.value, value: input.data };
}
gte(value, message) {
return this.setLimit("min", value, true, errorUtil.toString(message));
}
gt(value, message) {
return this.setLimit("min", value, false, errorUtil.toString(message));
}
lte(value, message) {
return this.setLimit("max", value, true, errorUtil.toString(message));
}
lt(value, message) {
return this.setLimit("max", value, false, errorUtil.toString(message));
}
setLimit(kind, value, inclusive, message) {
return new _ZodNumber({
...this._def,
checks: [
...this._def.checks,
{
kind,
value,
inclusive,
message: errorUtil.toString(message)
}
]
});
}
_addCheck(check) {
return new _ZodNumber({
...this._def,
checks: [...this._def.checks, check]
});
}
int(message) {
return this._addCheck({
kind: "int",
message: errorUtil.toString(message)
});
}
positive(message) {
return this._addCheck({
kind: "min",
value: 0,
inclusive: false,
message: errorUtil.toString(message)
});
}
negative(message) {
return this._addCheck({
kind: "max",
value: 0,
inclusive: false,
message: errorUtil.toString(message)
});
}
nonpositive(message) {
return this._addCheck({
kind: "max",
value: 0,
inclusive: true,
message: errorUtil.toString(message)
});
}
nonnegative(message) {
return this._addCheck({
kind: "min",
value: 0,
inclusive: true,
message: errorUtil.toString(message)
});
}
multipleOf(value, message) {
return this._addCheck({
kind: "multipleOf",
value,
message: errorUtil.toString(message)
});
}
finite(message) {
return this._addCheck({
kind: "finite",
message: errorUtil.toString(message)
});
}
safe(message) {
return this._addCheck({
kind: "min",
inclusive: true,
value: Number.MIN_SAFE_INTEGER,
message: errorUtil.toString(message)
})._addCheck({
kind: "max",
inclusive: true,
value: Number.MAX_SAFE_INTEGER,
message: errorUtil.toString(message)
});
}
get minValue() {
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
}
return min;
}
get maxValue() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return max;
}
get isInt() {
return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
}
get isFinite() {
let max = null;
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
return true;
} else if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
} else if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return Number.isFinite(min) && Number.isFinite(max);
}
};
ZodNumber.create = (params) => {
return new ZodNumber({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodNumber,
coerce: params?.coerce || false,
...processCreateParams(params)
});
};
var ZodBigInt = class _ZodBigInt extends ZodType {
constructor() {
super(...arguments);
this.min = this.gte;
this.max = this.lte;
}
_parse(input) {
if (this._def.coerce) {
try {
input.data = BigInt(input.data);
} catch {
return this._getInvalidInput(input);
}
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.bigint) {
return this._getInvalidInput(input);
}
let ctx = void 0;
const status = new ParseStatus();
for (const check of this._def.checks) {
if (check.kind === "min") {
const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
if (tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
type: "bigint",
minimum: check.value,
inclusive: check.inclusive,
message: check.message
});
status.dirty();
}
} else if (check.kind === "max") {
const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
if (tooBig) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
type: "bigint",
maximum: check.value,
inclusive: check.inclusive,
message: check.message
});
status.dirty();
}
} else if (check.kind === "multipleOf") {
if (input.data % check.value !== BigInt(0)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_multiple_of,
multipleOf: check.value,
message: check.message
});
status.dirty();
}
} else {
util.assertNever(check);
}
}
return { status: status.value, value: input.data };
}
_getInvalidInput(input) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.bigint,
received: ctx.parsedType
});
return INVALID;
}
gte(value, message) {
return this.setLimit("min", value, true, errorUtil.toString(message));
}
gt(value, message) {
return this.setLimit("min", value, false, errorUtil.toString(message));
}
lte(value, message) {
return this.setLimit("max", value, true, errorUtil.toString(message));
}
lt(value, message) {
return this.setLimit("max", value, false, errorUtil.toString(message));
}
setLimit(kind, value, inclusive, message) {
return new _ZodBigInt({
...this._def,
checks: [
...this._def.checks,
{
kind,
value,
inclusive,
message: errorUtil.toString(message)
}
]
});
}
_addCheck(check) {
return new _ZodBigInt({
...this._def,
checks: [...this._def.checks, check]
});
}
positive(message) {
return this._addCheck({
kind: "min",
value: BigInt(0),
inclusive: false,
message: errorUtil.toString(message)
});
}
negative(message) {
return this._addCheck({
kind: "max",
value: BigInt(0),
inclusive: false,
message: errorUtil.toString(message)
});
}
nonpositive(message) {
return this._addCheck({
kind: "max",
value: BigInt(0),
inclusive: true,
message: errorUtil.toString(message)
});
}
nonnegative(message) {
return this._addCheck({
kind: "min",
value: BigInt(0),
inclusive: true,
message: errorUtil.toString(message)
});
}
multipleOf(value, message) {
return this._addCheck({
kind: "multipleOf",
value,
message: errorUtil.toString(message)
});
}
get minValue() {
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
}
return min;
}
get maxValue() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return max;
}
};
ZodBigInt.create = (params) => {
return new ZodBigInt({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodBigInt,
coerce: params?.coerce ?? false,
...processCreateParams(params)
});
};
var ZodBoolean = class extends ZodType {
_parse(input) {
if (this._def.coerce) {
input.data = Boolean(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.boolean) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.boolean,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodBoolean.create = (params) => {
return new ZodBoolean({
typeName: ZodFirstPartyTypeKind.ZodBoolean,
coerce: params?.coerce || false,
...processCreateParams(params)
});
};
var ZodDate = class _ZodDate extends ZodType {
_parse(input) {
if (this._def.coerce) {
input.data = new Date(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.date) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.date,
received: ctx2.parsedType
});
return INVALID;
}
if (Number.isNaN(input.data.getTime())) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_date
});
return INVALID;
}
const status = new ParseStatus();
let ctx = void 0;
for (const check of this._def.checks) {
if (check.kind === "min") {
if (input.data.getTime() < check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
message: check.message,
inclusive: true,
exact: false,
minimum: check.value,
type: "date"
});
status.dirty();
}
} else if (check.kind === "max") {
if (input.data.getTime() > check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
message: check.message,
inclusive: true,
exact: false,
maximum: check.value,
type: "date"
});
status.dirty();
}
} else {
util.assertNever(check);
}
}
return {
status: status.value,
value: new Date(input.data.getTime())
};
}
_addCheck(check) {
return new _ZodDate({
...this._def,
checks: [...this._def.checks, check]
});
}
min(minDate, message) {
return this._addCheck({
kind: "min",
value: minDate.getTime(),
message: errorUtil.toString(message)
});
}
max(maxDate, message) {
return this._addCheck({
kind: "max",
value: maxDate.getTime(),
message: errorUtil.toString(message)
});
}
get minDate() {
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
}
return min != null ? new Date(min) : null;
}
get maxDate() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return max != null ? new Date(max) : null;
}
};
ZodDate.create = (params) => {
return new ZodDate({
checks: [],
coerce: params?.coerce || false,
typeName: ZodFirstPartyTypeKind.ZodDate,
...processCreateParams(params)
});
};
var ZodSymbol = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.symbol) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.symbol,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodSymbol.create = (params) => {
return new ZodSymbol({
typeName: ZodFirstPartyTypeKind.ZodSymbol,
...processCreateParams(params)
});
};
var ZodUndefined = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.undefined) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.undefined,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodUndefined.create = (params) => {
return new ZodUndefined({
typeName: ZodFirstPartyTypeKind.ZodUndefined,
...processCreateParams(params)
});
};
var ZodNull = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.null) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.null,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodNull.create = (params) => {
return new ZodNull({
typeName: ZodFirstPartyTypeKind.ZodNull,
...processCreateParams(params)
});
};
var ZodAny = class extends ZodType {
constructor() {
super(...arguments);
this._any = true;
}
_parse(input) {
return OK(input.data);
}
};
ZodAny.create = (params) => {
return new ZodAny({
typeName: ZodFirstPartyTypeKind.ZodAny,
...processCreateParams(params)
});
};
var ZodUnknown = class extends ZodType {
constructor() {
super(...arguments);
this._unknown = true;
}
_parse(input) {
return OK(input.data);
}
};
ZodUnknown.create = (params) => {
return new ZodUnknown({
typeName: ZodFirstPartyTypeKind.ZodUnknown,
...processCreateParams(params)
});
};
var ZodNever = class extends ZodType {
_parse(input) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.never,
received: ctx.parsedType
});
return INVALID;
}
};
ZodNever.create = (params) => {
return new ZodNever({
typeName: ZodFirstPartyTypeKind.ZodNever,
...processCreateParams(params)
});
};
var ZodVoid = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.undefined) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.void,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodVoid.create = (params) => {
return new ZodVoid({
typeName: ZodFirstPartyTypeKind.ZodVoid,
...processCreateParams(params)
});
};
var ZodArray = class _ZodArray extends ZodType {
_parse(input) {
const { ctx, status } = this._processInputParams(input);
const def = this._def;
if (ctx.parsedType !== ZodParsedType.array) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.array,
received: ctx.parsedType
});
return INVALID;
}
if (def.exactLength !== null) {
const tooBig = ctx.data.length > def.exactLength.value;
const tooSmall = ctx.data.length < def.exactLength.value;
if (tooBig || tooSmall) {
addIssueToContext(ctx, {
code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
minimum: tooSmall ? def.exactLength.value : void 0,
maximum: tooBig ? def.exactLength.value : void 0,
type: "array",
inclusive: true,
exact: true,
message: def.exactLength.message
});
status.dirty();
}
}
if (def.minLength !== null) {
if (ctx.data.length < def.minLength.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: def.minLength.value,
type: "array",
inclusive: true,
exact: false,
message: def.minLength.message
});
status.dirty();
}
}
if (def.maxLength !== null) {
if (ctx.data.length > def.maxLength.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: def.maxLength.value,
type: "array",
inclusive: true,
exact: false,
message: def.maxLength.message
});
status.dirty();
}
}
if (ctx.common.async) {
return Promise.all([...ctx.data].map((item, i) => {
return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
})).then((result2) => {
return ParseStatus.mergeArray(status, result2);
});
}
const result = [...ctx.data].map((item, i) => {
return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
});
return ParseStatus.mergeArray(status, result);
}
get element() {
return this._def.type;
}
min(minLength, message) {
return new _ZodArray({
...this._def,
minLength: { value: minLength, message: errorUtil.toString(message) }
});
}
max(maxLength, message) {
return new _ZodArray({
...this._def,
maxLength: { value: maxLength, message: errorUtil.toString(message) }
});
}
length(len, message) {
return new _ZodArray({
...this._def,
exactLength: { value: len, message: errorUtil.toString(message) }
});
}
nonempty(message) {
return this.min(1, message);
}
};
ZodArray.create = (schema, params) => {
return new ZodArray({
type: schema,
minLength: null,
maxLength: null,
exactLength: null,
typeName: ZodFirstPartyTypeKind.ZodArray,
...processCreateParams(params)
});
};
function deepPartialify(schema) {
if (schema instanceof ZodObject) {
const newShape = {};
for (const key in schema.shape) {
const fieldSchema = schema.shape[key];
newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
}
return new ZodObject({
...schema._def,
shape: () => newShape
});
} else if (schema instanceof ZodArray) {
return new ZodArray({
...schema._def,
type: deepPartialify(schema.element)
});
} else if (schema instanceof ZodOptional) {
return ZodOptional.create(deepPartialify(schema.unwrap()));
} else if (schema instanceof ZodNullable) {
return ZodNullable.create(deepPartialify(schema.unwrap()));
} else if (schema instanceof ZodTuple) {
return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
} else {
return schema;
}
}
var ZodObject = class _ZodObject extends ZodType {
constructor() {
super(...arguments);
this._cached = null;
this.nonstrict = this.passthrough;
this.augment = this.extend;
}
_getCached() {
if (this._cached !== null)
return this._cached;
const shape = this._def.shape();
const keys = util.objectKeys(shape);
this._cached = { shape, keys };
return this._cached;
}
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.object) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx2.parsedType
});
return INVALID;
}
const { status, ctx } = this._processInputParams(input);
const { shape, keys: shapeKeys } = this._getCached();
const extraKeys = [];
if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
for (const key in ctx.data) {
if (!shapeKeys.includes(key)) {
extraKeys.push(key);
}
}
}
const pairs = [];
for (const key of shapeKeys) {
const keyValidator = shape[key];
const value = ctx.data[key];
pairs.push({
key: { status: "valid", value: key },
value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
alwaysSet: key in ctx.data
});
}
if (this._def.catchall instanceof ZodNever) {
const unknownKeys = this._def.unknownKeys;
if (unknownKeys === "passthrough") {
for (const key of extraKeys) {
pairs.push({
key: { status: "valid", value: key },
value: { status: "valid", value: ctx.data[key] }
});
}
} else if (unknownKeys === "strict") {
if (extraKeys.length > 0) {
addIssueToContext(ctx, {
code: ZodIssueCode.unrecognized_keys,
keys: extraKeys
});
status.dirty();
}
} else if (unknownKeys === "strip") {
} else {
throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
}
} else {
const catchall = this._def.catchall;
for (const key of extraKeys) {
const value = ctx.data[key];
pairs.push({
key: { status: "valid", value: key },
value: catchall._parse(
new ParseInputLazyPath(ctx, value, ctx.path, key)
//, ctx.child(key), value, getParsedType(value)
),
alwaysSet: key in ctx.data
});
}
}
if (ctx.common.async) {
return Promise.resolve().then(async () => {
const syncPairs = [];
for (const pair of pairs) {
const key = await pair.key;
const value = await pair.value;
syncPairs.push({
key,
value,
alwaysSet: pair.alwaysSet
});
}
return syncPairs;
}).then((syncPairs) => {
return ParseStatus.mergeObjectSync(status, syncPairs);
});
} else {
return ParseStatus.mergeObjectSync(status, pairs);
}
}
get shape() {
return this._def.shape();
}
strict(message) {
errorUtil.errToObj;
return new _ZodObject({
...this._def,
unknownKeys: "strict",
...message !== void 0 ? {
errorMap: (issue, ctx) => {
const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
if (issue.code === "unrecognized_keys")
return {
message: errorUtil.errToObj(message).message ?? defaultError
};
return {
message: defaultError
};
}
} : {}
});
}
strip() {
return new _ZodObject({
...this._def,
unknownKeys: "strip"
});
}
passthrough() {
return new _ZodObject({
...this._def,
unknownKeys: "passthrough"
});
}
// const AugmentFactory =
// <Def extends ZodObjectDef>(def: Def) =>
// <Augmentation extends ZodRawShape>(
// augmentation: Augmentation
// ): ZodObject<
// extendShape<ReturnType<Def["shape"]>, Augmentation>,
// Def["unknownKeys"],
// Def["catchall"]
// > => {
// return new ZodObject({
// ...def,
// shape: () => ({
// ...def.shape(),
// ...augmentation,
// }),
// }) as any;
// };
extend(augmentation) {
return new _ZodObject({
...this._def,
shape: () => ({
...this._def.shape(),
...augmentation
})
});
}
/**
* Prior to zod@1.0.12 there was a bug in the
* inferred type of merged objects. Please
* upgrade if you are experiencing issues.
*/
merge(merging) {
const merged = new _ZodObject({
unknownKeys: merging._def.unknownKeys,
catchall: merging._def.catchall,
shape: () => ({
...this._def.shape(),
...merging._def.shape()
}),
typeName: ZodFirstPartyTypeKind.ZodObject
});
return merged;
}
// merge<
// Incoming extends AnyZodObject,
// Augmentation extends Incoming["shape"],
// NewOutput extends {
// [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
// ? Augmentation[k]["_output"]
// : k extends keyof Output
// ? Output[k]
// : never;
// },
// NewInput extends {
// [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
// ? Augmentation[k]["_input"]
// : k extends keyof Input
// ? Input[k]
// : never;
// }
// >(
// merging: Incoming
// ): ZodObject<
// extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
// Incoming["_def"]["unknownKeys"],
// Incoming["_def"]["catchall"],
// NewOutput,
// NewInput
// > {
// const merged: any = new ZodObject({
// unknownKeys: merging._def.unknownKeys,
// catchall: merging._def.catchall,
// shape: () =>
// objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
// typeName: ZodFirstPartyTypeKind.ZodObject,
// }) as any;
// return merged;
// }
setKey(key, schema) {
return this.augment({ [key]: schema });
}
// merge<Incoming extends AnyZodObject>(
// merging: Incoming
// ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
// ZodObject<
// extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
// Incoming["_def"]["unknownKeys"],
// Incoming["_def"]["catchall"]
// > {
// // const mergedShape = objectUtil.mergeShapes(
// // this._def.shape(),
// // merging._def.shape()
// // );
// const merged: any = new ZodObject({
// unknownKeys: merging._def.unknownKeys,
// catchall: merging._def.catchall,
// shape: () =>
// objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
// typeName: ZodFirstPartyTypeKind.ZodObject,
// }) as any;
// return merged;
// }
catchall(index) {
return new _ZodObject({
...this._def,
catchall: index
});
}
pick(mask) {
const shape = {};
for (const key of util.objectKeys(mask)) {
if (mask[key] && this.shape[key]) {
shape[key] = this.shape[key];
}
}
return new _ZodObject({
...this._def,
shape: () => shape
});
}
omit(mask) {
const shape = {};
for (const key of util.objectKeys(this.shape)) {
if (!mask[key]) {
shape[key] = this.shape[key];
}
}
return new _ZodObject({
...this._def,
shape: () => shape
});
}
/**
* @deprecated
*/
deepPartial() {
return deepPartialify(this);
}
partial(mask) {
const newShape = {};
for (const key of util.objectKeys(this.shape)) {
const fieldSchema = this.shape[key];
if (mask && !mask[key]) {
newShape[key] = fieldSchema;
} else {
newShape[key] = fieldSchema.optional();
}
}
return new _ZodObject({
...this._def,
shape: () => newShape
});
}
required(mask) {
const newShape = {};
for (const key of util.objectKeys(this.shape)) {
if (mask && !mask[key]) {
newShape[key] = this.shape[key];
} else {
const fieldSchema = this.shape[key];
let newField = fieldSchema;
while (newField instanceof ZodOptional) {
newField = newField._def.innerType;
}
newShape[key] = newField;
}
}
return new _ZodObject({
...this._def,
shape: () => newShape
});
}
keyof() {
return createZodEnum(util.objectKeys(this.shape));
}
};
ZodObject.create = (shape, params) => {
return new ZodObject({
shape: () => shape,
unknownKeys: "strip",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params)
});
};
ZodObject.strictCreate = (shape, params) => {
return new ZodObject({
shape: () => shape,
unknownKeys: "strict",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params)
});
};
ZodObject.lazycreate = (shape, params) => {
return new ZodObject({
shape,
unknownKeys: "strip",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params)
});
};
var ZodUnion = class extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const options = this._def.options;
function handleResults(results) {
for (const result of results) {
if (result.result.status === "valid") {
return result.result;
}
}
for (const result of results) {
if (result.result.status === "dirty") {
ctx.common.issues.push(...result.ctx.common.issues);
return result.result;
}
}
const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union,
unionErrors
});
return INVALID;
}
if (ctx.common.async) {
return Promise.all(options.map(async (option) => {
const childCtx = {
...ctx,
common: {
...ctx.common,
issues: []
},
parent: null
};
return {
result: await option._parseAsync({
data: ctx.data,
path: ctx.path,
parent: childCtx
}),
ctx: childCtx
};
})).then(handleResults);
} else {
let dirty = void 0;
const issues = [];
for (const option of options) {
const childCtx = {
...ctx,
common: {
...ctx.common,
issues: []
},
parent: null
};
const result = option._parseSync({
data: ctx.data,
path: ctx.path,
parent: childCtx
});
if (result.status === "valid") {
return result;
} else if (result.status === "dirty" && !dirty) {
dirty = { result, ctx: childCtx };
}
if (childCtx.common.issues.length) {
issues.push(childCtx.common.issues);
}
}
if (dirty) {
ctx.common.issues.push(...dirty.ctx.common.issues);
return dirty.result;
}
const unionErrors = issues.map((issues2) => new ZodError(issues2));
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union,
unionErrors
});
return INVALID;
}
}
get options() {
return this._def.options;
}
};
ZodUnion.create = (types, params) => {
return new ZodUnion({
options: types,
typeName: ZodFirstPartyTypeKind.ZodUnion,
...processCreateParams(params)
});
};
var getDiscriminator = (type) => {
if (type instanceof ZodLazy) {
return getDiscriminator(type.schema);
} else if (type instanceof ZodEffects) {
return getDiscriminator(type.innerType());
} else if (type instanceof ZodLiteral) {
return [type.value];
} else if (type instanceof ZodEnum) {
return type.options;
} else if (type instanceof ZodNativeEnum) {
return util.objectValues(type.enum);
} else if (type instanceof ZodDefault) {
return getDiscriminator(type._def.innerType);
} else if (type instanceof ZodUndefined) {
return [void 0];
} else if (type instanceof ZodNull) {
return [null];
} else if (type instanceof ZodOptional) {
return [void 0, ...getDiscriminator(type.unwrap())];
} else if (type instanceof ZodNullable) {
return [null, ...getDiscriminator(type.unwrap())];
} else if (type instanceof ZodBranded) {
return getDiscriminator(type.unwrap());
} else if (type instanceof ZodReadonly) {
return getDiscriminator(type.unwrap());
} else if (type instanceof ZodCatch) {
return getDiscriminator(type._def.innerType);
} else {
return [];
}
};
var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.object) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx.parsedType
});
return INVALID;
}
const discriminator = this.discriminator;
const discriminatorValue = ctx.data[discriminator];
const option = this.optionsMap.get(discriminatorValue);
if (!option) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union_discriminator,
options: Array.from(this.optionsMap.keys()),
path: [discriminator]
});
return INVALID;
}
if (ctx.common.async) {
return option._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
} else {
return option._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
}
}
get discriminator() {
return this._def.discriminator;
}
get options() {
return this._def.options;
}
get optionsMap() {
return this._def.optionsMap;
}
/**
* The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
* However, it only allows a union of objects, all of which need to share a discriminator property. This property must
* have a different value for each object in the union.
* @param discriminator the name of the discriminator property
* @param types an array of object schemas
* @param params
*/
static create(discriminator, options, params) {
const optionsMap = /* @__PURE__ */ new Map();
for (const type of options) {
const discriminatorValues = getDiscriminator(type.shape[discriminator]);
if (!discriminatorValues.length) {
throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
}
for (const value of discriminatorValues) {
if (optionsMap.has(value)) {
throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
}
optionsMap.set(value, type);
}
}
return new _ZodDiscriminatedUnion({
typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
discriminator,
options,
optionsMap,
...processCreateParams(params)
});
}
};
function mergeValues(a, b) {
const aType = getParsedType(a);
const bType = getParsedType(b);
if (a === b) {
return { valid: true, data: a };
} else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
const bKeys = util.objectKeys(b);
const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
const newObj = { ...a, ...b };
for (const key of sharedKeys) {
const sharedValue = mergeValues(a[key], b[key]);
if (!sharedValue.valid) {
return { valid: false };
}
newObj[key] = sharedValue.data;
}
return { valid: true, data: newObj };
} else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
if (a.length !== b.length) {
return { valid: false };
}
const newArray = [];
for (let index = 0; index < a.length; index++) {
const itemA = a[index];
const itemB = b[index];
const sharedValue = mergeValues(itemA, itemB);
if (!sharedValue.valid) {
return { valid: false };
}
newArray.push(sharedValue.data);
}
return { valid: true, data: newArray };
} else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
return { valid: true, data: a };
} else {
return { valid: false };
}
}
var ZodIntersection = class extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
const handleParsed = (parsedLeft, parsedRight) => {
if (isAborted(parsedLeft) || isAborted(parsedRight)) {
return INVALID;
}
const merged = mergeValues(parsedLeft.value, parsedRight.value);
if (!merged.valid) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_intersection_types
});
return INVALID;
}
if (isDirty(parsedLeft) || isDirty(parsedRight)) {
status.dirty();
}
return { status: status.value, value: merged.data };
};
if (ctx.common.async) {
return Promise.all([
this._def.left._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
}),
this._def.right._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
})
]).then(([left, right]) => handleParsed(left, right));
} else {
return handleParsed(this._def.left._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
}), this._def.right._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
}));
}
}
};
ZodIntersection.create = (left, right, params) => {
return new ZodIntersection({
left,
right,
typeName: ZodFirstPartyTypeKind.ZodIntersection,
...processCreateParams(params)
});
};
var ZodTuple = class _ZodTuple extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.array) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.array,
received: ctx.parsedType
});
return INVALID;
}
if (ctx.data.length < this._def.items.length) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: this._def.items.length,
inclusive: true,
exact: false,
type: "array"
});
return INVALID;
}
const rest = this._def.rest;
if (!rest && ctx.data.length > this._def.items.length) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: this._def.items.length,
inclusive: true,
exact: false,
type: "array"
});
status.dirty();
}
const items = [...ctx.data].map((item, itemIndex) => {
const schema = this._def.items[itemIndex] || this._def.rest;
if (!schema)
return null;
return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
}).filter((x) => !!x);
if (ctx.common.async) {
return Promise.all(items).then((results) => {
return ParseStatus.mergeArray(status, results);
});
} else {
return ParseStatus.mergeArray(status, items);
}
}
get items() {
return this._def.items;
}
rest(rest) {
return new _ZodTuple({
...this._def,
rest
});
}
};
ZodTuple.create = (schemas, params) => {
if (!Array.isArray(schemas)) {
throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
}
return new ZodTuple({
items: schemas,
typeName: ZodFirstPartyTypeKind.ZodTuple,
rest: null,
...processCreateParams(params)
});
};
var ZodRecord = class _ZodRecord extends ZodType {
get keySchema() {
return this._def.keyType;
}
get valueSchema() {
return this._def.valueType;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.object) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx.parsedType
});
return INVALID;
}
const pairs = [];
const keyType = this._def.keyType;
const valueType = this._def.valueType;
for (const key in ctx.data) {
pairs.push({
key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
alwaysSet: key in ctx.data
});
}
if (ctx.common.async) {
return ParseStatus.mergeObjectAsync(status, pairs);
} else {
return ParseStatus.mergeObjectSync(status, pairs);
}
}
get element() {
return this._def.valueType;
}
static create(first, second, third) {
if (second instanceof ZodType) {
return new _ZodRecord({
keyType: first,
valueType: second,
typeName: ZodFirstPartyTypeKind.ZodRecord,
...processCreateParams(third)
});
}
return new _ZodRecord({
keyType: ZodString.create(),
valueType: first,
typeName: ZodFirstPartyTypeKind.ZodRecord,
...processCreateParams(second)
});
}
};
var ZodMap = class extends ZodType {
get keySchema() {
return this._def.keyType;
}
get valueSchema() {
return this._def.valueType;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.map) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.map,
received: ctx.parsedType
});
return INVALID;
}
const keyType = this._def.keyType;
const valueType = this._def.valueType;
const pairs = [...ctx.data.entries()].map(([key, value], index) => {
return {
key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
};
});
if (ctx.common.async) {
const finalMap = /* @__PURE__ */ new Map();
return Promise.resolve().then(async () => {
for (const pair of pairs) {
const key = await pair.key;
const value = await pair.value;
if (key.status === "aborted" || value.status === "aborted") {
return INVALID;
}
if (key.status === "dirty" || value.status === "dirty") {
status.dirty();
}
finalMap.set(key.value, value.value);
}
return { status: status.value, value: finalMap };
});
} else {
const finalMap = /* @__PURE__ */ new Map();
for (const pair of pairs) {
const key = pair.key;
const value = pair.value;
if (key.status === "aborted" || value.status === "aborted") {
return INVALID;
}
if (key.status === "dirty" || value.status === "dirty") {
status.dirty();
}
finalMap.set(key.value, value.value);
}
return { status: status.value, value: finalMap };
}
}
};
ZodMap.create = (keyType, valueType, params) => {
return new ZodMap({
valueType,
keyType,
typeName: ZodFirstPartyTypeKind.ZodMap,
...processCreateParams(params)
});
};
var ZodSet = class _ZodSet extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.set) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.set,
received: ctx.parsedType
});
return INVALID;
}
const def = this._def;
if (def.minSize !== null) {
if (ctx.data.size < def.minSize.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: def.minSize.value,
type: "set",
inclusive: true,
exact: false,
message: def.minSize.message
});
status.dirty();
}
}
if (def.maxSize !== null) {
if (ctx.data.size > def.maxSize.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: def.maxSize.value,
type: "set",
inclusive: true,
exact: false,
message: def.maxSize.message
});
status.dirty();
}
}
const valueType = this._def.valueType;
function finalizeSet(elements2) {
const parsedSet = /* @__PURE__ */ new Set();
for (const element of elements2) {
if (element.status === "aborted")
return INVALID;
if (element.status === "dirty")
status.dirty();
parsedSet.add(element.value);
}
return { status: status.value, value: parsedSet };
}
const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
if (ctx.common.async) {
return Promise.all(elements).then((elements2) => finalizeSet(elements2));
} else {
return finalizeSet(elements);
}
}
min(minSize, message) {
return new _ZodSet({
...this._def,
minSize: { value: minSize, message: errorUtil.toString(message) }
});
}
max(maxSize, message) {
return new _ZodSet({
...this._def,
maxSize: { value: maxSize, message: errorUtil.toString(message) }
});
}
size(size, message) {
return this.min(size, message).max(size, message);
}
nonempty(message) {
return this.min(1, message);
}
};
ZodSet.create = (valueType, params) => {
return new ZodSet({
valueType,
minSize: null,
maxSize: null,
typeName: ZodFirstPartyTypeKind.ZodSet,
...processCreateParams(params)
});
};
var ZodFunction = class _ZodFunction extends ZodType {
constructor() {
super(...arguments);
this.validate = this.implement;
}
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.function) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.function,
received: ctx.parsedType
});
return INVALID;
}
function makeArgsIssue(args, error) {
return makeIssue({
data: args,
path: ctx.path,
errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
issueData: {
code: ZodIssueCode.invalid_arguments,
argumentsError: error
}
});
}
function makeReturnsIssue(returns, error) {
return makeIssue({
data: returns,
path: ctx.path,
errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
issueData: {
code: ZodIssueCode.invalid_return_type,
returnTypeError: error
}
});
}
const params = { errorMap: ctx.common.contextualErrorMap };
const fn = ctx.data;
if (this._def.returns instanceof ZodPromise) {
const me = this;
return OK(async function(...args) {
const error = new ZodError([]);
const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
error.addIssue(makeArgsIssue(args, e));
throw error;
});
const result = await Reflect.apply(fn, this, parsedArgs);
const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
error.addIssue(makeReturnsIssue(result, e));
throw error;
});
return parsedReturns;
});
} else {
const me = this;
return OK(function(...args) {
const parsedArgs = me._def.args.safeParse(args, params);
if (!parsedArgs.success) {
throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
}
const result = Reflect.apply(fn, this, parsedArgs.data);
const parsedReturns = me._def.returns.safeParse(result, params);
if (!parsedReturns.success) {
throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
}
return parsedReturns.data;
});
}
}
parameters() {
return this._def.args;
}
returnType() {
return this._def.returns;
}
args(...items) {
return new _ZodFunction({
...this._def,
args: ZodTuple.create(items).rest(ZodUnknown.create())
});
}
returns(returnType) {
return new _ZodFunction({
...this._def,
returns: returnType
});
}
implement(func) {
const validatedFunc = this.parse(func);
return validatedFunc;
}
strictImplement(func) {
const validatedFunc = this.parse(func);
return validatedFunc;
}
static create(args, returns, params) {
return new _ZodFunction({
args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
returns: returns || ZodUnknown.create(),
typeName: ZodFirstPartyTypeKind.ZodFunction,
...processCreateParams(params)
});
}
};
var ZodLazy = class extends ZodType {
get schema() {
return this._def.getter();
}
_parse(input) {
const { ctx } = this._processInputParams(input);
const lazySchema = this._def.getter();
return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
}
};
ZodLazy.create = (getter, params) => {
return new ZodLazy({
getter,
typeName: ZodFirstPartyTypeKind.ZodLazy,
...processCreateParams(params)
});
};
var ZodLiteral = class extends ZodType {
_parse(input) {
if (input.data !== this._def.value) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_literal,
expected: this._def.value
});
return INVALID;
}
return { status: "valid", value: input.data };
}
get value() {
return this._def.value;
}
};
ZodLiteral.create = (value, params) => {
return new ZodLiteral({
value,
typeName: ZodFirstPartyTypeKind.ZodLiteral,
...processCreateParams(params)
});
};
function createZodEnum(values, params) {
return new ZodEnum({
values,
typeName: ZodFirstPartyTypeKind.ZodEnum,
...processCreateParams(params)
});
}
var ZodEnum = class _ZodEnum extends ZodType {
_parse(input) {
if (typeof input.data !== "string") {
const ctx = this._getOrReturnCtx(input);
const expectedValues = this._def.values;
addIssueToContext(ctx, {
expected: util.joinValues(expectedValues),
received: ctx.parsedType,
code: ZodIssueCode.invalid_type
});
return INVALID;
}
if (!this._cache) {
this._cache = new Set(this._def.values);
}
if (!this._cache.has(input.data)) {
const ctx = this._getOrReturnCtx(input);
const expectedValues = this._def.values;
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_enum_value,
options: expectedValues
});
return INVALID;
}
return OK(input.data);
}
get options() {
return this._def.values;
}
get enum() {
const enumValues = {};
for (const val of this._def.values) {
enumValues[val] = val;
}
return enumValues;
}
get Values() {
const enumValues = {};
for (const val of this._def.values) {
enumValues[val] = val;
}
return enumValues;
}
get Enum() {
const enumValues = {};
for (const val of this._def.values) {
enumValues[val] = val;
}
return enumValues;
}
extract(values, newDef = this._def) {
return _ZodEnum.create(values, {
...this._def,
...newDef
});
}
exclude(values, newDef = this._def) {
return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
...this._def,
...newDef
});
}
};
ZodEnum.create = createZodEnum;
var ZodNativeEnum = class extends ZodType {
_parse(input) {
const nativeEnumValues = util.getValidEnumValues(this._def.values);
const ctx = this._getOrReturnCtx(input);
if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
const expectedValues = util.objectValues(nativeEnumValues);
addIssueToContext(ctx, {
expected: util.joinValues(expectedValues),
received: ctx.parsedType,
code: ZodIssueCode.invalid_type
});
return INVALID;
}
if (!this._cache) {
this._cache = new Set(util.getValidEnumValues(this._def.values));
}
if (!this._cache.has(input.data)) {
const expectedValues = util.objectValues(nativeEnumValues);
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_enum_value,
options: expectedValues
});
return INVALID;
}
return OK(input.data);
}
get enum() {
return this._def.values;
}
};
ZodNativeEnum.create = (values, params) => {
return new ZodNativeEnum({
values,
typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
...processCreateParams(params)
});
};
var ZodPromise = class extends ZodType {
unwrap() {
return this._def.type;
}
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.promise,
received: ctx.parsedType
});
return INVALID;
}
const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
return OK(promisified.then((data) => {
return this._def.type.parseAsync(data, {
path: ctx.path,
errorMap: ctx.common.contextualErrorMap
});
}));
}
};
ZodPromise.create = (schema, params) => {
return new ZodPromise({
type: schema,
typeName: ZodFirstPartyTypeKind.ZodPromise,
...processCreateParams(params)
});
};
var ZodEffects = class extends ZodType {
innerType() {
return this._def.schema;
}
sourceType() {
return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
const effect = this._def.effect || null;
const checkCtx = {
addIssue: (arg) => {
addIssueToContext(ctx, arg);
if (arg.fatal) {
status.abort();
} else {
status.dirty();
}
},
get path() {
return ctx.path;
}
};
checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
if (effect.type === "preprocess") {
const processed = effect.transform(ctx.data, checkCtx);
if (ctx.common.async) {
return Promise.resolve(processed).then(async (processed2) => {
if (status.value === "aborted")
return INVALID;
const result = await this._def.schema._parseAsync({
data: processed2,
path: ctx.path,
parent: ctx
});
if (result.status === "aborted")
return INVALID;
if (result.status === "dirty")
return DIRTY(result.value);
if (status.value === "dirty")
return DIRTY(result.value);
return result;
});
} else {
if (status.value === "aborted")
return INVALID;
const result = this._def.schema._parseSync({
data: processed,
path: ctx.path,
parent: ctx
});
if (result.status === "aborted")
return INVALID;
if (result.status === "dirty")
return DIRTY(result.value);
if (status.value === "dirty")
return DIRTY(result.value);
return result;
}
}
if (effect.type === "refinement") {
const executeRefinement = (acc) => {
const result = effect.refinement(acc, checkCtx);
if (ctx.common.async) {
return Promise.resolve(result);
}
if (result instanceof Promise) {
throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
}
return acc;
};
if (ctx.common.async === false) {
const inner = this._def.schema._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (inner.status === "aborted")
return INVALID;
if (inner.status === "dirty")
status.dirty();
executeRefinement(inner.value);
return { status: status.value, value: inner.value };
} else {
return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
if (inner.status === "aborted")
return INVALID;
if (inner.status === "dirty")
status.dirty();
return executeRefinement(inner.value).then(() => {
return { status: status.value, value: inner.value };
});
});
}
}
if (effect.type === "transform") {
if (ctx.common.async === false) {
const base = this._def.schema._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (!isValid(base))
return INVALID;
const result = effect.transform(base.value, checkCtx);
if (result instanceof Promise) {
throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
}
return { status: status.value, value: result };
} else {
return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
if (!isValid(base))
return INVALID;
return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
status: status.value,
value: result
}));
});
}
}
util.assertNever(effect);
}
};
ZodEffects.create = (schema, effect, params) => {
return new ZodEffects({
schema,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect,
...processCreateParams(params)
});
};
ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
return new ZodEffects({
schema,
effect: { type: "preprocess", transform: preprocess },
typeName: ZodFirstPartyTypeKind.ZodEffects,
...processCreateParams(params)
});
};
var ZodOptional = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType === ZodParsedType.undefined) {
return OK(void 0);
}
return this._def.innerType._parse(input);
}
unwrap() {
return this._def.innerType;
}
};
ZodOptional.create = (type, params) => {
return new ZodOptional({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodOptional,
...processCreateParams(params)
});
};
var ZodNullable = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType === ZodParsedType.null) {
return OK(null);
}
return this._def.innerType._parse(input);
}
unwrap() {
return this._def.innerType;
}
};
ZodNullable.create = (type, params) => {
return new ZodNullable({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodNullable,
...processCreateParams(params)
});
};
var ZodDefault = class extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
let data = ctx.data;
if (ctx.parsedType === ZodParsedType.undefined) {
data = this._def.defaultValue();
}
return this._def.innerType._parse({
data,
path: ctx.path,
parent: ctx
});
}
removeDefault() {
return this._def.innerType;
}
};
ZodDefault.create = (type, params) => {
return new ZodDefault({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodDefault,
defaultValue: typeof params.default === "function" ? params.default : () => params.default,
...processCreateParams(params)
});
};
var ZodCatch = class extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const newCtx = {
...ctx,
common: {
...ctx.common,
issues: []
}
};
const result = this._def.innerType._parse({
data: newCtx.data,
path: newCtx.path,
parent: {
...newCtx
}
});
if (isAsync(result)) {
return result.then((result2) => {
return {
status: "valid",
value: result2.status === "valid" ? result2.value : this._def.catchValue({
get error() {
return new ZodError(newCtx.common.issues);
},
input: newCtx.data
})
};
});
} else {
return {
status: "valid",
value: result.status === "valid" ? result.value : this._def.catchValue({
get error() {
return new ZodError(newCtx.common.issues);
},
input: newCtx.data
})
};
}
}
removeCatch() {
return this._def.innerType;
}
};
ZodCatch.create = (type, params) => {
return new ZodCatch({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodCatch,
catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
...processCreateParams(params)
});
};
var ZodNaN = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.nan) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.nan,
received: ctx.parsedType
});
return INVALID;
}
return { status: "valid", value: input.data };
}
};
ZodNaN.create = (params) => {
return new ZodNaN({
typeName: ZodFirstPartyTypeKind.ZodNaN,
...processCreateParams(params)
});
};
var BRAND = /* @__PURE__ */ Symbol("zod_brand");
var ZodBranded = class extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const data = ctx.data;
return this._def.type._parse({
data,
path: ctx.path,
parent: ctx
});
}
unwrap() {
return this._def.type;
}
};
var ZodPipeline = class _ZodPipeline extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.common.async) {
const handleAsync = async () => {
const inResult = await this._def.in._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (inResult.status === "aborted")
return INVALID;
if (inResult.status === "dirty") {
status.dirty();
return DIRTY(inResult.value);
} else {
return this._def.out._parseAsync({
data: inResult.value,
path: ctx.path,
parent: ctx
});
}
};
return handleAsync();
} else {
const inResult = this._def.in._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (inResult.status === "aborted")
return INVALID;
if (inResult.status === "dirty") {
status.dirty();
return {
status: "dirty",
value: inResult.value
};
} else {
return this._def.out._parseSync({
data: inResult.value,
path: ctx.path,
parent: ctx
});
}
}
}
static create(a, b) {
return new _ZodPipeline({
in: a,
out: b,
typeName: ZodFirstPartyTypeKind.ZodPipeline
});
}
};
var ZodReadonly = class extends ZodType {
_parse(input) {
const result = this._def.innerType._parse(input);
const freeze2 = (data) => {
if (isValid(data)) {
data.value = Object.freeze(data.value);
}
return data;
};
return isAsync(result) ? result.then((data) => freeze2(data)) : freeze2(result);
}
unwrap() {
return this._def.innerType;
}
};
ZodReadonly.create = (type, params) => {
return new ZodReadonly({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodReadonly,
...processCreateParams(params)
});
};
function cleanParams(params, data) {
const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
const p2 = typeof p === "string" ? { message: p } : p;
return p2;
}
function custom(check, _params = {}, fatal) {
if (check)
return ZodAny.create().superRefine((data, ctx) => {
const r = check(data);
if (r instanceof Promise) {
return r.then((r2) => {
if (!r2) {
const params = cleanParams(_params, data);
const _fatal = params.fatal ?? fatal ?? true;
ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
}
});
}
if (!r) {
const params = cleanParams(_params, data);
const _fatal = params.fatal ?? fatal ?? true;
ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
}
return;
});
return ZodAny.create();
}
var late = {
object: ZodObject.lazycreate
};
var ZodFirstPartyTypeKind;
(function(ZodFirstPartyTypeKind2) {
ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
var instanceOfType = (cls, params = {
message: `Input not instance of ${cls.name}`
}) => custom((data) => data instanceof cls, params);
var stringType = ZodString.create;
var numberType = ZodNumber.create;
var nanType = ZodNaN.create;
var bigIntType = ZodBigInt.create;
var booleanType = ZodBoolean.create;
var dateType = ZodDate.create;
var symbolType = ZodSymbol.create;
var undefinedType = ZodUndefined.create;
var nullType = ZodNull.create;
var anyType = ZodAny.create;
var unknownType = ZodUnknown.create;
var neverType = ZodNever.create;
var voidType = ZodVoid.create;
var arrayType = ZodArray.create;
var objectType = ZodObject.create;
var strictObjectType = ZodObject.strictCreate;
var unionType = ZodUnion.create;
var discriminatedUnionType = ZodDiscriminatedUnion.create;
var intersectionType = ZodIntersection.create;
var tupleType = ZodTuple.create;
var recordType = ZodRecord.create;
var mapType = ZodMap.create;
var setType = ZodSet.create;
var functionType = ZodFunction.create;
var lazyType = ZodLazy.create;
var literalType = ZodLiteral.create;
var enumType = ZodEnum.create;
var nativeEnumType = ZodNativeEnum.create;
var promiseType = ZodPromise.create;
var effectsType = ZodEffects.create;
var optionalType = ZodOptional.create;
var nullableType = ZodNullable.create;
var preprocessType = ZodEffects.createWithPreprocess;
var pipelineType = ZodPipeline.create;
var ostring = () => stringType().optional();
var onumber = () => numberType().optional();
var oboolean = () => booleanType().optional();
var coerce = {
string: ((arg) => ZodString.create({ ...arg, coerce: true })),
number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),
boolean: ((arg) => ZodBoolean.create({
...arg,
coerce: true
})),
bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),
date: ((arg) => ZodDate.create({ ...arg, coerce: true }))
};
var NEVER = INVALID;
// node_modules/@lmstudio/sdk/dist/index.mjs
var import_process = __toESM(require("process"), 1);
var import_chalk = __toESM(require_source(), 1);
var import_lms_isomorphic = __toESM(require_cjs(), 1);
// node_modules/zod-to-json-schema/dist/esm/parsers/string.js
var ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
// node_modules/@lmstudio/sdk/dist/index.mjs
function isSignalLike(value) {
return typeof value === "object" && value !== null && typeof value.get === "function" && typeof value.subscribe === "function";
}
var Subscribable = class {
subscribeWithCleaner(cleaner, listener) {
const unsubscribe = this.subscribe(listener);
cleaner.register(unsubscribe);
}
subscribeOnce(listener) {
const unsubscribe = this.subscribe((data) => {
unsubscribe();
listener(data);
});
return unsubscribe;
}
subscribeOnceWithCleaner(cleaner, listener) {
const unsubscribe = this.subscribeOnce(listener);
cleaner.register(unsubscribe);
}
derive(deriver, outputEqualsPredicate = (a, b) => a === b) {
if (isSignalLike(this)) {
return LazySignal.deriveFrom([this], deriver);
}
const thisWithGetter = this;
if (thisWithGetter.get !== void 0) {
const initialValue = thisWithGetter.get();
if (initialValue === LazySignal.NOT_AVAILABLE) {
return LazySignal.createWithoutInitialValue((setDownstream) => {
return thisWithGetter.subscribe((data) => {
if (isAvailable(data)) {
setDownstream(deriver(data));
}
});
});
}
const thisNarrowed = thisWithGetter;
return LazySignal.create(deriver(thisNarrowed.get()), (setDownstream) => {
return thisNarrowed.subscribe((data) => {
setDownstream(deriver(data));
});
}, outputEqualsPredicate);
}
return LazySignal.createWithoutInitialValue((setDownstream) => {
return this.subscribe((data) => {
if (isAvailable(data)) {
setDownstream(deriver(data));
}
});
}, outputEqualsPredicate);
}
};
var Event = class _Event extends Subscribable {
/**
* Internal state that tracks whether the event has any subscribers.
*/
constructor() {
super();
this.subscribers = /* @__PURE__ */ new Set();
this.onSubscribed = null;
this.onUnsubscribed = null;
}
emit(data) {
queueMicrotask(() => {
for (const subscriber of this.subscribers) {
subscriber(data);
}
});
}
static create() {
const event = new _Event();
const emitter = (data) => {
event.emit(data);
};
return [event, emitter];
}
subscribe(listener) {
const previousSize = this.subscribers.size;
this.subscribers.add(listener);
if (previousSize === 0 && this.subscribers.size === 1) {
this.onSubscribed?.();
}
return () => {
const previousSize2 = this.subscribers.size;
this.subscribers.delete(listener);
if (previousSize2 === 1 && this.subscribers.size === 0) {
this.onUnsubscribed?.();
}
};
}
batch({ minIdleTimeMs = 200, maxBatchTimeMs = 1e3 }) {
const [batchedEvent, emitBatchedEvent] = _Event.create();
batchedEvent.onSubscribed = () => {
let batch = [];
let emitBatchTimeout = null;
let firstEventTime = 0;
const emitBatch = () => {
emitBatchTimeout = null;
emitBatchedEvent(batch);
batch = [];
};
batchedEvent.onUnsubscribed = this.subscribe((data) => {
batch.push(data);
if (emitBatchTimeout === null) {
firstEventTime = Date.now();
emitBatchTimeout = setTimeout(emitBatch, Math.min(minIdleTimeMs, maxBatchTimeMs));
} else {
clearTimeout(emitBatchTimeout);
const timeSinceFirstEvent = Date.now() - firstEventTime;
emitBatchTimeout = setTimeout(emitBatch, Math.min(minIdleTimeMs, Math.max(0, maxBatchTimeMs - timeSinceFirstEvent)));
}
});
};
return batchedEvent;
}
};
function makePromise() {
let resolve;
let reject;
const promise = new Promise((_resolve, _reject) => {
resolve = _resolve;
reject = _reject;
});
return { promise, resolve, reject };
}
var NOTHING = /* @__PURE__ */ Symbol.for("immer-nothing");
var DRAFTABLE = /* @__PURE__ */ Symbol.for("immer-draftable");
var DRAFT_STATE = /* @__PURE__ */ Symbol.for("immer-state");
var errors = process.env.NODE_ENV !== "production" ? [
// All error codes, starting by 0:
function(plugin) {
return `The plugin for '${plugin}' has not been loaded into Immer. To enable the plugin, import and call \`enable${plugin}()\` when initializing your application.`;
},
function(thing) {
return `produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${thing}'`;
},
"This object has been frozen and should not be mutated",
function(data) {
return "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " + data;
},
"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.",
"Immer forbids circular references",
"The first or second argument to `produce` must be a function",
"The third argument to `produce` must be a function or undefined",
"First argument to `createDraft` must be a plain object, an array, or an immerable object",
"First argument to `finishDraft` must be a draft returned by `createDraft`",
function(thing) {
return `'current' expects a draft, got: ${thing}`;
},
"Object.defineProperty() cannot be used on an Immer draft",
"Object.setPrototypeOf() cannot be used on an Immer draft",
"Immer only supports deleting array indices",
"Immer only supports setting array indices and the 'length' property",
function(thing) {
return `'original' expects a draft, got: ${thing}`;
}
// Note: if more errors are added, the errorOffset in Patches.ts should be increased
// See Patches.ts for additional errors
] : [];
function die(error, ...args) {
if (process.env.NODE_ENV !== "production") {
const e = errors[error];
const msg = typeof e === "function" ? e.apply(null, args) : e;
throw new Error(`[Immer] ${msg}`);
}
throw new Error(
`[Immer] minified error nr: ${error}. Full error at: https://bit.ly/3cXEKWf`
);
}
var getPrototypeOf = Object.getPrototypeOf;
function isDraft(value) {
return !!value && !!value[DRAFT_STATE];
}
function isDraftable(value) {
if (!value)
return false;
return isPlainObject$2(value) || Array.isArray(value) || !!value[DRAFTABLE] || !!value.constructor?.[DRAFTABLE] || isMap$1(value) || isSet$1(value);
}
var objectCtorString = Object.prototype.constructor.toString();
function isPlainObject$2(value) {
if (!value || typeof value !== "object")
return false;
const proto = getPrototypeOf(value);
if (proto === null) {
return true;
}
const Ctor = Object.hasOwnProperty.call(proto, "constructor") && proto.constructor;
if (Ctor === Object)
return true;
return typeof Ctor == "function" && Function.toString.call(Ctor) === objectCtorString;
}
function each(obj, iter) {
if (getArchtype(obj) === 0) {
Reflect.ownKeys(obj).forEach((key) => {
iter(key, obj[key], obj);
});
} else {
obj.forEach((entry, index) => iter(index, entry, obj));
}
}
function getArchtype(thing) {
const state = thing[DRAFT_STATE];
return state ? state.type_ : Array.isArray(thing) ? 1 : isMap$1(thing) ? 2 : isSet$1(thing) ? 3 : 0;
}
function has(thing, prop) {
return getArchtype(thing) === 2 ? thing.has(prop) : Object.prototype.hasOwnProperty.call(thing, prop);
}
function get(thing, prop) {
return getArchtype(thing) === 2 ? thing.get(prop) : thing[prop];
}
function set(thing, propOrOldValue, value) {
const t = getArchtype(thing);
if (t === 2)
thing.set(propOrOldValue, value);
else if (t === 3) {
thing.add(value);
} else
thing[propOrOldValue] = value;
}
function is(x, y) {
if (x === y) {
return x !== 0 || 1 / x === 1 / y;
} else {
return x !== x && y !== y;
}
}
function isMap$1(target) {
return target instanceof Map;
}
function isSet$1(target) {
return target instanceof Set;
}
function latest(state) {
return state.copy_ || state.base_;
}
function shallowCopy(base, strict) {
if (isMap$1(base)) {
return new Map(base);
}
if (isSet$1(base)) {
return new Set(base);
}
if (Array.isArray(base))
return Array.prototype.slice.call(base);
const isPlain = isPlainObject$2(base);
if (strict === true || strict === "class_only" && !isPlain) {
const descriptors = Object.getOwnPropertyDescriptors(base);
delete descriptors[DRAFT_STATE];
let keys = Reflect.ownKeys(descriptors);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const desc = descriptors[key];
if (desc.writable === false) {
desc.writable = true;
desc.configurable = true;
}
if (desc.get || desc.set)
descriptors[key] = {
configurable: true,
writable: true,
// could live with !!desc.set as well here...
enumerable: desc.enumerable,
value: base[key]
};
}
return Object.create(getPrototypeOf(base), descriptors);
} else {
const proto = getPrototypeOf(base);
if (proto !== null && isPlain) {
return { ...base };
}
const obj = Object.create(proto);
return Object.assign(obj, base);
}
}
function freeze(obj, deep = false) {
if (isFrozen(obj) || isDraft(obj) || !isDraftable(obj))
return obj;
if (getArchtype(obj) > 1) {
obj.set = obj.add = obj.clear = obj.delete = dontMutateFrozenCollections;
}
Object.freeze(obj);
if (deep)
Object.values(obj).forEach((value) => freeze(value, true));
return obj;
}
function dontMutateFrozenCollections() {
die(2);
}
function isFrozen(obj) {
return Object.isFrozen(obj);
}
var plugins = {};
function getPlugin(pluginKey) {
const plugin = plugins[pluginKey];
if (!plugin) {
die(0, pluginKey);
}
return plugin;
}
function loadPlugin(pluginKey, implementation) {
if (!plugins[pluginKey])
plugins[pluginKey] = implementation;
}
var currentScope;
function getCurrentScope() {
return currentScope;
}
function createScope(parent_, immer_) {
return {
drafts_: [],
parent_,
immer_,
// Whenever the modified draft contains a draft from another scope, we
// need to prevent auto-freezing so the unowned draft can be finalized.
canAutoFreeze_: true,
unfinalizedDrafts_: 0
};
}
function usePatchesInScope(scope, patchListener) {
if (patchListener) {
getPlugin("Patches");
scope.patches_ = [];
scope.inversePatches_ = [];
scope.patchListener_ = patchListener;
}
}
function revokeScope(scope) {
leaveScope(scope);
scope.drafts_.forEach(revokeDraft);
scope.drafts_ = null;
}
function leaveScope(scope) {
if (scope === currentScope) {
currentScope = scope.parent_;
}
}
function enterScope(immer2) {
return currentScope = createScope(currentScope, immer2);
}
function revokeDraft(draft) {
const state = draft[DRAFT_STATE];
if (state.type_ === 0 || state.type_ === 1)
state.revoke_();
else
state.revoked_ = true;
}
function processResult(result, scope) {
scope.unfinalizedDrafts_ = scope.drafts_.length;
const baseDraft = scope.drafts_[0];
const isReplaced = result !== void 0 && result !== baseDraft;
if (isReplaced) {
if (baseDraft[DRAFT_STATE].modified_) {
revokeScope(scope);
die(4);
}
if (isDraftable(result)) {
result = finalize(scope, result);
if (!scope.parent_)
maybeFreeze(scope, result);
}
if (scope.patches_) {
getPlugin("Patches").generateReplacementPatches_(
baseDraft[DRAFT_STATE].base_,
result,
scope.patches_,
scope.inversePatches_
);
}
} else {
result = finalize(scope, baseDraft, []);
}
revokeScope(scope);
if (scope.patches_) {
scope.patchListener_(scope.patches_, scope.inversePatches_);
}
return result !== NOTHING ? result : void 0;
}
function finalize(rootScope, value, path4) {
if (isFrozen(value))
return value;
const state = value[DRAFT_STATE];
if (!state) {
each(
value,
(key, childValue) => finalizeProperty(rootScope, state, value, key, childValue, path4)
);
return value;
}
if (state.scope_ !== rootScope)
return value;
if (!state.modified_) {
maybeFreeze(rootScope, state.base_, true);
return state.base_;
}
if (!state.finalized_) {
state.finalized_ = true;
state.scope_.unfinalizedDrafts_--;
const result = state.copy_;
let resultEach = result;
let isSet2 = false;
if (state.type_ === 3) {
resultEach = new Set(result);
result.clear();
isSet2 = true;
}
each(
resultEach,
(key, childValue) => finalizeProperty(rootScope, state, result, key, childValue, path4, isSet2)
);
maybeFreeze(rootScope, result, false);
if (path4 && rootScope.patches_) {
getPlugin("Patches").generatePatches_(
state,
path4,
rootScope.patches_,
rootScope.inversePatches_
);
}
}
return state.copy_;
}
function finalizeProperty(rootScope, parentState, targetObject, prop, childValue, rootPath, targetIsSet) {
if (process.env.NODE_ENV !== "production" && childValue === targetObject)
die(5);
if (isDraft(childValue)) {
const path4 = rootPath && parentState && parentState.type_ !== 3 && // Set objects are atomic since they have no keys.
!has(parentState.assigned_, prop) ? rootPath.concat(prop) : void 0;
const res = finalize(rootScope, childValue, path4);
set(targetObject, prop, res);
if (isDraft(res)) {
rootScope.canAutoFreeze_ = false;
} else
return;
} else if (targetIsSet) {
targetObject.add(childValue);
}
if (isDraftable(childValue) && !isFrozen(childValue)) {
if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {
return;
}
finalize(rootScope, childValue);
if ((!parentState || !parentState.scope_.parent_) && typeof prop !== "symbol" && Object.prototype.propertyIsEnumerable.call(targetObject, prop))
maybeFreeze(rootScope, childValue);
}
}
function maybeFreeze(scope, value, deep = false) {
if (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {
freeze(value, deep);
}
}
function createProxyProxy(base, parent) {
const isArray2 = Array.isArray(base);
const state = {
type_: isArray2 ? 1 : 0,
// Track which produce call this is associated with.
scope_: parent ? parent.scope_ : getCurrentScope(),
// True for both shallow and deep changes.
modified_: false,
// Used during finalization.
finalized_: false,
// Track which properties have been assigned (true) or deleted (false).
assigned_: {},
// The parent draft state.
parent_: parent,
// The base state.
base_: base,
// The base proxy.
draft_: null,
// set below
// The base copy with any updated values.
copy_: null,
// Called by the `produce` function.
revoke_: null,
isManual_: false
};
let target = state;
let traps = objectTraps;
if (isArray2) {
target = [state];
traps = arrayTraps;
}
const { revoke, proxy } = Proxy.revocable(target, traps);
state.draft_ = proxy;
state.revoke_ = revoke;
return proxy;
}
var objectTraps = {
get(state, prop) {
if (prop === DRAFT_STATE)
return state;
const source = latest(state);
if (!has(source, prop)) {
return readPropFromProto(state, source, prop);
}
const value = source[prop];
if (state.finalized_ || !isDraftable(value)) {
return value;
}
if (value === peek(state.base_, prop)) {
prepareCopy(state);
return state.copy_[prop] = createProxy(value, state);
}
return value;
},
has(state, prop) {
return prop in latest(state);
},
ownKeys(state) {
return Reflect.ownKeys(latest(state));
},
set(state, prop, value) {
const desc = getDescriptorFromProto(latest(state), prop);
if (desc?.set) {
desc.set.call(state.draft_, value);
return true;
}
if (!state.modified_) {
const current2 = peek(latest(state), prop);
const currentState = current2?.[DRAFT_STATE];
if (currentState && currentState.base_ === value) {
state.copy_[prop] = value;
state.assigned_[prop] = false;
return true;
}
if (is(value, current2) && (value !== void 0 || has(state.base_, prop)))
return true;
prepareCopy(state);
markChanged(state);
}
if (state.copy_[prop] === value && // special case: handle new props with value 'undefined'
(value !== void 0 || prop in state.copy_) || // special case: NaN
Number.isNaN(value) && Number.isNaN(state.copy_[prop]))
return true;
state.copy_[prop] = value;
state.assigned_[prop] = true;
return true;
},
deleteProperty(state, prop) {
if (peek(state.base_, prop) !== void 0 || prop in state.base_) {
state.assigned_[prop] = false;
prepareCopy(state);
markChanged(state);
} else {
delete state.assigned_[prop];
}
if (state.copy_) {
delete state.copy_[prop];
}
return true;
},
// Note: We never coerce `desc.value` into an Immer draft, because we can't make
// the same guarantee in ES5 mode.
getOwnPropertyDescriptor(state, prop) {
const owner = latest(state);
const desc = Reflect.getOwnPropertyDescriptor(owner, prop);
if (!desc)
return desc;
return {
writable: true,
configurable: state.type_ !== 1 || prop !== "length",
enumerable: desc.enumerable,
value: owner[prop]
};
},
defineProperty() {
die(11);
},
getPrototypeOf(state) {
return getPrototypeOf(state.base_);
},
setPrototypeOf() {
die(12);
}
};
var arrayTraps = {};
each(objectTraps, (key, fn) => {
arrayTraps[key] = function() {
arguments[0] = arguments[0][0];
return fn.apply(this, arguments);
};
});
arrayTraps.deleteProperty = function(state, prop) {
if (process.env.NODE_ENV !== "production" && isNaN(parseInt(prop)))
die(13);
return arrayTraps.set.call(this, state, prop, void 0);
};
arrayTraps.set = function(state, prop, value) {
if (process.env.NODE_ENV !== "production" && prop !== "length" && isNaN(parseInt(prop)))
die(14);
return objectTraps.set.call(this, state[0], prop, value, state[0]);
};
function peek(draft, prop) {
const state = draft[DRAFT_STATE];
const source = state ? latest(state) : draft;
return source[prop];
}
function readPropFromProto(state, source, prop) {
const desc = getDescriptorFromProto(source, prop);
return desc ? `value` in desc ? desc.value : (
// This is a very special case, if the prop is a getter defined by the
// prototype, we should invoke it with the draft as context!
desc.get?.call(state.draft_)
) : void 0;
}
function getDescriptorFromProto(source, prop) {
if (!(prop in source))
return void 0;
let proto = getPrototypeOf(source);
while (proto) {
const desc = Object.getOwnPropertyDescriptor(proto, prop);
if (desc)
return desc;
proto = getPrototypeOf(proto);
}
return void 0;
}
function markChanged(state) {
if (!state.modified_) {
state.modified_ = true;
if (state.parent_) {
markChanged(state.parent_);
}
}
}
function prepareCopy(state) {
if (!state.copy_) {
state.copy_ = shallowCopy(
state.base_,
state.scope_.immer_.useStrictShallowCopy_
);
}
}
var Immer2 = class {
constructor(config) {
this.autoFreeze_ = true;
this.useStrictShallowCopy_ = false;
this.produce = (base, recipe, patchListener) => {
if (typeof base === "function" && typeof recipe !== "function") {
const defaultBase = recipe;
recipe = base;
const self = this;
return function curriedProduce(base2 = defaultBase, ...args) {
return self.produce(base2, (draft) => recipe.call(this, draft, ...args));
};
}
if (typeof recipe !== "function")
die(6);
if (patchListener !== void 0 && typeof patchListener !== "function")
die(7);
let result;
if (isDraftable(base)) {
const scope = enterScope(this);
const proxy = createProxy(base, void 0);
let hasError = true;
try {
result = recipe(proxy);
hasError = false;
} finally {
if (hasError)
revokeScope(scope);
else
leaveScope(scope);
}
usePatchesInScope(scope, patchListener);
return processResult(result, scope);
} else if (!base || typeof base !== "object") {
result = recipe(base);
if (result === void 0)
result = base;
if (result === NOTHING)
result = void 0;
if (this.autoFreeze_)
freeze(result, true);
if (patchListener) {
const p = [];
const ip = [];
getPlugin("Patches").generateReplacementPatches_(base, result, p, ip);
patchListener(p, ip);
}
return result;
} else
die(1, base);
};
this.produceWithPatches = (base, recipe) => {
if (typeof base === "function") {
return (state, ...args) => this.produceWithPatches(state, (draft) => base(draft, ...args));
}
let patches, inversePatches;
const result = this.produce(base, recipe, (p, ip) => {
patches = p;
inversePatches = ip;
});
return [result, patches, inversePatches];
};
if (typeof config?.autoFreeze === "boolean")
this.setAutoFreeze(config.autoFreeze);
if (typeof config?.useStrictShallowCopy === "boolean")
this.setUseStrictShallowCopy(config.useStrictShallowCopy);
}
createDraft(base) {
if (!isDraftable(base))
die(8);
if (isDraft(base))
base = current(base);
const scope = enterScope(this);
const proxy = createProxy(base, void 0);
proxy[DRAFT_STATE].isManual_ = true;
leaveScope(scope);
return proxy;
}
finishDraft(draft, patchListener) {
const state = draft && draft[DRAFT_STATE];
if (!state || !state.isManual_)
die(9);
const { scope_: scope } = state;
usePatchesInScope(scope, patchListener);
return processResult(void 0, scope);
}
/**
* Pass true to automatically freeze all copies created by Immer.
*
* By default, auto-freezing is enabled.
*/
setAutoFreeze(value) {
this.autoFreeze_ = value;
}
/**
* Pass true to enable strict shallow copy.
*
* By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.
*/
setUseStrictShallowCopy(value) {
this.useStrictShallowCopy_ = value;
}
applyPatches(base, patches) {
let i;
for (i = patches.length - 1; i >= 0; i--) {
const patch = patches[i];
if (patch.path.length === 0 && patch.op === "replace") {
base = patch.value;
break;
}
}
if (i > -1) {
patches = patches.slice(i + 1);
}
const applyPatchesImpl = getPlugin("Patches").applyPatches_;
if (isDraft(base)) {
return applyPatchesImpl(base, patches);
}
return this.produce(
base,
(draft) => applyPatchesImpl(draft, patches)
);
}
};
function createProxy(value, parent) {
const draft = isMap$1(value) ? getPlugin("MapSet").proxyMap_(value, parent) : isSet$1(value) ? getPlugin("MapSet").proxySet_(value, parent) : createProxyProxy(value, parent);
const scope = parent ? parent.scope_ : getCurrentScope();
scope.drafts_.push(draft);
return draft;
}
function current(value) {
if (!isDraft(value))
die(10, value);
return currentImpl(value);
}
function currentImpl(value) {
if (!isDraftable(value) || isFrozen(value))
return value;
const state = value[DRAFT_STATE];
let copy2;
if (state) {
if (!state.modified_)
return state.base_;
state.finalized_ = true;
copy2 = shallowCopy(value, state.scope_.immer_.useStrictShallowCopy_);
} else {
copy2 = shallowCopy(value, true);
}
each(copy2, (key, childValue) => {
set(copy2, key, currentImpl(childValue));
});
if (state) {
state.finalized_ = false;
}
return copy2;
}
function enableMapSet() {
class DraftMap extends Map {
constructor(target, parent) {
super();
this[DRAFT_STATE] = {
type_: 2,
parent_: parent,
scope_: parent ? parent.scope_ : getCurrentScope(),
modified_: false,
finalized_: false,
copy_: void 0,
assigned_: void 0,
base_: target,
draft_: this,
isManual_: false,
revoked_: false
};
}
get size() {
return latest(this[DRAFT_STATE]).size;
}
has(key) {
return latest(this[DRAFT_STATE]).has(key);
}
set(key, value) {
const state = this[DRAFT_STATE];
assertUnrevoked(state);
if (!latest(state).has(key) || latest(state).get(key) !== value) {
prepareMapCopy(state);
markChanged(state);
state.assigned_.set(key, true);
state.copy_.set(key, value);
state.assigned_.set(key, true);
}
return this;
}
delete(key) {
if (!this.has(key)) {
return false;
}
const state = this[DRAFT_STATE];
assertUnrevoked(state);
prepareMapCopy(state);
markChanged(state);
if (state.base_.has(key)) {
state.assigned_.set(key, false);
} else {
state.assigned_.delete(key);
}
state.copy_.delete(key);
return true;
}
clear() {
const state = this[DRAFT_STATE];
assertUnrevoked(state);
if (latest(state).size) {
prepareMapCopy(state);
markChanged(state);
state.assigned_ = /* @__PURE__ */ new Map();
each(state.base_, (key) => {
state.assigned_.set(key, false);
});
state.copy_.clear();
}
}
forEach(cb, thisArg) {
const state = this[DRAFT_STATE];
latest(state).forEach((_value, key, _map) => {
cb.call(thisArg, this.get(key), key, this);
});
}
get(key) {
const state = this[DRAFT_STATE];
assertUnrevoked(state);
const value = latest(state).get(key);
if (state.finalized_ || !isDraftable(value)) {
return value;
}
if (value !== state.base_.get(key)) {
return value;
}
const draft = createProxy(value, state);
prepareMapCopy(state);
state.copy_.set(key, draft);
return draft;
}
keys() {
return latest(this[DRAFT_STATE]).keys();
}
values() {
const iterator = this.keys();
return {
[Symbol.iterator]: () => this.values(),
next: () => {
const r = iterator.next();
if (r.done)
return r;
const value = this.get(r.value);
return {
done: false,
value
};
}
};
}
entries() {
const iterator = this.keys();
return {
[Symbol.iterator]: () => this.entries(),
next: () => {
const r = iterator.next();
if (r.done)
return r;
const value = this.get(r.value);
return {
done: false,
value: [r.value, value]
};
}
};
}
[Symbol.iterator]() {
return this.entries();
}
}
function proxyMap_(target, parent) {
return new DraftMap(target, parent);
}
function prepareMapCopy(state) {
if (!state.copy_) {
state.assigned_ = /* @__PURE__ */ new Map();
state.copy_ = new Map(state.base_);
}
}
class DraftSet extends Set {
constructor(target, parent) {
super();
this[DRAFT_STATE] = {
type_: 3,
parent_: parent,
scope_: parent ? parent.scope_ : getCurrentScope(),
modified_: false,
finalized_: false,
copy_: void 0,
base_: target,
draft_: this,
drafts_: /* @__PURE__ */ new Map(),
revoked_: false,
isManual_: false
};
}
get size() {
return latest(this[DRAFT_STATE]).size;
}
has(value) {
const state = this[DRAFT_STATE];
assertUnrevoked(state);
if (!state.copy_) {
return state.base_.has(value);
}
if (state.copy_.has(value))
return true;
if (state.drafts_.has(value) && state.copy_.has(state.drafts_.get(value)))
return true;
return false;
}
add(value) {
const state = this[DRAFT_STATE];
assertUnrevoked(state);
if (!this.has(value)) {
prepareSetCopy(state);
markChanged(state);
state.copy_.add(value);
}
return this;
}
delete(value) {
if (!this.has(value)) {
return false;
}
const state = this[DRAFT_STATE];
assertUnrevoked(state);
prepareSetCopy(state);
markChanged(state);
return state.copy_.delete(value) || (state.drafts_.has(value) ? state.copy_.delete(state.drafts_.get(value)) : (
/* istanbul ignore next */
false
));
}
clear() {
const state = this[DRAFT_STATE];
assertUnrevoked(state);
if (latest(state).size) {
prepareSetCopy(state);
markChanged(state);
state.copy_.clear();
}
}
values() {
const state = this[DRAFT_STATE];
assertUnrevoked(state);
prepareSetCopy(state);
return state.copy_.values();
}
entries() {
const state = this[DRAFT_STATE];
assertUnrevoked(state);
prepareSetCopy(state);
return state.copy_.entries();
}
keys() {
return this.values();
}
[Symbol.iterator]() {
return this.values();
}
forEach(cb, thisArg) {
const iterator = this.values();
let result = iterator.next();
while (!result.done) {
cb.call(thisArg, result.value, result.value, this);
result = iterator.next();
}
}
}
function proxySet_(target, parent) {
return new DraftSet(target, parent);
}
function prepareSetCopy(state) {
if (!state.copy_) {
state.copy_ = /* @__PURE__ */ new Set();
state.base_.forEach((value) => {
if (isDraftable(value)) {
const draft = createProxy(value, state);
state.drafts_.set(value, draft);
state.copy_.add(draft);
} else {
state.copy_.add(value);
}
});
}
}
function assertUnrevoked(state) {
if (state.revoked_)
die(3, JSON.stringify(latest(state)));
}
loadPlugin("MapSet", { proxyMap_, proxySet_ });
}
function enablePatches() {
const errorOffset = 16;
if (process.env.NODE_ENV !== "production") {
errors.push(
'Sets cannot have "replace" patches.',
function(op) {
return "Unsupported patch operation: " + op;
},
function(path4) {
return "Cannot apply patch, path doesn't resolve: " + path4;
},
"Patching reserved attributes like __proto__, prototype and constructor is not allowed"
);
}
const REPLACE = "replace";
const ADD = "add";
const REMOVE = "remove";
function generatePatches_(state, basePath, patches, inversePatches) {
switch (state.type_) {
case 0:
case 2:
return generatePatchesFromAssigned(
state,
basePath,
patches,
inversePatches
);
case 1:
return generateArrayPatches(state, basePath, patches, inversePatches);
case 3:
return generateSetPatches(
state,
basePath,
patches,
inversePatches
);
}
}
function generateArrayPatches(state, basePath, patches, inversePatches) {
let { base_, assigned_ } = state;
let copy_ = state.copy_;
if (copy_.length < base_.length) {
[base_, copy_] = [copy_, base_];
[patches, inversePatches] = [inversePatches, patches];
}
for (let i = 0; i < base_.length; i++) {
if (assigned_[i] && copy_[i] !== base_[i]) {
const path4 = basePath.concat([i]);
patches.push({
op: REPLACE,
path: path4,
// Need to maybe clone it, as it can in fact be the original value
// due to the base/copy inversion at the start of this function
value: clonePatchValueIfNeeded(copy_[i])
});
inversePatches.push({
op: REPLACE,
path: path4,
value: clonePatchValueIfNeeded(base_[i])
});
}
}
for (let i = base_.length; i < copy_.length; i++) {
const path4 = basePath.concat([i]);
patches.push({
op: ADD,
path: path4,
// Need to maybe clone it, as it can in fact be the original value
// due to the base/copy inversion at the start of this function
value: clonePatchValueIfNeeded(copy_[i])
});
}
for (let i = copy_.length - 1; base_.length <= i; --i) {
const path4 = basePath.concat([i]);
inversePatches.push({
op: REMOVE,
path: path4
});
}
}
function generatePatchesFromAssigned(state, basePath, patches, inversePatches) {
const { base_, copy_ } = state;
each(state.assigned_, (key, assignedValue) => {
const origValue = get(base_, key);
const value = get(copy_, key);
const op = !assignedValue ? REMOVE : has(base_, key) ? REPLACE : ADD;
if (origValue === value && op === REPLACE)
return;
const path4 = basePath.concat(key);
patches.push(op === REMOVE ? { op, path: path4 } : { op, path: path4, value });
inversePatches.push(
op === ADD ? { op: REMOVE, path: path4 } : op === REMOVE ? { op: ADD, path: path4, value: clonePatchValueIfNeeded(origValue) } : { op: REPLACE, path: path4, value: clonePatchValueIfNeeded(origValue) }
);
});
}
function generateSetPatches(state, basePath, patches, inversePatches) {
let { base_, copy_ } = state;
let i = 0;
base_.forEach((value) => {
if (!copy_.has(value)) {
const path4 = basePath.concat([i]);
patches.push({
op: REMOVE,
path: path4,
value
});
inversePatches.unshift({
op: ADD,
path: path4,
value
});
}
i++;
});
i = 0;
copy_.forEach((value) => {
if (!base_.has(value)) {
const path4 = basePath.concat([i]);
patches.push({
op: ADD,
path: path4,
value
});
inversePatches.unshift({
op: REMOVE,
path: path4,
value
});
}
i++;
});
}
function generateReplacementPatches_(baseValue, replacement, patches, inversePatches) {
patches.push({
op: REPLACE,
path: [],
value: replacement === NOTHING ? void 0 : replacement
});
inversePatches.push({
op: REPLACE,
path: [],
value: baseValue
});
}
function applyPatches_(draft, patches) {
patches.forEach((patch) => {
const { path: path4, op } = patch;
let base = draft;
for (let i = 0; i < path4.length - 1; i++) {
const parentType = getArchtype(base);
let p = path4[i];
if (typeof p !== "string" && typeof p !== "number") {
p = "" + p;
}
if ((parentType === 0 || parentType === 1) && (p === "__proto__" || p === "constructor"))
die(errorOffset + 3);
if (typeof base === "function" && p === "prototype")
die(errorOffset + 3);
base = get(base, p);
if (typeof base !== "object")
die(errorOffset + 2, path4.join("/"));
}
const type = getArchtype(base);
const value = deepClonePatchValue(patch.value);
const key = path4[path4.length - 1];
switch (op) {
case REPLACE:
switch (type) {
case 2:
return base.set(key, value);
case 3:
die(errorOffset);
default:
return base[key] = value;
}
case ADD:
switch (type) {
case 1:
return key === "-" ? base.push(value) : base.splice(key, 0, value);
case 2:
return base.set(key, value);
case 3:
return base.add(value);
default:
return base[key] = value;
}
case REMOVE:
switch (type) {
case 1:
return base.splice(key, 1);
case 2:
return base.delete(key);
case 3:
return base.delete(patch.value);
default:
return delete base[key];
}
default:
die(errorOffset + 1, op);
}
});
return draft;
}
function deepClonePatchValue(obj) {
if (!isDraftable(obj))
return obj;
if (Array.isArray(obj))
return obj.map(deepClonePatchValue);
if (isMap$1(obj))
return new Map(
Array.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)])
);
if (isSet$1(obj))
return new Set(Array.from(obj).map(deepClonePatchValue));
const cloned = Object.create(getPrototypeOf(obj));
for (const key in obj)
cloned[key] = deepClonePatchValue(obj[key]);
if (has(obj, DRAFTABLE))
cloned[DRAFTABLE] = obj[DRAFTABLE];
return cloned;
}
function clonePatchValueIfNeeded(obj) {
if (isDraft(obj)) {
return deepClonePatchValue(obj);
} else
return obj;
}
loadPlugin("Patches", {
applyPatches_,
generatePatches_,
generateReplacementPatches_
});
}
var immer = new Immer2();
immer.produce;
var produceWithPatches = immer.produceWithPatches.bind(
immer
);
immer.setAutoFreeze.bind(immer);
immer.setUseStrictShallowCopy.bind(immer);
var applyPatches = immer.applyPatches.bind(immer);
immer.createDraft.bind(immer);
immer.finishDraft.bind(immer);
enableMapSet();
enablePatches();
function cwt(...allTags) {
return allTags.filter((tags) => tags !== void 0).reduce((acc, tags) => acc.concat(tags), []);
}
function makeRootReplacingPatches(value) {
return [
{
op: "replace",
path: [],
value
}
];
}
function makeSetterWithPatches(update, prependTagsFn) {
const setter = (value, tags) => {
update(() => [value, makeRootReplacingPatches(value)], cwt(prependTagsFn?.(), tags));
};
setter.withProducer = (producer, tags) => {
update((oldData) => {
const [newData, patches] = produceWithPatches(oldData, producer);
if (isAvailable(newData)) {
return [newData, patches];
}
throw new Error("Cannot update value to NOT_AVAILABLE");
}, cwt(prependTagsFn?.(), tags));
};
setter.withUpdater = (updater, tags) => {
update((oldData) => {
const newData = updater(oldData);
return [newData, makeRootReplacingPatches(newData)];
}, cwt(prependTagsFn?.(), tags));
};
setter.withPatchUpdater = (updater, tags) => {
update(updater, cwt(prependTagsFn?.(), tags));
};
setter.withPatches = (patches, tags) => {
update((oldData) => {
return [applyPatches(oldData, patches), patches];
}, cwt(prependTagsFn?.(), tags));
};
setter.withValueAndPatches = (newValue, patches, tags) => {
update(() => [newValue, patches], cwt(prependTagsFn?.(), tags));
};
return setter;
}
var equals = (a, b) => a === b;
var Signal = class _Signal extends Subscribable {
/**
* Creates a signal.
*
* @param value - The initial value of the signal.
* @param equalsPredicate - A function to compare two values. The subscribers will only be called
* if the value changes according to the `equalsPredicate`. By default, it uses the `===`
* operator.
* @returns This method returns a tuple with two elements:
* - The signal
* - A function to update the value
**/
static create(value, equalsPredicate = equals) {
const signal = new _Signal(value, equalsPredicate);
const update = (updater, tags) => {
signal.update(updater, tags);
};
const setter = makeSetterWithPatches(update);
return [signal, setter];
}
static createReadonly(value) {
return _Signal.create(value)[0];
}
constructor(value, equalsPredicate) {
super();
this.value = value;
this.equalsPredicate = equalsPredicate;
this.subscribers = /* @__PURE__ */ new Set();
this.queuedUpdaters = [];
this.isEmitting = false;
}
/**
* Returns the current value of the signal.
*/
get() {
return this.value;
}
pull() {
return this.value;
}
notifyFull(value, patches, tags) {
for (const { type, callback } of this.subscribers) {
if (type === "full") {
callback(value, patches, tags);
}
}
}
notifyAll(value, patches, tags) {
for (const { type, callback } of this.subscribers) {
if (type === "regular") {
callback(value);
} else {
callback(value, patches, tags);
}
}
}
notifyAndUpdateIfChanged(value, patches, tags) {
if (!this.equalsPredicate(this.value, value)) {
this.value = value;
this.notifyAll(value, patches, tags);
} else if (tags.length > 0) {
this.notifyFull(value, patches, tags);
}
}
isReplaceRoot(patch) {
return patch.path.length === 0 && patch.op === "replace";
}
update(updater, tags) {
this.queuedUpdaters.push([updater, tags]);
if (this.isEmitting) {
return;
}
this.isEmitting = true;
try {
while (this.queuedUpdaters.length > 0) {
let value = this.value;
let patches = [];
const tags2 = [];
while (this.queuedUpdaters.length > 0) {
const [updater2, newTags] = this.queuedUpdaters.shift();
const [newValue, newPatches] = updater2(value);
value = newValue;
const rootReplacerIndex = newPatches.findIndex(this.isReplaceRoot);
if (rootReplacerIndex !== -1) {
patches = newPatches.slice(rootReplacerIndex);
} else {
patches.push(...newPatches);
}
if (newTags !== void 0) {
tags2.push(...newTags);
}
}
this.notifyAndUpdateIfChanged(value, patches, tags2);
}
} finally {
this.isEmitting = false;
}
}
/**
* Subscribes to the signal. The callback will be called whenever the value changes. All callbacks
* are called synchronously upon updating. It will NOT be immediately called with the current
* value. (Use `get()` to get the current value.) Returns a function to unsubscribe.
*
* Edge cases involving manipulating the signal in the callback:
*
* - If the callback adds new subscribers, they will also be called within the same update.
* - If the callback causes removal of subscribers that have not been called yet, they will no
* longer be called.
* - If the callback causes an update of the value, the update will be queued. If multiple updates
* are queued, only the last one will be executed.
*
* Edge cases involving adding the same callback multiple times.
*
* - Callbacks are tracked with a set. Adding the same subscriber will not cause it to be called
* multiple times.
*/
subscribe(callback) {
const subscriber = {
type: "regular",
callback
};
this.subscribers.add(subscriber);
return () => {
this.subscribers.delete(subscriber);
};
}
/**
* Subscribes to the signal with the callback and trigger the callback immediately with the
* current value.
*/
subscribeAndNow(callback) {
const unsubscribe = this.subscribe(callback);
callback(this.value);
return unsubscribe;
}
subscribeFull(callback) {
const subscriber = {
type: "full",
callback
};
this.subscribers.add(subscriber);
return () => {
this.subscribers.delete(subscriber);
};
}
/**
* Wait until the signal satisfies a predicate. If the predicate is already satisfied, it will
* return immediately. Otherwise, it will wait until the signal satisfies the predicate.
*/
async until(predicate) {
const current2 = this.get();
if (predicate(current2)) {
return current2;
}
const { promise, resolve } = makePromise();
const unsubscribe = this.subscribe((data) => {
if (predicate(data)) {
resolve(data);
unsubscribe();
}
});
return await promise;
}
};
function isAvailable(data) {
return data !== LazySignal.NOT_AVAILABLE;
}
var LazySignal = class _LazySignal extends Subscribable {
static {
this.NOT_AVAILABLE = /* @__PURE__ */ Symbol("notAvailable");
}
static create(initialValue, subscribeUpstream, equalsPredicate = (a, b) => a === b) {
return new _LazySignal(initialValue, subscribeUpstream, equalsPredicate);
}
static createWithoutInitialValue(subscribeUpstream, equalsPredicate = (a, b) => a === b) {
const fullEqualsPredicate = (a, b) => {
if (a === _LazySignal.NOT_AVAILABLE || b === _LazySignal.NOT_AVAILABLE) {
return a === b;
}
return equalsPredicate(a, b);
};
return new _LazySignal(_LazySignal.NOT_AVAILABLE, subscribeUpstream, fullEqualsPredicate);
}
static deriveFrom(sourceSignals, deriver, outputEqualsPredicate) {
let fullEqualsPredicate = void 0;
if (outputEqualsPredicate !== void 0) {
fullEqualsPredicate = (a, b) => {
if (a === _LazySignal.NOT_AVAILABLE || b === _LazySignal.NOT_AVAILABLE) {
return a === b;
}
return outputEqualsPredicate(a, b);
};
}
const derive = () => {
const sourceValues = sourceSignals.map((signal) => signal.get());
if (sourceValues.some((value) => value === _LazySignal.NOT_AVAILABLE)) {
return _LazySignal.NOT_AVAILABLE;
}
return deriver(...sourceValues);
};
return new _LazySignal(derive(), (setDownstream) => {
const unsubscriber = sourceSignals.map((signal) => signal.subscribe(() => {
const value = derive();
if (isAvailable(value)) {
setDownstream(value);
}
}));
const newValue = derive();
if (isAvailable(newValue)) {
setDownstream(newValue);
}
return () => {
unsubscriber.forEach((unsub) => unsub());
};
}, fullEqualsPredicate);
}
static asyncDeriveFrom(strategy, sourceSignals, deriver, outputEqualsPredicate) {
let fullEqualsPredicate = void 0;
if (outputEqualsPredicate !== void 0) {
fullEqualsPredicate = (a, b) => {
if (a === _LazySignal.NOT_AVAILABLE || b === _LazySignal.NOT_AVAILABLE) {
return a === b;
}
return outputEqualsPredicate(a, b);
};
}
let lastAppliedUpdateId = -1;
let lastIssuedUpdateId = -1;
return new _LazySignal(_LazySignal.NOT_AVAILABLE, (setDownstream) => {
const deriveAndUpdate = () => {
lastIssuedUpdateId++;
const updateId = lastIssuedUpdateId;
const sourceValues = sourceSignals.map((signal) => signal.get());
if (sourceValues.some((value) => value === _LazySignal.NOT_AVAILABLE)) {
return;
}
deriver(...sourceValues).then((result) => {
if (!isAvailable(result)) {
return;
}
switch (strategy) {
case "eager": {
if (updateId > lastAppliedUpdateId) {
lastAppliedUpdateId = updateId;
setDownstream(result);
}
break;
}
default: {
const exhaustiveCheck = strategy;
throw new Error(`Unknown strategy: ${exhaustiveCheck}`);
}
}
});
};
const unsubscriber = sourceSignals.map((signal) => signal.subscribe(() => {
deriveAndUpdate();
}));
deriveAndUpdate();
return () => {
unsubscriber.forEach((unsub) => unsub());
};
}, fullEqualsPredicate);
}
constructor(initialValue, subscribeUpstream, equalsPredicate = (a, b) => a === b) {
super();
this.subscribeUpstream = subscribeUpstream;
this.dataIsStale = true;
this.upstreamUnsubscribe = null;
this.subscribersCount = 0;
this.isSubscribedToUpstream = false;
this.updateReceivedSynchronousCallbacks = /* @__PURE__ */ new Set();
[this.signal, this.setValue] = Signal.create(initialValue, equalsPredicate);
[this.updateReceivedEvent, this.emitUpdateReceivedEvent] = Event.create();
}
/**
* Returns whether the value is currently stale.
*
* A value is stale whenever the upstream subscription is not active. This can happen in three
* cases:
*
* 1. When no subscriber is attached to this signal, the signal will not subscribe to the
* upstream. In this case, the value is always stale.
* 2. When a subscriber is attached, but the upstream has not yet emitted a single value, the
* value is also stale.
* 3. When the upstream has emitted an error. In this case, the subscription to the upstream is
* terminated and the value is stale.
*
* If you wish to get the current value and ensure that it is not stale, use the method
* {@link LazySignal#pull}.
*/
isStale() {
return this.dataIsStale;
}
subscribeToUpstream() {
this.isSubscribedToUpstream = true;
let subscribed = true;
let becameStale = false;
const unsubscribeFromUpstream = this.subscribeUpstream(makeSetterWithPatches((updater, tags) => {
if (!subscribed) {
return;
}
this.setValue.withPatchUpdater(updater, tags);
this.dataIsStale = becameStale;
this.emitUpdateReceivedEvent();
for (const callback of this.updateReceivedSynchronousCallbacks) {
callback();
}
}), (error) => {
if (!subscribed) {
return;
}
Promise.reject(error);
this.dataIsStale = true;
this.isSubscribedToUpstream = false;
this.upstreamUnsubscribe = null;
subscribed = false;
});
this.upstreamUnsubscribe = () => {
if (subscribed) {
subscribed = false;
becameStale = true;
unsubscribeFromUpstream();
}
};
}
unsubscribeFromUpstream() {
this.isSubscribedToUpstream = false;
if (this.upstreamUnsubscribe !== null) {
this.upstreamUnsubscribe();
this.upstreamUnsubscribe = null;
this.dataIsStale = true;
}
}
/**
* Gets the current value of the signal. If the value is not available, it will return
* {@link LazySignal.NOT_AVAILABLE}. (A value will only be unavailable if the signal is created
* without an initial value and the upstream has not emitted a value yet.)
*
* In addition, the value returned by this method may be stale. Use {@link LazySignal#isStale} to
* check if the value is stale.
*
* If you wish to get the current value and ensure that it is not stale, use the method
* {@link LazySignal#pull}.
*/
get() {
return this.signal.get();
}
/**
* Pulls the current value of the signal. If the value is stale, it will subscribe and wait for
* the next value from the upstream and return it.
*/
async pull() {
const { promise, resolve } = makePromise();
if (!this.isStale()) {
resolve(this.get());
} else {
const unsubscribe = this.subscribe(() => {
});
this.updateReceivedEvent.subscribeOnce(() => {
resolve(this.get());
});
promise.then(unsubscribe);
}
return promise;
}
/**
* If the data is not stale, the callback will be called synchronously with the current value.
*
* If the data is stale, it will pull the current value and call the callback with the value.
*/
runOnNextFreshData(callback) {
if (!this.isStale()) {
callback(this.get());
} else {
let unsubscribe = null;
const updateCallback = () => {
this.updateReceivedSynchronousCallbacks.delete(updateCallback);
callback(this.get());
unsubscribe?.();
};
this.updateReceivedSynchronousCallbacks.add(updateCallback);
unsubscribe = this.subscribe(() => {
});
}
}
async ensureAvailable() {
await this.pull();
return this;
}
subscribe(subscriber) {
if (!this.isSubscribedToUpstream) {
this.subscribeToUpstream();
}
this.subscribersCount++;
const unsubscribe = this.signal.subscribe(subscriber);
let unsubscribeCalled = false;
return () => {
if (unsubscribeCalled) {
return;
}
unsubscribe();
unsubscribeCalled = true;
this.subscribersCount--;
if (this.subscribersCount === 0 && this.isSubscribedToUpstream) {
this.unsubscribeFromUpstream();
}
};
}
subscribeFull(subscriber) {
if (!this.isSubscribedToUpstream) {
this.subscribeToUpstream();
}
this.subscribersCount++;
const unsubscribe = this.signal.subscribeFull(subscriber);
let unsubscribeCalled = false;
return () => {
if (unsubscribeCalled) {
return;
}
unsubscribe();
unsubscribeCalled = true;
this.subscribersCount--;
if (this.subscribersCount === 0 && this.isSubscribedToUpstream) {
this.unsubscribeFromUpstream();
}
};
}
/**
* Subscribes to the signal. Will not cause the signal to subscribe to the upstream.
*/
passiveSubscribe(subscriber) {
return this.signal.subscribe(subscriber);
}
passiveSubscribeFull(subscriber) {
return this.signal.subscribeFull(subscriber);
}
async until(predicate) {
const current2 = this.get();
if (isAvailable(current2) && predicate(current2)) {
return current2;
}
const { promise, resolve } = makePromise();
const unsubscribe = this.subscribe((data) => {
if (isAvailable(data) && predicate(data)) {
resolve(data);
unsubscribe();
}
});
return await promise;
}
};
function getCurrentStack(goAbove = 0) {
const stack = new Error().stack;
if (!stack) {
return "";
}
const lines = stack.split("\n");
return lines.slice(2 + goAbove).join("\n");
}
function changeErrorStackInPlace(error, newStack) {
if (import_process.default.env.LMS_KEEP_INTERNAL_STACK) {
return;
}
const stackContent = error.stack ?? "";
error.stack = (stackContent.substring(0, stackContent.indexOf("\n at ")).trimEnd() + "\n" + newStack).trimEnd();
}
var IdGiver = class {
constructor(firstId = 0) {
this.nextId = firstId;
}
next() {
const id = this.nextId;
this.nextId++;
return id;
}
};
function getDefaultExportFromCjs(x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
}
var boxen$1 = { exports: {} };
var stringWidth = { exports: {} };
var ansiRegex;
var hasRequiredAnsiRegex;
function requireAnsiRegex() {
if (hasRequiredAnsiRegex) return ansiRegex;
hasRequiredAnsiRegex = 1;
ansiRegex = ({ onlyFirst = false } = {}) => {
const pattern = [
"[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
"(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"
].join("|");
return new RegExp(pattern, onlyFirst ? void 0 : "g");
};
return ansiRegex;
}
var stripAnsi;
var hasRequiredStripAnsi;
function requireStripAnsi() {
if (hasRequiredStripAnsi) return stripAnsi;
hasRequiredStripAnsi = 1;
const ansiRegex2 = requireAnsiRegex();
stripAnsi = (string) => typeof string === "string" ? string.replace(ansiRegex2(), "") : string;
return stripAnsi;
}
var isFullwidthCodePoint = { exports: {} };
var hasRequiredIsFullwidthCodePoint;
function requireIsFullwidthCodePoint() {
if (hasRequiredIsFullwidthCodePoint) return isFullwidthCodePoint.exports;
hasRequiredIsFullwidthCodePoint = 1;
const isFullwidthCodePoint$1 = (codePoint) => {
if (Number.isNaN(codePoint)) {
return false;
}
if (codePoint >= 4352 && (codePoint <= 4447 || // Hangul Jamo
codePoint === 9001 || // LEFT-POINTING ANGLE BRACKET
codePoint === 9002 || // RIGHT-POINTING ANGLE BRACKET
// CJK Radicals Supplement .. Enclosed CJK Letters and Months
11904 <= codePoint && codePoint <= 12871 && codePoint !== 12351 || // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A
12880 <= codePoint && codePoint <= 19903 || // CJK Unified Ideographs .. Yi Radicals
19968 <= codePoint && codePoint <= 42182 || // Hangul Jamo Extended-A
43360 <= codePoint && codePoint <= 43388 || // Hangul Syllables
44032 <= codePoint && codePoint <= 55203 || // CJK Compatibility Ideographs
63744 <= codePoint && codePoint <= 64255 || // Vertical Forms
65040 <= codePoint && codePoint <= 65049 || // CJK Compatibility Forms .. Small Form Variants
65072 <= codePoint && codePoint <= 65131 || // Halfwidth and Fullwidth Forms
65281 <= codePoint && codePoint <= 65376 || 65504 <= codePoint && codePoint <= 65510 || // Kana Supplement
110592 <= codePoint && codePoint <= 110593 || // Enclosed Ideographic Supplement
127488 <= codePoint && codePoint <= 127569 || // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane
131072 <= codePoint && codePoint <= 262141)) {
return true;
}
return false;
};
isFullwidthCodePoint.exports = isFullwidthCodePoint$1;
isFullwidthCodePoint.exports.default = isFullwidthCodePoint$1;
return isFullwidthCodePoint.exports;
}
var emojiRegex2;
var hasRequiredEmojiRegex;
function requireEmojiRegex() {
if (hasRequiredEmojiRegex) return emojiRegex2;
hasRequiredEmojiRegex = 1;
emojiRegex2 = function() {
return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g;
};
return emojiRegex2;
}
var hasRequiredStringWidth;
function requireStringWidth() {
if (hasRequiredStringWidth) return stringWidth.exports;
hasRequiredStringWidth = 1;
const stripAnsi2 = requireStripAnsi();
const isFullwidthCodePoint2 = requireIsFullwidthCodePoint();
const emojiRegex3 = requireEmojiRegex();
const stringWidth$1 = (string) => {
if (typeof string !== "string" || string.length === 0) {
return 0;
}
string = stripAnsi2(string);
if (string.length === 0) {
return 0;
}
string = string.replace(emojiRegex3(), " ");
let width = 0;
for (let i = 0; i < string.length; i++) {
const code = string.codePointAt(i);
if (code <= 31 || code >= 127 && code <= 159) {
continue;
}
if (code >= 768 && code <= 879) {
continue;
}
if (code > 65535) {
i++;
}
width += isFullwidthCodePoint2(code) ? 2 : 1;
}
return width;
};
stringWidth.exports = stringWidth$1;
stringWidth.exports.default = stringWidth$1;
return stringWidth.exports;
}
var widestLine = { exports: {} };
var hasRequiredWidestLine;
function requireWidestLine() {
if (hasRequiredWidestLine) return widestLine.exports;
hasRequiredWidestLine = 1;
const stringWidth2 = requireStringWidth();
const widestLine$1 = (input) => {
let max = 0;
for (const line of input.split("\n")) {
max = Math.max(max, stringWidth2(line));
}
return max;
};
widestLine.exports = widestLine$1;
widestLine.exports.default = widestLine$1;
return widestLine.exports;
}
var cliBoxes = { exports: {} };
var single = {
topLeft: "\u250C",
topRight: "\u2510",
bottomRight: "\u2518",
bottomLeft: "\u2514",
vertical: "\u2502",
horizontal: "\u2500"
};
var double = {
topLeft: "\u2554",
topRight: "\u2557",
bottomRight: "\u255D",
bottomLeft: "\u255A",
vertical: "\u2551",
horizontal: "\u2550"
};
var round = {
topLeft: "\u256D",
topRight: "\u256E",
bottomRight: "\u256F",
bottomLeft: "\u2570",
vertical: "\u2502",
horizontal: "\u2500"
};
var bold = {
topLeft: "\u250F",
topRight: "\u2513",
bottomRight: "\u251B",
bottomLeft: "\u2517",
vertical: "\u2503",
horizontal: "\u2501"
};
var singleDouble = {
topLeft: "\u2553",
topRight: "\u2556",
bottomRight: "\u255C",
bottomLeft: "\u2559",
vertical: "\u2551",
horizontal: "\u2500"
};
var doubleSingle = {
topLeft: "\u2552",
topRight: "\u2555",
bottomRight: "\u255B",
bottomLeft: "\u2558",
vertical: "\u2502",
horizontal: "\u2550"
};
var classic = {
topLeft: "+",
topRight: "+",
bottomRight: "+",
bottomLeft: "+",
vertical: "|",
horizontal: "-"
};
var require$$0 = {
single,
double,
round,
bold,
singleDouble,
doubleSingle,
classic
};
var hasRequiredCliBoxes;
function requireCliBoxes() {
if (hasRequiredCliBoxes) return cliBoxes.exports;
hasRequiredCliBoxes = 1;
const cliBoxes$1 = require$$0;
cliBoxes.exports = cliBoxes$1;
cliBoxes.exports.default = cliBoxes$1;
return cliBoxes.exports;
}
var camelcase = { exports: {} };
var hasRequiredCamelcase;
function requireCamelcase() {
if (hasRequiredCamelcase) return camelcase.exports;
hasRequiredCamelcase = 1;
const UPPERCASE = /[\p{Lu}]/u;
const LOWERCASE = /[\p{Ll}]/u;
const LEADING_CAPITAL = /^[\p{Lu}](?![\p{Lu}])/gu;
const IDENTIFIER = /([\p{Alpha}\p{N}_]|$)/u;
const SEPARATORS = /[_.\- ]+/;
const LEADING_SEPARATORS = new RegExp("^" + SEPARATORS.source);
const SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, "gu");
const NUMBERS_AND_IDENTIFIER = new RegExp("\\d+" + IDENTIFIER.source, "gu");
const preserveCamelCase = (string, toLowerCase, toUpperCase) => {
let isLastCharLower = false;
let isLastCharUpper = false;
let isLastLastCharUpper = false;
for (let i = 0; i < string.length; i++) {
const character = string[i];
if (isLastCharLower && UPPERCASE.test(character)) {
string = string.slice(0, i) + "-" + string.slice(i);
isLastCharLower = false;
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper = true;
i++;
} else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character)) {
string = string.slice(0, i - 1) + "-" + string.slice(i - 1);
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper = false;
isLastCharLower = true;
} else {
isLastCharLower = toLowerCase(character) === character && toUpperCase(character) !== character;
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper = toUpperCase(character) === character && toLowerCase(character) !== character;
}
}
return string;
};
const preserveConsecutiveUppercase = (input, toLowerCase) => {
LEADING_CAPITAL.lastIndex = 0;
return input.replace(LEADING_CAPITAL, (m1) => toLowerCase(m1));
};
const postProcess = (input, toUpperCase) => {
SEPARATORS_AND_IDENTIFIER.lastIndex = 0;
NUMBERS_AND_IDENTIFIER.lastIndex = 0;
return input.replace(SEPARATORS_AND_IDENTIFIER, (_, identifier) => toUpperCase(identifier)).replace(NUMBERS_AND_IDENTIFIER, (m) => toUpperCase(m));
};
const camelCase = (input, options) => {
if (!(typeof input === "string" || Array.isArray(input))) {
throw new TypeError("Expected the input to be `string | string[]`");
}
options = {
pascalCase: false,
preserveConsecutiveUppercase: false,
...options
};
if (Array.isArray(input)) {
input = input.map((x) => x.trim()).filter((x) => x.length).join("-");
} else {
input = input.trim();
}
if (input.length === 0) {
return "";
}
const toLowerCase = options.locale === false ? (string) => string.toLowerCase() : (string) => string.toLocaleLowerCase(options.locale);
const toUpperCase = options.locale === false ? (string) => string.toUpperCase() : (string) => string.toLocaleUpperCase(options.locale);
if (input.length === 1) {
return options.pascalCase ? toUpperCase(input) : toLowerCase(input);
}
const hasUpperCase = input !== toLowerCase(input);
if (hasUpperCase) {
input = preserveCamelCase(input, toLowerCase, toUpperCase);
}
input = input.replace(LEADING_SEPARATORS, "");
if (options.preserveConsecutiveUppercase) {
input = preserveConsecutiveUppercase(input, toLowerCase);
} else {
input = toLowerCase(input);
}
if (options.pascalCase) {
input = toUpperCase(input.charAt(0)) + input.slice(1);
}
return postProcess(input, toUpperCase);
};
camelcase.exports = camelCase;
camelcase.exports.default = camelCase;
return camelcase.exports;
}
var ansiAlign_1;
var hasRequiredAnsiAlign;
function requireAnsiAlign() {
if (hasRequiredAnsiAlign) return ansiAlign_1;
hasRequiredAnsiAlign = 1;
const stringWidth2 = requireStringWidth();
function ansiAlign(text2, opts) {
if (!text2) return text2;
opts = opts || {};
const align = opts.align || "center";
if (align === "left") return text2;
const split = opts.split || "\n";
const pad = opts.pad || " ";
const widthDiffFn = align !== "right" ? halfDiff : fullDiff;
let returnString = false;
if (!Array.isArray(text2)) {
returnString = true;
text2 = String(text2).split(split);
}
let width;
let maxWidth = 0;
text2 = text2.map(function(str) {
str = String(str);
width = stringWidth2(str);
maxWidth = Math.max(width, maxWidth);
return {
str,
width
};
}).map(function(obj) {
return new Array(widthDiffFn(maxWidth, obj.width) + 1).join(pad) + obj.str;
});
return returnString ? text2.join(split) : text2;
}
ansiAlign.left = function left(text2) {
return ansiAlign(text2, { align: "left" });
};
ansiAlign.center = function center(text2) {
return ansiAlign(text2, { align: "center" });
};
ansiAlign.right = function right(text2) {
return ansiAlign(text2, { align: "right" });
};
ansiAlign_1 = ansiAlign;
function halfDiff(maxWidth, curWidth) {
return Math.floor((maxWidth - curWidth) / 2);
}
function fullDiff(maxWidth, curWidth) {
return maxWidth - curWidth;
}
return ansiAlign_1;
}
var ansiStyles = { exports: {} };
var colorName;
var hasRequiredColorName;
function requireColorName() {
if (hasRequiredColorName) return colorName;
hasRequiredColorName = 1;
colorName = {
"aliceblue": [240, 248, 255],
"antiquewhite": [250, 235, 215],
"aqua": [0, 255, 255],
"aquamarine": [127, 255, 212],
"azure": [240, 255, 255],
"beige": [245, 245, 220],
"bisque": [255, 228, 196],
"black": [0, 0, 0],
"blanchedalmond": [255, 235, 205],
"blue": [0, 0, 255],
"blueviolet": [138, 43, 226],
"brown": [165, 42, 42],
"burlywood": [222, 184, 135],
"cadetblue": [95, 158, 160],
"chartreuse": [127, 255, 0],
"chocolate": [210, 105, 30],
"coral": [255, 127, 80],
"cornflowerblue": [100, 149, 237],
"cornsilk": [255, 248, 220],
"crimson": [220, 20, 60],
"cyan": [0, 255, 255],
"darkblue": [0, 0, 139],
"darkcyan": [0, 139, 139],
"darkgoldenrod": [184, 134, 11],
"darkgray": [169, 169, 169],
"darkgreen": [0, 100, 0],
"darkgrey": [169, 169, 169],
"darkkhaki": [189, 183, 107],
"darkmagenta": [139, 0, 139],
"darkolivegreen": [85, 107, 47],
"darkorange": [255, 140, 0],
"darkorchid": [153, 50, 204],
"darkred": [139, 0, 0],
"darksalmon": [233, 150, 122],
"darkseagreen": [143, 188, 143],
"darkslateblue": [72, 61, 139],
"darkslategray": [47, 79, 79],
"darkslategrey": [47, 79, 79],
"darkturquoise": [0, 206, 209],
"darkviolet": [148, 0, 211],
"deeppink": [255, 20, 147],
"deepskyblue": [0, 191, 255],
"dimgray": [105, 105, 105],
"dimgrey": [105, 105, 105],
"dodgerblue": [30, 144, 255],
"firebrick": [178, 34, 34],
"floralwhite": [255, 250, 240],
"forestgreen": [34, 139, 34],
"fuchsia": [255, 0, 255],
"gainsboro": [220, 220, 220],
"ghostwhite": [248, 248, 255],
"gold": [255, 215, 0],
"goldenrod": [218, 165, 32],
"gray": [128, 128, 128],
"green": [0, 128, 0],
"greenyellow": [173, 255, 47],
"grey": [128, 128, 128],
"honeydew": [240, 255, 240],
"hotpink": [255, 105, 180],
"indianred": [205, 92, 92],
"indigo": [75, 0, 130],
"ivory": [255, 255, 240],
"khaki": [240, 230, 140],
"lavender": [230, 230, 250],
"lavenderblush": [255, 240, 245],
"lawngreen": [124, 252, 0],
"lemonchiffon": [255, 250, 205],
"lightblue": [173, 216, 230],
"lightcoral": [240, 128, 128],
"lightcyan": [224, 255, 255],
"lightgoldenrodyellow": [250, 250, 210],
"lightgray": [211, 211, 211],
"lightgreen": [144, 238, 144],
"lightgrey": [211, 211, 211],
"lightpink": [255, 182, 193],
"lightsalmon": [255, 160, 122],
"lightseagreen": [32, 178, 170],
"lightskyblue": [135, 206, 250],
"lightslategray": [119, 136, 153],
"lightslategrey": [119, 136, 153],
"lightsteelblue": [176, 196, 222],
"lightyellow": [255, 255, 224],
"lime": [0, 255, 0],
"limegreen": [50, 205, 50],
"linen": [250, 240, 230],
"magenta": [255, 0, 255],
"maroon": [128, 0, 0],
"mediumaquamarine": [102, 205, 170],
"mediumblue": [0, 0, 205],
"mediumorchid": [186, 85, 211],
"mediumpurple": [147, 112, 219],
"mediumseagreen": [60, 179, 113],
"mediumslateblue": [123, 104, 238],
"mediumspringgreen": [0, 250, 154],
"mediumturquoise": [72, 209, 204],
"mediumvioletred": [199, 21, 133],
"midnightblue": [25, 25, 112],
"mintcream": [245, 255, 250],
"mistyrose": [255, 228, 225],
"moccasin": [255, 228, 181],
"navajowhite": [255, 222, 173],
"navy": [0, 0, 128],
"oldlace": [253, 245, 230],
"olive": [128, 128, 0],
"olivedrab": [107, 142, 35],
"orange": [255, 165, 0],
"orangered": [255, 69, 0],
"orchid": [218, 112, 214],
"palegoldenrod": [238, 232, 170],
"palegreen": [152, 251, 152],
"paleturquoise": [175, 238, 238],
"palevioletred": [219, 112, 147],
"papayawhip": [255, 239, 213],
"peachpuff": [255, 218, 185],
"peru": [205, 133, 63],
"pink": [255, 192, 203],
"plum": [221, 160, 221],
"powderblue": [176, 224, 230],
"purple": [128, 0, 128],
"rebeccapurple": [102, 51, 153],
"red": [255, 0, 0],
"rosybrown": [188, 143, 143],
"royalblue": [65, 105, 225],
"saddlebrown": [139, 69, 19],
"salmon": [250, 128, 114],
"sandybrown": [244, 164, 96],
"seagreen": [46, 139, 87],
"seashell": [255, 245, 238],
"sienna": [160, 82, 45],
"silver": [192, 192, 192],
"skyblue": [135, 206, 235],
"slateblue": [106, 90, 205],
"slategray": [112, 128, 144],
"slategrey": [112, 128, 144],
"snow": [255, 250, 250],
"springgreen": [0, 255, 127],
"steelblue": [70, 130, 180],
"tan": [210, 180, 140],
"teal": [0, 128, 128],
"thistle": [216, 191, 216],
"tomato": [255, 99, 71],
"turquoise": [64, 224, 208],
"violet": [238, 130, 238],
"wheat": [245, 222, 179],
"white": [255, 255, 255],
"whitesmoke": [245, 245, 245],
"yellow": [255, 255, 0],
"yellowgreen": [154, 205, 50]
};
return colorName;
}
var conversions;
var hasRequiredConversions;
function requireConversions() {
if (hasRequiredConversions) return conversions;
hasRequiredConversions = 1;
const cssKeywords = requireColorName();
const reverseKeywords = {};
for (const key of Object.keys(cssKeywords)) {
reverseKeywords[cssKeywords[key]] = key;
}
const convert = {
rgb: { channels: 3, labels: "rgb" },
hsl: { channels: 3, labels: "hsl" },
hsv: { channels: 3, labels: "hsv" },
hwb: { channels: 3, labels: "hwb" },
cmyk: { channels: 4, labels: "cmyk" },
xyz: { channels: 3, labels: "xyz" },
lab: { channels: 3, labels: "lab" },
lch: { channels: 3, labels: "lch" },
hex: { channels: 1, labels: ["hex"] },
keyword: { channels: 1, labels: ["keyword"] },
ansi16: { channels: 1, labels: ["ansi16"] },
ansi256: { channels: 1, labels: ["ansi256"] },
hcg: { channels: 3, labels: ["h", "c", "g"] },
apple: { channels: 3, labels: ["r16", "g16", "b16"] },
gray: { channels: 1, labels: ["gray"] }
};
conversions = convert;
for (const model of Object.keys(convert)) {
if (!("channels" in convert[model])) {
throw new Error("missing channels property: " + model);
}
if (!("labels" in convert[model])) {
throw new Error("missing channel labels property: " + model);
}
if (convert[model].labels.length !== convert[model].channels) {
throw new Error("channel and label counts mismatch: " + model);
}
const { channels, labels } = convert[model];
delete convert[model].channels;
delete convert[model].labels;
Object.defineProperty(convert[model], "channels", { value: channels });
Object.defineProperty(convert[model], "labels", { value: labels });
}
convert.rgb.hsl = function(rgb) {
const r = rgb[0] / 255;
const g = rgb[1] / 255;
const b = rgb[2] / 255;
const min = Math.min(r, g, b);
const max = Math.max(r, g, b);
const delta = max - min;
let h;
let s;
if (max === min) {
h = 0;
} else if (r === max) {
h = (g - b) / delta;
} else if (g === max) {
h = 2 + (b - r) / delta;
} else if (b === max) {
h = 4 + (r - g) / delta;
}
h = Math.min(h * 60, 360);
if (h < 0) {
h += 360;
}
const l = (min + max) / 2;
if (max === min) {
s = 0;
} else if (l <= 0.5) {
s = delta / (max + min);
} else {
s = delta / (2 - max - min);
}
return [h, s * 100, l * 100];
};
convert.rgb.hsv = function(rgb) {
let rdif;
let gdif;
let bdif;
let h;
let s;
const r = rgb[0] / 255;
const g = rgb[1] / 255;
const b = rgb[2] / 255;
const v = Math.max(r, g, b);
const diff = v - Math.min(r, g, b);
const diffc = function(c) {
return (v - c) / 6 / diff + 1 / 2;
};
if (diff === 0) {
h = 0;
s = 0;
} else {
s = diff / v;
rdif = diffc(r);
gdif = diffc(g);
bdif = diffc(b);
if (r === v) {
h = bdif - gdif;
} else if (g === v) {
h = 1 / 3 + rdif - bdif;
} else if (b === v) {
h = 2 / 3 + gdif - rdif;
}
if (h < 0) {
h += 1;
} else if (h > 1) {
h -= 1;
}
}
return [
h * 360,
s * 100,
v * 100
];
};
convert.rgb.hwb = function(rgb) {
const r = rgb[0];
const g = rgb[1];
let b = rgb[2];
const h = convert.rgb.hsl(rgb)[0];
const w = 1 / 255 * Math.min(r, Math.min(g, b));
b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
return [h, w * 100, b * 100];
};
convert.rgb.cmyk = function(rgb) {
const r = rgb[0] / 255;
const g = rgb[1] / 255;
const b = rgb[2] / 255;
const k = Math.min(1 - r, 1 - g, 1 - b);
const c = (1 - r - k) / (1 - k) || 0;
const m = (1 - g - k) / (1 - k) || 0;
const y = (1 - b - k) / (1 - k) || 0;
return [c * 100, m * 100, y * 100, k * 100];
};
function comparativeDistance(x, y) {
return (x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2 + (x[2] - y[2]) ** 2;
}
convert.rgb.keyword = function(rgb) {
const reversed = reverseKeywords[rgb];
if (reversed) {
return reversed;
}
let currentClosestDistance = Infinity;
let currentClosestKeyword;
for (const keyword of Object.keys(cssKeywords)) {
const value = cssKeywords[keyword];
const distance = comparativeDistance(rgb, value);
if (distance < currentClosestDistance) {
currentClosestDistance = distance;
currentClosestKeyword = keyword;
}
}
return currentClosestKeyword;
};
convert.keyword.rgb = function(keyword) {
return cssKeywords[keyword];
};
convert.rgb.xyz = function(rgb) {
let r = rgb[0] / 255;
let g = rgb[1] / 255;
let b = rgb[2] / 255;
r = r > 0.04045 ? ((r + 0.055) / 1.055) ** 2.4 : r / 12.92;
g = g > 0.04045 ? ((g + 0.055) / 1.055) ** 2.4 : g / 12.92;
b = b > 0.04045 ? ((b + 0.055) / 1.055) ** 2.4 : b / 12.92;
const x = r * 0.4124 + g * 0.3576 + b * 0.1805;
const y = r * 0.2126 + g * 0.7152 + b * 0.0722;
const z = r * 0.0193 + g * 0.1192 + b * 0.9505;
return [x * 100, y * 100, z * 100];
};
convert.rgb.lab = function(rgb) {
const xyz = convert.rgb.xyz(rgb);
let x = xyz[0];
let y = xyz[1];
let z = xyz[2];
x /= 95.047;
y /= 100;
z /= 108.883;
x = x > 8856e-6 ? x ** (1 / 3) : 7.787 * x + 16 / 116;
y = y > 8856e-6 ? y ** (1 / 3) : 7.787 * y + 16 / 116;
z = z > 8856e-6 ? z ** (1 / 3) : 7.787 * z + 16 / 116;
const l = 116 * y - 16;
const a = 500 * (x - y);
const b = 200 * (y - z);
return [l, a, b];
};
convert.hsl.rgb = function(hsl) {
const h = hsl[0] / 360;
const s = hsl[1] / 100;
const l = hsl[2] / 100;
let t2;
let t3;
let val;
if (s === 0) {
val = l * 255;
return [val, val, val];
}
if (l < 0.5) {
t2 = l * (1 + s);
} else {
t2 = l + s - l * s;
}
const t1 = 2 * l - t2;
const rgb = [0, 0, 0];
for (let i = 0; i < 3; i++) {
t3 = h + 1 / 3 * -(i - 1);
if (t3 < 0) {
t3++;
}
if (t3 > 1) {
t3--;
}
if (6 * t3 < 1) {
val = t1 + (t2 - t1) * 6 * t3;
} else if (2 * t3 < 1) {
val = t2;
} else if (3 * t3 < 2) {
val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
} else {
val = t1;
}
rgb[i] = val * 255;
}
return rgb;
};
convert.hsl.hsv = function(hsl) {
const h = hsl[0];
let s = hsl[1] / 100;
let l = hsl[2] / 100;
let smin = s;
const lmin = Math.max(l, 0.01);
l *= 2;
s *= l <= 1 ? l : 2 - l;
smin *= lmin <= 1 ? lmin : 2 - lmin;
const v = (l + s) / 2;
const sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s);
return [h, sv * 100, v * 100];
};
convert.hsv.rgb = function(hsv) {
const h = hsv[0] / 60;
const s = hsv[1] / 100;
let v = hsv[2] / 100;
const hi = Math.floor(h) % 6;
const f = h - Math.floor(h);
const p = 255 * v * (1 - s);
const q = 255 * v * (1 - s * f);
const t = 255 * v * (1 - s * (1 - f));
v *= 255;
switch (hi) {
case 0:
return [v, t, p];
case 1:
return [q, v, p];
case 2:
return [p, v, t];
case 3:
return [p, q, v];
case 4:
return [t, p, v];
case 5:
return [v, p, q];
}
};
convert.hsv.hsl = function(hsv) {
const h = hsv[0];
const s = hsv[1] / 100;
const v = hsv[2] / 100;
const vmin = Math.max(v, 0.01);
let sl;
let l;
l = (2 - s) * v;
const lmin = (2 - s) * vmin;
sl = s * vmin;
sl /= lmin <= 1 ? lmin : 2 - lmin;
sl = sl || 0;
l /= 2;
return [h, sl * 100, l * 100];
};
convert.hwb.rgb = function(hwb) {
const h = hwb[0] / 360;
let wh = hwb[1] / 100;
let bl = hwb[2] / 100;
const ratio = wh + bl;
let f;
if (ratio > 1) {
wh /= ratio;
bl /= ratio;
}
const i = Math.floor(6 * h);
const v = 1 - bl;
f = 6 * h - i;
if ((i & 1) !== 0) {
f = 1 - f;
}
const n = wh + f * (v - wh);
let r;
let g;
let b;
switch (i) {
default:
case 6:
case 0:
r = v;
g = n;
b = wh;
break;
case 1:
r = n;
g = v;
b = wh;
break;
case 2:
r = wh;
g = v;
b = n;
break;
case 3:
r = wh;
g = n;
b = v;
break;
case 4:
r = n;
g = wh;
b = v;
break;
case 5:
r = v;
g = wh;
b = n;
break;
}
return [r * 255, g * 255, b * 255];
};
convert.cmyk.rgb = function(cmyk) {
const c = cmyk[0] / 100;
const m = cmyk[1] / 100;
const y = cmyk[2] / 100;
const k = cmyk[3] / 100;
const r = 1 - Math.min(1, c * (1 - k) + k);
const g = 1 - Math.min(1, m * (1 - k) + k);
const b = 1 - Math.min(1, y * (1 - k) + k);
return [r * 255, g * 255, b * 255];
};
convert.xyz.rgb = function(xyz) {
const x = xyz[0] / 100;
const y = xyz[1] / 100;
const z = xyz[2] / 100;
let r;
let g;
let b;
r = x * 3.2406 + y * -1.5372 + z * -0.4986;
g = x * -0.9689 + y * 1.8758 + z * 0.0415;
b = x * 0.0557 + y * -0.204 + z * 1.057;
r = r > 31308e-7 ? 1.055 * r ** (1 / 2.4) - 0.055 : r * 12.92;
g = g > 31308e-7 ? 1.055 * g ** (1 / 2.4) - 0.055 : g * 12.92;
b = b > 31308e-7 ? 1.055 * b ** (1 / 2.4) - 0.055 : b * 12.92;
r = Math.min(Math.max(0, r), 1);
g = Math.min(Math.max(0, g), 1);
b = Math.min(Math.max(0, b), 1);
return [r * 255, g * 255, b * 255];
};
convert.xyz.lab = function(xyz) {
let x = xyz[0];
let y = xyz[1];
let z = xyz[2];
x /= 95.047;
y /= 100;
z /= 108.883;
x = x > 8856e-6 ? x ** (1 / 3) : 7.787 * x + 16 / 116;
y = y > 8856e-6 ? y ** (1 / 3) : 7.787 * y + 16 / 116;
z = z > 8856e-6 ? z ** (1 / 3) : 7.787 * z + 16 / 116;
const l = 116 * y - 16;
const a = 500 * (x - y);
const b = 200 * (y - z);
return [l, a, b];
};
convert.lab.xyz = function(lab) {
const l = lab[0];
const a = lab[1];
const b = lab[2];
let x;
let y;
let z;
y = (l + 16) / 116;
x = a / 500 + y;
z = y - b / 200;
const y2 = y ** 3;
const x2 = x ** 3;
const z2 = z ** 3;
y = y2 > 8856e-6 ? y2 : (y - 16 / 116) / 7.787;
x = x2 > 8856e-6 ? x2 : (x - 16 / 116) / 7.787;
z = z2 > 8856e-6 ? z2 : (z - 16 / 116) / 7.787;
x *= 95.047;
y *= 100;
z *= 108.883;
return [x, y, z];
};
convert.lab.lch = function(lab) {
const l = lab[0];
const a = lab[1];
const b = lab[2];
let h;
const hr = Math.atan2(b, a);
h = hr * 360 / 2 / Math.PI;
if (h < 0) {
h += 360;
}
const c = Math.sqrt(a * a + b * b);
return [l, c, h];
};
convert.lch.lab = function(lch) {
const l = lch[0];
const c = lch[1];
const h = lch[2];
const hr = h / 360 * 2 * Math.PI;
const a = c * Math.cos(hr);
const b = c * Math.sin(hr);
return [l, a, b];
};
convert.rgb.ansi16 = function(args, saturation = null) {
const [r, g, b] = args;
let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation;
value = Math.round(value / 50);
if (value === 0) {
return 30;
}
let ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255));
if (value === 2) {
ansi += 60;
}
return ansi;
};
convert.hsv.ansi16 = function(args) {
return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
};
convert.rgb.ansi256 = function(args) {
const r = args[0];
const g = args[1];
const b = args[2];
if (r === g && g === b) {
if (r < 8) {
return 16;
}
if (r > 248) {
return 231;
}
return Math.round((r - 8) / 247 * 24) + 232;
}
const ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5);
return ansi;
};
convert.ansi16.rgb = function(args) {
let color = args % 10;
if (color === 0 || color === 7) {
if (args > 50) {
color += 3.5;
}
color = color / 10.5 * 255;
return [color, color, color];
}
const mult = (~~(args > 50) + 1) * 0.5;
const r = (color & 1) * mult * 255;
const g = (color >> 1 & 1) * mult * 255;
const b = (color >> 2 & 1) * mult * 255;
return [r, g, b];
};
convert.ansi256.rgb = function(args) {
if (args >= 232) {
const c = (args - 232) * 10 + 8;
return [c, c, c];
}
args -= 16;
let rem;
const r = Math.floor(args / 36) / 5 * 255;
const g = Math.floor((rem = args % 36) / 6) / 5 * 255;
const b = rem % 6 / 5 * 255;
return [r, g, b];
};
convert.rgb.hex = function(args) {
const integer = ((Math.round(args[0]) & 255) << 16) + ((Math.round(args[1]) & 255) << 8) + (Math.round(args[2]) & 255);
const string = integer.toString(16).toUpperCase();
return "000000".substring(string.length) + string;
};
convert.hex.rgb = function(args) {
const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
if (!match) {
return [0, 0, 0];
}
let colorString = match[0];
if (match[0].length === 3) {
colorString = colorString.split("").map((char) => {
return char + char;
}).join("");
}
const integer = parseInt(colorString, 16);
const r = integer >> 16 & 255;
const g = integer >> 8 & 255;
const b = integer & 255;
return [r, g, b];
};
convert.rgb.hcg = function(rgb) {
const r = rgb[0] / 255;
const g = rgb[1] / 255;
const b = rgb[2] / 255;
const max = Math.max(Math.max(r, g), b);
const min = Math.min(Math.min(r, g), b);
const chroma = max - min;
let grayscale;
let hue;
if (chroma < 1) {
grayscale = min / (1 - chroma);
} else {
grayscale = 0;
}
if (chroma <= 0) {
hue = 0;
} else if (max === r) {
hue = (g - b) / chroma % 6;
} else if (max === g) {
hue = 2 + (b - r) / chroma;
} else {
hue = 4 + (r - g) / chroma;
}
hue /= 6;
hue %= 1;
return [hue * 360, chroma * 100, grayscale * 100];
};
convert.hsl.hcg = function(hsl) {
const s = hsl[1] / 100;
const l = hsl[2] / 100;
const c = l < 0.5 ? 2 * s * l : 2 * s * (1 - l);
let f = 0;
if (c < 1) {
f = (l - 0.5 * c) / (1 - c);
}
return [hsl[0], c * 100, f * 100];
};
convert.hsv.hcg = function(hsv) {
const s = hsv[1] / 100;
const v = hsv[2] / 100;
const c = s * v;
let f = 0;
if (c < 1) {
f = (v - c) / (1 - c);
}
return [hsv[0], c * 100, f * 100];
};
convert.hcg.rgb = function(hcg) {
const h = hcg[0] / 360;
const c = hcg[1] / 100;
const g = hcg[2] / 100;
if (c === 0) {
return [g * 255, g * 255, g * 255];
}
const pure = [0, 0, 0];
const hi = h % 1 * 6;
const v = hi % 1;
const w = 1 - v;
let mg = 0;
switch (Math.floor(hi)) {
case 0:
pure[0] = 1;
pure[1] = v;
pure[2] = 0;
break;
case 1:
pure[0] = w;
pure[1] = 1;
pure[2] = 0;
break;
case 2:
pure[0] = 0;
pure[1] = 1;
pure[2] = v;
break;
case 3:
pure[0] = 0;
pure[1] = w;
pure[2] = 1;
break;
case 4:
pure[0] = v;
pure[1] = 0;
pure[2] = 1;
break;
default:
pure[0] = 1;
pure[1] = 0;
pure[2] = w;
}
mg = (1 - c) * g;
return [
(c * pure[0] + mg) * 255,
(c * pure[1] + mg) * 255,
(c * pure[2] + mg) * 255
];
};
convert.hcg.hsv = function(hcg) {
const c = hcg[1] / 100;
const g = hcg[2] / 100;
const v = c + g * (1 - c);
let f = 0;
if (v > 0) {
f = c / v;
}
return [hcg[0], f * 100, v * 100];
};
convert.hcg.hsl = function(hcg) {
const c = hcg[1] / 100;
const g = hcg[2] / 100;
const l = g * (1 - c) + 0.5 * c;
let s = 0;
if (l > 0 && l < 0.5) {
s = c / (2 * l);
} else if (l >= 0.5 && l < 1) {
s = c / (2 * (1 - l));
}
return [hcg[0], s * 100, l * 100];
};
convert.hcg.hwb = function(hcg) {
const c = hcg[1] / 100;
const g = hcg[2] / 100;
const v = c + g * (1 - c);
return [hcg[0], (v - c) * 100, (1 - v) * 100];
};
convert.hwb.hcg = function(hwb) {
const w = hwb[1] / 100;
const b = hwb[2] / 100;
const v = 1 - b;
const c = v - w;
let g = 0;
if (c < 1) {
g = (v - c) / (1 - c);
}
return [hwb[0], c * 100, g * 100];
};
convert.apple.rgb = function(apple) {
return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255];
};
convert.rgb.apple = function(rgb) {
return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535];
};
convert.gray.rgb = function(args) {
return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
};
convert.gray.hsl = function(args) {
return [0, 0, args[0]];
};
convert.gray.hsv = convert.gray.hsl;
convert.gray.hwb = function(gray) {
return [0, 100, gray[0]];
};
convert.gray.cmyk = function(gray) {
return [0, 0, 0, gray[0]];
};
convert.gray.lab = function(gray) {
return [gray[0], 0, 0];
};
convert.gray.hex = function(gray) {
const val = Math.round(gray[0] / 100 * 255) & 255;
const integer = (val << 16) + (val << 8) + val;
const string = integer.toString(16).toUpperCase();
return "000000".substring(string.length) + string;
};
convert.rgb.gray = function(rgb) {
const val = (rgb[0] + rgb[1] + rgb[2]) / 3;
return [val / 255 * 100];
};
return conversions;
}
var route;
var hasRequiredRoute;
function requireRoute() {
if (hasRequiredRoute) return route;
hasRequiredRoute = 1;
const conversions2 = requireConversions();
function buildGraph() {
const graph = {};
const models = Object.keys(conversions2);
for (let len = models.length, i = 0; i < len; i++) {
graph[models[i]] = {
// http://jsperf.com/1-vs-infinity
// micro-opt, but this is simple.
distance: -1,
parent: null
};
}
return graph;
}
function deriveBFS(fromModel) {
const graph = buildGraph();
const queue = [fromModel];
graph[fromModel].distance = 0;
while (queue.length) {
const current2 = queue.pop();
const adjacents = Object.keys(conversions2[current2]);
for (let len = adjacents.length, i = 0; i < len; i++) {
const adjacent = adjacents[i];
const node = graph[adjacent];
if (node.distance === -1) {
node.distance = graph[current2].distance + 1;
node.parent = current2;
queue.unshift(adjacent);
}
}
}
return graph;
}
function link(from, to) {
return function(args) {
return to(from(args));
};
}
function wrapConversion(toModel, graph) {
const path4 = [graph[toModel].parent, toModel];
let fn = conversions2[graph[toModel].parent][toModel];
let cur = graph[toModel].parent;
while (graph[cur].parent) {
path4.unshift(graph[cur].parent);
fn = link(conversions2[graph[cur].parent][cur], fn);
cur = graph[cur].parent;
}
fn.conversion = path4;
return fn;
}
route = function(fromModel) {
const graph = deriveBFS(fromModel);
const conversion = {};
const models = Object.keys(graph);
for (let len = models.length, i = 0; i < len; i++) {
const toModel = models[i];
const node = graph[toModel];
if (node.parent === null) {
continue;
}
conversion[toModel] = wrapConversion(toModel, graph);
}
return conversion;
};
return route;
}
var colorConvert;
var hasRequiredColorConvert;
function requireColorConvert() {
if (hasRequiredColorConvert) return colorConvert;
hasRequiredColorConvert = 1;
const conversions2 = requireConversions();
const route2 = requireRoute();
const convert = {};
const models = Object.keys(conversions2);
function wrapRaw(fn) {
const wrappedFn = function(...args) {
const arg0 = args[0];
if (arg0 === void 0 || arg0 === null) {
return arg0;
}
if (arg0.length > 1) {
args = arg0;
}
return fn(args);
};
if ("conversion" in fn) {
wrappedFn.conversion = fn.conversion;
}
return wrappedFn;
}
function wrapRounded(fn) {
const wrappedFn = function(...args) {
const arg0 = args[0];
if (arg0 === void 0 || arg0 === null) {
return arg0;
}
if (arg0.length > 1) {
args = arg0;
}
const result = fn(args);
if (typeof result === "object") {
for (let len = result.length, i = 0; i < len; i++) {
result[i] = Math.round(result[i]);
}
}
return result;
};
if ("conversion" in fn) {
wrappedFn.conversion = fn.conversion;
}
return wrappedFn;
}
models.forEach((fromModel) => {
convert[fromModel] = {};
Object.defineProperty(convert[fromModel], "channels", { value: conversions2[fromModel].channels });
Object.defineProperty(convert[fromModel], "labels", { value: conversions2[fromModel].labels });
const routes = route2(fromModel);
const routeModels = Object.keys(routes);
routeModels.forEach((toModel) => {
const fn = routes[toModel];
convert[fromModel][toModel] = wrapRounded(fn);
convert[fromModel][toModel].raw = wrapRaw(fn);
});
});
colorConvert = convert;
return colorConvert;
}
ansiStyles.exports;
var hasRequiredAnsiStyles;
function requireAnsiStyles() {
if (hasRequiredAnsiStyles) return ansiStyles.exports;
hasRequiredAnsiStyles = 1;
(function(module2) {
const wrapAnsi16 = (fn, offset) => (...args) => {
const code = fn(...args);
return `\x1B[${code + offset}m`;
};
const wrapAnsi256 = (fn, offset) => (...args) => {
const code = fn(...args);
return `\x1B[${38 + offset};5;${code}m`;
};
const wrapAnsi16m = (fn, offset) => (...args) => {
const rgb = fn(...args);
return `\x1B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
};
const ansi2ansi = (n) => n;
const rgb2rgb = (r, g, b) => [r, g, b];
const setLazyProperty = (object, property, get3) => {
Object.defineProperty(object, property, {
get: () => {
const value = get3();
Object.defineProperty(object, property, {
value,
enumerable: true,
configurable: true
});
return value;
},
enumerable: true,
configurable: true
});
};
let colorConvert2;
const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => {
if (colorConvert2 === void 0) {
colorConvert2 = requireColorConvert();
}
const offset = isBackground ? 10 : 0;
const styles = {};
for (const [sourceSpace, suite] of Object.entries(colorConvert2)) {
const name = sourceSpace === "ansi16" ? "ansi" : sourceSpace;
if (sourceSpace === targetSpace) {
styles[name] = wrap(identity, offset);
} else if (typeof suite === "object") {
styles[name] = wrap(suite[targetSpace], offset);
}
}
return styles;
};
function assembleStyles() {
const codes = /* @__PURE__ */ new Map();
const styles = {
modifier: {
reset: [0, 0],
// 21 isn't widely supported and 22 does the same thing
bold: [1, 22],
dim: [2, 22],
italic: [3, 23],
underline: [4, 24],
inverse: [7, 27],
hidden: [8, 28],
strikethrough: [9, 29]
},
color: {
black: [30, 39],
red: [31, 39],
green: [32, 39],
yellow: [33, 39],
blue: [34, 39],
magenta: [35, 39],
cyan: [36, 39],
white: [37, 39],
// Bright color
blackBright: [90, 39],
redBright: [91, 39],
greenBright: [92, 39],
yellowBright: [93, 39],
blueBright: [94, 39],
magentaBright: [95, 39],
cyanBright: [96, 39],
whiteBright: [97, 39]
},
bgColor: {
bgBlack: [40, 49],
bgRed: [41, 49],
bgGreen: [42, 49],
bgYellow: [43, 49],
bgBlue: [44, 49],
bgMagenta: [45, 49],
bgCyan: [46, 49],
bgWhite: [47, 49],
// Bright color
bgBlackBright: [100, 49],
bgRedBright: [101, 49],
bgGreenBright: [102, 49],
bgYellowBright: [103, 49],
bgBlueBright: [104, 49],
bgMagentaBright: [105, 49],
bgCyanBright: [106, 49],
bgWhiteBright: [107, 49]
}
};
styles.color.gray = styles.color.blackBright;
styles.bgColor.bgGray = styles.bgColor.bgBlackBright;
styles.color.grey = styles.color.blackBright;
styles.bgColor.bgGrey = styles.bgColor.bgBlackBright;
for (const [groupName, group] of Object.entries(styles)) {
for (const [styleName, style] of Object.entries(group)) {
styles[styleName] = {
open: `\x1B[${style[0]}m`,
close: `\x1B[${style[1]}m`
};
group[styleName] = styles[styleName];
codes.set(style[0], style[1]);
}
Object.defineProperty(styles, groupName, {
value: group,
enumerable: false
});
}
Object.defineProperty(styles, "codes", {
value: codes,
enumerable: false
});
styles.color.close = "\x1B[39m";
styles.bgColor.close = "\x1B[49m";
setLazyProperty(styles.color, "ansi", () => makeDynamicStyles(wrapAnsi16, "ansi16", ansi2ansi, false));
setLazyProperty(styles.color, "ansi256", () => makeDynamicStyles(wrapAnsi256, "ansi256", ansi2ansi, false));
setLazyProperty(styles.color, "ansi16m", () => makeDynamicStyles(wrapAnsi16m, "rgb", rgb2rgb, false));
setLazyProperty(styles.bgColor, "ansi", () => makeDynamicStyles(wrapAnsi16, "ansi16", ansi2ansi, true));
setLazyProperty(styles.bgColor, "ansi256", () => makeDynamicStyles(wrapAnsi256, "ansi256", ansi2ansi, true));
setLazyProperty(styles.bgColor, "ansi16m", () => makeDynamicStyles(wrapAnsi16m, "rgb", rgb2rgb, true));
return styles;
}
Object.defineProperty(module2, "exports", {
enumerable: true,
get: assembleStyles
});
})(ansiStyles);
return ansiStyles.exports;
}
var wrapAnsi_1;
var hasRequiredWrapAnsi;
function requireWrapAnsi() {
if (hasRequiredWrapAnsi) return wrapAnsi_1;
hasRequiredWrapAnsi = 1;
const stringWidth2 = requireStringWidth();
const stripAnsi2 = requireStripAnsi();
const ansiStyles2 = requireAnsiStyles();
const ESCAPES = /* @__PURE__ */ new Set([
"\x1B",
"\x9B"
]);
const END_CODE = 39;
const ANSI_ESCAPE_BELL = "\x07";
const ANSI_CSI = "[";
const ANSI_OSC = "]";
const ANSI_SGR_TERMINATOR = "m";
const ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`;
const wrapAnsi = (code) => `${ESCAPES.values().next().value}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`;
const wrapAnsiHyperlink = (uri) => `${ESCAPES.values().next().value}${ANSI_ESCAPE_LINK}${uri}${ANSI_ESCAPE_BELL}`;
const wordLengths = (string) => string.split(" ").map((character) => stringWidth2(character));
const wrapWord = (rows, word, columns) => {
const characters = [...word];
let isInsideEscape = false;
let isInsideLinkEscape = false;
let visible = stringWidth2(stripAnsi2(rows[rows.length - 1]));
for (const [index, character] of characters.entries()) {
const characterLength = stringWidth2(character);
if (visible + characterLength <= columns) {
rows[rows.length - 1] += character;
} else {
rows.push(character);
visible = 0;
}
if (ESCAPES.has(character)) {
isInsideEscape = true;
isInsideLinkEscape = characters.slice(index + 1).join("").startsWith(ANSI_ESCAPE_LINK);
}
if (isInsideEscape) {
if (isInsideLinkEscape) {
if (character === ANSI_ESCAPE_BELL) {
isInsideEscape = false;
isInsideLinkEscape = false;
}
} else if (character === ANSI_SGR_TERMINATOR) {
isInsideEscape = false;
}
continue;
}
visible += characterLength;
if (visible === columns && index < characters.length - 1) {
rows.push("");
visible = 0;
}
}
if (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) {
rows[rows.length - 2] += rows.pop();
}
};
const stringVisibleTrimSpacesRight = (string) => {
const words = string.split(" ");
let last = words.length;
while (last > 0) {
if (stringWidth2(words[last - 1]) > 0) {
break;
}
last--;
}
if (last === words.length) {
return string;
}
return words.slice(0, last).join(" ") + words.slice(last).join("");
};
const exec = (string, columns, options = {}) => {
if (options.trim !== false && string.trim() === "") {
return "";
}
let returnValue = "";
let escapeCode;
let escapeUrl;
const lengths = wordLengths(string);
let rows = [""];
for (const [index, word] of string.split(" ").entries()) {
if (options.trim !== false) {
rows[rows.length - 1] = rows[rows.length - 1].trimStart();
}
let rowLength = stringWidth2(rows[rows.length - 1]);
if (index !== 0) {
if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) {
rows.push("");
rowLength = 0;
}
if (rowLength > 0 || options.trim === false) {
rows[rows.length - 1] += " ";
rowLength++;
}
}
if (options.hard && lengths[index] > columns) {
const remainingColumns = columns - rowLength;
const breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns);
const breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns);
if (breaksStartingNextLine < breaksStartingThisLine) {
rows.push("");
}
wrapWord(rows, word, columns);
continue;
}
if (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) {
if (options.wordWrap === false && rowLength < columns) {
wrapWord(rows, word, columns);
continue;
}
rows.push("");
}
if (rowLength + lengths[index] > columns && options.wordWrap === false) {
wrapWord(rows, word, columns);
continue;
}
rows[rows.length - 1] += word;
}
if (options.trim !== false) {
rows = rows.map(stringVisibleTrimSpacesRight);
}
const pre = [...rows.join("\n")];
for (const [index, character] of pre.entries()) {
returnValue += character;
if (ESCAPES.has(character)) {
const { groups } = new RegExp(`(?:\\${ANSI_CSI}(?<code>\\d+)m|\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`).exec(pre.slice(index).join("")) || { groups: {} };
if (groups.code !== void 0) {
const code2 = Number.parseFloat(groups.code);
escapeCode = code2 === END_CODE ? void 0 : code2;
} else if (groups.uri !== void 0) {
escapeUrl = groups.uri.length === 0 ? void 0 : groups.uri;
}
}
const code = ansiStyles2.codes.get(Number(escapeCode));
if (pre[index + 1] === "\n") {
if (escapeUrl) {
returnValue += wrapAnsiHyperlink("");
}
if (escapeCode && code) {
returnValue += wrapAnsi(code);
}
} else if (character === "\n") {
if (escapeCode && code) {
returnValue += wrapAnsi(escapeCode);
}
if (escapeUrl) {
returnValue += wrapAnsiHyperlink(escapeUrl);
}
}
}
return returnValue;
};
wrapAnsi_1 = (string, columns, options) => {
return String(string).normalize().replace(/\r\n/g, "\n").split("\n").map((line) => exec(line, columns, options)).join("\n");
};
return wrapAnsi_1;
}
var hasRequiredBoxen;
function requireBoxen() {
if (hasRequiredBoxen) return boxen$1.exports;
hasRequiredBoxen = 1;
const stringWidth2 = requireStringWidth();
const chalk$1 = import_chalk.default;
const widestLine2 = requireWidestLine();
const cliBoxes2 = requireCliBoxes();
const camelCase = requireCamelcase();
const ansiAlign = requireAnsiAlign();
const wrapAnsi = requireWrapAnsi();
const NL = "\n";
const PAD = " ";
const terminalColumns = () => {
const { env, stdout, stderr } = process;
if (stdout && stdout.columns) {
return stdout.columns;
}
if (stderr && stderr.columns) {
return stderr.columns;
}
if (env.COLUMNS) {
return Number.parseInt(env.COLUMNS, 10);
}
return 80;
};
const getObject = (detail) => {
return typeof detail === "number" ? {
top: detail,
right: detail * 3,
bottom: detail,
left: detail * 3
} : {
top: 0,
right: 0,
bottom: 0,
left: 0,
...detail
};
};
const getBorderChars = (borderStyle) => {
const sides = [
"topLeft",
"topRight",
"bottomRight",
"bottomLeft",
"vertical",
"horizontal"
];
let chararacters;
if (typeof borderStyle === "string") {
chararacters = cliBoxes2[borderStyle];
if (!chararacters) {
throw new TypeError(`Invalid border style: ${borderStyle}`);
}
} else {
for (const side of sides) {
if (!borderStyle[side] || typeof borderStyle[side] !== "string") {
throw new TypeError(`Invalid border style: ${side}`);
}
}
chararacters = borderStyle;
}
return chararacters;
};
const makeTitle = (text2, horizontal, alignement) => {
let title = "";
const textWidth = stringWidth2(text2);
switch (alignement) {
case "left":
title = text2 + horizontal.slice(textWidth);
break;
case "right":
title = horizontal.slice(textWidth) + text2;
break;
default:
horizontal = horizontal.slice(textWidth);
if (horizontal.length % 2 === 1) {
horizontal = horizontal.slice(Math.floor(horizontal.length / 2));
title = horizontal.slice(1) + text2 + horizontal;
} else {
horizontal = horizontal.slice(horizontal.length / 2);
title = horizontal + text2 + horizontal;
}
break;
}
return title;
};
const makeContentText = (text2, padding, columns, align) => {
text2 = ansiAlign(text2, { align });
let lines = text2.split(NL);
const textWidth = widestLine2(text2);
const max = columns - padding.left - padding.right;
if (textWidth > max) {
const newLines = [];
for (const line of lines) {
const createdLines = wrapAnsi(line, max, { hard: true });
const alignedLines = ansiAlign(createdLines, { align });
const alignedLinesArray = alignedLines.split("\n");
const longestLength = Math.max(...alignedLinesArray.map((s) => stringWidth2(s)));
for (const alignedLine of alignedLinesArray) {
let paddedLine;
switch (align) {
case "center":
paddedLine = PAD.repeat((max - longestLength) / 2) + alignedLine;
break;
case "right":
paddedLine = PAD.repeat(max - longestLength) + alignedLine;
break;
default:
paddedLine = alignedLine;
break;
}
newLines.push(paddedLine);
}
}
lines = newLines;
}
if (align === "center" && textWidth < max) {
lines = lines.map((line) => PAD.repeat((max - textWidth) / 2) + line);
} else if (align === "right" && textWidth < max) {
lines = lines.map((line) => PAD.repeat(max - textWidth) + line);
}
const paddingLeft = PAD.repeat(padding.left);
const paddingRight = PAD.repeat(padding.right);
lines = lines.map((line) => paddingLeft + line + paddingRight);
lines = lines.map((line) => {
if (columns - stringWidth2(line) > 0) {
switch (align) {
case "center":
return line + PAD.repeat(columns - stringWidth2(line));
case "right":
return line + PAD.repeat(columns - stringWidth2(line));
default:
return line + PAD.repeat(columns - stringWidth2(line));
}
}
return line;
});
if (padding.top > 0) {
lines = new Array(padding.top).fill(PAD.repeat(columns)).concat(lines);
}
if (padding.bottom > 0) {
lines = lines.concat(new Array(padding.bottom).fill(PAD.repeat(columns)));
}
return lines.join(NL);
};
const isHex = (color) => color.match(/^#(?:[0-f]{3}){1,2}$/i);
const isColorValid = (color) => typeof color === "string" && (chalk$1[color] || isHex(color));
const getColorFn = (color) => isHex(color) ? chalk$1.hex(color) : chalk$1[color];
const getBGColorFn = (color) => isHex(color) ? chalk$1.bgHex(color) : chalk$1[camelCase(["bg", color])];
boxen$1.exports = (text2, options) => {
options = {
padding: 0,
borderStyle: "single",
dimBorder: false,
textAlignment: "left",
float: "left",
titleAlignment: "left",
...options
};
if (options.align) {
options.textAlignment = options.align;
}
const BORDERS_WIDTH = 2;
if (options.borderColor && !isColorValid(options.borderColor)) {
throw new Error(`${options.borderColor} is not a valid borderColor`);
}
if (options.backgroundColor && !isColorValid(options.backgroundColor)) {
throw new Error(`${options.backgroundColor} is not a valid backgroundColor`);
}
const chars = getBorderChars(options.borderStyle);
const padding = getObject(options.padding);
const margin = getObject(options.margin);
const colorizeBorder = (border) => {
const newBorder = options.borderColor ? getColorFn(options.borderColor)(border) : border;
return options.dimBorder ? chalk$1.dim(newBorder) : newBorder;
};
const colorizeContent = (content) => options.backgroundColor ? getBGColorFn(options.backgroundColor)(content) : content;
const columns = terminalColumns() - 1;
let contentWidth = widestLine2(wrapAnsi(text2, columns - BORDERS_WIDTH, { hard: true, trim: false })) + padding.left + padding.right;
let title = options.title && options.title.slice(0, columns - 4 - margin.left - margin.right);
if (title) {
title = ` ${title} `;
if (stringWidth2(title) > contentWidth) {
contentWidth = stringWidth2(title);
}
}
if (margin.left && margin.right && contentWidth + BORDERS_WIDTH + margin.left + margin.right > columns) {
const spaceForMargins = columns - contentWidth - BORDERS_WIDTH;
const multiplier = spaceForMargins / (margin.left + margin.right);
margin.left = Math.max(0, Math.floor(margin.left * multiplier));
margin.right = Math.max(0, Math.floor(margin.right * multiplier));
}
contentWidth = Math.min(contentWidth, columns - BORDERS_WIDTH - margin.left - margin.right);
text2 = makeContentText(text2, padding, contentWidth, options.textAlignment);
let marginLeft = PAD.repeat(margin.left);
if (options.float === "center") {
const marginWidth = Math.max((columns - contentWidth - BORDERS_WIDTH) / 2, 0);
marginLeft = PAD.repeat(marginWidth);
} else if (options.float === "right") {
const marginWidth = Math.max(columns - contentWidth - margin.right - BORDERS_WIDTH, 0);
marginLeft = PAD.repeat(marginWidth);
}
const horizontal = chars.horizontal.repeat(contentWidth);
const top = colorizeBorder(NL.repeat(margin.top) + marginLeft + chars.topLeft + (title ? makeTitle(title, horizontal, options.titleAlignment) : horizontal) + chars.topRight);
const bottom = colorizeBorder(marginLeft + chars.bottomLeft + horizontal + chars.bottomRight + NL.repeat(margin.bottom));
const side = colorizeBorder(chars.vertical);
const LINE_SEPARATOR = NL;
const lines = text2.split(NL);
const middle = lines.map((line) => {
return marginLeft + side + colorizeContent(line) + side;
}).join(LINE_SEPARATOR);
return top + LINE_SEPARATOR + middle + LINE_SEPARATOR + bottom;
};
boxen$1.exports._borderStyles = cliBoxes2;
return boxen$1.exports;
}
var boxenExports = requireBoxen();
var boxen = /* @__PURE__ */ getDefaultExportFromCjs(boxenExports);
function makeTitledPrettyError(title, content, stack) {
return makePrettyError(import_chalk.default.redBright(title) + "\n\n" + content, stack);
}
function makePrettyError(content, stack) {
if (import_process.default.browser || import_process.default.env.LMS_NO_FANCY_ERRORS || (0, import_lms_isomorphic.terminalSize)().columns < 80) {
const error = new Error(content);
if (stack === void 0) {
changeErrorStackInPlace(error, "");
} else {
changeErrorStackInPlace(error, stack);
}
return error;
} else {
if (stack !== void 0) {
content += "\n\n\n " + import_chalk.default.bgWhite.black(" </> STACK TRACE ") + "\n\n" + import_chalk.default.gray(stack);
}
const error = new Error("\n" + boxen(content, { padding: 1, margin: 1, borderColor: "redBright", title: "Error" }));
Object.defineProperty(error, "lmstudioRawError", { value: content, enumerable: false });
changeErrorStackInPlace(error, "");
return error;
}
}
var compiledTemplatesCache = /* @__PURE__ */ new WeakMap();
function text(strings, ...values) {
if (values.length + 1 !== strings.length) {
throw new Error("text called with the wrong number of arguments.");
}
let compiled = compiledTemplatesCache.get(strings);
if (compiled === void 0) {
compiled = compile(strings);
compiledTemplatesCache.set(strings, compiled);
}
for (let i = 0; i < values.length; i++) {
if (typeof values[i] === "object") {
if (typeof values[i].stack === "string") {
compiled[i * 2 + 1] = values[i].stack;
} else {
try {
compiled[i * 2 + 1] = JSON.stringify(values[i]);
} catch (error) {
compiled[i * 2 + 1] = "[Object failed to stringify]";
}
}
} else {
compiled[i * 2 + 1] = String(values[i]);
}
}
return compiled.join("");
}
function removeLeadingNewlines(input) {
return input.replace(/^\n+/, "");
}
function removeTrailingNewlinesAndWhitespace(input) {
return input.replace(/[\n ]+$/, "");
}
function removeLeadingWhitespace(input) {
return input.replace(/^ +/, "");
}
function removeTrailingWhitespace(input) {
return input.replace(/ +$/, "");
}
function breakIntoLines(strings) {
const lines = [];
let currentLine = [];
for (const string of strings) {
let prevNewlineIndex = -1;
let nextNewlineIndex;
while ((nextNewlineIndex = string.indexOf("\n", prevNewlineIndex + 1)) !== -1) {
currentLine.push(string.substring(prevNewlineIndex + 1, nextNewlineIndex));
lines.push(currentLine);
currentLine = [];
prevNewlineIndex = nextNewlineIndex;
}
currentLine.push(string.substring(prevNewlineIndex + 1));
}
lines.push(currentLine);
return lines;
}
function countStringIndentations(string) {
let count = 0;
for (const char of string) {
if (char === " ") {
count++;
} else {
return count;
}
}
return Infinity;
}
function countLineIndentations(line) {
const firstPart = line[0];
const firstPartIndentation = countStringIndentations(firstPart);
if (firstPartIndentation === Infinity) {
if (line.length === 1) {
return Infinity;
} else {
return firstPart.length;
}
}
return firstPartIndentation;
}
function findMaxCommonIndentation(lines) {
let minIndentation = Infinity;
for (const line of lines) {
minIndentation = Math.min(minIndentation, countLineIndentations(line));
}
return minIndentation;
}
function removeIndentation(line, indentation) {
if (line.length < indentation) {
return "";
}
return line.slice(indentation);
}
function removeAllIndentation(lines, indentation) {
for (const line of lines) {
line[0] = removeIndentation(line[0], indentation);
}
}
function isEmptyLine(line) {
if (line.length !== 1) {
return false;
}
for (const char of line[0]) {
if (char !== " ") {
return false;
}
}
return true;
}
function mergeLines(lines) {
const linesAreEmpty = lines.map(isEmptyLine);
const paragraphs = [];
let currentParagraph = [];
for (let i = 0; i < lines.length; i++) {
if (linesAreEmpty[i]) {
if (currentParagraph.length !== 0) {
paragraphs.push(currentParagraph);
currentParagraph = [];
}
continue;
}
if (currentParagraph.length !== 0) {
const last = removeTrailingWhitespace(currentParagraph[currentParagraph.length - 1]);
const next = removeLeadingWhitespace(lines[i][0]);
currentParagraph[currentParagraph.length - 1] = last + " " + next;
currentParagraph.push(...lines[i].slice(1));
} else {
currentParagraph.push(...lines[i]);
}
}
if (currentParagraph.length !== 0) {
paragraphs.push(currentParagraph);
}
return paragraphs;
}
function mergeParagraphs(paragraphs) {
const result = [];
if (paragraphs.length === 0) {
return [""];
}
result.push(...paragraphs[0]);
for (let i = 1; i < paragraphs.length; i++) {
result[result.length - 1] += "\n\n" + paragraphs[i][0];
result.push(...paragraphs[i].slice(1));
}
return result;
}
function addHolesForVariables(strings) {
const result = [];
for (let i = 0; i < strings.length; i++) {
result.push(strings[i]);
if (i < strings.length - 1) {
result.push("");
}
}
return result;
}
function compile(readonlyStrings) {
const strings = [...readonlyStrings];
strings[0] = removeLeadingNewlines(strings[0]);
strings[strings.length - 1] = removeTrailingNewlinesAndWhitespace(strings[strings.length - 1]);
const lines = breakIntoLines(strings);
const commonIndentation = findMaxCommonIndentation(lines);
removeAllIndentation(lines, commonIndentation);
const paragraphs = mergeLines(lines);
return addHolesForVariables(mergeParagraphs(paragraphs));
}
var MaybeMutable = class {
constructor(data, mutable) {
this.data = data;
this.mutable = mutable;
}
/**
* Gets the underlying data without any access control. Only used internally.
*
* @internal
*/
_internalGetData() {
return this.data;
}
/**
* If this instance is mutable, return as is.
*
* If this instance is immutable, return a mutable copy.
*
* Very easy to misuse, thus internal only for now.
*
* @internal
*/
_internalToMutable() {
if (this.mutable) {
return this;
}
return this.asMutableCopy();
}
asMutableCopy() {
return this.create(this.cloneData(this.data), true);
}
asImmutableCopy() {
if (this.mutable) {
return this.create(this.cloneData(this.data), false);
}
return this;
}
guardMutable() {
if (!this.mutable) {
throw new Error(text`
Cannot modify immutable ${this.getClassName()} instance. Use asMutableCopy() to get a
mutable copy.
`);
}
}
};
function accessMaybeMutableInternals(maybeMutable) {
return maybeMutable;
}
var OWLSignal = class _OWLSignal extends Subscribable {
static {
this.NOT_AVAILABLE = LazySignal.NOT_AVAILABLE;
}
applyOptimisticUpdates(data) {
for (const update of this.queuedUpdates) {
[data] = update.updater(data);
}
return data;
}
updateOptimisticValue(tags) {
const innerValue = this.innerSignal.get();
if (!isAvailable(innerValue)) {
return;
}
this.setOuterSignal(this.applyOptimisticUpdates(innerValue), tags);
}
constructor(initialValue, subscribeUpstream, writeUpstream, equalsPredicate) {
super();
this.writeUpstream = writeUpstream;
this.isWriteLoopRunning = false;
this.isSubscriptionHandledByWriteLoop = false;
this.queuedUpdates = [];
this.currentEnsureAvailablePromise = null;
[this.writeErrorEvent, this.emitWriteErrorEvent] = Event.create();
[this.outerSignal, this.setOuterSignal] = Signal.create(initialValue, equalsPredicate);
this.innerSignal = LazySignal.create(initialValue, subscribeUpstream, equalsPredicate);
this.innerSignal.passiveSubscribeFull((_data, _patches, tags) => {
if (this.isSubscriptionHandledByWriteLoop) {
return;
}
this.updateOptimisticValue(tags);
});
}
static create(initialValue, subscribeUpstream, writeUpstream, equalsPredicate = (a, b) => a === b) {
const signal = new _OWLSignal(initialValue, subscribeUpstream, writeUpstream, equalsPredicate);
const setSignal = makeSetterWithPatches(signal.update.bind(signal));
const emitError = (tags, error) => signal.emitWriteErrorEvent({ tags, error });
return [signal, setSignal, emitError];
}
static createWithoutInitialValue(subscribeUpstream, writeUpstream, equalsPredicate = (a, b) => a === b) {
const fullEqualsPredicate = (a, b) => {
if (a === _OWLSignal.NOT_AVAILABLE || b === _OWLSignal.NOT_AVAILABLE) {
return a === b;
}
return equalsPredicate(a, b);
};
return _OWLSignal.create(_OWLSignal.NOT_AVAILABLE, subscribeUpstream, writeUpstream, fullEqualsPredicate);
}
async update(updater, tags) {
const { promise, reject, resolve } = makePromise();
this.queuedUpdates.push({
updater,
tags: tags ?? [],
resolve,
reject
});
this.updateOptimisticValue();
this.ensureWriteLoop();
return promise;
}
/**
* Starts the write loop if it is not already running.
*/
ensureWriteLoop() {
if (!this.isWriteLoopRunning) {
this.writeLoop();
}
}
/**
* The main write loop, it will keep running until there are no more updates to process.
*/
async writeLoop() {
const unsubscribe = this.innerSignal.subscribe(() => {
});
this.isWriteLoopRunning = true;
if (this.isStale()) {
await this.innerSignal.pull();
}
while (this.queuedUpdates.length > 0) {
const numQueuedUpdatesToHandle = this.queuedUpdates.length;
const updater = (data) => {
const patches = [];
for (let i = 0; i < numQueuedUpdatesToHandle; i++) {
const [newData, newPatches] = this.queuedUpdates[i].updater(data);
data = newData;
patches.push(...newPatches);
}
return [data, patches];
};
const resolve = () => {
for (let i = 0; i < numQueuedUpdatesToHandle; i++) {
this.queuedUpdates[i].resolve();
}
};
const reject = (error) => {
for (let i = 0; i < numQueuedUpdatesToHandle; i++) {
this.queuedUpdates[i].reject(error);
}
};
const queuedUpdateTags = this.queuedUpdates.flatMap((update) => update.tags);
const tag = Date.now() + "-" + Math.random();
await new Promise((nextStep) => {
this.isSubscriptionHandledByWriteLoop = true;
const unsubscribeArray = [];
const settle = () => {
this.isSubscriptionHandledByWriteLoop = false;
unsubscribeArray.forEach((unsubscribe2) => unsubscribe2());
nextStep();
};
unsubscribeArray.push(this.innerSignal.subscribeFull((_data, _patches, tags) => {
if (!this.isSubscriptionHandledByWriteLoop) {
return;
}
if (tags?.includes(tag)) {
settle();
resolve();
this.queuedUpdates.splice(0, numQueuedUpdatesToHandle);
this.updateOptimisticValue(tags.filter((t) => t !== tag));
} else {
this.updateOptimisticValue(tags);
}
}));
unsubscribeArray.push(this.writeErrorEvent.subscribe(({ tags, error }) => {
if (!this.isSubscriptionHandledByWriteLoop) {
return;
}
if (tags.includes(tag)) {
settle();
reject(error);
this.queuedUpdates.splice(0, numQueuedUpdatesToHandle);
}
}));
const sent = this.writeUpstream(...updater(this.innerSignal.get()), [tag, ...queuedUpdateTags]);
if (!sent) {
settle();
resolve();
this.queuedUpdates.splice(0, numQueuedUpdatesToHandle);
this.updateOptimisticValue(queuedUpdateTags.filter((t) => t !== tag));
}
});
}
this.isWriteLoopRunning = false;
unsubscribe();
}
/**
* Returns whether the value is currently stale.
*
* A value is stale whenever the upstream subscription is not active. This can happen in three
* cases:
*
* 1. When no subscriber is attached to this signal, the signal will not subscribe to the
* upstream. In this case, the value is always stale.
* 2. When a subscriber is attached, but the upstream has not yet emitted a single value, the
* value is also stale.
* 3. When the upstream has emitted an error. In this case, the subscription to the upstream is
* terminated and the value is stale.
*
* If you wish to get the current value and ensure that it is not stale, use the method
* {@link OWLSignal#pull}.
*/
isStale() {
return this.innerSignal.isStale();
}
/**
* Gets the current value of the signal. If the value is not available, it will return
* {@link OWLSignal.NOT_AVAILABLE}. (A value will only be unavailable if the signal is created
* without an initial value and the upstream has not emitted a value yet.)
*
* In addition, the value returned by this method may be stale. Use {@link OWLSignal#isStale} to
* check if the value is stale.
*
* If you wish to get the current value and ensure that it is not stale, use the method
* {@link OWLSignal#pull}.
*/
get() {
return this.outerSignal.get();
}
/**
* Gets the current value of the signal pessimistically. If the value is not available, it will
* return {@link OWLSignal.NOT_AVAILABLE}. (A value will only be unavailable if the signal is
* created without an initial value and the upstream has not emitted a value yet.)
*/
getPessimistic() {
return this.innerSignal.get();
}
/**
* Pulls the current value of the signal. If the value is stale, it will subscribe and wait for
* the next value from the upstream and return it.
*
* You must also provide an `optimistic` flag. If `optimistic` is true, the pending optimistic
* updates will be applied to the value before returning it.
*/
async pull({ optimistic = true } = {}) {
if (optimistic) {
return this.applyOptimisticUpdates(await this.innerSignal.pull());
} else {
return this.innerSignal.pull();
}
}
async ensureAvailable() {
if (this.currentEnsureAvailablePromise === null) {
this.currentEnsureAvailablePromise = (async () => {
await this.innerSignal.pull();
return this;
})();
}
return this.currentEnsureAvailablePromise;
}
subscribe(subscriber) {
const unsubscribeOuter = this.outerSignal.subscribe(subscriber);
const unsubscribeInner = this.innerSignal.subscribe(() => {
});
return () => {
unsubscribeOuter();
unsubscribeInner();
};
}
subscribeFull(subscriber) {
const unsubscribeOuter = this.outerSignal.subscribeFull(subscriber);
const unsubscribeInner = this.innerSignal.subscribeFull(() => {
});
return () => {
unsubscribeOuter();
unsubscribeInner();
};
}
};
function parseFileIdentifier(fileIdentifier) {
if (!fileIdentifier.includes(":")) {
fileIdentifier = `local:${fileIdentifier}`;
}
const colonIndex = fileIdentifier.indexOf(":");
const namespace = fileIdentifier.slice(0, colonIndex);
const content = fileIdentifier.slice(colonIndex + 1);
switch (namespace) {
case "local": {
if (content.includes("/") || content.includes("\\") || content.length === 0) {
throw new Error(`Invalid local file name: ${content}.`);
}
return {
type: "local",
fileName: content
};
}
case "base64": {
return {
type: "base64",
base64Data: content
};
}
default: {
throw new Error(`Unknown file identifier namespace: ${namespace}.`);
}
}
}
var allowableEnvVarKeys = ["HSA_OVERRIDE_GFX_VERSION"];
var allowableEnvVarKeysSchema = external_exports.enum(allowableEnvVarKeys);
var allowableEnvVarsSchema = external_exports.record(allowableEnvVarKeysSchema, external_exports.string());
var kebabCaseRegex = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
var kebabCaseSchema = external_exports.string().regex(kebabCaseRegex);
var kebabCaseWithDotsRegex = /^[a-z0-9]+(?:[-.][a-z0-9]+)*$/;
var kebabCaseWithDotsSchema = external_exports.string().regex(kebabCaseWithDotsRegex);
var fileNameRegex = /^[\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~`][\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~` ]*(?<![. ])$/u;
var fileNameSchema = external_exports.string().regex(fileNameRegex, { message: "Invalid file name" });
var relativePathNoLeadingDotSlashRegex = /^[\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~`][\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~` ]*(?<![. ])(?:\/[\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~`][\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~` ]*(?<![. ]))*$/u;
external_exports.string().regex(relativePathNoLeadingDotSlashRegex, {
message: "Invalid relative path"
});
var huggingFaceModelDownloadSourceSchema = external_exports.object({
type: external_exports.literal("huggingface"),
user: fileNameSchema,
repo: fileNameSchema
});
var modelDownloadSourceSchema = external_exports.discriminatedUnion("type", [huggingFaceModelDownloadSourceSchema]);
var artifactDependencyPurposeSchema = external_exports.enum([
"baseModel",
"draftModel",
"custom"
]);
var artifactDependencyBaseSchema = external_exports.object({
purpose: artifactDependencyPurposeSchema
});
var artifactModelDependencySchema = external_exports.object({
type: external_exports.literal("model"),
...artifactDependencyBaseSchema.shape,
modelKeys: external_exports.array(external_exports.string().min(1)),
sources: external_exports.array(modelDownloadSourceSchema)
});
var artifactArtifactDependencySchema = external_exports.object({
type: external_exports.literal("artifact"),
...artifactDependencyBaseSchema.shape,
owner: kebabCaseSchema,
name: kebabCaseWithDotsSchema
});
var artifactDependencySchema = external_exports.discriminatedUnion("type", [
artifactModelDependencySchema,
artifactArtifactDependencySchema
]);
var artifactManifestBaseSchema = external_exports.object({
owner: kebabCaseSchema,
name: kebabCaseWithDotsSchema.min(1, "Name is required").max(100, "Name too long"),
revision: external_exports.number().int().optional(),
dependencies: external_exports.array(artifactDependencySchema).optional(),
tags: external_exports.array(external_exports.string()).optional()
});
var artifactIdentifierRegex = /^[a-z0-9]+(?:-[a-z0-9]+)*\/[a-z0-9]+(?:[-.][a-z0-9]+)*$/;
var artifactIdentifierSchema = external_exports.string().regex(artifactIdentifierRegex, {
message: "Invalid artifact identifier format. Expected 'owner/name'."
});
var modelManifestSchema = external_exports.object({
type: external_exports.literal("model"),
...artifactManifestBaseSchema.shape
});
var pluginRunnerTypeSchema = external_exports.enum(["ecmascript", "node", "mcpBridge"]);
var pluginManifestSchema = external_exports.object({
type: external_exports.literal("plugin"),
runner: pluginRunnerTypeSchema,
...artifactManifestBaseSchema.shape
});
var presetManifestSchema = external_exports.object({
type: external_exports.literal("preset"),
...artifactManifestBaseSchema.shape
});
external_exports.discriminatedUnion("type", [
pluginManifestSchema,
presetManifestSchema,
modelManifestSchema
]);
var artifactTypeSchema = external_exports.enum(["plugin", "preset", "model"]);
var backendNotificationSchema = external_exports.object({
title: external_exports.string(),
description: external_exports.string().optional(),
noAutoDismiss: external_exports.boolean().optional()
});
var fileTypeSchema = external_exports.enum([
"image",
"text/plain",
"application/pdf",
"application/word",
"text/other",
"unknown"
]);
var jsonSerializableSchema = external_exports.any().transform((val, ctx) => {
try {
return JSON.parse(JSON.stringify(val));
} catch (e) {
ctx.addIssue({
code: external_exports.ZodIssueCode.custom,
message: "Not JSON serializable: " + e.message
});
return val;
}
});
var chatMessagePartTextDataSchema = external_exports.object({
type: external_exports.literal("text"),
text: external_exports.string()
});
var chatMessagePartFileDataSchema = external_exports.object({
type: external_exports.literal("file"),
name: external_exports.string(),
identifier: external_exports.string(),
sizeBytes: external_exports.number().int(),
fileType: fileTypeSchema
});
var functionToolCallRequestSchema = external_exports.object({
id: external_exports.string().optional(),
type: external_exports.literal("function"),
arguments: external_exports.record(jsonSerializableSchema).optional(),
name: external_exports.string()
});
var toolCallRequestSchema = external_exports.discriminatedUnion("type", [
functionToolCallRequestSchema
]);
var chatMessagePartToolCallRequestDataSchema = external_exports.object({
type: external_exports.literal("toolCallRequest"),
toolCallRequest: toolCallRequestSchema
});
external_exports.object({
content: external_exports.string(),
toolCallId: external_exports.string().optional()
});
var chatMessagePartToolCallResultDataSchema = external_exports.object({
type: external_exports.literal("toolCallResult"),
content: external_exports.string(),
toolCallId: external_exports.string().optional()
});
external_exports.discriminatedUnion("type", [
chatMessagePartTextDataSchema,
chatMessagePartFileDataSchema,
chatMessagePartToolCallRequestDataSchema,
chatMessagePartToolCallResultDataSchema
]);
external_exports.enum(["assistant", "user", "system", "tool"]);
var chatMessageDataSchema = external_exports.discriminatedUnion("role", [
external_exports.object({
role: external_exports.literal("assistant"),
content: external_exports.array(external_exports.discriminatedUnion("type", [
chatMessagePartTextDataSchema,
chatMessagePartFileDataSchema,
chatMessagePartToolCallRequestDataSchema
]))
}),
external_exports.object({
role: external_exports.literal("user"),
content: external_exports.array(external_exports.discriminatedUnion("type", [chatMessagePartTextDataSchema, chatMessagePartFileDataSchema]))
}),
external_exports.object({
role: external_exports.literal("system"),
content: external_exports.array(external_exports.discriminatedUnion("type", [chatMessagePartTextDataSchema, chatMessagePartFileDataSchema]))
}),
external_exports.object({
role: external_exports.literal("tool"),
content: external_exports.array(chatMessagePartToolCallResultDataSchema)
})
]);
var chatHistoryDataSchema = external_exports.object({
messages: external_exports.array(chatMessageDataSchema)
});
var citationSourceSchema = external_exports.object({
fileName: external_exports.string(),
absoluteFilePath: external_exports.string().optional(),
pageNumber: external_exports.union([external_exports.number().int(), external_exports.tuple([external_exports.number().int(), external_exports.number().int()])]).optional(),
lineNumber: external_exports.union([external_exports.number().int(), external_exports.tuple([external_exports.number().int(), external_exports.number().int()])]).optional()
});
var colorPalette = external_exports.enum([
"red",
"green",
"blue",
"yellow",
"orange",
"purple",
"default"
]);
var colorPaletteSchema = colorPalette;
var diagnosticsLogEventDataSchema = external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("llm.prediction.input"),
modelPath: external_exports.string(),
modelIdentifier: external_exports.string(),
input: external_exports.string()
})
]);
var diagnosticsLogEventSchema = external_exports.object({
timestamp: external_exports.number(),
data: diagnosticsLogEventDataSchema
});
var llmLlamaAccelerationOffloadRatioSchema = external_exports.union([
external_exports.number().min(0).max(1),
external_exports.literal("max"),
external_exports.literal("off")
]);
var llmSplitStrategySchema = external_exports.enum(["evenly", "favorMainGpu"]);
var gpuSettingSchema = external_exports.object({
ratio: llmLlamaAccelerationOffloadRatioSchema.optional(),
mainGpu: external_exports.number().int().optional(),
splitStrategy: llmSplitStrategySchema.optional(),
disabledGpus: external_exports.array(external_exports.number().int()).optional()
});
var llmLlamaCacheQuantizationTypes = [
"f32",
"f16",
"q8_0",
"q4_0",
"q4_1",
"iq4_nl",
"q5_0",
"q5_1"
];
var llmLlamaCacheQuantizationTypeSchema = external_exports.enum(llmLlamaCacheQuantizationTypes);
var llmMlxKvCacheBitsTypeSchema = external_exports.union([
external_exports.literal(8),
external_exports.literal(6),
external_exports.literal(4),
external_exports.literal(3),
external_exports.literal(2)
]);
var llmMlxKvCacheGroupSizeTypesSchema = external_exports.union([
external_exports.literal(32),
external_exports.literal(64),
external_exports.literal(128)
]);
var llmMlxKvCacheQuantizationSchema = external_exports.object({
enabled: external_exports.boolean(),
bits: llmMlxKvCacheBitsTypeSchema,
groupSize: llmMlxKvCacheGroupSizeTypesSchema,
quantizedStart: external_exports.number().int().nonnegative()
});
var llmLoadModelConfigSchema = external_exports.object({
gpu: gpuSettingSchema.optional(),
gpuStrictVramCap: external_exports.boolean().optional(),
offloadKVCacheToGpu: external_exports.boolean().optional(),
contextLength: external_exports.number().int().min(1).optional(),
ropeFrequencyBase: external_exports.number().optional(),
ropeFrequencyScale: external_exports.number().optional(),
evalBatchSize: external_exports.number().int().min(1).optional(),
flashAttention: external_exports.boolean().optional(),
keepModelInMemory: external_exports.boolean().optional(),
seed: external_exports.number().int().optional(),
useFp16ForKVCache: external_exports.boolean().optional(),
tryMmap: external_exports.boolean().optional(),
numExperts: external_exports.number().int().optional(),
llamaKCacheQuantizationType: external_exports.enum(llmLlamaCacheQuantizationTypes).or(external_exports.literal(false)).optional(),
llamaVCacheQuantizationType: external_exports.enum(llmLlamaCacheQuantizationTypes).or(external_exports.literal(false)).optional()
});
var embeddingLoadModelConfigSchema = external_exports.object({
gpu: gpuSettingSchema.optional(),
contextLength: external_exports.number().int().min(1).optional(),
ropeFrequencyBase: external_exports.number().optional(),
ropeFrequencyScale: external_exports.number().optional(),
keepModelInMemory: external_exports.boolean().optional(),
tryMmap: external_exports.boolean().optional()
});
var modelCompatibilityTypeSchema = external_exports.enum([
"gguf",
"safetensors",
"onnx",
"ggml",
"mlx_placeholder",
"torch_safetensors"
]);
var quantizationSchema = external_exports.object({
name: external_exports.string(),
bits: external_exports.number().int()
});
var modelInfoBaseSchema = external_exports.object({
modelKey: external_exports.string(),
format: modelCompatibilityTypeSchema,
displayName: external_exports.string(),
path: external_exports.string(),
sizeBytes: external_exports.number().int(),
paramsString: external_exports.string().optional(),
architecture: external_exports.string().optional(),
quantization: quantizationSchema.optional()
});
var modelInstanceInfoBaseSchema = modelInfoBaseSchema.extend({
identifier: external_exports.string(),
instanceReference: external_exports.string()
});
var embeddingModelAdditionalInfoSchema = external_exports.object({
maxContextLength: external_exports.number().int()
});
var embeddingModelInstanceAdditionalInfoSchema = external_exports.object({
contextLength: external_exports.number().int()
});
var embeddingModelInfoSchema = external_exports.object({
type: external_exports.literal("embedding")
}).extend(modelInfoBaseSchema.shape).extend(embeddingModelAdditionalInfoSchema.shape);
var embeddingModelInstanceInfoSchema = external_exports.object({ type: external_exports.literal("embedding") }).extend(modelInstanceInfoBaseSchema.shape).extend(embeddingModelAdditionalInfoSchema.shape).extend(embeddingModelInstanceAdditionalInfoSchema.shape);
var modelDomainTypeSchema = external_exports.enum([
"llm",
"embedding",
"imageGen",
"transcription",
"tts"
]);
var reasonableKeyStringSchema = external_exports.string().min(1).max(1024).refine((value) => value !== "__proto__", {
message: 'For security reasons, "__proto__" is not allowed'
}).refine((value) => new RegExp("\\p{C}", "u").test(value) === false, {
message: "Control characters are not allowed"
});
var modelQuerySchema = external_exports.object({
domain: modelDomainTypeSchema.optional(),
identifier: reasonableKeyStringSchema.optional(),
path: reasonableKeyStringSchema.optional(),
vision: external_exports.boolean().optional()
});
var modelSpecifierSchema = external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("query"),
query: modelQuerySchema
}),
external_exports.object({
type: external_exports.literal("instanceReference"),
instanceReference: external_exports.string()
})
]);
var genericErrorDisplayDataSchema = [
external_exports.object({
code: external_exports.literal("generic.specificModelUnloaded")
}),
external_exports.object({
code: external_exports.literal("generic.noModelMatchingQuery"),
query: modelQuerySchema,
loadedModelsSample: external_exports.array(external_exports.string()),
totalLoadedModels: external_exports.number().int()
}),
external_exports.object({
code: external_exports.literal("generic.pathNotFound"),
path: external_exports.string(),
availablePathsSample: external_exports.array(external_exports.string()),
totalModels: external_exports.number().int()
}),
external_exports.object({
code: external_exports.literal("generic.identifierNotFound"),
identifier: external_exports.string(),
loadedModelsSample: external_exports.array(external_exports.string()),
totalLoadedModels: external_exports.number().int()
}),
external_exports.object({
code: external_exports.literal("generic.domainMismatch"),
path: external_exports.string(),
actualDomain: modelDomainTypeSchema,
expectedDomain: modelDomainTypeSchema
}),
external_exports.object({
code: external_exports.literal("generic.engineDoesNotSupportFeature"),
feature: external_exports.string(),
engineName: external_exports.string(),
engineType: external_exports.string(),
installedVersion: external_exports.string(),
supportedVersion: external_exports.string().nullable()
}),
external_exports.object({
code: external_exports.literal("generic.presetNotFound"),
specifiedFuzzyPresetIdentifier: external_exports.string(),
availablePresetsSample: external_exports.array(external_exports.object({
identifier: external_exports.string(),
name: external_exports.string()
})),
totalAvailablePresets: external_exports.number().int()
})
];
var llmErrorDisplayDataSchema = [];
var errorDisplayDataSchema = external_exports.discriminatedUnion("code", [
...llmErrorDisplayDataSchema,
...genericErrorDisplayDataSchema
]);
function failOk(schema) {
return external_exports.any().transform((val) => schema.safeParse(val).success ? val : void 0);
}
var serializedLMSExtendedErrorSchema = external_exports.object({
title: failOk(external_exports.string()).default("Unknown error"),
cause: failOk(external_exports.string()).optional(),
suggestion: failOk(external_exports.string()).optional(),
errorData: failOk(external_exports.record(external_exports.string(), external_exports.unknown())).optional(),
displayData: failOk(errorDisplayDataSchema).optional(),
stack: failOk(external_exports.string()).optional(),
rootTitle: failOk(external_exports.string()).optional()
});
function serializeError(error) {
if (typeof error === "object") {
const title = error.title ?? error.lmstudioRawError ?? error.message ?? "Unknown error";
return serializedLMSExtendedErrorSchema.parse({
title,
cause: error.cause,
suggestion: error.suggestion,
errorData: error.errorData,
displayData: error.displayData,
stack: error.stack,
rootTitle: title
});
} else {
const title = String(error);
return {
title,
rootTitle: title
};
}
}
var documentParsingLibraryIdentifierSchema = external_exports.object({
library: external_exports.string(),
version: external_exports.string()
});
var documentParsingOptsSchema = external_exports.object({
parserId: documentParsingLibraryIdentifierSchema.optional()
});
external_exports.enum(["local", "base64"]);
external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("local"),
fileName: external_exports.string()
}),
external_exports.object({
type: external_exports.literal("base64"),
base64Data: external_exports.string()
})
]);
var gpuSplitStrategies = ["evenly", "priorityOrder", "custom"];
var gpuSplitStrategySchema = external_exports.enum(gpuSplitStrategies);
var defaultGPUSplitConfig = {
strategy: "evenly",
disabledGpus: [],
priority: [],
customRatio: []
};
var gpuSplitConfigSchema = external_exports.object({
strategy: gpuSplitStrategySchema,
disabledGpus: external_exports.array(external_exports.number().int().min(0)),
priority: external_exports.array(external_exports.number().int().min(0)),
customRatio: external_exports.array(external_exports.number().min(0))
});
var kvConfigFieldSchema = external_exports.object({
key: external_exports.string(),
value: external_exports.any()
});
var kvConfigSchema = external_exports.object({
fields: external_exports.array(kvConfigFieldSchema)
});
var kvConfigLayerNameSchema = external_exports.enum([
"currentlyEditing",
"currentlyLoaded",
"apiOverride",
"conversationSpecific",
"conversationGlobal",
"preset",
"serverSession",
"httpServerRequestOverride",
"completeModeFormatting",
"instance",
"userModelDefault",
"virtualModel",
"modelDefault",
"hardware"
]);
var kvConfigStackLayerSchema = external_exports.object({
layerName: kvConfigLayerNameSchema,
config: kvConfigSchema
});
var kvConfigStackSchema = external_exports.object({
layers: external_exports.array(kvConfigStackLayerSchema)
});
var kvConfigFieldDependencySchema = external_exports.object({
key: external_exports.string(),
condition: external_exports.discriminatedUnion("type", [
external_exports.object({ type: external_exports.literal("equals"), value: external_exports.any() }),
external_exports.object({ type: external_exports.literal("notEquals"), value: external_exports.any() })
])
});
var contentBlockStyleSchema = external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("default")
}),
external_exports.object({
type: external_exports.literal("customLabel"),
label: external_exports.string(),
color: external_exports.optional(colorPaletteSchema)
}),
external_exports.object({
type: external_exports.literal("thinking"),
ended: external_exports.boolean().optional(),
title: external_exports.string().optional()
})
]);
var llmToolParametersSchema = external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("object"),
properties: external_exports.record(jsonSerializableSchema),
required: external_exports.array(external_exports.string()).optional(),
additionalProperties: external_exports.boolean().optional(),
$defs: external_exports.record(jsonSerializableSchema).optional()
})
// add more parameter types here
// ...
]);
var llmToolSchema = external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("function"),
function: external_exports.object({
name: external_exports.string(),
description: external_exports.string().optional(),
parameters: llmToolParametersSchema.optional()
})
})
// add more tool types here
// ...
]);
external_exports.array(llmToolSchema);
var llmToolUseSettingSchema = external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("none")
}),
external_exports.object({
type: external_exports.literal("toolArray"),
tools: external_exports.array(llmToolSchema).optional(),
force: external_exports.boolean().optional()
})
]);
var llmApplyPromptTemplateOptsSchema = external_exports.object({
omitBosToken: external_exports.boolean().optional(),
omitEosToken: external_exports.boolean().optional(),
toolDefinitions: external_exports.array(llmToolSchema).optional()
});
var llmContextReferenceSchema = external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("jsonFile"),
absPath: external_exports.string()
}),
external_exports.object({
type: external_exports.literal("yamlFile"),
absPath: external_exports.string()
})
]);
external_exports.array(external_exports.object({
role: external_exports.enum(["user", "assistant", "system"]),
content: external_exports.string()
}));
external_exports.array(external_exports.union([
external_exports.object({
system: external_exports.string()
}),
external_exports.object({
user: external_exports.string()
}),
external_exports.object({
assistant: external_exports.string()
})
]));
var llmAdditionalInfoSchema = external_exports.object({
vision: external_exports.boolean(),
trainedForToolUse: external_exports.boolean(),
maxContextLength: external_exports.number().int()
});
var llmInstanceAdditionalInfoSchema = external_exports.object({
contextLength: external_exports.number().int()
});
var llmInfoSchema = external_exports.object({
type: external_exports.literal("llm")
}).extend(modelInfoBaseSchema.shape).extend(llmAdditionalInfoSchema.shape);
var llmInstanceInfoSchema = external_exports.object({
type: external_exports.literal("llm")
}).extend(modelInstanceInfoBaseSchema.shape).extend(llmAdditionalInfoSchema.shape).extend(llmInstanceAdditionalInfoSchema.shape);
var toolNamingSchema = external_exports.enum(["passThrough", "removeSpecial", "snakeCase", "camelCase"]);
var zodSchemaSchema = external_exports.custom((value) => {
if (typeof value?.parse !== "function") {
return false;
}
return true;
}, "Expected a zod schema");
var llmManualPromptTemplateSchema = external_exports.object({
beforeSystem: external_exports.string(),
afterSystem: external_exports.string(),
beforeUser: external_exports.string(),
afterUser: external_exports.string(),
beforeAssistant: external_exports.string(),
afterAssistant: external_exports.string()
});
var llmJinjaPromptTemplateSchema = external_exports.object({
template: external_exports.string()
});
var llmPromptTemplateTypeSchema = external_exports.enum(["manual", "jinja"]);
var llmPromptTemplateSchema = external_exports.object({
type: llmPromptTemplateTypeSchema,
manualPromptTemplate: llmManualPromptTemplateSchema.optional(),
jinjaPromptTemplate: llmJinjaPromptTemplateSchema.optional(),
stopStrings: external_exports.array(external_exports.string())
});
var llmStructuredPredictionTypeSchema = external_exports.enum(["none", "json", "gbnf"]);
var llmStructuredPredictionSettingSchema = external_exports.object({
type: llmStructuredPredictionTypeSchema,
jsonSchema: jsonSerializableSchema.optional(),
gbnfGrammar: external_exports.string().optional()
});
var llmContextOverflowPolicySchema = external_exports.enum([
"stopAtLimit",
"truncateMiddle",
"rollingWindow"
]);
var llmReasoningParsingSchema = external_exports.object({
enabled: external_exports.boolean(),
startString: external_exports.string(),
endString: external_exports.string()
});
var llmPredictionConfigInputSchema = external_exports.object({
maxTokens: external_exports.number().int().min(-1).optional().or(external_exports.literal(false)),
temperature: external_exports.number().min(0).optional(),
stopStrings: external_exports.array(external_exports.string()).optional(),
toolCallStopStrings: external_exports.array(external_exports.string()).optional(),
contextOverflowPolicy: llmContextOverflowPolicySchema.optional(),
structured: external_exports.union([zodSchemaSchema, llmStructuredPredictionSettingSchema]).optional(),
rawTools: llmToolUseSettingSchema.optional(),
toolNaming: toolNamingSchema.optional(),
topKSampling: external_exports.number().optional(),
repeatPenalty: external_exports.number().optional().or(external_exports.literal(false)),
minPSampling: external_exports.number().optional().or(external_exports.literal(false)),
topPSampling: external_exports.number().optional().or(external_exports.literal(false)),
cpuThreads: external_exports.number().int().optional(),
promptTemplate: llmPromptTemplateSchema.optional(),
draftModel: external_exports.string().optional(),
speculativeDecodingNumDraftTokensExact: external_exports.number().int().min(1).optional(),
speculativeDecodingMinDraftLengthToConsider: external_exports.number().int().min(0).optional(),
speculativeDecodingMinContinueDraftingProbability: external_exports.number().optional(),
reasoningParsing: llmReasoningParsingSchema.optional(),
raw: kvConfigSchema.optional()
});
external_exports.object({
...llmPredictionConfigInputSchema.shape,
structured: llmStructuredPredictionSettingSchema.optional()
});
var llmLlamaMirostatSamplingConfigSchema = external_exports.object({
version: external_exports.union([external_exports.literal(0), external_exports.literal(1), external_exports.literal(2)]),
learningRate: external_exports.number(),
targetEntropy: external_exports.number()
});
var llmLlamaSingleLogitBiasModificationSchema = external_exports.union([external_exports.number(), external_exports.literal("-inf")]);
var llmLlamaLogitBiasConfigSchema = external_exports.array(external_exports.tuple([external_exports.number(), llmLlamaSingleLogitBiasModificationSchema]));
var llmPredictionFragmentReasoningTypeSchema = external_exports.enum([
"none",
"reasoning",
"reasoningStartTag",
"reasoningEndTag"
]);
var llmPredictionFragmentSchema = external_exports.object({
content: external_exports.string(),
tokensCount: external_exports.number().int(),
containsDrafted: external_exports.boolean(),
reasoningType: llmPredictionFragmentReasoningTypeSchema,
isStructural: external_exports.boolean()
});
var llmPredictionFragmentInputOptsSchema = external_exports.object({
tokenCount: external_exports.number().int().optional(),
containsDrafted: external_exports.boolean().optional(),
reasoningType: llmPredictionFragmentReasoningTypeSchema.optional(),
isStructural: external_exports.boolean().optional()
});
var llmPredictionStopReasonSchema = external_exports.enum([
"userStopped",
"modelUnloaded",
"failed",
"eosFound",
"stopStringFound",
"toolCalls",
"maxPredictedTokensReached",
"contextLengthReached"
]);
var llmPredictionStatsSchema = external_exports.object({
stopReason: llmPredictionStopReasonSchema,
tokensPerSecond: external_exports.number().optional(),
numGpuLayers: external_exports.number().optional(),
timeToFirstTokenSec: external_exports.number().optional(),
totalTimeSec: external_exports.number().optional(),
promptTokensCount: external_exports.number().int().optional(),
predictedTokensCount: external_exports.number().int().optional(),
totalTokensCount: external_exports.number().int().optional(),
usedDraftModelKey: external_exports.string().optional(),
totalDraftTokensCount: external_exports.number().int().optional(),
acceptedDraftTokensCount: external_exports.number().int().optional(),
rejectedDraftTokensCount: external_exports.number().int().optional(),
ignoredDraftTokensCount: external_exports.number().int().optional()
});
var llmGenInfoSchema = external_exports.object({
indexedModelIdentifier: external_exports.string(),
identifier: external_exports.string(),
loadModelConfig: kvConfigSchema,
predictionConfig: kvConfigSchema,
stats: llmPredictionStatsSchema
});
var blockLocationSchema = external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("beforeId"),
id: external_exports.string()
}),
external_exports.object({
type: external_exports.literal("afterId"),
id: external_exports.string()
})
]);
var statusStepStatusSchema = external_exports.enum([
"waiting",
"loading",
"done",
"error",
"canceled"
]);
var statusStepStateSchema = external_exports.object({
status: statusStepStatusSchema,
text: external_exports.string()
});
var processingUpdateStatusCreateSchema = external_exports.object({
type: external_exports.literal("status.create"),
id: external_exports.string(),
state: statusStepStateSchema,
location: blockLocationSchema.optional(),
indentation: external_exports.number().int().optional()
});
var processingUpdateStatusUpdateSchema = external_exports.object({
type: external_exports.literal("status.update"),
id: external_exports.string(),
state: statusStepStateSchema
});
var processingUpdateStatusRemoveSchema = external_exports.object({
type: external_exports.literal("status.remove"),
id: external_exports.string()
});
var processingUpdateCitationBlockCreateSchema = external_exports.object({
type: external_exports.literal("citationBlock.create"),
id: external_exports.string(),
citedText: external_exports.string(),
fileName: external_exports.string(),
fileIdentifier: external_exports.string(),
pageNumber: external_exports.union([external_exports.number().int(), external_exports.tuple([external_exports.number().int(), external_exports.number().int()])]).optional(),
lineNumber: external_exports.union([external_exports.number().int(), external_exports.tuple([external_exports.number().int(), external_exports.number().int()])]).optional()
});
var processingUpdateDebugInfoBlockCreateSchema = external_exports.object({
type: external_exports.literal("debugInfoBlock.create"),
id: external_exports.string(),
debugInfo: external_exports.string()
});
var processingUpdateContentBlockCreateSchema = external_exports.object({
type: external_exports.literal("contentBlock.create"),
id: external_exports.string(),
includeInContext: external_exports.boolean(),
roleOverride: external_exports.enum(["user", "assistant", "system", "tool"]).optional(),
style: contentBlockStyleSchema.optional(),
prefix: external_exports.string().optional(),
suffix: external_exports.string().optional()
});
var processingUpdateContentBlockAppendTextSchema = external_exports.object({
type: external_exports.literal("contentBlock.appendText"),
id: external_exports.string(),
text: external_exports.string(),
tokensCount: external_exports.number().int().optional(),
fromDraftModel: external_exports.boolean().optional(),
isStructural: external_exports.boolean().optional()
});
var processingUpdateContentBlockAppendToolResultSchema = external_exports.object({
type: external_exports.literal("contentBlock.appendToolResult"),
id: external_exports.string(),
callId: external_exports.number().int(),
toolCallRequestId: external_exports.string().optional(),
content: external_exports.string()
});
var processingUpdateContentBlockAppendToolRequestSchema = external_exports.object({
type: external_exports.literal("contentBlock.appendToolRequest"),
id: external_exports.string(),
callId: external_exports.number().int(),
toolCallRequestId: external_exports.string().optional(),
name: external_exports.string(),
parameters: external_exports.record(external_exports.unknown()),
pluginIdentifier: external_exports.string().optional()
});
var processingUpdateContentBlockReplaceToolRequestSchema = external_exports.object({
type: external_exports.literal("contentBlock.replaceToolRequest"),
id: external_exports.string(),
callId: external_exports.number().int(),
toolCallRequestId: external_exports.string().optional(),
name: external_exports.string(),
parameters: external_exports.record(external_exports.unknown()),
pluginIdentifier: external_exports.string().optional()
});
var processingUpdateContentBlockReplaceTextSchema = external_exports.object({
type: external_exports.literal("contentBlock.replaceText"),
id: external_exports.string(),
text: external_exports.string()
});
var processingUpdateContentBlockSetPrefixSchema = external_exports.object({
type: external_exports.literal("contentBlock.setPrefix"),
id: external_exports.string(),
prefix: external_exports.string()
});
var processingUpdateContentBlockSetSuffixSchema = external_exports.object({
type: external_exports.literal("contentBlock.setSuffix"),
id: external_exports.string(),
suffix: external_exports.string()
});
var processingUpdateContentBlockAttachGenInfoSchema = external_exports.object({
type: external_exports.literal("contentBlock.attachGenInfo"),
id: external_exports.string(),
genInfo: llmGenInfoSchema
});
var processingUpdateContentBlockSetStyleSchema = external_exports.object({
type: external_exports.literal("contentBlock.setStyle"),
id: external_exports.string(),
style: contentBlockStyleSchema
});
var toolStatusStepStateStatusSchema = external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("generatingToolCall"),
name: external_exports.string().optional(),
pluginIdentifier: external_exports.string().optional(),
argumentsString: external_exports.string().optional()
}),
external_exports.object({
type: external_exports.literal("toolCallGenerationFailed"),
error: external_exports.string(),
rawContent: external_exports.string().optional()
}),
external_exports.object({
type: external_exports.literal("toolCallQueued")
}),
external_exports.object({
type: external_exports.literal("confirmingToolCall")
}),
external_exports.object({
type: external_exports.literal("toolCallDenied"),
denyReason: external_exports.string().optional()
}),
external_exports.object({
type: external_exports.literal("callingTool")
}),
external_exports.object({
type: external_exports.literal("toolCallFailed"),
error: external_exports.string()
}),
external_exports.object({
type: external_exports.literal("toolCallSucceeded"),
timeMs: external_exports.number().int()
})
]);
var toolStatusStepStateSchema = external_exports.object({
status: toolStatusStepStateStatusSchema,
customStatus: external_exports.string(),
customWarnings: external_exports.array(external_exports.string())
});
var processingUpdateToolStatusCreateSchema = external_exports.object({
type: external_exports.literal("toolStatus.create"),
id: external_exports.string(),
callId: external_exports.number().int(),
state: toolStatusStepStateSchema
});
var processingUpdateToolStatusUpdateSchema = external_exports.object({
type: external_exports.literal("toolStatus.update"),
id: external_exports.string(),
state: toolStatusStepStateSchema
});
var processingUpdateToolStatusArgumentFragmentSchema = external_exports.object({
type: external_exports.literal("toolStatus.argumentFragment"),
id: external_exports.string(),
content: external_exports.string()
});
var processingUpdateSetSenderNameSchema = external_exports.object({
type: external_exports.literal("setSenderName"),
name: external_exports.string()
});
var processingUpdateSchema = external_exports.discriminatedUnion("type", [
processingUpdateStatusCreateSchema,
processingUpdateStatusUpdateSchema,
processingUpdateStatusRemoveSchema,
processingUpdateCitationBlockCreateSchema,
processingUpdateDebugInfoBlockCreateSchema,
processingUpdateContentBlockCreateSchema,
processingUpdateContentBlockAppendTextSchema,
processingUpdateContentBlockAppendToolRequestSchema,
processingUpdateContentBlockReplaceToolRequestSchema,
processingUpdateContentBlockAppendToolResultSchema,
processingUpdateContentBlockReplaceTextSchema,
processingUpdateContentBlockSetPrefixSchema,
processingUpdateContentBlockSetSuffixSchema,
processingUpdateContentBlockAttachGenInfoSchema,
processingUpdateContentBlockSetStyleSchema,
processingUpdateToolStatusCreateSchema,
processingUpdateToolStatusUpdateSchema,
processingUpdateToolStatusArgumentFragmentSchema,
processingUpdateSetSenderNameSchema
]);
external_exports.discriminatedUnion("type", [
processingUpdateStatusCreateSchema,
processingUpdateStatusUpdateSchema,
processingUpdateStatusRemoveSchema,
processingUpdateCitationBlockCreateSchema,
processingUpdateDebugInfoBlockCreateSchema,
processingUpdateContentBlockCreateSchema,
processingUpdateContentBlockAppendTextSchema,
processingUpdateContentBlockReplaceTextSchema,
processingUpdateContentBlockAppendToolRequestSchema,
processingUpdateContentBlockReplaceToolRequestSchema,
processingUpdateContentBlockAppendToolResultSchema,
processingUpdateContentBlockAttachGenInfoSchema,
processingUpdateContentBlockSetStyleSchema,
processingUpdateToolStatusCreateSchema,
processingUpdateToolStatusUpdateSchema,
processingUpdateToolStatusArgumentFragmentSchema,
processingUpdateSetSenderNameSchema
]);
var processingRequestConfirmToolCallSchema = external_exports.object({
type: external_exports.literal("confirmToolCall"),
callId: external_exports.number().int(),
pluginIdentifier: external_exports.string().optional(),
name: external_exports.string(),
parameters: external_exports.record(external_exports.any())
});
var processingRequestTextInputSchema = external_exports.object({
type: external_exports.literal("textInput"),
prompt: external_exports.string()
});
var processingRequestSchema = external_exports.discriminatedUnion("type", [
processingRequestConfirmToolCallSchema,
processingRequestTextInputSchema
]);
var processingRequestResponseConfirmToolCallSchema = external_exports.object({
type: external_exports.literal("confirmToolCall"),
result: external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("allow"),
toolArgsOverride: external_exports.record(external_exports.any()).optional()
}),
external_exports.object({
type: external_exports.literal("deny"),
denyReason: external_exports.string().optional()
})
])
});
var processingRequestResponseTextInputSchema = external_exports.object({
type: external_exports.literal("textInput"),
result: external_exports.string()
});
var processingRequestResponseSchema = external_exports.discriminatedUnion("type", [
processingRequestResponseConfirmToolCallSchema,
processingRequestResponseTextInputSchema
]);
external_exports.object({
modelTag: external_exports.string().optional(),
ignoreUserConfig: external_exports.boolean().optional()
});
external_exports.discriminatedUnion("type", [
processingUpdateStatusCreateSchema,
processingUpdateStatusUpdateSchema,
processingUpdateStatusRemoveSchema,
processingUpdateCitationBlockCreateSchema,
processingUpdateDebugInfoBlockCreateSchema
]);
var tokenSourceIdentifierSchema = external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("model"),
identifier: external_exports.string()
}),
external_exports.object({
type: external_exports.literal("generator"),
pluginIdentifier: external_exports.string()
})
]);
var modelInfoSchema = external_exports.discriminatedUnion("type", [
llmInfoSchema,
embeddingModelInfoSchema
]);
var modelInstanceInfoSchema = external_exports.discriminatedUnion("type", [
llmInstanceInfoSchema,
embeddingModelInstanceInfoSchema
]);
var pluginConfigSpecifierSchema = external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("direct"),
config: kvConfigSchema,
workingDirectoryPath: external_exports.string().optional()
}),
external_exports.object({
type: external_exports.literal("predictionProcess"),
pci: external_exports.string(),
token: external_exports.string()
})
]);
var remotePluginInfoSchema = external_exports.object({
identifier: external_exports.string(),
isDev: external_exports.boolean(),
isTrusted: external_exports.boolean(),
hasPromptPreprocessor: external_exports.boolean(),
hasPredictionLoopHandler: external_exports.boolean(),
hasToolsProvider: external_exports.boolean(),
hasGenerator: external_exports.boolean()
});
var artifactDownloadPlanModelInfoSchema = external_exports.object({
displayName: external_exports.string(),
sizeBytes: external_exports.number(),
quantName: external_exports.string().optional(),
compatibilityType: modelCompatibilityTypeSchema
});
var artifactDownloadPlanNodeStateSchema = external_exports.enum(["pending", "fetching", "satisfied", "completed"]);
var artifactDownloadPlanNodeSchema = external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("artifact"),
owner: kebabCaseSchema,
name: kebabCaseWithDotsSchema,
state: artifactDownloadPlanNodeStateSchema,
artifactType: artifactTypeSchema.optional(),
sizeBytes: external_exports.number().int().optional(),
dependencyNodes: external_exports.array(external_exports.number().int())
}),
external_exports.object({
type: external_exports.literal("model"),
state: artifactDownloadPlanNodeStateSchema,
resolvedSources: external_exports.number().int().optional(),
totalSources: external_exports.number().int().optional(),
alreadyOwned: artifactDownloadPlanModelInfoSchema.optional(),
selected: artifactDownloadPlanModelInfoSchema.optional()
})
]);
var artifactDownloadPlanSchema = external_exports.object({
nodes: external_exports.array(artifactDownloadPlanNodeSchema),
downloadSizeBytes: external_exports.number().int()
});
var localArtifactFileEntrySchema = external_exports.object({
relativePath: external_exports.string(),
sizeBytes: external_exports.number().int()
});
var localArtifactFileListSchema = external_exports.object({
files: external_exports.array(localArtifactFileEntrySchema),
usedIgnoreFile: external_exports.string().nullable()
});
var downloadProgressUpdateSchema = external_exports.object({
downloadedBytes: external_exports.number().int(),
totalBytes: external_exports.number().int(),
speedBytesPerSecond: external_exports.number()
});
var modelSearchResultDownloadOptionFitEstimationSchema = external_exports.enum([
"fullGPUOffload",
"partialGPUOffload",
"fitWithoutGPU",
"willNotFit"
]);
var modelSearchResultDownloadOptionDataSchema = external_exports.object({
quantization: external_exports.string().optional(),
name: external_exports.string(),
sizeBytes: external_exports.number().int(),
fitEstimation: modelSearchResultDownloadOptionFitEstimationSchema,
recommended: external_exports.boolean().optional(),
downloadIdentifier: external_exports.string(),
indexedModelIdentifier: external_exports.string()
});
var modelSearchResultIdentifierSchema = external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("catalog"),
identifier: external_exports.string()
}),
external_exports.object({
type: external_exports.literal("hf"),
identifier: external_exports.string()
})
]);
var modelSearchResultEntryDataSchema = external_exports.object({
name: external_exports.string(),
identifier: modelSearchResultIdentifierSchema,
exact: external_exports.boolean().optional(),
staffPick: external_exports.boolean().optional()
});
var modelSearchOptsSchema = external_exports.object({
searchTerm: external_exports.string().optional(),
limit: external_exports.number().int().positive().max(25).optional(),
compatibilityTypes: external_exports.array(modelCompatibilityTypeSchema).optional()
});
var internalRetrievalResultEntrySchema = external_exports.object({
content: external_exports.string(),
score: external_exports.number(),
sourceIndex: external_exports.number().int(),
pageNumber: external_exports.union([external_exports.number().int(), external_exports.tuple([external_exports.number().int(), external_exports.number().int()])]).optional(),
lineNumber: external_exports.union([external_exports.number().int(), external_exports.tuple([external_exports.number().int(), external_exports.number().int()])]).optional()
});
var internalRetrievalResultSchema = external_exports.object({
entries: external_exports.array(internalRetrievalResultEntrySchema)
});
external_exports.object({
content: external_exports.string(),
score: external_exports.number(),
citation: citationSourceSchema
});
var retrievalChunkingMethodSchema = external_exports.discriminatedUnion("type", [
external_exports.object({
type: external_exports.literal("recursive-v1"),
chunkSize: external_exports.number().int(),
chunkOverlap: external_exports.number().int()
})
]);
var retrievalFileProcessingStepSchema = external_exports.enum(["loading", "chunking", "embedding"]);
var acceleratorTypeSchema = external_exports.enum(["unknown", "integratedGpu", "dedicatedGpu"]);
var acceleratorSchema = external_exports.object({
name: external_exports.string(),
deviceId: external_exports.number().int(),
totalMemoryBytes: external_exports.number().int(),
type: acceleratorTypeSchema
});
external_exports.object({
key: external_exports.string(),
name: external_exports.string(),
accelerators: external_exports.array(acceleratorSchema)
});
var serializedKVConfigSchematicsFieldSchema = external_exports.object({
shortKey: external_exports.string(),
fullKey: external_exports.string(),
typeKey: external_exports.string(),
typeParams: jsonSerializableSchema,
defaultValue: jsonSerializableSchema
});
var serializedKVConfigSchematicsSchema = external_exports.object({
fields: external_exports.array(serializedKVConfigSchematicsFieldSchema),
extensionPrefixes: external_exports.array(external_exports.string()).optional()
});
external_exports.object({
fullKey: external_exports.string(),
error: jsonSerializableSchema
});
var booleanOrMixedSchema = external_exports.union([
external_exports.literal(true),
external_exports.literal(false),
external_exports.literal("mixed")
]);
var virtualModelDefinitionMetadataOverridesSchema = external_exports.object({
domain: modelDomainTypeSchema.optional(),
architectures: external_exports.array(external_exports.string()).optional(),
compatibilityTypes: external_exports.array(modelCompatibilityTypeSchema).optional(),
paramsStrings: external_exports.array(external_exports.string()).optional(),
minMemoryUsageBytes: external_exports.number().optional(),
contextLengths: external_exports.array(external_exports.number()).optional(),
trainedForToolUse: booleanOrMixedSchema.optional(),
vision: booleanOrMixedSchema.optional(),
reasoning: booleanOrMixedSchema.optional(),
fim: booleanOrMixedSchema.optional()
});
var virtualModelDefinitionConcreteModelBaseSchema = external_exports.object({
key: external_exports.string(),
sources: external_exports.array(modelDownloadSourceSchema)
});
var virtualModelCustomFieldSetJinjaVariableEffectSchema = external_exports.object({
type: external_exports.literal("setJinjaVariable"),
variable: external_exports.string()
});
var virtualModelCustomFieldPrependSystemPromptEffectSchema = external_exports.object({
type: external_exports.literal("prependSystemPrompt"),
content: external_exports.string()
});
var virtualModelCustomFieldAppendSystemPromptEffectSchema = external_exports.object({
type: external_exports.literal("appendSystemPrompt"),
content: external_exports.string()
});
var virtualModelCustomFieldDefinitionBaseSchema = external_exports.object({
key: external_exports.string(),
displayName: external_exports.string(),
description: external_exports.string()
});
var virtualModelBooleanCustomFieldDefinitionSchema = virtualModelCustomFieldDefinitionBaseSchema.extend({
type: external_exports.literal("boolean"),
defaultValue: external_exports.boolean(),
effects: external_exports.array(external_exports.discriminatedUnion("type", [
virtualModelCustomFieldSetJinjaVariableEffectSchema,
virtualModelCustomFieldPrependSystemPromptEffectSchema,
virtualModelCustomFieldAppendSystemPromptEffectSchema
]))
});
var virtualModelStringCustomFieldDefinitionSchema = virtualModelCustomFieldDefinitionBaseSchema.extend({
type: external_exports.literal("string"),
defaultValue: external_exports.string(),
effects: external_exports.array(external_exports.discriminatedUnion("type", [virtualModelCustomFieldSetJinjaVariableEffectSchema]))
});
var virtualModelSelectCustomFieldDefinitionSchema = virtualModelCustomFieldDefinitionBaseSchema.extend({
type: external_exports.literal("select"),
options: external_exports.array(external_exports.object({
label: external_exports.string(),
value: external_exports.string()
})),
defaultValue: external_exports.string(),
effects: external_exports.array(external_exports.discriminatedUnion("type", [virtualModelCustomFieldSetJinjaVariableEffectSchema]))
});
var virtualModelCustomFieldDefinitionSchema = external_exports.discriminatedUnion("type", [
virtualModelBooleanCustomFieldDefinitionSchema,
virtualModelStringCustomFieldDefinitionSchema,
virtualModelSelectCustomFieldDefinitionSchema
]);
var virtualModelConditionEqualsSchema = external_exports.object({
type: external_exports.literal("equals"),
key: external_exports.string(),
value: jsonSerializableSchema
});
var virtualModelConditionSchema = external_exports.discriminatedUnion("type", [
virtualModelConditionEqualsSchema
]);
var virtualModelSuggestionSchema = external_exports.object({
message: external_exports.string(),
conditions: external_exports.array(virtualModelConditionSchema),
fields: external_exports.array(kvConfigFieldSchema).optional()
});
external_exports.object({
model: external_exports.string().regex(/^[^/]+\/[^/]+$/),
base: external_exports.union([external_exports.string(), external_exports.array(virtualModelDefinitionConcreteModelBaseSchema)]),
tags: external_exports.array(external_exports.string().max(100)).optional(),
config: external_exports.object({
load: kvConfigSchema.optional(),
operation: kvConfigSchema.optional()
}).optional(),
metadataOverrides: virtualModelDefinitionMetadataOverridesSchema.optional(),
customFields: external_exports.array(virtualModelCustomFieldDefinitionSchema).optional(),
suggestions: external_exports.array(virtualModelSuggestionSchema).optional()
});
var logLevelSchema = external_exports.enum(["debug", "info", "warn", "error"]);
function isSimpleLogger(logger2) {
return logger2?.isSimpleLogger === true;
}
var defaultInfoPrefix = import_chalk.default.greenBright("I");
var defaultWarnPrefix = import_chalk.default.yellowBright("W");
var defaultErrorPrefix = import_chalk.default.redBright("E");
var defaultDebugPrefix = import_chalk.default.blueBright("D");
var SimpleLogger = class _SimpleLogger {
constructor(prefixText = "", parentLogger = console, { useLogLevelPrefixes, infoPrefix, warnPrefix, errorPrefix, debugPrefix } = {}) {
this.isSimpleLogger = true;
this.infoPrefix = [];
this.warnPrefix = [];
this.errorPrefix = [];
this.debugPrefix = [];
if (isSimpleLogger(parentLogger)) {
useLogLevelPrefixes = useLogLevelPrefixes ?? parentLogger.opts.useLogLevelPrefixes;
infoPrefix = infoPrefix === void 0 ? parentLogger.opts.infoPrefix : infoPrefix;
warnPrefix = warnPrefix === void 0 ? parentLogger.opts.warnPrefix : warnPrefix;
errorPrefix = errorPrefix === void 0 ? parentLogger.opts.errorPrefix : errorPrefix;
debugPrefix = debugPrefix === void 0 ? parentLogger.opts.debugPrefix : debugPrefix;
if (prefixText === "") {
this.innerPrefix = parentLogger.innerPrefix;
this.fullPrefix = parentLogger.fullPrefix;
} else {
if (parentLogger.fullPrefix === "") {
this.innerPrefix = prefixText;
} else {
this.innerPrefix = `${parentLogger.innerPrefix}][${prefixText}`;
}
this.fullPrefix = import_chalk.default.whiteBright(`[${this.innerPrefix}]`);
}
this.parentLogger = parentLogger.parentLogger;
} else {
useLogLevelPrefixes = useLogLevelPrefixes ?? false;
infoPrefix = infoPrefix === void 0 ? defaultInfoPrefix : infoPrefix;
warnPrefix = warnPrefix === void 0 ? defaultWarnPrefix : warnPrefix;
errorPrefix = errorPrefix === void 0 ? defaultErrorPrefix : errorPrefix;
debugPrefix = debugPrefix === void 0 ? defaultDebugPrefix : debugPrefix;
if (prefixText === "") {
this.innerPrefix = "";
this.fullPrefix = "";
} else {
this.innerPrefix = prefixText;
this.fullPrefix = import_chalk.default.whiteBright(`[${this.innerPrefix}]`);
}
this.parentLogger = parentLogger;
}
if (useLogLevelPrefixes) {
if (infoPrefix !== null) {
this.infoPrefix.push(infoPrefix);
}
if (warnPrefix !== null) {
this.warnPrefix.push(warnPrefix);
}
if (errorPrefix !== null) {
this.errorPrefix.push(errorPrefix);
}
if (debugPrefix !== null) {
this.debugPrefix.push(debugPrefix);
}
}
if (this.fullPrefix !== "") {
this.infoPrefix.push(this.fullPrefix);
this.warnPrefix.push(this.fullPrefix);
this.errorPrefix.push(this.fullPrefix);
this.debugPrefix.push(this.fullPrefix);
}
this.opts = {
useLogLevelPrefixes,
infoPrefix,
warnPrefix,
errorPrefix,
debugPrefix
};
}
subclass(prefixText) {
return new _SimpleLogger(`${this.innerPrefix}:${prefixText}`, this.parentLogger);
}
info(...messages) {
this.parentLogger.info(...this.infoPrefix, ...messages);
}
infoText(strings, ...values) {
this.info(text(strings, ...values));
}
infoWithoutPrefix(...messages) {
this.parentLogger.info(...messages);
}
error(...messages) {
this.parentLogger.error(...this.errorPrefix, ...messages);
}
errorText(strings, ...values) {
this.error(text(strings, ...values));
}
errorWithoutPrefix(...messages) {
this.parentLogger.error(...messages);
}
warn(...messages) {
this.parentLogger.warn(...this.warnPrefix, ...messages);
}
warnText(strings, ...values) {
this.warn(text(strings, ...values));
}
warnWithoutPrefix(...messages) {
this.parentLogger.warn(...messages);
}
debug(...messages) {
this.parentLogger.debug(...this.debugPrefix, ...messages);
}
debugText(strings, ...values) {
this.debug(text(strings, ...values));
}
debugWithoutPrefix(...messages) {
this.parentLogger.debug(...messages);
}
throw(message) {
throw new Error(`${this.fullPrefix} ${message}`);
}
logAtLevel(level, ...messages) {
switch (level) {
case "debug":
this.debug(...messages);
break;
case "info":
this.info(...messages);
break;
case "warn":
this.warn(...messages);
break;
case "error":
this.error(...messages);
break;
}
}
static fromMultiple(loggers, opts) {
return new _SimpleLogger("", {
debug: (...messages) => {
for (const logger2 of loggers) {
logger2.debug(...messages);
}
},
info: (...messages) => {
for (const logger2 of loggers) {
logger2.info(...messages);
}
},
warn: (...messages) => {
for (const logger2 of loggers) {
logger2.warn(...messages);
}
},
error: (...messages) => {
for (const logger2 of loggers) {
logger2.error(...messages);
}
}
}, {
...opts,
useLogLevelPrefixes: false
});
}
};
var _a;
var finished = /* @__PURE__ */ Symbol("finished");
var StreamablePromise = class {
/**
* Called by the producer when it has finished producing values. If an error is provided, the
* promise will be rejected with that error. If no error is provided, the promise will be resolved
* with the final value.
*
* This method should be exposed in the static constructor of the subclass.
*
* @param error - The error to reject the promise with, if any.
*/
finished(error) {
if (this.status !== "pending") {
throw new Error("`finished` called while not pending");
}
if (error === void 0) {
this.status = "resolved";
this.nextFragmentPromiseBundle?.resolve(finished);
this.resolveFinal(this.collect(this.buffer));
} else {
this.status = "rejected";
this.nextFragmentPromiseBundle?.reject(error);
this.rejectFinal(error);
}
}
/**
* Called by the producer to push a new fragment into the buffer. This method should be exposed in
* the static constructor of the subclass.
*
* This method should be exposed in the static constructor of the subclass.
*
* @param fragment - The fragment to push into the buffer.
*/
push(fragment) {
if (this.status !== "pending") {
throw new Error("`push` called while not pending");
}
this.buffer.push(fragment);
this.nextFragmentPromiseBundle?.resolve(fragment);
this.nextFragmentPromiseBundle = null;
}
constructor() {
this.status = "pending";
this.buffer = [];
this.nextFragmentPromiseBundle = null;
this.hasIterator = false;
this[_a] = "StreamablePromise";
const { promise, resolve, reject } = makePromise();
this.promiseFinal = promise;
this.resolveFinal = resolve;
this.rejectFinal = reject;
}
then(onfulfilled, onrejected) {
return this.promiseFinal.then(onfulfilled, onrejected);
}
catch(onrejected) {
return this.promiseFinal.catch(onrejected);
}
finally(onfinally) {
return this.promiseFinal.finally(onfinally);
}
/**
* If nextFragmentPromiseBundle exists, it is returned. Otherwise, a new one is created and
* returned.
*/
obtainNextFragmentPromiseBundle() {
if (this.nextFragmentPromiseBundle === null) {
this.nextFragmentPromiseBundle = makePromise();
}
return this.nextFragmentPromiseBundle;
}
async *[(_a = Symbol.toStringTag, Symbol.asyncIterator)]() {
if (!this.hasIterator) {
this.promiseFinal.catch(() => {
});
this.hasIterator = true;
}
let i = 0;
while (i < this.buffer.length || this.status === "pending") {
if (i < this.buffer.length) {
yield this.buffer[i];
i++;
} else {
const nextFragmentPromiseBundle = this.obtainNextFragmentPromiseBundle();
const nextFragment = await nextFragmentPromiseBundle.promise;
if (nextFragment === finished) {
break;
}
yield nextFragment;
i++;
}
}
await this.promiseFinal;
await Promise.resolve();
}
};
var Validator = class _Validator {
constructor({ attachStack } = {}) {
this.attachStack = attachStack ?? true;
}
/**
* Pretty-prints a Zod error.
*
* @param rootObjectName - The name of the object being validated (used for error messages)
* @param error - The Zod error to pretty-print
*
* @returns The pretty-printed error in a string
*/
static prettyPrintZod(rootObjectName, error) {
return error.errors.map((e) => {
if (e.path.length === 0) {
return `- ${import_chalk.default.redBright(rootObjectName)}: ${e.message}`;
}
const path4 = import_chalk.default.red(`.${e.path.join(".")}`);
return `- ${import_chalk.default.redBright(rootObjectName)}${path4}: ${e.message}`;
}).join("\n");
}
/**
* Validates a value against a schema and throws an error if it's invalid.
*
* @param lead - The start of the error message (used for error messages)
* @param rootObjectName - The name of the object being validated (used for error messages)
* @param schema - The schema to validate against
* @param value - The value to validate
*
* @returns The validated value
* @throws An error if the value is invalid
*/
validateOrThrow(lead, rootObjectName, schema, value, stack) {
const result = schema.safeParse(value);
if (result.success) {
return result.data;
} else {
throw makePrettyError(`${lead}
${_Validator.prettyPrintZod(rootObjectName, result.error)}`, this.attachStack ? stack : void 0);
}
}
/**
* Validates multiple values against multiple schemas and throws an error if any of them are
* invalid. All values are validated before any errors are thrown. This is useful when you want to
* validate multiple values at once and want to see all the errors at once.
*
* @param leadProducer - The function to produce the start of the error message (used for error).
* It is called with a set of indices of the invalid values.
* @param rootObjectNames - The names of the objects being validated (used for error messages)
* @param schemas - The schemas to validate against
* @param values - The values to validate
*
* @returns The validated values
* @throws An error if any of the values are invalid
*/
validateMultipleOrThrow(leadProducer, rootObjectNames, schemas, values, stack) {
const results = schemas.map((schema, index) => schema.safeParse(values[index]));
const errors2 = results.map((result, index) => ({ result, index, rootObjectName: rootObjectNames[index] })).filter(({ result }) => !result.success).map(({ result, rootObjectName, index }) => ({
error: result.error,
rootObjectName,
index
}));
if (errors2.length === 0) {
return results.map((result) => result.data);
} else {
const erroredValues = new Set(errors2.map(({ index }) => index));
const lead = leadProducer(erroredValues);
throw makePrettyError(`${lead}
${errors2.map(({ error, rootObjectName }) => _Validator.prettyPrintZod(rootObjectName, error)).join("\n")}`, this.attachStack ? stack : void 0);
}
}
/**
* Validates a value against a schema and throws an error if it's invalid. This is a convenience
* function for validating one single method parameter.
*
* @param className - The name of the class containing the method (used for error messages)
* @param methodName - The name of the method (used for error messages)
* @param paramName - The name of the parameter being validated (used for error messages)
* @param schema - The schema to validate against
* @param value - The value to validate
*
* @returns The validated value
* @throws An error if the value is invalid
*/
validateMethodParamOrThrow(className, methodName, paramName, schema, value, stack) {
const functionCall = import_chalk.default.yellowBright(text`
${className}.${methodName}(${import_chalk.default.redBright(paramName)})
`);
return this.validateOrThrow(`Invalid parameter(s) for ${functionCall}:`, paramName, schema, value, stack);
}
/**
* Validates multiple values against multiple schemas and throws an error if any of them are
* invalid. This is a convenience function for validating multiple method parameters.
*
* @param className - The name of the class containing the method (used for error messages)
* @param methodName - The name of the method (used for error messages)
* @param paramNames - The names of the parameters being validated (used for error messages)
* @param schemas - The schemas to validate against
* @param values - The values to validate
*
* @returns The validated values
* @throws An error if any of the values are invalid
*/
validateMethodParamsOrThrow(className, methodName, paramNames, schemas, values, stack) {
return this.validateMultipleOrThrow((erroredValues) => {
const coloredParamNames = paramNames.map((name, index) => erroredValues.has(index) ? import_chalk.default.redBright(name) : name);
const functionCall = import_chalk.default.yellowBright(text`
${className}.${methodName}(${coloredParamNames.join(", ")})
`);
return `Invalid parameter(s) for ${functionCall}:`;
}, paramNames, schemas, values, stack);
}
/**
* Validates a value against a schema and throws an error if it's invalid. This is a convenience
* function for validating one single constructor parameter.
*
* @param className - The name of the class (used for error messages)
* @param paramName - The name of the parameter being validated (used for error messages)
* @param schema - The schema to validate against
* @param value - The value to validate
*
* @returns The validated value
* @throws An error if the value is invalid
*/
validateConstructorParamOrThrow(className, paramName, schema, value, stack) {
const functionCall = import_chalk.default.yellowBright(text`
${className}(${import_chalk.default.redBright(paramName)})
`);
return this.validateOrThrow(`Invalid parameter(s) when constructing ${functionCall}`, paramName, schema, value, stack);
}
/**
* Validates multiple values against multiple schemas and throws an error if any of them are
* invalid. This is a convenience function for validating multiple constructor parameters.
*
* @param className - The name of the class (used for error messages)
* @param paramNames - The names of the parameters being validated (used for error messages)
*
* @param schemas - The schemas to validate against
* @param values - The values to validate
*/
validateConstructorParamsOrThrow(className, paramNames, schemas, values, stack) {
return this.validateMultipleOrThrow((erroredValues) => {
const coloredParamNames = paramNames.map((name, index) => erroredValues.has(index) ? import_chalk.default.redBright(name) : name);
const functionCall = import_chalk.default.yellowBright(text`
${className}(${coloredParamNames.join(", ")})
`);
return `Invalid parameter(s) when constructing ${functionCall}:`;
}, paramNames, schemas, values, stack);
}
};
var sharedValidator = new Validator();
var FileHandle = class {
/**
* @deprecated Direct construction is not recommended. Please use the `prepareFile` API instead
*/
constructor(filesNamespace, identifier, type, sizeBytes, name) {
this.filesNamespace = filesNamespace;
this.identifier = identifier;
this.type = type;
this.sizeBytes = sizeBytes;
this.name = name;
this.parsedIdentifier = parseFileIdentifier(identifier);
}
/**
* Gets the absolute file path of this file.
*/
async getFilePath() {
switch (this.parsedIdentifier.type) {
case "local": {
return (await this.filesNamespace.getLocalFileAbsolutePath(this.parsedIdentifier.fileName)).path;
}
case "base64": {
throw new Error("Not implemented. Please open an issue on GitHub if you encountered this error.");
}
default: {
const _exhaustiveCheck = this.parsedIdentifier;
throw new Error(`Unexpected file identifier type: ${JSON.stringify(_exhaustiveCheck)}`);
}
}
}
isImage() {
return this.type === "image";
}
};
var chatMessageInputSchema = external_exports.object({
role: external_exports.enum(["user", "assistant", "system"]).optional(),
content: external_exports.string().optional(),
images: external_exports.array(external_exports.instanceof(FileHandle)).optional()
});
var chatHistoryInputSchema = external_exports.array(chatMessageInputSchema);
function isChatMessageInputAsOpposeToChatMessageData(chatMessageInput) {
return !Array.isArray(chatMessageInput.content);
}
function isChatMessageInputAsOpposeToChatHistoryData(chatMessageInput) {
return !("messages" in chatMessageInput);
}
function chatMessageInputToChatMessageData(chatMessageInput) {
const { role, content, images } = chatMessageInput;
const parts = [];
if (images === void 0 || images.length === 0) {
if (content === void 0) {
parts.push({
type: "text",
text: ""
});
}
} else {
for (const file of images) {
parts.push({
type: "file",
identifier: file.identifier,
name: file.name,
fileType: file.type,
sizeBytes: file.sizeBytes
});
}
}
if (content !== void 0) {
parts.push({
type: "text",
text: content
});
}
return {
role: role ?? "user",
content: parts
};
}
var Chat = class _Chat extends MaybeMutable {
getClassName() {
return "Chat";
}
create(data, mutable) {
return new _Chat(data, mutable);
}
cloneData(data) {
return chatHistoryDataSchema.parse(data);
}
/**
* Don't use this constructor directly.
*
* - To create an empty chat history, use `Chat.empty()`.
* - To create a chat history with existing data, use `Chat.from()`.
*/
constructor(data, mutable) {
super(data, mutable);
}
/**
* Creates an empty mutable chat history.
*/
static empty() {
return new _Chat({ messages: [] }, true);
}
/**
* Quickly create a mutable chat history with something that can be converted to a chat history.
*
* The created chat history will be a mutable copy of the input.
*
* @example
* ```ts
* const history = Chat.from([
* { role: "user", content: "Hello" },
* { role: "assistant", content: "Hi!" },
* { role: "user", content: "What is your name?" },
* ]);
* ```
*/
static from(initializer) {
const stack = getCurrentStack(1);
sharedValidator.validateMethodParamOrThrow("Chat", "from", "initializer", chatHistoryLikeSchema, initializer, stack);
if (initializer instanceof _Chat) {
return initializer.asMutableCopy();
}
if (typeof initializer === "string") {
const chatHistory = _Chat.empty();
chatHistory.append("user", initializer);
return chatHistory;
}
if (Array.isArray(initializer)) {
return new _Chat({ messages: initializer.map(chatMessageInputToChatMessageData) }, true);
}
if (isChatMessageInputAsOpposeToChatHistoryData(initializer)) {
return new _Chat({ messages: [chatMessageInputToChatMessageData(initializer)] }, true);
} else {
return new _Chat(initializer, false).asMutableCopy();
}
}
/**
* Creates a chat history with raw data. This method is intended for internal use only.
*
* If mutable is set to false, you MUST ensure that the data is not mutated.
*
* @internal
*/
static createRaw(data, mutable) {
return new _Chat(data, mutable);
}
/**
* Gets the raw data of this message. This method is intended for internal use only.
*
* If mutable is set to false, you MUST ensure that the data is not mutated.
*
* @internal
*/
getRaw() {
return this.data;
}
append(...args) {
this.guardMutable();
if (args.length === 1) {
const [chatMessageLike] = args;
const chatMessage = ChatMessage.from(chatMessageLike);
const messageMutable = accessMaybeMutableInternals(chatMessage)._internalToMutable();
this.data.messages.push(accessMaybeMutableInternals(messageMutable)._internalGetData());
} else {
const [role, content, opts = {}] = args;
if (role === "user" || role === "system" || role === "assistant") {
const parts = [
{ type: "text", text: content }
];
if (opts.images !== void 0) {
for (const image of opts.images) {
parts.push({
type: "file",
name: image.name,
identifier: image.identifier,
sizeBytes: image.sizeBytes,
fileType: image.type
});
}
}
this.data.messages.push({ role, content: parts });
} else {
throw new Error(text`
Unsupported role for append() API with [role, content] parameters: ${role}.
Supported roles are 'user', 'system', and 'assistant'.
`);
}
}
}
withAppended(...args) {
const copy2 = this.asMutableCopy();
copy2.append(...args);
return copy2;
}
/**
* Get the number of messages in the history.
*/
getLength() {
return this.data.messages.length;
}
/**
* Get the number of messages in the history.
*/
get length() {
return this.getLength();
}
/**
* Remove the last message from the history. If the history is empty, this method will throw.
*/
pop() {
this.guardMutable();
if (this.data.messages.length === 0) {
throw new Error("Tried to pop from an empty history.");
}
const popped = this.data.messages.pop();
return ChatMessage.createRaw(popped, true);
}
/**
* Gets all files contained in this history.
*
* @param client - LMStudio client
*/
getAllFiles(client) {
return this.data.messages.flatMap((message) => message.content.filter((part) => part.type === "file")).map((part) => new FileHandle(client.files, part.identifier, part.fileType, part.sizeBytes, part.name));
}
/**
* Allows iterating over the files in the history.
*/
*files(client) {
for (const message of this.data.messages) {
for (const part of message.content) {
if (part.type === "file") {
yield new FileHandle(client.files, part.identifier, part.fileType, part.sizeBytes, part.name);
}
}
}
}
/**
* Returns true if this history contains any files.
*/
hasFiles() {
return this.data.messages.some((message) => message.content.some((part) => part.type === "file"));
}
/**
* Gets the message at the given index. If the index is negative, it will be counted from the end.
*
* If the index is out of bounds, this method will throw as oppose to returning undefined. This is
* to help catch bugs early.
*/
at(index) {
let actualIndex = index;
if (index < 0) {
actualIndex = this.data.messages.length + index;
}
if (actualIndex < 0 || actualIndex >= this.data.messages.length) {
throw new Error(text`
Tried to access the message at index ${index}, but the history only has
${this.data.messages.length} messages.
`);
}
return ChatMessage.createRaw(this.data.messages[actualIndex], this.mutable);
}
/**
* Get all the messages in the history as an array of ChatMessage objects.
*/
getMessagesArray() {
return this.data.messages.map((message) => ChatMessage.createRaw(message, this.mutable));
}
/**
* Maps over the messages in the history and returns an array of the results.
*/
map(mapper) {
return this.getMessagesArray().map(mapper);
}
/**
* Maps over the messages in the history and returns a flattened array of the results.
*
* This is similar to `Array.prototype.flatMap`, but it works with ChatMessage objects.
*/
flatMap(mapper) {
return this.getMessagesArray().flatMap(mapper);
}
/**
* Allows iterating over the messages in the history.
*/
*[Symbol.iterator]() {
for (const message of this.data.messages) {
yield ChatMessage.createRaw(message, this.mutable);
}
}
/**
* Given a predicate, the predicate is called for each file in the history.
*
* - If the predicate returns true, the file is removed from the history and is collected into the
* returned array.
* - If the predicate returns false, the file is kept in the history.
*
* This method is useful if you are implementing a promptPreprocessor that needs to convert certain
* types of files.
*
* If the predicate needs to be async, use the {@link Chat#consumeFilesAsync} method.
*
* @param client - LMStudio client
* @param predicate - The predicate to call for each file.
* @returns The files that were consumed.
*/
consumeFiles(client, predicate) {
this.guardMutable();
const consumedFiles = [];
for (const message of this.data.messages) {
consumedFiles.push(...ChatMessage.createRaw(message, true).consumeFiles(client, predicate));
}
return consumedFiles;
}
/**
* Given an async predicate, the predicate is called for each file in the history.
*
* - If the predicate returns true, the file is removed from the history and is collected into the
* returned array.
* - If the predicate returns false, the file is kept in the history.
*
* This method is useful if you are implementing a promptPreprocessor that needs to convert certain
* types of files.
*
* If you need a synchronous version, use the {@link Chat#consumeFiles} method.
*
* @param client - LMStudio client
* @param predicate - The predicate to call for each file.
* @returns The files that were consumed.
*/
async consumeFilesAsync(client, predicate) {
this.guardMutable();
const consumedFiles = [];
for (const message of this.data.messages) {
consumedFiles.push(...await ChatMessage.createRaw(message, true).consumeFilesAsync(client, predicate));
}
return consumedFiles;
}
getSystemPrompt() {
return this.data.messages.filter((message) => message.role === "system").map((message) => message.content.filter((part) => part.type === "text").map((part) => part.text).join(" ")).join("\n\n");
}
replaceSystemPrompt(content) {
this.guardMutable();
this.data.messages = this.data.messages.filter((message) => message.role !== "system");
this.data.messages.unshift({ role: "system", content: [{ type: "text", text: content }] });
}
filterInPlace(predicate) {
this.guardMutable();
this.data.messages = this.data.messages.filter((message) => predicate(ChatMessage.createRaw(message, true)));
}
toString() {
return "Chat {\n" + this.data.messages.map((message) => {
const messageString = ChatMessage.createRaw(message, false).toString();
return messageString.split("\n").map((line) => " " + line).join("\n");
}).join("\n") + "\n}";
}
};
var chatHistoryLikeSchema = external_exports.union([
external_exports.instanceof(Chat),
chatHistoryDataSchema,
external_exports.string(),
chatHistoryInputSchema,
chatMessageInputSchema
]);
var ChatMessage = class _ChatMessage extends MaybeMutable {
getClassName() {
return "ChatMessage";
}
create(data, mutable) {
return new _ChatMessage(data, mutable);
}
cloneData(data) {
return chatMessageDataSchema.parse(data);
}
constructor(data, mutable) {
super(data, mutable);
}
/**
* Create a mutable text only message.
*/
static create(role, content) {
return new _ChatMessage(chatMessageDataSchema.parse({
role,
content: [{ type: "text", text: content }]
}), true);
}
/**
* Quickly create a mutable message with something that can be converted to a message.
*/
static from(initializer) {
const stack = getCurrentStack(1);
sharedValidator.validateMethodParamOrThrow("ChatMessage", "from", "initializer", chatMessageLikeSchema, initializer, stack);
if (initializer instanceof _ChatMessage) {
return initializer.asMutableCopy();
}
if (typeof initializer === "string") {
return new _ChatMessage(chatMessageDataSchema.parse({
role: "user",
content: [{ type: "text", text: initializer }]
}), true);
}
if (isChatMessageInputAsOpposeToChatMessageData(initializer)) {
return new _ChatMessage(chatMessageInputToChatMessageData(initializer), true);
} else {
return new _ChatMessage(initializer, true);
}
}
/**
* Creates a chat history with raw data. This method is intended for internal use only.
*
* If mutable is set to false, you MUST ensure that the data is not mutated.
*
* @internal
*/
static createRaw(data, mutable) {
return new _ChatMessage(data, mutable);
}
/**
* Gets the raw data of this message. This method is intended for internal use only.
*
* If mutable is set to false, you MUST ensure that the data is not mutated.
*
* @internal
*/
getRaw() {
return this.data;
}
getRole() {
return this.data.role;
}
setRole(role) {
this.guardMutable();
this.data.role = role;
}
getFileParts() {
return this.data.content.filter((part) => part.type === "file");
}
/**
* Gets all text contained in this message.
*/
getText() {
return this.data.content.filter((part) => part.type === "text").map((part) => part.text).join(" ");
}
/**
* Get all tool call results within this message.
*/
getToolCallResults() {
return this.data.content.filter((part) => part.type === "toolCallResult").map((part) => ({
content: part.content,
toolCallId: part.toolCallId
}));
}
/**
* Gets all file parts contained in this message.
*/
getToolCallRequests() {
return this.data.content.filter((part) => part.type === "toolCallRequest").map((part) => part.toolCallRequest);
}
/**
* Gets all files contained in this message.
*
* @param client - LMStudio client
*/
getFiles(client) {
return this.getFileParts().map((part) => new FileHandle(client.files, part.identifier, part.fileType, part.sizeBytes, part.name));
}
/**
* Allows iterating over the files in the message.
*/
*files(client) {
for (const part of this.getFileParts()) {
yield new FileHandle(client.files, part.identifier, part.fileType, part.sizeBytes, part.name);
}
}
/**
* Given a predicate, the predicate is called for each file in the message.
*
* - If the predicate returns true, the file is removed from the message and is collected into the
* returned array.
* - If the predicate returns false, the file is kept in the message.
*
* This method is useful if you are implementing a promptPreprocessor that needs to convert certain
* types of files.
*
* If the predicate needs to be async, use the {@link ChatMessage#consumeFilesAsync} method.
*
* @param client - LMStudio client
* @param predicate - The predicate to call for each file.
* @returns The files that were consumed.
*/
consumeFiles(client, predicate) {
this.guardMutable();
const consumedFiles = [];
const partIndexesToRemove = /* @__PURE__ */ new Set();
for (const [index, part] of this.data.content.entries()) {
if (part.type !== "file") {
continue;
}
const file = new FileHandle(client.files, part.identifier, part.fileType, part.sizeBytes, part.name);
if (predicate(file)) {
consumedFiles.push(file);
partIndexesToRemove.add(index);
}
}
this.data.content = this.data.content.filter((_, index) => !partIndexesToRemove.has(index));
return consumedFiles;
}
/**
* Given an async predicate, the predicate is called for each file in the message.
*
* - If the predicate returns true, the file is removed from the message and is collected into the
* returned array.
* - If the predicate returns false, the file is kept in the message.
*
* This method is useful if you are implementing a promptPreprocessor that needs to convert certain
* types of files.
*
* If you need a synchronous version, use the {@link ChatMessage#consumeFiles} method.
*
* @param client - LMStudio client
* @param predicate - The predicate to call for each file.
* @returns The files that were consumed.
*/
async consumeFilesAsync(client, predicate) {
this.guardMutable();
const consumedFiles = [];
const partIndexesToRemove = /* @__PURE__ */ new Set();
for (const [index, part] of this.data.content.entries()) {
if (part.type !== "file") {
continue;
}
const file = new FileHandle(client.files, part.identifier, part.fileType, part.sizeBytes, part.name);
if (await predicate(file)) {
consumedFiles.push(file);
partIndexesToRemove.add(index);
}
}
this.data.content = this.data.content.filter((_, index) => !partIndexesToRemove.has(index));
return consumedFiles;
}
/**
* Returns true if this message contains any files.
*/
hasFiles() {
return this.data.content.some((part) => part.type === "file");
}
/**
* Append text to the message.
*/
appendText(text2) {
this.guardMutable();
switch (this.data.role) {
case "assistant":
case "user":
case "system":
this.data.content.push({
type: "text",
text: text2
});
break;
case "tool":
throw new Error(`Cannot append text to a message with role "${this.data.role}"`);
default: {
const exhaustiveCheck = this.data;
throw new Error(`Unhandled role in switch statement: ${exhaustiveCheck.role}`);
}
}
}
/**
* Append a file to the message. Takes in a FileHandle. You can obtain a FileHandle from
* `client.files.prepareImage`.
*/
appendFile(file) {
this.guardMutable();
switch (this.data.role) {
case "assistant":
case "user":
case "system":
this.data.content.push({
type: "file",
name: file.name,
identifier: file.identifier,
sizeBytes: file.sizeBytes,
fileType: file.type
});
break;
case "tool":
throw new Error(`Cannot append text to a message with role "${this.data.role}"`);
default: {
const exhaustiveCheck = this.data;
throw new Error(`Unhandled role in switch statement: ${exhaustiveCheck.role}`);
}
}
}
/**
* Replaces all text in the messages.
*
* If the message contains other components (such as files), they will kept. The replaced text
* will be inserted to the beginning of the message.
*/
replaceText(text2) {
this.guardMutable();
switch (this.data.role) {
case "assistant":
case "user":
case "system":
this.data.content = [
{ type: "text", text: text2 },
...this.data.content.filter((part) => part.type !== "text")
];
break;
case "tool":
throw new Error(`Cannot replace text in a message with role "${this.data.role}"`);
default: {
const exhaustiveCheck = this.data;
throw new Error(`Unhandled role in switch statement: ${exhaustiveCheck.role}`);
}
}
}
isSystemPrompt() {
return this.data.role === "system";
}
isUserMessage() {
return this.data.role === "user";
}
isAssistantMessage() {
return this.data.role === "assistant";
}
toString() {
const text2 = this.data.content.map((part) => {
switch (part.type) {
case "text":
return part.text;
case "file":
return `<file ${part.name}>`;
case "toolCallRequest":
return part.toolCallRequest.name + `(${JSON.stringify(part.toolCallRequest.arguments)})`;
case "toolCallResult":
return part.content;
default: {
const exhaustiveCheck = part;
throw new Error(`Unknown part type: ${exhaustiveCheck.type}`);
}
}
}).join(" ");
if (text2.includes("\n")) {
return this.data.role + ":\n" + text2.split("\n").map((line) => " " + line).join("\n");
} else {
return this.data.role + ": " + text2;
}
}
};
var chatMessageLikeSchema = external_exports.union([
external_exports.instanceof(ChatMessage),
chatMessageInputSchema,
external_exports.string(),
chatMessageDataSchema
]);
var KVFieldValueTypesLibraryBuilder = class {
constructor(baseSchema) {
this.baseSchema = baseSchema;
this.valueTypes = /* @__PURE__ */ new Map();
}
/**
* Define a new field value type.
*/
valueType(key, param) {
if (this.valueTypes.has(key)) {
throw new Error(`ValueType with key ${key} already exists`);
}
this.valueTypes.set(key, {
paramType: external_exports.object({
...this.baseSchema,
...param.paramType
}),
schemaMaker: param.schemaMaker,
effectiveEquals: param.effectiveEquals,
stringify: param.stringify
});
return this;
}
build() {
return new KVFieldValueTypeLibrary(new Map(this.valueTypes));
}
};
var KVFieldValueTypeLibrary = class {
constructor(valueTypes) {
this.valueTypes = valueTypes;
}
/**
* Gets the schema for a specific field value type with the given key and parameters.
*/
getSchema(key, param) {
const valueType = this.valueTypes.get(key);
if (valueType === void 0) {
throw new Error(`Cannot find value type ${key}`);
}
return valueType.schemaMaker(valueType.paramType.parse(param));
}
parseParamTypes(key, param) {
return this.valueTypes.get(key).paramType.parse(param);
}
effectiveEquals(key, typeParam, a, b) {
return this.valueTypes.get(key).effectiveEquals(a, b, typeParam);
}
stringify(key, typeParam, opts, value) {
return this.valueTypes.get(key).stringify(value, typeParam, opts);
}
};
var KVConfigSchematicsBuilder = class _KVConfigSchematicsBuilder {
constructor(valueTypeLibrary) {
this.valueTypeLibrary = valueTypeLibrary;
this.fields = /* @__PURE__ */ new Map();
this.extensionPrefixes = [];
}
/**
* Adds a field
*/
field(key, valueTypeKey, valueTypeParams, defaultValue) {
const schema = this.valueTypeLibrary.getSchema(valueTypeKey, valueTypeParams);
const defaultValueParseResult = schema.safeParse(defaultValue);
if (!defaultValueParseResult.success) {
throw new Error(`Invalid default value for field ${key}: ${defaultValueParseResult.error.message}`);
}
defaultValue = defaultValueParseResult.data;
if (this.fields.has(key)) {
throw new Error(`Cannot add field with key ${key}. Key already exists in the schematics.`);
}
this.fields.set(key, {
valueTypeKey,
valueTypeParams,
schema: this.valueTypeLibrary.getSchema(valueTypeKey, valueTypeParams),
fullKey: key,
defaultValue
});
return this;
}
/**
* Adds an extension point. For example, if called with .extension("hello.world"), then any keys
* that match "hello.world.*" will be allowed when going through lenient zod schema. However,
* any extension fields will still not be accessible via this schematics.
*/
extension(prefix) {
this.extensionPrefixes.push(`${prefix}.`);
return this;
}
/**
* Convenience method for grouping a set of fields under a shared namespace.
*
* For example, if we want to create two fields: `some:namespace:a` and `some:namespace:b`.
* Instead of doing:
*
* ```ts
* builder
* .field("some:namespace:a", ...)
* .field("some:namespace:b", ...)
* ```
*
* We can do:
*
* ```ts
* builder.scope("some:namespace", builder =>
* builder
* .field("a", ...)
* .field("b", ...)
* )
* ```
*
* This method does support nesting. Whether to nest or not is up to the user.
*/
scope(scopeKey, fn) {
const innerBuilder = fn(new _KVConfigSchematicsBuilder(this.valueTypeLibrary));
for (const [key, { valueTypeKey, valueTypeParams, schema, defaultValue }] of innerBuilder.fields.entries()) {
const fullKey = `${scopeKey}.${key}`;
if (this.fields.has(fullKey)) {
throw new Error(`Cannot add field with key ${fullKey}. Key already exists in the schematics.`);
}
this.fields.set(fullKey, {
valueTypeKey,
valueTypeParams,
schema,
fullKey,
defaultValue
});
}
this.extensionPrefixes.push(...innerBuilder.extensionPrefixes.map((prefix) => `${scopeKey}.${prefix}`));
return this;
}
build() {
return new KVConfigSchematics(this.valueTypeLibrary, this.fields, this.extensionPrefixes);
}
};
var createParsedKVConfig = /* @__PURE__ */ Symbol("createParsedKVConfig");
var KVConfigSchematics = class _KVConfigSchematics {
constructor(valueTypeLibrary, fields, extensionPrefixes) {
this.valueTypeLibrary = valueTypeLibrary;
this.fields = fields;
this.extensionPrefixes = extensionPrefixes;
this.fullKepMap = void 0;
this.lenientZodSchema = void 0;
}
getFieldsMap() {
return new Map([...this.fields.values()].map((field) => [field.fullKey, field]));
}
obtainField(key) {
const field = this.fields.get(key);
if (field === void 0) {
const fieldKeys = [...this.fields.keys()];
let availableList = fieldKeys.slice(0, 10).map((key2) => `- ${key2}`).join("\n");
if (fieldKeys.length > 10) {
availableList += `
... and ${fieldKeys.length - 10} more`;
}
throw new Error(`Cannot access key ${key}. Key does not exist in the schematics. Available keys:
` + availableList);
}
return field;
}
obtainFieldByFullKey(fullKey) {
const field = this.getFullKeyMap().get(fullKey);
if (field === void 0) {
const fieldKeys = [...this.getFullKeyMap().keys()];
let availableList = fieldKeys.slice(0, 10).map((key) => `- ${key}`).join("\n");
if (fieldKeys.length > 10) {
availableList += `
... and ${fieldKeys.length - 10} more`;
}
throw new Error(`Cannot access full key ${fullKey}. Full key does not exist in the schematics. Availablekeys:
` + availableList);
}
return field;
}
getSchemaForKey(key) {
const field = this.obtainField(key);
return field.schema;
}
parseField(fieldSchema, value) {
if (value === void 0) {
if (fieldSchema.defaultValue === void 0) {
throw new Error(`Field with key ${fieldSchema.fullKey} is missing and has no default value`);
}
return fieldSchema.defaultValue;
}
const parseResult = fieldSchema.schema.safeParse(value);
if (!parseResult.success) {
throw new Error(`Field with key ${fieldSchema.fullKey} does not satisfy the schema:` + parseResult.error.message);
}
return parseResult.data;
}
parseFieldWithoutDefault(field, value) {
if (value === void 0) {
return void 0;
}
const parseResult = field.schema.safeParse(value);
if (!parseResult.success) {
throw new Error(`Field with key ${field.fullKey} does not satisfy the schema:` + parseResult.error.message);
}
return parseResult.data;
}
/**
* Parse and access a field in the config.
*/
access(config, key) {
const field = this.obtainField(key);
return this.parseField(field, config.fields.find((f) => f.key === field.fullKey)?.value);
}
accessByFullKey(config, fullKey) {
const field = this.obtainFieldByFullKey(fullKey);
return this.parseField(field, config.fields.find((f) => f.key === field.fullKey)?.value);
}
/**
* Parse and access a field in the config. Returns undefined if the field is missing.
*/
accessPartial(config, key) {
const field = this.obtainField(key);
return this.parseFieldWithoutDefault(field, config.fields.find((f) => f.key === field.fullKey)?.value);
}
/**
* Gets a slice of the config schema with the given key patterns. Support syntax:
*
* - `some.namespace.key`: Matches exactly `some.namespace.key`
* - `some.namespace.*`: Matches anything that starts with `some.namespace.`
*/
sliced(...patterns) {
const parsedPatterns = patterns.map((p) => {
if (p.endsWith("*")) {
return { type: "prefix", value: p.substring(0, p.length - 1) };
}
return { type: "exact", value: p };
});
const newFields = /* @__PURE__ */ new Map();
for (const [key, field] of this.fields.entries()) {
for (const pattern of parsedPatterns) {
if (pattern.type === "exact" && key === pattern.value || pattern.type === "prefix" && key.startsWith(pattern.value)) {
newFields.set(key, field);
}
}
}
return new _KVConfigSchematics(this.valueTypeLibrary, newFields, this.extensionPrefixes);
}
/**
* Get a subset of the config schema with a specific scope.
*/
scoped(scopeKey) {
const newFields = /* @__PURE__ */ new Map();
for (const [key, field] of this.fields.entries()) {
if (key.startsWith(`${scopeKey}.`)) {
newFields.set(key.substring(scopeKey.length + 1), field);
}
}
return new _KVConfigSchematics(this.valueTypeLibrary, newFields, this.extensionPrefixes);
}
union(other) {
const newFields = /* @__PURE__ */ new Map();
for (const [key, field] of this.fields.entries()) {
newFields.set(key, field);
}
for (const [key, field] of other.fields.entries()) {
if (newFields.has(key)) {
throw new Error("Cannot union two KVConfigSchematics. The following key is duplicated: " + key);
}
newFields.set(key, field);
}
return new _KVConfigSchematics(this.valueTypeLibrary, newFields, [
...this.extensionPrefixes,
...other.extensionPrefixes
]);
}
/**
* Combine baseKey into the fields. Effectively removes the baseKey.
*/
flattenBaseKey() {
const newFields = /* @__PURE__ */ new Map();
for (const field of this.fields.values()) {
newFields.set(field.fullKey, field);
}
return new _KVConfigSchematics(this.valueTypeLibrary, newFields, this.extensionPrefixes);
}
parseToMap(config) {
const rawConfigMap = kvConfigToMap(config);
const parsedConfigMap = /* @__PURE__ */ new Map();
for (const [key, field] of this.fields.entries()) {
const value = rawConfigMap.get(field.fullKey);
const parsedValue = this.parseField(field, value);
parsedConfigMap.set(key, parsedValue);
}
return parsedConfigMap;
}
parseToMapWithFullKey(config) {
const rawConfigMap = kvConfigToMap(config);
const parsedConfigMap = /* @__PURE__ */ new Map();
for (const field of this.fields.values()) {
const value = rawConfigMap.get(field.fullKey);
const parsedValue = this.parseField(field, value);
parsedConfigMap.set(field.fullKey, parsedValue);
}
return parsedConfigMap;
}
parseToMapPartial(config) {
const rawConfigMap = kvConfigToMap(config);
const parsedConfigMap = /* @__PURE__ */ new Map();
for (const [key, field] of this.fields.entries()) {
const value = rawConfigMap.get(field.fullKey);
const parsedValue = this.parseFieldWithoutDefault(field, value);
if (parsedValue !== void 0) {
parsedConfigMap.set(key, parsedValue);
}
}
return parsedConfigMap;
}
/**
* Parse the given config to a ParsedKVConfig. **Will throw** if the config does not satisfy the
* schema.
*/
parse(config) {
return ParsedKVConfig[createParsedKVConfig](this.parseToMap(config));
}
parsePartial(config) {
return PartialParsedKVConfig[createParsedKVConfig](this.parseToMapPartial(config));
}
/**
* Builds a full KV config from the given values record. **Will throw** if any of the values are
* missing or do not satisfy the schema.
*/
buildFullConfig(valuesRecord) {
return {
fields: Array.from(this.fields.entries()).map(([key, field]) => {
const value = this.parseField(field, valuesRecord[key]);
return { key: field.fullKey, value };
})
};
}
/**
* Builds a partial KV config from the given values record. Will leave holes in the config if the
* values are missing. **Will throw** if any of the values do not satisfy the schema.
*/
buildPartialConfig(valuesRecord) {
return {
fields: Object.entries(valuesRecord).filter(([_key, value]) => value !== void 0).map(([key, value]) => {
const field = this.obtainField(key);
return { key: field.fullKey, value: this.parseField(field, value) };
})
};
}
createBuildPartialConfigInput() {
return {};
}
configBuilder() {
return new KVConfigBuilder(this.fields);
}
clone() {
return new _KVConfigSchematics(this.valueTypeLibrary, new Map(this.fields), this.extensionPrefixes);
}
withTypeParamOverride(key, paramMapper) {
const field = this.obtainField(key);
const clone = this.clone();
clone.fields.set(key, {
...field,
valueTypeParams: paramMapper(field.valueTypeParams),
schema: this.valueTypeLibrary.getSchema(field.valueTypeKey, paramMapper(field.valueTypeParams))
});
return clone;
}
getFullKeyMap() {
if (this.fullKepMap !== void 0) {
return this.fullKepMap;
}
this.fullKepMap = new Map([...this.fields.values()].map((field) => [field.fullKey, field]));
return this.fullKepMap;
}
makeLenientZodSchema() {
const fullKeyMap = this.getFullKeyMap();
return kvConfigSchema.transform((value) => {
const seenKeys = /* @__PURE__ */ new Set();
return {
fields: value.fields.filter((field) => {
if (this.extensionPrefixes.some((prefix) => field.key.startsWith(prefix))) {
return true;
}
if (seenKeys.has(field.key)) {
return false;
}
const fieldDef = fullKeyMap.get(field.key);
if (fieldDef === void 0) {
return false;
}
const parsed = fieldDef.schema.safeParse(field.value);
if (!parsed.success) {
return false;
}
seenKeys.add(field.key);
return true;
})
};
});
}
/**
* Makes a zod schema that parses a KVConfig which only allows fields with correct keys and types
* through.
*
* Will filter out any fields that are not in the schema.
*/
getLenientZodSchema() {
if (this.lenientZodSchema !== void 0) {
return this.lenientZodSchema;
}
this.lenientZodSchema = this.makeLenientZodSchema();
return this.lenientZodSchema;
}
getValueType(key) {
const field = this.fields.get(key);
if (field === void 0) {
return null;
}
return field.valueTypeKey;
}
getValueTypeParam(key) {
const field = this.fields.get(key);
if (field === void 0) {
return null;
}
return field.valueTypeParams;
}
getValueTypeParamByFullKey(key) {
const field = this.getFullKeyMap().get(key);
if (field === void 0) {
throw new Error(`Field with key ${key} does not exist in the schematics`);
}
return field.valueTypeParams;
}
hasFullKey(key) {
const field = this.getFullKeyMap().get(key);
return field !== void 0;
}
/**
* Given a KVConfig, filter it to only include fields that are in the schematics.
*/
filterConfig(config, additionalFilter) {
const fullKeyMap = this.getFullKeyMap();
return {
fields: config.fields.filter((configField) => {
const field = fullKeyMap.get(configField.key);
if (field === void 0) {
return false;
}
if (additionalFilter !== void 0) {
return additionalFilter(field.fullKey, {
type: field.valueTypeKey,
param: field.valueTypeParams
});
}
return true;
})
};
}
/**
* Given a KVConfigStack, filter it to only include fields that are in the schematics.
*/
filterStack(stack) {
return {
layers: stack.layers.map((layer) => ({
layerName: layer.layerName,
config: this.filterConfig(layer.config)
}))
};
}
twoWayFilterConfig(config, additionalFilter) {
const includedFields = [];
const excludedFields = [];
const fullKeyMap = this.getFullKeyMap();
for (const configField of config.fields) {
const field = fullKeyMap.get(configField.key);
let include = field !== void 0;
if (field !== void 0 && additionalFilter !== void 0) {
include = additionalFilter(field.fullKey, {
type: field.valueTypeKey,
param: field.valueTypeParams
});
}
if (include) {
includedFields.push(configField);
} else {
excludedFields.push(configField);
}
}
return [{ fields: includedFields }, { fields: excludedFields }];
}
/**
* Given a list of keys, filter it to only include keys that are in the schematics.
*/
filterFullKeys(keys) {
const fullKeyMap = this.getFullKeyMap();
return keys.filter((key) => fullKeyMap.has(key));
}
/**
* Compares two KV config. Compare with "effective equals". Only compare fields in the schematics.
* Does not apply defaults.
*/
configEffectiveEquals(a, b) {
const aMap = kvConfigToMap(a);
const bMap = kvConfigToMap(b);
for (const field of this.fields.values()) {
const aValue = aMap.get(field.fullKey);
const bValue = bMap.get(field.fullKey);
if (aValue === void 0) {
if (bValue === void 0) {
continue;
} else {
return false;
}
}
this.valueTypeLibrary.effectiveEquals(field.valueTypeKey, field.valueTypeParams, aValue, bValue);
}
return true;
}
/**
* Compares two KV config field. Compare with "effective equals". Can only compare fields in the
* schematics.
*/
fieldEffectiveEquals(key, a, b) {
const field = this.obtainField(key);
return this.valueTypeLibrary.effectiveEquals(field.valueTypeKey, field.valueTypeParams, field.schema.parse(a), field.schema.parse(b));
}
fieldEffectiveEqualsWithFullKey(fullKey, a, b) {
const fullKeyMap = this.getFullKeyMap();
const field = fullKeyMap.get(fullKey);
if (field === void 0) {
throw new Error(`Field with key ${fullKey} does not exist in the schematics`);
}
return this.valueTypeLibrary.effectiveEquals(field.valueTypeKey, field.valueTypeParams, field.schema.parse(a), field.schema.parse(b));
}
makeInternalFieldStringifyOpts(opts) {
return {
t: opts.t ?? ((_key, fallback) => fallback),
desiredLength: opts.desiredLength
};
}
stringifyField(key, value, opts = {}) {
const field = this.obtainField(key);
return this.valueTypeLibrary.stringify(field.valueTypeKey, field.valueTypeParams, this.makeInternalFieldStringifyOpts(opts), value);
}
tryStringifyFieldWithFullKey(key, value, opts) {
const fullKeyMap = this.getFullKeyMap();
const field = fullKeyMap.get(key);
if (field === void 0) {
return null;
}
return this.valueTypeLibrary.stringify(field.valueTypeKey, field.valueTypeParams, this.makeInternalFieldStringifyOpts(opts), value);
}
/**
* Apply config in patch to target. Only apply fields that are in the schematics.
*/
apply(target, patch) {
const filteredPatch = this.filterConfig(patch);
return collapseKVStackRaw([target, filteredPatch]);
}
/**
* Tries to un-apply the patch from the target. Will only un-apply fields that are in the
* schematics.
*
* If the value in the target is not effective equal to the value in the patch, it will not be
* removed.
*/
unApply(target, patch) {
const filteredPatch = this.filterConfig(patch);
const patchMap = kvConfigToMap(filteredPatch);
const newMap = new Map(kvConfigToMap(target));
const fullKeyMap = this.getFullKeyMap();
for (const [key, value] of patchMap.entries()) {
const field = fullKeyMap.get(key);
if (field === void 0) {
continue;
}
const targetValue = newMap.get(key);
if (targetValue !== void 0) {
if (!this.valueTypeLibrary.effectiveEquals(field.valueTypeKey, field.valueTypeParams, value, targetValue)) {
continue;
}
newMap.delete(key);
}
}
return mapToKVConfig(newMap);
}
/**
* Given a KVConfig, iterate through all the fields that are in the schematics. Keys will be full
* keys.
*/
*iterateFieldsOfConfig(config) {
const fullKeyMap = this.getFullKeyMap();
for (const { key, value } of config.fields) {
const field = fullKeyMap.get(key);
if (field !== void 0) {
yield [key, value];
}
}
}
/**
* Given a KVConfig, iterate through all the fields that are in the schematics.
*/
*fullKeys() {
const fullKeyMap = this.getFullKeyMap();
for (const key of fullKeyMap.keys()) {
yield key;
}
}
/**
* Effectively compare two KV config, and return full keys of fields that are different.
*/
effectiveCompareConfig(a, b, opts = {}) {
const { fieldFilter } = opts;
const aMap = kvConfigToMap(a);
const bMap = kvConfigToMap(b);
const onlyInA = [];
const onlyInB = [];
const inBothButDifferent = [];
for (const field of this.fields.values()) {
if (fieldFilter !== void 0) {
if (!fieldFilter(field.fullKey, {
type: field.valueTypeKey,
param: field.valueTypeParams
})) {
continue;
}
}
const aValue = aMap.get(field.fullKey);
const bValue = bMap.get(field.fullKey);
if (aValue === void 0) {
if (bValue === void 0) {
continue;
} else {
onlyInB.push(field.fullKey);
}
} else {
if (bValue === void 0) {
onlyInA.push(field.fullKey);
} else {
if (!this.valueTypeLibrary.effectiveEquals(field.valueTypeKey, field.valueTypeParams, aValue, bValue)) {
inBothButDifferent.push(field.fullKey);
}
}
}
}
return { onlyInA, onlyInB, inBothButDifferent };
}
serialize() {
return {
fields: [...this.fields.entries()].map(([key, field]) => ({
shortKey: key,
fullKey: field.fullKey,
typeKey: field.valueTypeKey,
typeParams: field.valueTypeParams,
defaultValue: field.defaultValue
})),
extensionPrefixes: this.extensionPrefixes
};
}
/**
* Check if any of the fields in the schematics has a full key that starts with the given prefix.
*/
hasFieldsWithPrefix(prefix) {
for (const field of this.fields.values()) {
if (field.fullKey.startsWith(prefix)) {
return true;
}
}
return false;
}
static deserialize(valueTypeLibrary, serialized) {
const fields = new Map(serialized.fields.map((field) => {
const typeParams = valueTypeLibrary.parseParamTypes(field.typeKey, field.typeParams);
const valueSchema = valueTypeLibrary.getSchema(field.typeKey, typeParams);
return [
field.shortKey,
{
valueTypeKey: field.typeKey,
valueTypeParams: typeParams,
schema: valueSchema,
fullKey: field.fullKey,
defaultValue: valueSchema.parse(field.defaultValue)
}
];
}));
return new _KVConfigSchematics(valueTypeLibrary, fields, serialized.extensionPrefixes ?? []);
}
static tryDeserialize(valueTypeLibrary, serialized) {
const fields = /* @__PURE__ */ new Map();
const errors2 = [];
for (const field of serialized.fields) {
try {
const typeParams = valueTypeLibrary.parseParamTypes(field.typeKey, field.typeParams);
const valueSchema = valueTypeLibrary.getSchema(field.typeKey, typeParams);
fields.set(field.shortKey, {
valueTypeKey: field.typeKey,
valueTypeParams: typeParams,
schema: valueSchema,
fullKey: field.fullKey,
defaultValue: valueSchema.parse(field.defaultValue)
});
} catch (error) {
errors2.push({
fullKey: field.fullKey,
error: serializeError(error)
});
}
}
return {
schematics: new _KVConfigSchematics(valueTypeLibrary, fields, serialized.extensionPrefixes ?? []),
errors: errors2
};
}
};
var KVConfigBuilder = class {
constructor(fieldDefs) {
this.fieldDefs = fieldDefs;
this.fields = /* @__PURE__ */ new Map();
}
with(key, value) {
const field = this.fieldDefs.get(key);
if (field === void 0) {
throw new Error(`Field with key ${key} does not exist in the schematics.`);
}
this.fields.set(field.fullKey, value);
return this;
}
build() {
return mapToKVConfig(this.fields);
}
};
var ParsedKVConfig = class _ParsedKVConfig {
constructor(configMap) {
this.configMap = configMap;
}
/**
* @internal
*/
static [createParsedKVConfig](configMap) {
return new _ParsedKVConfig(configMap);
}
get(key) {
return this.configMap.get(key);
}
};
var PartialParsedKVConfig = class _PartialParsedKVConfig {
constructor(configMap) {
this.configMap = configMap;
}
static [createParsedKVConfig](configMap) {
return new _PartialParsedKVConfig(configMap);
}
get(key) {
return this.configMap.get(key);
}
has(key) {
return this.configMap.has(key);
}
};
function kvConfigToMap(config) {
return new Map(config.fields.map((f) => [f.key, f.value]));
}
function mapToKVConfig(map) {
return {
fields: Array.from(map.entries()).map(([key, value]) => ({ key, value }))
};
}
function collapseKVStackRaw(configs) {
const map = /* @__PURE__ */ new Map();
for (const config of configs) {
for (const { key, value } of config.fields) {
map.set(key, value);
}
}
return mapToKVConfig(map);
}
function deepEquals(a, b) {
if (a === b) {
return true;
}
if (typeof a !== "object" || typeof b !== "object") {
return false;
}
if (a === null || b === null) {
return false;
}
if (Array.isArray(a) !== Array.isArray(b)) {
return false;
}
if (Array.isArray(a)) {
if (a.length !== b?.length) {
return false;
}
for (let i = 0; i < a.length; i++) {
if (!deepEquals(a[i], b[i])) {
return false;
}
}
return true;
}
const aKeys = new Set(Object.keys(a));
const bKeys = new Set(Object.keys(b));
if (aKeys.size !== bKeys.size) {
return false;
}
for (const key of aKeys) {
if (!bKeys.has(key)) {
return false;
}
if (!deepEquals(a[key], b[key])) {
return false;
}
}
return true;
}
function quoteString(str, empty) {
if (str === void 0 || str === "") {
return empty ?? '""';
}
return JSON.stringify(str);
}
function quoteStringWithManualEscape(str, empty) {
return quoteString(str?.replace(/\\n/g, "\n"), empty);
}
var baseKVValueTypesLibraryBuilder = new KVFieldValueTypesLibraryBuilder({
/**
* Display name of the field.
*/
displayName: external_exports.string().optional(),
/**
* Hint about the field. Shown when hovering over the field.
*/
hint: external_exports.string().optional(),
/**
* A field can be marked as model centric when it loses its meaning when there is no model to
* reference.
*
* An example would be prompt template. There is no point to configure prompt template when there
* isn't a specific model.
*
* @experimental This field is experimental and may change in the future.
*/
modelCentric: external_exports.boolean().optional(),
/**
* A field can be marked as non-configurable when it is only used as a means to carry information.
* As a result, it will not be shown in the UI.
*
* An example would be context length for MLX, as you cannot change it.
*
* @experimental This field is experimental and may change in the future.
*/
nonConfigurable: external_exports.boolean().optional(),
/**
* A field can be marked as engineDoesNotSupport when when the engine running the model does not
* support the field.
*
* @experimental This field is experimental and may change in the future.
*/
engineDoesNotSupport: external_exports.boolean().optional(),
/**
* A field can be marked as machine dependent when its value is highly dependent on the machine
* that is being used. When exporting the config, one may decide to not include machine dependent
* fields by default.
*
* An example would be GPU offload settings.
*
* @experimental This field is experimental and may change in the future.
*/
machineDependent: external_exports.boolean().optional(),
warning: external_exports.string().optional(),
subtitle: external_exports.string().optional(),
isExperimental: external_exports.boolean().optional(),
dependencies: external_exports.array(kvConfigFieldDependencySchema).optional()
}).valueType("numeric", {
paramType: {
min: external_exports.number().optional(),
max: external_exports.number().optional(),
step: external_exports.number().optional(),
int: external_exports.boolean().optional(),
precision: external_exports.number().int().nonnegative().optional(),
slider: external_exports.object({
min: external_exports.number(),
max: external_exports.number(),
step: external_exports.number()
}).optional(),
shortHand: external_exports.string().optional()
},
schemaMaker: ({ min, max, int, precision }) => {
let schema = external_exports.number();
if (min !== void 0) {
schema = schema.min(min);
}
if (max !== void 0) {
schema = schema.max(max);
}
if (int) {
if (precision !== void 0) {
throw new Error("Cannot specify both int and precision.");
}
schema = schema.int();
}
return schema;
},
effectiveEquals: (a, b) => {
return a === b;
},
stringify: (value, { int, precision }) => {
if (int) {
return String(Math.round(value));
}
return value.toFixed(precision ?? 2);
}
}).valueType("string", {
paramType: {
minLength: external_exports.number().optional(),
maxLength: external_exports.number().optional(),
isParagraph: external_exports.boolean().optional(),
isProtected: external_exports.boolean().optional(),
/**
* If true, the string should match to a single token.
*/
isToken: external_exports.boolean().optional(),
placeholder: external_exports.string().optional()
},
schemaMaker: ({ minLength, maxLength }) => {
let schema = external_exports.string();
if (minLength !== void 0) {
schema = schema.min(minLength);
}
if (maxLength !== void 0) {
schema = schema.max(maxLength);
}
return schema;
},
effectiveEquals: (a, b) => {
return a === b;
},
stringify: (value, { isParagraph, isProtected }, { t, desiredLength }) => {
if (isProtected) {
return "********";
}
if (isParagraph) {
if (value === "") {
return t("config:customInputs.string.emptyParagraph", "<Empty>");
} else {
if (desiredLength === void 0 || value.length <= desiredLength) {
return value;
} else {
return value.slice(0, Math.floor(desiredLength / 2)) + " ... " + value.slice(-Math.ceil(desiredLength / 2));
}
}
} else {
const quoted = quoteString(value);
if (desiredLength === void 0 || quoted.length <= desiredLength) {
return quoted;
} else {
return quoted.slice(0, Math.floor(desiredLength / 2)) + "..." + quoted.slice(-Math.ceil(desiredLength / 2));
}
}
}
}).valueType("select", {
paramType: {
options: external_exports.array(external_exports.object({ value: external_exports.string().nonempty(), displayName: external_exports.string() }).or(external_exports.string())).refine((options) => {
const values = /* @__PURE__ */ new Set();
for (const option of options) {
const value = typeof option === "string" ? option : option.value;
if (values.has(value)) {
return false;
}
values.add(value);
}
return true;
}, {
message: "Duplicate values in options."
})
},
schemaMaker: ({ options }) => {
const allowedValues = new Set(options.map((option) => typeof option === "string" ? option : option.value));
return external_exports.string().refine((value) => allowedValues.has(value));
},
effectiveEquals: (a, b) => {
return a === b;
},
stringify: (value) => {
return value;
}
}).valueType("boolean", {
paramType: {},
schemaMaker: () => {
return external_exports.boolean();
},
effectiveEquals: (a, b) => {
return a === b;
},
stringify: (value) => {
return value ? "ON" : "OFF";
}
}).valueType("stringArray", {
paramType: {
maxNumItems: external_exports.number().optional(),
/**
* Whether to allow empty strings in the array. Default is false.
*/
allowEmptyStrings: external_exports.boolean().optional()
},
schemaMaker: ({ maxNumItems, allowEmptyStrings }) => {
let stringSchema = external_exports.string();
if (!allowEmptyStrings) {
stringSchema = stringSchema.min(1);
}
let schema = external_exports.array(stringSchema);
if (maxNumItems !== void 0) {
schema = schema.max(maxNumItems);
}
return schema;
},
effectiveEquals: (a, b) => {
return a.length === b.length && a.every((v, i) => v === b[i]);
},
stringify: (value, _typeParam, { t, desiredLength }) => {
const quoted = value.map((v) => quoteString(v));
if (quoted.length === 0) {
return t("config:customInputs.stringArray.empty", "<Empty>");
}
if (quoted.length <= 2 || desiredLength === void 0) {
return quoted.join(", ");
}
let currentLength = quoted[0].length + quoted[1].length + 6;
for (let i = 1; i < quoted.length - 1; i++) {
currentLength += quoted[i].length + 2;
if (currentLength >= desiredLength) {
return quoted.slice(0, i).join(", ") + ", ..." + quoted[quoted.length - 1];
}
}
return quoted.join(", ");
}
});
baseKVValueTypesLibraryBuilder.build();
var kvValueTypesLibrary = baseKVValueTypesLibraryBuilder.valueType("checkboxNumeric", {
paramType: {
min: external_exports.number().optional(),
max: external_exports.number().optional(),
step: external_exports.number().optional(),
int: external_exports.boolean().optional(),
uncheckedHint: external_exports.string().optional(),
precision: external_exports.number().int().nonnegative().optional(),
slider: external_exports.object({
min: external_exports.number(),
max: external_exports.number(),
step: external_exports.number()
}).optional()
},
schemaMaker: ({ min, max, int, precision }) => {
let numberSchema = external_exports.number();
if (min !== void 0) {
numberSchema = numberSchema.min(min);
}
if (max !== void 0) {
numberSchema = numberSchema.max(max);
}
if (int) {
if (precision !== void 0) {
throw new Error("Cannot specify both int and precision.");
}
numberSchema = numberSchema.int();
}
return external_exports.object({
checked: external_exports.boolean(),
value: numberSchema
});
},
effectiveEquals: (a, b) => {
if (a.checked !== b.checked) {
return false;
}
if (!a.checked) {
return true;
}
return a.value === b.value;
},
stringify: (value, { int, precision }, { t }) => {
if (!value.checked) {
return t("config:customInputs.checkboxNumeric.off", "OFF");
}
if (int) {
return String(Math.round(value.value));
}
return value.value.toFixed(precision ?? 2);
}
}).valueType("numericArray", {
paramType: {
min: external_exports.number().optional(),
max: external_exports.number().optional(),
int: external_exports.boolean().optional()
},
schemaMaker: ({ min, max, int }) => {
let numberSchema = external_exports.number();
if (min !== void 0) {
numberSchema = numberSchema.min(min);
}
if (max !== void 0) {
numberSchema = numberSchema.max(max);
}
if (int) {
numberSchema = numberSchema.int();
}
return external_exports.array(numberSchema);
},
effectiveEquals: (a, b) => {
return a.length === b.length && a.every((v, i) => v === b[i]);
},
stringify: (value, { int }) => {
return value.map((v) => int ? String(Math.round(v)) : String(v)).join(", ");
}
}).valueType("contextOverflowPolicy", {
paramType: {},
schemaMaker: () => {
return llmContextOverflowPolicySchema;
},
effectiveEquals: (a, b) => {
return a === b;
},
stringify: (value, _typeParam, { t }) => {
switch (value) {
case "stopAtLimit":
return t("config:customInputs.contextOverflowPolicy.stopAtLimit", "Stop At Limit");
case "truncateMiddle":
return t("config:customInputs.contextOverflowPolicy.truncateMiddle", "Truncate Middle");
case "rollingWindow":
return t("config:customInputs.contextOverflowPolicy.rollingWindow", "Rolling Window");
}
}
}).valueType("context", {
paramType: {},
schemaMaker: () => {
return external_exports.array(llmContextReferenceSchema);
},
effectiveEquals: (a, b) => {
return deepEquals(a, b);
},
stringify: (value) => {
return JSON.stringify(value, null, 2);
}
}).valueType("contextLength", {
paramType: {
max: external_exports.number().optional()
},
schemaMaker: () => {
return external_exports.number().int().positive();
},
effectiveEquals: (a, b) => {
return a === b;
},
stringify: (value, { max }) => {
if (max === void 0) {
return String(value);
}
return `${value}/${max}`;
}
}).valueType("modelIdentifier", {
paramType: {
domain: external_exports.array(modelDomainTypeSchema).optional()
},
schemaMaker: () => {
return external_exports.string();
},
effectiveEquals: (a, b) => {
return a === b;
},
stringify: (value) => {
return value;
}
}).valueType("llmPromptTemplate", {
paramType: {},
schemaMaker: () => {
return llmPromptTemplateSchema;
},
effectiveEquals: (a, b) => {
if (a.type !== b.type) {
return false;
}
if (a.stopStrings.length !== b.stopStrings.length) {
return false;
}
if (!a.stopStrings.every((v, i) => v === b.stopStrings[i])) {
return false;
}
switch (a.type) {
case "jinja":
return a.jinjaPromptTemplate?.template === b.jinjaPromptTemplate?.template;
case "manual":
return a.manualPromptTemplate?.beforeSystem === b.manualPromptTemplate?.beforeSystem && a.manualPromptTemplate?.afterSystem === b.manualPromptTemplate?.afterSystem && a.manualPromptTemplate?.beforeUser === b.manualPromptTemplate?.beforeUser && a.manualPromptTemplate?.afterUser === b.manualPromptTemplate?.afterUser && a.manualPromptTemplate?.beforeAssistant === b.manualPromptTemplate?.beforeAssistant && a.manualPromptTemplate?.afterAssistant === b.manualPromptTemplate?.afterAssistant;
default: {
const exhaustiveCheck = a.type;
throw new Error("Unknown template type: " + exhaustiveCheck);
}
}
},
stringify: (value, _typeParam, { t, desiredLength }) => {
switch (value.type) {
case "jinja": {
const lead = `${t("config:customInputs.llmPromptTemplate.type", "Type")}: ${t("config:customInputs.llmPromptTemplate.types.jinja/label", "Jinja")}
${t("config:customInputs.llmPromptTemplate.jinja.template/label", "Template")}: `;
if (desiredLength === void 0) {
return lead + value.jinjaPromptTemplate?.template;
}
const currentLength = lead.length;
const remainingLength = Math.min(100, desiredLength - currentLength);
const template = value.jinjaPromptTemplate?.template ?? "";
if (template.length <= remainingLength) {
return lead + template;
}
return lead + template.slice(0, Math.floor(remainingLength / 2)) + "..." + template.slice(-Math.ceil(remainingLength / 2));
}
case "manual": {
return `${t("config:customInputs.llmPromptTemplate.type", "Type")}: ${t("config:customInputs.llmPromptTemplate.types.manual/label", "Manual")}
${t("config:customInputs.llmPromptTemplate.manual.subfield.beforeSystem/label", "Before System")}: ${quoteStringWithManualEscape(value.manualPromptTemplate?.beforeSystem)}
${t("config:customInputs.llmPromptTemplate.manual.subfield.afterSystem/label", "After System")}: ${quoteStringWithManualEscape(value.manualPromptTemplate?.afterSystem)}
${t("config:customInputs.llmPromptTemplate.manual.subfield.beforeUser/label", "Before User")}: ${quoteStringWithManualEscape(value.manualPromptTemplate?.beforeUser)}
${t("config:customInputs.llmPromptTemplate.manual.subfield.afterUser/label", "After User")}: ${quoteStringWithManualEscape(value.manualPromptTemplate?.afterUser)}
${t("config:customInputs.llmPromptTemplate.manual.subfield.beforeAssistant/label", "Before Assistant")}: ${quoteStringWithManualEscape(value.manualPromptTemplate?.beforeAssistant)}
${t("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label", "After Assistant")}: ${quoteStringWithManualEscape(value.manualPromptTemplate?.afterAssistant)}`;
}
default: {
const exhaustiveCheck = value.type;
throw new Error("Unknown template type: " + exhaustiveCheck);
}
}
}
}).valueType("llmReasoningParsing", {
paramType: {},
schemaMaker: () => {
return llmReasoningParsingSchema;
},
effectiveEquals: (a, b) => {
return a.startString === b.startString && a.endString === b.endString;
},
stringify: (value) => {
return JSON.stringify(value, null, 2);
}
}).valueType("llamaStructuredOutput", {
paramType: {},
schemaMaker: () => {
return llmStructuredPredictionSettingSchema;
},
effectiveEquals: (a, b) => {
if (a.type === "json" && b.type === "json") {
return deepEquals(a, b);
} else if (a.type === "none" && b.type === "none") {
return true;
} else {
return false;
}
},
stringify: (value) => {
return JSON.stringify(value, null, 2);
}
}).valueType("speculativeDecodingDraftModel", {
paramType: {},
schemaMaker: () => {
return external_exports.string();
},
effectiveEquals: (a, b) => {
return a === b;
},
stringify: (value, _typeParam, { t }) => {
if (value === "") {
return t("config:customInputs.speculativeDecodingDraftModel.off", "OFF");
}
return value;
}
}).valueType("toolUse", {
paramType: {},
schemaMaker: () => {
return llmToolUseSettingSchema;
},
effectiveEquals: (a, b) => {
return deepEquals(a, b);
},
stringify: (value) => {
return JSON.stringify(value, null, 2);
}
}).valueType("toolNaming", {
paramType: {},
schemaMaker: () => {
return toolNamingSchema;
},
effectiveEquals: (a, b) => {
return a === b;
},
stringify: (value) => {
return value;
}
}).valueType("llamaAccelerationOffloadRatio", {
paramType: {
numLayers: external_exports.number().optional()
},
schemaMaker: () => {
return llmLlamaAccelerationOffloadRatioSchema;
},
effectiveEquals: (a, b) => {
const ratioA = a === "max" ? 1 : a === "off" ? 0 : a;
const ratioB = b === "max" ? 1 : b === "off" ? 0 : b;
return ratioA === ratioB;
},
stringify: (value, { numLayers }, { t }) => {
if (value === "max" || value === 1) {
const label = t("config:customInputs.llamaAccelerationOffloadRatio.max", "MAX");
if (numLayers !== 0) {
return `${label} (${numLayers})`;
}
return label;
}
if (value === "off" || value === 0) {
return t("config:customInputs.llamaAccelerationOffloadRatio.off", "OFF");
}
if (numLayers !== void 0) {
return String(Math.round(numLayers * value));
}
return (value * 100).toFixed(0) + "%";
}
}).valueType("llamaMirostatSampling", {
paramType: {},
schemaMaker: () => {
return llmLlamaMirostatSamplingConfigSchema;
},
effectiveEquals: (a, b) => {
return deepEquals(a, b);
},
stringify: (value) => {
return JSON.stringify(value, null, 2);
}
}).valueType("llamaLogitBias", {
paramType: {},
schemaMaker: () => {
return llmLlamaLogitBiasConfigSchema;
},
effectiveEquals: (a, b) => {
return deepEquals(a, b);
},
stringify: (value) => {
return JSON.stringify(value, null, 2);
}
}).valueType("llamaCacheQuantizationType", {
paramType: {},
schemaMaker: () => {
return external_exports.object({
checked: external_exports.boolean(),
value: llmLlamaCacheQuantizationTypeSchema
});
},
effectiveEquals: (a, b) => {
if (a.checked !== b.checked) {
return false;
}
if (!a.checked) {
return true;
}
return a.value === b.value;
},
stringify: (value, _typeParam, { t }) => {
if (!value.checked) {
return t("config:customInputs.llamaCacheQuantizationType.off", "OFF");
}
return value.value;
}
}).valueType("mlxKvCacheQuantizationType", {
paramType: {},
schemaMaker: () => {
return llmMlxKvCacheQuantizationSchema;
},
effectiveEquals: (a, b) => {
if (a.enabled !== b.enabled) {
return false;
}
if (!a.enabled) {
return true;
}
return a.bits === b.bits && a.groupSize === b.groupSize && a.quantizedStart === b.quantizedStart;
},
stringify: (value) => {
return JSON.stringify(value, null, 2);
}
}).valueType("retrievalChunkingMethod", {
paramType: {},
schemaMaker: () => {
return retrievalChunkingMethodSchema;
},
effectiveEquals: (a, b) => {
return deepEquals(a, b);
},
stringify: (value) => {
return JSON.stringify(value, null, 2);
}
}).valueType("envVars", {
paramType: {},
schemaMaker: () => {
return allowableEnvVarsSchema;
},
effectiveEquals: (a, b) => {
return deepEquals(a, b);
},
stringify: (value) => {
return JSON.stringify(value, null, 2);
}
}).valueType("gpuSplitConfig", {
paramType: {},
schemaMaker: () => {
return gpuSplitConfigSchema;
},
effectiveEquals: (a, b) => {
return deepEquals(a, b);
},
stringify: (value) => {
return JSON.stringify(value, null, 2);
}
}).build();
var globalConfigSchematics = new KVConfigSchematicsBuilder(kvValueTypesLibrary).extension("ext.virtualModel.customField").field("envVars", "envVars", {}, {}).scope("llm.prediction", (builder) => builder.field("temperature", "numeric", {
min: 0,
step: 0.01,
slider: { min: 0, max: 1, step: 0.01 },
precision: 2,
shortHand: "temp"
}, 0.8).field("contextOverflowPolicy", "contextOverflowPolicy", {}, "truncateMiddle").field("maxPredictedTokens", "checkboxNumeric", { min: 1, int: true }, { checked: false, value: 1e3 }).field("stopStrings", "stringArray", {}, []).field("toolCallStopStrings", "stringArray", {}, []).field("structured", "llamaStructuredOutput", {}, { type: "none" }).scope("speculativeDecoding", (builder2) => builder2.field("draftModel", "speculativeDecodingDraftModel", {
modelCentric: true
}, "").field("minDraftLengthToConsider", "numeric", {
modelCentric: true,
min: 0,
int: true,
slider: { min: 0, max: 10, step: 1 }
}, 0).field("numReuseTokens", "numeric", { modelCentric: true, min: 1, int: true }, 256).field("minContinueDraftingProbability", "numeric", {
modelCentric: true,
min: 0,
max: 1,
step: 0.01,
precision: 2,
slider: { min: 0, max: 1, step: 0.01 }
}, 0.75).field("maxTokensToDraft", "numeric", { modelCentric: true, min: 1, int: true, slider: { min: 10, max: 30, step: 1 } }, 16).field("numDraftTokensExact", "numeric", {
modelCentric: true,
min: 1,
int: true,
slider: { min: 1, max: 10, step: 1 }
}, 2)).field("tools", "toolUse", {}, { type: "none" }).field("toolNaming", "toolNaming", {}, "removeSpecial").field("promptTemplate", "llmPromptTemplate", { modelCentric: true }, {
type: "manual",
manualPromptTemplate: {
beforeSystem: "Instruct: ",
afterSystem: "\n",
beforeAssistant: "AI: ",
afterAssistant: "\n",
beforeUser: "Human: ",
afterUser: "\n"
},
stopStrings: []
}).field("systemPrompt", "string", { isParagraph: true }, "").field("seed", "checkboxNumeric", { int: true, min: -1, uncheckedHint: "config:seedUncheckedHint" }, { checked: false, value: -1 }).field("contextPrefill", "context", {}, []).field("topKSampling", "numeric", { min: -1, max: 500, int: true }, 40).field("repeatPenalty", "checkboxNumeric", { min: -1, step: 0.01 }, { checked: true, value: 1.1 }).field("minPSampling", "checkboxNumeric", { min: 0, max: 1, step: 0.01, precision: 2, slider: { min: 0, max: 1, step: 0.01 } }, { checked: true, value: 0.05 }).field("topPSampling", "checkboxNumeric", { min: 0, max: 1, step: 0.01, precision: 2, slider: { min: 0, max: 1, step: 0.01 } }, { checked: true, value: 0.95 }).field("logProbs", "checkboxNumeric", { min: 0, max: 100, int: true }, { checked: false, value: 0 }).scope("reasoning", (builder2) => builder2.field("parsing", "llmReasoningParsing", {}, {
enabled: true,
startString: "<think>",
endString: "</think>"
})).scope("llama", (builder2) => builder2.field("cpuThreads", "numeric", { min: 1, int: true }, 4).field("frequencyPenalty", "checkboxNumeric", { precision: 2 }, { checked: false, value: 0 }).field("xtcProbability", "checkboxNumeric", { min: 0, max: 1, step: 0.01, precision: 2, slider: { min: 0, max: 1, step: 0.01 } }, { checked: false, value: 0.5 }).field("xtcThreshold", "checkboxNumeric", { min: 0, max: 1, step: 0.01, precision: 2, slider: { min: 0, max: 0.5, step: 0.01 } }, { checked: false, value: 0.1 }).field("presencePenalty", "checkboxNumeric", { precision: 2 }, { checked: false, value: 0 }).field("mirostatSampling", "llamaMirostatSampling", {}, {
// Disabled by default
version: 0,
learningRate: 0.1,
targetEntropy: 5
}).field("tailFreeSampling", "checkboxNumeric", { min: 0, max: 1, step: 0.01, precision: 2, slider: { min: 0, max: 1, step: 0.01 } }, { checked: false, value: 0.95 }).field("locallyTypicalSampling", "checkboxNumeric", { min: 0, max: 1, step: 0.01, precision: 2, slider: { min: 0, max: 1, step: 0.01 } }, { checked: false, value: 0.9 }).field("logitBias", "llamaLogitBias", {}, []))).scope("llm.load", (builder) => builder.field("contextLength", "contextLength", {
machineDependent: true
}, 2048).field("numExperts", "numeric", { min: 0, int: true }, 0).field("seed", "checkboxNumeric", { int: true, min: -1, uncheckedHint: "config:seedUncheckedHint" }, { checked: false, value: -1 }).field("offloadKVCacheToGpu", "boolean", {}, true).field("numCpuExpertLayersRatio", "llamaAccelerationOffloadRatio", { machineDependent: true, isExperimental: true }, "off").scope("llama", (builder2) => builder2.scope("acceleration", (builder3) => builder3.field("offloadRatio", "llamaAccelerationOffloadRatio", { machineDependent: true }, "max")).field("cpuThreadPoolSize", "numeric", { min: 1, machineDependent: true }, 4).field("evalBatchSize", "numeric", { min: 1, int: true }, 512).field("flashAttention", "boolean", { isExperimental: true, warning: "config:flashAttentionWarning" }, false).field("ropeFrequencyBase", "checkboxNumeric", { min: 0, uncheckedHint: "config:ropeFrequencyBaseUncheckedHint" }, { checked: false, value: 0 }).field("ropeFrequencyScale", "checkboxNumeric", { min: 0, uncheckedHint: "config:ropeFrequencyScaleUncheckedHint" }, { checked: false, value: 0 }).field("keepModelInMemory", "boolean", {}, true).field("useFp16ForKVCache", "boolean", {}, true).field("tryMmap", "boolean", {}, true).field("kCacheQuantizationType", "llamaCacheQuantizationType", { isExperimental: true }, { checked: false, value: "f16" }).field("vCacheQuantizationType", "llamaCacheQuantizationType", { isExperimental: true, warning: "config:llamaKvCacheQuantizationWarning" }, { checked: false, value: "f16" })).scope("mlx", (builder2) => builder2.field("kvCacheQuantization", "mlxKvCacheQuantizationType", { isExperimental: true }, { enabled: false, bits: 8, groupSize: 64, quantizedStart: 5e3 }))).scope("load", (builder) => builder.field("gpuSplitConfig", "gpuSplitConfig", {}, defaultGPUSplitConfig).field("gpuStrictVramCap", "boolean", {}, false)).scope("embedding.load", (builder) => builder.field("contextLength", "contextLength", { machineDependent: true }, 2048).field("seed", "checkboxNumeric", { int: true, min: -1, uncheckedHint: "config:seedUncheckedHint" }, { checked: false, value: -1 }).scope("llama", (builder2) => builder2.scope("acceleration", (builder3) => builder3.field("offloadRatio", "llamaAccelerationOffloadRatio", { machineDependent: true }, "max")).field("evalBatchSize", "numeric", { min: 1, int: true }, 512).field("ropeFrequencyBase", "checkboxNumeric", { min: 0, uncheckedHint: "config:ropeFrequencyBaseUncheckedHint" }, { checked: false, value: 0 }).field("ropeFrequencyScale", "checkboxNumeric", { min: 0, uncheckedHint: "config:ropeFrequencyScaleUncheckedHint" }, { checked: false, value: 0 }).field("keepModelInMemory", "boolean", {}, true).field("tryMmap", "boolean", {}, true))).scope("retrieval", (builder) => builder.field("databaseFile", "string", { machineDependent: true }, "").field("chunkingMethod", "retrievalChunkingMethod", {}, {
type: "recursive-v1",
chunkSize: 512,
chunkOverlap: 100
}).field("limit", "numeric", { min: 1, int: true }, 5).field("embeddingModel", "modelIdentifier", { domain: ["embedding"] }, "")).build();
var llmPredictionConfigSchematics = globalConfigSchematics.scoped("llm.prediction");
var llmSharedPredictionConfigSchematics = llmPredictionConfigSchematics.sliced("temperature", "maxPredictedTokens", "promptTemplate", "systemPrompt", "seed", "contextPrefill", "tools", "toolNaming", "reasoning.*");
llmSharedPredictionConfigSchematics.union(llmPredictionConfigSchematics.sliced("llama.*", "contextOverflowPolicy", "stopStrings", "toolCallStopStrings", "structured", "topKSampling", "repeatPenalty", "minPSampling", "topPSampling", "logProbs", "speculativeDecoding.draftModel", "speculativeDecoding.minContinueDraftingProbability", "speculativeDecoding.minDraftLengthToConsider", "speculativeDecoding.maxTokensToDraft", "speculativeDecoding.numReuseTokens"));
llmSharedPredictionConfigSchematics.union(llmPredictionConfigSchematics.sliced("mlx.*", "contextOverflowPolicy", "stopStrings", "toolCallStopStrings", "structured", "repeatPenalty", "minPSampling", "topPSampling", "topKSampling", "speculativeDecoding.draftModel", "speculativeDecoding.numDraftTokensExact"));
llmSharedPredictionConfigSchematics.union(llmPredictionConfigSchematics.sliced("transformers.*"));
llmSharedPredictionConfigSchematics.union(llmPredictionConfigSchematics.sliced("onnx.*", "repeatPenalty", "topPSampling", "topKSampling"));
var llmLoadSchematics = globalConfigSchematics.scoped("llm.load").union(globalConfigSchematics.sliced("envVars"));
var llmSharedLoadConfigSchematics = llmLoadSchematics.sliced("contextLength", "seed", "envVars");
var llamaLoadConfigSchematics = globalConfigSchematics.sliced("llama.load.*", "load.*");
var llmLlamaLoadConfigSchematics = llmSharedLoadConfigSchematics.union(llmLoadSchematics.sliced("llama.*", "load.*", "offloadKVCacheToGpu")).union(llamaLoadConfigSchematics);
llmSharedLoadConfigSchematics.union(llmLoadSchematics.sliced("mlx.*"));
llmSharedLoadConfigSchematics.union(llmLoadSchematics.sliced("transformers.*"));
llmSharedLoadConfigSchematics.union(llmLoadSchematics.sliced("onnx.*"));
var llmLlamaMoeAdditionalLoadConfigSchematics = llmLoadSchematics.sliced("numExperts", "numCpuExpertLayersRatio");
var llmLlamaMoeLoadConfigSchematics = llmLlamaLoadConfigSchematics.union(llmLlamaMoeAdditionalLoadConfigSchematics);
var embeddingLoadSchematics = globalConfigSchematics.scoped("embedding.load").union(globalConfigSchematics.sliced("load.*"));
var embeddingSharedLoadConfigSchematics = embeddingLoadSchematics.sliced("contextLength", "seed");
var retrievalSchematics = globalConfigSchematics.scoped("retrieval");
var embeddingLlamaLoadConfigSchematics = embeddingSharedLoadConfigSchematics.union(embeddingLoadSchematics.sliced("llama.*")).union(llamaLoadConfigSchematics);
new KVConfigSchematicsBuilder(kvValueTypesLibrary).build();
function createConfigSchematics() {
return new KVConfigSchematicsBuilder(kvValueTypesLibrary);
}
var lib = {};
var helpers = {};
var hasRequiredHelpers;
function requireHelpers() {
if (hasRequiredHelpers) return helpers;
hasRequiredHelpers = 1;
var ValidationError2 = helpers.ValidationError = function ValidationError3(message, instance, schema, path4, name, argument) {
if (Array.isArray(path4)) {
this.path = path4;
this.property = path4.reduce(function(sum, item) {
return sum + makeSuffix(item);
}, "instance");
} else if (path4 !== void 0) {
this.property = path4;
}
if (message) {
this.message = message;
}
if (schema) {
var id = schema.$id || schema.id;
this.schema = id || schema;
}
if (instance !== void 0) {
this.instance = instance;
}
this.name = name;
this.argument = argument;
this.stack = this.toString();
};
ValidationError2.prototype.toString = function toString() {
return this.property + " " + this.message;
};
var ValidatorResult = helpers.ValidatorResult = function ValidatorResult2(instance, schema, options, ctx) {
this.instance = instance;
this.schema = schema;
this.options = options;
this.path = ctx.path;
this.propertyPath = ctx.propertyPath;
this.errors = [];
this.throwError = options && options.throwError;
this.throwFirst = options && options.throwFirst;
this.throwAll = options && options.throwAll;
this.disableFormat = options && options.disableFormat === true;
};
ValidatorResult.prototype.addError = function addError(detail) {
var err;
if (typeof detail == "string") {
err = new ValidationError2(detail, this.instance, this.schema, this.path);
} else {
if (!detail) throw new Error("Missing error detail");
if (!detail.message) throw new Error("Missing error message");
if (!detail.name) throw new Error("Missing validator type");
err = new ValidationError2(detail.message, this.instance, this.schema, this.path, detail.name, detail.argument);
}
this.errors.push(err);
if (this.throwFirst) {
throw new ValidatorResultError(this);
} else if (this.throwError) {
throw err;
}
return err;
};
ValidatorResult.prototype.importErrors = function importErrors(res) {
if (typeof res == "string" || res && res.validatorType) {
this.addError(res);
} else if (res && res.errors) {
this.errors = this.errors.concat(res.errors);
}
};
function stringizer(v, i) {
return i + ": " + v.toString() + "\n";
}
ValidatorResult.prototype.toString = function toString(res) {
return this.errors.map(stringizer).join("");
};
Object.defineProperty(ValidatorResult.prototype, "valid", { get: function() {
return !this.errors.length;
} });
helpers.ValidatorResultError = ValidatorResultError;
function ValidatorResultError(result) {
if (typeof Error.captureStackTrace === "function") {
Error.captureStackTrace(this, ValidatorResultError);
}
this.instance = result.instance;
this.schema = result.schema;
this.options = result.options;
this.errors = result.errors;
}
ValidatorResultError.prototype = new Error();
ValidatorResultError.prototype.constructor = ValidatorResultError;
ValidatorResultError.prototype.name = "Validation Error";
var SchemaError = helpers.SchemaError = function SchemaError2(msg, schema) {
this.message = msg;
this.schema = schema;
Error.call(this, msg);
if (typeof Error.captureStackTrace === "function") {
Error.captureStackTrace(this, SchemaError2);
}
};
SchemaError.prototype = Object.create(
Error.prototype,
{
constructor: { value: SchemaError, enumerable: false },
name: { value: "SchemaError", enumerable: false }
}
);
var SchemaContext = helpers.SchemaContext = function SchemaContext2(schema, options, path4, base, schemas) {
this.schema = schema;
this.options = options;
if (Array.isArray(path4)) {
this.path = path4;
this.propertyPath = path4.reduce(function(sum, item) {
return sum + makeSuffix(item);
}, "instance");
} else {
this.propertyPath = path4;
}
this.base = base;
this.schemas = schemas;
};
SchemaContext.prototype.resolve = function resolve(target) {
return (() => resolveUrl(this.base, target))();
};
SchemaContext.prototype.makeChild = function makeChild(schema, propertyName) {
var path4 = propertyName === void 0 ? this.path : this.path.concat([propertyName]);
var id = schema.$id || schema.id;
let base = (() => resolveUrl(this.base, id || ""))();
var ctx = new SchemaContext(schema, this.options, path4, base, Object.create(this.schemas));
if (id && !ctx.schemas[base]) {
ctx.schemas[base] = schema;
}
return ctx;
};
var FORMAT_REGEXPS = helpers.FORMAT_REGEXPS = {
// 7.3.1. Dates, Times, and Duration
"date-time": /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-(3[01]|0[1-9]|[12][0-9])[tT ](2[0-4]|[01][0-9]):([0-5][0-9]):(60|[0-5][0-9])(\.\d+)?([zZ]|[+-]([0-5][0-9]):(60|[0-5][0-9]))$/,
"date": /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-(3[01]|0[1-9]|[12][0-9])$/,
"time": /^(2[0-4]|[01][0-9]):([0-5][0-9]):(60|[0-5][0-9])$/,
"duration": /P(T\d+(H(\d+M(\d+S)?)?|M(\d+S)?|S)|\d+(D|M(\d+D)?|Y(\d+M(\d+D)?)?)(T\d+(H(\d+M(\d+S)?)?|M(\d+S)?|S))?|\d+W)/i,
// 7.3.2. Email Addresses
// TODO: fix the email production
"email": /^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/,
"idn-email": /^("(?:[!#-\[\]-\u{10FFFF}]|\\[\t -\u{10FFFF}])*"|[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}](?:\.?[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}])*)@([!#-'*+\-/-9=?A-Z\^-\u{10FFFF}](?:\.?[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}])*|\[[!-Z\^-\u{10FFFF}]*\])$/u,
// 7.3.3. Hostnames
// 7.3.4. IP Addresses
"ip-address": /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
// FIXME whitespace is invalid
"ipv6": /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/,
// 7.3.5. Resource Identifiers
// TODO: A more accurate regular expression for "uri" goes:
// [A-Za-z][+\-.0-9A-Za-z]*:((/(/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?)?)?#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|(/(/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~])|/?%[0-9A-Fa-f]{2}|[!$&-.0-;=?-Z_a-z~])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*(#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*)?|/(/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+(:\d*)?|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?:\d*|\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)?)?
"uri": /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/,
"uri-reference": /^(((([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|([A-Za-z][+\-.0-9A-Za-z]*:?)?)|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|(\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?)?))#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|(([A-Za-z][+\-.0-9A-Za-z]*)?%[0-9A-Fa-f]{2}|[!$&-.0-9;=@_~]|[A-Za-z][+\-.0-9A-Za-z]*[!$&-*,;=@_~])(%[0-9A-Fa-f]{2}|[!$&-.0-9;=@-Z_a-z~])*((([/?](%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*)?#|[/?])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*)?|([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+(:\d*)?|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?:\d*|\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)?|[A-Za-z][+\-.0-9A-Za-z]*:?)?$/,
"iri": /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/,
"iri-reference": /^(((([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~-\u{10FFFF}]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|([A-Za-z][+\-.0-9A-Za-z]*:?)?)|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|(\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?)?))#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|(([A-Za-z][+\-.0-9A-Za-z]*)?%[0-9A-Fa-f]{2}|[!$&-.0-9;=@_~-\u{10FFFF}]|[A-Za-z][+\-.0-9A-Za-z]*[!$&-*,;=@_~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-.0-9;=@-Z_a-z~-\u{10FFFF}])*((([/?](%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*)?#|[/?])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*)?|([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~-\u{10FFFF}]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+(:\d*)?|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?:\d*|\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)?|[A-Za-z][+\-.0-9A-Za-z]*:?)?$/u,
"uuid": /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i,
// 7.3.6. uri-template
"uri-template": /(%[0-9a-f]{2}|[!#$&(-;=?@\[\]_a-z~]|\{[!#&+,./;=?@|]?(%[0-9a-f]{2}|[0-9_a-z])(\.?(%[0-9a-f]{2}|[0-9_a-z]))*(:[1-9]\d{0,3}|\*)?(,(%[0-9a-f]{2}|[0-9_a-z])(\.?(%[0-9a-f]{2}|[0-9_a-z]))*(:[1-9]\d{0,3}|\*)?)*\})*/iu,
// 7.3.7. JSON Pointers
"json-pointer": /^(\/([\x00-\x2e0-@\[-}\x7f]|~[01])*)*$/iu,
"relative-json-pointer": /^\d+(#|(\/([\x00-\x2e0-@\[-}\x7f]|~[01])*)*)$/iu,
// hostname regex from: http://stackoverflow.com/a/1420225/5628
"hostname": /^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$/,
"host-name": /^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$/,
"utc-millisec": function(input) {
return typeof input === "string" && parseFloat(input) === parseInt(input, 10) && !isNaN(input);
},
// 7.3.8. regex
"regex": function(input) {
var result = true;
try {
new RegExp(input);
} catch (e) {
result = false;
}
return result;
},
// Other definitions
// "style" was removed from JSON Schema in draft-4 and is deprecated
"style": /[\r\n\t ]*[^\r\n\t ][^:]*:[\r\n\t ]*[^\r\n\t ;]*[\r\n\t ]*;?/,
// "color" was removed from JSON Schema in draft-4 and is deprecated
"color": /^(#?([0-9A-Fa-f]{3}){1,2}\b|aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow|(rgb\(\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*\))|(rgb\(\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*\)))$/,
"phone": /^\+(?:[0-9] ?){6,14}[0-9]$/,
"alpha": /^[a-zA-Z]+$/,
"alphanumeric": /^[a-zA-Z0-9]+$/
};
FORMAT_REGEXPS.regexp = FORMAT_REGEXPS.regex;
FORMAT_REGEXPS.pattern = FORMAT_REGEXPS.regex;
FORMAT_REGEXPS.ipv4 = FORMAT_REGEXPS["ip-address"];
helpers.isFormat = function isFormat(input, format, validator2) {
if (typeof input === "string" && FORMAT_REGEXPS[format] !== void 0) {
if (FORMAT_REGEXPS[format] instanceof RegExp) {
return FORMAT_REGEXPS[format].test(input);
}
if (typeof FORMAT_REGEXPS[format] === "function") {
return FORMAT_REGEXPS[format](input);
}
} else if (validator2 && validator2.customFormats && typeof validator2.customFormats[format] === "function") {
return validator2.customFormats[format](input);
}
return true;
};
var makeSuffix = helpers.makeSuffix = function makeSuffix2(key) {
key = key.toString();
if (!key.match(/[.\s\[\]]/) && !key.match(/^[\d]/)) {
return "." + key;
}
if (key.match(/^\d+$/)) {
return "[" + key + "]";
}
return "[" + JSON.stringify(key) + "]";
};
helpers.deepCompareStrict = function deepCompareStrict(a, b) {
if (typeof a !== typeof b) {
return false;
}
if (Array.isArray(a)) {
if (!Array.isArray(b)) {
return false;
}
if (a.length !== b.length) {
return false;
}
return a.every(function(v, i) {
return deepCompareStrict(a[i], b[i]);
});
}
if (typeof a === "object") {
if (!a || !b) {
return a === b;
}
var aKeys = Object.keys(a);
var bKeys = Object.keys(b);
if (aKeys.length !== bKeys.length) {
return false;
}
return aKeys.every(function(v) {
return deepCompareStrict(a[v], b[v]);
});
}
return a === b;
};
function deepMerger(target, dst, e, i) {
if (typeof e === "object") {
dst[i] = deepMerge(target[i], e);
} else {
if (target.indexOf(e) === -1) {
dst.push(e);
}
}
}
function copyist(src, dst, key) {
dst[key] = src[key];
}
function copyistWithDeepMerge(target, src, dst, key) {
if (typeof src[key] !== "object" || !src[key]) {
dst[key] = src[key];
} else {
if (!target[key]) {
dst[key] = src[key];
} else {
dst[key] = deepMerge(target[key], src[key]);
}
}
}
function deepMerge(target, src) {
var array = Array.isArray(src);
var dst = array && [] || {};
if (array) {
target = target || [];
dst = dst.concat(target);
src.forEach(deepMerger.bind(null, target, dst));
} else {
if (target && typeof target === "object") {
Object.keys(target).forEach(copyist.bind(null, target, dst));
}
Object.keys(src).forEach(copyistWithDeepMerge.bind(null, target, src, dst));
}
return dst;
}
helpers.deepMerge = deepMerge;
helpers.objectGetPath = function objectGetPath(o, s) {
var parts = s.split("/").slice(1);
var k;
while (typeof (k = parts.shift()) == "string") {
var n = decodeURIComponent(k.replace(/~0/, "~").replace(/~1/g, "/"));
if (!(n in o)) return;
o = o[n];
}
return o;
};
function pathEncoder(v) {
return "/" + encodeURIComponent(v).replace(/~/g, "%7E");
}
helpers.encodePath = function encodePointer(a) {
return a.map(pathEncoder).join("");
};
helpers.getDecimalPlaces = function getDecimalPlaces(number) {
var decimalPlaces = 0;
if (isNaN(number)) return decimalPlaces;
if (typeof number !== "number") {
number = Number(number);
}
var parts = number.toString().split("e");
if (parts.length === 2) {
if (parts[1][0] !== "-") {
return decimalPlaces;
} else {
decimalPlaces = Number(parts[1].slice(1));
}
}
var decimalParts = parts[0].split(".");
if (decimalParts.length === 2) {
decimalPlaces += decimalParts[1].length;
}
return decimalPlaces;
};
helpers.isSchema = function isSchema(val) {
return typeof val === "object" && val || typeof val === "boolean";
};
var resolveUrl = helpers.resolveUrl = function resolveUrl2(from, to) {
const resolvedUrl = new URL(to, new URL(from, "resolve://"));
if (resolvedUrl.protocol === "resolve:") {
const { pathname, search, hash } = resolvedUrl;
return pathname + search + hash;
}
return resolvedUrl.toString();
};
return helpers;
}
var attribute_1;
var hasRequiredAttribute;
function requireAttribute() {
if (hasRequiredAttribute) return attribute_1;
hasRequiredAttribute = 1;
var helpers2 = requireHelpers();
var ValidatorResult = helpers2.ValidatorResult;
var SchemaError = helpers2.SchemaError;
var attribute = {};
attribute.ignoreProperties = {
// informative properties
"id": true,
"default": true,
"description": true,
"title": true,
// arguments to other properties
"additionalItems": true,
"then": true,
"else": true,
// special-handled properties
"$schema": true,
"$ref": true,
"extends": true
};
var validators = attribute.validators = {};
validators.type = function validateType(instance, schema, options, ctx) {
if (instance === void 0) {
return null;
}
var result = new ValidatorResult(instance, schema, options, ctx);
var types = Array.isArray(schema.type) ? schema.type : [schema.type];
if (!types.some(this.testType.bind(this, instance, schema, options, ctx))) {
var list = types.map(function(v) {
if (!v) return;
var id = v.$id || v.id;
return id ? "<" + id + ">" : v + "";
});
result.addError({
name: "type",
argument: list,
message: "is not of a type(s) " + list
});
}
return result;
};
function testSchemaNoThrow(instance, options, ctx, callback, schema) {
var throwError = options.throwError;
var throwAll = options.throwAll;
options.throwError = false;
options.throwAll = false;
var res = this.validateSchema(instance, schema, options, ctx);
options.throwError = throwError;
options.throwAll = throwAll;
if (!res.valid && callback instanceof Function) {
callback(res);
}
return res.valid;
}
validators.anyOf = function validateAnyOf(instance, schema, options, ctx) {
if (instance === void 0) {
return null;
}
var result = new ValidatorResult(instance, schema, options, ctx);
var inner = new ValidatorResult(instance, schema, options, ctx);
if (!Array.isArray(schema.anyOf)) {
throw new SchemaError("anyOf must be an array");
}
if (!schema.anyOf.some(
testSchemaNoThrow.bind(
this,
instance,
options,
ctx,
function(res) {
inner.importErrors(res);
}
)
)) {
var list = schema.anyOf.map(function(v, i) {
var id = v.$id || v.id;
if (id) return "<" + id + ">";
return v.title && JSON.stringify(v.title) || v["$ref"] && "<" + v["$ref"] + ">" || "[subschema " + i + "]";
});
if (options.nestedErrors) {
result.importErrors(inner);
}
result.addError({
name: "anyOf",
argument: list,
message: "is not any of " + list.join(",")
});
}
return result;
};
validators.allOf = function validateAllOf(instance, schema, options, ctx) {
if (instance === void 0) {
return null;
}
if (!Array.isArray(schema.allOf)) {
throw new SchemaError("allOf must be an array");
}
var result = new ValidatorResult(instance, schema, options, ctx);
var self = this;
schema.allOf.forEach(function(v, i) {
var valid = self.validateSchema(instance, v, options, ctx);
if (!valid.valid) {
var id = v.$id || v.id;
var msg = id || v.title && JSON.stringify(v.title) || v["$ref"] && "<" + v["$ref"] + ">" || "[subschema " + i + "]";
result.addError({
name: "allOf",
argument: { id: msg, length: valid.errors.length, valid },
message: "does not match allOf schema " + msg + " with " + valid.errors.length + " error[s]:"
});
result.importErrors(valid);
}
});
return result;
};
validators.oneOf = function validateOneOf(instance, schema, options, ctx) {
if (instance === void 0) {
return null;
}
if (!Array.isArray(schema.oneOf)) {
throw new SchemaError("oneOf must be an array");
}
var result = new ValidatorResult(instance, schema, options, ctx);
var inner = new ValidatorResult(instance, schema, options, ctx);
var count = schema.oneOf.filter(
testSchemaNoThrow.bind(
this,
instance,
options,
ctx,
function(res) {
inner.importErrors(res);
}
)
).length;
var list = schema.oneOf.map(function(v, i) {
var id = v.$id || v.id;
return id || v.title && JSON.stringify(v.title) || v["$ref"] && "<" + v["$ref"] + ">" || "[subschema " + i + "]";
});
if (count !== 1) {
if (options.nestedErrors) {
result.importErrors(inner);
}
result.addError({
name: "oneOf",
argument: list,
message: "is not exactly one from " + list.join(",")
});
}
return result;
};
validators.if = function validateIf(instance, schema, options, ctx) {
if (instance === void 0) return null;
if (!helpers2.isSchema(schema.if)) throw new Error('Expected "if" keyword to be a schema');
var ifValid = testSchemaNoThrow.call(this, instance, options, ctx, null, schema.if);
var result = new ValidatorResult(instance, schema, options, ctx);
var res;
if (ifValid) {
if (schema.then === void 0) return;
if (!helpers2.isSchema(schema.then)) throw new Error('Expected "then" keyword to be a schema');
res = this.validateSchema(instance, schema.then, options, ctx.makeChild(schema.then));
result.importErrors(res);
} else {
if (schema.else === void 0) return;
if (!helpers2.isSchema(schema.else)) throw new Error('Expected "else" keyword to be a schema');
res = this.validateSchema(instance, schema.else, options, ctx.makeChild(schema.else));
result.importErrors(res);
}
return result;
};
function getEnumerableProperty(object, key) {
if (Object.hasOwnProperty.call(object, key)) return object[key];
if (!(key in object)) return;
while (object = Object.getPrototypeOf(object)) {
if (Object.propertyIsEnumerable.call(object, key)) return object[key];
}
}
validators.propertyNames = function validatePropertyNames(instance, schema, options, ctx) {
if (!this.types.object(instance)) return;
var result = new ValidatorResult(instance, schema, options, ctx);
var subschema = schema.propertyNames !== void 0 ? schema.propertyNames : {};
if (!helpers2.isSchema(subschema)) throw new SchemaError('Expected "propertyNames" to be a schema (object or boolean)');
for (var property in instance) {
if (getEnumerableProperty(instance, property) !== void 0) {
var res = this.validateSchema(property, subschema, options, ctx.makeChild(subschema));
result.importErrors(res);
}
}
return result;
};
validators.properties = function validateProperties(instance, schema, options, ctx) {
if (!this.types.object(instance)) return;
var result = new ValidatorResult(instance, schema, options, ctx);
var properties = schema.properties || {};
for (var property in properties) {
var subschema = properties[property];
if (subschema === void 0) {
continue;
} else if (subschema === null) {
throw new SchemaError('Unexpected null, expected schema in "properties"');
}
if (typeof options.preValidateProperty == "function") {
options.preValidateProperty(instance, property, subschema, options, ctx);
}
var prop = getEnumerableProperty(instance, property);
var res = this.validateSchema(prop, subschema, options, ctx.makeChild(subschema, property));
if (res.instance !== result.instance[property]) result.instance[property] = res.instance;
result.importErrors(res);
}
return result;
};
function testAdditionalProperty(instance, schema, options, ctx, property, result) {
if (!this.types.object(instance)) return;
if (schema.properties && schema.properties[property] !== void 0) {
return;
}
if (schema.additionalProperties === false) {
result.addError({
name: "additionalProperties",
argument: property,
message: "is not allowed to have the additional property " + JSON.stringify(property)
});
} else {
var additionalProperties = schema.additionalProperties || {};
if (typeof options.preValidateProperty == "function") {
options.preValidateProperty(instance, property, additionalProperties, options, ctx);
}
var res = this.validateSchema(instance[property], additionalProperties, options, ctx.makeChild(additionalProperties, property));
if (res.instance !== result.instance[property]) result.instance[property] = res.instance;
result.importErrors(res);
}
}
validators.patternProperties = function validatePatternProperties(instance, schema, options, ctx) {
if (!this.types.object(instance)) return;
var result = new ValidatorResult(instance, schema, options, ctx);
var patternProperties = schema.patternProperties || {};
for (var property in instance) {
var test = true;
for (var pattern in patternProperties) {
var subschema = patternProperties[pattern];
if (subschema === void 0) {
continue;
} else if (subschema === null) {
throw new SchemaError('Unexpected null, expected schema in "patternProperties"');
}
try {
var regexp = new RegExp(pattern, "u");
} catch (_e) {
regexp = new RegExp(pattern);
}
if (!regexp.test(property)) {
continue;
}
test = false;
if (typeof options.preValidateProperty == "function") {
options.preValidateProperty(instance, property, subschema, options, ctx);
}
var res = this.validateSchema(instance[property], subschema, options, ctx.makeChild(subschema, property));
if (res.instance !== result.instance[property]) result.instance[property] = res.instance;
result.importErrors(res);
}
if (test) {
testAdditionalProperty.call(this, instance, schema, options, ctx, property, result);
}
}
return result;
};
validators.additionalProperties = function validateAdditionalProperties(instance, schema, options, ctx) {
if (!this.types.object(instance)) return;
if (schema.patternProperties) {
return null;
}
var result = new ValidatorResult(instance, schema, options, ctx);
for (var property in instance) {
testAdditionalProperty.call(this, instance, schema, options, ctx, property, result);
}
return result;
};
validators.minProperties = function validateMinProperties(instance, schema, options, ctx) {
if (!this.types.object(instance)) return;
var result = new ValidatorResult(instance, schema, options, ctx);
var keys = Object.keys(instance);
if (!(keys.length >= schema.minProperties)) {
result.addError({
name: "minProperties",
argument: schema.minProperties,
message: "does not meet minimum property length of " + schema.minProperties
});
}
return result;
};
validators.maxProperties = function validateMaxProperties(instance, schema, options, ctx) {
if (!this.types.object(instance)) return;
var result = new ValidatorResult(instance, schema, options, ctx);
var keys = Object.keys(instance);
if (!(keys.length <= schema.maxProperties)) {
result.addError({
name: "maxProperties",
argument: schema.maxProperties,
message: "does not meet maximum property length of " + schema.maxProperties
});
}
return result;
};
validators.items = function validateItems(instance, schema, options, ctx) {
var self = this;
if (!this.types.array(instance)) return;
if (schema.items === void 0) return;
var result = new ValidatorResult(instance, schema, options, ctx);
instance.every(function(value, i) {
if (Array.isArray(schema.items)) {
var items = schema.items[i] === void 0 ? schema.additionalItems : schema.items[i];
} else {
var items = schema.items;
}
if (items === void 0) {
return true;
}
if (items === false) {
result.addError({
name: "items",
message: "additionalItems not permitted"
});
return false;
}
var res = self.validateSchema(value, items, options, ctx.makeChild(items, i));
if (res.instance !== result.instance[i]) result.instance[i] = res.instance;
result.importErrors(res);
return true;
});
return result;
};
validators.contains = function validateContains(instance, schema, options, ctx) {
var self = this;
if (!this.types.array(instance)) return;
if (schema.contains === void 0) return;
if (!helpers2.isSchema(schema.contains)) throw new Error('Expected "contains" keyword to be a schema');
var result = new ValidatorResult(instance, schema, options, ctx);
var count = instance.some(function(value, i) {
var res = self.validateSchema(value, schema.contains, options, ctx.makeChild(schema.contains, i));
return res.errors.length === 0;
});
if (count === false) {
result.addError({
name: "contains",
argument: schema.contains,
message: "must contain an item matching given schema"
});
}
return result;
};
validators.minimum = function validateMinimum(instance, schema, options, ctx) {
if (!this.types.number(instance)) return;
var result = new ValidatorResult(instance, schema, options, ctx);
if (schema.exclusiveMinimum && schema.exclusiveMinimum === true) {
if (!(instance > schema.minimum)) {
result.addError({
name: "minimum",
argument: schema.minimum,
message: "must be greater than " + schema.minimum
});
}
} else {
if (!(instance >= schema.minimum)) {
result.addError({
name: "minimum",
argument: schema.minimum,
message: "must be greater than or equal to " + schema.minimum
});
}
}
return result;
};
validators.maximum = function validateMaximum(instance, schema, options, ctx) {
if (!this.types.number(instance)) return;
var result = new ValidatorResult(instance, schema, options, ctx);
if (schema.exclusiveMaximum && schema.exclusiveMaximum === true) {
if (!(instance < schema.maximum)) {
result.addError({
name: "maximum",
argument: schema.maximum,
message: "must be less than " + schema.maximum
});
}
} else {
if (!(instance <= schema.maximum)) {
result.addError({
name: "maximum",
argument: schema.maximum,
message: "must be less than or equal to " + schema.maximum
});
}
}
return result;
};
validators.exclusiveMinimum = function validateExclusiveMinimum(instance, schema, options, ctx) {
if (typeof schema.exclusiveMinimum === "boolean") return;
if (!this.types.number(instance)) return;
var result = new ValidatorResult(instance, schema, options, ctx);
var valid = instance > schema.exclusiveMinimum;
if (!valid) {
result.addError({
name: "exclusiveMinimum",
argument: schema.exclusiveMinimum,
message: "must be strictly greater than " + schema.exclusiveMinimum
});
}
return result;
};
validators.exclusiveMaximum = function validateExclusiveMaximum(instance, schema, options, ctx) {
if (typeof schema.exclusiveMaximum === "boolean") return;
if (!this.types.number(instance)) return;
var result = new ValidatorResult(instance, schema, options, ctx);
var valid = instance < schema.exclusiveMaximum;
if (!valid) {
result.addError({
name: "exclusiveMaximum",
argument: schema.exclusiveMaximum,
message: "must be strictly less than " + schema.exclusiveMaximum
});
}
return result;
};
var validateMultipleOfOrDivisbleBy = function validateMultipleOfOrDivisbleBy2(instance, schema, options, ctx, validationType, errorMessage) {
if (!this.types.number(instance)) return;
var validationArgument = schema[validationType];
if (validationArgument == 0) {
throw new SchemaError(validationType + " cannot be zero");
}
var result = new ValidatorResult(instance, schema, options, ctx);
var instanceDecimals = helpers2.getDecimalPlaces(instance);
var divisorDecimals = helpers2.getDecimalPlaces(validationArgument);
var maxDecimals = Math.max(instanceDecimals, divisorDecimals);
var multiplier = Math.pow(10, maxDecimals);
if (Math.round(instance * multiplier) % Math.round(validationArgument * multiplier) !== 0) {
result.addError({
name: validationType,
argument: validationArgument,
message: errorMessage + JSON.stringify(validationArgument)
});
}
return result;
};
validators.multipleOf = function validateMultipleOf(instance, schema, options, ctx) {
return validateMultipleOfOrDivisbleBy.call(this, instance, schema, options, ctx, "multipleOf", "is not a multiple of (divisible by) ");
};
validators.divisibleBy = function validateDivisibleBy(instance, schema, options, ctx) {
return validateMultipleOfOrDivisbleBy.call(this, instance, schema, options, ctx, "divisibleBy", "is not divisible by (multiple of) ");
};
validators.required = function validateRequired(instance, schema, options, ctx) {
var result = new ValidatorResult(instance, schema, options, ctx);
if (instance === void 0 && schema.required === true) {
result.addError({
name: "required",
message: "is required"
});
} else if (this.types.object(instance) && Array.isArray(schema.required)) {
schema.required.forEach(function(n) {
if (getEnumerableProperty(instance, n) === void 0) {
result.addError({
name: "required",
argument: n,
message: "requires property " + JSON.stringify(n)
});
}
});
}
return result;
};
validators.pattern = function validatePattern(instance, schema, options, ctx) {
if (!this.types.string(instance)) return;
var result = new ValidatorResult(instance, schema, options, ctx);
var pattern = schema.pattern;
try {
var regexp = new RegExp(pattern, "u");
} catch (_e) {
regexp = new RegExp(pattern);
}
if (!instance.match(regexp)) {
result.addError({
name: "pattern",
argument: schema.pattern,
message: "does not match pattern " + JSON.stringify(schema.pattern.toString())
});
}
return result;
};
validators.format = function validateFormat(instance, schema, options, ctx) {
if (instance === void 0) return;
var result = new ValidatorResult(instance, schema, options, ctx);
if (!result.disableFormat && !helpers2.isFormat(instance, schema.format, this)) {
result.addError({
name: "format",
argument: schema.format,
message: "does not conform to the " + JSON.stringify(schema.format) + " format"
});
}
return result;
};
validators.minLength = function validateMinLength(instance, schema, options, ctx) {
if (!this.types.string(instance)) return;
var result = new ValidatorResult(instance, schema, options, ctx);
var hsp = instance.match(/[\uDC00-\uDFFF]/g);
var length = instance.length - (hsp ? hsp.length : 0);
if (!(length >= schema.minLength)) {
result.addError({
name: "minLength",
argument: schema.minLength,
message: "does not meet minimum length of " + schema.minLength
});
}
return result;
};
validators.maxLength = function validateMaxLength(instance, schema, options, ctx) {
if (!this.types.string(instance)) return;
var result = new ValidatorResult(instance, schema, options, ctx);
var hsp = instance.match(/[\uDC00-\uDFFF]/g);
var length = instance.length - (hsp ? hsp.length : 0);
if (!(length <= schema.maxLength)) {
result.addError({
name: "maxLength",
argument: schema.maxLength,
message: "does not meet maximum length of " + schema.maxLength
});
}
return result;
};
validators.minItems = function validateMinItems(instance, schema, options, ctx) {
if (!this.types.array(instance)) return;
var result = new ValidatorResult(instance, schema, options, ctx);
if (!(instance.length >= schema.minItems)) {
result.addError({
name: "minItems",
argument: schema.minItems,
message: "does not meet minimum length of " + schema.minItems
});
}
return result;
};
validators.maxItems = function validateMaxItems(instance, schema, options, ctx) {
if (!this.types.array(instance)) return;
var result = new ValidatorResult(instance, schema, options, ctx);
if (!(instance.length <= schema.maxItems)) {
result.addError({
name: "maxItems",
argument: schema.maxItems,
message: "does not meet maximum length of " + schema.maxItems
});
}
return result;
};
function testArrays(v, i, a) {
var j, len = a.length;
for (j = i + 1, len; j < len; j++) {
if (helpers2.deepCompareStrict(v, a[j])) {
return false;
}
}
return true;
}
validators.uniqueItems = function validateUniqueItems(instance, schema, options, ctx) {
if (schema.uniqueItems !== true) return;
if (!this.types.array(instance)) return;
var result = new ValidatorResult(instance, schema, options, ctx);
if (!instance.every(testArrays)) {
result.addError({
name: "uniqueItems",
message: "contains duplicate item"
});
}
return result;
};
validators.dependencies = function validateDependencies(instance, schema, options, ctx) {
if (!this.types.object(instance)) return;
var result = new ValidatorResult(instance, schema, options, ctx);
for (var property in schema.dependencies) {
if (instance[property] === void 0) {
continue;
}
var dep = schema.dependencies[property];
var childContext = ctx.makeChild(dep, property);
if (typeof dep == "string") {
dep = [dep];
}
if (Array.isArray(dep)) {
dep.forEach(function(prop) {
if (instance[prop] === void 0) {
result.addError({
// FIXME there's two different "dependencies" errors here with slightly different outputs
// Can we make these the same? Or should we create different error types?
name: "dependencies",
argument: childContext.propertyPath,
message: "property " + prop + " not found, required by " + childContext.propertyPath
});
}
});
} else {
var res = this.validateSchema(instance, dep, options, childContext);
if (result.instance !== res.instance) result.instance = res.instance;
if (res && res.errors.length) {
result.addError({
name: "dependencies",
argument: childContext.propertyPath,
message: "does not meet dependency required by " + childContext.propertyPath
});
result.importErrors(res);
}
}
}
return result;
};
validators["enum"] = function validateEnum(instance, schema, options, ctx) {
if (instance === void 0) {
return null;
}
if (!Array.isArray(schema["enum"])) {
throw new SchemaError("enum expects an array", schema);
}
var result = new ValidatorResult(instance, schema, options, ctx);
if (!schema["enum"].some(helpers2.deepCompareStrict.bind(null, instance))) {
result.addError({
name: "enum",
argument: schema["enum"],
message: "is not one of enum values: " + schema["enum"].map(String).join(",")
});
}
return result;
};
validators["const"] = function validateEnum(instance, schema, options, ctx) {
if (instance === void 0) {
return null;
}
var result = new ValidatorResult(instance, schema, options, ctx);
if (!helpers2.deepCompareStrict(schema["const"], instance)) {
result.addError({
name: "const",
argument: schema["const"],
message: "does not exactly match expected constant: " + schema["const"]
});
}
return result;
};
validators.not = validators.disallow = function validateNot(instance, schema, options, ctx) {
var self = this;
if (instance === void 0) return null;
var result = new ValidatorResult(instance, schema, options, ctx);
var notTypes = schema.not || schema.disallow;
if (!notTypes) return null;
if (!Array.isArray(notTypes)) notTypes = [notTypes];
notTypes.forEach(function(type) {
if (self.testType(instance, schema, options, ctx, type)) {
var id = type && (type.$id || type.id);
var schemaId = id || type;
result.addError({
name: "not",
argument: schemaId,
message: "is of prohibited type " + schemaId
});
}
});
return result;
};
attribute_1 = attribute;
return attribute_1;
}
var scan = {};
var hasRequiredScan;
function requireScan() {
if (hasRequiredScan) return scan;
hasRequiredScan = 1;
var helpers2 = requireHelpers();
scan.SchemaScanResult = SchemaScanResult;
function SchemaScanResult(found, ref) {
this.id = found;
this.ref = ref;
}
scan.scan = function scan2(base, schema) {
function scanSchema(baseuri, schema2) {
if (!schema2 || typeof schema2 != "object") return;
if (schema2.$ref) {
let resolvedUri = helpers2.resolveUrl(baseuri, schema2.$ref);
ref[resolvedUri] = ref[resolvedUri] ? ref[resolvedUri] + 1 : 0;
return;
}
var id = schema2.$id || schema2.id;
let resolvedBase = helpers2.resolveUrl(baseuri, id);
var ourBase = id ? resolvedBase : baseuri;
if (ourBase) {
if (ourBase.indexOf("#") < 0) ourBase += "#";
if (found[ourBase]) {
if (!helpers2.deepCompareStrict(found[ourBase], schema2)) {
throw new Error("Schema <" + ourBase + "> already exists with different definition");
}
return found[ourBase];
}
found[ourBase] = schema2;
if (ourBase[ourBase.length - 1] == "#") {
found[ourBase.substring(0, ourBase.length - 1)] = schema2;
}
}
scanArray(ourBase + "/items", Array.isArray(schema2.items) ? schema2.items : [schema2.items]);
scanArray(ourBase + "/extends", Array.isArray(schema2.extends) ? schema2.extends : [schema2.extends]);
scanSchema(ourBase + "/additionalItems", schema2.additionalItems);
scanObject(ourBase + "/properties", schema2.properties);
scanSchema(ourBase + "/additionalProperties", schema2.additionalProperties);
scanObject(ourBase + "/definitions", schema2.definitions);
scanObject(ourBase + "/patternProperties", schema2.patternProperties);
scanObject(ourBase + "/dependencies", schema2.dependencies);
scanArray(ourBase + "/disallow", schema2.disallow);
scanArray(ourBase + "/allOf", schema2.allOf);
scanArray(ourBase + "/anyOf", schema2.anyOf);
scanArray(ourBase + "/oneOf", schema2.oneOf);
scanSchema(ourBase + "/not", schema2.not);
}
function scanArray(baseuri, schemas) {
if (!Array.isArray(schemas)) return;
for (var i = 0; i < schemas.length; i++) {
scanSchema(baseuri + "/" + i, schemas[i]);
}
}
function scanObject(baseuri, schemas) {
if (!schemas || typeof schemas != "object") return;
for (var p in schemas) {
scanSchema(baseuri + "/" + p, schemas[p]);
}
}
var found = {};
var ref = {};
scanSchema(base, schema);
return new SchemaScanResult(found, ref);
};
return scan;
}
var validator;
var hasRequiredValidator;
function requireValidator() {
if (hasRequiredValidator) return validator;
hasRequiredValidator = 1;
var attribute = requireAttribute();
var helpers2 = requireHelpers();
var scanSchema = requireScan().scan;
var ValidatorResult = helpers2.ValidatorResult;
var ValidatorResultError = helpers2.ValidatorResultError;
var SchemaError = helpers2.SchemaError;
var SchemaContext = helpers2.SchemaContext;
var anonymousBase = "/";
var Validator2 = function Validator3() {
this.customFormats = Object.create(Validator3.prototype.customFormats);
this.schemas = {};
this.unresolvedRefs = [];
this.types = Object.create(types);
this.attributes = Object.create(attribute.validators);
};
Validator2.prototype.customFormats = {};
Validator2.prototype.schemas = null;
Validator2.prototype.types = null;
Validator2.prototype.attributes = null;
Validator2.prototype.unresolvedRefs = null;
Validator2.prototype.addSchema = function addSchema(schema, base) {
var self = this;
if (!schema) {
return null;
}
var scan2 = scanSchema(base || anonymousBase, schema);
var ourUri = base || schema.$id || schema.id;
for (var uri in scan2.id) {
this.schemas[uri] = scan2.id[uri];
}
for (var uri in scan2.ref) {
this.unresolvedRefs.push(uri);
}
this.unresolvedRefs = this.unresolvedRefs.filter(function(uri2) {
return typeof self.schemas[uri2] === "undefined";
});
return this.schemas[ourUri];
};
Validator2.prototype.addSubSchemaArray = function addSubSchemaArray(baseuri, schemas) {
if (!Array.isArray(schemas)) return;
for (var i = 0; i < schemas.length; i++) {
this.addSubSchema(baseuri, schemas[i]);
}
};
Validator2.prototype.addSubSchemaObject = function addSubSchemaArray(baseuri, schemas) {
if (!schemas || typeof schemas != "object") return;
for (var p in schemas) {
this.addSubSchema(baseuri, schemas[p]);
}
};
Validator2.prototype.setSchemas = function setSchemas(schemas) {
this.schemas = schemas;
};
Validator2.prototype.getSchema = function getSchema(urn) {
return this.schemas[urn];
};
Validator2.prototype.validate = function validate(instance, schema, options, ctx) {
if (typeof schema !== "boolean" && typeof schema !== "object" || schema === null) {
throw new SchemaError("Expected `schema` to be an object or boolean");
}
if (!options) {
options = {};
}
var id = schema.$id || schema.id;
let base = helpers2.resolveUrl(options.base, id || "");
if (!ctx) {
ctx = new SchemaContext(schema, options, [], base, Object.create(this.schemas));
if (!ctx.schemas[base]) {
ctx.schemas[base] = schema;
}
var found = scanSchema(base, schema);
for (var n in found.id) {
var sch = found.id[n];
ctx.schemas[n] = sch;
}
}
if (options.required && instance === void 0) {
var result = new ValidatorResult(instance, schema, options, ctx);
result.addError("is required, but is undefined");
return result;
}
var result = this.validateSchema(instance, schema, options, ctx);
if (!result) {
throw new Error("Result undefined");
} else if (options.throwAll && result.errors.length) {
throw new ValidatorResultError(result);
}
return result;
};
function shouldResolve(schema) {
var ref = typeof schema === "string" ? schema : schema.$ref;
if (typeof ref == "string") return ref;
return false;
}
Validator2.prototype.validateSchema = function validateSchema(instance, schema, options, ctx) {
var result = new ValidatorResult(instance, schema, options, ctx);
if (typeof schema === "boolean") {
if (schema === true) {
schema = {};
} else if (schema === false) {
schema = { type: [] };
}
} else if (!schema) {
throw new Error("schema is undefined");
}
if (schema["extends"]) {
if (Array.isArray(schema["extends"])) {
var schemaobj = { schema, ctx };
schema["extends"].forEach(this.schemaTraverser.bind(this, schemaobj));
schema = schemaobj.schema;
schemaobj.schema = null;
schemaobj.ctx = null;
schemaobj = null;
} else {
schema = helpers2.deepMerge(schema, this.superResolve(schema["extends"], ctx));
}
}
var switchSchema = shouldResolve(schema);
if (switchSchema) {
var resolved = this.resolve(schema, switchSchema, ctx);
var subctx = new SchemaContext(resolved.subschema, options, ctx.path, resolved.switchSchema, ctx.schemas);
return this.validateSchema(instance, resolved.subschema, options, subctx);
}
var skipAttributes = options && options.skipAttributes || [];
for (var key in schema) {
if (!attribute.ignoreProperties[key] && skipAttributes.indexOf(key) < 0) {
var validatorErr = null;
var validator2 = this.attributes[key];
if (validator2) {
validatorErr = validator2.call(this, instance, schema, options, ctx);
} else if (options.allowUnknownAttributes === false) {
throw new SchemaError("Unsupported attribute: " + key, schema);
}
if (validatorErr) {
result.importErrors(validatorErr);
}
}
}
if (typeof options.rewrite == "function") {
var value = options.rewrite.call(this, instance, schema, options, ctx);
result.instance = value;
}
return result;
};
Validator2.prototype.schemaTraverser = function schemaTraverser(schemaobj, s) {
schemaobj.schema = helpers2.deepMerge(schemaobj.schema, this.superResolve(s, schemaobj.ctx));
};
Validator2.prototype.superResolve = function superResolve(schema, ctx) {
var ref = shouldResolve(schema);
if (ref) {
return this.resolve(schema, ref, ctx).subschema;
}
return schema;
};
Validator2.prototype.resolve = function resolve(schema, switchSchema, ctx) {
switchSchema = ctx.resolve(switchSchema);
if (ctx.schemas[switchSchema]) {
return { subschema: ctx.schemas[switchSchema], switchSchema };
}
let parsed = new URL(switchSchema, "thismessage::/");
let fragment = parsed.hash;
var document = fragment && fragment.length && switchSchema.substr(0, switchSchema.length - fragment.length);
if (!document || !ctx.schemas[document]) {
throw new SchemaError("no such schema <" + switchSchema + ">", schema);
}
var subschema = helpers2.objectGetPath(ctx.schemas[document], fragment.substr(1));
if (subschema === void 0) {
throw new SchemaError("no such schema " + fragment + " located in <" + document + ">", schema);
}
return { subschema, switchSchema };
};
Validator2.prototype.testType = function validateType(instance, schema, options, ctx, type) {
if (type === void 0) {
return;
} else if (type === null) {
throw new SchemaError('Unexpected null in "type" keyword');
}
if (typeof this.types[type] == "function") {
return this.types[type].call(this, instance);
}
if (type && typeof type == "object") {
var res = this.validateSchema(instance, type, options, ctx);
return res === void 0 || !(res && res.errors.length);
}
return true;
};
var types = Validator2.prototype.types = {};
types.string = function testString(instance) {
return typeof instance == "string";
};
types.number = function testNumber(instance) {
return typeof instance == "number" && isFinite(instance);
};
types.integer = function testInteger(instance) {
return typeof instance == "number" && instance % 1 === 0;
};
types.boolean = function testBoolean(instance) {
return typeof instance == "boolean";
};
types.array = function testArray(instance) {
return Array.isArray(instance);
};
types["null"] = function testNull(instance) {
return instance === null;
};
types.date = function testDate(instance) {
return instance instanceof Date;
};
types.any = function testAny(instance) {
return true;
};
types.object = function testObject(instance) {
return instance && typeof instance === "object" && !Array.isArray(instance) && !(instance instanceof Date);
};
validator = Validator2;
return validator;
}
var hasRequiredLib;
function requireLib() {
if (hasRequiredLib) return lib;
hasRequiredLib = 1;
var Validator2 = lib.Validator = requireValidator();
lib.ValidatorResult = requireHelpers().ValidatorResult;
lib.ValidatorResultError = requireHelpers().ValidatorResultError;
lib.ValidationError = requireHelpers().ValidationError;
lib.SchemaError = requireHelpers().SchemaError;
lib.SchemaScanResult = requireScan().SchemaScanResult;
lib.scan = requireScan().scan;
lib.validate = function(instance, schema, options) {
var v = new Validator2();
return v.validate(instance, schema, options);
};
return lib;
}
var libExports = requireLib();
var toolBaseSchema = external_exports.object({
name: external_exports.string(),
description: external_exports.string()
});
var functionToolSchema = toolBaseSchema.extend({
type: external_exports.literal("function"),
parametersSchema: zodSchemaSchema,
checkParameters: external_exports.function(),
implementation: external_exports.function()
});
var rawFunctionToolSchema = toolBaseSchema.extend({
type: external_exports.literal("rawFunction"),
parametersSchema: zodSchemaSchema,
checkParameters: external_exports.function(),
implementation: external_exports.function()
});
var unimplementedRawFunctionToolSchema = toolBaseSchema.extend({
type: external_exports.literal("unimplementedRawFunction"),
parametersJsonSchema: zodSchemaSchema,
checkParameters: external_exports.function(),
implementation: external_exports.function()
});
var remoteToolSchema = toolBaseSchema.extend({
type: external_exports.literal("remoteTool"),
pluginIdentifier: external_exports.string(),
parametersJsonSchema: zodSchemaSchema,
checkParameters: external_exports.function(),
implementation: external_exports.function()
});
external_exports.discriminatedUnion("type", [
functionToolSchema,
rawFunctionToolSchema,
unimplementedRawFunctionToolSchema,
remoteToolSchema
]);
function tool({ name, description, parameters, implementation }) {
const parametersSchema = external_exports.object(parameters);
return {
name,
description,
type: "function",
parametersSchema,
checkParameters(params) {
const parametersParseResult = parametersSchema.safeParse(params);
if (!parametersParseResult.success) {
throw new Error(text`
Failed to parse arguments for tool "${name}":
${parametersParseResult.error.message}
`);
}
},
implementation: (params, ctx) => {
const parametersParseResult = parametersSchema.safeParse(params);
if (!parametersParseResult.success) {
throw new Error(text`
Failed to parse arguments for tool "${name}":
${parametersParseResult.error.message}
`);
}
return implementation(parametersParseResult.data, ctx);
}
};
}
var ConnectionStatus;
(function(ConnectionStatus2) {
ConnectionStatus2["Connected"] = "CONNECTED";
ConnectionStatus2["Errored"] = "ERRORED";
ConnectionStatus2["Closed"] = "CLOSED";
})(ConnectionStatus || (ConnectionStatus = {}));
var logger = new SimpleLogger("Channel");
var DoubleIndexedKV = (
/** @class */
(function() {
function DoubleIndexedKV2() {
this.keyToValue = /* @__PURE__ */ new Map();
this.valueToKey = /* @__PURE__ */ new Map();
}
DoubleIndexedKV2.prototype.set = function(key, value) {
this.keyToValue.set(key, value);
this.valueToKey.set(value, key);
};
DoubleIndexedKV2.prototype.getByKey = function(key) {
return this.keyToValue.get(key);
};
DoubleIndexedKV2.prototype.getByValue = function(value) {
return this.valueToKey.get(value);
};
DoubleIndexedKV2.prototype.clear = function() {
this.keyToValue.clear();
this.valueToKey.clear();
};
return DoubleIndexedKV2;
})()
);
var Registry = (
/** @class */
(function() {
function Registry2(generateIdentifier) {
this.generateIdentifier = generateIdentifier;
this.kv = new DoubleIndexedKV();
}
Registry2.prototype.register = function(value, identifier) {
if (this.kv.getByValue(value)) {
return;
}
if (!identifier) {
identifier = this.generateIdentifier(value);
}
this.kv.set(identifier, value);
};
Registry2.prototype.clear = function() {
this.kv.clear();
};
Registry2.prototype.getIdentifier = function(value) {
return this.kv.getByValue(value);
};
Registry2.prototype.getValue = function(identifier) {
return this.kv.getByKey(identifier);
};
return Registry2;
})()
);
var __extends = globalThis && globalThis.__extends || /* @__PURE__ */ (function() {
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
d2.__proto__ = b2;
} || function(d2, b2) {
for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
};
return extendStatics(d, b);
};
return function(d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var ClassRegistry = (
/** @class */
(function(_super) {
__extends(ClassRegistry2, _super);
function ClassRegistry2() {
var _this = _super.call(this, function(c) {
return c.name;
}) || this;
_this.classToAllowedProps = /* @__PURE__ */ new Map();
return _this;
}
ClassRegistry2.prototype.register = function(value, options) {
if (typeof options === "object") {
if (options.allowProps) {
this.classToAllowedProps.set(value, options.allowProps);
}
_super.prototype.register.call(this, value, options.identifier);
} else {
_super.prototype.register.call(this, value, options);
}
};
ClassRegistry2.prototype.getAllowedProps = function(value) {
return this.classToAllowedProps.get(value);
};
return ClassRegistry2;
})(Registry)
);
var __read$3 = globalThis && globalThis.__read || function(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
} catch (error) {
e = { error };
} finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
} finally {
if (e) throw e.error;
}
}
return ar;
};
function valuesOfObj(record) {
if ("values" in Object) {
return Object.values(record);
}
var values = [];
for (var key in record) {
if (record.hasOwnProperty(key)) {
values.push(record[key]);
}
}
return values;
}
function find(record, predicate) {
var values = valuesOfObj(record);
if ("find" in values) {
return values.find(predicate);
}
var valuesNotNever = values;
for (var i = 0; i < valuesNotNever.length; i++) {
var value = valuesNotNever[i];
if (predicate(value)) {
return value;
}
}
return void 0;
}
function forEach(record, run) {
Object.entries(record).forEach(function(_a2) {
var _b = __read$3(_a2, 2), key = _b[0], value = _b[1];
return run(value, key);
});
}
function includes(arr, value) {
return arr.indexOf(value) !== -1;
}
function findArr(record, predicate) {
for (var i = 0; i < record.length; i++) {
var value = record[i];
if (predicate(value)) {
return value;
}
}
return void 0;
}
var CustomTransformerRegistry = (
/** @class */
(function() {
function CustomTransformerRegistry2() {
this.transfomers = {};
}
CustomTransformerRegistry2.prototype.register = function(transformer) {
this.transfomers[transformer.name] = transformer;
};
CustomTransformerRegistry2.prototype.findApplicable = function(v) {
return find(this.transfomers, function(transformer) {
return transformer.isApplicable(v);
});
};
CustomTransformerRegistry2.prototype.findByName = function(name) {
return this.transfomers[name];
};
return CustomTransformerRegistry2;
})()
);
var getType$1 = function(payload) {
return Object.prototype.toString.call(payload).slice(8, -1);
};
var isUndefined = function(payload) {
return typeof payload === "undefined";
};
var isNull = function(payload) {
return payload === null;
};
var isPlainObject$1 = function(payload) {
if (typeof payload !== "object" || payload === null)
return false;
if (payload === Object.prototype)
return false;
if (Object.getPrototypeOf(payload) === null)
return true;
return Object.getPrototypeOf(payload) === Object.prototype;
};
var isEmptyObject = function(payload) {
return isPlainObject$1(payload) && Object.keys(payload).length === 0;
};
var isArray$1 = function(payload) {
return Array.isArray(payload);
};
var isString = function(payload) {
return typeof payload === "string";
};
var isNumber = function(payload) {
return typeof payload === "number" && !isNaN(payload);
};
var isBoolean = function(payload) {
return typeof payload === "boolean";
};
var isRegExp = function(payload) {
return payload instanceof RegExp;
};
var isMap = function(payload) {
return payload instanceof Map;
};
var isSet = function(payload) {
return payload instanceof Set;
};
var isSymbol = function(payload) {
return getType$1(payload) === "Symbol";
};
var isDate = function(payload) {
return payload instanceof Date && !isNaN(payload.valueOf());
};
var isError = function(payload) {
return payload instanceof Error;
};
var isNaNValue = function(payload) {
return typeof payload === "number" && isNaN(payload);
};
var isPrimitive = function(payload) {
return isBoolean(payload) || isNull(payload) || isUndefined(payload) || isNumber(payload) || isString(payload) || isSymbol(payload);
};
var isBigint = function(payload) {
return typeof payload === "bigint";
};
var isInfinite = function(payload) {
return payload === Infinity || payload === -Infinity;
};
var isTypedArray = function(payload) {
return ArrayBuffer.isView(payload) && !(payload instanceof DataView);
};
var isURL = function(payload) {
return payload instanceof URL;
};
var escapeKey = function(key) {
return key.replace(/\./g, "\\.");
};
var stringifyPath = function(path4) {
return path4.map(String).map(escapeKey).join(".");
};
var parsePath = function(string) {
var result = [];
var segment = "";
for (var i = 0; i < string.length; i++) {
var char = string.charAt(i);
var isEscapedDot = char === "\\" && string.charAt(i + 1) === ".";
if (isEscapedDot) {
segment += ".";
i++;
continue;
}
var isEndOfSegment = char === ".";
if (isEndOfSegment) {
result.push(segment);
segment = "";
continue;
}
segment += char;
}
var lastSegment = segment;
result.push(lastSegment);
return result;
};
var __assign$1 = globalThis && globalThis.__assign || function() {
__assign$1 = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign$1.apply(this, arguments);
};
var __read$2 = globalThis && globalThis.__read || function(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
} catch (error) {
e = { error };
} finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
} finally {
if (e) throw e.error;
}
}
return ar;
};
var __spreadArray$2 = globalThis && globalThis.__spreadArray || function(to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
function simpleTransformation(isApplicable, annotation, transform2, untransform) {
return {
isApplicable,
annotation,
transform: transform2,
untransform
};
}
var simpleRules = [
simpleTransformation(isUndefined, "undefined", function() {
return null;
}, function() {
return void 0;
}),
simpleTransformation(isBigint, "bigint", function(v) {
return v.toString();
}, function(v) {
if (typeof BigInt !== "undefined") {
return BigInt(v);
}
console.error("Please add a BigInt polyfill.");
return v;
}),
simpleTransformation(isDate, "Date", function(v) {
return v.toISOString();
}, function(v) {
return new Date(v);
}),
simpleTransformation(isError, "Error", function(v, superJson) {
var baseError = {
name: v.name,
message: v.message
};
superJson.allowedErrorProps.forEach(function(prop) {
baseError[prop] = v[prop];
});
return baseError;
}, function(v, superJson) {
var e = new Error(v.message);
e.name = v.name;
e.stack = v.stack;
superJson.allowedErrorProps.forEach(function(prop) {
e[prop] = v[prop];
});
return e;
}),
simpleTransformation(isRegExp, "regexp", function(v) {
return "" + v;
}, function(regex) {
var body = regex.slice(1, regex.lastIndexOf("/"));
var flags = regex.slice(regex.lastIndexOf("/") + 1);
return new RegExp(body, flags);
}),
simpleTransformation(
isSet,
"set",
// (sets only exist in es6+)
// eslint-disable-next-line es5/no-es6-methods
function(v) {
return __spreadArray$2([], __read$2(v.values()));
},
function(v) {
return new Set(v);
}
),
simpleTransformation(isMap, "map", function(v) {
return __spreadArray$2([], __read$2(v.entries()));
}, function(v) {
return new Map(v);
}),
simpleTransformation(function(v) {
return isNaNValue(v) || isInfinite(v);
}, "number", function(v) {
if (isNaNValue(v)) {
return "NaN";
}
if (v > 0) {
return "Infinity";
} else {
return "-Infinity";
}
}, Number),
simpleTransformation(function(v) {
return v === 0 && 1 / v === -Infinity;
}, "number", function() {
return "-0";
}, Number),
simpleTransformation(isURL, "URL", function(v) {
return v.toString();
}, function(v) {
return new URL(v);
})
];
function compositeTransformation(isApplicable, annotation, transform2, untransform) {
return {
isApplicable,
annotation,
transform: transform2,
untransform
};
}
var symbolRule = compositeTransformation(function(s, superJson) {
if (isSymbol(s)) {
var isRegistered = !!superJson.symbolRegistry.getIdentifier(s);
return isRegistered;
}
return false;
}, function(s, superJson) {
var identifier = superJson.symbolRegistry.getIdentifier(s);
return ["symbol", identifier];
}, function(v) {
return v.description;
}, function(_, a, superJson) {
var value = superJson.symbolRegistry.getValue(a[1]);
if (!value) {
throw new Error("Trying to deserialize unknown symbol");
}
return value;
});
var constructorToName = [
Int8Array,
Uint8Array,
Int16Array,
Uint16Array,
Int32Array,
Uint32Array,
Float32Array,
Float64Array,
Uint8ClampedArray
].reduce(function(obj, ctor) {
obj[ctor.name] = ctor;
return obj;
}, {});
var typedArrayRule = compositeTransformation(isTypedArray, function(v) {
return ["typed-array", v.constructor.name];
}, function(v) {
return __spreadArray$2([], __read$2(v));
}, function(v, a) {
var ctor = constructorToName[a[1]];
if (!ctor) {
throw new Error("Trying to deserialize unknown typed array");
}
return new ctor(v);
});
function isInstanceOfRegisteredClass(potentialClass, superJson) {
if (potentialClass === null || potentialClass === void 0 ? void 0 : potentialClass.constructor) {
var isRegistered = !!superJson.classRegistry.getIdentifier(potentialClass.constructor);
return isRegistered;
}
return false;
}
var classRule = compositeTransformation(isInstanceOfRegisteredClass, function(clazz, superJson) {
var identifier = superJson.classRegistry.getIdentifier(clazz.constructor);
return ["class", identifier];
}, function(clazz, superJson) {
var allowedProps = superJson.classRegistry.getAllowedProps(clazz.constructor);
if (!allowedProps) {
return __assign$1({}, clazz);
}
var result = {};
allowedProps.forEach(function(prop) {
result[prop] = clazz[prop];
});
return result;
}, function(v, a, superJson) {
var clazz = superJson.classRegistry.getValue(a[1]);
if (!clazz) {
throw new Error("Trying to deserialize unknown class - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564");
}
return Object.assign(Object.create(clazz.prototype), v);
});
var customRule = compositeTransformation(function(value, superJson) {
return !!superJson.customTransformerRegistry.findApplicable(value);
}, function(value, superJson) {
var transformer = superJson.customTransformerRegistry.findApplicable(value);
return ["custom", transformer.name];
}, function(value, superJson) {
var transformer = superJson.customTransformerRegistry.findApplicable(value);
return transformer.serialize(value);
}, function(v, a, superJson) {
var transformer = superJson.customTransformerRegistry.findByName(a[1]);
if (!transformer) {
throw new Error("Trying to deserialize unknown custom value");
}
return transformer.deserialize(v);
});
var compositeRules = [classRule, symbolRule, customRule, typedArrayRule];
var transformValue = function(value, superJson) {
var applicableCompositeRule = findArr(compositeRules, function(rule) {
return rule.isApplicable(value, superJson);
});
if (applicableCompositeRule) {
return {
value: applicableCompositeRule.transform(value, superJson),
type: applicableCompositeRule.annotation(value, superJson)
};
}
var applicableSimpleRule = findArr(simpleRules, function(rule) {
return rule.isApplicable(value, superJson);
});
if (applicableSimpleRule) {
return {
value: applicableSimpleRule.transform(value, superJson),
type: applicableSimpleRule.annotation
};
}
return void 0;
};
var simpleRulesByAnnotation = {};
simpleRules.forEach(function(rule) {
simpleRulesByAnnotation[rule.annotation] = rule;
});
var untransformValue = function(json, type, superJson) {
if (isArray$1(type)) {
switch (type[0]) {
case "symbol":
return symbolRule.untransform(json, type, superJson);
case "class":
return classRule.untransform(json, type, superJson);
case "custom":
return customRule.untransform(json, type, superJson);
case "typed-array":
return typedArrayRule.untransform(json, type, superJson);
default:
throw new Error("Unknown transformation: " + type);
}
} else {
var transformation = simpleRulesByAnnotation[type];
if (!transformation) {
throw new Error("Unknown transformation: " + type);
}
return transformation.untransform(json, superJson);
}
};
var getNthKey = function(value, n) {
var keys = value.keys();
while (n > 0) {
keys.next();
n--;
}
return keys.next().value;
};
function validatePath(path4) {
if (includes(path4, "__proto__")) {
throw new Error("__proto__ is not allowed as a property");
}
if (includes(path4, "prototype")) {
throw new Error("prototype is not allowed as a property");
}
if (includes(path4, "constructor")) {
throw new Error("constructor is not allowed as a property");
}
}
var getDeep = function(object, path4) {
validatePath(path4);
for (var i = 0; i < path4.length; i++) {
var key = path4[i];
if (isSet(object)) {
object = getNthKey(object, +key);
} else if (isMap(object)) {
var row = +key;
var type = +path4[++i] === 0 ? "key" : "value";
var keyOfRow = getNthKey(object, row);
switch (type) {
case "key":
object = keyOfRow;
break;
case "value":
object = object.get(keyOfRow);
break;
}
} else {
object = object[key];
}
}
return object;
};
var setDeep = function(object, path4, mapper) {
validatePath(path4);
if (path4.length === 0) {
return mapper(object);
}
var parent = object;
for (var i = 0; i < path4.length - 1; i++) {
var key = path4[i];
if (isArray$1(parent)) {
var index = +key;
parent = parent[index];
} else if (isPlainObject$1(parent)) {
parent = parent[key];
} else if (isSet(parent)) {
var row = +key;
parent = getNthKey(parent, row);
} else if (isMap(parent)) {
var isEnd = i === path4.length - 2;
if (isEnd) {
break;
}
var row = +key;
var type = +path4[++i] === 0 ? "key" : "value";
var keyOfRow = getNthKey(parent, row);
switch (type) {
case "key":
parent = keyOfRow;
break;
case "value":
parent = parent.get(keyOfRow);
break;
}
}
}
var lastKey = path4[path4.length - 1];
if (isArray$1(parent)) {
parent[+lastKey] = mapper(parent[+lastKey]);
} else if (isPlainObject$1(parent)) {
parent[lastKey] = mapper(parent[lastKey]);
}
if (isSet(parent)) {
var oldValue = getNthKey(parent, +lastKey);
var newValue = mapper(oldValue);
if (oldValue !== newValue) {
parent["delete"](oldValue);
parent.add(newValue);
}
}
if (isMap(parent)) {
var row = +path4[path4.length - 2];
var keyToRow = getNthKey(parent, row);
var type = +lastKey === 0 ? "key" : "value";
switch (type) {
case "key": {
var newKey = mapper(keyToRow);
parent.set(newKey, parent.get(keyToRow));
if (newKey !== keyToRow) {
parent["delete"](keyToRow);
}
break;
}
case "value": {
parent.set(keyToRow, mapper(parent.get(keyToRow)));
break;
}
}
}
return object;
};
var __read$1 = globalThis && globalThis.__read || function(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
} catch (error) {
e = { error };
} finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
} finally {
if (e) throw e.error;
}
}
return ar;
};
var __spreadArray$1 = globalThis && globalThis.__spreadArray || function(to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
function traverse(tree, walker2, origin) {
if (origin === void 0) {
origin = [];
}
if (!tree) {
return;
}
if (!isArray$1(tree)) {
forEach(tree, function(subtree, key) {
return traverse(subtree, walker2, __spreadArray$1(__spreadArray$1([], __read$1(origin)), __read$1(parsePath(key))));
});
return;
}
var _a2 = __read$1(tree, 2), nodeValue = _a2[0], children = _a2[1];
if (children) {
forEach(children, function(child, key) {
traverse(child, walker2, __spreadArray$1(__spreadArray$1([], __read$1(origin)), __read$1(parsePath(key))));
});
}
walker2(nodeValue, origin);
}
function applyValueAnnotations(plain, annotations, superJson) {
traverse(annotations, function(type, path4) {
plain = setDeep(plain, path4, function(v) {
return untransformValue(v, type, superJson);
});
});
return plain;
}
function applyReferentialEqualityAnnotations(plain, annotations) {
function apply(identicalPaths, path4) {
var object = getDeep(plain, parsePath(path4));
identicalPaths.map(parsePath).forEach(function(identicalObjectPath) {
plain = setDeep(plain, identicalObjectPath, function() {
return object;
});
});
}
if (isArray$1(annotations)) {
var _a2 = __read$1(annotations, 2), root = _a2[0], other = _a2[1];
root.forEach(function(identicalPath) {
plain = setDeep(plain, parsePath(identicalPath), function() {
return plain;
});
});
if (other) {
forEach(other, apply);
}
} else {
forEach(annotations, apply);
}
return plain;
}
var isDeep = function(object, superJson) {
return isPlainObject$1(object) || isArray$1(object) || isMap(object) || isSet(object) || isInstanceOfRegisteredClass(object, superJson);
};
function addIdentity(object, path4, identities) {
var existingSet = identities.get(object);
if (existingSet) {
existingSet.push(path4);
} else {
identities.set(object, [path4]);
}
}
function generateReferentialEqualityAnnotations(identitites, dedupe) {
var result = {};
var rootEqualityPaths = void 0;
identitites.forEach(function(paths) {
if (paths.length <= 1) {
return;
}
if (!dedupe) {
paths = paths.map(function(path4) {
return path4.map(String);
}).sort(function(a, b) {
return a.length - b.length;
});
}
var _a2 = __read$1(paths), representativePath = _a2[0], identicalPaths = _a2.slice(1);
if (representativePath.length === 0) {
rootEqualityPaths = identicalPaths.map(stringifyPath);
} else {
result[stringifyPath(representativePath)] = identicalPaths.map(stringifyPath);
}
});
if (rootEqualityPaths) {
if (isEmptyObject(result)) {
return [rootEqualityPaths];
} else {
return [rootEqualityPaths, result];
}
} else {
return isEmptyObject(result) ? void 0 : result;
}
}
var walker = function(object, identities, superJson, dedupe, path4, objectsInThisPath, seenObjects) {
var _a2;
if (path4 === void 0) {
path4 = [];
}
if (objectsInThisPath === void 0) {
objectsInThisPath = [];
}
if (seenObjects === void 0) {
seenObjects = /* @__PURE__ */ new Map();
}
var primitive = isPrimitive(object);
if (!primitive) {
addIdentity(object, path4, identities);
var seen = seenObjects.get(object);
if (seen) {
return dedupe ? {
transformedValue: null
} : seen;
}
}
if (!isDeep(object, superJson)) {
var transformed_1 = transformValue(object, superJson);
var result_1 = transformed_1 ? {
transformedValue: transformed_1.value,
annotations: [transformed_1.type]
} : {
transformedValue: object
};
if (!primitive) {
seenObjects.set(object, result_1);
}
return result_1;
}
if (includes(objectsInThisPath, object)) {
return {
transformedValue: null
};
}
var transformationResult = transformValue(object, superJson);
var transformed = (_a2 = transformationResult === null || transformationResult === void 0 ? void 0 : transformationResult.value) !== null && _a2 !== void 0 ? _a2 : object;
var transformedValue = isArray$1(transformed) ? [] : {};
var innerAnnotations = {};
forEach(transformed, function(value, index) {
var recursiveResult = walker(value, identities, superJson, dedupe, __spreadArray$1(__spreadArray$1([], __read$1(path4)), [index]), __spreadArray$1(__spreadArray$1([], __read$1(objectsInThisPath)), [object]), seenObjects);
transformedValue[index] = recursiveResult.transformedValue;
if (isArray$1(recursiveResult.annotations)) {
innerAnnotations[index] = recursiveResult.annotations;
} else if (isPlainObject$1(recursiveResult.annotations)) {
forEach(recursiveResult.annotations, function(tree, key) {
innerAnnotations[escapeKey(index) + "." + key] = tree;
});
}
});
var result = isEmptyObject(innerAnnotations) ? {
transformedValue,
annotations: !!transformationResult ? [transformationResult.type] : void 0
} : {
transformedValue,
annotations: !!transformationResult ? [transformationResult.type, innerAnnotations] : innerAnnotations
};
if (!primitive) {
seenObjects.set(object, result);
}
return result;
};
function getType(payload) {
return Object.prototype.toString.call(payload).slice(8, -1);
}
function isArray(payload) {
return getType(payload) === "Array";
}
function isPlainObject(payload) {
if (getType(payload) !== "Object")
return false;
const prototype = Object.getPrototypeOf(payload);
return !!prototype && prototype.constructor === Object && prototype === Object.prototype;
}
function assignProp(carry, key, newVal, originalObject, includeNonenumerable) {
const propType = {}.propertyIsEnumerable.call(originalObject, key) ? "enumerable" : "nonenumerable";
if (propType === "enumerable")
carry[key] = newVal;
if (includeNonenumerable && propType === "nonenumerable") {
Object.defineProperty(carry, key, {
value: newVal,
enumerable: false,
writable: true,
configurable: true
});
}
}
function copy(target, options = {}) {
if (isArray(target)) {
return target.map((item) => copy(item, options));
}
if (!isPlainObject(target)) {
return target;
}
const props = Object.getOwnPropertyNames(target);
const symbols = Object.getOwnPropertySymbols(target);
return [...props, ...symbols].reduce((carry, key) => {
if (isArray(options.props) && !options.props.includes(key)) {
return carry;
}
const val = target[key];
const newVal = copy(val, options);
assignProp(carry, key, newVal, target, options.nonenumerable);
return carry;
}, {});
}
var __assign = globalThis && globalThis.__assign || function() {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __read = globalThis && globalThis.__read || function(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
} catch (error) {
e = { error };
} finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
} finally {
if (e) throw e.error;
}
}
return ar;
};
var __spreadArray = globalThis && globalThis.__spreadArray || function(to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
var SuperJSON = (
/** @class */
(function() {
function SuperJSON2(_a2) {
var _b = _a2 === void 0 ? {} : _a2, _c = _b.dedupe, dedupe = _c === void 0 ? false : _c;
this.classRegistry = new ClassRegistry();
this.symbolRegistry = new Registry(function(s) {
var _a3;
return (_a3 = s.description) !== null && _a3 !== void 0 ? _a3 : "";
});
this.customTransformerRegistry = new CustomTransformerRegistry();
this.allowedErrorProps = [];
this.dedupe = dedupe;
}
SuperJSON2.prototype.serialize = function(object) {
var identities = /* @__PURE__ */ new Map();
var output = walker(object, identities, this, this.dedupe);
var res = {
json: output.transformedValue
};
if (output.annotations) {
res.meta = __assign(__assign({}, res.meta), { values: output.annotations });
}
var equalityAnnotations = generateReferentialEqualityAnnotations(identities, this.dedupe);
if (equalityAnnotations) {
res.meta = __assign(__assign({}, res.meta), { referentialEqualities: equalityAnnotations });
}
return res;
};
SuperJSON2.prototype.deserialize = function(payload) {
var json = payload.json, meta = payload.meta;
var result = copy(json);
if (meta === null || meta === void 0 ? void 0 : meta.values) {
result = applyValueAnnotations(result, meta.values, this);
}
if (meta === null || meta === void 0 ? void 0 : meta.referentialEqualities) {
result = applyReferentialEqualityAnnotations(result, meta.referentialEqualities);
}
return result;
};
SuperJSON2.prototype.stringify = function(object) {
return JSON.stringify(this.serialize(object));
};
SuperJSON2.prototype.parse = function(string) {
return this.deserialize(JSON.parse(string));
};
SuperJSON2.prototype.registerClass = function(v, options) {
this.classRegistry.register(v, options);
};
SuperJSON2.prototype.registerSymbol = function(v, identifier) {
this.symbolRegistry.register(v, identifier);
};
SuperJSON2.prototype.registerCustom = function(transformer, name) {
this.customTransformerRegistry.register(__assign({ name }, transformer));
};
SuperJSON2.prototype.allowErrorProps = function() {
var _a2;
var props = [];
for (var _i = 0; _i < arguments.length; _i++) {
props[_i] = arguments[_i];
}
(_a2 = this.allowedErrorProps).push.apply(_a2, __spreadArray([], __read(props)));
};
SuperJSON2.defaultInstance = new SuperJSON2();
SuperJSON2.serialize = SuperJSON2.defaultInstance.serialize.bind(SuperJSON2.defaultInstance);
SuperJSON2.deserialize = SuperJSON2.defaultInstance.deserialize.bind(SuperJSON2.defaultInstance);
SuperJSON2.stringify = SuperJSON2.defaultInstance.stringify.bind(SuperJSON2.defaultInstance);
SuperJSON2.parse = SuperJSON2.defaultInstance.parse.bind(SuperJSON2.defaultInstance);
SuperJSON2.registerClass = SuperJSON2.defaultInstance.registerClass.bind(SuperJSON2.defaultInstance);
SuperJSON2.registerSymbol = SuperJSON2.defaultInstance.registerSymbol.bind(SuperJSON2.defaultInstance);
SuperJSON2.registerCustom = SuperJSON2.defaultInstance.registerCustom.bind(SuperJSON2.defaultInstance);
SuperJSON2.allowErrorProps = SuperJSON2.defaultInstance.allowErrorProps.bind(SuperJSON2.defaultInstance);
return SuperJSON2;
})()
);
var serialize$1 = SuperJSON.serialize;
var deserialize$1 = SuperJSON.deserialize;
var serializedOpaqueSchema = external_exports.any();
var clientToServerMessageSchema = external_exports.discriminatedUnion("type", [
// Communication
external_exports.object({
type: external_exports.literal("communicationWarning"),
warning: external_exports.string()
}),
external_exports.object({
type: external_exports.literal("keepAlive")
}),
// Channel
external_exports.object({
type: external_exports.literal("channelCreate"),
endpoint: external_exports.string(),
channelId: external_exports.number().int(),
creationParameter: serializedOpaqueSchema
}),
external_exports.object({
type: external_exports.literal("channelSend"),
channelId: external_exports.number().int(),
message: serializedOpaqueSchema,
ackId: external_exports.number().int().optional()
}),
external_exports.object({
type: external_exports.literal("channelAck"),
channelId: external_exports.number().int(),
ackId: external_exports.number().int()
}),
// RPC
external_exports.object({
type: external_exports.literal("rpcCall"),
endpoint: external_exports.string(),
callId: external_exports.number().int(),
parameter: serializedOpaqueSchema
}),
// Readonly signal
external_exports.object({
type: external_exports.literal("signalSubscribe"),
creationParameter: serializedOpaqueSchema,
endpoint: external_exports.string(),
subscribeId: external_exports.number().int()
}),
external_exports.object({
type: external_exports.literal("signalUnsubscribe"),
subscribeId: external_exports.number().int()
}),
// Writable signal
external_exports.object({
type: external_exports.literal("writableSignalSubscribe"),
creationParameter: serializedOpaqueSchema,
endpoint: external_exports.string(),
subscribeId: external_exports.number().int()
}),
external_exports.object({
type: external_exports.literal("writableSignalUnsubscribe"),
subscribeId: external_exports.number().int()
}),
external_exports.object({
type: external_exports.literal("writableSignalUpdate"),
subscribeId: external_exports.number().int(),
patches: external_exports.array(serializedOpaqueSchema),
tags: external_exports.array(external_exports.string())
})
]);
var serverToClientMessageSchema = external_exports.discriminatedUnion("type", [
// Communication
external_exports.object({
type: external_exports.literal("communicationWarning"),
warning: external_exports.string()
}),
external_exports.object({
type: external_exports.literal("keepAliveAck")
}),
// Channel
external_exports.object({
type: external_exports.literal("channelSend"),
channelId: external_exports.number().int(),
message: serializedOpaqueSchema,
ackId: external_exports.number().int().optional()
}),
external_exports.object({
type: external_exports.literal("channelAck"),
channelId: external_exports.number().int(),
ackId: external_exports.number().int()
}),
external_exports.object({
type: external_exports.literal("channelClose"),
channelId: external_exports.number().int()
}),
external_exports.object({
type: external_exports.literal("channelError"),
channelId: external_exports.number().int(),
error: serializedLMSExtendedErrorSchema
}),
// RPC
external_exports.object({
type: external_exports.literal("rpcResult"),
callId: external_exports.number().int(),
result: serializedOpaqueSchema
}),
external_exports.object({
type: external_exports.literal("rpcError"),
callId: external_exports.number().int(),
error: serializedLMSExtendedErrorSchema
}),
// Readonly signal
external_exports.object({
type: external_exports.literal("signalUpdate"),
subscribeId: external_exports.number().int(),
patches: external_exports.array(serializedOpaqueSchema),
tags: external_exports.array(external_exports.string())
}),
external_exports.object({
type: external_exports.literal("signalError"),
subscribeId: external_exports.number().int(),
error: serializedLMSExtendedErrorSchema
}),
// Writable signal
external_exports.object({
type: external_exports.literal("writableSignalUpdate"),
subscribeId: external_exports.number().int(),
patches: external_exports.array(serializedOpaqueSchema),
tags: external_exports.array(external_exports.string())
}),
external_exports.object({
type: external_exports.literal("writableSignalError"),
subscribeId: external_exports.number().int(),
error: serializedLMSExtendedErrorSchema
})
]);
var wsAuthenticationResultSchema = external_exports.discriminatedUnion("success", [
external_exports.object({
success: external_exports.literal(true)
}),
external_exports.object({
success: external_exports.literal(false),
error: external_exports.string()
})
]);
var WsClientTransportStatus;
(function(WsClientTransportStatus2) {
WsClientTransportStatus2["Disconnected"] = "DISCONNECTED";
WsClientTransportStatus2["Connecting"] = "CONNECTING";
WsClientTransportStatus2["Connected"] = "CONNECTED";
})(WsClientTransportStatus || (WsClientTransportStatus = {}));
var DynamicHandle = class {
/**
* Don't construct this on your own. Use {@link LLMNamespace#get} or {@link LLMNamespace#load}
* instead.
*
* @internal
*/
constructor(port, specifier) {
this.port = port;
this.specifier = specifier;
}
/**
* Gets the information of the model that is currently associated with this `DynamicHandle`. If no
* model is currently associated, this will return `undefined`.
*
* Note: As models are loaded/unloaded, the model associated with this `LLMModel` may change at
* any moment.
*/
async getModelInfo() {
const info = await this.port.callRpc("getModelInfo", { specifier: this.specifier, throwIfNotFound: false }, { stack: getCurrentStack(1) });
if (info === void 0) {
return void 0;
}
return info;
}
async getLoadConfig(stack) {
const loadConfig2 = await this.port.callRpc("getLoadConfig", { specifier: this.specifier }, { stack });
return loadConfig2;
}
};
var EmbeddingDynamicHandle = class extends DynamicHandle {
/**
* Don't construct this on your own. Use {@link EmbeddingNamespace#get} or
* {@link EmbeddingNamespace#load}
* instead.
*
* @internal
*/
constructor(port, specifier, validator2, logger2 = new SimpleLogger(`EmbeddingModel`)) {
super(port, specifier);
this.validator = validator2;
this.logger = logger2;
}
async embed(inputString) {
const stack = getCurrentStack(1);
inputString = this.validator.validateMethodParamOrThrow("client.embedding", "embed", "inputString", external_exports.string().or(external_exports.array(external_exports.string())), inputString, stack);
if (Array.isArray(inputString)) {
return await Promise.all(inputString.map((s) => this.port.callRpc("embedString", { inputString: s, modelSpecifier: this.specifier }, { stack })));
} else {
return await this.port.callRpc("embedString", { inputString, modelSpecifier: this.specifier }, { stack });
}
}
async getContextLength() {
const stack = getCurrentStack(1);
const loadConfig2 = await this.getLoadConfig(stack);
return embeddingSharedLoadConfigSchematics.access(loadConfig2, "contextLength");
}
async getEvalBatchSize() {
const stack = getCurrentStack(1);
const loadConfig2 = await this.getLoadConfig(stack);
return globalConfigSchematics.access(loadConfig2, "embedding.load.llama.evalBatchSize");
}
async tokenize(inputString) {
const stack = getCurrentStack(1);
inputString = this.validator.validateMethodParamOrThrow("model", "tokenize", "inputString", external_exports.string().or(external_exports.array(external_exports.string())), inputString, stack);
if (Array.isArray(inputString)) {
return (await Promise.all(inputString.map((s) => this.port.callRpc("tokenize", { specifier: this.specifier, inputString: s }, { stack })))).map((r) => r.tokens);
} else {
return (await this.port.callRpc("tokenize", {
specifier: this.specifier,
inputString
}, { stack })).tokens;
}
}
async countTokens(inputString) {
const stack = getCurrentStack(1);
inputString = this.validator.validateMethodParamOrThrow("model", "countTokens", "inputString", external_exports.string(), inputString, stack);
return (await this.port.callRpc("countTokens", {
specifier: this.specifier,
inputString
}, { stack })).tokenCount;
}
};
var parseDocumentOptsSchema = documentParsingOptsSchema.extend({
onProgress: external_exports.function().optional(),
signal: external_exports.instanceof(AbortSignal).optional()
});
var retrievalCallbacksSchema = external_exports.object({
onFileProcessList: external_exports.function().optional(),
onFileProcessingStart: external_exports.function().optional(),
onFileProcessingEnd: external_exports.function().optional(),
onFileProcessingStepStart: external_exports.function().optional(),
onFileProcessingStepProgress: external_exports.function().optional(),
onFileProcessingStepEnd: external_exports.function().optional(),
onSearchingStart: external_exports.function().optional(),
onSearchingEnd: external_exports.function().optional(),
verbose: external_exports.union([external_exports.boolean(), external_exports.string()]).optional()
});
var retrievalOptsSchema = external_exports.object({
chunkingMethod: retrievalChunkingMethodSchema.optional(),
limit: external_exports.number().int().optional(),
embeddingModel: external_exports.instanceof(EmbeddingDynamicHandle).optional(),
databasePath: external_exports.string().optional(),
signal: external_exports.instanceof(AbortSignal).optional(),
...retrievalCallbacksSchema.shape
});
var errorDeserializersMap = /* @__PURE__ */ new Map();
function registerErrorDeserializer(code, deserializer) {
errorDeserializersMap.set(code, deserializer);
}
function formatAvailableLLMs(availablePathsSample, totalModels) {
if (availablePathsSample.length === 0) {
return import_chalk.default.gray(" You don't have any LLMs downloaded.");
}
let text2 = availablePathsSample.map((path4) => import_chalk.default.cyanBright(" \u2022 " + path4)).join("\n");
if (availablePathsSample.length < totalModels) {
text2 += import_chalk.default.gray(`
... (and ${totalModels - availablePathsSample.length} more)`);
}
return text2;
}
registerErrorDeserializer("generic.pathNotFound", ({ availablePathsSample, path: path4, totalModels }, stack) => {
return makeTitledPrettyError(`Cannot find a model with path "${import_chalk.default.yellowBright(path4)}"`, text`
Here are your available models:
${formatAvailableLLMs(availablePathsSample, totalModels)}
Run
${import_chalk.default.yellowBright("lms ls")}
to see a full list of loadable models
`, stack);
});
function formatLoadedModels(loadedModelsSample, totalLoadedModels) {
if (loadedModelsSample.length === 0) {
return import_chalk.default.gray(" You don't have any models loaded.");
}
let text2 = loadedModelsSample.map((path4) => import_chalk.default.cyanBright(" \u2022 " + path4)).join("\n");
if (loadedModelsSample.length < totalLoadedModels) {
text2 += import_chalk.default.gray(`
... (and ${totalLoadedModels - loadedModelsSample.length} more)`);
}
return text2;
}
registerErrorDeserializer("generic.identifierNotFound", ({ loadedModelsSample, identifier, totalLoadedModels }, stack) => {
return makeTitledPrettyError(`Cannot find a model with identifier "${import_chalk.default.yellowBright(identifier)}"`, text`
Here are your loaded models:
${formatLoadedModels(loadedModelsSample, totalLoadedModels)}
Run
${import_chalk.default.yellowBright("lms ps")}
to see a full list of loaded models
`, stack);
});
registerErrorDeserializer("generic.specificModelUnloaded", (_, stack) => {
return makePrettyError(import_chalk.default.bgRed.white(text`
This model has already been unloaded.
`), stack);
});
function getModelDomainTypeDisplayNameSingular(domain) {
switch (domain) {
case "llm":
return "an LLM";
case "embedding":
return "an embedding model";
case "imageGen":
return "an image generation model";
case "transcription":
return "a transcription model";
case "tts":
return "a text-to-speech model";
default: {
const exhaustiveCheck = domain;
console.error(`Unexpected domain type: ${exhaustiveCheck}`);
return "Unknown Model Domain";
}
}
}
function formatQuery(query) {
const requirements = [];
if (query.domain !== void 0) {
requirements.push(text`
The model must be ${import_chalk.default.yellowBright(getModelDomainTypeDisplayNameSingular(query.domain))}
`);
}
if (query.identifier !== void 0) {
requirements.push(`The identifier must be exactly "${import_chalk.default.yellowBright(query.identifier)}"`);
}
if (query.path !== void 0) {
requirements.push(`The path must match "${import_chalk.default.yellowBright(query.path)}"`);
}
if (requirements.length === 0) {
return import_chalk.default.gray(" \u2022 Any Model");
}
return requirements.map((req) => import_chalk.default.white(" \u2022 " + req)).join("\n");
}
registerErrorDeserializer("generic.noModelMatchingQuery", ({ loadedModelsSample, totalLoadedModels, query }, stack) => {
return makePrettyError(text`
${import_chalk.default.bgRed.white(" No loaded model satisfies all requirements specified in the query. ")}
Loaded Models:
${formatLoadedModels(loadedModelsSample, totalLoadedModels)}
Your query:
${formatQuery(query)}
Run
${import_chalk.default.yellowBright("lms ps")}
to see a full list of loaded models with details
`, stack);
});
registerErrorDeserializer("generic.domainMismatch", ({ actualDomain, expectedDomain, path: path4 }, stack) => {
return makePrettyError(text`
${import_chalk.default.bgRed.white(" Model has wrong domain. ")}
Expecting ${import_chalk.default.greenBright(path4)} to be ${import_chalk.default.yellowBright(getModelDomainTypeDisplayNameSingular(expectedDomain))}, but it is actually ${import_chalk.default.yellowBright(getModelDomainTypeDisplayNameSingular(actualDomain))}.
`, stack);
});
function formatAvailablePresets(presets, totalAvailablePresets) {
if (presets.length === 0) {
return import_chalk.default.gray(" You don't have any presets available.");
}
let text2 = presets.map(({ identifier, name }) => import_chalk.default.cyanBright(` \u2022 ${name} (${import_chalk.default.cyan(identifier)})`)).join("\n");
if (presets.length < totalAvailablePresets) {
text2 += import_chalk.default.gray(`
... (and ${totalAvailablePresets - presets.length} more)`);
}
return text2;
}
registerErrorDeserializer("generic.presetNotFound", ({ specifiedFuzzyPresetIdentifier, availablePresetsSample, totalAvailablePresets }) => {
return makeTitledPrettyError(`Cannot find a preset with identifier "${import_chalk.default.yellowBright(specifiedFuzzyPresetIdentifier)}"`, text`
Here are your available presets:
${formatAvailablePresets(availablePresetsSample, totalAvailablePresets)}
Note: To specify a preset in the SDK, you need to use its identifier (in parentheses). You
can get a preset's identifier by right-clicking on it and then select "Copy Preset
Identifier".
`);
});
var callIdGiver = new IdGiver(Math.floor(Math.random() * (Number.MAX_SAFE_INTEGER / 2 / 1e4)) * 1e4);
var llmActBaseOptsSchema = external_exports.object({
onFirstToken: external_exports.function().optional(),
onPredictionFragment: external_exports.function().optional(),
onMessage: external_exports.function().optional(),
onRoundStart: external_exports.function().optional(),
onRoundEnd: external_exports.function().optional(),
onPredictionCompleted: external_exports.function().optional(),
onPromptProcessingProgress: external_exports.function().optional(),
onToolCallRequestStart: external_exports.function().optional(),
onToolCallRequestNameReceived: external_exports.function().optional(),
onToolCallRequestArgumentFragmentGenerated: external_exports.function().optional(),
onToolCallRequestEnd: external_exports.function().optional(),
onToolCallRequestFinalized: external_exports.function().optional(),
onToolCallRequestFailure: external_exports.function().optional(),
onToolCallRequestDequeued: external_exports.function().optional(),
guardToolCall: external_exports.function().optional(),
handleInvalidToolRequest: external_exports.function().optional(),
maxPredictionRounds: external_exports.number().int().min(1).optional(),
signal: external_exports.instanceof(AbortSignal).optional(),
allowParallelToolExecution: external_exports.boolean().optional()
});
var llmPredictionOptsSchema = llmPredictionConfigInputSchema.extend({
onPromptProcessingProgress: external_exports.function().optional(),
onFirstToken: external_exports.function().optional(),
onPredictionFragment: external_exports.function().optional(),
onToolCallRequestStart: external_exports.function().optional(),
onToolCallRequestNameReceived: external_exports.function().optional(),
onToolCallRequestArgumentFragmentGenerated: external_exports.function().optional(),
onToolCallRequestEnd: external_exports.function().optional(),
onToolCallRequestFailure: external_exports.function().optional(),
signal: external_exports.instanceof(AbortSignal).optional(),
preset: external_exports.string().optional()
});
var llmRespondOptsSchema = llmPredictionOptsSchema.extend({
onMessage: external_exports.function().optional(),
onToolCallRequestStart: external_exports.function().optional(),
onToolCallRequestNameReceived: external_exports.function().optional(),
onToolCallRequestArgumentFragmentGenerated: external_exports.function().optional(),
onToolCallRequestEnd: external_exports.function().optional(),
onToolCallRequestFailure: external_exports.function().optional()
});
var llmActionOptsSchema = llmPredictionConfigInputSchema.extend(llmActBaseOptsSchema.shape).extend({
preset: external_exports.string().optional()
});
var noFormattingTemplate = text`
{% for message in messages %}{{ message['content'] }}{% endfor %}
`;
var llmGeneratorPredictionOptsSchema = external_exports.object({
onFirstToken: external_exports.function().optional(),
onPredictionFragment: external_exports.function().optional(),
onMessage: external_exports.function().optional(),
signal: external_exports.instanceof(AbortSignal).optional(),
pluginConfig: kvConfigSchema.optional(),
workingDirectory: external_exports.string().optional()
});
var llmGeneratorActOptsSchema = llmActBaseOptsSchema.extend({
pluginConfig: kvConfigSchema.optional(),
workingDirectory: external_exports.string().optional()
});
var generatorSchema = external_exports.function();
var __addDisposableResource$1 = globalThis && globalThis.__addDisposableResource || function(env, value, async) {
if (value !== null && value !== void 0) {
if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
var dispose, inner;
if (async) {
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
dispose = value[Symbol.asyncDispose];
}
if (dispose === void 0) {
if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
dispose = value[Symbol.dispose];
if (async) inner = dispose;
}
if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
if (inner) dispose = function() {
try {
inner.call(this);
} catch (e) {
return Promise.reject(e);
}
};
env.stack.push({ value, dispose, async });
} else if (async) {
env.stack.push({ async: true });
}
return value;
};
var __disposeResources$1 = globalThis && globalThis.__disposeResources || /* @__PURE__ */ (function(SuppressedError2) {
return function(env) {
function fail(e) {
env.error = env.hasError ? new SuppressedError2(e, env.error, "An error was suppressed during disposal.") : e;
env.hasError = true;
}
var r, s = 0;
function next() {
while (r = env.stack.pop()) {
try {
if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
if (r.dispose) {
var result = r.dispose.call(r.value);
if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
fail(e);
return next();
});
} else s |= 1;
} catch (e) {
fail(e);
}
}
if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
if (env.hasError) throw env.error;
}
return next();
};
})(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
});
var __addDisposableResource = globalThis && globalThis.__addDisposableResource || function(env, value, async) {
if (value !== null && value !== void 0) {
if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
var dispose, inner;
if (async) {
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
dispose = value[Symbol.asyncDispose];
}
if (dispose === void 0) {
if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
dispose = value[Symbol.dispose];
if (async) inner = dispose;
}
if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
if (inner) dispose = function() {
try {
inner.call(this);
} catch (e) {
return Promise.reject(e);
}
};
env.stack.push({ value, dispose, async });
} else if (async) {
env.stack.push({ async: true });
}
return value;
};
var __disposeResources = globalThis && globalThis.__disposeResources || /* @__PURE__ */ (function(SuppressedError2) {
return function(env) {
function fail(e) {
env.error = env.hasError ? new SuppressedError2(e, env.error, "An error was suppressed during disposal.") : e;
env.hasError = true;
}
var r, s = 0;
function next() {
while (r = env.stack.pop()) {
try {
if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
if (r.dispose) {
var result = r.dispose.call(r.value);
if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
fail(e);
return next();
});
} else s |= 1;
} catch (e) {
fail(e);
}
}
if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
if (env.hasError) throw env.error;
}
return next();
};
})(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
});
var pluginToolsOptsSchema = external_exports.object({
pluginConfig: kvConfigSchema.optional(),
workingDirectory: external_exports.string().optional()
});
var registerDevelopmentPluginOptsSchema = external_exports.object({
manifest: pluginManifestSchema
});
var artifactDownloadPlannerDownloadOptsSchema = external_exports.object({
onStartFinalizing: external_exports.function().optional(),
onProgress: external_exports.function().optional(),
signal: external_exports.instanceof(AbortSignal).optional()
});
var downloadOptsSchema = external_exports.object({
onProgress: external_exports.function().optional(),
onStartFinalizing: external_exports.function().optional(),
signal: external_exports.instanceof(AbortSignal).optional()
});
var downloadArtifactOptsSchema = external_exports.object({
owner: external_exports.string(),
name: external_exports.string(),
revisionNumber: external_exports.number(),
path: external_exports.string(),
onProgress: external_exports.function().optional(),
onStartFinalizing: external_exports.function().optional(),
signal: external_exports.instanceof(AbortSignal).optional()
});
var pushArtifactOptsSchema = external_exports.object({
path: external_exports.string(),
description: external_exports.string().optional(),
makePrivate: external_exports.boolean().optional(),
writeRevision: external_exports.boolean().optional(),
overrides: jsonSerializableSchema.optional(),
onMessage: external_exports.function().optional()
});
var ensureAuthenticatedOptsSchema = external_exports.object({
onAuthenticationUrl: external_exports.function()
});
var loginWithPreAuthenticatedKeysOptsSchema = external_exports.object({
keyId: external_exports.string(),
publicKey: external_exports.string(),
privateKey: external_exports.string()
});
external_exports.object({
userName: external_exports.string()
});
var createArtifactDownloadPlannerOptsSchema = external_exports.object({
owner: external_exports.string(),
name: external_exports.string(),
onPlanUpdated: external_exports.function().optional()
});
var startHttpServerOptsSchema = external_exports.object({
port: external_exports.number().int().min(1).max(65535).describe("Port to run the API server on. Must be between 1 and 65535."),
cors: external_exports.boolean().describe("Enable CORS on the API server. Allows any website to access the server.")
});
var constructorOptsSchema = external_exports.object({
logger: external_exports.any().optional(),
baseUrl: external_exports.string().optional(),
verboseErrorMessages: external_exports.boolean().optional(),
clientIdentifier: external_exports.string().optional(),
clientPasskey: external_exports.string().optional(),
// Internal testing options
disableConnection: external_exports.boolean().optional(),
llmPort: external_exports.any().optional(),
embeddingPort: external_exports.any().optional(),
systemPort: external_exports.any().optional(),
diagnosticsPort: external_exports.any().optional(),
retrievalPort: external_exports.any().optional(),
filesPort: external_exports.any().optional(),
repositoryPort: external_exports.any().optional(),
pluginsPort: external_exports.any().optional()
}).strict();
// node_modules/uuid/dist/esm-node/stringify.js
var byteToHex = [];
for (let i = 0; i < 256; ++i) {
byteToHex.push((i + 256).toString(16).slice(1));
}
function unsafeStringify(arr, offset = 0) {
return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
}
// node_modules/uuid/dist/esm-node/rng.js
var import_node_crypto = __toESM(require("node:crypto"));
var rnds8Pool = new Uint8Array(256);
var poolPtr = rnds8Pool.length;
function rng() {
if (poolPtr > rnds8Pool.length - 16) {
import_node_crypto.default.randomFillSync(rnds8Pool);
poolPtr = 0;
}
return rnds8Pool.slice(poolPtr, poolPtr += 16);
}
// node_modules/uuid/dist/esm-node/native.js
var import_node_crypto2 = __toESM(require("node:crypto"));
var native_default = {
randomUUID: import_node_crypto2.default.randomUUID
};
// node_modules/uuid/dist/esm-node/v4.js
function v4(options, buf, offset) {
if (native_default.randomUUID && !buf && !options) {
return native_default.randomUUID();
}
options = options || {};
const rnds = options.random || (options.rng || rng)();
rnds[6] = rnds[6] & 15 | 64;
rnds[8] = rnds[8] & 63 | 128;
if (buf) {
offset = offset || 0;
for (let i = 0; i < 16; ++i) {
buf[offset + i] = rnds[i];
}
return buf;
}
return unsafeStringify(rnds);
}
var v4_default = v4;
// src/engine/csv-engine.ts
var import_promises2 = __toESM(require("node:fs/promises"), 1);
// node_modules/csv-parse/lib/api/CsvError.js
var CsvError = class _CsvError extends Error {
constructor(code, message, options, ...contexts) {
if (Array.isArray(message)) message = message.join(" ").trim();
super(message);
if (Error.captureStackTrace !== void 0) {
Error.captureStackTrace(this, _CsvError);
}
this.code = code;
for (const context of contexts) {
for (const key in context) {
const value = context[key];
this[key] = Buffer.isBuffer(value) ? value.toString(options.encoding) : value == null ? value : JSON.parse(JSON.stringify(value));
}
}
}
};
// node_modules/csv-parse/lib/utils/is_object.js
var is_object = function(obj) {
return typeof obj === "object" && obj !== null && !Array.isArray(obj);
};
// node_modules/csv-parse/lib/api/normalize_columns_array.js
var normalize_columns_array = function(columns) {
const normalizedColumns = [];
for (let i = 0, l = columns.length; i < l; i++) {
const column = columns[i];
if (column === void 0 || column === null || column === false) {
normalizedColumns[i] = { disabled: true };
} else if (typeof column === "string") {
normalizedColumns[i] = { name: column };
} else if (is_object(column)) {
if (typeof column.name !== "string") {
throw new CsvError("CSV_OPTION_COLUMNS_MISSING_NAME", [
"Option columns missing name:",
`property "name" is required at position ${i}`,
"when column is an object literal"
]);
}
normalizedColumns[i] = column;
} else {
throw new CsvError("CSV_INVALID_COLUMN_DEFINITION", [
"Invalid column definition:",
"expect a string or a literal object,",
`got ${JSON.stringify(column)} at position ${i}`
]);
}
}
return normalizedColumns;
};
// node_modules/csv-parse/lib/utils/ResizeableBuffer.js
var ResizeableBuffer = class {
constructor(size = 100) {
this.size = size;
this.length = 0;
this.buf = Buffer.allocUnsafe(size);
}
prepend(val) {
if (Buffer.isBuffer(val)) {
const length = this.length + val.length;
if (length >= this.size) {
this.resize();
if (length >= this.size) {
throw Error("INVALID_BUFFER_STATE");
}
}
const buf = this.buf;
this.buf = Buffer.allocUnsafe(this.size);
val.copy(this.buf, 0);
buf.copy(this.buf, val.length);
this.length += val.length;
} else {
const length = this.length++;
if (length === this.size) {
this.resize();
}
const buf = this.clone();
this.buf[0] = val;
buf.copy(this.buf, 1, 0, length);
}
}
append(val) {
const length = this.length++;
if (length === this.size) {
this.resize();
}
this.buf[length] = val;
}
clone() {
return Buffer.from(this.buf.slice(0, this.length));
}
resize() {
const length = this.length;
this.size = this.size * 2;
const buf = Buffer.allocUnsafe(this.size);
this.buf.copy(buf, 0, 0, length);
this.buf = buf;
}
toString(encoding) {
if (encoding) {
return this.buf.slice(0, this.length).toString(encoding);
} else {
return Uint8Array.prototype.slice.call(this.buf.slice(0, this.length));
}
}
toJSON() {
return this.toString("utf8");
}
reset() {
this.length = 0;
}
};
var ResizeableBuffer_default = ResizeableBuffer;
// node_modules/csv-parse/lib/api/init_state.js
var np = 12;
var cr = 13;
var nl = 10;
var space = 32;
var tab = 9;
var init_state = function(options) {
return {
bomSkipped: false,
bufBytesStart: 0,
castField: options.cast_function,
commenting: false,
// Current error encountered by a record
error: void 0,
enabled: options.from_line === 1,
escaping: false,
escapeIsQuote: Buffer.isBuffer(options.escape) && Buffer.isBuffer(options.quote) && Buffer.compare(options.escape, options.quote) === 0,
// columns can be `false`, `true`, `Array`
expectedRecordLength: Array.isArray(options.columns) ? options.columns.length : void 0,
field: new ResizeableBuffer_default(20),
firstLineToHeaders: options.cast_first_line_to_header,
needMoreDataSize: Math.max(
// Skip if the remaining buffer smaller than comment
options.comment !== null ? options.comment.length : 0,
...options.delimiter.map((delimiter) => delimiter.length),
// Skip if the remaining buffer can be escape sequence
options.quote !== null ? options.quote.length : 0
),
previousBuf: void 0,
quoting: false,
stop: false,
rawBuffer: new ResizeableBuffer_default(100),
record: [],
recordHasError: false,
record_length: 0,
recordDelimiterMaxLength: options.record_delimiter.length === 0 ? 0 : Math.max(...options.record_delimiter.map((v) => v.length)),
trimChars: [
Buffer.from(" ", options.encoding)[0],
Buffer.from(" ", options.encoding)[0]
],
wasQuoting: false,
wasRowDelimiter: false,
timchars: [
Buffer.from(Buffer.from([cr], "utf8").toString(), options.encoding),
Buffer.from(Buffer.from([nl], "utf8").toString(), options.encoding),
Buffer.from(Buffer.from([np], "utf8").toString(), options.encoding),
Buffer.from(Buffer.from([space], "utf8").toString(), options.encoding),
Buffer.from(Buffer.from([tab], "utf8").toString(), options.encoding)
]
};
};
// node_modules/csv-parse/lib/utils/underscore.js
var underscore = function(str) {
return str.replace(/([A-Z])/g, function(_, match) {
return "_" + match.toLowerCase();
});
};
// node_modules/csv-parse/lib/api/normalize_options.js
var normalize_options = function(opts) {
const options = {};
for (const opt in opts) {
options[underscore(opt)] = opts[opt];
}
if (options.encoding === void 0 || options.encoding === true) {
options.encoding = "utf8";
} else if (options.encoding === null || options.encoding === false) {
options.encoding = null;
} else if (typeof options.encoding !== "string" && options.encoding !== null) {
throw new CsvError(
"CSV_INVALID_OPTION_ENCODING",
[
"Invalid option encoding:",
"encoding must be a string or null to return a buffer,",
`got ${JSON.stringify(options.encoding)}`
],
options
);
}
if (options.bom === void 0 || options.bom === null || options.bom === false) {
options.bom = false;
} else if (options.bom !== true) {
throw new CsvError(
"CSV_INVALID_OPTION_BOM",
[
"Invalid option bom:",
"bom must be true,",
`got ${JSON.stringify(options.bom)}`
],
options
);
}
options.cast_function = null;
if (options.cast === void 0 || options.cast === null || options.cast === false || options.cast === "") {
options.cast = void 0;
} else if (typeof options.cast === "function") {
options.cast_function = options.cast;
options.cast = true;
} else if (options.cast !== true) {
throw new CsvError(
"CSV_INVALID_OPTION_CAST",
[
"Invalid option cast:",
"cast must be true or a function,",
`got ${JSON.stringify(options.cast)}`
],
options
);
}
if (options.cast_date === void 0 || options.cast_date === null || options.cast_date === false || options.cast_date === "") {
options.cast_date = false;
} else if (options.cast_date === true) {
options.cast_date = function(value) {
const date = Date.parse(value);
return !isNaN(date) ? new Date(date) : value;
};
} else if (typeof options.cast_date !== "function") {
throw new CsvError(
"CSV_INVALID_OPTION_CAST_DATE",
[
"Invalid option cast_date:",
"cast_date must be true or a function,",
`got ${JSON.stringify(options.cast_date)}`
],
options
);
}
options.cast_first_line_to_header = null;
if (options.columns === true) {
options.cast_first_line_to_header = void 0;
} else if (typeof options.columns === "function") {
options.cast_first_line_to_header = options.columns;
options.columns = true;
} else if (Array.isArray(options.columns)) {
options.columns = normalize_columns_array(options.columns);
} else if (options.columns === void 0 || options.columns === null || options.columns === false) {
options.columns = false;
} else {
throw new CsvError(
"CSV_INVALID_OPTION_COLUMNS",
[
"Invalid option columns:",
"expect an array, a function or true,",
`got ${JSON.stringify(options.columns)}`
],
options
);
}
if (options.group_columns_by_name === void 0 || options.group_columns_by_name === null || options.group_columns_by_name === false) {
options.group_columns_by_name = false;
} else if (options.group_columns_by_name !== true) {
throw new CsvError(
"CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME",
[
"Invalid option group_columns_by_name:",
"expect an boolean,",
`got ${JSON.stringify(options.group_columns_by_name)}`
],
options
);
} else if (options.columns === false) {
throw new CsvError(
"CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME",
[
"Invalid option group_columns_by_name:",
"the `columns` mode must be activated."
],
options
);
}
if (options.comment === void 0 || options.comment === null || options.comment === false || options.comment === "") {
options.comment = null;
} else {
if (typeof options.comment === "string") {
options.comment = Buffer.from(options.comment, options.encoding);
}
if (!Buffer.isBuffer(options.comment)) {
throw new CsvError(
"CSV_INVALID_OPTION_COMMENT",
[
"Invalid option comment:",
"comment must be a buffer or a string,",
`got ${JSON.stringify(options.comment)}`
],
options
);
}
}
if (options.comment_no_infix === void 0 || options.comment_no_infix === null || options.comment_no_infix === false) {
options.comment_no_infix = false;
} else if (options.comment_no_infix !== true) {
throw new CsvError(
"CSV_INVALID_OPTION_COMMENT",
[
"Invalid option comment_no_infix:",
"value must be a boolean,",
`got ${JSON.stringify(options.comment_no_infix)}`
],
options
);
}
const delimiter_json = JSON.stringify(options.delimiter);
if (!Array.isArray(options.delimiter))
options.delimiter = [options.delimiter];
if (options.delimiter.length === 0) {
throw new CsvError(
"CSV_INVALID_OPTION_DELIMITER",
[
"Invalid option delimiter:",
"delimiter must be a non empty string or buffer or array of string|buffer,",
`got ${delimiter_json}`
],
options
);
}
options.delimiter = options.delimiter.map(function(delimiter) {
if (delimiter === void 0 || delimiter === null || delimiter === false) {
return Buffer.from(",", options.encoding);
}
if (typeof delimiter === "string") {
delimiter = Buffer.from(delimiter, options.encoding);
}
if (!Buffer.isBuffer(delimiter) || delimiter.length === 0) {
throw new CsvError(
"CSV_INVALID_OPTION_DELIMITER",
[
"Invalid option delimiter:",
"delimiter must be a non empty string or buffer or array of string|buffer,",
`got ${delimiter_json}`
],
options
);
}
return delimiter;
});
if (options.escape === void 0 || options.escape === true) {
options.escape = Buffer.from('"', options.encoding);
} else if (typeof options.escape === "string") {
options.escape = Buffer.from(options.escape, options.encoding);
} else if (options.escape === null || options.escape === false) {
options.escape = null;
}
if (options.escape !== null) {
if (!Buffer.isBuffer(options.escape)) {
throw new Error(
`Invalid Option: escape must be a buffer, a string or a boolean, got ${JSON.stringify(options.escape)}`
);
}
}
if (options.from === void 0 || options.from === null) {
options.from = 1;
} else {
if (typeof options.from === "string" && /\d+/.test(options.from)) {
options.from = parseInt(options.from);
}
if (Number.isInteger(options.from)) {
if (options.from < 0) {
throw new Error(
`Invalid Option: from must be a positive integer, got ${JSON.stringify(opts.from)}`
);
}
} else {
throw new Error(
`Invalid Option: from must be an integer, got ${JSON.stringify(options.from)}`
);
}
}
if (options.from_line === void 0 || options.from_line === null) {
options.from_line = 1;
} else {
if (typeof options.from_line === "string" && /\d+/.test(options.from_line)) {
options.from_line = parseInt(options.from_line);
}
if (Number.isInteger(options.from_line)) {
if (options.from_line <= 0) {
throw new Error(
`Invalid Option: from_line must be a positive integer greater than 0, got ${JSON.stringify(opts.from_line)}`
);
}
} else {
throw new Error(
`Invalid Option: from_line must be an integer, got ${JSON.stringify(opts.from_line)}`
);
}
}
if (options.ignore_last_delimiters === void 0 || options.ignore_last_delimiters === null) {
options.ignore_last_delimiters = false;
} else if (typeof options.ignore_last_delimiters === "number") {
options.ignore_last_delimiters = Math.floor(options.ignore_last_delimiters);
if (options.ignore_last_delimiters === 0) {
options.ignore_last_delimiters = false;
}
} else if (typeof options.ignore_last_delimiters !== "boolean") {
throw new CsvError(
"CSV_INVALID_OPTION_IGNORE_LAST_DELIMITERS",
[
"Invalid option `ignore_last_delimiters`:",
"the value must be a boolean value or an integer,",
`got ${JSON.stringify(options.ignore_last_delimiters)}`
],
options
);
}
if (options.ignore_last_delimiters === true && options.columns === false) {
throw new CsvError(
"CSV_IGNORE_LAST_DELIMITERS_REQUIRES_COLUMNS",
[
"The option `ignore_last_delimiters`",
"requires the activation of the `columns` option"
],
options
);
}
if (options.info === void 0 || options.info === null || options.info === false) {
options.info = false;
} else if (options.info !== true) {
throw new Error(
`Invalid Option: info must be true, got ${JSON.stringify(options.info)}`
);
}
if (options.max_record_size === void 0 || options.max_record_size === null || options.max_record_size === false) {
options.max_record_size = 0;
} else if (Number.isInteger(options.max_record_size) && options.max_record_size >= 0) {
} else if (typeof options.max_record_size === "string" && /\d+/.test(options.max_record_size)) {
options.max_record_size = parseInt(options.max_record_size);
} else {
throw new Error(
`Invalid Option: max_record_size must be a positive integer, got ${JSON.stringify(options.max_record_size)}`
);
}
if (options.objname === void 0 || options.objname === null || options.objname === false) {
options.objname = void 0;
} else if (Buffer.isBuffer(options.objname)) {
if (options.objname.length === 0) {
throw new Error(`Invalid Option: objname must be a non empty buffer`);
}
if (options.encoding === null) {
} else {
options.objname = options.objname.toString(options.encoding);
}
} else if (typeof options.objname === "string") {
if (options.objname.length === 0) {
throw new Error(`Invalid Option: objname must be a non empty string`);
}
} else if (typeof options.objname === "number") {
} else {
throw new Error(
`Invalid Option: objname must be a string or a buffer, got ${options.objname}`
);
}
if (options.objname !== void 0) {
if (typeof options.objname === "number") {
if (options.columns !== false) {
throw Error(
"Invalid Option: objname index cannot be combined with columns or be defined as a field"
);
}
} else {
if (options.columns === false) {
throw Error(
"Invalid Option: objname field must be combined with columns or be defined as an index"
);
}
}
}
if (options.on_record === void 0 || options.on_record === null) {
options.on_record = void 0;
} else if (typeof options.on_record !== "function") {
throw new CsvError(
"CSV_INVALID_OPTION_ON_RECORD",
[
"Invalid option `on_record`:",
"expect a function,",
`got ${JSON.stringify(options.on_record)}`
],
options
);
}
if (options.on_skip !== void 0 && options.on_skip !== null && typeof options.on_skip !== "function") {
throw new Error(
`Invalid Option: on_skip must be a function, got ${JSON.stringify(options.on_skip)}`
);
}
if (options.quote === null || options.quote === false || options.quote === "") {
options.quote = null;
} else {
if (options.quote === void 0 || options.quote === true) {
options.quote = Buffer.from('"', options.encoding);
} else if (typeof options.quote === "string") {
options.quote = Buffer.from(options.quote, options.encoding);
}
if (!Buffer.isBuffer(options.quote)) {
throw new Error(
`Invalid Option: quote must be a buffer or a string, got ${JSON.stringify(options.quote)}`
);
}
}
if (options.raw === void 0 || options.raw === null || options.raw === false) {
options.raw = false;
} else if (options.raw !== true) {
throw new Error(
`Invalid Option: raw must be true, got ${JSON.stringify(options.raw)}`
);
}
if (options.record_delimiter === void 0) {
options.record_delimiter = [];
} else if (typeof options.record_delimiter === "string" || Buffer.isBuffer(options.record_delimiter)) {
if (options.record_delimiter.length === 0) {
throw new CsvError(
"CSV_INVALID_OPTION_RECORD_DELIMITER",
[
"Invalid option `record_delimiter`:",
"value must be a non empty string or buffer,",
`got ${JSON.stringify(options.record_delimiter)}`
],
options
);
}
options.record_delimiter = [options.record_delimiter];
} else if (!Array.isArray(options.record_delimiter)) {
throw new CsvError(
"CSV_INVALID_OPTION_RECORD_DELIMITER",
[
"Invalid option `record_delimiter`:",
"value must be a string, a buffer or array of string|buffer,",
`got ${JSON.stringify(options.record_delimiter)}`
],
options
);
}
options.record_delimiter = options.record_delimiter.map(function(rd, i) {
if (typeof rd !== "string" && !Buffer.isBuffer(rd)) {
throw new CsvError(
"CSV_INVALID_OPTION_RECORD_DELIMITER",
[
"Invalid option `record_delimiter`:",
"value must be a string, a buffer or array of string|buffer",
`at index ${i},`,
`got ${JSON.stringify(rd)}`
],
options
);
} else if (rd.length === 0) {
throw new CsvError(
"CSV_INVALID_OPTION_RECORD_DELIMITER",
[
"Invalid option `record_delimiter`:",
"value must be a non empty string or buffer",
`at index ${i},`,
`got ${JSON.stringify(rd)}`
],
options
);
}
if (typeof rd === "string") {
rd = Buffer.from(rd, options.encoding);
}
return rd;
});
if (typeof options.relax_column_count === "boolean") {
} else if (options.relax_column_count === void 0 || options.relax_column_count === null) {
options.relax_column_count = false;
} else {
throw new Error(
`Invalid Option: relax_column_count must be a boolean, got ${JSON.stringify(options.relax_column_count)}`
);
}
if (typeof options.relax_column_count_less === "boolean") {
} else if (options.relax_column_count_less === void 0 || options.relax_column_count_less === null) {
options.relax_column_count_less = false;
} else {
throw new Error(
`Invalid Option: relax_column_count_less must be a boolean, got ${JSON.stringify(options.relax_column_count_less)}`
);
}
if (typeof options.relax_column_count_more === "boolean") {
} else if (options.relax_column_count_more === void 0 || options.relax_column_count_more === null) {
options.relax_column_count_more = false;
} else {
throw new Error(
`Invalid Option: relax_column_count_more must be a boolean, got ${JSON.stringify(options.relax_column_count_more)}`
);
}
if (typeof options.relax_quotes === "boolean") {
} else if (options.relax_quotes === void 0 || options.relax_quotes === null) {
options.relax_quotes = false;
} else {
throw new Error(
`Invalid Option: relax_quotes must be a boolean, got ${JSON.stringify(options.relax_quotes)}`
);
}
if (typeof options.skip_empty_lines === "boolean") {
} else if (options.skip_empty_lines === void 0 || options.skip_empty_lines === null) {
options.skip_empty_lines = false;
} else {
throw new Error(
`Invalid Option: skip_empty_lines must be a boolean, got ${JSON.stringify(options.skip_empty_lines)}`
);
}
if (typeof options.skip_records_with_empty_values === "boolean") {
} else if (options.skip_records_with_empty_values === void 0 || options.skip_records_with_empty_values === null) {
options.skip_records_with_empty_values = false;
} else {
throw new Error(
`Invalid Option: skip_records_with_empty_values must be a boolean, got ${JSON.stringify(options.skip_records_with_empty_values)}`
);
}
if (typeof options.skip_records_with_error === "boolean") {
} else if (options.skip_records_with_error === void 0 || options.skip_records_with_error === null) {
options.skip_records_with_error = false;
} else {
throw new Error(
`Invalid Option: skip_records_with_error must be a boolean, got ${JSON.stringify(options.skip_records_with_error)}`
);
}
if (options.rtrim === void 0 || options.rtrim === null || options.rtrim === false) {
options.rtrim = false;
} else if (options.rtrim !== true) {
throw new Error(
`Invalid Option: rtrim must be a boolean, got ${JSON.stringify(options.rtrim)}`
);
}
if (options.ltrim === void 0 || options.ltrim === null || options.ltrim === false) {
options.ltrim = false;
} else if (options.ltrim !== true) {
throw new Error(
`Invalid Option: ltrim must be a boolean, got ${JSON.stringify(options.ltrim)}`
);
}
if (options.trim === void 0 || options.trim === null || options.trim === false) {
options.trim = false;
} else if (options.trim !== true) {
throw new Error(
`Invalid Option: trim must be a boolean, got ${JSON.stringify(options.trim)}`
);
}
if (options.trim === true && opts.ltrim !== false) {
options.ltrim = true;
} else if (options.ltrim !== true) {
options.ltrim = false;
}
if (options.trim === true && opts.rtrim !== false) {
options.rtrim = true;
} else if (options.rtrim !== true) {
options.rtrim = false;
}
if (options.to === void 0 || options.to === null) {
options.to = -1;
} else {
if (typeof options.to === "string" && /\d+/.test(options.to)) {
options.to = parseInt(options.to);
}
if (Number.isInteger(options.to)) {
if (options.to <= 0) {
throw new Error(
`Invalid Option: to must be a positive integer greater than 0, got ${JSON.stringify(opts.to)}`
);
}
} else {
throw new Error(
`Invalid Option: to must be an integer, got ${JSON.stringify(opts.to)}`
);
}
}
if (options.to_line === void 0 || options.to_line === null) {
options.to_line = -1;
} else {
if (typeof options.to_line === "string" && /\d+/.test(options.to_line)) {
options.to_line = parseInt(options.to_line);
}
if (Number.isInteger(options.to_line)) {
if (options.to_line <= 0) {
throw new Error(
`Invalid Option: to_line must be a positive integer greater than 0, got ${JSON.stringify(opts.to_line)}`
);
}
} else {
throw new Error(
`Invalid Option: to_line must be an integer, got ${JSON.stringify(opts.to_line)}`
);
}
}
return options;
};
// node_modules/csv-parse/lib/api/index.js
var isRecordEmpty = function(record) {
return record.every(
(field) => field == null || field.toString && field.toString().trim() === ""
);
};
var cr2 = 13;
var nl2 = 10;
var boms = {
// Note, the following are equals:
// Buffer.from("\ufeff")
// Buffer.from([239, 187, 191])
// Buffer.from('EFBBBF', 'hex')
utf8: Buffer.from([239, 187, 191]),
// Note, the following are equals:
// Buffer.from "\ufeff", 'utf16le
// Buffer.from([255, 254])
utf16le: Buffer.from([255, 254])
};
var transform = function(original_options = {}) {
const info = {
bytes: 0,
comment_lines: 0,
empty_lines: 0,
invalid_field_length: 0,
lines: 1,
records: 0
};
const options = normalize_options(original_options);
return {
info,
original_options,
options,
state: init_state(options),
__needMoreData: function(i, bufLen, end) {
if (end) return false;
const { encoding, escape, quote } = this.options;
const { quoting, needMoreDataSize, recordDelimiterMaxLength } = this.state;
const numOfCharLeft = bufLen - i - 1;
const requiredLength = Math.max(
needMoreDataSize,
// Skip if the remaining buffer smaller than record delimiter
// If "record_delimiter" is yet to be discovered:
// 1. It is equals to `[]` and "recordDelimiterMaxLength" equals `0`
// 2. We set the length to windows line ending in the current encoding
// Note, that encoding is known from user or bom discovery at that point
// recordDelimiterMaxLength,
recordDelimiterMaxLength === 0 ? Buffer.from("\r\n", encoding).length : recordDelimiterMaxLength,
// Skip if remaining buffer can be an escaped quote
quoting ? (escape === null ? 0 : escape.length) + quote.length : 0,
// Skip if remaining buffer can be record delimiter following the closing quote
quoting ? quote.length + recordDelimiterMaxLength : 0
);
return numOfCharLeft < requiredLength;
},
// Central parser implementation
parse: function(nextBuf, end, push, close) {
const {
bom,
comment_no_infix,
encoding,
from_line,
ltrim,
max_record_size,
raw,
relax_quotes,
rtrim,
skip_empty_lines,
to,
to_line
} = this.options;
let { comment, escape, quote, record_delimiter } = this.options;
const { bomSkipped, previousBuf, rawBuffer, escapeIsQuote } = this.state;
let buf;
if (previousBuf === void 0) {
if (nextBuf === void 0) {
close();
return;
} else {
buf = nextBuf;
}
} else if (previousBuf !== void 0 && nextBuf === void 0) {
buf = previousBuf;
} else {
buf = Buffer.concat([previousBuf, nextBuf]);
}
if (bomSkipped === false) {
if (bom === false) {
this.state.bomSkipped = true;
} else if (buf.length < 3) {
if (end === false) {
this.state.previousBuf = buf;
return;
}
} else {
for (const encoding2 in boms) {
if (boms[encoding2].compare(buf, 0, boms[encoding2].length) === 0) {
const bomLength = boms[encoding2].length;
this.state.bufBytesStart += bomLength;
buf = buf.slice(bomLength);
this.options = normalize_options({
...this.original_options,
encoding: encoding2
});
({ comment, escape, quote } = this.options);
break;
}
}
this.state.bomSkipped = true;
}
}
const bufLen = buf.length;
let pos;
for (pos = 0; pos < bufLen; pos++) {
if (this.__needMoreData(pos, bufLen, end)) {
break;
}
if (this.state.wasRowDelimiter === true) {
this.info.lines++;
this.state.wasRowDelimiter = false;
}
if (to_line !== -1 && this.info.lines > to_line) {
this.state.stop = true;
close();
return;
}
if (this.state.quoting === false && record_delimiter.length === 0) {
const record_delimiterCount = this.__autoDiscoverRecordDelimiter(
buf,
pos
);
if (record_delimiterCount) {
record_delimiter = this.options.record_delimiter;
}
}
const chr = buf[pos];
if (raw === true) {
rawBuffer.append(chr);
}
if ((chr === cr2 || chr === nl2) && this.state.wasRowDelimiter === false) {
this.state.wasRowDelimiter = true;
}
if (this.state.escaping === true) {
this.state.escaping = false;
} else {
if (escape !== null && this.state.quoting === true && this.__isEscape(buf, pos, chr) && pos + escape.length < bufLen) {
if (escapeIsQuote) {
if (this.__isQuote(buf, pos + escape.length)) {
this.state.escaping = true;
pos += escape.length - 1;
continue;
}
} else {
this.state.escaping = true;
pos += escape.length - 1;
continue;
}
}
if (this.state.commenting === false && this.__isQuote(buf, pos)) {
if (this.state.quoting === true) {
const nextChr = buf[pos + quote.length];
const isNextChrTrimable = rtrim && this.__isCharTrimable(buf, pos + quote.length);
const isNextChrComment = comment !== null && this.__compareBytes(comment, buf, pos + quote.length, nextChr);
const isNextChrDelimiter = this.__isDelimiter(
buf,
pos + quote.length,
nextChr
);
const isNextChrRecordDelimiter = record_delimiter.length === 0 ? this.__autoDiscoverRecordDelimiter(buf, pos + quote.length) : this.__isRecordDelimiter(nextChr, buf, pos + quote.length);
if (escape !== null && this.__isEscape(buf, pos, chr) && this.__isQuote(buf, pos + escape.length)) {
pos += escape.length - 1;
} else if (!nextChr || isNextChrDelimiter || isNextChrRecordDelimiter || isNextChrComment || isNextChrTrimable) {
this.state.quoting = false;
this.state.wasQuoting = true;
pos += quote.length - 1;
continue;
} else if (relax_quotes === false) {
const err = this.__error(
new CsvError(
"CSV_INVALID_CLOSING_QUOTE",
[
"Invalid Closing Quote:",
`got "${String.fromCharCode(nextChr)}"`,
`at line ${this.info.lines}`,
"instead of delimiter, record delimiter, trimable character",
"(if activated) or comment"
],
this.options,
this.__infoField()
)
);
if (err !== void 0) return err;
} else {
this.state.quoting = false;
this.state.wasQuoting = true;
this.state.field.prepend(quote);
pos += quote.length - 1;
}
} else {
if (this.state.field.length !== 0) {
if (relax_quotes === false) {
const info2 = this.__infoField();
const bom2 = Object.keys(boms).map(
(b) => boms[b].equals(this.state.field.toString()) ? b : false
).filter(Boolean)[0];
const err = this.__error(
new CsvError(
"INVALID_OPENING_QUOTE",
[
"Invalid Opening Quote:",
`a quote is found on field ${JSON.stringify(info2.column)} at line ${info2.lines}, value is ${JSON.stringify(this.state.field.toString(encoding))}`,
bom2 ? `(${bom2} bom)` : void 0
],
this.options,
info2,
{
field: this.state.field
}
)
);
if (err !== void 0) return err;
}
} else {
this.state.quoting = true;
pos += quote.length - 1;
continue;
}
}
}
if (this.state.quoting === false) {
const recordDelimiterLength = this.__isRecordDelimiter(
chr,
buf,
pos
);
if (recordDelimiterLength !== 0) {
const skipCommentLine = this.state.commenting && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0;
if (skipCommentLine) {
this.info.comment_lines++;
} else {
if (this.state.enabled === false && this.info.lines + (this.state.wasRowDelimiter === true ? 1 : 0) >= from_line) {
this.state.enabled = true;
this.__resetField();
this.__resetRecord();
pos += recordDelimiterLength - 1;
continue;
}
if (skip_empty_lines === true && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0) {
this.info.empty_lines++;
pos += recordDelimiterLength - 1;
continue;
}
this.info.bytes = this.state.bufBytesStart + pos;
const errField = this.__onField();
if (errField !== void 0) return errField;
this.info.bytes = this.state.bufBytesStart + pos + recordDelimiterLength;
const errRecord = this.__onRecord(push);
if (errRecord !== void 0) return errRecord;
if (to !== -1 && this.info.records >= to) {
this.state.stop = true;
close();
return;
}
}
this.state.commenting = false;
pos += recordDelimiterLength - 1;
continue;
}
if (this.state.commenting) {
continue;
}
if (comment !== null && (comment_no_infix === false || this.state.record.length === 0 && this.state.field.length === 0)) {
const commentCount = this.__compareBytes(comment, buf, pos, chr);
if (commentCount !== 0) {
this.state.commenting = true;
continue;
}
}
const delimiterLength = this.__isDelimiter(buf, pos, chr);
if (delimiterLength !== 0) {
this.info.bytes = this.state.bufBytesStart + pos;
const errField = this.__onField();
if (errField !== void 0) return errField;
pos += delimiterLength - 1;
continue;
}
}
}
if (this.state.commenting === false) {
if (max_record_size !== 0 && this.state.record_length + this.state.field.length > max_record_size) {
return this.__error(
new CsvError(
"CSV_MAX_RECORD_SIZE",
[
"Max Record Size:",
"record exceed the maximum number of tolerated bytes",
`of ${max_record_size}`,
`at line ${this.info.lines}`
],
this.options,
this.__infoField()
)
);
}
}
const lappend = ltrim === false || this.state.quoting === true || this.state.field.length !== 0 || !this.__isCharTrimable(buf, pos);
const rappend = rtrim === false || this.state.wasQuoting === false;
if (lappend === true && rappend === true) {
this.state.field.append(chr);
} else if (rtrim === true && !this.__isCharTrimable(buf, pos)) {
return this.__error(
new CsvError(
"CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE",
[
"Invalid Closing Quote:",
"found non trimable byte after quote",
`at line ${this.info.lines}`
],
this.options,
this.__infoField()
)
);
} else {
if (lappend === false) {
pos += this.__isCharTrimable(buf, pos) - 1;
}
continue;
}
}
if (end === true) {
if (this.state.quoting === true) {
const err = this.__error(
new CsvError(
"CSV_QUOTE_NOT_CLOSED",
[
"Quote Not Closed:",
`the parsing is finished with an opening quote at line ${this.info.lines}`
],
this.options,
this.__infoField()
)
);
if (err !== void 0) return err;
} else {
if (this.state.wasQuoting === true || this.state.record.length !== 0 || this.state.field.length !== 0) {
this.info.bytes = this.state.bufBytesStart + pos;
const errField = this.__onField();
if (errField !== void 0) return errField;
const errRecord = this.__onRecord(push);
if (errRecord !== void 0) return errRecord;
} else if (this.state.wasRowDelimiter === true) {
this.info.empty_lines++;
} else if (this.state.commenting === true) {
this.info.comment_lines++;
}
}
} else {
this.state.bufBytesStart += pos;
this.state.previousBuf = buf.slice(pos);
}
if (this.state.wasRowDelimiter === true) {
this.info.lines++;
this.state.wasRowDelimiter = false;
}
},
__onRecord: function(push) {
const {
columns,
group_columns_by_name,
encoding,
info: info2,
from,
relax_column_count,
relax_column_count_less,
relax_column_count_more,
raw,
skip_records_with_empty_values
} = this.options;
const { enabled, record } = this.state;
if (enabled === false) {
return this.__resetRecord();
}
const recordLength = record.length;
if (columns === true) {
if (skip_records_with_empty_values === true && isRecordEmpty(record)) {
this.__resetRecord();
return;
}
return this.__firstLineToColumns(record);
}
if (columns === false && this.info.records === 0) {
this.state.expectedRecordLength = recordLength;
}
if (recordLength !== this.state.expectedRecordLength) {
const err = columns === false ? new CsvError(
"CSV_RECORD_INCONSISTENT_FIELDS_LENGTH",
[
"Invalid Record Length:",
`expect ${this.state.expectedRecordLength},`,
`got ${recordLength} on line ${this.info.lines}`
],
this.options,
this.__infoField(),
{
record
}
) : new CsvError(
"CSV_RECORD_INCONSISTENT_COLUMNS",
[
"Invalid Record Length:",
`columns length is ${columns.length},`,
// rename columns
`got ${recordLength} on line ${this.info.lines}`
],
this.options,
this.__infoField(),
{
record
}
);
if (relax_column_count === true || relax_column_count_less === true && recordLength < this.state.expectedRecordLength || relax_column_count_more === true && recordLength > this.state.expectedRecordLength) {
this.info.invalid_field_length++;
this.state.error = err;
} else {
const finalErr = this.__error(err);
if (finalErr) return finalErr;
}
}
if (skip_records_with_empty_values === true && isRecordEmpty(record)) {
this.__resetRecord();
return;
}
if (this.state.recordHasError === true) {
this.__resetRecord();
this.state.recordHasError = false;
return;
}
this.info.records++;
if (from === 1 || this.info.records >= from) {
const { objname } = this.options;
if (columns !== false) {
const obj = {};
for (let i = 0, l = record.length; i < l; i++) {
if (columns[i] === void 0 || columns[i].disabled) continue;
if (group_columns_by_name === true && obj[columns[i].name] !== void 0) {
if (Array.isArray(obj[columns[i].name])) {
obj[columns[i].name] = obj[columns[i].name].concat(record[i]);
} else {
obj[columns[i].name] = [obj[columns[i].name], record[i]];
}
} else {
obj[columns[i].name] = record[i];
}
}
if (raw === true || info2 === true) {
const extRecord = Object.assign(
{ record: obj },
raw === true ? { raw: this.state.rawBuffer.toString(encoding) } : {},
info2 === true ? { info: this.__infoRecord() } : {}
);
const err = this.__push(
objname === void 0 ? extRecord : [obj[objname], extRecord],
push
);
if (err) {
return err;
}
} else {
const err = this.__push(
objname === void 0 ? obj : [obj[objname], obj],
push
);
if (err) {
return err;
}
}
} else {
if (raw === true || info2 === true) {
const extRecord = Object.assign(
{ record },
raw === true ? { raw: this.state.rawBuffer.toString(encoding) } : {},
info2 === true ? { info: this.__infoRecord() } : {}
);
const err = this.__push(
objname === void 0 ? extRecord : [record[objname], extRecord],
push
);
if (err) {
return err;
}
} else {
const err = this.__push(
objname === void 0 ? record : [record[objname], record],
push
);
if (err) {
return err;
}
}
}
}
this.__resetRecord();
},
__firstLineToColumns: function(record) {
const { firstLineToHeaders } = this.state;
try {
const headers = firstLineToHeaders === void 0 ? record : firstLineToHeaders.call(null, record);
if (!Array.isArray(headers)) {
return this.__error(
new CsvError(
"CSV_INVALID_COLUMN_MAPPING",
[
"Invalid Column Mapping:",
"expect an array from column function,",
`got ${JSON.stringify(headers)}`
],
this.options,
this.__infoField(),
{
headers
}
)
);
}
const normalizedHeaders = normalize_columns_array(headers);
this.state.expectedRecordLength = normalizedHeaders.length;
this.options.columns = normalizedHeaders;
this.__resetRecord();
return;
} catch (err) {
return err;
}
},
__resetRecord: function() {
if (this.options.raw === true) {
this.state.rawBuffer.reset();
}
this.state.error = void 0;
this.state.record = [];
this.state.record_length = 0;
},
__onField: function() {
const { cast, encoding, rtrim, max_record_size } = this.options;
const { enabled, wasQuoting } = this.state;
if (enabled === false) {
return this.__resetField();
}
let field = this.state.field.toString(encoding);
if (rtrim === true && wasQuoting === false) {
field = field.trimRight();
}
if (cast === true) {
const [err, f] = this.__cast(field);
if (err !== void 0) return err;
field = f;
}
this.state.record.push(field);
if (max_record_size !== 0 && typeof field === "string") {
this.state.record_length += field.length;
}
this.__resetField();
},
__resetField: function() {
this.state.field.reset();
this.state.wasQuoting = false;
},
__push: function(record, push) {
const { on_record } = this.options;
if (on_record !== void 0) {
const info2 = this.__infoRecord();
try {
record = on_record.call(null, record, info2);
} catch (err) {
return err;
}
if (record === void 0 || record === null) {
return;
}
}
push(record);
},
// Return a tuple with the error and the casted value
__cast: function(field) {
const { columns, relax_column_count } = this.options;
const isColumns = Array.isArray(columns);
if (isColumns === true && relax_column_count && this.options.columns.length <= this.state.record.length) {
return [void 0, void 0];
}
if (this.state.castField !== null) {
try {
const info2 = this.__infoField();
return [void 0, this.state.castField.call(null, field, info2)];
} catch (err) {
return [err];
}
}
if (this.__isFloat(field)) {
return [void 0, parseFloat(field)];
} else if (this.options.cast_date !== false) {
const info2 = this.__infoField();
return [void 0, this.options.cast_date.call(null, field, info2)];
}
return [void 0, field];
},
// Helper to test if a character is a space or a line delimiter
__isCharTrimable: function(buf, pos) {
const isTrim = (buf2, pos2) => {
const { timchars } = this.state;
loop1: for (let i = 0; i < timchars.length; i++) {
const timchar = timchars[i];
for (let j = 0; j < timchar.length; j++) {
if (timchar[j] !== buf2[pos2 + j]) continue loop1;
}
return timchar.length;
}
return 0;
};
return isTrim(buf, pos);
},
// Keep it in case we implement the `cast_int` option
// __isInt(value){
// // return Number.isInteger(parseInt(value))
// // return !isNaN( parseInt( obj ) );
// return /^(\-|\+)?[1-9][0-9]*$/.test(value)
// }
__isFloat: function(value) {
return value - parseFloat(value) + 1 >= 0;
},
__compareBytes: function(sourceBuf, targetBuf, targetPos, firstByte) {
if (sourceBuf[0] !== firstByte) return 0;
const sourceLength = sourceBuf.length;
for (let i = 1; i < sourceLength; i++) {
if (sourceBuf[i] !== targetBuf[targetPos + i]) return 0;
}
return sourceLength;
},
__isDelimiter: function(buf, pos, chr) {
const { delimiter, ignore_last_delimiters } = this.options;
if (ignore_last_delimiters === true && this.state.record.length === this.options.columns.length - 1) {
return 0;
} else if (ignore_last_delimiters !== false && typeof ignore_last_delimiters === "number" && this.state.record.length === ignore_last_delimiters - 1) {
return 0;
}
loop1: for (let i = 0; i < delimiter.length; i++) {
const del = delimiter[i];
if (del[0] === chr) {
for (let j = 1; j < del.length; j++) {
if (del[j] !== buf[pos + j]) continue loop1;
}
return del.length;
}
}
return 0;
},
__isRecordDelimiter: function(chr, buf, pos) {
const { record_delimiter } = this.options;
const recordDelimiterLength = record_delimiter.length;
loop1: for (let i = 0; i < recordDelimiterLength; i++) {
const rd = record_delimiter[i];
const rdLength = rd.length;
if (rd[0] !== chr) {
continue;
}
for (let j = 1; j < rdLength; j++) {
if (rd[j] !== buf[pos + j]) {
continue loop1;
}
}
return rd.length;
}
return 0;
},
__isEscape: function(buf, pos, chr) {
const { escape } = this.options;
if (escape === null) return false;
const l = escape.length;
if (escape[0] === chr) {
for (let i = 0; i < l; i++) {
if (escape[i] !== buf[pos + i]) {
return false;
}
}
return true;
}
return false;
},
__isQuote: function(buf, pos) {
const { quote } = this.options;
if (quote === null) return false;
const l = quote.length;
for (let i = 0; i < l; i++) {
if (quote[i] !== buf[pos + i]) {
return false;
}
}
return true;
},
__autoDiscoverRecordDelimiter: function(buf, pos) {
const { encoding } = this.options;
const rds = [
// Important, the windows line ending must be before mac os 9
Buffer.from("\r\n", encoding),
Buffer.from("\n", encoding),
Buffer.from("\r", encoding)
];
loop: for (let i = 0; i < rds.length; i++) {
const l = rds[i].length;
for (let j = 0; j < l; j++) {
if (rds[i][j] !== buf[pos + j]) {
continue loop;
}
}
this.options.record_delimiter.push(rds[i]);
this.state.recordDelimiterMaxLength = rds[i].length;
return rds[i].length;
}
return 0;
},
__error: function(msg) {
const { encoding, raw, skip_records_with_error } = this.options;
const err = typeof msg === "string" ? new Error(msg) : msg;
if (skip_records_with_error) {
this.state.recordHasError = true;
if (this.options.on_skip !== void 0) {
this.options.on_skip(
err,
raw ? this.state.rawBuffer.toString(encoding) : void 0
);
}
return void 0;
} else {
return err;
}
},
__infoDataSet: function() {
return {
...this.info,
columns: this.options.columns
};
},
__infoRecord: function() {
const { columns, raw, encoding } = this.options;
return {
...this.__infoDataSet(),
error: this.state.error,
header: columns === true,
index: this.state.record.length,
raw: raw ? this.state.rawBuffer.toString(encoding) : void 0
};
},
__infoField: function() {
const { columns } = this.options;
const isColumns = Array.isArray(columns);
return {
...this.__infoRecord(),
column: isColumns === true ? columns.length > this.state.record.length ? columns[this.state.record.length].name : null : this.state.record.length,
quoting: this.state.wasQuoting
};
}
};
};
// node_modules/csv-parse/lib/sync.js
var parse = function(data, opts = {}) {
if (typeof data === "string") {
data = Buffer.from(data);
}
const records = opts && opts.objname ? {} : [];
const parser = transform(opts);
const push = (record) => {
if (parser.options.objname === void 0) records.push(record);
else {
records[record[0]] = record[1];
}
};
const close = () => {
};
const err1 = parser.parse(data, false, push, close);
if (err1 !== void 0) throw err1;
const err2 = parser.parse(void 0, true, push, close);
if (err2 !== void 0) throw err2;
return records;
};
// node_modules/csv-stringify/lib/utils/get.js
var charCodeOfDot = ".".charCodeAt(0);
var reEscapeChar = /\\(\\)?/g;
var rePropName = RegExp(
// Match anything that isn't a dot or bracket.
`[^.[\\]]+|\\[(?:([^"'][^[]*)|(["'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))`,
"g"
);
var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/;
var reIsPlainProp = /^\w*$/;
var getTag = function(value) {
return Object.prototype.toString.call(value);
};
var isSymbol2 = function(value) {
const type = typeof value;
return type === "symbol" || type === "object" && value && getTag(value) === "[object Symbol]";
};
var isKey = function(value, object) {
if (Array.isArray(value)) {
return false;
}
const type = typeof value;
if (type === "number" || type === "symbol" || type === "boolean" || !value || isSymbol2(value)) {
return true;
}
return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object);
};
var stringToPath = function(string) {
const result = [];
if (string.charCodeAt(0) === charCodeOfDot) {
result.push("");
}
string.replace(rePropName, function(match, expression, quote, subString) {
let key = match;
if (quote) {
key = subString.replace(reEscapeChar, "$1");
} else if (expression) {
key = expression.trim();
}
result.push(key);
});
return result;
};
var castPath = function(value, object) {
if (Array.isArray(value)) {
return value;
} else {
return isKey(value, object) ? [value] : stringToPath(value);
}
};
var toKey = function(value) {
if (typeof value === "string" || isSymbol2(value)) return value;
const result = `${value}`;
return result == "0" && 1 / value == -Infinity ? "-0" : result;
};
var get2 = function(object, path4) {
path4 = castPath(path4, object);
let index = 0;
const length = path4.length;
while (object != null && index < length) {
object = object[toKey(path4[index++])];
}
return index && index === length ? object : void 0;
};
// node_modules/csv-stringify/lib/utils/is_object.js
var is_object2 = function(obj) {
return typeof obj === "object" && obj !== null && !Array.isArray(obj);
};
// node_modules/csv-stringify/lib/api/normalize_columns.js
var normalize_columns = function(columns) {
if (columns === void 0 || columns === null) {
return [void 0, void 0];
}
if (typeof columns !== "object") {
return [Error('Invalid option "columns": expect an array or an object')];
}
if (!Array.isArray(columns)) {
const newcolumns = [];
for (const k in columns) {
newcolumns.push({
key: k,
header: columns[k]
});
}
columns = newcolumns;
} else {
const newcolumns = [];
for (const column of columns) {
if (typeof column === "string") {
newcolumns.push({
key: column,
header: column
});
} else if (typeof column === "object" && column !== null && !Array.isArray(column)) {
if (!column.key) {
return [
Error('Invalid column definition: property "key" is required')
];
}
if (column.header === void 0) {
column.header = column.key;
}
newcolumns.push(column);
} else {
return [
Error("Invalid column definition: expect a string or an object")
];
}
}
columns = newcolumns;
}
return [void 0, columns];
};
// node_modules/csv-stringify/lib/api/CsvError.js
var CsvError2 = class _CsvError extends Error {
constructor(code, message, ...contexts) {
if (Array.isArray(message)) message = message.join(" ");
super(message);
if (Error.captureStackTrace !== void 0) {
Error.captureStackTrace(this, _CsvError);
}
this.code = code;
for (const context of contexts) {
for (const key in context) {
const value = context[key];
this[key] = Buffer.isBuffer(value) ? value.toString() : value == null ? value : JSON.parse(JSON.stringify(value));
}
}
}
};
// node_modules/csv-stringify/lib/utils/underscore.js
var underscore2 = function(str) {
return str.replace(/([A-Z])/g, function(_, match) {
return "_" + match.toLowerCase();
});
};
// node_modules/csv-stringify/lib/api/normalize_options.js
var normalize_options2 = function(opts) {
const options = {};
for (const opt in opts) {
options[underscore2(opt)] = opts[opt];
}
if (options.bom === void 0 || options.bom === null || options.bom === false) {
options.bom = false;
} else if (options.bom !== true) {
return [
new CsvError2("CSV_OPTION_BOOLEAN_INVALID_TYPE", [
"option `bom` is optional and must be a boolean value,",
`got ${JSON.stringify(options.bom)}`
])
];
}
if (options.delimiter === void 0 || options.delimiter === null) {
options.delimiter = ",";
} else if (Buffer.isBuffer(options.delimiter)) {
options.delimiter = options.delimiter.toString();
} else if (typeof options.delimiter !== "string") {
return [
new CsvError2("CSV_OPTION_DELIMITER_INVALID_TYPE", [
"option `delimiter` must be a buffer or a string,",
`got ${JSON.stringify(options.delimiter)}`
])
];
}
if (options.quote === void 0 || options.quote === null) {
options.quote = '"';
} else if (options.quote === true) {
options.quote = '"';
} else if (options.quote === false) {
options.quote = "";
} else if (Buffer.isBuffer(options.quote)) {
options.quote = options.quote.toString();
} else if (typeof options.quote !== "string") {
return [
new CsvError2("CSV_OPTION_QUOTE_INVALID_TYPE", [
"option `quote` must be a boolean, a buffer or a string,",
`got ${JSON.stringify(options.quote)}`
])
];
}
if (options.quoted === void 0 || options.quoted === null) {
options.quoted = false;
} else {
}
if (options.escape_formulas === void 0 || options.escape_formulas === null) {
options.escape_formulas = false;
} else if (typeof options.escape_formulas !== "boolean") {
return [
new CsvError2("CSV_OPTION_ESCAPE_FORMULAS_INVALID_TYPE", [
"option `escape_formulas` must be a boolean,",
`got ${JSON.stringify(options.escape_formulas)}`
])
];
}
if (options.quoted_empty === void 0 || options.quoted_empty === null) {
options.quoted_empty = void 0;
} else {
}
if (options.quoted_match === void 0 || options.quoted_match === null || options.quoted_match === false) {
options.quoted_match = null;
} else if (!Array.isArray(options.quoted_match)) {
options.quoted_match = [options.quoted_match];
}
if (options.quoted_match) {
for (const quoted_match of options.quoted_match) {
const isString2 = typeof quoted_match === "string";
const isRegExp2 = quoted_match instanceof RegExp;
if (!isString2 && !isRegExp2) {
return [
new CsvError2("CSV_OPTION_QUOTED_MATCH", [
"option `quoted_match` must be a string or a regex,",
`got ${JSON.stringify(options.quoted_match)}`
])
];
}
}
}
if (options.quoted_string === void 0 || options.quoted_string === null) {
options.quoted_string = false;
} else {
}
if (options.eof === void 0 || options.eof === null) {
options.eof = true;
} else {
}
if (options.escape === void 0 || options.escape === null) {
options.escape = '"';
} else if (Buffer.isBuffer(options.escape)) {
options.escape = options.escape.toString();
} else if (typeof options.escape !== "string") {
return [
Error(
`Invalid Option: escape must be a buffer or a string, got ${JSON.stringify(options.escape)}`
)
];
}
if (options.escape.length > 1) {
return [
Error(
`Invalid Option: escape must be one character, got ${options.escape.length} characters`
)
];
}
if (options.header === void 0 || options.header === null || options.header === false) {
options.header = false;
} else if (options.header !== true) {
throw new CsvError2(
"CSV_INVALID_OPTION_HEADER",
[
"option `header` is expected to be a boolean,",
`got ${JSON.stringify(options.header)}`
],
options
);
}
if (options.header_as_comment === void 0 || options.header_as_comment === null || options.header_as_comment === false) {
options.header_as_comment = false;
} else if (options.header_as_comment === true) {
options.header_as_comment = "#";
} else if (Buffer.isBuffer(options.header_as_comment)) {
options.header_as_comment = options.header_as_comment.toString();
} else if (typeof options.header_as_comment !== "string") {
throw new CsvError2(
"CSV_INVALID_OPTION_HEADER_AS_COMMENT",
[
"option `header_as_comment` must be a boolean, a string or a buffer,",
`got ${JSON.stringify(options.header_as_comment)}`
],
options
);
}
const [errColumns, columns] = normalize_columns(options.columns);
if (errColumns !== void 0) return [errColumns];
options.columns = columns;
if (options.quoted === void 0 || options.quoted === null) {
options.quoted = false;
} else {
}
if (options.cast === void 0 || options.cast === null) {
options.cast = {};
} else {
}
if (options.cast.bigint === void 0 || options.cast.bigint === null) {
options.cast.bigint = (value) => "" + value;
}
if (options.cast.boolean === void 0 || options.cast.boolean === null) {
options.cast.boolean = (value) => value ? "1" : "";
}
if (options.cast.date === void 0 || options.cast.date === null) {
options.cast.date = (value) => "" + value.getTime();
}
if (options.cast.number === void 0 || options.cast.number === null) {
options.cast.number = (value) => "" + value;
}
if (options.cast.object === void 0 || options.cast.object === null) {
options.cast.object = (value) => JSON.stringify(value);
}
if (options.cast.string === void 0 || options.cast.string === null) {
options.cast.string = function(value) {
return value;
};
}
if (options.on_record !== void 0 && typeof options.on_record !== "function") {
return [Error(`Invalid Option: "on_record" must be a function.`)];
}
if (options.record_delimiter === void 0 || options.record_delimiter === null) {
options.record_delimiter = "\n";
} else if (Buffer.isBuffer(options.record_delimiter)) {
options.record_delimiter = options.record_delimiter.toString();
} else if (typeof options.record_delimiter !== "string") {
return [
Error(
`Invalid Option: record_delimiter must be a buffer or a string, got ${JSON.stringify(options.record_delimiter)}`
)
];
}
switch (options.record_delimiter) {
case "unix":
options.record_delimiter = "\n";
break;
case "mac":
options.record_delimiter = "\r";
break;
case "windows":
options.record_delimiter = "\r\n";
break;
case "ascii":
options.record_delimiter = "";
break;
case "unicode":
options.record_delimiter = "\u2028";
break;
}
return [void 0, options];
};
// node_modules/csv-stringify/lib/api/index.js
var bom_utf8 = Buffer.from([239, 187, 191]);
var stringifier = function(options, state, info) {
return {
options,
state,
info,
__transform: function(chunk, push) {
if (!Array.isArray(chunk) && typeof chunk !== "object") {
return Error(
`Invalid Record: expect an array or an object, got ${JSON.stringify(chunk)}`
);
}
if (this.info.records === 0) {
if (Array.isArray(chunk)) {
if (this.options.header === true && this.options.columns === void 0) {
return Error(
"Undiscoverable Columns: header option requires column option or object records"
);
}
} else if (this.options.columns === void 0) {
const [err2, columns] = normalize_columns(Object.keys(chunk));
if (err2) return;
this.options.columns = columns;
}
}
if (this.info.records === 0) {
this.bom(push);
const err2 = this.headers(push);
if (err2) return err2;
}
try {
if (this.options.on_record) {
this.options.on_record(chunk, this.info.records);
}
} catch (err2) {
return err2;
}
let err, chunk_string;
if (this.options.eof) {
[err, chunk_string] = this.stringify(chunk);
if (err) return err;
if (chunk_string === void 0) {
return;
} else {
chunk_string = chunk_string + this.options.record_delimiter;
}
} else {
[err, chunk_string] = this.stringify(chunk);
if (err) return err;
if (chunk_string === void 0) {
return;
} else {
if (this.options.header || this.info.records) {
chunk_string = this.options.record_delimiter + chunk_string;
}
}
}
this.info.records++;
push(chunk_string);
},
stringify: function(chunk, chunkIsHeader = false) {
if (typeof chunk !== "object") {
return [void 0, chunk];
}
const { columns } = this.options;
const record = [];
if (Array.isArray(chunk)) {
if (columns) {
chunk.splice(columns.length);
}
for (let i = 0; i < chunk.length; i++) {
const field = chunk[i];
const [err, value] = this.__cast(field, {
index: i,
column: i,
records: this.info.records,
header: chunkIsHeader
});
if (err) return [err];
record[i] = [value, field];
}
} else {
for (let i = 0; i < columns.length; i++) {
const field = get2(chunk, columns[i].key);
const [err, value] = this.__cast(field, {
index: i,
column: columns[i].key,
records: this.info.records,
header: chunkIsHeader
});
if (err) return [err];
record[i] = [value, field];
}
}
let csvrecord = "";
for (let i = 0; i < record.length; i++) {
let options2, err;
let [value, field] = record[i];
if (typeof value === "string") {
options2 = this.options;
} else if (is_object2(value)) {
options2 = value;
value = options2.value;
delete options2.value;
if (typeof value !== "string" && value !== void 0 && value !== null) {
if (err)
return [
Error(
`Invalid Casting Value: returned value must return a string, null or undefined, got ${JSON.stringify(value)}`
)
];
}
options2 = { ...this.options, ...options2 };
[err, options2] = normalize_options2(options2);
if (err !== void 0) {
return [err];
}
} else if (value === void 0 || value === null) {
options2 = this.options;
} else {
return [
Error(
`Invalid Casting Value: returned value must return a string, an object, null or undefined, got ${JSON.stringify(value)}`
)
];
}
const {
delimiter,
escape,
quote,
quoted,
quoted_empty,
quoted_string,
quoted_match,
record_delimiter,
escape_formulas
} = options2;
if ("" === value && "" === field) {
let quotedMatch = quoted_match && quoted_match.filter((quoted_match2) => {
if (typeof quoted_match2 === "string") {
return value.indexOf(quoted_match2) !== -1;
} else {
return quoted_match2.test(value);
}
});
quotedMatch = quotedMatch && quotedMatch.length > 0;
const shouldQuote = quotedMatch || true === quoted_empty || true === quoted_string && false !== quoted_empty;
if (shouldQuote === true) {
value = quote + value + quote;
}
csvrecord += value;
} else if (value) {
if (typeof value !== "string") {
return [
Error(
`Formatter must return a string, null or undefined, got ${JSON.stringify(value)}`
)
];
}
const containsdelimiter = delimiter.length && value.indexOf(delimiter) >= 0;
const containsQuote = quote !== "" && value.indexOf(quote) >= 0;
const containsEscape = value.indexOf(escape) >= 0 && escape !== quote;
const containsRecordDelimiter = value.indexOf(record_delimiter) >= 0;
const quotedString = quoted_string && typeof field === "string";
let quotedMatch = quoted_match && quoted_match.filter((quoted_match2) => {
if (typeof quoted_match2 === "string") {
return value.indexOf(quoted_match2) !== -1;
} else {
return quoted_match2.test(value);
}
});
quotedMatch = quotedMatch && quotedMatch.length > 0;
if (escape_formulas) {
switch (value[0]) {
case "=":
case "+":
case "-":
case "@":
case " ":
case "\r":
case "\uFF1D":
// Unicode '='
case "\uFF0B":
// Unicode '+'
case "\uFF0D":
// Unicode '-'
case "\uFF20":
value = `'${value}`;
break;
}
}
const shouldQuote = containsQuote === true || containsdelimiter || containsRecordDelimiter || quoted || quotedString || quotedMatch;
if (shouldQuote === true && containsEscape === true) {
const regexp = escape === "\\" ? new RegExp(escape + escape, "g") : new RegExp(escape, "g");
value = value.replace(regexp, escape + escape);
}
if (containsQuote === true) {
const regexp = new RegExp(quote, "g");
value = value.replace(regexp, escape + quote);
}
if (shouldQuote === true) {
value = quote + value + quote;
}
csvrecord += value;
} else if (quoted_empty === true || field === "" && quoted_string === true && quoted_empty !== false) {
csvrecord += quote + quote;
}
if (i !== record.length - 1) {
csvrecord += delimiter;
}
}
return [void 0, csvrecord];
},
bom: function(push) {
if (this.options.bom !== true) {
return;
}
push(bom_utf8);
},
headers: function(push) {
if (this.options.header === false) {
return;
}
if (this.options.columns === void 0) {
return;
}
let err;
let headers = this.options.columns.map((column) => column.header);
if (this.options.eof) {
[err, headers] = this.stringify(headers, true);
headers += this.options.record_delimiter;
} else {
[err, headers] = this.stringify(headers);
}
if (err) return err;
if (this.options.header_as_comment) {
headers = this.options.header_as_comment + " " + headers;
}
push(headers);
},
__cast: function(value, context) {
const type = typeof value;
try {
if (type === "string") {
return [void 0, this.options.cast.string(value, context)];
} else if (type === "bigint") {
return [void 0, this.options.cast.bigint(value, context)];
} else if (type === "number") {
return [void 0, this.options.cast.number(value, context)];
} else if (type === "boolean") {
return [void 0, this.options.cast.boolean(value, context)];
} else if (value instanceof Date) {
return [void 0, this.options.cast.date(value, context)];
} else if (type === "object" && value !== null) {
return [void 0, this.options.cast.object(value, context)];
} else {
return [void 0, value, value];
}
} catch (err) {
return [err];
}
}
};
};
// node_modules/csv-stringify/lib/sync.js
var stringify = function(records, opts = {}) {
const data = [];
const [err, options] = normalize_options2(opts);
if (err !== void 0) throw err;
const state = {
stop: false
};
const info = {
records: 0
};
const api = stringifier(options, state, info);
for (const record of records) {
const err2 = api.__transform(record, function(record2) {
data.push(record2);
});
if (err2 !== void 0) throw err2;
}
if (data.length === 0) {
api.bom((d) => {
data.push(d);
});
const err2 = api.headers((headers) => {
data.push(headers);
});
if (err2 !== void 0) throw err2;
}
return data.join("");
};
// src/errors.ts
var DataPluginError = class extends Error {
code;
constructor(message, code) {
super(message);
this.name = "DataPluginError";
this.code = code;
}
};
var CSVParseError = class extends DataPluginError {
constructor(message) {
super(message, "CSV_PARSE_ERROR");
this.name = "CSVParseError";
}
};
var SchemaNotFoundError = class extends DataPluginError {
constructor(message) {
super(message, "SCHEMA_NOT_FOUND");
this.name = "SchemaNotFoundError";
}
};
var NotFoundError = class extends DataPluginError {
constructor(message, code = "DB_NOT_FOUND") {
super(message, code);
this.name = "NotFoundError";
}
};
var FilesystemError = class extends DataPluginError {
constructor(message) {
super(message, "FILESYSTEM_ERROR");
this.name = "FilesystemError";
}
};
var DuplicateError = class extends DataPluginError {
constructor(message, code = "DUPLICATE_DATABASE") {
super(message, code);
this.name = "DuplicateError";
}
};
// src/engine/csv-engine.ts
async function parseCSV(path4, options) {
let raw;
try {
raw = await import_promises2.default.readFile(path4, "utf-8");
} catch (cause) {
throw new FilesystemError(`Cannot read file: ${path4}`);
}
if (options?.bom !== false && raw.charCodeAt(0) === 65279) {
raw = raw.slice(1);
}
try {
const records = parse(raw, {
columns: true,
skip_empty_lines: options?.skipEmptyLines ?? true,
delimiter: options?.delimiter ?? ",",
bom: false,
relax_column_count: true
});
return records;
} catch (cause) {
throw new CSVParseError(`Failed to parse CSV: ${cause.message}`);
}
}
async function stringifyCSV(rows, columns, options) {
const colNames = columns.map((c) => c.name);
const data = rows.map((row) => {
const ordered = {};
for (const name of colNames) {
ordered[name] = row[name] ?? "";
}
return ordered;
});
try {
const out = stringify(data, {
header: options?.header ?? true,
delimiter: options?.delimiter ?? ",",
quoted_string: options?.quotedString ?? true
});
return out;
} catch (cause) {
throw new CSVParseError(
`Failed to stringify CSV: ${cause.message}`
);
}
}
async function writeCSV(path4, rows, columns) {
const content = await stringifyCSV(rows, columns);
try {
await import_promises2.default.writeFile(path4, content, "utf-8");
} catch (cause) {
throw new FilesystemError(`Cannot write file: ${path4}`);
}
}
async function appendToCSV(path4, row, columns) {
try {
await import_promises2.default.access(path4);
const content = await stringifyCSV([row], columns, { header: false });
await import_promises2.default.appendFile(path4, content, "utf-8");
} catch {
await writeCSV(path4, [row], columns);
}
}
async function appendRowsToCSV(path4, rows, columns) {
try {
await import_promises2.default.access(path4);
const content = await stringifyCSV(rows, columns, { header: false });
await import_promises2.default.appendFile(path4, content, "utf-8");
} catch {
await writeCSV(path4, rows, columns);
}
}
// src/engine/schema.ts
var import_node_path2 = __toESM(require("node:path"), 1);
var import_promises3 = __toESM(require("node:fs/promises"), 1);
function schemaPath(database, table, dataRoot) {
return import_node_path2.default.join(dataRoot, "databases", database, `${table}.schema.json`);
}
function now() {
return (/* @__PURE__ */ new Date()).toISOString();
}
function createSchema(columns, description) {
return {
columns,
createdAt: now(),
description,
version: 1
};
}
async function loadSchema(schemaFile) {
try {
const raw = await import_promises3.default.readFile(schemaFile, "utf-8");
return JSON.parse(raw);
} catch (cause) {
if (cause.code === "ENOENT") {
throw new SchemaNotFoundError(`Schema not found: ${schemaFile}`);
}
throw new FilesystemError(`Cannot read schema: ${schemaFile}`);
}
}
async function saveSchema(schemaFile, schema) {
try {
await import_promises3.default.writeFile(schemaFile, JSON.stringify(schema, null, 2), "utf-8");
} catch (cause) {
throw new FilesystemError(`Cannot write schema: ${schemaFile}`);
}
}
function coerceType(value, colType) {
const actual = typeof value;
if (value === null || value === void 0 || value === "") {
return { ok: true, expected: colType, actual: String(actual) };
}
switch (colType) {
case "string":
return { ok: true, expected: "string", actual: "string" };
case "number": {
const n = Number(value);
return { ok: !isNaN(n), expected: "number", actual };
}
case "boolean": {
if (typeof value === "boolean")
return { ok: true, expected: "boolean", actual: "boolean" };
const s = String(value).toLowerCase();
const isBool = ["true", "false", "1", "0", "yes", "no"].includes(s);
return { ok: isBool, expected: "boolean", actual };
}
case "date": {
if (value instanceof Date)
return { ok: true, expected: "date", actual: "date" };
if (typeof value === "string") {
const d = new Date(value);
return { ok: !isNaN(d.getTime()), expected: "date", actual: "string" };
}
return { ok: false, expected: "date", actual };
}
default:
return { ok: true, expected: colType, actual };
}
}
function validateRowAgainstSchema(row, schema) {
const errors2 = [];
for (const col of schema.columns) {
const val = row[col.name];
if (col.required && (val === void 0 || val === null || val === "")) {
errors2.push({
column: col.name,
message: `Field "${col.name}" is required`,
code: "REQUIRED_FIELD",
expected: col.type,
actual: val
});
continue;
}
if (val !== void 0 && val !== null && val !== "") {
const check = coerceType(val, col.type);
if (!check.ok) {
errors2.push({
column: col.name,
message: `Expected ${col.type} for "${col.name}", got ${check.actual}`,
code: "TYPE_MISMATCH",
expected: col.type,
actual: val
});
}
}
}
return { valid: errors2.length === 0, errors: errors2 };
}
function validateRowsAgainstSchema(rows, schema) {
const allErrors = [];
for (const row of rows) {
const result = validateRowAgainstSchema(row, schema);
allErrors.push(...result.errors);
}
return { valid: allErrors.length === 0, errors: allErrors };
}
// src/engine/index-manager.ts
var import_node_path3 = __toESM(require("node:path"), 1);
var import_promises4 = __toESM(require("node:fs/promises"), 1);
var import_node_fs2 = require("node:fs");
function now2() {
return (/* @__PURE__ */ new Date()).toISOString();
}
function dbDir(dataRoot, database) {
return import_node_path3.default.join(dataRoot, "databases", database);
}
function metaPath(dataRoot, database) {
return import_node_path3.default.join(dbDir(dataRoot, database), ".meta.json");
}
function databasesDir(dataRoot) {
return import_node_path3.default.join(dataRoot, "databases");
}
async function tableExists(dataRoot, database, table) {
try {
const idx = await getIndex(dataRoot, database);
return table in idx.tables;
} catch {
return false;
}
}
async function getIndex(dataRoot, database) {
const fp = metaPath(dataRoot, database);
try {
const raw = await import_promises4.default.readFile(fp, "utf-8");
return JSON.parse(raw);
} catch (cause) {
if (cause.code === "ENOENT") {
throw new NotFoundError(`Database "${database}" not found`);
}
throw new FilesystemError(`Cannot read index for "${database}"`);
}
}
async function updateIndex(dataRoot, database, updates) {
const current2 = await getIndex(dataRoot, database);
const merged = { ...current2, ...updates, updatedAt: now2() };
const fp = metaPath(dataRoot, database);
await import_promises4.default.writeFile(fp, JSON.stringify(merged, null, 2), "utf-8");
}
async function initDatabase(dataRoot, name, displayName, description) {
const dir = dbDir(dataRoot, name);
if ((0, import_node_fs2.existsSync)(dir)) {
throw new DuplicateError(`Database "${name}" already exists`);
}
await import_promises4.default.mkdir(dir, { recursive: true });
const index = {
version: 1,
name,
displayName: displayName ?? name,
description,
createdAt: now2(),
updatedAt: now2(),
tables: {}
};
await import_promises4.default.writeFile(
metaPath(dataRoot, name),
JSON.stringify(index, null, 2),
"utf-8"
);
}
async function deleteDatabase(dataRoot, name) {
const dir = dbDir(dataRoot, name);
if (!(0, import_node_fs2.existsSync)(dir)) {
throw new NotFoundError(`Database "${name}" not found`);
}
await import_promises4.default.rm(dir, { recursive: true, force: true });
}
async function getDatabases(dataRoot) {
const dir = databasesDir(dataRoot);
if (!(0, import_node_fs2.existsSync)(dir)) {
return [];
}
const entries = await import_promises4.default.readdir(dir, { withFileTypes: true });
const infos = [];
for (const entry of entries) {
if (!entry.isDirectory()) continue;
try {
const idx = await getIndex(dataRoot, entry.name);
const tableCount = Object.keys(idx.tables).length;
const totalSizeBytes = Object.values(idx.tables).reduce(
(sum, t) => sum + (t.sizeBytes ?? 0),
0
);
infos.push({
name: entry.name,
displayName: idx.displayName,
tableCount,
totalSizeBytes,
createdAt: idx.createdAt,
updatedAt: idx.updatedAt
});
} catch {
}
}
return infos;
}
async function getTables(dataRoot, database) {
const idx = await getIndex(dataRoot, database);
return Object.entries(idx.tables).map(([name, meta]) => ({
name,
displayName: meta.displayName,
rowCount: meta.rowCount,
createdAt: meta.createdAt,
updatedAt: idx.updatedAt,
sizeBytes: meta.sizeBytes
}));
}
// src/toolsProvider.ts
var ColumnDefSchema = external_exports.object({
name: external_exports.string().min(1),
type: external_exports.enum(["string", "number", "boolean", "date"]),
required: external_exports.boolean().optional(),
primaryKey: external_exports.boolean().optional(),
unique: external_exports.boolean().optional(),
defaultValue: external_exports.unknown().optional(),
description: external_exports.string().optional()
});
async function ensureDataRoot() {
const root = getDataRoot();
await initDataRoot(root);
return root;
}
async function createToolsProvider() {
const dataRoot = await ensureDataRoot();
return [
// ── create_database ──────────────────────────────────────────────
tool({
name: "create_database",
description: "Create a new database (a directory that will contain tables)",
parameters: {
name: external_exports.string().min(1).describe("Database name"),
displayName: external_exports.string().optional().describe("Optional display name"),
description: external_exports.string().optional().describe("Optional description")
},
implementation: async ({ name, displayName, description }, ctx) => {
try {
await initDatabase(
dataRoot,
name,
displayName,
description
);
return JSON.stringify({
success: true,
name,
path: `${dataRoot}/databases/${name}`
});
} catch (e) {
if (e instanceof DuplicateError)
return JSON.stringify({ success: false, error: e.message });
throw e;
}
}
}),
// ── delete_database ──────────────────────────────────────────────
tool({
name: "delete_database",
description: "Delete a database and all its tables permanently",
parameters: {
name: external_exports.string().min(1).describe("Database name to delete"),
confirm: external_exports.boolean().describe("Must be true to confirm deletion")
},
implementation: async ({ name, confirm }, ctx) => {
if (!confirm)
return JSON.stringify({
success: false,
error: "Deletion not confirmed"
});
try {
const idx = await getIndex(dataRoot, name);
const tableCount = Object.keys(idx.tables).length;
await deleteDatabase(dataRoot, name);
return JSON.stringify({ success: true, deletedTables: tableCount });
} catch (e) {
if (e instanceof NotFoundError)
return JSON.stringify({ success: false, error: e.message });
throw e;
}
}
}),
// ── list_databases ───────────────────────────────────────────────
tool({
name: "list_databases",
description: "List all databases with summary information",
parameters: {},
implementation: async () => {
const dbs = await getDatabases(dataRoot);
return JSON.stringify({ databases: dbs, total: dbs.length });
}
}),
// ── get_database_info ────────────────────────────────────────────
tool({
name: "get_database_info",
description: "Get detailed information about a database including its tables",
parameters: {
name: external_exports.string().min(1).describe("Database name")
},
implementation: async ({ name }) => {
const idx = await getIndex(dataRoot, name);
const tables = await getTables(dataRoot, name);
const tableCount = Object.keys(idx.tables).length;
const totalSizeBytes = tables.reduce((s, t) => s + t.sizeBytes, 0);
return JSON.stringify({
name,
displayName: idx.displayName,
tableCount,
totalSizeBytes,
createdAt: idx.createdAt,
updatedAt: idx.updatedAt,
tables
});
}
}),
// ── create_table ─────────────────────────────────────────────────
tool({
name: "create_table",
description: "Create a new table in a database with a defined schema",
parameters: {
database: external_exports.string().min(1).describe("Database name"),
table: external_exports.string().min(1).describe("Table name"),
columns: external_exports.array(ColumnDefSchema).min(1).describe("Column definitions"),
description: external_exports.string().optional()
},
implementation: async ({ database, table, columns, description }) => {
const exists = await tableExists(
dataRoot,
database,
table
);
if (exists) {
return JSON.stringify({
success: false,
error: `Table "${table}" already exists in "${database}"`
});
}
const schema = createSchema(columns, description);
const dbDir2 = `${dataRoot}/databases/${database}`;
const schemaFile = schemaPath(database, table, dataRoot);
await saveSchema(schemaFile, schema);
await writeCSV(`${dbDir2}/${table}.csv`, [], columns);
const idx = await getIndex(dataRoot, database);
idx.tables[table] = {
name: table,
displayName: table,
createdAt: schema.createdAt,
rowCount: 0,
sizeBytes: 0
};
await updateIndex(dataRoot, database, {
tables: idx.tables
});
return JSON.stringify({
success: true,
database,
table,
columnCount: columns.length
});
}
}),
// ── delete_table ─────────────────────────────────────────────────
tool({
name: "delete_table",
description: "Delete a table and its schema permanently",
parameters: {
database: external_exports.string().min(1).describe("Database name"),
table: external_exports.string().min(1).describe("Table name"),
confirm: external_exports.boolean().describe("Must be true to confirm deletion")
},
implementation: async ({ database, table, confirm }) => {
if (!confirm)
return JSON.stringify({
success: false,
error: "Deletion not confirmed"
});
const dbDir2 = `${dataRoot}/databases/${database}`;
try {
const idx = await getIndex(dataRoot, database);
if (!(table in idx.tables)) {
return JSON.stringify({
success: false,
error: `Table "${table}" not found`
});
}
delete idx.tables[table];
await updateIndex(dataRoot, database, {
tables: idx.tables
});
await fsRm(`${dbDir2}/${table}.csv`);
await fsRm(`${dbDir2}/${table}.schema.json`);
return JSON.stringify({
success: true,
deletedFiles: [`${table}.csv`, `${table}.schema.json`]
});
} catch (e) {
if (e instanceof NotFoundError)
return JSON.stringify({ success: false, error: e.message });
throw e;
}
}
}),
// ── get_schema ───────────────────────────────────────────────────
tool({
name: "get_schema",
description: "Get the schema (column definitions) of a table",
parameters: {
database: external_exports.string().min(1),
table: external_exports.string().min(1)
},
implementation: async ({ database, table }) => {
const schemaFile = schemaPath(database, table, dataRoot);
const schema = await loadSchema(schemaFile);
return JSON.stringify({
database,
table,
columns: schema.columns,
createdAt: schema.createdAt,
description: schema.description
});
}
}),
// ── list_tables ──────────────────────────────────────────────────
tool({
name: "list_tables",
description: "List all tables in a database",
parameters: {
database: external_exports.string().min(1).describe("Database name")
},
implementation: async ({ database }) => {
const tables = await getTables(dataRoot, database);
return JSON.stringify({ database, tables, total: tables.length });
}
}),
// ── insert_row ───────────────────────────────────────────────────
tool({
name: "insert_row",
description: "Insert a single row into a table. Returns the generated row ID.",
parameters: {
database: external_exports.string().min(1),
table: external_exports.string().min(1),
data: external_exports.record(external_exports.unknown()).describe("Row data as key-value pairs")
},
implementation: async ({ database, table, data }) => {
const schemaFile = schemaPath(database, table, dataRoot);
const schema = await loadSchema(schemaFile);
const id = v4_default();
const row = { id, ...data };
const validation = validateRowAgainstSchema(row, schema);
if (!validation.valid) {
return JSON.stringify({
success: false,
error: `Validation failed: ${validation.errors.map((e) => e.message).join("; ")}`
});
}
const columns = schema.columns;
const dbDir2 = `${dataRoot}/databases/${database}`;
await appendToCSV(`${dbDir2}/${table}.csv`, row, columns);
const idx = await getIndex(dataRoot, database);
if (idx.tables[table]) {
idx.tables[table].rowCount = (idx.tables[table].rowCount || 0) + 1;
await updateIndex(dataRoot, database, {
tables: idx.tables
});
}
return JSON.stringify({ success: true, id, table });
}
}),
// ── insert_batch ─────────────────────────────────────────────────
tool({
name: "insert_batch",
description: "Insert multiple rows into a table in one operation",
parameters: {
database: external_exports.string().min(1),
table: external_exports.string().min(1),
rows: external_exports.array(external_exports.record(external_exports.unknown())).min(1).describe("Array of row objects")
},
implementation: async ({ database, table, rows }) => {
const schemaFile = schemaPath(database, table, dataRoot);
const schema = await loadSchema(schemaFile);
const enriched = rows.map((r) => ({ id: v4_default(), ...r }));
const validation = validateRowsAgainstSchema(
enriched,
schema
);
if (!validation.valid) {
return JSON.stringify({
success: false,
error: `Validation failed: ${validation.errors.map((e) => e.message).join("; ")}`
});
}
const columns = schema.columns;
const dbDir2 = `${dataRoot}/databases/${database}`;
await appendRowsToCSV(
`${dbDir2}/${table}.csv`,
enriched,
columns
);
const ids = enriched.map((r) => r.id);
const idx = await getIndex(dataRoot, database);
if (idx.tables[table]) {
idx.tables[table].rowCount = (idx.tables[table].rowCount || 0) + enriched.length;
await updateIndex(dataRoot, database, {
tables: idx.tables
});
}
return JSON.stringify({
success: true,
inserted: enriched.length,
ids
});
}
}),
// ── select_rows ──────────────────────────────────────────────────
tool({
name: "select_rows",
description: "Select rows from a table with optional filtering, limit and offset",
parameters: {
database: external_exports.string().min(1),
table: external_exports.string().min(1),
filter: external_exports.record(external_exports.unknown()).optional().describe("Key-value pairs to filter by (exact match)"),
limit: external_exports.number().int().positive().optional().describe("Max rows to return"),
offset: external_exports.number().int().min(0).optional().describe("Number of rows to skip")
},
implementation: async ({ database, table, filter, limit, offset }) => {
const dbDir2 = `${dataRoot}/databases/${database}`;
const allRows = await parseCSV(`${dbDir2}/${table}.csv`);
let filtered = allRows;
if (filter) {
for (const [key, value] of Object.entries(filter)) {
filtered = filtered.filter((r) => String(r[key]) === String(value));
}
}
const total = filtered.length;
const offsetVal = offset ?? 0;
const limitVal = limit ?? total;
const page = filtered.slice(offsetVal, offsetVal + limitVal);
return JSON.stringify({
rows: page,
total: allRows.length,
filteredTotal: total
});
}
}),
// ── update_row ───────────────────────────────────────────────────
tool({
name: "update_row",
description: "Update a row by its ID. Only the provided fields will be updated.",
parameters: {
database: external_exports.string().min(1),
table: external_exports.string().min(1),
id: external_exports.string().min(1).describe("Row UUID to update"),
data: external_exports.record(external_exports.unknown()).describe("Fields to update")
},
implementation: async ({ database, table, id, data }) => {
const dbDir2 = `${dataRoot}/databases/${database}`;
const csvPath = `${dbDir2}/${table}.csv`;
const schemaFile = schemaPath(database, table, dataRoot);
const schema = await loadSchema(schemaFile);
const allRows = await parseCSV(csvPath);
const idx = allRows.findIndex((r) => String(r.id) === id);
if (idx === -1) {
return JSON.stringify({
success: false,
error: `Row with id "${id}" not found`
});
}
const updated = { ...allRows[idx], ...data };
allRows[idx] = updated;
await writeCSV(csvPath, allRows, schema.columns);
return JSON.stringify({
success: true,
id,
updated: Object.keys(data)
});
}
}),
// ── delete_row ───────────────────────────────────────────────────
tool({
name: "delete_row",
description: "Delete a row by its ID",
parameters: {
database: external_exports.string().min(1),
table: external_exports.string().min(1),
id: external_exports.string().min(1).describe("Row UUID to delete")
},
implementation: async ({ database, table, id }) => {
const dbDir2 = `${dataRoot}/databases/${database}`;
const csvPath = `${dbDir2}/${table}.csv`;
const schemaFile = schemaPath(database, table, dataRoot);
const schema = await loadSchema(schemaFile);
const allRows = await parseCSV(csvPath);
const filtered = allRows.filter((r) => String(r.id) !== id);
if (filtered.length === allRows.length) {
return JSON.stringify({
success: false,
error: `Row with id "${id}" not found`
});
}
await writeCSV(csvPath, filtered, schema.columns);
const idx = await getIndex(dataRoot, database);
if (idx.tables[table]) {
idx.tables[table].rowCount = Math.max(
0,
(idx.tables[table].rowCount || 1) - 1
);
await updateIndex(dataRoot, database, {
tables: idx.tables
});
}
return JSON.stringify({ success: true, id });
}
}),
// ── get_row ──────────────────────────────────────────────────────
tool({
name: "get_row",
description: "Get a single row by its ID",
parameters: {
database: external_exports.string().min(1),
table: external_exports.string().min(1),
id: external_exports.string().min(1).describe("Row UUID")
},
implementation: async ({ database, table, id }) => {
const dbDir2 = `${dataRoot}/databases/${database}`;
const allRows = await parseCSV(`${dbDir2}/${table}.csv`);
const row = allRows.find((r) => String(r.id) === id) ?? null;
return JSON.stringify({ row });
}
}),
// ── query_table ──────────────────────────────────────────────────
tool({
name: "query_table",
description: "Advanced query with filters, search, sort, and pagination",
parameters: {
database: external_exports.string().min(1),
table: external_exports.string().min(1),
filters: external_exports.array(
external_exports.object({
column: external_exports.string(),
operator: external_exports.enum([
"eq",
"neq",
"gt",
"gte",
"lt",
"lte",
"contains"
]),
value: external_exports.unknown()
})
).optional().describe("Array of filter conditions"),
search: external_exports.object({
column: external_exports.string(),
query: external_exports.string(),
caseSensitive: external_exports.boolean().optional()
}).optional().describe("Full-text search on a column"),
sort: external_exports.object({
column: external_exports.string(),
direction: external_exports.enum(["asc", "desc"])
}).optional().describe("Sort configuration"),
limit: external_exports.number().int().positive().optional(),
offset: external_exports.number().int().min(0).optional()
},
implementation: async ({
database,
table,
filters,
search,
sort,
limit,
offset
}) => {
const dbDir2 = `${dataRoot}/databases/${database}`;
const allRows = await parseCSV(`${dbDir2}/${table}.csv`);
let result = [...allRows];
if (filters) {
for (const f of filters) {
result = result.filter((r) => {
const cell = r[f.column];
switch (f.operator) {
case "eq":
return String(cell) === String(f.value);
case "neq":
return String(cell) !== String(f.value);
case "gt":
return Number(cell) > Number(f.value);
case "gte":
return Number(cell) >= Number(f.value);
case "lt":
return Number(cell) < Number(f.value);
case "lte":
return Number(cell) <= Number(f.value);
case "contains":
return String(cell).toLowerCase().includes(String(f.value).toLowerCase());
default:
return true;
}
});
}
}
if (search) {
result = result.filter((r) => {
const cell = String(r[search.column] ?? "");
const q = search.caseSensitive ? search.query : search.query.toLowerCase();
const val = search.caseSensitive ? cell : cell.toLowerCase();
return val.includes(q);
});
}
if (sort) {
result.sort((a, b) => {
const aVal = a[sort.column];
const bVal = b[sort.column];
if (aVal == null) return 1;
if (bVal == null) return -1;
const cmp = typeof aVal === "number" ? aVal - Number(bVal) : String(aVal).localeCompare(String(bVal));
return sort.direction === "desc" ? -cmp : cmp;
});
}
const total = result.length;
const offsetVal = offset ?? 0;
const limitVal = limit ?? total;
const page = result.slice(offsetVal, offsetVal + limitVal);
const totalPages = limitVal > 0 ? Math.ceil(total / limitVal) : 1;
return JSON.stringify({
rows: page,
total: allRows.length,
filteredTotal: total,
page: Math.floor(offsetVal / (limitVal || 1)) + 1,
totalPages
});
}
}),
// ── aggregate_table ──────────────────────────────────────────────
tool({
name: "aggregate_table",
description: "Perform aggregation operations on a numeric column",
parameters: {
database: external_exports.string().min(1),
table: external_exports.string().min(1),
column: external_exports.string().min(1).describe("Column to aggregate"),
operation: external_exports.enum(["count", "sum", "avg", "min", "max"]).describe("Aggregation operation")
},
implementation: async ({ database, table, column, operation }) => {
const dbDir2 = `${dataRoot}/databases/${database}`;
const allRows = await parseCSV(`${dbDir2}/${table}.csv`);
const values = allRows.map((r) => Number(r[column])).filter((v) => !isNaN(v));
const count = values.length;
let result;
switch (operation) {
case "count":
result = count;
break;
case "sum":
result = values.reduce((a, b) => a + b, 0);
break;
case "avg":
result = count > 0 ? values.reduce((a, b) => a + b, 0) / count : 0;
break;
case "min":
result = count > 0 ? Math.min(...values) : 0;
break;
case "max":
result = count > 0 ? Math.max(...values) : 0;
break;
}
return JSON.stringify({ operation, column, result, count });
}
})
];
}
async function fsRm(fp) {
try {
const fs5 = await import("node:fs/promises");
await fs5.rm(fp, { force: true });
} catch {
}
}
// src/config-schematics.ts
var globalConfigSchematics2 = createConfigSchematics().field(
"dataRoot",
"string",
{
displayName: "Data Root Directory",
hint: "Absolute path where databases and tables are stored. Use ~/ for home directory.",
placeholder: "~/.lmstudio/plugins/data-plugin/data",
maxLength: 512
},
"~/.lmstudio/plugins/data-plugin/data"
).field(
"csv.delimiter",
"string",
{
displayName: "CSV Delimiter",
hint: "Character used to separate values in CSV files",
placeholder: ",",
maxLength: 2
},
","
).scope(
"csv",
(csv) => csv.field(
"encoding",
"select",
{
displayName: "CSV Encoding",
options: [
{ value: "utf-8", displayName: "UTF-8" },
{ value: "utf-16", displayName: "UTF-16" },
{ value: "latin1", displayName: "Latin-1" }
]
},
"utf-8"
)
).build();
var perChatConfigSchematics = createConfigSchematics().field(
"maxRowsPerPage",
"numeric",
{
displayName: "Max Rows Per Page",
hint: "Default number of rows returned per page in queries",
min: 1,
max: 1e4,
int: true
},
100
).field(
"dateFormat",
"select",
{
displayName: "Date Format",
hint: "Format for date display in query results",
options: [
{ value: "ISO", displayName: "ISO 8601" },
{ value: "US", displayName: "MM/DD/YYYY" },
{ value: "EU", displayName: "DD/MM/YYYY" }
]
},
"ISO"
).build();
// src/index.ts
async function main(context) {
const config = await loadConfig();
await saveConfig(config);
context.withGlobalConfigSchematics(globalConfigSchematics2).withConfigSchematics(perChatConfigSchematics).withToolsProvider(async () => {
const tools = await createToolsProvider();
return tools;
});
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
main
});