@mercnet/windmill
Version:
Windmill integration adapter for MercNet GraphQL API
8,715 lines • 286 kB
JavaScript
var MercNetWindmill = (function (exports) {
'use strict';
// @mercnet/windmill - Windmill integration adapter for MercNet GraphQL API
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 __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
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.
__defProp(target, "default", { value: mod, enumerable: true }) ,
mod
));
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
// ../../node_modules/.pnpm/cross-fetch@3.2.0/node_modules/cross-fetch/dist/browser-ponyfill.js
var require_browser_ponyfill = __commonJS({
"../../node_modules/.pnpm/cross-fetch@3.2.0/node_modules/cross-fetch/dist/browser-ponyfill.js"(exports, module) {
var __global__ = typeof globalThis !== "undefined" && globalThis || typeof self !== "undefined" && self || typeof global !== "undefined" && global;
var __globalThis__ = function() {
function F() {
this.fetch = false;
this.DOMException = __global__.DOMException;
}
F.prototype = __global__;
return new F();
}();
(function(globalThis2) {
(function(exports2) {
var g = typeof globalThis2 !== "undefined" && globalThis2 || typeof self !== "undefined" && self || // eslint-disable-next-line no-undef
typeof global !== "undefined" && global || {};
var support = {
searchParams: "URLSearchParams" in g,
iterable: "Symbol" in g && "iterator" in Symbol,
blob: "FileReader" in g && "Blob" in g && function() {
try {
new Blob();
return true;
} catch (e) {
return false;
}
}(),
formData: "FormData" in g,
arrayBuffer: "ArrayBuffer" in g
};
function isDataView(obj) {
return obj && DataView.prototype.isPrototypeOf(obj);
}
if (support.arrayBuffer) {
var viewClasses = [
"[object Int8Array]",
"[object Uint8Array]",
"[object Uint8ClampedArray]",
"[object Int16Array]",
"[object Uint16Array]",
"[object Int32Array]",
"[object Uint32Array]",
"[object Float32Array]",
"[object Float64Array]"
];
var isArrayBufferView = ArrayBuffer.isView || function(obj) {
return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1;
};
}
function normalizeName(name) {
if (typeof name !== "string") {
name = String(name);
}
if (/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(name) || name === "") {
throw new TypeError('Invalid character in header field name: "' + name + '"');
}
return name.toLowerCase();
}
function normalizeValue(value) {
if (typeof value !== "string") {
value = String(value);
}
return value;
}
function iteratorFor(items) {
var iterator = {
next: function() {
var value = items.shift();
return { done: value === void 0, value };
}
};
if (support.iterable) {
iterator[Symbol.iterator] = function() {
return iterator;
};
}
return iterator;
}
function Headers3(headers) {
this.map = {};
if (headers instanceof Headers3) {
headers.forEach(function(value, name) {
this.append(name, value);
}, this);
} else if (Array.isArray(headers)) {
headers.forEach(function(header) {
if (header.length != 2) {
throw new TypeError("Headers constructor: expected name/value pair to be length 2, found" + header.length);
}
this.append(header[0], header[1]);
}, this);
} else if (headers) {
Object.getOwnPropertyNames(headers).forEach(function(name) {
this.append(name, headers[name]);
}, this);
}
}
Headers3.prototype.append = function(name, value) {
name = normalizeName(name);
value = normalizeValue(value);
var oldValue = this.map[name];
this.map[name] = oldValue ? oldValue + ", " + value : value;
};
Headers3.prototype["delete"] = function(name) {
delete this.map[normalizeName(name)];
};
Headers3.prototype.get = function(name) {
name = normalizeName(name);
return this.has(name) ? this.map[name] : null;
};
Headers3.prototype.has = function(name) {
return this.map.hasOwnProperty(normalizeName(name));
};
Headers3.prototype.set = function(name, value) {
this.map[normalizeName(name)] = normalizeValue(value);
};
Headers3.prototype.forEach = function(callback, thisArg) {
for (var name in this.map) {
if (this.map.hasOwnProperty(name)) {
callback.call(thisArg, this.map[name], name, this);
}
}
};
Headers3.prototype.keys = function() {
var items = [];
this.forEach(function(value, name) {
items.push(name);
});
return iteratorFor(items);
};
Headers3.prototype.values = function() {
var items = [];
this.forEach(function(value) {
items.push(value);
});
return iteratorFor(items);
};
Headers3.prototype.entries = function() {
var items = [];
this.forEach(function(value, name) {
items.push([name, value]);
});
return iteratorFor(items);
};
if (support.iterable) {
Headers3.prototype[Symbol.iterator] = Headers3.prototype.entries;
}
function consumed(body) {
if (body._noBody) return;
if (body.bodyUsed) {
return Promise.reject(new TypeError("Already read"));
}
body.bodyUsed = true;
}
function fileReaderReady(reader) {
return new Promise(function(resolve, reject) {
reader.onload = function() {
resolve(reader.result);
};
reader.onerror = function() {
reject(reader.error);
};
});
}
function readBlobAsArrayBuffer(blob) {
var reader = new FileReader();
var promise = fileReaderReady(reader);
reader.readAsArrayBuffer(blob);
return promise;
}
function readBlobAsText(blob) {
var reader = new FileReader();
var promise = fileReaderReady(reader);
var match = /charset=([A-Za-z0-9_-]+)/.exec(blob.type);
var encoding = match ? match[1] : "utf-8";
reader.readAsText(blob, encoding);
return promise;
}
function readArrayBufferAsText(buf) {
var view = new Uint8Array(buf);
var chars = new Array(view.length);
for (var i = 0; i < view.length; i++) {
chars[i] = String.fromCharCode(view[i]);
}
return chars.join("");
}
function bufferClone(buf) {
if (buf.slice) {
return buf.slice(0);
} else {
var view = new Uint8Array(buf.byteLength);
view.set(new Uint8Array(buf));
return view.buffer;
}
}
function Body() {
this.bodyUsed = false;
this._initBody = function(body) {
this.bodyUsed = this.bodyUsed;
this._bodyInit = body;
if (!body) {
this._noBody = true;
this._bodyText = "";
} else if (typeof body === "string") {
this._bodyText = body;
} else if (support.blob && Blob.prototype.isPrototypeOf(body)) {
this._bodyBlob = body;
} else if (support.formData && FormData.prototype.isPrototypeOf(body)) {
this._bodyFormData = body;
} else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
this._bodyText = body.toString();
} else if (support.arrayBuffer && support.blob && isDataView(body)) {
this._bodyArrayBuffer = bufferClone(body.buffer);
this._bodyInit = new Blob([this._bodyArrayBuffer]);
} else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {
this._bodyArrayBuffer = bufferClone(body);
} else {
this._bodyText = body = Object.prototype.toString.call(body);
}
if (!this.headers.get("content-type")) {
if (typeof body === "string") {
this.headers.set("content-type", "text/plain;charset=UTF-8");
} else if (this._bodyBlob && this._bodyBlob.type) {
this.headers.set("content-type", this._bodyBlob.type);
} else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
this.headers.set("content-type", "application/x-www-form-urlencoded;charset=UTF-8");
}
}
};
if (support.blob) {
this.blob = function() {
var rejected = consumed(this);
if (rejected) {
return rejected;
}
if (this._bodyBlob) {
return Promise.resolve(this._bodyBlob);
} else if (this._bodyArrayBuffer) {
return Promise.resolve(new Blob([this._bodyArrayBuffer]));
} else if (this._bodyFormData) {
throw new Error("could not read FormData body as blob");
} else {
return Promise.resolve(new Blob([this._bodyText]));
}
};
}
this.arrayBuffer = function() {
if (this._bodyArrayBuffer) {
var isConsumed = consumed(this);
if (isConsumed) {
return isConsumed;
} else if (ArrayBuffer.isView(this._bodyArrayBuffer)) {
return Promise.resolve(
this._bodyArrayBuffer.buffer.slice(
this._bodyArrayBuffer.byteOffset,
this._bodyArrayBuffer.byteOffset + this._bodyArrayBuffer.byteLength
)
);
} else {
return Promise.resolve(this._bodyArrayBuffer);
}
} else if (support.blob) {
return this.blob().then(readBlobAsArrayBuffer);
} else {
throw new Error("could not read as ArrayBuffer");
}
};
this.text = function() {
var rejected = consumed(this);
if (rejected) {
return rejected;
}
if (this._bodyBlob) {
return readBlobAsText(this._bodyBlob);
} else if (this._bodyArrayBuffer) {
return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer));
} else if (this._bodyFormData) {
throw new Error("could not read FormData body as text");
} else {
return Promise.resolve(this._bodyText);
}
};
if (support.formData) {
this.formData = function() {
return this.text().then(decode);
};
}
this.json = function() {
return this.text().then(JSON.parse);
};
return this;
}
var methods = ["CONNECT", "DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT", "TRACE"];
function normalizeMethod(method) {
var upcased = method.toUpperCase();
return methods.indexOf(upcased) > -1 ? upcased : method;
}
function Request(input, options) {
if (!(this instanceof Request)) {
throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');
}
options = options || {};
var body = options.body;
if (input instanceof Request) {
if (input.bodyUsed) {
throw new TypeError("Already read");
}
this.url = input.url;
this.credentials = input.credentials;
if (!options.headers) {
this.headers = new Headers3(input.headers);
}
this.method = input.method;
this.mode = input.mode;
this.signal = input.signal;
if (!body && input._bodyInit != null) {
body = input._bodyInit;
input.bodyUsed = true;
}
} else {
this.url = String(input);
}
this.credentials = options.credentials || this.credentials || "same-origin";
if (options.headers || !this.headers) {
this.headers = new Headers3(options.headers);
}
this.method = normalizeMethod(options.method || this.method || "GET");
this.mode = options.mode || this.mode || null;
this.signal = options.signal || this.signal || function() {
if ("AbortController" in g) {
var ctrl = new AbortController();
return ctrl.signal;
}
}();
this.referrer = null;
if ((this.method === "GET" || this.method === "HEAD") && body) {
throw new TypeError("Body not allowed for GET or HEAD requests");
}
this._initBody(body);
if (this.method === "GET" || this.method === "HEAD") {
if (options.cache === "no-store" || options.cache === "no-cache") {
var reParamSearch = /([?&])_=[^&]*/;
if (reParamSearch.test(this.url)) {
this.url = this.url.replace(reParamSearch, "$1_=" + (/* @__PURE__ */ new Date()).getTime());
} else {
var reQueryString = /\?/;
this.url += (reQueryString.test(this.url) ? "&" : "?") + "_=" + (/* @__PURE__ */ new Date()).getTime();
}
}
}
}
Request.prototype.clone = function() {
return new Request(this, { body: this._bodyInit });
};
function decode(body) {
var form = new FormData();
body.trim().split("&").forEach(function(bytes) {
if (bytes) {
var split = bytes.split("=");
var name = split.shift().replace(/\+/g, " ");
var value = split.join("=").replace(/\+/g, " ");
form.append(decodeURIComponent(name), decodeURIComponent(value));
}
});
return form;
}
function parseHeaders(rawHeaders) {
var headers = new Headers3();
var preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, " ");
preProcessedHeaders.split("\r").map(function(header) {
return header.indexOf("\n") === 0 ? header.substr(1, header.length) : header;
}).forEach(function(line) {
var parts = line.split(":");
var key = parts.shift().trim();
if (key) {
var value = parts.join(":").trim();
try {
headers.append(key, value);
} catch (error) {
console.warn("Response " + error.message);
}
}
});
return headers;
}
Body.call(Request.prototype);
function Response(bodyInit, options) {
if (!(this instanceof Response)) {
throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');
}
if (!options) {
options = {};
}
this.type = "default";
this.status = options.status === void 0 ? 200 : options.status;
if (this.status < 200 || this.status > 599) {
throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");
}
this.ok = this.status >= 200 && this.status < 300;
this.statusText = options.statusText === void 0 ? "" : "" + options.statusText;
this.headers = new Headers3(options.headers);
this.url = options.url || "";
this._initBody(bodyInit);
}
Body.call(Response.prototype);
Response.prototype.clone = function() {
return new Response(this._bodyInit, {
status: this.status,
statusText: this.statusText,
headers: new Headers3(this.headers),
url: this.url
});
};
Response.error = function() {
var response = new Response(null, { status: 200, statusText: "" });
response.ok = false;
response.status = 0;
response.type = "error";
return response;
};
var redirectStatuses = [301, 302, 303, 307, 308];
Response.redirect = function(url, status) {
if (redirectStatuses.indexOf(status) === -1) {
throw new RangeError("Invalid status code");
}
return new Response(null, { status, headers: { location: url } });
};
exports2.DOMException = g.DOMException;
try {
new exports2.DOMException();
} catch (err) {
exports2.DOMException = function(message, name) {
this.message = message;
this.name = name;
var error = Error(message);
this.stack = error.stack;
};
exports2.DOMException.prototype = Object.create(Error.prototype);
exports2.DOMException.prototype.constructor = exports2.DOMException;
}
function fetch(input, init) {
return new Promise(function(resolve, reject) {
var request = new Request(input, init);
if (request.signal && request.signal.aborted) {
return reject(new exports2.DOMException("Aborted", "AbortError"));
}
var xhr = new XMLHttpRequest();
function abortXhr() {
xhr.abort();
}
xhr.onload = function() {
var options = {
statusText: xhr.statusText,
headers: parseHeaders(xhr.getAllResponseHeaders() || "")
};
if (request.url.indexOf("file://") === 0 && (xhr.status < 200 || xhr.status > 599)) {
options.status = 200;
} else {
options.status = xhr.status;
}
options.url = "responseURL" in xhr ? xhr.responseURL : options.headers.get("X-Request-URL");
var body = "response" in xhr ? xhr.response : xhr.responseText;
setTimeout(function() {
resolve(new Response(body, options));
}, 0);
};
xhr.onerror = function() {
setTimeout(function() {
reject(new TypeError("Network request failed"));
}, 0);
};
xhr.ontimeout = function() {
setTimeout(function() {
reject(new TypeError("Network request timed out"));
}, 0);
};
xhr.onabort = function() {
setTimeout(function() {
reject(new exports2.DOMException("Aborted", "AbortError"));
}, 0);
};
function fixUrl(url) {
try {
return url === "" && g.location.href ? g.location.href : url;
} catch (e) {
return url;
}
}
xhr.open(request.method, fixUrl(request.url), true);
if (request.credentials === "include") {
xhr.withCredentials = true;
} else if (request.credentials === "omit") {
xhr.withCredentials = false;
}
if ("responseType" in xhr) {
if (support.blob) {
xhr.responseType = "blob";
} else if (support.arrayBuffer) {
xhr.responseType = "arraybuffer";
}
}
if (init && typeof init.headers === "object" && !(init.headers instanceof Headers3 || g.Headers && init.headers instanceof g.Headers)) {
var names = [];
Object.getOwnPropertyNames(init.headers).forEach(function(name) {
names.push(normalizeName(name));
xhr.setRequestHeader(name, normalizeValue(init.headers[name]));
});
request.headers.forEach(function(value, name) {
if (names.indexOf(name) === -1) {
xhr.setRequestHeader(name, value);
}
});
} else {
request.headers.forEach(function(value, name) {
xhr.setRequestHeader(name, value);
});
}
if (request.signal) {
request.signal.addEventListener("abort", abortXhr);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
request.signal.removeEventListener("abort", abortXhr);
}
};
}
xhr.send(typeof request._bodyInit === "undefined" ? null : request._bodyInit);
});
}
fetch.polyfill = true;
if (!g.fetch) {
g.fetch = fetch;
g.Headers = Headers3;
g.Request = Request;
g.Response = Response;
}
exports2.Headers = Headers3;
exports2.Request = Request;
exports2.Response = Response;
exports2.fetch = fetch;
Object.defineProperty(exports2, "__esModule", { value: true });
return exports2;
})({});
})(__globalThis__);
__globalThis__.fetch.ponyfill = true;
delete __globalThis__.fetch.polyfill;
var ctx = __global__.fetch ? __global__ : __globalThis__;
exports = ctx.fetch;
exports.default = ctx.fetch;
exports.fetch = ctx.fetch;
exports.Headers = ctx.Headers;
exports.Request = ctx.Request;
exports.Response = ctx.Response;
module.exports = exports;
}
});
// ../../node_modules/.pnpm/graphql-request@6.1.0_graphql@16.11.0/node_modules/graphql-request/build/esm/defaultJsonSerializer.js
var defaultJsonSerializer = JSON;
// ../../node_modules/.pnpm/graphql-request@6.1.0_graphql@16.11.0/node_modules/graphql-request/build/esm/helpers.js
var uppercase = (str) => str.toUpperCase();
var HeadersInstanceToPlainObject = (headers) => {
const o = {};
headers.forEach((v, k) => {
o[k] = v;
});
return o;
};
// ../../node_modules/.pnpm/graphql-request@6.1.0_graphql@16.11.0/node_modules/graphql-request/build/esm/parseArgs.js
var parseRequestArgs = (documentOrOptions, variables, requestHeaders) => {
return documentOrOptions.document ? documentOrOptions : {
document: documentOrOptions,
variables,
requestHeaders,
signal: void 0
};
};
var parseRawRequestArgs = (queryOrOptions, variables, requestHeaders) => {
return queryOrOptions.query ? queryOrOptions : {
query: queryOrOptions,
variables,
requestHeaders,
signal: void 0
};
};
var parseBatchRequestArgs = (documentsOrOptions, requestHeaders) => {
return documentsOrOptions.documents ? documentsOrOptions : {
documents: documentsOrOptions,
requestHeaders,
signal: void 0
};
};
// ../../node_modules/.pnpm/graphql@16.11.0/node_modules/graphql/jsutils/devAssert.mjs
function devAssert(condition, message) {
const booleanCondition = Boolean(condition);
if (!booleanCondition) {
throw new Error(message);
}
}
// ../../node_modules/.pnpm/graphql@16.11.0/node_modules/graphql/jsutils/isObjectLike.mjs
function isObjectLike(value) {
return typeof value == "object" && value !== null;
}
// ../../node_modules/.pnpm/graphql@16.11.0/node_modules/graphql/jsutils/invariant.mjs
function invariant(condition, message) {
const booleanCondition = Boolean(condition);
if (!booleanCondition) {
throw new Error(
"Unexpected invariant triggered."
);
}
}
// ../../node_modules/.pnpm/graphql@16.11.0/node_modules/graphql/language/location.mjs
var LineRegExp = /\r\n|[\n\r]/g;
function getLocation(source, position) {
let lastLineStart = 0;
let line = 1;
for (const match of source.body.matchAll(LineRegExp)) {
typeof match.index === "number" || invariant(false);
if (match.index >= position) {
break;
}
lastLineStart = match.index + match[0].length;
line += 1;
}
return {
line,
column: position + 1 - lastLineStart
};
}
// ../../node_modules/.pnpm/graphql@16.11.0/node_modules/graphql/language/printLocation.mjs
function printLocation(location) {
return printSourceLocation(
location.source,
getLocation(location.source, location.start)
);
}
function printSourceLocation(source, sourceLocation) {
const firstLineColumnOffset = source.locationOffset.column - 1;
const body = "".padStart(firstLineColumnOffset) + source.body;
const lineIndex = sourceLocation.line - 1;
const lineOffset = source.locationOffset.line - 1;
const lineNum = sourceLocation.line + lineOffset;
const columnOffset = sourceLocation.line === 1 ? firstLineColumnOffset : 0;
const columnNum = sourceLocation.column + columnOffset;
const locationStr = `${source.name}:${lineNum}:${columnNum}
`;
const lines = body.split(/\r\n|[\n\r]/g);
const locationLine = lines[lineIndex];
if (locationLine.length > 120) {
const subLineIndex = Math.floor(columnNum / 80);
const subLineColumnNum = columnNum % 80;
const subLines = [];
for (let i = 0; i < locationLine.length; i += 80) {
subLines.push(locationLine.slice(i, i + 80));
}
return locationStr + printPrefixedLines([
[`${lineNum} |`, subLines[0]],
...subLines.slice(1, subLineIndex + 1).map((subLine) => ["|", subLine]),
["|", "^".padStart(subLineColumnNum)],
["|", subLines[subLineIndex + 1]]
]);
}
return locationStr + printPrefixedLines([
// Lines specified like this: ["prefix", "string"],
[`${lineNum - 1} |`, lines[lineIndex - 1]],
[`${lineNum} |`, locationLine],
["|", "^".padStart(columnNum)],
[`${lineNum + 1} |`, lines[lineIndex + 1]]
]);
}
function printPrefixedLines(lines) {
const existingLines = lines.filter(([_, line]) => line !== void 0);
const padLen = Math.max(...existingLines.map(([prefix]) => prefix.length));
return existingLines.map(([prefix, line]) => prefix.padStart(padLen) + (line ? " " + line : "")).join("\n");
}
// ../../node_modules/.pnpm/graphql@16.11.0/node_modules/graphql/error/GraphQLError.mjs
function toNormalizedOptions(args) {
const firstArg = args[0];
if (firstArg == null || "kind" in firstArg || "length" in firstArg) {
return {
nodes: firstArg,
source: args[1],
positions: args[2],
path: args[3],
originalError: args[4],
extensions: args[5]
};
}
return firstArg;
}
var GraphQLError = class _GraphQLError extends Error {
/**
* An array of `{ line, column }` locations within the source GraphQL document
* which correspond to this error.
*
* Errors during validation often contain multiple locations, for example to
* point out two things with the same name. Errors during execution include a
* single location, the field which produced the error.
*
* Enumerable, and appears in the result of JSON.stringify().
*/
/**
* An array describing the JSON-path into the execution response which
* corresponds to this error. Only included for errors during execution.
*
* Enumerable, and appears in the result of JSON.stringify().
*/
/**
* An array of GraphQL AST Nodes corresponding to this error.
*/
/**
* The source GraphQL document for the first location of this error.
*
* Note that if this Error represents more than one node, the source may not
* represent nodes after the first node.
*/
/**
* An array of character offsets within the source GraphQL document
* which correspond to this error.
*/
/**
* The original error thrown from a field resolver during execution.
*/
/**
* Extension fields to add to the formatted error.
*/
/**
* @deprecated Please use the `GraphQLErrorOptions` constructor overload instead.
*/
constructor(message, ...rawArgs) {
var _this$nodes, _nodeLocations$, _ref;
const { nodes, source, positions, path, originalError, extensions } = toNormalizedOptions(rawArgs);
super(message);
this.name = "GraphQLError";
this.path = path !== null && path !== void 0 ? path : void 0;
this.originalError = originalError !== null && originalError !== void 0 ? originalError : void 0;
this.nodes = undefinedIfEmpty(
Array.isArray(nodes) ? nodes : nodes ? [nodes] : void 0
);
const nodeLocations = undefinedIfEmpty(
(_this$nodes = this.nodes) === null || _this$nodes === void 0 ? void 0 : _this$nodes.map((node) => node.loc).filter((loc) => loc != null)
);
this.source = source !== null && source !== void 0 ? source : nodeLocations === null || nodeLocations === void 0 ? void 0 : (_nodeLocations$ = nodeLocations[0]) === null || _nodeLocations$ === void 0 ? void 0 : _nodeLocations$.source;
this.positions = positions !== null && positions !== void 0 ? positions : nodeLocations === null || nodeLocations === void 0 ? void 0 : nodeLocations.map((loc) => loc.start);
this.locations = positions && source ? positions.map((pos) => getLocation(source, pos)) : nodeLocations === null || nodeLocations === void 0 ? void 0 : nodeLocations.map((loc) => getLocation(loc.source, loc.start));
const originalExtensions = isObjectLike(
originalError === null || originalError === void 0 ? void 0 : originalError.extensions
) ? originalError === null || originalError === void 0 ? void 0 : originalError.extensions : void 0;
this.extensions = (_ref = extensions !== null && extensions !== void 0 ? extensions : originalExtensions) !== null && _ref !== void 0 ? _ref : /* @__PURE__ */ Object.create(null);
Object.defineProperties(this, {
message: {
writable: true,
enumerable: true
},
name: {
enumerable: false
},
nodes: {
enumerable: false
},
source: {
enumerable: false
},
positions: {
enumerable: false
},
originalError: {
enumerable: false
}
});
if (originalError !== null && originalError !== void 0 && originalError.stack) {
Object.defineProperty(this, "stack", {
value: originalError.stack,
writable: true,
configurable: true
});
} else if (Error.captureStackTrace) {
Error.captureStackTrace(this, _GraphQLError);
} else {
Object.defineProperty(this, "stack", {
value: Error().stack,
writable: true,
configurable: true
});
}
}
get [Symbol.toStringTag]() {
return "GraphQLError";
}
toString() {
let output = this.message;
if (this.nodes) {
for (const node of this.nodes) {
if (node.loc) {
output += "\n\n" + printLocation(node.loc);
}
}
} else if (this.source && this.locations) {
for (const location of this.locations) {
output += "\n\n" + printSourceLocation(this.source, location);
}
}
return output;
}
toJSON() {
const formattedError = {
message: this.message
};
if (this.locations != null) {
formattedError.locations = this.locations;
}
if (this.path != null) {
formattedError.path = this.path;
}
if (this.extensions != null && Object.keys(this.extensions).length > 0) {
formattedError.extensions = this.extensions;
}
return formattedError;
}
};
function undefinedIfEmpty(array) {
return array === void 0 || array.length === 0 ? void 0 : array;
}
// ../../node_modules/.pnpm/graphql@16.11.0/node_modules/graphql/error/syntaxError.mjs
function syntaxError(source, position, description) {
return new GraphQLError(`Syntax Error: ${description}`, {
source,
positions: [position]
});
}
// ../../node_modules/.pnpm/graphql@16.11.0/node_modules/graphql/language/ast.mjs
var Location = class {
/**
* The character offset at which this Node begins.
*/
/**
* The character offset at which this Node ends.
*/
/**
* The Token at which this Node begins.
*/
/**
* The Token at which this Node ends.
*/
/**
* The Source document the AST represents.
*/
constructor(startToken, endToken, source) {
this.start = startToken.start;
this.end = endToken.end;
this.startToken = startToken;
this.endToken = endToken;
this.source = source;
}
get [Symbol.toStringTag]() {
return "Location";
}
toJSON() {
return {
start: this.start,
end: this.end
};
}
};
var Token = class {
/**
* The kind of Token.
*/
/**
* The character offset at which this Node begins.
*/
/**
* The character offset at which this Node ends.
*/
/**
* The 1-indexed line number on which this Token appears.
*/
/**
* The 1-indexed column number at which this Token begins.
*/
/**
* For non-punctuation tokens, represents the interpreted value of the token.
*
* Note: is undefined for punctuation tokens, but typed as string for
* convenience in the parser.
*/
/**
* Tokens exist as nodes in a double-linked-list amongst all tokens
* including ignored tokens. <SOF> is always the first node and <EOF>
* the last.
*/
constructor(kind, start, end, line, column, value) {
this.kind = kind;
this.start = start;
this.end = end;
this.line = line;
this.column = column;
this.value = value;
this.prev = null;
this.next = null;
}
get [Symbol.toStringTag]() {
return "Token";
}
toJSON() {
return {
kind: this.kind,
value: this.value,
line: this.line,
column: this.column
};
}
};
var QueryDocumentKeys = {
Name: [],
Document: ["definitions"],
OperationDefinition: [
"name",
"variableDefinitions",
"directives",
"selectionSet"
],
VariableDefinition: ["variable", "type", "defaultValue", "directives"],
Variable: ["name"],
SelectionSet: ["selections"],
Field: ["alias", "name", "arguments", "directives", "selectionSet"],
Argument: ["name", "value"],
FragmentSpread: ["name", "directives"],
InlineFragment: ["typeCondition", "directives", "selectionSet"],
FragmentDefinition: [
"name",
// Note: fragment variable definitions are deprecated and will removed in v17.0.0
"variableDefinitions",
"typeCondition",
"directives",
"selectionSet"
],
IntValue: [],
FloatValue: [],
StringValue: [],
BooleanValue: [],
NullValue: [],
EnumValue: [],
ListValue: ["values"],
ObjectValue: ["fields"],
ObjectField: ["name", "value"],
Directive: ["name", "arguments"],
NamedType: ["name"],
ListType: ["type"],
NonNullType: ["type"],
SchemaDefinition: ["description", "directives", "operationTypes"],
OperationTypeDefinition: ["type"],
ScalarTypeDefinition: ["description", "name", "directives"],
ObjectTypeDefinition: [
"description",
"name",
"interfaces",
"directives",
"fields"
],
FieldDefinition: ["description", "name", "arguments", "type", "directives"],
InputValueDefinition: [
"description",
"name",
"type",
"defaultValue",
"directives"
],
InterfaceTypeDefinition: [
"description",
"name",
"interfaces",
"directives",
"fields"
],
UnionTypeDefinition: ["description", "name", "directives", "types"],
EnumTypeDefinition: ["description", "name", "directives", "values"],
EnumValueDefinition: ["description", "name", "directives"],
InputObjectTypeDefinition: ["description", "name", "directives", "fields"],
DirectiveDefinition: ["description", "name", "arguments", "locations"],
SchemaExtension: ["directives", "operationTypes"],
ScalarTypeExtension: ["name", "directives"],
ObjectTypeExtension: ["name", "interfaces", "directives", "fields"],
InterfaceTypeExtension: ["name", "interfaces", "directives", "fields"],
UnionTypeExtension: ["name", "directives", "types"],
EnumTypeExtension: ["name", "directives", "values"],
InputObjectTypeExtension: ["name", "directives", "fields"]
};
var kindValues = new Set(Object.keys(QueryDocumentKeys));
function isNode(maybeNode) {
const maybeKind = maybeNode === null || maybeNode === void 0 ? void 0 : maybeNode.kind;
return typeof maybeKind === "string" && kindValues.has(maybeKind);
}
var OperationTypeNode;
(function(OperationTypeNode2) {
OperationTypeNode2["QUERY"] = "query";
OperationTypeNode2["MUTATION"] = "mutation";
OperationTypeNode2["SUBSCRIPTION"] = "subscription";
})(OperationTypeNode || (OperationTypeNode = {}));
// ../../node_modules/.pnpm/graphql@16.11.0/node_modules/graphql/language/directiveLocation.mjs
var DirectiveLocation;
(function(DirectiveLocation2) {
DirectiveLocation2["QUERY"] = "QUERY";
DirectiveLocation2["MUTATION"] = "MUTATION";
DirectiveLocation2["SUBSCRIPTION"] = "SUBSCRIPTION";
DirectiveLocation2["FIELD"] = "FIELD";
DirectiveLocation2["FRAGMENT_DEFINITION"] = "FRAGMENT_DEFINITION";
DirectiveLocation2["FRAGMENT_SPREAD"] = "FRAGMENT_SPREAD";
DirectiveLocation2["INLINE_FRAGMENT"] = "INLINE_FRAGMENT";
DirectiveLocation2["VARIABLE_DEFINITION"] = "VARIABLE_DEFINITION";
DirectiveLocation2["SCHEMA"] = "SCHEMA";
DirectiveLocation2["SCALAR"] = "SCALAR";
DirectiveLocation2["OBJECT"] = "OBJECT";
DirectiveLocation2["FIELD_DEFINITION"] = "FIELD_DEFINITION";
DirectiveLocation2["ARGUMENT_DEFINITION"] = "ARGUMENT_DEFINITION";
DirectiveLocation2["INTERFACE"] = "INTERFACE";
DirectiveLocation2["UNION"] = "UNION";
DirectiveLocation2["ENUM"] = "ENUM";
DirectiveLocation2["ENUM_VALUE"] = "ENUM_VALUE";
DirectiveLocation2["INPUT_OBJECT"] = "INPUT_OBJECT";
DirectiveLocation2["INPUT_FIELD_DEFINITION"] = "INPUT_FIELD_DEFINITION";
})(DirectiveLocation || (DirectiveLocation = {}));
// ../../node_modules/.pnpm/graphql@16.11.0/node_modules/graphql/language/kinds.mjs
var Kind;
(function(Kind2) {
Kind2["NAME"] = "Name";
Kind2["DOCUMENT"] = "Document";
Kind2["OPERATION_DEFINITION"] = "OperationDefinition";
Kind2["VARIABLE_DEFINITION"] = "VariableDefinition";
Kind2["SELECTION_SET"] = "SelectionSet";
Kind2["FIELD"] = "Field";
Kind2["ARGUMENT"] = "Argument";
Kind2["FRAGMENT_SPREAD"] = "FragmentSpread";
Kind2["INLINE_FRAGMENT"] = "InlineFragment";
Kind2["FRAGMENT_DEFINITION"] = "FragmentDefinition";
Kind2["VARIABLE"] = "Variable";
Kind2["INT"] = "IntValue";
Kind2["FLOAT"] = "FloatValue";
Kind2["STRING"] = "StringValue";
Kind2["BOOLEAN"] = "BooleanValue";
Kind2["NULL"] = "NullValue";
Kind2["ENUM"] = "EnumValue";
Kind2["LIST"] = "ListValue";
Kind2["OBJECT"] = "ObjectValue";
Kind2["OBJECT_FIELD"] = "ObjectField";
Kind2["DIRECTIVE"] = "Directive";
Kind2["NAMED_TYPE"] = "NamedType";
Kind2["LIST_TYPE"] = "ListType";
Kind2["NON_NULL_TYPE"] = "NonNullType";
Kind2["SCHEMA_DEFINITION"] = "SchemaDefinition";
Kind2["OPERATION_TYPE_DEFINITION"] = "OperationTypeDefinition";
Kind2["SCALAR_TYPE_DEFINITION"] = "ScalarTypeDefinition";
Kind2["OBJECT_TYPE_DEFINITION"] = "ObjectTypeDefinition";
Kind2["FIELD_DEFINITION"] = "FieldDefinition";
Kind2["INPUT_VALUE_DEFINITION"] = "InputValueDefinition";
Kind2["INTERFACE_TYPE_DEFINITION"] = "InterfaceTypeDefinition";
Kind2["UNION_TYPE_DEFINITION"] = "UnionTypeDefinition";
Kind2["ENUM_TYPE_DEFINITION"] = "EnumTypeDefinition";
Kind2["ENUM_VALUE_DEFINITION"] = "EnumValueDefinition";
Kind2["INPUT_OBJECT_TYPE_DEFINITION"] = "InputObjectTypeDefinition";
Kind2["DIRECTIVE_DEFINITION"] = "DirectiveDefinition";
Kind2["SCHEMA_EXTENSION"] = "SchemaExtension";
Kind2["SCALAR_TYPE_EXTENSION"] = "ScalarTypeExtension";
Kind2["OBJECT_TYPE_EXTENSION"] = "ObjectTypeExtension";
Kind2["INTERFACE_TYPE_EXTENSION"] = "InterfaceTypeExtension";
Kind2["UNION_TYPE_EXTENSION"] = "UnionTypeExtension";
Kind2["ENUM_TYPE_EXTENSION"] = "EnumTypeExtension";
Kind2["INPUT_OBJECT_TYPE_EXTENSION"] = "InputObjectTypeExtension";
})(Kind || (Kind = {}));
// ../../node_modules/.pnpm/graphql@16.11.0/node_modules/graphql/language/characterClasses.mjs
function isWhiteSpace(code) {
return code === 9 || code === 32;
}
function isDigit(code) {
return code >= 48 && code <= 57;
}
function isLetter(code) {
return code >= 97 && code <= 122 || // A-Z
code >= 65 && code <= 90;
}
function isNameStart(code) {
return isLetter(code) || code === 95;
}
function isNameContinue(code) {
return isLetter(code) || isDigit(code) || code === 95;
}
// ../../node_modules/.pnpm/graphql@16.11.0/node_modules/graphql/language/blockString.mjs
function dedentBlockStringLines(lines) {
var _firstNonEmptyLine2;
let commonIndent = Number.MAX_SAFE_INTEGER;
let firstNonEmptyLine = null;
let lastNonEmptyLine = -1;
for (let i = 0; i < lines.length; ++i) {
var _firstNonEmptyLine;
const line = lines[i];
const indent2 = leadingWhitespace(line);
if (indent2 === line.length) {
continue;
}
firstNonEmptyLine = (_firstNonEmptyLine = firstNonEmptyLine) !== null && _firstNonEmptyLine !== void 0 ? _firstNonEmptyLine : i;
lastNonEmptyLine = i;
if (i !== 0 && indent2 < commonIndent) {
commonIndent = indent2;
}
}
return lines.map((line, i) => i === 0 ? line : line.slice(commonIndent)).slice(
(_firstNonEmptyLine2 = firstNonEmptyLine) !== null && _firstNonEmptyLine2 !== void 0 ? _firstNonEmptyLine2 : 0,
lastNonEmptyLine + 1
);
}
function leadingWhitespace(str) {
let i = 0;
while (i < str.length && isWhiteSpace(str.charCodeAt(i))) {
++i;
}
return i;
}
function printBlockString(value, options) {
const escapedValue = value.replace(/"""/g, '\\"""');
const lines = escapedValue.split(/\r\n|[\n\r]/g);
const isSingleLine = lines.length === 1;
const forceLeadingNewLine = lines.length > 1 && lines.slice(1).every((line) => line.length === 0 || isWhiteSpace(line.charCodeAt(0)));
const hasTrailingTripleQuotes = escapedValue.endsWith('\\"""');
const hasTrailingQuote = value.endsWith('"') && !hasTrailingTripleQuotes;
const hasTrailingSlash = value.endsWith("\\");
const forceTrailingNewline = hasTrailingQuote || hasTrailingSlash;
const printAsMultipleLines = // add leading and trailing new lines only if it improves readability
(!isSingleLine || value.length > 70 || forceTrailingNewline || forceLeadingNewLine || hasTrailingTripleQuotes);
let result = "";
const skipLeadingNewLine = isSingleLine && isWhiteSpace(value.charCodeAt(0));
if (printAsMultipleLines && !skipLeadingNewLine || forceLeadingNewLine) {
result += "\n";
}
result += escapedValue;
if (printAsMultipleLines || forceTrailingNewline) {
result += "\n";
}
return '"""' + result + '"""';
}
// ../../node_modules/.pnpm/graphql@16.11.0/node_modules/graphql/language/tokenKind.mjs
var TokenKind;
(function(TokenKind2) {
TokenKind2["SOF"] = "<SOF>";
TokenKind2["EOF"] = "<EOF>";
TokenKind2["BANG"] = "!";
TokenKind2["DOLLAR"] = "$";
TokenKind2["AMP"] = "&";
TokenKind2["PAREN_L"] = "(";
TokenKind2["PAREN_R"] = ")";
TokenKind2["SPREAD"] = "...";
TokenKind2["COLON"] = ":";
TokenKind2["EQUALS"] = "=";
TokenKind2["AT"] = "@";
TokenKind2["BRACKET_L"] = "[";
TokenKind2["BRACKET_R"] = "]";
TokenKind2["BRACE_L"] = "{";
TokenKind2["PIPE"] = "|";
TokenKind2["BRACE_R"] = "}";
TokenKind2["NAME"] = "Name";
TokenKind2["INT"] = "Int";
TokenKind2["FLOAT"] = "Float";
TokenKind2["STRING"] = "String";
TokenKind2["BLOCK_STRING"] = "BlockString";
TokenKind2["COMMENT"] = "Comment";
})(TokenKind || (TokenKind = {}));
// ../../node_modules/.pnpm/graphql@16.11.0/node_modules/graphql/language/lexer.mjs
var Lexer = class {
/**
* The previously focused non-ignored token.
*/
/**
* The currently focused non-ignored token.
*/
/**
* The (1-indexed) line containing the current token.
*/
/**
* The character offset at which the current line begins.
*/
constructor(source) {
const startOfFileToken = new Token(TokenKind.SOF, 0, 0, 0, 0);
this.source = source;
this.lastToken = startOfFileToken;
this.token = startOfFileToken;
this.line = 1;
this.lineStart = 0;
}
get [Symbol.toStringTag]() {
return "Lexer";
}
/**
* Advances the token stream to the next non-ignored token.
*/
advance() {
this.lastToken = this.token;
const token = this.token = this.lookahead();
return token;
}
/**
* Looks ahead and returns the next non-ignored token, but does not change
* the state of Lexer.
*/
lookahead() {
let token = this.token;
if (token.kind !== TokenKind.EOF) {
do {
if (token.next) {
token = token.next;
} else {
const nextToken = readNextToken(this, token.end);
token.next = nextToken;
nextToken.prev = token;
token = nextToken;
}
} while (token.kind === TokenKind.COMMENT);
}
return token;
}
};
function isPunctuatorTokenKind(kind) {
return kind === TokenKind.BANG || kind === TokenKind.DOLLAR || kind === TokenKind.AMP || kind === TokenKind.PAREN_L || kind === TokenKind.PAREN_R || kind === TokenKind.SPREAD || kind === TokenKind.COLON || kind === TokenKind.EQUALS || kind === TokenKind.AT || kind === TokenKind.BRACKET_L || kind === TokenKind.BRACKET_R || kind === TokenKind.BRACE_L || kind === TokenKind.PIPE || kind === TokenKind.BRACE_R;
}
function isUnicodeScalarValue(code) {
return code >= 0 && code <= 55295 || code >= 57344 && code <= 1114111;
}
function isSupplementaryCodePoint(body, location) {
return isLeadingSurrogate(body.charCodeAt(location)) && isTrailingSurrogate(body.charCodeAt(location + 1));
}
function isLeadingSurrogate(code) {
return code >= 55296 && code <= 56319;
}
function isTrailingSurrogate(code) {
return code >= 56320 && code <= 57343;
}
function printCodePointAt(lexer, location) {
const code = lexer.source.body.codePointAt(location);
if (code === void 0) {
return TokenKind.EOF;
} else if (code >= 32 && code <= 126) {
const char = String.fromCodePoint(code);
return char === '"' ? `'"'` : `"${char}"`;
}
return "U+" + code.toString(16).toUpperCase().padStart(4, "0");
}
function createToken(lexer, kind, start, end, value) {
const line = lexer.line;
const col = 1 + start - lexer.lineStart;
return new Token(kind, start, end, line, col, value);
}
function readNextToken(lexer, start) {
const body = lexer.source.body;
const bodyLength = body.length;
let position = start;
while (position < bodyLength) {
const code = body.charCodeAt(position);
switch (code) {
// Ignored ::
// - UnicodeBOM
// - WhiteSpace
// - LineTerminator
// - Comment
// - Comma
//
// UnicodeBOM :: "Byte Order Mark (U+FEFF)"
//
// WhiteSpace ::
// - "Horizontal Tab (U+0009)"
// - "Space (U+0020)"
//
// Comma :: ,
case 65279:
// <BOM>
case 9:
// \t
case 32:
// <space>
case 44:
++position;
continue;
// LineTerminator ::
// - "New Line (U+000A)"
// - "Carriage Return (U+000D)" [lookahead != "New Line (U+000A)"]
// - "Carriage Return (U+000D)" "New Line (U+000A)"
case 10:
++position;
++lexer.line;
lexer.lineStart = position;
continue;
case 13:
if (body.charCodeAt(position + 1) === 10) {
position += 2;
} else {
++position;
}
++lexer.line;
lexer.lineStart = position;
continue;
// Comment
case 35:
return readComment(lexer, position);
// Token ::
// - Punctuator
// - Name
// - IntValue
// - FloatValue
// - StringValue
//
// Punctuator :: one of ! $ & ( ) ... : = @ [ ] { | }
case 33:
return createToken(lexer, TokenKind.BANG, position, position + 1);
case 36:
return createToken(lexer, TokenKind.DOLLAR, position, position + 1);
case 38:
return createToken(lexer, TokenKind.AMP, position, position + 1);
case 40:
return createToken(lexer, TokenKind.PAREN_L, position, position + 1);
case 41:
return createToken(lexer, TokenKind.PAREN_R, position, position + 1);
case 46:
if (body.charCodeAt(position + 1) === 46 && body.charCodeAt(position + 2) === 46) {
return createToken(lexer, TokenKind.SPREAD, position, position + 3);
}
break;
case 58:
return createToken(lexer, TokenKind.COLON, position, position + 1);
case 61:
return createToken(lexer, TokenKind.EQUALS, position, position + 1);
case 64:
return createToken(lexer, TokenKind.AT, position, position + 1);
case 91:
return createToken(lexer, TokenKind.BRACKET_L, position, position + 1);
case 93:
return createToken(lexer, TokenKind.BRACKET_R, position, position + 1);
case 123:
return createToken(lexer, TokenKind.BRACE_L, position, position + 1);
case 124:
return createToken(lexer, TokenKind.PIPE, position, position + 1);
case 125:
return createToken(lexer, TokenKind.BRACE_R, position, position + 1);
// StringValue
case 34:
if (body.charCodeAt(position + 1) === 34 && body.charCodeAt(position + 2) === 34) {
return readBlockString(lexer, position);
}
return readString(lexer, position);
}
if (isDigit(code) || code === 45) {
return readNumber(lexer, position, code);
}
if (isNameStart(code)) {
return readName(lexer, position);
}
throw syntaxError(
lexer.source,
position,
code === 39 ? `Unexpected single quote character ('), did you mean to use a double quote (")?` : isUnicodeScalarValue(code) || isSupplementaryCodePoint(body, position) ? `Unexpected character: ${printCodePointAt(lexer, position)}.` : `Invalid character: ${printCodePointAt(lexer, position)}.`
);
}
return createToken(lexer, TokenKind.EOF, bodyLength, bodyLength);
}
function readComment(lexer, start) {
const body = lexer.source.body;
const bodyLength = body.length;
let position = start + 1;
while (position < bodyLength) {
const code = body.charCodeAt(position);
if (code === 10 || code === 13) {
break;
}
if (isUnicodeScalarValue(code)) {
++position;
} else if (isSupplementaryCodePoint(body, position)) {
position += 2;
} else {
break;
}
}
return createToken(
lexer,
TokenKind.COMMENT,
start,
position,
body.slice(start + 1, position)
);
}
function readNumber(lexer, start, firstCode) {
const body = lexer.source.body;
let position = start;
let code = firstCode;
let isFloat = false;
if (code === 45) {
code = body.charCodeAt(++position);
}
if (code === 48) {
code = body.charCodeAt(++position);
if (isDigit(code)) {
throw syntaxError(
lexer.source,
position,
`Invalid number, unexpected digit after 0: ${printCodePointAt(
lexer,
position
)}.`
);
}
} else {
position = readDigits(lexer, position, code);
code = body.charCodeAt(position);
}
if (code === 46) {
isFloat = true;
code = body.charCodeAt(++position);
position = readDigits(lexer, position, code);
code = body.charCodeAt(position);
}
if (code === 69 || code === 101) {
isFloat = true;
code = body.charCodeAt(++position);
if (code === 43 || code === 45) {
code = body.charCodeAt(++position);
}
position = readDigits(lexer, position, code);
code = body.charCodeAt(position);
}
if (code === 46 || isNameStart(code)) {
throw syntaxError(
lexer.source,
position,
`Invalid number, expected digit but got: ${printCodePointAt(
lexer,
position
)}.`
);
}
return createToken(
lexer,
isFloat ? TokenKind.FLOAT : TokenKind.INT,
start,
position,
body.slice(start, position)
);
}
function readDigits(lexer, start, firstCode) {
if (!isDigit(firstCode)) {
throw syntaxError(
lexer.source,
start,
`Invalid number, expected digit but got: ${printCodePointAt(
lexer,
start
)}.`
);
}
const body = lexer.source.body;
let position = start + 1;
while (isDigit(body.charCodeAt(position))) {
++position;
}
return position;
}
function readString(lexer, start) {
const body = lexer.source.body;
const bodyLength = body.length;
let position = start + 1;
let chunkStart = position;
let value = "";
while (position < bodyLength) {
const code = body.charCodeAt(position);
if (code === 34) {
value += body.slice(chunkStart, position);
return createToken(lexer, TokenKind.STRING, start, position + 1, value);
}
if (code === 92) {
value += body.slice(chunkStart, position);
const escape = body.charCodeAt(position + 1) === 117 ? body.charCodeAt(position + 2) === 123 ? readEscapedUnicodeVariableWidth(lexer, position) : readEscapedUnicodeFixedWidth(lexer, position) : readEscapedCharacter(lexer, position);
value += escape.value;
position += escape.size;
chunkStart = position;
continue;
}
if (code === 10 || code === 13) {
break;
}
if (isUnicodeScalarValue(code)) {
++position;
} else if (isSupplementaryCodePoint(body, position)) {
position += 2;
} else {
throw syntaxError(
lexer.source,
position,
`Invalid character within String: ${printCodePointAt(
lexer,
position
)}.`
);
}
}
throw syntaxError(lexer.source, position, "Unterminated string.");
}
function readEscapedUnicodeVariableWidth(lexer, position) {
const body = lexer.source.body;
let point = 0;
let size = 3;
while (size < 12) {
const code = body.charCodeAt(position + size++);
if (code === 125) {
if (size < 5 || !isUnicodeScalarValue(point)) {
break;
}
return {
value: String.fromCodePoint(point),
size
};
}
point = point << 4 | readHexDigit(code);
if (point < 0) {
break;
}
}
throw syntaxError(
lexer.source,
position,
`Invalid Unicode escape sequence: "${body.slice(
position,
position + size
)}".`
);
}
function readEscapedUnicodeFixedWidth(lexer, position) {
const body = lexer.source.body;
const code = read16BitHexCode(body, position + 2);
if (isUnicodeScalarValue(code)) {
return {
value: String.fromCodePoint(code),
size: 6
};
}
if (isLeadingSurrogate(code)) {
if (body.charCodeAt(position + 6) === 92 && body.charCodeAt(position + 7) === 117) {
const trailingCode = read16BitHexCode(body, position + 8);
if (isTrailingSurrogate(trailingCode)) {
return {
value: String.fromCodePoint(code, trailingCode),
size: 12
};
}
}
}
throw syntaxError(
lexer.source,
position,
`Invalid Unicode escape sequence: "${body.slice(position, position + 6)}".`
);
}
function read16BitHexCode(body, position) {
return readHexDigit(body.charCodeAt(position)) << 12 | readHexDigit(body.charCodeAt(position + 1)) << 8 | readHexDigit(body.charCodeAt(position + 2)) << 4 | readHexDigit(body.charCodeAt(position + 3));
}
function readHexDigit(code) {
return code >= 48 && code <= 57 ? code - 48 : code >= 65 && code <= 70 ? code - 55 : code >= 97 && code <= 102 ? code - 87 : -1;
}
function readEscapedCharacter(lexer, position) {
const body = lexer.source.body;
const code = body.charCodeAt(position + 1);
switch (code) {
case 34:
return {
value: '"',
size: 2
};
case 92:
return {
value: "\\",
size: 2
};
case 47:
return {
value: "/",
size: 2
};
case 98:
return {
value: "\b",
size: 2
};
case 102:
return {
value: "\f",
size: 2
};
case 110:
return {
value: "\n",
size: 2
};
case 114:
return {
value: "\r",
size: 2
};
case 116:
return {
value: " ",
size: 2
};
}
throw syntaxError(
lexer.source,
position,
`Invalid character escape sequence: "${body.slice(
position,
position + 2
)}".`
);
}
function readBlockString(lexer, start) {
const body = lexer.source.body;
const bodyLength = body.length;
let lineStart = lexer.lineStart;
let position = start + 3;
let chunkStart = position;
let currentLine = "";
const blockLines = [];
while (position < bodyLength) {
const code = body.charCodeAt(position);
if (code === 34 && body.charCodeAt(position + 1) === 34 && body.charCodeAt(position + 2) === 34) {
currentLine += body.slice(chunkStart, position);
blockLines.push(currentLine);
const token = createToken(
lexer,
TokenKind.BLOCK_STRING,
start,
position + 3,
// Return a string of the lines joined with U+000A.
dedentBlockStringLines(blockLines).join("\n")
);
lexer.line += blockLines.length - 1;
lexer.lineStart = lineStart;
return token;
}
if (code === 92 && body.charCodeAt(position + 1) === 34 && body.charCodeAt(position + 2) === 34 && body.charCodeAt(position + 3) === 34) {
currentLine += body.slice(chunkStart, position);
chunkStart = position + 1;
position += 4;
continue;
}
if (code === 10 || code === 13) {
currentLine += body.slice(chunkStart, position);
blockLines.push(currentLine);
if (code === 13 && body.charCodeAt(position + 1) === 10) {
position += 2;
} else {
++position;
}
currentLine = "";
chunkStart = position;
lineStart = position;
continue;
}
if (isUnicodeScalarValue(code)) {
++position;
} else if (isSupplementaryCodePoint(body, position)) {
position += 2;
} else {
throw syntaxError(
lexer.source,
position,
`Invalid character within String: ${printCodePointAt(
lexer,
position
)}.`
);
}
}
throw syntaxError(lexer.source, position, "Unterminated string.");
}
function readName(lexer, start) {
const body = lexer.source.body;
const bodyLength = body.length;
let position = start + 1;
while (position < bodyLength) {
const code = body.charCodeAt(position);
if (isNameContinue(code)) {
++position;
} else {
break;
}
}
return createToken(
lexer,
TokenKind.NAME,
start,
position,
body.slice(start, position)
);
}
// ../../node_modules/.pnpm/graphql@16.11.0/node_modules/graphql/jsutils/inspect.mjs
var MAX_ARRAY_LENGTH = 10;
var MAX_RECURSIVE_DEPTH = 2;
function inspect(value) {
return formatValue(value, []);
}
function formatValue(value, seenValues) {
switch (typeof value) {
case "string":
return JSON.stringify(value);
case "function":
return value.name ? `[function ${value.name}]` : "[function]";
case "object":
return formatObjectValue(value, seenValues);
default:
return String(value);
}
}
function formatObjectValue(value, previouslySeenValues) {
if (value === null) {
return "null";
}
if (previouslySeenValues.includes(value)) {
return "[Circular]";
}
const seenValues = [...previouslySeenValues, value];
if (isJSONable(value)) {
const jsonValue = value.toJSON();
if (jsonValue !== value) {
return typeof jsonValue === "string" ? jsonValue : formatValue(jsonValue, seenValues);
}
} else if (Array.isArray(value)) {
return formatArray(value, seenValues);
}
return formatObject(value, seenValues);
}
function isJSONable(value) {
return typeof value.toJSON === "function";
}
function formatObject(object, seenValues) {
const entries = Object.entries(object);
if (entries.length === 0) {
return "{}";
}
if (seenValues.length > MAX_RECURSIVE_DEPTH) {
return "[" + getObjectTag(object) + "]";
}
const properties = entries.map(
([key, value]) => key + ": " + formatValue(value, seenValues)
);
return "{ " + properties.join(", ") + " }";
}
function formatArray(array, seenValues) {
if (array.length === 0) {
return "[]";
}
if (seenValues.length > MAX_RECURSIVE_DEPTH) {
return "[Array]";
}
const len = Math.min(MAX_ARRAY_LENGTH, array.length);
const remaining = array.length - len;
const items = [];
for (let i = 0; i < len; ++i) {
items.push(formatValue(array[i], seenValues));
}
if (remaining === 1) {
items.push("... 1 more item");
} else if (remaining > 1) {
items.push(`... ${remaining} more items`);
}
return "[" + items.join(", ") + "]";
}
function getObjectTag(object) {
const tag = Object.prototype.toString.call(object).replace(/^\[object /, "").replace(/]$/, "");
if (tag === "Object" && typeof object.constructor === "function") {
const name = object.constructor.name;
if (typeof name === "string" && name !== "") {
return name;
}
}
return tag;
}
var instanceOf = (
/* c8 ignore next 6 */
// FIXME: https://github.com/graphql/graphql-js/issues/2317
function instanceOf3(value, constructor) {
if (value instanceof constructor) {
return true;
}
if (typeof value === "object" && value !== null) {
var _value$constructor;
const className = constructor.prototype[Symbol.toStringTag];
const valueClassName = (
// We still need to support constructor's name to detect conflicts with older versions of this library.
Symbol.toStringTag in value ? value[Symbol.toStringTag] : (_value$constructor = value.constructor) === null || _value$constructor === void 0 ? void 0 : _value$constructor.name
);
if (className === valueClassName) {
const stringifiedValue = inspect(value);
throw new Error(`Cannot use ${className} "${stringifiedValue}" from another module or realm.
Ensure that there is only one instance of "graphql" in the node_modules
directory. If different versions of "graphql" are the dependencies of other
relied on modules, use "resolutions" to ensure only one version is installed.
https://yarnpkg.com/en/docs/selective-version-resolutions
Duplicate "graphql" modules cannot be used at the same time since different
versions may have different capabilities and behavior. The data from one
version used in the function from another could produce confusing and
spurious results.`);
}
}
return false;
}
);
// ../../node_modules/.pnpm/graphql@16.11.0/node_modules/graphql/language/source.mjs
var Source = class {
constructor(body, name = "GraphQL request", locationOffset = {
line: 1,
column: 1
}) {
typeof body === "string" || devAssert(false, `Body must be a string. Received: ${inspect(body)}.`);
this.body = body;
this.name = name;
this.locationOffset = locationOffset;
this.locationOffset.line > 0 || devAssert(
false,
"line in locationOffset is 1-indexed and must be positive."
);
this.locationOffset.column > 0 || devAssert(
false,
"column in locationOffset is 1-indexed and must be positive."
);
}
get [Symbol.toStringTag]() {
return "Source";
}
};
function isSource(source) {
return instanceOf(source, Source);
}
// ../../node_modules/.pnpm/graphql@16.11.0/node_modules/graphql/language/parser.mjs
function parse(source, options) {
const parser = new Parser(source, options);
const document = parser.parseDocument();
Object.defineProperty(document, "tokenCount", {
enumerable: false,
value: parser.tokenCount
});
return document;
}
var Parser = class {
constructor(source, options = {}) {
const sourceObj = isSource(source) ? source : new Source(source);
this._lexer = new Lexer(sourceObj);
this._options = options;
this._tokenCounter = 0;
}
get tokenCount() {
return this._tokenCounter;
}
/**
* Converts a name lex token into a name parse node.
*/
parseName() {
const token = this.expectToken(TokenKind.NAME);
return this.node(token, {
kind: Kind.NAME,
value: token.value
});
}
// Implements the parsing rules in the Document section.
/**
* Document : Definition+
*/
parseDocument() {
return this.node(this._lexer.token, {
kind: Kind.DOCUMENT,
definitions: this.many(
TokenKind.SOF,
this.parseDefinition,
TokenKind.EOF
)
});
}
/**
* Definition :
* - ExecutableDefinition
* - TypeSystemDefinition
* - TypeSystemExtension
*
* ExecutableDefinition :
* - OperationDefinition
* - FragmentDefinition
*
* TypeSystemDefinition :
* - SchemaDefinition
* - TypeDefinition
* - DirectiveDefinition
*
* TypeDefinition :
* - ScalarTypeDefinition
* - ObjectTypeDefinition
* - InterfaceTypeDefinition
* - UnionTypeDefinition
* - EnumTypeDefinition
* - InputObjectTypeDefinition
*/
parseDefinition() {
if (this.peek(TokenKind.BRACE_L)) {
return this.parseOperationDefinition();
}
const hasDescription = this.peekDescription();
const keywordToken = hasDescription ? this._lexer.lookahead() : this._lexer.token;
if (keywordToken.kind === TokenKind.NAME) {
switch (keywordToken.value) {
case "schema":
return this.parseSchemaDefinition();
case "scalar":
return this.parseScalarTypeDefinition();
case "type":
return this.parseObjectTypeDefinition();
case "interface":
return this.parseInterfaceTypeDefinition();
case "union":
return this.parseUnionTypeDefinition();
case "enum":
return this.parseEnumTypeDefinition();
case "input":
return this.parseInputObjectTypeDefinition();
case "directive":
return this.parseDirectiveDefinition();
}
if (hasDescription) {
throw syntaxError(
this._lexer.source,
this._lexer.token.start,
"Unexpected description, descriptions are supported only on type definitions."
);
}
switch (keywordToken.value) {
case "query":
case "mutation":
case "subscription":
return this.parseOperationDefinition();
case "fragment":
return this.parseFragmentDefinition();
case "extend":
return this.parseTypeSystemExtension();
}
}
throw this.unexpected(keywordToken);
}
// Implements the parsing rules in the Operations section.
/**
* OperationDefinition :
* - SelectionSet
* - OperationType Name? VariableDefinitions? Directives? SelectionSet
*/
parseOperationDefinition() {
const start = this._lexer.token;
if (this.peek(TokenKind.BRACE_L)) {
return this.node(start, {
kind: Kind.OPERATION_DEFINITION,
operation: OperationTypeNode.QUERY,
name: void 0,
variableDefinitions: [],
directives: [],
selectionSet: this.parseSelectionSet()
});
}
const operation = this.parseOperationType();
let name;
if (this.peek(TokenKind.NAME)) {
name = this.parseName();
}
return this.node(start, {
kind: Kind.OPERATION_DEFINITION,
operation,
name,
variableDefinitions: this.parseVariableDefinitions(),
directives: this.parseDirectives(false),
selectionSet: this.parseSelectionSet()
});
}
/**
* OperationType : one of query mutation subscription
*/
parseOperationType() {
const operationToken = this.expectToken(TokenKind.NAME);
switch (operationToken.value) {
case "query":
return OperationTypeNode.QUERY;
case "mutation":
return OperationTypeNode.MUTATION;
case "subscription":
return OperationTypeNode.SUBSCRIPTION;
}
throw this.unexpected(operationToken);
}
/**
* VariableDefinitions : ( VariableDefinition+ )
*/
parseVariableDefinitions() {
return this.optionalMany(
TokenKind.PAREN_L,
this.parseVariableDefinition,
TokenKind.PAREN_R
);
}
/**
* VariableDefinition : Variable : Type DefaultValue? Directives[Const]?
*/
parseVariableDefinition() {
return this.node(this._lexer.token, {
kind: Kind.VARIABLE_DEFINITION,
variable: this.parseVariable(),
type: (this.expectToken(TokenKind.COLON), this.parseTypeReference()),
defaultValue: this.expectOptionalToken(TokenKind.EQUALS) ? this.parseConstValueLiteral() : void 0,
directives: this.parseConstDirectives()
});
}
/**
* Variable : $ Name
*/
parseVariable() {
const start = this._lexer.token;
this.expectToken(TokenKind.DOLLAR);
return this.node(start, {
kind: Kind.VARIABLE,
name: this.parseName()
});
}
/**
* ```
* SelectionSet : { Selection+ }
* ```
*/
parseSelectionSet() {
return this.node(this._lexer.token, {
kind: Kind.SELECTION_SET,
selections: this.many(
TokenKind.BRACE_L,
this.parseSelection,
TokenKind.BRACE_R
)
});
}
/**
* Selection :
* - Field
* - FragmentSpread
* - InlineFragment
*/
parseSelection() {
return this.peek(TokenKind.SPREAD) ? this.parseFragment() : this.parseField();
}
/**
* Field : Alias? Name Arguments? Directives? SelectionSet?
*
* Alias : Name :
*/
parseField() {
const start = this._lexer.token;
const nameOrAlias = this.parseName();
let alias;
let name;
if (this.expectOptionalToken(TokenKind.COLON)) {
alias = nameOrAlias;
name = this.parseName();
} else {
name = nameOrAlias;
}
return this.node(start, {
kind: Kind.FIELD,
alias,
name,
arguments: this.parseArguments(false),
directives: this.parseDirectives(false),
selectionSet: this.peek(TokenKind.BRACE_L) ? this.parseSelectionSet() : void 0
});
}
/**
* Arguments[Const] : ( Argument[?Const]+ )
*/
parseArguments(isConst) {
const item = isConst ? this.parseConstArgument : this.parseArgument;
return this.optionalMany(TokenKind.PAREN_L, item, TokenKind.PAREN_R);
}
/**
* Argument[Const] : Name : Value[?Const]
*/
parseArgument(isConst = false) {
const start = this._lexer.token;
const name = this.parseName();
this.expectToken(TokenKind.COLON);
return this.node(start, {
kind: Kind.ARGUMENT,
name,
value: this.parseValueLiteral(isConst)
});
}
parseConstArgument() {
return this.parseArgument(true);
}
// Implements the parsing rules in the Fragments section.
/**
* Corresponds to both FragmentSpread and InlineFragment in the spec.
*
* FragmentSpread : ... FragmentName Directives?
*
* InlineFragment : ... TypeCondition? Directives? SelectionSet
*/
parseFragment() {
const start = this._lexer.token;
this.expectToken(TokenKind.SPREAD);
const hasTypeCondition = this.expectOptionalKeyword("on");
if (!hasTypeCondition && this.peek(TokenKind.NAME)) {
return this.node(start, {
kind: Kind.FRAGMENT_SPREAD,
name: this.parseFragmentName(),
directives: this.parseDirectives(false)
});
}
return this.node(start, {
kind: Kind.INLINE_FRAGMENT,
typeCondition: hasTypeCondition ? this.parseNamedType() : void 0,
directives: this.parseDirectives(false),
selectionSet: this.parseSelectionSet()
});
}
/**
* FragmentDefinition :
* - fragment FragmentName on TypeCondition Directives? SelectionSet
*
* TypeCondition : NamedType
*/
parseFragmentDefinition() {
const start = this._lexer.token;
this.expectKeyword("fragment");
if (this._options.allowLegacyFragmentVariables === true) {
return this.node(start, {
kind: Kind.FRAGMENT_DEFINITION,
name: this.parseFragmentName(),
variableDefinitions: this.parseVariableDefinitions(),
typeCondition: (this.expectKeyword("on"), this.parseNamedType()),
directives: this.parseDirectives(false),
selectionSet: this.parseSelectionSet()
});
}
return this.node(start, {
kind: Kind.FRAGMENT_DEFINITION,
name: this.parseFragmentName(),
typeCondition: (this.expectKeyword("on"), this.parseNamedType()),
directives: this.parseDirectives(false),
selectionSet: this.parseSelectionSet()
});
}
/**
* FragmentName : Name but not `on`
*/
parseFragmentName() {
if (this._lexer.token.value === "on") {
throw this.unexpected();
}
return this.parseName();
}
// Implements the parsing rules in the Values section.
/**
* Value[Const] :
* - [~Const] Variable
* - IntValue
* - FloatValue
* - StringValue
* - BooleanValue
* - NullValue
* - EnumValue
* - ListValue[?Const]
* - ObjectValue[?Const]
*
* BooleanValue : one of `true` `false`
*
* NullValue : `null`
*
* EnumValue : Name but not `true`, `false` or `null`
*/
parseValueLiteral(isConst) {
const token = this._lexer.token;
switch (token.kind) {
case TokenKind.BRACKET_L:
return this.parseList(isConst);
case TokenKind.BRACE_L:
return this.parseObject(isConst);
case TokenKind.INT:
this.advanceLexer();
return this.node(token, {
kind: Kind.INT,
value: token.value
});
case TokenKind.FLOAT:
this.advanceLexer();
return this.node(token, {
kind: Kind.FLOAT,
value: token.value
});
case TokenKind.STRING:
case TokenKind.BLOCK_STRING:
return this.parseStringLiteral();
case TokenKind.NAME:
this.advanceLexer();
switch (token.value) {
case "true":
return this.node(token, {
kind: Kind.BOOLEAN,
value: true
});
case "false":
return this.node(token, {
kind: Kind.BOOLEAN,
value: false
});
case "null":
return this.node(token, {
kind: Kind.NULL
});
default:
return this.node(token, {
kind: Kind.ENUM,
value: token.value
});
}
case TokenKind.DOLLAR:
if (isConst) {
this.expectToken(TokenKind.DOLLAR);
if (this._lexer.token.kind === TokenKind.NAME) {
const varName = this._lexer.token.value;
throw syntaxError(
this._lexer.source,
token.start,
`Unexpected variable "$${varName}" in constant value.`
);
} else {
throw this.unexpected(token);
}
}
return this.parseVariable();
default:
throw this.unexpected();
}
}
parseConstValueLiteral() {
return this.parseValueLiteral(true);
}
parseStringLiteral() {
const token = this._lexer.token;
this.advanceLexer();
return this.node(token, {
kind: Kind.STRING,
value: token.value,
block: token.kind === TokenKind.BLOCK_STRING
});
}
/**
* ListValue[Const] :
* - [ ]
* - [ Value[?Const]+ ]
*/
parseList(isConst) {
const item = () => this.parseValueLiteral(isConst);
return this.node(this._lexer.token, {
kind: Kind.LIST,
values: this.any(TokenKind.BRACKET_L, item, TokenKind.BRACKET_R)
});
}
/**
* ```
* ObjectValue[Const] :
* - { }
* - { ObjectField[?Const]+ }
* ```
*/
parseObject(isConst) {
const item = () => this.parseObjectField(isConst);
return this.node(this._lexer.token, {
kind: Kind.OBJECT,
fields: this.any(TokenKind.BRACE_L, item, TokenKind.BRACE_R)
});
}
/**
* ObjectField[Const] : Name : Value[?Const]
*/
parseObjectField(isConst) {
const start = this._lexer.token;
const name = this.parseName();
this.expectToken(TokenKind.COLON);
return this.node(start, {
kind: Kind.OBJECT_FIELD,
name,
value: this.parseValueLiteral(isConst)
});
}
// Implements the parsing rules in the Directives section.
/**
* Directives[Const] : Directive[?Const]+
*/
parseDirectives(isConst) {
const directives = [];
while (this.peek(TokenKind.AT)) {
directives.push(this.parseDirective(isConst));
}
return directives;
}
parseConstDirectives() {
return this.parseDirectives(true);
}
/**
* ```
* Directive[Const] : @ Name Arguments[?Const]?
* ```
*/
parseDirective(isConst) {
const start = this._lexer.token;
this.expectToken(TokenKind.AT);
return this.node(start, {
kind: Kind.DIRECTIVE,
name: this.parseName(),
arguments: this.parseArguments(isConst)
});
}
// Implements the parsing rules in the Types section.
/**
* Type :
* - NamedType
* - ListType
* - NonNullType
*/
parseTypeReference() {
const start = this._lexer.token;
let type;
if (this.expectOptionalToken(TokenKind.BRACKET_L)) {
const innerType = this.parseTypeReference();
this.expectToken(TokenKind.BRACKET_R);
type = this.node(start, {
kind: Kind.LIST_TYPE,
type: innerType
});
} else {
type = this.parseNamedType();
}
if (this.expectOptionalToken(TokenKind.BANG)) {
return this.node(start, {
kind: Kind.NON_NULL_TYPE,
type
});
}
return type;
}
/**
* NamedType : Name
*/
parseNamedType() {
return this.node(this._lexer.token, {
kind: Kind.NAMED_TYPE,
name: this.parseName()
});
}
// Implements the parsing rules in the Type Definition section.
peekDescription() {
return this.peek(TokenKind.STRING) || this.peek(TokenKind.BLOCK_STRING);
}
/**
* Description : StringValue
*/
parseDescription() {
if (this.peekDescription()) {
return this.parseStringLiteral();
}
}
/**
* ```
* SchemaDefinition : Description? schema Directives[Const]? { OperationTypeDefinition+ }
* ```
*/
parseSchemaDefinition() {
const start = this._lexer.token;
const description = this.parseDescription();
this.expectKeyword("schema");
const directives = this.parseConstDirectives();
const operationTypes = this.many(
TokenKind.BRACE_L,
this.parseOperationTypeDefinition,
TokenKind.BRACE_R
);
return this.node(start, {
kind: Kind.SCHEMA_DEFINITION,
description,
directives,
operationTypes
});
}
/**
* OperationTypeDefinition : OperationType : NamedType
*/
parseOperationTypeDefinition() {
const start = this._lexer.token;
const operation = this.parseOperationType();
this.expectToken(TokenKind.COLON);
const type = this.parseNamedType();
return this.node(start, {
kind: Kind.OPERATION_TYPE_DEFINITION,
operation,
type
});
}
/**
* ScalarTypeDefinition : Description? scalar Name Directives[Const]?
*/
parseScalarTypeDefinition() {
const start = this._lexer.token;
const description = this.parseDescription();
this.expectKeyword("scalar");
const name = this.parseName();
const directives = this.parseConstDirectives();
return this.node(start, {
kind: Kind.SCALAR_TYPE_DEFINITION,
description,
name,
directives
});
}
/**
* ObjectTypeDefinition :
* Description?
* type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition?
*/
parseObjectTypeDefinition() {
const start = this._lexer.token;
const description = this.parseDescription();
this.expectKeyword("type");
const name = this.parseName();
const interfaces = this.parseImplementsInterfaces();
const directives = this.parseConstDirectives();
const fields = this.parseFieldsDefinition();
return this.node(start, {
kind: Kind.OBJECT_TYPE_DEFINITION,
description,
name,
interfaces,
directives,
fields
});
}
/**
* ImplementsInterfaces :
* - implements `&`? NamedType
* - ImplementsInterfaces & NamedType
*/
parseImplementsInterfaces() {
return this.expectOptionalKeyword("implements") ? this.delimitedMany(TokenKind.AMP, this.parseNamedType) : [];
}
/**
* ```
* FieldsDefinition : { FieldDefinition+ }
* ```
*/
parseFieldsDefinition() {
return this.optionalMany(
TokenKind.BRACE_L,
this.parseFieldDefinition,
TokenKind.BRACE_R
);
}
/**
* FieldDefinition :
* - Description? Name ArgumentsDefinition? : Type Directives[Const]?
*/
parseFieldDefinition() {
const start = this._lexer.token;
const description = this.parseDescription();
const name = this.parseName();
const args = this.parseArgumentDefs();
this.expectToken(TokenKind.COLON);
const type = this.parseTypeReference();
const directives = this.parseConstDirectives();
return this.node(start, {
kind: Kind.FIELD_DEFINITION,
description,
name,
arguments: args,
type,
directives
});
}
/**
* ArgumentsDefinition : ( InputValueDefinition+ )
*/
parseArgumentDefs() {
return this.optionalMany(
TokenKind.PAREN_L,
this.parseInputValueDef,
TokenKind.PAREN_R
);
}
/**
* InputValueDefinition :
* - Description? Name : Type DefaultValue? Directives[Const]?
*/
parseInputValueDef() {
const start = this._lexer.token;
const description = this.parseDescription();
const name = this.parseName();
this.expectToken(TokenKind.COLON);
const type = this.parseTypeReference();
let defaultValue;
if (this.expectOptionalToken(TokenKind.EQUALS)) {
defaultValue = this.parseConstValueLiteral();
}
const directives = this.parseConstDirectives();
return this.node(start, {
kind: Kind.INPUT_VALUE_DEFINITION,
description,
name,
type,
defaultValue,
directives
});
}
/**
* InterfaceTypeDefinition :
* - Description? interface Name Directives[Const]? FieldsDefinition?
*/
parseInterfaceTypeDefinition() {
const start = this._lexer.token;
const description = this.parseDescription();
this.expectKeyword("interface");
const name = this.parseName();
const interfaces = this.parseImplementsInterfaces();
const directives = this.parseConstDirectives();
const fields = this.parseFieldsDefinition();
return this.node(start, {
kind: Kind.INTERFACE_TYPE_DEFINITION,
description,
name,
interfaces,
directives,
fields
});
}
/**
* UnionTypeDefinition :
* - Description? union Name Directives[Const]? UnionMemberTypes?
*/
parseUnionTypeDefinition() {
const start = this._lexer.token;
const description = this.parseDescription();
this.expectKeyword("union");
const name = this.parseName();
const directives = this.parseConstDirectives();
const types = this.parseUnionMemberTypes();
return this.node(start, {
kind: Kind.UNION_TYPE_DEFINITION,
description,
name,
directives,
types
});
}
/**
* UnionMemberTypes :
* - = `|`? NamedType
* - UnionMemberTypes | NamedType
*/
parseUnionMemberTypes() {
return this.expectOptionalToken(TokenKind.EQUALS) ? this.delimitedMany(TokenKind.PIPE, this.parseNamedType) : [];
}
/**
* EnumTypeDefinition :
* - Description? enum Name Directives[Const]? EnumValuesDefinition?
*/
parseEnumTypeDefinition() {
const start = this._lexer.token;
const description = this.parseDescription();
this.expectKeyword("enum");
const name = this.parseName();
const directives = this.parseConstDirectives();
const values = this.parseEnumValuesDefinition();
return this.node(start, {
kind: Kind.ENUM_TYPE_DEFINITION,
description,
name,
directives,
values
});
}
/**
* ```
* EnumValuesDefinition : { EnumValueDefinition+ }
* ```
*/
parseEnumValuesDefinition() {
return this.optionalMany(
TokenKind.BRACE_L,
this.parseEnumValueDefinition,
TokenKind.BRACE_R
);
}
/**
* EnumValueDefinition : Description? EnumValue Directives[Const]?
*/
parseEnumValueDefinition() {
const start = this._lexer.token;
const description = this.parseDescription();
const name = this.parseEnumValueName();
const directives = this.parseConstDirectives();
return this.node(start, {
kind: Kind.ENUM_VALUE_DEFINITION,
description,
name,
directives
});
}
/**
* EnumValue : Name but not `true`, `false` or `null`
*/
parseEnumValueName() {
if (this._lexer.token.value === "true" || this._lexer.token.value === "false" || this._lexer.token.value === "null") {
throw syntaxError(
this._lexer.source,
this._lexer.token.start,
`${getTokenDesc(
this._lexer.token
)} is reserved and cannot be used for an enum value.`
);
}
return this.parseName();
}
/**
* InputObjectTypeDefinition :
* - Description? input Name Directives[Const]? InputFieldsDefinition?
*/
parseInputObjectTypeDefinition() {
const start = this._lexer.token;
const description = this.parseDescription();
this.expectKeyword("input");
const name = this.parseName();
const directives = this.parseConstDirectives();
const fields = this.parseInputFieldsDefinition();
return this.node(start, {
kind: Kind.INPUT_OBJECT_TYPE_DEFINITION,
description,
name,
directives,
fields
});
}
/**
* ```
* InputFieldsDefinition : { InputValueDefinition+ }
* ```
*/
parseInputFieldsDefinition() {
return this.optionalMany(
TokenKind.BRACE_L,
this.parseInputValueDef,
TokenKind.BRACE_R
);
}
/**
* TypeSystemExtension :
* - SchemaExtension
* - TypeExtension
*
* TypeExtension :
* - ScalarTypeExtension
* - ObjectTypeExtension
* - InterfaceTypeExtension
* - UnionTypeExtension
* - EnumTypeExtension
* - InputObjectTypeDefinition
*/
parseTypeSystemExtension() {
const keywordToken = this._lexer.lookahead();
if (keywordToken.kind === TokenKind.NAME) {
switch (keywordToken.value) {
case "schema":
return this.parseSchemaExtension();
case "scalar":
return this.parseScalarTypeExtension();
case "type":
return this.parseObjectTypeExtension();
case "interface":
return this.parseInterfaceTypeExtension();
case "union":
return this.parseUnionTypeExtension();
case "enum":
return this.parseEnumTypeExtension();
case "input":
return this.parseInputObjectTypeExtension();
}
}
throw this.unexpected(keywordToken);
}
/**
* ```
* SchemaExtension :
* - extend schema Directives[Const]? { OperationTypeDefinition+ }
* - extend schema Directives[Const]
* ```
*/
parseSchemaExtension() {
const start = this._lexer.token;
this.expectKeyword("extend");
this.expectKeyword("schema");
const directives = this.parseConstDirectives();
const operationTypes = this.optionalMany(
TokenKind.BRACE_L,
this.parseOperationTypeDefinition,
TokenKind.BRACE_R
);
if (directives.length === 0 && operationTypes.length === 0) {
throw this.unexpected();
}
return this.node(start, {
kind: Kind.SCHEMA_EXTENSION,
directives,
operationTypes
});
}
/**
* ScalarTypeExtension :
* - extend scalar Name Directives[Const]
*/
parseScalarTypeExtension() {
const start = this._lexer.token;
this.expectKeyword("extend");
this.expectKeyword("scalar");
const name = this.parseName();
const directives = this.parseConstDirectives();
if (directives.length === 0) {
throw this.unexpected();
}
return this.node(start, {
kind: Kind.SCALAR_TYPE_EXTENSION,
name,
directives
});
}
/**
* ObjectTypeExtension :
* - extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition
* - extend type Name ImplementsInterfaces? Directives[Const]
* - extend type Name ImplementsInterfaces
*/
parseObjectTypeExtension() {
const start = this._lexer.token;
this.expectKeyword("extend");
this.expectKeyword("type");
const name = this.parseName();
const interfaces = this.parseImplementsInterfaces();
const directives = this.parseConstDirectives();
const fields = this.parseFieldsDefinition();
if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) {
throw this.unexpected();
}
return this.node(start, {
kind: Kind.OBJECT_TYPE_EXTENSION,
name,
interfaces,
directives,
fields
});
}
/**
* InterfaceTypeExtension :
* - extend interface Name ImplementsInterfaces? Directives[Const]? FieldsDefinition
* - extend interface Name ImplementsInterfaces? Directives[Const]
* - extend interface Name ImplementsInterfaces
*/
parseInterfaceTypeExtension() {
const start = this._lexer.token;
this.expectKeyword("extend");
this.expectKeyword("interface");
const name = this.parseName();
const interfaces = this.parseImplementsInterfaces();
const directives = this.parseConstDirectives();
const fields = this.parseFieldsDefinition();
if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) {
throw this.unexpected();
}
return this.node(start, {
kind: Kind.INTERFACE_TYPE_EXTENSION,
name,
interfaces,
directives,
fields
});
}
/**
* UnionTypeExtension :
* - extend union Name Directives[Const]? UnionMemberTypes
* - extend union Name Directives[Const]
*/
parseUnionTypeExtension() {
const start = this._lexer.token;
this.expectKeyword("extend");
this.expectKeyword("union");
const name = this.parseName();
const directives = this.parseConstDirectives();
const types = this.parseUnionMemberTypes();
if (directives.length === 0 && types.length === 0) {
throw this.unexpected();
}
return this.node(start, {
kind: Kind.UNION_TYPE_EXTENSION,
name,
directives,
types
});
}
/**
* EnumTypeExtension :
* - extend enum Name Directives[Const]? EnumValuesDefinition
* - extend enum Name Directives[Const]
*/
parseEnumTypeExtension() {
const start = this._lexer.token;
this.expectKeyword("extend");
this.expectKeyword("enum");
const name = this.parseName();
const directives = this.parseConstDirectives();
const values = this.parseEnumValuesDefinition();
if (directives.length === 0 && values.length === 0) {
throw this.unexpected();
}
return this.node(start, {
kind: Kind.ENUM_TYPE_EXTENSION,
name,
directives,
values
});
}
/**
* InputObjectTypeExtension :
* - extend input Name Directives[Const]? InputFieldsDefinition
* - extend input Name Directives[Const]
*/
parseInputObjectTypeExtension() {
const start = this._lexer.token;
this.expectKeyword("extend");
this.expectKeyword("input");
const name = this.parseName();
const directives = this.parseConstDirectives();
const fields = this.parseInputFieldsDefinition();
if (directives.length === 0 && fields.length === 0) {
throw this.unexpected();
}
return this.node(start, {
kind: Kind.INPUT_OBJECT_TYPE_EXTENSION,
name,
directives,
fields
});
}
/**
* ```
* DirectiveDefinition :
* - Description? directive @ Name ArgumentsDefinition? `repeatable`? on DirectiveLocations
* ```
*/
parseDirectiveDefinition() {
const start = this._lexer.token;
const description = this.parseDescription();
this.expectKeyword("directive");
this.expectToken(TokenKind.AT);
const name = this.parseName();
const args = this.parseArgumentDefs();
const repeatable = this.expectOptionalKeyword("repeatable");
this.expectKeyword("on");
const locations = this.parseDirectiveLocations();
return this.node(start, {
kind: Kind.DIRECTIVE_DEFINITION,
description,
name,
arguments: args,
repeatable,
locations
});
}
/**
* DirectiveLocations :
* - `|`? DirectiveLocation
* - DirectiveLocations | DirectiveLocation
*/
parseDirectiveLocations() {
return this.delimitedMany(TokenKind.PIPE, this.parseDirectiveLocation);
}
/*
* DirectiveLocation :
* - ExecutableDirectiveLocation
* - TypeSystemDirectiveLocation
*
* ExecutableDirectiveLocation : one of
* `QUERY`
* `MUTATION`
* `SUBSCRIPTION`
* `FIELD`
* `FRAGMENT_DEFINITION`
* `FRAGMENT_SPREAD`
* `INLINE_FRAGMENT`
*
* TypeSystemDirectiveLocation : one of
* `SCHEMA`
* `SCALAR`
* `OBJECT`
* `FIELD_DEFINITION`
* `ARGUMENT_DEFINITION`
* `INTERFACE`
* `UNION`
* `ENUM`
* `ENUM_VALUE`
* `INPUT_OBJECT`
* `INPUT_FIELD_DEFINITION`
*/
parseDirectiveLocation() {
const start = this._lexer.token;
const name = this.parseName();
if (Object.prototype.hasOwnProperty.call(DirectiveLocation, name.value)) {
return name;
}
throw this.unexpected(start);
}
// Core parsing utility functions
/**
* Returns a node that, if configured to do so, sets a "loc" field as a
* location object, used to identify the place in the source that created a
* given parsed object.
*/
node(startToken, node) {
if (this._options.noLocation !== true) {
node.loc = new Location(
startToken,
this._lexer.lastToken,
this._lexer.source
);
}
return node;
}
/**
* Determines if the next token is of a given kind
*/
peek(kind) {
return this._lexer.token.kind === kind;
}
/**
* If the next token is of the given kind, return that token after advancing the lexer.
* Otherwise, do not change the parser state and throw an error.
*/
expectToken(kind) {
const token = this._lexer.token;
if (token.kind === kind) {
this.advanceLexer();
return token;
}
throw syntaxError(
this._lexer.source,
token.start,
`Expected ${getTokenKindDesc(kind)}, found ${getTokenDesc(token)}.`
);
}
/**
* If the next token is of the given kind, return "true" after advancing the lexer.
* Otherwise, do not change the parser state and return "false".
*/
expectOptionalToken(kind) {
const token = this._lexer.token;
if (token.kind === kind) {
this.advanceLexer();
return true;
}
return false;
}
/**
* If the next token is a given keyword, advance the lexer.
* Otherwise, do not change the parser state and throw an error.
*/
expectKeyword(value) {
const token = this._lexer.token;
if (token.kind === TokenKind.NAME && token.value === value) {
this.advanceLexer();
} else {
throw syntaxError(
this._lexer.source,
token.start,
`Expected "${value}", found ${getTokenDesc(token)}.`
);
}
}
/**
* If the next token is a given keyword, return "true" after advancing the lexer.
* Otherwise, do not change the parser state and return "false".
*/
expectOptionalKeyword(value) {
const token = this._lexer.token;
if (token.kind === TokenKind.NAME && token.value === value) {
this.advanceLexer();
return true;
}
return false;
}
/**
* Helper function for creating an error when an unexpected lexed token is encountered.
*/
unexpected(atToken) {
const token = atToken !== null && atToken !== void 0 ? atToken : this._lexer.token;
return syntaxError(
this._lexer.source,
token.start,
`Unexpected ${getTokenDesc(token)}.`
);
}
/**
* Returns a possibly empty list of parse nodes, determined by the parseFn.
* This list begins with a lex token of openKind and ends with a lex token of closeKind.
* Advances the parser to the next lex token after the closing token.
*/
any(openKind, parseFn, closeKind) {
this.expectToken(openKind);
const nodes = [];
while (!this.expectOptionalToken(closeKind)) {
nodes.push(parseFn.call(this));
}
return nodes;
}
/**
* Returns a list of parse nodes, determined by the parseFn.
* It can be empty only if open token is missing otherwise it will always return non-empty list
* that begins with a lex token of openKind and ends with a lex token of closeKind.
* Advances the parser to the next lex token after the closing token.
*/
optionalMany(openKind, parseFn, closeKind) {
if (this.expectOptionalToken(openKind)) {
const nodes = [];
do {
nodes.push(parseFn.call(this));
} while (!this.expectOptionalToken(closeKind));
return nodes;
}
return [];
}
/**
* Returns a non-empty list of parse nodes, determined by the parseFn.
* This list begins with a lex token of openKind and ends with a lex token of closeKind.
* Advances the parser to the next lex token after the closing token.
*/
many(openKind, parseFn, closeKind) {
this.expectToken(openKind);
const nodes = [];
do {
nodes.push(parseFn.call(this));
} while (!this.expectOptionalToken(closeKind));
return nodes;
}
/**
* Returns a non-empty list of parse nodes, determined by the parseFn.
* This list may begin with a lex token of delimiterKind followed by items separated by lex tokens of tokenKind.
* Advances the parser to the next lex token after last item in the list.
*/
delimitedMany(delimiterKind, parseFn) {
this.expectOptionalToken(delimiterKind);
const nodes = [];
do {
nodes.push(parseFn.call(this));
} while (this.expectOptionalToken(delimiterKind));
return nodes;
}
advanceLexer() {
const { maxTokens } = this._options;
const token = this._lexer.advance();
if (token.kind !== TokenKind.EOF) {
++this._tokenCounter;
if (maxTokens !== void 0 && this._tokenCounter > maxTokens) {
throw syntaxError(
this._lexer.source,
token.start,
`Document contains more that ${maxTokens} tokens. Parsing aborted.`
);
}
}
}
};
function getTokenDesc(token) {
const value = token.value;
return getTokenKindDesc(token.kind) + (value != null ? ` "${value}"` : "");
}
function getTokenKindDesc(kind) {
return isPunctuatorTokenKind(kind) ? `"${kind}"` : kind;
}
// ../../node_modules/.pnpm/graphql@16.11.0/node_modules/graphql/language/printString.mjs
function printString(str) {
return `"${str.replace(escapedRegExp, escapedReplacer)}"`;
}
var escapedRegExp = /[\x00-\x1f\x22\x5c\x7f-\x9f]/g;
function escapedReplacer(str) {
return escapeSequences[str.charCodeAt(0)];
}
var escapeSequences = [
"\\u0000",
"\\u0001",
"\\u0002",
"\\u0003",
"\\u0004",
"\\u0005",
"\\u0006",
"\\u0007",
"\\b",
"\\t",
"\\n",
"\\u000B",
"\\f",
"\\r",
"\\u000E",
"\\u000F",
"\\u0010",
"\\u0011",
"\\u0012",
"\\u0013",
"\\u0014",
"\\u0015",
"\\u0016",
"\\u0017",
"\\u0018",
"\\u0019",
"\\u001A",
"\\u001B",
"\\u001C",
"\\u001D",
"\\u001E",
"\\u001F",
"",
"",
'\\"',
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
// 2F
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
// 3F
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
// 4F
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"\\\\",
"",
"",
"",
// 5F
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
// 6F
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"\\u007F",
"\\u0080",
"\\u0081",
"\\u0082",
"\\u0083",
"\\u0084",
"\\u0085",
"\\u0086",
"\\u0087",
"\\u0088",
"\\u0089",
"\\u008A",
"\\u008B",
"\\u008C",
"\\u008D",
"\\u008E",
"\\u008F",
"\\u0090",
"\\u0091",
"\\u0092",
"\\u0093",
"\\u0094",
"\\u0095",
"\\u0096",
"\\u0097",
"\\u0098",
"\\u0099",
"\\u009A",
"\\u009B",
"\\u009C",
"\\u009D",
"\\u009E",
"\\u009F"
];
// ../../node_modules/.pnpm/graphql@16.11.0/node_modules/graphql/language/visitor.mjs
var BREAK = Object.freeze({});
function visit(root, visitor, visitorKeys = QueryDocumentKeys) {
const enterLeaveMap = /* @__PURE__ */ new Map();
for (const kind of Object.values(Kind)) {
enterLeaveMap.set(kind, getEnterLeaveForKind(visitor, kind));
}
let stack = void 0;
let inArray = Array.isArray(root);
let keys = [root];
let index = -1;
let edits = [];
let node = root;
let key = void 0;
let parent = void 0;
const path = [];
const ancestors = [];
do {
index++;
const isLeaving = index === keys.length;
const isEdited = isLeaving && edits.length !== 0;
if (isLeaving) {
key = ancestors.length === 0 ? void 0 : path[path.length - 1];
node = parent;
parent = ancestors.pop();
if (isEdited) {
if (inArray) {
node = node.slice();
let editOffset = 0;
for (const [editKey, editValue] of edits) {
const arrayKey = editKey - editOffset;
if (editValue === null) {
node.splice(arrayKey, 1);
editOffset++;
} else {
node[arrayKey] = editValue;
}
}
} else {
node = { ...node };
for (const [editKey, editValue] of edits) {
node[editKey] = editValue;
}
}
}
index = stack.index;
keys = stack.keys;
edits = stack.edits;
inArray = stack.inArray;
stack = stack.prev;
} else if (parent) {
key = inArray ? index : keys[index];
node = parent[key];
if (node === null || node === void 0) {
continue;
}
path.push(key);
}
let result;
if (!Array.isArray(node)) {
var _enterLeaveMap$get, _enterLeaveMap$get2;
isNode(node) || devAssert(false, `Invalid AST Node: ${inspect(node)}.`);
const visitFn = isLeaving ? (_enterLeaveMap$get = enterLeaveMap.get(node.kind)) === null || _enterLeaveMap$get === void 0 ? void 0 : _enterLeaveMap$get.leave : (_enterLeaveMap$get2 = enterLeaveMap.get(node.kind)) === null || _enterLeaveMap$get2 === void 0 ? void 0 : _enterLeaveMap$get2.enter;
result = visitFn === null || visitFn === void 0 ? void 0 : visitFn.call(visitor, node, key, parent, path, ancestors);
if (result === BREAK) {
break;
}
if (result === false) {
if (!isLeaving) {
path.pop();
continue;
}
} else if (result !== void 0) {
edits.push([key, result]);
if (!isLeaving) {
if (isNode(result)) {
node = result;
} else {
path.pop();
continue;
}
}
}
}
if (result === void 0 && isEdited) {
edits.push([key, node]);
}
if (isLeaving) {
path.pop();
} else {
var _node$kind;
stack = {
inArray,
index,
keys,
edits,
prev: stack
};
inArray = Array.isArray(node);
keys = inArray ? node : (_node$kind = visitorKeys[node.kind]) !== null && _node$kind !== void 0 ? _node$kind : [];
index = -1;
edits = [];
if (parent) {
ancestors.push(parent);
}
parent = node;
}
} while (stack !== void 0);
if (edits.length !== 0) {
return edits[edits.length - 1][1];
}
return root;
}
function getEnterLeaveForKind(visitor, kind) {
const kindVisitor = visitor[kind];
if (typeof kindVisitor === "object") {
return kindVisitor;
} else if (typeof kindVisitor === "function") {
return {
enter: kindVisitor,
leave: void 0
};
}
return {
enter: visitor.enter,
leave: visitor.leave
};
}
// ../../node_modules/.pnpm/graphql@16.11.0/node_modules/graphql/language/printer.mjs
function print(ast) {
return visit(ast, printDocASTReducer);
}
var MAX_LINE_LENGTH = 80;
var printDocASTReducer = {
Name: {
leave: (node) => node.value
},
Variable: {
leave: (node) => "$" + node.name
},
// Document
Document: {
leave: (node) => join(node.definitions, "\n\n")
},
OperationDefinition: {
leave(node) {
const varDefs = wrap("(", join(node.variableDefinitions, ", "), ")");
const prefix = join(
[
node.operation,
join([node.name, varDefs]),
join(node.directives, " ")
],
" "
);
return (prefix === "query" ? "" : prefix + " ") + node.selectionSet;
}
},
VariableDefinition: {
leave: ({ variable, type, defaultValue, directives }) => variable + ": " + type + wrap(" = ", defaultValue) + wrap(" ", join(directives, " "))
},
SelectionSet: {
leave: ({ selections }) => block(selections)
},
Field: {
leave({ alias, name, arguments: args, directives, selectionSet }) {
const prefix = wrap("", alias, ": ") + name;
let argsLine = prefix + wrap("(", join(args, ", "), ")");
if (argsLine.length > MAX_LINE_LENGTH) {
argsLine = prefix + wrap("(\n", indent(join(args, "\n")), "\n)");
}
return join([argsLine, join(directives, " "), selectionSet], " ");
}
},
Argument: {
leave: ({ name, value }) => name + ": " + value
},
// Fragments
FragmentSpread: {
leave: ({ name, directives }) => "..." + name + wrap(" ", join(directives, " "))
},
InlineFragment: {
leave: ({ typeCondition, directives, selectionSet }) => join(
[
"...",
wrap("on ", typeCondition),
join(directives, " "),
selectionSet
],
" "
)
},
FragmentDefinition: {
leave: ({ name, typeCondition, variableDefinitions, directives, selectionSet }) => (
// or removed in the future.
`fragment ${name}${wrap("(", join(variableDefinitions, ", "), ")")} on ${typeCondition} ${wrap("", join(directives, " "), " ")}` + selectionSet
)
},
// Value
IntValue: {
leave: ({ value }) => value
},
FloatValue: {
leave: ({ value }) => value
},
StringValue: {
leave: ({ value, block: isBlockString }) => isBlockString ? printBlockString(value) : printString(value)
},
BooleanValue: {
leave: ({ value }) => value ? "true" : "false"
},
NullValue: {
leave: () => "null"
},
EnumValue: {
leave: ({ value }) => value
},
ListValue: {
leave: ({ values }) => "[" + join(values, ", ") + "]"
},
ObjectValue: {
leave: ({ fields }) => "{" + join(fields, ", ") + "}"
},
ObjectField: {
leave: ({ name, value }) => name + ": " + value
},
// Directive
Directive: {
leave: ({ name, arguments: args }) => "@" + name + wrap("(", join(args, ", "), ")")
},
// Type
NamedType: {
leave: ({ name }) => name
},
ListType: {
leave: ({ type }) => "[" + type + "]"
},
NonNullType: {
leave: ({ type }) => type + "!"
},
// Type System Definitions
SchemaDefinition: {
leave: ({ description, directives, operationTypes }) => wrap("", description, "\n") + join(["schema", join(directives, " "), block(operationTypes)], " ")
},
OperationTypeDefinition: {
leave: ({ operation, type }) => operation + ": " + type
},
ScalarTypeDefinition: {
leave: ({ description, name, directives }) => wrap("", description, "\n") + join(["scalar", name, join(directives, " ")], " ")
},
ObjectTypeDefinition: {
leave: ({ description, name, interfaces, directives, fields }) => wrap("", description, "\n") + join(
[
"type",
name,
wrap("implements ", join(interfaces, " & ")),
join(directives, " "),
block(fields)
],
" "
)
},
FieldDefinition: {
leave: ({ description, name, arguments: args, type, directives }) => wrap("", description, "\n") + name + (hasMultilineItems(args) ? wrap("(\n", indent(join(args, "\n")), "\n)") : wrap("(", join(args, ", "), ")")) + ": " + type + wrap(" ", join(directives, " "))
},
InputValueDefinition: {
leave: ({ description, name, type, defaultValue, directives }) => wrap("", description, "\n") + join(
[name + ": " + type, wrap("= ", defaultValue), join(directives, " ")],
" "
)
},
InterfaceTypeDefinition: {
leave: ({ description, name, interfaces, directives, fields }) => wrap("", description, "\n") + join(
[
"interface",
name,
wrap("implements ", join(interfaces, " & ")),
join(directives, " "),
block(fields)
],
" "
)
},
UnionTypeDefinition: {
leave: ({ description, name, directives, types }) => wrap("", description, "\n") + join(
["union", name, join(directives, " "), wrap("= ", join(types, " | "))],
" "
)
},
EnumTypeDefinition: {
leave: ({ description, name, directives, values }) => wrap("", description, "\n") + join(["enum", name, join(directives, " "), block(values)], " ")
},
EnumValueDefinition: {
leave: ({ description, name, directives }) => wrap("", description, "\n") + join([name, join(directives, " ")], " ")
},
InputObjectTypeDefinition: {
leave: ({ description, name, directives, fields }) => wrap("", description, "\n") + join(["input", name, join(directives, " "), block(fields)], " ")
},
DirectiveDefinition: {
leave: ({ description, name, arguments: args, repeatable, locations }) => wrap("", description, "\n") + "directive @" + name + (hasMultilineItems(args) ? wrap("(\n", indent(join(args, "\n")), "\n)") : wrap("(", join(args, ", "), ")")) + (repeatable ? " repeatable" : "") + " on " + join(locations, " | ")
},
SchemaExtension: {
leave: ({ directives, operationTypes }) => join(
["extend schema", join(directives, " "), block(operationTypes)],
" "
)
},
ScalarTypeExtension: {
leave: ({ name, directives }) => join(["extend scalar", name, join(directives, " ")], " ")
},
ObjectTypeExtension: {
leave: ({ name, interfaces, directives, fields }) => join(
[
"extend type",
name,
wrap("implements ", join(interfaces, " & ")),
join(directives, " "),
block(fields)
],
" "
)
},
InterfaceTypeExtension: {
leave: ({ name, interfaces, directives, fields }) => join(
[
"extend interface",
name,
wrap("implements ", join(interfaces, " & ")),
join(directives, " "),
block(fields)
],
" "
)
},
UnionTypeExtension: {
leave: ({ name, directives, types }) => join(
[
"extend union",
name,
join(directives, " "),
wrap("= ", join(types, " | "))
],
" "
)
},
EnumTypeExtension: {
leave: ({ name, directives, values }) => join(["extend enum", name, join(directives, " "), block(values)], " ")
},
InputObjectTypeExtension: {
leave: ({ name, directives, fields }) => join(["extend input", name, join(directives, " "), block(fields)], " ")
}
};
function join(maybeArray, separator = "") {
var _maybeArray$filter$jo;
return (_maybeArray$filter$jo = maybeArray === null || maybeArray === void 0 ? void 0 : maybeArray.filter((x) => x).join(separator)) !== null && _maybeArray$filter$jo !== void 0 ? _maybeArray$filter$jo : "";
}
function block(array) {
return wrap("{\n", indent(join(array, "\n")), "\n}");
}
function wrap(start, maybeString, end = "") {
return maybeString != null && maybeString !== "" ? start + maybeString + end : "";
}
function indent(str) {
return wrap(" ", str.replace(/\n/g, "\n "));
}
function hasMultilineItems(maybeArray) {
var _maybeArray$some;
return (_maybeArray$some = maybeArray === null || maybeArray === void 0 ? void 0 : maybeArray.some((str) => str.includes("\n"))) !== null && _maybeArray$some !== void 0 ? _maybeArray$some : false;
}
// ../../node_modules/.pnpm/graphql-request@6.1.0_graphql@16.11.0/node_modules/graphql-request/build/esm/resolveRequestDocument.js
var extractOperationName = (document) => {
let operationName = void 0;
const operationDefinitions = document.definitions.filter((definition) => definition.kind === `OperationDefinition`);
if (operationDefinitions.length === 1) {
operationName = operationDefinitions[0]?.name?.value;
}
return operationName;
};
var resolveRequestDocument = (document) => {
if (typeof document === `string`) {
let operationName2 = void 0;
try {
const parsedDocument = parse(document);
operationName2 = extractOperationName(parsedDocument);
} catch (err) {
}
return { query: document, operationName: operationName2 };
}
const operationName = extractOperationName(document);
return { query: print(document), operationName };
};
// ../../node_modules/.pnpm/graphql-request@6.1.0_graphql@16.11.0/node_modules/graphql-request/build/esm/types.js
var ClientError = class _ClientError extends Error {
constructor(response, request) {
const message = `${_ClientError.extractMessage(response)}: ${JSON.stringify({
response,
request
})}`;
super(message);
Object.setPrototypeOf(this, _ClientError.prototype);
this.response = response;
this.request = request;
if (typeof Error.captureStackTrace === `function`) {
Error.captureStackTrace(this, _ClientError);
}
}
static extractMessage(response) {
return response.errors?.[0]?.message ?? `GraphQL Error (Code: ${response.status})`;
}
};
// ../../node_modules/.pnpm/graphql-request@6.1.0_graphql@16.11.0/node_modules/graphql-request/build/esm/index.js
var CrossFetch = __toESM(require_browser_ponyfill());
// ../../node_modules/.pnpm/graphql-request@6.1.0_graphql@16.11.0/node_modules/graphql-request/build/esm/index.js
var resolveHeaders = (headers) => {
let oHeaders = {};
if (headers) {
if (typeof Headers !== `undefined` && headers instanceof Headers || CrossFetch && CrossFetch.Headers && headers instanceof CrossFetch.Headers) {
oHeaders = HeadersInstanceToPlainObject(headers);
} else if (Array.isArray(headers)) {
headers.forEach(([name, value]) => {
if (name && value !== void 0) {
oHeaders[name] = value;
}
});
} else {
oHeaders = headers;
}
}
return oHeaders;
};
var cleanQuery = (str) => str.replace(/([\s,]|#[^\n\r]+)+/g, ` `).trim();
var buildRequestConfig = (params) => {
if (!Array.isArray(params.query)) {
const params_2 = params;
const search = [`query=${encodeURIComponent(cleanQuery(params_2.query))}`];
if (params.variables) {
search.push(`variables=${encodeURIComponent(params_2.jsonSerializer.stringify(params_2.variables))}`);
}
if (params_2.operationName) {
search.push(`operationName=${encodeURIComponent(params_2.operationName)}`);
}
return search.join(`&`);
}
if (typeof params.variables !== `undefined` && !Array.isArray(params.variables)) {
throw new Error(`Cannot create query with given variable type, array expected`);
}
const params_ = params;
const payload = params.query.reduce((acc, currentQuery, index) => {
acc.push({
query: cleanQuery(currentQuery),
variables: params_.variables ? params_.jsonSerializer.stringify(params_.variables[index]) : void 0
});
return acc;
}, []);
return `query=${encodeURIComponent(params_.jsonSerializer.stringify(payload))}`;
};
var createHttpMethodFetcher = (method) => async (params) => {
const { url, query, variables, operationName, fetch, fetchOptions, middleware } = params;
const headers = { ...params.headers };
let queryParams = ``;
let body = void 0;
if (method === `POST`) {
body = createRequestBody(query, variables, operationName, fetchOptions.jsonSerializer);
if (typeof body === `string`) {
headers[`Content-Type`] = `application/json`;
}
} else {
queryParams = buildRequestConfig({
query,
variables,
operationName,
jsonSerializer: fetchOptions.jsonSerializer ?? defaultJsonSerializer
});
}
const init = {
method,
headers,
body,
...fetchOptions
};
let urlResolved = url;
let initResolved = init;
if (middleware) {
const result = await Promise.resolve(middleware({ ...init, url, operationName, variables }));
const { url: urlNew, ...initNew } = result;
urlResolved = urlNew;
initResolved = initNew;
}
if (queryParams) {
urlResolved = `${urlResolved}?${queryParams}`;
}
return await fetch(urlResolved, initResolved);
};
var GraphQLClient = class {
constructor(url, requestConfig = {}) {
this.url = url;
this.requestConfig = requestConfig;
this.rawRequest = async (...args) => {
const [queryOrOptions, variables, requestHeaders] = args;
const rawRequestOptions = parseRawRequestArgs(queryOrOptions, variables, requestHeaders);
const { headers, fetch = CrossFetch.default, method = `POST`, requestMiddleware, responseMiddleware, ...fetchOptions } = this.requestConfig;
const { url: url2 } = this;
if (rawRequestOptions.signal !== void 0) {
fetchOptions.signal = rawRequestOptions.signal;
}
const { operationName } = resolveRequestDocument(rawRequestOptions.query);
return makeRequest({
url: url2,
query: rawRequestOptions.query,
variables: rawRequestOptions.variables,
headers: {
...resolveHeaders(callOrIdentity(headers)),
...resolveHeaders(rawRequestOptions.requestHeaders)
},
operationName,
fetch,
method,
fetchOptions,
middleware: requestMiddleware
}).then((response) => {
if (responseMiddleware) {
responseMiddleware(response);
}
return response;
}).catch((error) => {
if (responseMiddleware) {
responseMiddleware(error);
}
throw error;
});
};
}
async request(documentOrOptions, ...variablesAndRequestHeaders) {
const [variables, requestHeaders] = variablesAndRequestHeaders;
const requestOptions = parseRequestArgs(documentOrOptions, variables, requestHeaders);
const { headers, fetch = CrossFetch.default, method = `POST`, requestMiddleware, responseMiddleware, ...fetchOptions } = this.requestConfig;
const { url } = this;
if (requestOptions.signal !== void 0) {
fetchOptions.signal = requestOptions.signal;
}
const { query, operationName } = resolveRequestDocument(requestOptions.document);
return makeRequest({
url,
query,
variables: requestOptions.variables,
headers: {
...resolveHeaders(callOrIdentity(headers)),
...resolveHeaders(requestOptions.requestHeaders)
},
operationName,
fetch,
method,
fetchOptions,
middleware: requestMiddleware
}).then((response) => {
if (responseMiddleware) {
responseMiddleware(response);
}
return response.data;
}).catch((error) => {
if (responseMiddleware) {
responseMiddleware(error);
}
throw error;
});
}
// prettier-ignore
batchRequests(documentsOrOptions, requestHeaders) {
const batchRequestOptions = parseBatchRequestArgs(documentsOrOptions, requestHeaders);
const { headers, ...fetchOptions } = this.requestConfig;
if (batchRequestOptions.signal !== void 0) {
fetchOptions.signal = batchRequestOptions.signal;
}
const queries = batchRequestOptions.documents.map(({ document }) => resolveRequestDocument(document).query);
const variables = batchRequestOptions.documents.map(({ variables: variables2 }) => variables2);
return makeRequest({
url: this.url,
query: queries,
// @ts-expect-error TODO reconcile batch variables into system.
variables,
headers: {
...resolveHeaders(callOrIdentity(headers)),
...resolveHeaders(batchRequestOptions.requestHeaders)
},
operationName: void 0,
fetch: this.requestConfig.fetch ?? CrossFetch.default,
method: this.requestConfig.method || `POST`,
fetchOptions,
middleware: this.requestConfig.requestMiddleware
}).then((response) => {
if (this.requestConfig.responseMiddleware) {
this.requestConfig.responseMiddleware(response);
}
return response.data;
}).catch((error) => {
if (this.requestConfig.responseMiddleware) {
this.requestConfig.responseMiddleware(error);
}
throw error;
});
}
setHeaders(headers) {
this.requestConfig.headers = headers;
return this;
}
/**
* Attach a header to the client. All subsequent requests will have this header.
*/
setHeader(key, value) {
const { headers } = this.requestConfig;
if (headers) {
headers[key] = value;
} else {
this.requestConfig.headers = { [key]: value };
}
return this;
}
/**
* Change the client endpoint. All subsequent requests will send to this endpoint.
*/
setEndpoint(value) {
this.url = value;
return this;
}
};
var makeRequest = async (params) => {
const { query, variables, fetchOptions } = params;
const fetcher = createHttpMethodFetcher(uppercase(params.method ?? `post`));
const isBatchingQuery = Array.isArray(params.query);
const response = await fetcher(params);
const result = await getResult(response, fetchOptions.jsonSerializer ?? defaultJsonSerializer);
const successfullyReceivedData = Array.isArray(result) ? !result.some(({ data }) => !data) : Boolean(result.data);
const successfullyPassedErrorPolicy = Array.isArray(result) || !result.errors || Array.isArray(result.errors) && !result.errors.length || fetchOptions.errorPolicy === `all` || fetchOptions.errorPolicy === `ignore`;
if (response.ok && successfullyPassedErrorPolicy && successfullyReceivedData) {
const { errors: _, ...rest } = Array.isArray(result) ? result : result;
const data = fetchOptions.errorPolicy === `ignore` ? rest : result;
const dataEnvelope = isBatchingQuery ? { data } : data;
return {
...dataEnvelope,
headers: response.headers,
status: response.status
};
} else {
const errorResult = typeof result === `string` ? {
error: result
} : result;
throw new ClientError(
// @ts-expect-error TODO
{ ...errorResult, status: response.status, headers: response.headers },
{ query, variables }
);
}
};
var createRequestBody = (query, variables, operationName, jsonSerializer) => {
const jsonSerializer_ = jsonSerializer ?? defaultJsonSerializer;
if (!Array.isArray(query)) {
return jsonSerializer_.stringify({ query, variables, operationName });
}
if (typeof variables !== `undefined` && !Array.isArray(variables)) {
throw new Error(`Cannot create request body with given variable type, array expected`);
}
const payload = query.reduce((acc, currentQuery, index) => {
acc.push({ query: currentQuery, variables: variables ? variables[index] : void 0 });
return acc;
}, []);
return jsonSerializer_.stringify(payload);
};
var getResult = async (response, jsonSerializer) => {
let contentType;
response.headers.forEach((value, key) => {
if (key.toLowerCase() === `content-type`) {
contentType = value;
}
});
if (contentType && (contentType.toLowerCase().startsWith(`application/json`) || contentType.toLowerCase().startsWith(`application/graphql+json`) || contentType.toLowerCase().startsWith(`application/graphql-response+json`))) {
return jsonSerializer.parse(await response.text());
} else {
return response.text();
}
};
var callOrIdentity = (value) => {
return typeof value === `function` ? value() : value;
};
// ../../node_modules/.pnpm/tslib@2.8.1/node_modules/tslib/tslib.es6.mjs
var __assign = function() {
__assign = Object.assign || function __assign2(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);
};
// ../../node_modules/.pnpm/graphql-tag@2.12.6_graphql@16.11.0/node_modules/graphql-tag/lib/index.js
var docCache = /* @__PURE__ */ new Map();
var fragmentSourceMap = /* @__PURE__ */ new Map();
var printFragmentWarnings = true;
var experimentalFragmentVariables = false;
function normalize(string) {
return string.replace(/[\s,]+/g, " ").trim();
}
function cacheKeyFromLoc(loc) {
return normalize(loc.source.body.substring(loc.start, loc.end));
}
function processFragments(ast) {
var seenKeys = /* @__PURE__ */ new Set();
var definitions = [];
ast.definitions.forEach(function(fragmentDefinition) {
if (fragmentDefinition.kind === "FragmentDefinition") {
var fragmentName = fragmentDefinition.name.value;
var sourceKey = cacheKeyFromLoc(fragmentDefinition.loc);
var sourceKeySet = fragmentSourceMap.get(fragmentName);
if (sourceKeySet && !sourceKeySet.has(sourceKey)) {
if (printFragmentWarnings) {
console.warn("Warning: fragment with name " + fragmentName + " already exists.\ngraphql-tag enforces all fragment names across your application to be unique; read more about\nthis in the docs: http://dev.apollodata.com/core/fragments.html#unique-names");
}
} else if (!sourceKeySet) {
fragmentSourceMap.set(fragmentName, sourceKeySet = /* @__PURE__ */ new Set());
}
sourceKeySet.add(sourceKey);
if (!seenKeys.has(sourceKey)) {
seenKeys.add(sourceKey);
definitions.push(fragmentDefinition);
}
} else {
definitions.push(fragmentDefinition);
}
});
return __assign(__assign({}, ast), { definitions });
}
function stripLoc(doc) {
var workSet = new Set(doc.definitions);
workSet.forEach(function(node) {
if (node.loc)
delete node.loc;
Object.keys(node).forEach(function(key) {
var value = node[key];
if (value && typeof value === "object") {
workSet.add(value);
}
});
});
var loc = doc.loc;
if (loc) {
delete loc.startToken;
delete loc.endToken;
}
return doc;
}
function parseDocument(source) {
var cacheKey = normalize(source);
if (!docCache.has(cacheKey)) {
var parsed = parse(source, {
experimentalFragmentVariables,
allowLegacyFragmentVariables: experimentalFragmentVariables
});
if (!parsed || parsed.kind !== "Document") {
throw new Error("Not a valid GraphQL document.");
}
docCache.set(cacheKey, stripLoc(processFragments(parsed)));
}
return docCache.get(cacheKey);
}
function gql(literals) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
if (typeof literals === "string") {
literals = [literals];
}
var result = literals[0];
args.forEach(function(arg, i) {
if (arg && arg.kind === "Document") {
result += arg.loc.source.body;
} else {
result += arg;
}
result += literals[i + 1];
});
return parseDocument(result);
}
function resetCaches() {
docCache.clear();
fragmentSourceMap.clear();
}
function disableFragmentWarnings() {
printFragmentWarnings = false;
}
function enableExperimentalFragmentVariables() {
experimentalFragmentVariables = true;
}
function disableExperimentalFragmentVariables() {
experimentalFragmentVariables = false;
}
var extras = {
gql,
resetCaches,
disableFragmentWarnings,
enableExperimentalFragmentVariables,
disableExperimentalFragmentVariables
};
(function(gql_1) {
gql_1.gql = extras.gql, gql_1.resetCaches = extras.resetCaches, gql_1.disableFragmentWarnings = extras.disableFragmentWarnings, gql_1.enableExperimentalFragmentVariables = extras.enableExperimentalFragmentVariables, gql_1.disableExperimentalFragmentVariables = extras.disableExperimentalFragmentVariables;
})(gql || (gql = {}));
gql["default"] = gql;
var lib_default = gql;
// ../../node_modules/.pnpm/zod@3.25.67/node_modules/zod/dist/esm/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/.pnpm/zod@3.25.67/node_modules/zod/dist/esm/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/.pnpm/zod@3.25.67/node_modules/zod/dist/esm/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) {
fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
fieldErrors[sub.path[0]].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/.pnpm/zod@3.25.67/node_modules/zod/dist/esm/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 === "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/.pnpm/zod@3.25.67/node_modules/zod/dist/esm/v3/errors.js
var overrideErrorMap = en_default;
function setErrorMap(map) {
overrideErrorMap = map;
}
function getErrorMap() {
return overrideErrorMap;
}
// ../../node_modules/.pnpm/zod@3.25.67/node_modules/zod/dist/esm/v3/helpers/parseUtil.js
var makeIssue = (params) => {
const { data, path, errorMaps, issueData } = params;
const fullPath = [...path, ...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/.pnpm/zod@3.25.67/node_modules/zod/dist/esm/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/.pnpm/zod@3.25.67/node_modules/zod/dist/esm/v3/types.js
var ParseInputLazyPath = class {
constructor(parent, value, path, key) {
this._cachedPath = [];
this.parent = parent;
this.data = value;
this._path = path;
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(transform) {
return new ZodEffects({
...processCreateParams(this._def),
schema: this,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect: { type: "transform", transform }
});
}
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(".");
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 = 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 freeze = (data) => {
if (isValid(data)) {
data.value = Object.freeze(data.value);
}
return data;
};
return isAsync(result) ? result.then((data) => freeze(data)) : freeze(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;
// ../core/dist/index.js
var MercNetError = class extends Error {
constructor(message, code, details) {
super(message);
this.code = code;
this.details = details;
this.name = "MercNetError";
}
};
var GetAllMarketsDocument = lib_default`
query GetAllMarkets {
marketCollection {
edges {
node {
id
name
short_name
ticker
price
type
created_at
last_update_at
trend_status
sentiment
sentiment_update_at
market_activity_score_1h
market_activity_score_1d
data
status
}
}
}
}
`;
var GetMarketByIdDocument = lib_default`
query GetMarketById($id: Int!) {
marketCollection(filter: { id: { eq: $id } }) {
edges {
node {
id
name
short_name
ticker
price
type
created_at
last_update_at
trend_status
sentiment
sentiment_update_at
market_activity_score_1h
market_activity_score_1d
data
status
}
}
}
}
`;
var GetMarketByTickerDocument = lib_default`
query GetMarketByTicker($ticker: String!) {
marketCollection(filter: { ticker: { eq: $ticker } }) {
edges {
node {
id
name
short_name
ticker
price
type
created_at
last_update_at
trend_status
sentiment
sentiment_update_at
market_activity_score_1h
market_activity_score_1d
data
status
}
}
}
}
`;
var GetMarketsByStatusDocument = lib_default`
query GetMarketsByStatus($status: String!) {
marketCollection(filter: { status: { eq: $status } }) {
edges {
node {
id
name
short_name
ticker
price
type
created_at
last_update_at
trend_status
sentiment
sentiment_update_at
market_activity_score_1h
market_activity_score_1d
data
status
}
}
}
}
`;
var defaultWrapper = (action, _operationName, _operationType, _variables) => action();
function getSdk(client, withWrapper = defaultWrapper) {
return {
GetAllMarkets(variables, requestHeaders, signal) {
return withWrapper(
(wrappedRequestHeaders) => client.request({
document: GetAllMarketsDocument,
variables,
requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },
signal
}),
"GetAllMarkets",
"query",
variables
);
},
GetMarketById(variables, requestHeaders, signal) {
return withWrapper(
(wrappedRequestHeaders) => client.request({
document: GetMarketByIdDocument,
variables,
requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },
signal
}),
"GetMarketById",
"query",
variables
);
},
GetMarketByTicker(variables, requestHeaders, signal) {
return withWrapper(
(wrappedRequestHeaders) => client.request({
document: GetMarketByTickerDocument,
variables,
requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },
signal
}),
"GetMarketByTicker",
"query",
variables
);
},
GetMarketsByStatus(variables, requestHeaders, signal) {
return withWrapper(
(wrappedRequestHeaders) => client.request({
document: GetMarketsByStatusDocument,
variables,
requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },
signal
}),
"GetMarketsByStatus",
"query",
variables
);
}
};
}
var DEFAULT_CONFIG = {
retries: 3,
debug: false
};
var MercNetGraphQLClient = class {
constructor(config) {
__publicField(this, "client");
__publicField(this, "config");
__publicField(this, "sdk");
this.config = { ...DEFAULT_CONFIG, ...config };
this.client = new GraphQLClient(this.config.endpoint, {
headers: this.config.headers
});
this.sdk = getSdk(this.client);
}
// Update headers (useful for authentication)
setHeaders(headers) {
this.client.setHeaders(headers);
}
// Add a single header
setHeader(key, value) {
this.client.setHeader(key, value);
}
// Execute a GraphQL query
async query(query, variables, requestHeaders) {
try {
if (this.config.debug) {
console.log("[GraphQL Query]", { query, variables });
}
const response = await this.client.request(query, variables, requestHeaders);
if (this.config.debug) {
console.log("[GraphQL Response]", response);
}
return response;
} catch (error) {
if (this.config.debug) {
console.error("[GraphQL Error]", error);
}
throw this.handleGraphQLError(error);
}
}
// Execute a GraphQL mutation
async mutate(mutation, variables, requestHeaders) {
return this.query(mutation, variables, requestHeaders);
}
// Execute raw request with full response
async rawRequest(query, variables, requestHeaders) {
try {
const response = await this.client.rawRequest(query, variables, requestHeaders);
return {
data: response.data,
errors: response.errors
};
} catch (error) {
throw this.handleGraphQLError(error);
}
}
// Typed methods for market operations using generated SDK
async getAllMarkets() {
try {
if (this.config.debug) {
console.log("[GraphQL] Fetching all markets");
}
const response = await this.sdk.GetAllMarkets();
const markets = this.transformMarketsResponse(response);
if (this.config.debug) {
console.log("[GraphQL] Retrieved markets:", markets.length);
}
return markets;
} catch (error) {
throw this.handleGraphQLError(error);
}
}
async getMarketById(id) {
try {
if (this.config.debug) {
console.log("[GraphQL] Fetching market by ID:", id);
}
const response = await this.sdk.GetMarketById({ id });
const markets = this.transformMarketsResponse(response);
const market = markets.length > 0 ? markets[0] : null;
if (this.config.debug) {
console.log("[GraphQL] Retrieved market:", market ? market.id : "not found");
}
return market;
} catch (error) {
throw this.handleGraphQLError(error);
}
}
async getMarketByTicker(ticker) {
try {
if (this.config.debug) {
console.log("[GraphQL] Fetching market by ticker:", ticker);
}
const response = await this.sdk.GetMarketByTicker({ ticker });
const markets = this.transformMarketsResponse(response);
const market = markets.length > 0 ? markets[0] : null;
if (this.config.debug) {
console.log("[GraphQL] Retrieved market by ticker:", market ? market.ticker : "not found");
}
return market;
} catch (error) {
throw this.handleGraphQLError(error);
}
}
async getMarketsByStatus(status) {
try {
if (this.config.debug) {
console.log("[GraphQL] Fetching markets by status:", status);
}
const response = await this.sdk.GetMarketsByStatus({ status });
const markets = this.transformMarketsResponse(response);
if (this.config.debug) {
console.log("[GraphQL] Retrieved markets by status:", markets.length);
}
return markets;
} catch (error) {
throw this.handleGraphQLError(error);
}
}
// Transform GraphQL response to Market array
transformMarketsResponse(response) {
if (!response.marketCollection?.edges) {
return [];
}
return response.marketCollection.edges.filter((edge) => edge?.node).map((edge) => {
const node = edge.node;
return {
id: node.id,
name: node.name,
short_name: node.short_name,
ticker: node.ticker,
price: node.price,
type: node.type,
created_at: node.created_at,
last_update_at: node.last_update_at,
trend_status: node.trend_status,
sentiment: node.sentiment,
sentiment_update_at: node.sentiment_update_at,
market_activity_score_1h: node.market_activity_score_1h,
market_activity_score_1d: node.market_activity_score_1d,
data: node.data,
status: node.status
};
});
}
// Handle GraphQL errors
handleGraphQLError(error) {
if (error.response?.errors) {
const graphqlErrors = error.response.errors;
const message = graphqlErrors.map((e) => e.message).join(", ");
return new MercNetError(message, "GRAPHQL_ERROR", {
errors: graphqlErrors,
query: error.request?.query,
variables: error.request?.variables
});
}
if (error.message) {
return new MercNetError(error.message, "GRAPHQL_NETWORK_ERROR", {
originalError: error
});
}
return new MercNetError("Unknown GraphQL error", "GRAPHQL_UNKNOWN_ERROR", {
originalError: error
});
}
};
var createGraphQLClient = (config) => {
return new MercNetGraphQLClient(config);
};
external_exports.object({
id: external_exports.string().min(1, "ID is required"),
createdAt: external_exports.date(),
updatedAt: external_exports.date()
});
external_exports.object({
page: external_exports.number().int().positive().optional().default(1),
limit: external_exports.number().int().positive().max(100).optional().default(20),
offset: external_exports.number().int().nonnegative().optional()
});
var validators = {
email: external_exports.string().email("Invalid email format"),
password: external_exports.string().min(8, "Password must be at least 8 characters"),
url: external_exports.string().url("Invalid URL format"),
phone: external_exports.string().regex(/^\+?[1-9]\d{1,14}$/, "Invalid phone number format"),
uuid: external_exports.string().uuid("Invalid UUID format"),
slug: external_exports.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "Invalid slug format"),
hex: external_exports.string().regex(/^#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/, "Invalid hex color"),
// Date validators
dateString: external_exports.string().datetime("Invalid date format"),
dateRange: external_exports.object({
start: external_exports.date(),
end: external_exports.date()
}).refine((data) => data.end > data.start, {
message: "End date must be after start date",
path: ["end"]
}),
// Number validators
positiveNumber: external_exports.number().positive("Must be a positive number"),
nonNegativeNumber: external_exports.number().nonnegative("Must be a non-negative number"),
percentage: external_exports.number().min(0).max(100, "Must be between 0 and 100"),
currency: external_exports.number().multipleOf(0.01, "Invalid currency format"),
// String validators
nonEmptyString: external_exports.string().min(1, "Cannot be empty"),
alphanumeric: external_exports.string().regex(/^[a-zA-Z0-9]+$/, "Must contain only letters and numbers"),
noWhitespace: external_exports.string().regex(/^\S+$/, "Cannot contain whitespace")
};
var environmentSchema = external_exports.enum(["development", "production", "test", "staging"]);
external_exports.object({
environment: environmentSchema,
apiUrl: validators.url,
graphqlUrl: validators.url.optional(),
debug: external_exports.boolean().optional().default(false)
});
({
stringToNumber: external_exports.string().transform((val, ctx) => {
const parsed = parseFloat(val);
if (isNaN(parsed)) {
ctx.addIssue({
code: external_exports.ZodIssueCode.custom,
message: "Not a number"
});
return external_exports.NEVER;
}
return parsed;
}),
stringToBoolean: external_exports.string().transform((val) => {
return val.toLowerCase() === "true" || val === "1";
}),
stringToDate: external_exports.string().transform((val, ctx) => {
const date = new Date(val);
if (isNaN(date.getTime())) {
ctx.addIssue({
code: external_exports.ZodIssueCode.custom,
message: "Invalid date"
});
return external_exports.NEVER;
}
return date;
}),
trimString: external_exports.string().transform((val) => val.trim()),
toLowerCase: external_exports.string().transform((val) => val.toLowerCase()),
toUpperCase: external_exports.string().transform((val) => val.toUpperCase())
});
({
strongPassword: external_exports.string().refine(
(password) => {
const hasUpperCase = /[A-Z]/.test(password);
const hasLowerCase = /[a-z]/.test(password);
const hasNumbers = /\d/.test(password);
const hasSpecialChar = /[!@#$%^&*(),.?":{}|<>]/.test(password);
return hasUpperCase && hasLowerCase && hasNumbers && hasSpecialChar;
},
{
message: "Password must contain uppercase, lowercase, number and special character"
}
),
futureDate: external_exports.date().refine((date) => date > /* @__PURE__ */ new Date(), { message: "Date must be in the future" }),
pastDate: external_exports.date().refine((date) => date < /* @__PURE__ */ new Date(), { message: "Date must be in the past" })
});
// src/index.ts
var DEFAULT_WINDMILL_CONFIG = {
retries: 3,
debug: false
};
function createClient(config) {
const mergedConfig = {
...DEFAULT_WINDMILL_CONFIG,
...config
};
const headers = {
"Content-Type": "application/json",
...mergedConfig.headers || {}
};
if (mergedConfig.token) {
headers["Authorization"] = `Bearer ${mergedConfig.token}`;
}
const graphqlConfig = {
endpoint: mergedConfig.endpoint,
headers,
retries: mergedConfig.retries || 3,
debug: mergedConfig.debug || false
};
return createGraphQLClient(graphqlConfig);
}
function createMercNetClient(config) {
return createClient({
endpoint: "https://graphql.rocketeer.trade/",
...config
});
}
var WindmillMercNetUtils = class {
constructor(client) {
this.client = client;
}
/**
* Get active markets with basic filtering
*/
async getActiveMarkets() {
const markets = await this.client.getAllMarkets();
return markets.filter((market) => market.status === "active").map((market) => ({
id: market.id,
name: market.name || "Unknown",
ticker: market.ticker,
price: market.price || null,
status: market.status || null
}));
}
/**
* Get market summary for reporting
*/
async getMarketSummary(marketId) {
const market = await this.client.getMarketById(marketId);
if (!market) {
return null;
}
return {
id: market.id,
name: market.name || "Unknown",
ticker: market.ticker,
price: market.price || null,
sentiment: market.sentiment || null,
trend: market.trend_status || null,
lastUpdate: market.last_update_at || null,
activityScore1h: market.market_activity_score_1h || null,
activityScore1d: market.market_activity_score_1d || null
};
}
/**
* Search markets by ticker pattern
*/
async searchMarketsByTicker(tickerPattern) {
const allMarkets = await this.client.getAllMarkets();
const pattern = tickerPattern.toLowerCase();
return allMarkets.filter((market) => market.ticker.toLowerCase().includes(pattern)).map((market) => ({
id: market.id,
name: market.name || "Unknown",
ticker: market.ticker,
price: market.price || null
}));
}
/**
* Get markets with sentiment analysis
*/
async getMarketsSentiment() {
const allMarkets = await this.client.getAllMarkets();
return allMarkets.filter((market) => market.sentiment !== null).map((market) => ({
id: market.id,
ticker: market.ticker,
sentiment: market.sentiment || null,
sentimentUpdateAt: market.sentiment_update_at || null,
trendStatus: market.trend_status || null
}));
}
};
function createUtils(config) {
const client = createClient(config);
return new WindmillMercNetUtils(client);
}
exports.MercNetError = MercNetError;
exports.WindmillMercNetUtils = WindmillMercNetUtils;
exports.createClient = createClient;
exports.createGraphQLClient = createGraphQLClient;
exports.createMercNetClient = createMercNetClient;
exports.createUtils = createUtils;
return exports;
})({});
//# sourceMappingURL=index.global.js.map
//# sourceMappingURL=index.global.js.map