42604315b7
* build(deps-dev): bump vitest from 0.32.2 to 0.33.0 Bumps [vitest](https://github.com/vitest-dev/vitest/tree/HEAD/packages/vitest) from 0.32.2 to 0.33.0. - [Release notes](https://github.com/vitest-dev/vitest/releases) - [Commits](https://github.com/vitest-dev/vitest/commits/v0.33.0/packages/vitest) --- updated-dependencies: - dependency-name: vitest dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> * Update mockserver --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Iain Sproat <68657+iainsproat@users.noreply.github.com>
7670 lines
234 KiB
JavaScript
Generated
7670 lines
234 KiB
JavaScript
Generated
import './sourcemap-register.cjs';import { createRequire as __WEBPACK_EXTERNAL_createRequire } from "module";
|
|
/******/ var __webpack_modules__ = ({
|
|
|
|
/***/ 2182:
|
|
/***/ ((module, exports, __nccwpck_require__) => {
|
|
|
|
|
|
var http = __nccwpck_require__(3685);
|
|
var https = __nccwpck_require__(5687);
|
|
|
|
/**
|
|
* Expose `addShutdown`.
|
|
*/
|
|
exports = module.exports = addShutdown;
|
|
|
|
/**
|
|
* Adds shutdown functionaility to the `http.Server` object
|
|
* @param {http.Server} server The server to add shutdown functionaility to
|
|
*/
|
|
function addShutdown(server) {
|
|
var connections = {};
|
|
var isShuttingDown = false;
|
|
var connectionCounter = 0;
|
|
|
|
function destroy(socket, force) {
|
|
if (force || (socket._isIdle && isShuttingDown)) {
|
|
socket.destroy();
|
|
delete connections[socket._connectionId];
|
|
}
|
|
};
|
|
|
|
function onConnection(socket) {
|
|
var id = connectionCounter++;
|
|
socket._isIdle = true;
|
|
socket._connectionId = id;
|
|
connections[id] = socket;
|
|
|
|
socket.on('close', function() {
|
|
delete connections[id];
|
|
});
|
|
};
|
|
|
|
server.on('request', function(req, res) {
|
|
req.socket._isIdle = false;
|
|
|
|
res.on('finish', function() {
|
|
req.socket._isIdle = true;
|
|
destroy(req.socket);
|
|
});
|
|
});
|
|
|
|
server.on('connection', onConnection);
|
|
server.on('secureConnection', onConnection);
|
|
|
|
function shutdown(force, cb) {
|
|
isShuttingDown = true;
|
|
server.close(function(err) {
|
|
if (cb) {
|
|
process.nextTick(function() { cb(err); });
|
|
}
|
|
});
|
|
|
|
Object.keys(connections).forEach(function(key) {
|
|
destroy(connections[key], force);
|
|
});
|
|
};
|
|
|
|
server.shutdown = function(cb) {
|
|
shutdown(false, cb);
|
|
};
|
|
|
|
server.forceShutdown = function(cb) {
|
|
shutdown(true, cb);
|
|
};
|
|
|
|
return server;
|
|
};
|
|
|
|
/**
|
|
* Extends the {http.Server} object with shutdown functionaility.
|
|
* @return {http.Server} The decorated server object
|
|
*/
|
|
exports.extend = function() {
|
|
http.Server.prototype.withShutdown = function() {
|
|
return addShutdown(this);
|
|
};
|
|
|
|
https.Server.prototype.withShutdown = function() {
|
|
return addShutdown(this);
|
|
};
|
|
};
|
|
|
|
|
|
/***/ }),
|
|
|
|
/***/ 9491:
|
|
/***/ ((module) => {
|
|
|
|
module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("assert");
|
|
|
|
/***/ }),
|
|
|
|
/***/ 4300:
|
|
/***/ ((module) => {
|
|
|
|
module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("buffer");
|
|
|
|
/***/ }),
|
|
|
|
/***/ 2081:
|
|
/***/ ((module) => {
|
|
|
|
module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("child_process");
|
|
|
|
/***/ }),
|
|
|
|
/***/ 6113:
|
|
/***/ ((module) => {
|
|
|
|
module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("crypto");
|
|
|
|
/***/ }),
|
|
|
|
/***/ 2361:
|
|
/***/ ((module) => {
|
|
|
|
module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("events");
|
|
|
|
/***/ }),
|
|
|
|
/***/ 7147:
|
|
/***/ ((module) => {
|
|
|
|
module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("fs");
|
|
|
|
/***/ }),
|
|
|
|
/***/ 3685:
|
|
/***/ ((module) => {
|
|
|
|
module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("http");
|
|
|
|
/***/ }),
|
|
|
|
/***/ 5687:
|
|
/***/ ((module) => {
|
|
|
|
module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("https");
|
|
|
|
/***/ }),
|
|
|
|
/***/ 9411:
|
|
/***/ ((module) => {
|
|
|
|
module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:path");
|
|
|
|
/***/ }),
|
|
|
|
/***/ 7742:
|
|
/***/ ((module) => {
|
|
|
|
module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:process");
|
|
|
|
/***/ }),
|
|
|
|
/***/ 1041:
|
|
/***/ ((module) => {
|
|
|
|
module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:url");
|
|
|
|
/***/ }),
|
|
|
|
/***/ 7261:
|
|
/***/ ((module) => {
|
|
|
|
module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:util");
|
|
|
|
/***/ }),
|
|
|
|
/***/ 2037:
|
|
/***/ ((module) => {
|
|
|
|
module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("os");
|
|
|
|
/***/ }),
|
|
|
|
/***/ 1017:
|
|
/***/ ((module) => {
|
|
|
|
module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("path");
|
|
|
|
/***/ }),
|
|
|
|
/***/ 2781:
|
|
/***/ ((module) => {
|
|
|
|
module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("stream");
|
|
|
|
/***/ }),
|
|
|
|
/***/ 3837:
|
|
/***/ ((module) => {
|
|
|
|
module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("util");
|
|
|
|
/***/ })
|
|
|
|
/******/ });
|
|
/************************************************************************/
|
|
/******/ // The module cache
|
|
/******/ var __webpack_module_cache__ = {};
|
|
/******/
|
|
/******/ // The require function
|
|
/******/ function __nccwpck_require__(moduleId) {
|
|
/******/ // Check if module is in cache
|
|
/******/ var cachedModule = __webpack_module_cache__[moduleId];
|
|
/******/ if (cachedModule !== undefined) {
|
|
/******/ return cachedModule.exports;
|
|
/******/ }
|
|
/******/ // Create a new module (and put it into the cache)
|
|
/******/ var module = __webpack_module_cache__[moduleId] = {
|
|
/******/ // no module.id needed
|
|
/******/ // no module.loaded needed
|
|
/******/ exports: {}
|
|
/******/ };
|
|
/******/
|
|
/******/ // Execute the module function
|
|
/******/ var threw = true;
|
|
/******/ try {
|
|
/******/ __webpack_modules__[moduleId](module, module.exports, __nccwpck_require__);
|
|
/******/ threw = false;
|
|
/******/ } finally {
|
|
/******/ if(threw) delete __webpack_module_cache__[moduleId];
|
|
/******/ }
|
|
/******/
|
|
/******/ // Return the exports of the module
|
|
/******/ return module.exports;
|
|
/******/ }
|
|
/******/
|
|
/******/ // expose the modules object (__webpack_modules__)
|
|
/******/ __nccwpck_require__.m = __webpack_modules__;
|
|
/******/
|
|
/************************************************************************/
|
|
/******/ /* webpack/runtime/create fake namespace object */
|
|
/******/ (() => {
|
|
/******/ var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);
|
|
/******/ var leafPrototypes;
|
|
/******/ // create a fake namespace object
|
|
/******/ // mode & 1: value is a module id, require it
|
|
/******/ // mode & 2: merge all properties of value into the ns
|
|
/******/ // mode & 4: return value when already ns object
|
|
/******/ // mode & 16: return value when it's Promise-like
|
|
/******/ // mode & 8|1: behave like require
|
|
/******/ __nccwpck_require__.t = function(value, mode) {
|
|
/******/ if(mode & 1) value = this(value);
|
|
/******/ if(mode & 8) return value;
|
|
/******/ if(typeof value === 'object' && value) {
|
|
/******/ if((mode & 4) && value.__esModule) return value;
|
|
/******/ if((mode & 16) && typeof value.then === 'function') return value;
|
|
/******/ }
|
|
/******/ var ns = Object.create(null);
|
|
/******/ __nccwpck_require__.r(ns);
|
|
/******/ var def = {};
|
|
/******/ leafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];
|
|
/******/ for(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) {
|
|
/******/ Object.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));
|
|
/******/ }
|
|
/******/ def['default'] = () => (value);
|
|
/******/ __nccwpck_require__.d(ns, def);
|
|
/******/ return ns;
|
|
/******/ };
|
|
/******/ })();
|
|
/******/
|
|
/******/ /* webpack/runtime/define property getters */
|
|
/******/ (() => {
|
|
/******/ // define getter functions for harmony exports
|
|
/******/ __nccwpck_require__.d = (exports, definition) => {
|
|
/******/ for(var key in definition) {
|
|
/******/ if(__nccwpck_require__.o(definition, key) && !__nccwpck_require__.o(exports, key)) {
|
|
/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
|
|
/******/ }
|
|
/******/ }
|
|
/******/ };
|
|
/******/ })();
|
|
/******/
|
|
/******/ /* webpack/runtime/ensure chunk */
|
|
/******/ (() => {
|
|
/******/ __nccwpck_require__.f = {};
|
|
/******/ // This file contains only the entry chunk.
|
|
/******/ // The chunk loading function for additional chunks
|
|
/******/ __nccwpck_require__.e = (chunkId) => {
|
|
/******/ return Promise.all(Object.keys(__nccwpck_require__.f).reduce((promises, key) => {
|
|
/******/ __nccwpck_require__.f[key](chunkId, promises);
|
|
/******/ return promises;
|
|
/******/ }, []));
|
|
/******/ };
|
|
/******/ })();
|
|
/******/
|
|
/******/ /* webpack/runtime/get javascript chunk filename */
|
|
/******/ (() => {
|
|
/******/ // This function allow to reference async chunks
|
|
/******/ __nccwpck_require__.u = (chunkId) => {
|
|
/******/ // return url for filenames based on template
|
|
/******/ return "" + chunkId + ".index.js";
|
|
/******/ };
|
|
/******/ })();
|
|
/******/
|
|
/******/ /* webpack/runtime/hasOwnProperty shorthand */
|
|
/******/ (() => {
|
|
/******/ __nccwpck_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
|
|
/******/ })();
|
|
/******/
|
|
/******/ /* webpack/runtime/make namespace object */
|
|
/******/ (() => {
|
|
/******/ // define __esModule on exports
|
|
/******/ __nccwpck_require__.r = (exports) => {
|
|
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
|
|
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
/******/ }
|
|
/******/ Object.defineProperty(exports, '__esModule', { value: true });
|
|
/******/ };
|
|
/******/ })();
|
|
/******/
|
|
/******/ /* webpack/runtime/compat */
|
|
/******/
|
|
/******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = new URL('.', import.meta.url).pathname.slice(import.meta.url.match(/^file:\/\/\/\w:/) ? 1 : 0, -1) + "/";
|
|
/******/
|
|
/******/ /* webpack/runtime/import chunk loading */
|
|
/******/ (() => {
|
|
/******/ // no baseURI
|
|
/******/
|
|
/******/ // object to store loaded and loading chunks
|
|
/******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched
|
|
/******/ // [resolve, reject, Promise] = chunk loading, 0 = chunk loaded
|
|
/******/ var installedChunks = {
|
|
/******/ 179: 0
|
|
/******/ };
|
|
/******/
|
|
/******/ var installChunk = (data) => {
|
|
/******/ var {ids, modules, runtime} = data;
|
|
/******/ // add "modules" to the modules object,
|
|
/******/ // then flag all "ids" as loaded and fire callback
|
|
/******/ var moduleId, chunkId, i = 0;
|
|
/******/ for(moduleId in modules) {
|
|
/******/ if(__nccwpck_require__.o(modules, moduleId)) {
|
|
/******/ __nccwpck_require__.m[moduleId] = modules[moduleId];
|
|
/******/ }
|
|
/******/ }
|
|
/******/ if(runtime) runtime(__nccwpck_require__);
|
|
/******/ for(;i < ids.length; i++) {
|
|
/******/ chunkId = ids[i];
|
|
/******/ if(__nccwpck_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {
|
|
/******/ installedChunks[chunkId][0]();
|
|
/******/ }
|
|
/******/ installedChunks[ids[i]] = 0;
|
|
/******/ }
|
|
/******/
|
|
/******/ }
|
|
/******/
|
|
/******/ __nccwpck_require__.f.j = (chunkId, promises) => {
|
|
/******/ // import() chunk loading for javascript
|
|
/******/ var installedChunkData = __nccwpck_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;
|
|
/******/ if(installedChunkData !== 0) { // 0 means "already installed".
|
|
/******/
|
|
/******/ // a Promise means "currently loading".
|
|
/******/ if(installedChunkData) {
|
|
/******/ promises.push(installedChunkData[1]);
|
|
/******/ } else {
|
|
/******/ if(true) { // all chunks have JS
|
|
/******/ // setup Promise in chunk cache
|
|
/******/ var promise = import("./" + __nccwpck_require__.u(chunkId)).then(installChunk, (e) => {
|
|
/******/ if(installedChunks[chunkId] !== 0) installedChunks[chunkId] = undefined;
|
|
/******/ throw e;
|
|
/******/ });
|
|
/******/ var promise = Promise.race([promise, new Promise((resolve) => (installedChunkData = installedChunks[chunkId] = [resolve]))])
|
|
/******/ promises.push(installedChunkData[1] = promise);
|
|
/******/ } else installedChunks[chunkId] = 0;
|
|
/******/ }
|
|
/******/ }
|
|
/******/ };
|
|
/******/
|
|
/******/ // no external install chunk
|
|
/******/
|
|
/******/ // no on chunks loaded
|
|
/******/ })();
|
|
/******/
|
|
/************************************************************************/
|
|
var __webpack_exports__ = {};
|
|
// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
|
|
(() => {
|
|
|
|
// EXPORTS
|
|
__nccwpck_require__.d(__webpack_exports__, {
|
|
"E": () => (/* binding */ FunctionVersionRequestSchema)
|
|
});
|
|
|
|
;// CONCATENATED MODULE: ./node_modules/ufo/dist/index.mjs
|
|
const n = /[^\0-\x7E]/;
|
|
const t = /[\x2E\u3002\uFF0E\uFF61]/g;
|
|
const o = {
|
|
overflow: "Overflow Error",
|
|
"not-basic": "Illegal Input",
|
|
"invalid-input": "Invalid Input"
|
|
};
|
|
const e = Math.floor;
|
|
const r = String.fromCharCode;
|
|
function s(n2) {
|
|
throw new RangeError(o[n2]);
|
|
}
|
|
const c = function(n2, t2) {
|
|
return n2 + 22 + 75 * (n2 < 26) - ((t2 != 0) << 5);
|
|
};
|
|
const u = function(n2, t2, o2) {
|
|
let r2 = 0;
|
|
for (n2 = o2 ? e(n2 / 700) : n2 >> 1, n2 += e(n2 / t2); n2 > 455; r2 += 36) {
|
|
n2 = e(n2 / 35);
|
|
}
|
|
return e(r2 + 36 * n2 / (n2 + 38));
|
|
};
|
|
function toASCII(o2) {
|
|
return function(n2, o3) {
|
|
const e2 = n2.split("@");
|
|
let r2 = "";
|
|
e2.length > 1 && (r2 = e2[0] + "@", n2 = e2[1]);
|
|
const s2 = function(n3, t2) {
|
|
const o4 = [];
|
|
let e3 = n3.length;
|
|
for (; e3--; ) {
|
|
o4[e3] = t2(n3[e3]);
|
|
}
|
|
return o4;
|
|
}((n2 = n2.replace(t, ".")).split("."), o3).join(".");
|
|
return r2 + s2;
|
|
}(o2, function(t2) {
|
|
return n.test(t2) ? "xn--" + function(n2) {
|
|
const t3 = [];
|
|
const o3 = (n2 = function(n3) {
|
|
const t4 = [];
|
|
let o4 = 0;
|
|
const e2 = n3.length;
|
|
for (; o4 < e2; ) {
|
|
const r2 = n3.charCodeAt(o4++);
|
|
if (r2 >= 55296 && r2 <= 56319 && o4 < e2) {
|
|
const e3 = n3.charCodeAt(o4++);
|
|
(64512 & e3) == 56320 ? t4.push(((1023 & r2) << 10) + (1023 & e3) + 65536) : (t4.push(r2), o4--);
|
|
} else {
|
|
t4.push(r2);
|
|
}
|
|
}
|
|
return t4;
|
|
}(n2)).length;
|
|
let f = 128;
|
|
let i = 0;
|
|
let l = 72;
|
|
for (const o4 of n2) {
|
|
o4 < 128 && t3.push(r(o4));
|
|
}
|
|
const h = t3.length;
|
|
let p = h;
|
|
for (h && t3.push("-"); p < o3; ) {
|
|
let o4 = 2147483647;
|
|
for (const t4 of n2) {
|
|
t4 >= f && t4 < o4 && (o4 = t4);
|
|
}
|
|
const a = p + 1;
|
|
o4 - f > e((2147483647 - i) / a) && s("overflow"), i += (o4 - f) * a, f = o4;
|
|
for (const o5 of n2) {
|
|
if (o5 < f && ++i > 2147483647 && s("overflow"), o5 == f) {
|
|
let n3 = i;
|
|
for (let o6 = 36; ; o6 += 36) {
|
|
const s2 = o6 <= l ? 1 : o6 >= l + 26 ? 26 : o6 - l;
|
|
if (n3 < s2) {
|
|
break;
|
|
}
|
|
const u2 = n3 - s2;
|
|
const f2 = 36 - s2;
|
|
t3.push(r(c(s2 + u2 % f2, 0))), n3 = e(u2 / f2);
|
|
}
|
|
t3.push(r(c(n3, 0))), l = u(i, a, p == h), i = 0, ++p;
|
|
}
|
|
}
|
|
++i, ++f;
|
|
}
|
|
return t3.join("");
|
|
}(t2) : t2;
|
|
});
|
|
}
|
|
|
|
const HASH_RE = /#/g;
|
|
const AMPERSAND_RE = /&/g;
|
|
const SLASH_RE = /\//g;
|
|
const EQUAL_RE = /=/g;
|
|
const IM_RE = /\?/g;
|
|
const PLUS_RE = /\+/g;
|
|
const ENC_CARET_RE = /%5e/gi;
|
|
const ENC_BACKTICK_RE = /%60/gi;
|
|
const ENC_CURLY_OPEN_RE = /%7b/gi;
|
|
const ENC_PIPE_RE = /%7c/gi;
|
|
const ENC_CURLY_CLOSE_RE = /%7d/gi;
|
|
const ENC_SPACE_RE = /%20/gi;
|
|
const ENC_SLASH_RE = /%2f/gi;
|
|
const ENC_ENC_SLASH_RE = /%252f/gi;
|
|
function encode(text) {
|
|
return encodeURI("" + text).replace(ENC_PIPE_RE, "|");
|
|
}
|
|
function encodeHash(text) {
|
|
return encode(text).replace(ENC_CURLY_OPEN_RE, "{").replace(ENC_CURLY_CLOSE_RE, "}").replace(ENC_CARET_RE, "^");
|
|
}
|
|
function encodeQueryValue(input) {
|
|
return encode(typeof input === "string" ? input : JSON.stringify(input)).replace(PLUS_RE, "%2B").replace(ENC_SPACE_RE, "+").replace(HASH_RE, "%23").replace(AMPERSAND_RE, "%26").replace(ENC_BACKTICK_RE, "`").replace(ENC_CARET_RE, "^");
|
|
}
|
|
function encodeQueryKey(text) {
|
|
return encodeQueryValue(text).replace(EQUAL_RE, "%3D");
|
|
}
|
|
function encodePath(text) {
|
|
return encode(text).replace(HASH_RE, "%23").replace(IM_RE, "%3F").replace(ENC_ENC_SLASH_RE, "%2F").replace(AMPERSAND_RE, "%26").replace(PLUS_RE, "%2B");
|
|
}
|
|
function encodeParam(text) {
|
|
return encodePath(text).replace(SLASH_RE, "%2F");
|
|
}
|
|
function decode(text = "") {
|
|
try {
|
|
return decodeURIComponent("" + text);
|
|
} catch {
|
|
return "" + text;
|
|
}
|
|
}
|
|
function decodePath(text) {
|
|
return decode(text.replace(ENC_SLASH_RE, "%252F"));
|
|
}
|
|
function decodeQueryValue(text) {
|
|
return decode(text.replace(PLUS_RE, " "));
|
|
}
|
|
function encodeHost(name = "") {
|
|
return toASCII(name);
|
|
}
|
|
|
|
function parseQuery(parametersString = "") {
|
|
const object = {};
|
|
if (parametersString[0] === "?") {
|
|
parametersString = parametersString.slice(1);
|
|
}
|
|
for (const parameter of parametersString.split("&")) {
|
|
const s = parameter.match(/([^=]+)=?(.*)/) || [];
|
|
if (s.length < 2) {
|
|
continue;
|
|
}
|
|
const key = decode(s[1]);
|
|
if (key === "__proto__" || key === "constructor") {
|
|
continue;
|
|
}
|
|
const value = decodeQueryValue(s[2] || "");
|
|
if (typeof object[key] !== "undefined") {
|
|
if (Array.isArray(object[key])) {
|
|
object[key].push(value);
|
|
} else {
|
|
object[key] = [object[key], value];
|
|
}
|
|
} else {
|
|
object[key] = value;
|
|
}
|
|
}
|
|
return object;
|
|
}
|
|
function encodeQueryItem(key, value) {
|
|
if (typeof value === "number" || typeof value === "boolean") {
|
|
value = String(value);
|
|
}
|
|
if (!value) {
|
|
return encodeQueryKey(key);
|
|
}
|
|
if (Array.isArray(value)) {
|
|
return value.map((_value) => `${encodeQueryKey(key)}=${encodeQueryValue(_value)}`).join("&");
|
|
}
|
|
return `${encodeQueryKey(key)}=${encodeQueryValue(value)}`;
|
|
}
|
|
function stringifyQuery(query) {
|
|
return Object.keys(query).filter((k) => query[k] !== void 0).map((k) => encodeQueryItem(k, query[k])).join("&");
|
|
}
|
|
|
|
class $URL {
|
|
constructor(input = "") {
|
|
this.query = {};
|
|
if (typeof input !== "string") {
|
|
throw new TypeError(
|
|
`URL input should be string received ${typeof input} (${input})`
|
|
);
|
|
}
|
|
const parsed = parseURL(input);
|
|
this.protocol = decode(parsed.protocol);
|
|
this.host = decode(parsed.host);
|
|
this.auth = decode(parsed.auth);
|
|
this.pathname = decodePath(parsed.pathname);
|
|
this.query = parseQuery(parsed.search);
|
|
this.hash = decode(parsed.hash);
|
|
}
|
|
get hostname() {
|
|
return parseHost(this.host).hostname;
|
|
}
|
|
get port() {
|
|
return parseHost(this.host).port || "";
|
|
}
|
|
get username() {
|
|
return parseAuth(this.auth).username;
|
|
}
|
|
get password() {
|
|
return parseAuth(this.auth).password || "";
|
|
}
|
|
get hasProtocol() {
|
|
return this.protocol.length;
|
|
}
|
|
get isAbsolute() {
|
|
return this.hasProtocol || this.pathname[0] === "/";
|
|
}
|
|
get search() {
|
|
const q = stringifyQuery(this.query);
|
|
return q.length > 0 ? "?" + q : "";
|
|
}
|
|
get searchParams() {
|
|
const p = new URLSearchParams();
|
|
for (const name in this.query) {
|
|
const value = this.query[name];
|
|
if (Array.isArray(value)) {
|
|
for (const v of value) {
|
|
p.append(name, v);
|
|
}
|
|
} else {
|
|
p.append(
|
|
name,
|
|
typeof value === "string" ? value : JSON.stringify(value)
|
|
);
|
|
}
|
|
}
|
|
return p;
|
|
}
|
|
get origin() {
|
|
return (this.protocol ? this.protocol + "//" : "") + encodeHost(this.host);
|
|
}
|
|
get fullpath() {
|
|
return encodePath(this.pathname) + this.search + encodeHash(this.hash);
|
|
}
|
|
get encodedAuth() {
|
|
if (!this.auth) {
|
|
return "";
|
|
}
|
|
const { username, password } = parseAuth(this.auth);
|
|
return encodeURIComponent(username) + (password ? ":" + encodeURIComponent(password) : "");
|
|
}
|
|
get href() {
|
|
const auth = this.encodedAuth;
|
|
const originWithAuth = (this.protocol ? this.protocol + "//" : "") + (auth ? auth + "@" : "") + encodeHost(this.host);
|
|
return this.hasProtocol && this.isAbsolute ? originWithAuth + this.fullpath : this.fullpath;
|
|
}
|
|
append(url) {
|
|
if (url.hasProtocol) {
|
|
throw new Error("Cannot append a URL with protocol");
|
|
}
|
|
Object.assign(this.query, url.query);
|
|
if (url.pathname) {
|
|
this.pathname = withTrailingSlash(this.pathname) + withoutLeadingSlash(url.pathname);
|
|
}
|
|
if (url.hash) {
|
|
this.hash = url.hash;
|
|
}
|
|
}
|
|
toJSON() {
|
|
return this.href;
|
|
}
|
|
toString() {
|
|
return this.href;
|
|
}
|
|
}
|
|
|
|
function isRelative(inputString) {
|
|
return ["./", "../"].some((string_) => inputString.startsWith(string_));
|
|
}
|
|
const PROTOCOL_STRICT_REGEX = /^\w{2,}:([/\\]{1,2})/;
|
|
const PROTOCOL_REGEX = /^\w{2,}:([/\\]{2})?/;
|
|
const PROTOCOL_RELATIVE_REGEX = /^([/\\]\s*){2,}[^/\\]/;
|
|
function hasProtocol(inputString, opts = {}) {
|
|
if (typeof opts === "boolean") {
|
|
opts = { acceptRelative: opts };
|
|
}
|
|
if (opts.strict) {
|
|
return PROTOCOL_STRICT_REGEX.test(inputString);
|
|
}
|
|
return PROTOCOL_REGEX.test(inputString) || (opts.acceptRelative ? PROTOCOL_RELATIVE_REGEX.test(inputString) : false);
|
|
}
|
|
const TRAILING_SLASH_RE = /\/$|\/\?/;
|
|
function hasTrailingSlash(input = "", queryParameters = false) {
|
|
if (!queryParameters) {
|
|
return input.endsWith("/");
|
|
}
|
|
return TRAILING_SLASH_RE.test(input);
|
|
}
|
|
function dist_withoutTrailingSlash(input = "", queryParameters = false) {
|
|
if (!queryParameters) {
|
|
return (hasTrailingSlash(input) ? input.slice(0, -1) : input) || "/";
|
|
}
|
|
if (!hasTrailingSlash(input, true)) {
|
|
return input || "/";
|
|
}
|
|
const [s0, ...s] = input.split("?");
|
|
return (s0.slice(0, -1) || "/") + (s.length > 0 ? `?${s.join("?")}` : "");
|
|
}
|
|
function withTrailingSlash(input = "", queryParameters = false) {
|
|
if (!queryParameters) {
|
|
return input.endsWith("/") ? input : input + "/";
|
|
}
|
|
if (hasTrailingSlash(input, true)) {
|
|
return input || "/";
|
|
}
|
|
const [s0, ...s] = input.split("?");
|
|
return s0 + "/" + (s.length > 0 ? `?${s.join("?")}` : "");
|
|
}
|
|
function hasLeadingSlash(input = "") {
|
|
return input.startsWith("/");
|
|
}
|
|
function withoutLeadingSlash(input = "") {
|
|
return (hasLeadingSlash(input) ? input.slice(1) : input) || "/";
|
|
}
|
|
function withLeadingSlash(input = "") {
|
|
return hasLeadingSlash(input) ? input : "/" + input;
|
|
}
|
|
function cleanDoubleSlashes(input = "") {
|
|
return input.split("://").map((string_) => string_.replace(/\/{2,}/g, "/")).join("://");
|
|
}
|
|
function withBase(input, base) {
|
|
if (isEmptyURL(base) || hasProtocol(input)) {
|
|
return input;
|
|
}
|
|
const _base = dist_withoutTrailingSlash(base);
|
|
if (input.startsWith(_base)) {
|
|
return input;
|
|
}
|
|
return joinURL(_base, input);
|
|
}
|
|
function dist_withoutBase(input, base) {
|
|
if (isEmptyURL(base)) {
|
|
return input;
|
|
}
|
|
const _base = dist_withoutTrailingSlash(base);
|
|
if (!input.startsWith(_base)) {
|
|
return input;
|
|
}
|
|
const trimmed = input.slice(_base.length);
|
|
return trimmed[0] === "/" ? trimmed : "/" + trimmed;
|
|
}
|
|
function withQuery(input, query) {
|
|
const parsed = parseURL(input);
|
|
const mergedQuery = { ...parseQuery(parsed.search), ...query };
|
|
parsed.search = stringifyQuery(mergedQuery);
|
|
return stringifyParsedURL(parsed);
|
|
}
|
|
function getQuery(input) {
|
|
return parseQuery(parseURL(input).search);
|
|
}
|
|
function isEmptyURL(url) {
|
|
return !url || url === "/";
|
|
}
|
|
function isNonEmptyURL(url) {
|
|
return url && url !== "/";
|
|
}
|
|
function joinURL(base, ...input) {
|
|
let url = base || "";
|
|
for (const index of input.filter((url2) => isNonEmptyURL(url2))) {
|
|
url = url ? withTrailingSlash(url) + withoutLeadingSlash(index) : index;
|
|
}
|
|
return url;
|
|
}
|
|
function withHttp(input) {
|
|
return withProtocol(input, "http://");
|
|
}
|
|
function withHttps(input) {
|
|
return withProtocol(input, "https://");
|
|
}
|
|
function withoutProtocol(input) {
|
|
return withProtocol(input, "");
|
|
}
|
|
function withProtocol(input, protocol) {
|
|
const match = input.match(PROTOCOL_REGEX);
|
|
if (!match) {
|
|
return protocol + input;
|
|
}
|
|
return protocol + input.slice(match[0].length);
|
|
}
|
|
function createURL(input) {
|
|
return new $URL(input);
|
|
}
|
|
function normalizeURL(input) {
|
|
return createURL(input).toString();
|
|
}
|
|
function resolveURL(base, ...input) {
|
|
const url = createURL(base);
|
|
for (const index of input.filter((url2) => isNonEmptyURL(url2))) {
|
|
url.append(createURL(index));
|
|
}
|
|
return url.toString();
|
|
}
|
|
function isSamePath(p1, p2) {
|
|
return decode(dist_withoutTrailingSlash(p1)) === decode(dist_withoutTrailingSlash(p2));
|
|
}
|
|
function isEqual(a, b, options = {}) {
|
|
if (!options.trailingSlash) {
|
|
a = withTrailingSlash(a);
|
|
b = withTrailingSlash(b);
|
|
}
|
|
if (!options.leadingSlash) {
|
|
a = withLeadingSlash(a);
|
|
b = withLeadingSlash(b);
|
|
}
|
|
if (!options.encoding) {
|
|
a = decode(a);
|
|
b = decode(b);
|
|
}
|
|
return a === b;
|
|
}
|
|
|
|
function parseURL(input = "", defaultProto) {
|
|
if (!hasProtocol(input, { acceptRelative: true })) {
|
|
return defaultProto ? parseURL(defaultProto + input) : parsePath(input);
|
|
}
|
|
const [protocol = "", auth, hostAndPath = ""] = (input.replace(/\\/g, "/").match(/([^/:]+:)?\/\/([^/@]+@)?(.*)/) || []).splice(1);
|
|
const [host = "", path = ""] = (hostAndPath.match(/([^#/?]*)(.*)?/) || []).splice(1);
|
|
const { pathname, search, hash } = parsePath(
|
|
path.replace(/\/(?=[A-Za-z]:)/, "")
|
|
);
|
|
return {
|
|
protocol,
|
|
auth: auth ? auth.slice(0, Math.max(0, auth.length - 1)) : "",
|
|
host,
|
|
pathname,
|
|
search,
|
|
hash
|
|
};
|
|
}
|
|
function parsePath(input = "") {
|
|
const [pathname = "", search = "", hash = ""] = (input.match(/([^#?]*)(\?[^#]*)?(#.*)?/) || []).splice(1);
|
|
return {
|
|
pathname,
|
|
search,
|
|
hash
|
|
};
|
|
}
|
|
function parseAuth(input = "") {
|
|
const [username, password] = input.split(":");
|
|
return {
|
|
username: decode(username),
|
|
password: decode(password)
|
|
};
|
|
}
|
|
function parseHost(input = "") {
|
|
const [hostname, port] = (input.match(/([^/:]*):?(\d+)?/) || []).splice(1);
|
|
return {
|
|
hostname: decode(hostname),
|
|
port
|
|
};
|
|
}
|
|
function stringifyParsedURL(parsed) {
|
|
const fullpath = parsed.pathname + (parsed.search ? (parsed.search.startsWith("?") ? "" : "?") + parsed.search : "") + parsed.hash;
|
|
if (!parsed.protocol) {
|
|
return fullpath;
|
|
}
|
|
return parsed.protocol + "//" + (parsed.auth ? parsed.auth + "@" : "") + parsed.host + fullpath;
|
|
}
|
|
|
|
|
|
|
|
;// CONCATENATED MODULE: ./node_modules/radix3/dist/index.mjs
|
|
const NODE_TYPES = {
|
|
NORMAL: 0,
|
|
WILDCARD: 1,
|
|
PLACEHOLDER: 2
|
|
};
|
|
|
|
function createRouter(options = {}) {
|
|
const ctx = {
|
|
options,
|
|
rootNode: createRadixNode(),
|
|
staticRoutesMap: {}
|
|
};
|
|
const normalizeTrailingSlash = (p) => options.strictTrailingSlash ? p : p.replace(/\/$/, "") || "/";
|
|
if (options.routes) {
|
|
for (const path in options.routes) {
|
|
insert(ctx, normalizeTrailingSlash(path), options.routes[path]);
|
|
}
|
|
}
|
|
return {
|
|
ctx,
|
|
// @ts-ignore
|
|
lookup: (path) => lookup(ctx, normalizeTrailingSlash(path)),
|
|
insert: (path, data) => insert(ctx, normalizeTrailingSlash(path), data),
|
|
remove: (path) => remove(ctx, normalizeTrailingSlash(path))
|
|
};
|
|
}
|
|
function lookup(ctx, path) {
|
|
const staticPathNode = ctx.staticRoutesMap[path];
|
|
if (staticPathNode) {
|
|
return staticPathNode.data;
|
|
}
|
|
const sections = path.split("/");
|
|
const params = {};
|
|
let paramsFound = false;
|
|
let wildcardNode = null;
|
|
let node = ctx.rootNode;
|
|
let wildCardParam = null;
|
|
for (let i = 0; i < sections.length; i++) {
|
|
const section = sections[i];
|
|
if (node.wildcardChildNode !== null) {
|
|
wildcardNode = node.wildcardChildNode;
|
|
wildCardParam = sections.slice(i).join("/");
|
|
}
|
|
const nextNode = node.children.get(section);
|
|
if (nextNode !== void 0) {
|
|
node = nextNode;
|
|
} else {
|
|
node = node.placeholderChildNode;
|
|
if (node !== null) {
|
|
params[node.paramName] = section;
|
|
paramsFound = true;
|
|
} else {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
if ((node === null || node.data === null) && wildcardNode !== null) {
|
|
node = wildcardNode;
|
|
params[node.paramName || "_"] = wildCardParam;
|
|
paramsFound = true;
|
|
}
|
|
if (!node) {
|
|
return null;
|
|
}
|
|
if (paramsFound) {
|
|
return {
|
|
...node.data,
|
|
params: paramsFound ? params : void 0
|
|
};
|
|
}
|
|
return node.data;
|
|
}
|
|
function insert(ctx, path, data) {
|
|
let isStaticRoute = true;
|
|
const sections = path.split("/");
|
|
let node = ctx.rootNode;
|
|
let _unnamedPlaceholderCtr = 0;
|
|
for (const section of sections) {
|
|
let childNode;
|
|
if (childNode = node.children.get(section)) {
|
|
node = childNode;
|
|
} else {
|
|
const type = getNodeType(section);
|
|
childNode = createRadixNode({ type, parent: node });
|
|
node.children.set(section, childNode);
|
|
if (type === NODE_TYPES.PLACEHOLDER) {
|
|
childNode.paramName = section === "*" ? `_${_unnamedPlaceholderCtr++}` : section.slice(1);
|
|
node.placeholderChildNode = childNode;
|
|
isStaticRoute = false;
|
|
} else if (type === NODE_TYPES.WILDCARD) {
|
|
node.wildcardChildNode = childNode;
|
|
childNode.paramName = section.slice(
|
|
3
|
|
/* "**:" */
|
|
) || "_";
|
|
isStaticRoute = false;
|
|
}
|
|
node = childNode;
|
|
}
|
|
}
|
|
node.data = data;
|
|
if (isStaticRoute === true) {
|
|
ctx.staticRoutesMap[path] = node;
|
|
}
|
|
return node;
|
|
}
|
|
function remove(ctx, path) {
|
|
let success = false;
|
|
const sections = path.split("/");
|
|
let node = ctx.rootNode;
|
|
for (const section of sections) {
|
|
node = node.children.get(section);
|
|
if (!node) {
|
|
return success;
|
|
}
|
|
}
|
|
if (node.data) {
|
|
const lastSection = sections[sections.length - 1];
|
|
node.data = null;
|
|
if (Object.keys(node.children).length === 0) {
|
|
const parentNode = node.parent;
|
|
parentNode.children.delete(lastSection);
|
|
parentNode.wildcardChildNode = null;
|
|
parentNode.placeholderChildNode = null;
|
|
}
|
|
success = true;
|
|
}
|
|
return success;
|
|
}
|
|
function createRadixNode(options = {}) {
|
|
return {
|
|
type: options.type || NODE_TYPES.NORMAL,
|
|
parent: options.parent || null,
|
|
children: /* @__PURE__ */ new Map(),
|
|
data: options.data || null,
|
|
paramName: options.paramName || null,
|
|
wildcardChildNode: null,
|
|
placeholderChildNode: null
|
|
};
|
|
}
|
|
function getNodeType(str) {
|
|
if (str.startsWith("**")) {
|
|
return NODE_TYPES.WILDCARD;
|
|
}
|
|
if (str[0] === ":" || str === "*") {
|
|
return NODE_TYPES.PLACEHOLDER;
|
|
}
|
|
return NODE_TYPES.NORMAL;
|
|
}
|
|
|
|
function toRouteMatcher(router) {
|
|
const table = _routerNodeToTable("", router.ctx.rootNode);
|
|
return _createMatcher(table);
|
|
}
|
|
function _createMatcher(table) {
|
|
return {
|
|
ctx: { table },
|
|
matchAll: (path) => _matchRoutes(path, table)
|
|
};
|
|
}
|
|
function _createRouteTable() {
|
|
return {
|
|
static: /* @__PURE__ */ new Map(),
|
|
wildcard: /* @__PURE__ */ new Map(),
|
|
dynamic: /* @__PURE__ */ new Map()
|
|
};
|
|
}
|
|
function _matchRoutes(path, table) {
|
|
const matches = [];
|
|
for (const [key, value] of _sortRoutesMap(table.wildcard)) {
|
|
if (path.startsWith(key)) {
|
|
matches.push(value);
|
|
}
|
|
}
|
|
for (const [key, value] of _sortRoutesMap(table.dynamic)) {
|
|
if (path.startsWith(key + "/")) {
|
|
const subPath = "/" + path.slice(key.length).split("/").splice(2).join("/");
|
|
matches.push(..._matchRoutes(subPath, value));
|
|
}
|
|
}
|
|
const staticMatch = table.static.get(path);
|
|
if (staticMatch) {
|
|
matches.push(staticMatch);
|
|
}
|
|
return matches.filter(Boolean);
|
|
}
|
|
function _sortRoutesMap(m) {
|
|
return [...m.entries()].sort((a, b) => a[0].length - b[0].length);
|
|
}
|
|
function _routerNodeToTable(initialPath, initialNode) {
|
|
const table = _createRouteTable();
|
|
function _addNode(path, node) {
|
|
if (path) {
|
|
if (node.type === NODE_TYPES.NORMAL && !(path.includes("*") || path.includes(":"))) {
|
|
table.static.set(path, node.data);
|
|
} else if (node.type === NODE_TYPES.WILDCARD) {
|
|
table.wildcard.set(path.replace("/**", ""), node.data);
|
|
} else if (node.type === NODE_TYPES.PLACEHOLDER) {
|
|
const subTable = _routerNodeToTable("", node);
|
|
if (node.data) {
|
|
subTable.static.set("/", node.data);
|
|
}
|
|
table.dynamic.set(path.replace(/\/\*|\/:\w+/, ""), subTable);
|
|
return;
|
|
}
|
|
}
|
|
for (const [childPath, child] of node.children.entries()) {
|
|
_addNode(`${path}/${childPath}`.replace("//", "/"), child);
|
|
}
|
|
}
|
|
_addNode(initialPath, initialNode);
|
|
return table;
|
|
}
|
|
|
|
|
|
|
|
;// CONCATENATED MODULE: ./node_modules/destr/dist/index.mjs
|
|
const suspectProtoRx = /"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/;
|
|
const suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
|
|
const JsonSigRx = /^\s*["[{]|^\s*-?\d[\d.]{0,14}\s*$/;
|
|
function jsonParseTransform(key, value) {
|
|
if (key === "__proto__" || key === "constructor" && value && typeof value === "object" && "prototype" in value) {
|
|
warnKeyDropped(key);
|
|
return;
|
|
}
|
|
return value;
|
|
}
|
|
function warnKeyDropped(key) {
|
|
console.warn(`[destr] Dropping "${key}" key to prevent prototype pollution.`);
|
|
}
|
|
function destr(value, options = {}) {
|
|
if (typeof value !== "string") {
|
|
return value;
|
|
}
|
|
const _value = value.trim();
|
|
if (value[0] === '"' && value[value.length - 1] === '"') {
|
|
return _value.slice(1, -1);
|
|
}
|
|
const _lval = _value.toLowerCase();
|
|
if (_lval === "true") {
|
|
return true;
|
|
}
|
|
if (_lval === "false") {
|
|
return false;
|
|
}
|
|
if (_lval === "undefined") {
|
|
return void 0;
|
|
}
|
|
if (_lval === "null") {
|
|
return null;
|
|
}
|
|
if (_lval === "nan") {
|
|
return Number.NaN;
|
|
}
|
|
if (_lval === "infinity") {
|
|
return Number.POSITIVE_INFINITY;
|
|
}
|
|
if (_lval === "-infinity") {
|
|
return Number.NEGATIVE_INFINITY;
|
|
}
|
|
if (!JsonSigRx.test(value)) {
|
|
if (options.strict) {
|
|
throw new SyntaxError("[destr] Invalid JSON");
|
|
}
|
|
return value;
|
|
}
|
|
try {
|
|
if (suspectProtoRx.test(value) || suspectConstructorRx.test(value)) {
|
|
if (options.strict) {
|
|
throw new Error("[destr] Possible prototype pollution");
|
|
}
|
|
return JSON.parse(value, jsonParseTransform);
|
|
}
|
|
return JSON.parse(value);
|
|
} catch (error) {
|
|
if (options.strict) {
|
|
throw error;
|
|
}
|
|
return value;
|
|
}
|
|
}
|
|
function safeDestr(value, options = {}) {
|
|
return destr(value, { ...options, strict: true });
|
|
}
|
|
|
|
|
|
|
|
;// CONCATENATED MODULE: ./node_modules/defu/dist/defu.mjs
|
|
function isObject(value) {
|
|
return value !== null && typeof value === "object";
|
|
}
|
|
function _defu(baseObject, defaults, namespace = ".", merger) {
|
|
if (!isObject(defaults)) {
|
|
return _defu(baseObject, {}, namespace, merger);
|
|
}
|
|
const object = Object.assign({}, defaults);
|
|
for (const key in baseObject) {
|
|
if (key === "__proto__" || key === "constructor") {
|
|
continue;
|
|
}
|
|
const value = baseObject[key];
|
|
if (value === null || value === void 0) {
|
|
continue;
|
|
}
|
|
if (merger && merger(object, key, value, namespace)) {
|
|
continue;
|
|
}
|
|
if (Array.isArray(value) && Array.isArray(object[key])) {
|
|
object[key] = [...value, ...object[key]];
|
|
} else if (isObject(value) && isObject(object[key])) {
|
|
object[key] = _defu(
|
|
value,
|
|
object[key],
|
|
(namespace ? `${namespace}.` : "") + key.toString(),
|
|
merger
|
|
);
|
|
} else {
|
|
object[key] = value;
|
|
}
|
|
}
|
|
return object;
|
|
}
|
|
function createDefu(merger) {
|
|
return (...arguments_) => (
|
|
// eslint-disable-next-line unicorn/no-array-reduce
|
|
arguments_.reduce((p, c) => _defu(p, c, "", merger), {})
|
|
);
|
|
}
|
|
const defu_defu = createDefu();
|
|
const defuFn = createDefu((object, key, currentValue) => {
|
|
if (typeof object[key] !== "undefined" && typeof currentValue === "function") {
|
|
object[key] = currentValue(object[key]);
|
|
return true;
|
|
}
|
|
});
|
|
const defuArrayFn = createDefu((object, key, currentValue) => {
|
|
if (Array.isArray(object[key]) && typeof currentValue === "function") {
|
|
object[key] = currentValue(object[key]);
|
|
return true;
|
|
}
|
|
});
|
|
|
|
|
|
|
|
;// CONCATENATED MODULE: ./node_modules/h3/dist/index.mjs
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function useBase(base, handler) {
|
|
base = withoutTrailingSlash(base);
|
|
if (!base) {
|
|
return handler;
|
|
}
|
|
return eventHandler((event) => {
|
|
event.node.req.originalUrl = event.node.req.originalUrl || event.node.req.url || "/";
|
|
event.node.req.url = withoutBase(event.node.req.url || "/", base);
|
|
return handler(event);
|
|
});
|
|
}
|
|
|
|
function parse(multipartBodyBuffer, boundary) {
|
|
let lastline = "";
|
|
let state = 0 /* INIT */;
|
|
let buffer = [];
|
|
const allParts = [];
|
|
let currentPartHeaders = [];
|
|
for (let i = 0; i < multipartBodyBuffer.length; i++) {
|
|
const prevByte = i > 0 ? multipartBodyBuffer[i - 1] : null;
|
|
const currByte = multipartBodyBuffer[i];
|
|
const newLineChar = currByte === 10 || currByte === 13;
|
|
if (!newLineChar) {
|
|
lastline += String.fromCodePoint(currByte);
|
|
}
|
|
const newLineDetected = currByte === 10 && prevByte === 13;
|
|
if (0 /* INIT */ === state && newLineDetected) {
|
|
if ("--" + boundary === lastline) {
|
|
state = 1 /* READING_HEADERS */;
|
|
}
|
|
lastline = "";
|
|
} else if (1 /* READING_HEADERS */ === state && newLineDetected) {
|
|
if (lastline.length > 0) {
|
|
const i2 = lastline.indexOf(":");
|
|
if (i2 > 0) {
|
|
const name = lastline.slice(0, i2).toLowerCase();
|
|
const value = lastline.slice(i2 + 1).trim();
|
|
currentPartHeaders.push([name, value]);
|
|
}
|
|
} else {
|
|
state = 2 /* READING_DATA */;
|
|
buffer = [];
|
|
}
|
|
lastline = "";
|
|
} else if (2 /* READING_DATA */ === state) {
|
|
if (lastline.length > boundary.length + 4) {
|
|
lastline = "";
|
|
}
|
|
if ("--" + boundary === lastline) {
|
|
const j = buffer.length - lastline.length;
|
|
const part = buffer.slice(0, j - 1);
|
|
allParts.push(dist_process(part, currentPartHeaders));
|
|
buffer = [];
|
|
currentPartHeaders = [];
|
|
lastline = "";
|
|
state = 3 /* READING_PART_SEPARATOR */;
|
|
} else {
|
|
buffer.push(currByte);
|
|
}
|
|
if (newLineDetected) {
|
|
lastline = "";
|
|
}
|
|
} else if (3 /* READING_PART_SEPARATOR */ === state && newLineDetected) {
|
|
state = 1 /* READING_HEADERS */;
|
|
}
|
|
}
|
|
return allParts;
|
|
}
|
|
function dist_process(data, headers) {
|
|
const dataObj = {};
|
|
const contentDispositionHeader = headers.find((h) => h[0] === "content-disposition")?.[1] || "";
|
|
for (const i of contentDispositionHeader.split(";")) {
|
|
const s = i.split("=");
|
|
if (s.length !== 2) {
|
|
continue;
|
|
}
|
|
const key = (s[0] || "").trim();
|
|
if (key === "name" || key === "filename") {
|
|
dataObj[key] = (s[1] || "").trim().replace(/"/g, "");
|
|
}
|
|
}
|
|
const contentType = headers.find((h) => h[0] === "content-type")?.[1] || "";
|
|
if (contentType) {
|
|
dataObj.type = contentType;
|
|
}
|
|
dataObj.data = Buffer.from(data);
|
|
return dataObj;
|
|
}
|
|
|
|
class H3Error extends Error {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.statusCode = 500;
|
|
this.fatal = false;
|
|
this.unhandled = false;
|
|
}
|
|
toJSON() {
|
|
const obj = {
|
|
message: this.message,
|
|
statusCode: sanitizeStatusCode(this.statusCode, 500)
|
|
};
|
|
if (this.statusMessage) {
|
|
obj.statusMessage = sanitizeStatusMessage(this.statusMessage);
|
|
}
|
|
if (this.data !== void 0) {
|
|
obj.data = this.data;
|
|
}
|
|
return obj;
|
|
}
|
|
}
|
|
H3Error.__h3_error__ = true;
|
|
function createError(input) {
|
|
if (typeof input === "string") {
|
|
return new H3Error(input);
|
|
}
|
|
if (isError(input)) {
|
|
return input;
|
|
}
|
|
const err = new H3Error(
|
|
input.message ?? input.statusMessage ?? "",
|
|
// @ts-ignore https://v8.dev/features/error-cause
|
|
input.cause ? { cause: input.cause } : void 0
|
|
);
|
|
if ("stack" in input) {
|
|
try {
|
|
Object.defineProperty(err, "stack", {
|
|
get() {
|
|
return input.stack;
|
|
}
|
|
});
|
|
} catch {
|
|
try {
|
|
err.stack = input.stack;
|
|
} catch {
|
|
}
|
|
}
|
|
}
|
|
if (input.data) {
|
|
err.data = input.data;
|
|
}
|
|
if (input.statusCode) {
|
|
err.statusCode = sanitizeStatusCode(input.statusCode, err.statusCode);
|
|
} else if (input.status) {
|
|
err.statusCode = sanitizeStatusCode(input.status, err.statusCode);
|
|
}
|
|
if (input.statusMessage) {
|
|
err.statusMessage = input.statusMessage;
|
|
} else if (input.statusText) {
|
|
err.statusMessage = input.statusText;
|
|
}
|
|
if (err.statusMessage) {
|
|
const originalMessage = err.statusMessage;
|
|
const sanitizedMessage = sanitizeStatusMessage(err.statusMessage);
|
|
if (sanitizedMessage !== originalMessage) {
|
|
console.warn(
|
|
"[h3] Please prefer using `message` for longer error messages instead of `statusMessage`. In the future, `statusMessage` will be sanitized by default."
|
|
);
|
|
}
|
|
}
|
|
if (input.fatal !== void 0) {
|
|
err.fatal = input.fatal;
|
|
}
|
|
if (input.unhandled !== void 0) {
|
|
err.unhandled = input.unhandled;
|
|
}
|
|
return err;
|
|
}
|
|
function sendError(event, error, debug) {
|
|
if (event.handled) {
|
|
return;
|
|
}
|
|
const h3Error = isError(error) ? error : createError(error);
|
|
const responseBody = {
|
|
statusCode: h3Error.statusCode,
|
|
statusMessage: h3Error.statusMessage,
|
|
stack: [],
|
|
data: h3Error.data
|
|
};
|
|
if (debug) {
|
|
responseBody.stack = (h3Error.stack || "").split("\n").map((l) => l.trim());
|
|
}
|
|
if (event.handled) {
|
|
return;
|
|
}
|
|
const _code = Number.parseInt(h3Error.statusCode);
|
|
setResponseStatus(event, _code, h3Error.statusMessage);
|
|
event.node.res.setHeader("content-type", MIMES.json);
|
|
event.node.res.end(JSON.stringify(responseBody, void 0, 2));
|
|
}
|
|
function isError(input) {
|
|
return input?.constructor?.__h3_error__ === true;
|
|
}
|
|
|
|
function dist_getQuery(event) {
|
|
return getQuery$1(event.node.req.url || "");
|
|
}
|
|
function getRouterParams(event) {
|
|
return event.context.params || {};
|
|
}
|
|
function getRouterParam(event, name) {
|
|
const params = getRouterParams(event);
|
|
return params[name];
|
|
}
|
|
function getMethod(event, defaultMethod = "GET") {
|
|
return (event.node.req.method || defaultMethod).toUpperCase();
|
|
}
|
|
function isMethod(event, expected, allowHead) {
|
|
const method = getMethod(event);
|
|
if (allowHead && method === "HEAD") {
|
|
return true;
|
|
}
|
|
if (typeof expected === "string") {
|
|
if (method === expected) {
|
|
return true;
|
|
}
|
|
} else if (expected.includes(method)) {
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
function assertMethod(event, expected, allowHead) {
|
|
if (!isMethod(event, expected, allowHead)) {
|
|
throw createError({
|
|
statusCode: 405,
|
|
statusMessage: "HTTP method is not allowed."
|
|
});
|
|
}
|
|
}
|
|
function getRequestHeaders(event) {
|
|
const _headers = {};
|
|
for (const key in event.node.req.headers) {
|
|
const val = event.node.req.headers[key];
|
|
_headers[key] = Array.isArray(val) ? val.filter(Boolean).join(", ") : val;
|
|
}
|
|
return _headers;
|
|
}
|
|
const getHeaders = (/* unused pure expression or super */ null && (getRequestHeaders));
|
|
function getRequestHeader(event, name) {
|
|
const headers = getRequestHeaders(event);
|
|
const value = headers[name.toLowerCase()];
|
|
return value;
|
|
}
|
|
const getHeader = (/* unused pure expression or super */ null && (getRequestHeader));
|
|
function getRequestHost(event, opts = {}) {
|
|
if (opts.xForwardedHost) {
|
|
const xForwardedHost = event.node.req.headers["x-forwarded-host"];
|
|
if (xForwardedHost) {
|
|
return xForwardedHost;
|
|
}
|
|
}
|
|
return event.node.req.headers.host || "localhost";
|
|
}
|
|
function getRequestProtocol(event, opts = {}) {
|
|
if (opts.xForwardedProto !== false && event.node.req.headers["x-forwarded-proto"] === "https") {
|
|
return "https";
|
|
}
|
|
return event.node.req.connection.encrypted ? "https" : "http";
|
|
}
|
|
const DOUBLE_SLASH_RE = /[/\\]{2,}/g;
|
|
function getRequestPath(event) {
|
|
const path = (event.node.req.url || "/").replace(DOUBLE_SLASH_RE, "/");
|
|
return path;
|
|
}
|
|
function getRequestURL(event, opts = {}) {
|
|
const host = getRequestHost(event, opts);
|
|
const protocol = getRequestProtocol(event);
|
|
const path = getRequestPath(event);
|
|
return new URL(path, `${protocol}://${host}`);
|
|
}
|
|
|
|
const RawBodySymbol = Symbol.for("h3RawBody");
|
|
const ParsedBodySymbol = Symbol.for("h3ParsedBody");
|
|
const PayloadMethods$1 = ["PATCH", "POST", "PUT", "DELETE"];
|
|
function readRawBody(event, encoding = "utf8") {
|
|
assertMethod(event, PayloadMethods$1);
|
|
const _rawBody = event.node.req[RawBodySymbol] || event.node.req.body;
|
|
if (_rawBody) {
|
|
const promise2 = Promise.resolve(_rawBody).then((_resolved) => {
|
|
if (Buffer.isBuffer(_resolved)) {
|
|
return _resolved;
|
|
}
|
|
if (_resolved.constructor === Object) {
|
|
return Buffer.from(JSON.stringify(_resolved));
|
|
}
|
|
return Buffer.from(_resolved);
|
|
});
|
|
return encoding ? promise2.then((buff) => buff.toString(encoding)) : promise2;
|
|
}
|
|
if (!Number.parseInt(event.node.req.headers["content-length"] || "")) {
|
|
return Promise.resolve(void 0);
|
|
}
|
|
const promise = event.node.req[RawBodySymbol] = new Promise(
|
|
(resolve, reject) => {
|
|
const bodyData = [];
|
|
event.node.req.on("error", (err) => {
|
|
reject(err);
|
|
}).on("data", (chunk) => {
|
|
bodyData.push(chunk);
|
|
}).on("end", () => {
|
|
resolve(Buffer.concat(bodyData));
|
|
});
|
|
}
|
|
);
|
|
const result = encoding ? promise.then((buff) => buff.toString(encoding)) : promise;
|
|
return result;
|
|
}
|
|
async function readBody(event) {
|
|
if (ParsedBodySymbol in event.node.req) {
|
|
return event.node.req[ParsedBodySymbol];
|
|
}
|
|
const body = await readRawBody(event, "utf8");
|
|
if (event.node.req.headers["content-type"] === "application/x-www-form-urlencoded") {
|
|
const form = new URLSearchParams(body);
|
|
const parsedForm = /* @__PURE__ */ Object.create(null);
|
|
for (const [key, value] of form.entries()) {
|
|
if (key in parsedForm) {
|
|
if (!Array.isArray(parsedForm[key])) {
|
|
parsedForm[key] = [parsedForm[key]];
|
|
}
|
|
parsedForm[key].push(value);
|
|
} else {
|
|
parsedForm[key] = value;
|
|
}
|
|
}
|
|
return parsedForm;
|
|
}
|
|
const json = destr(body);
|
|
event.node.req[ParsedBodySymbol] = json;
|
|
return json;
|
|
}
|
|
async function readMultipartFormData(event) {
|
|
const contentType = getRequestHeader(event, "content-type");
|
|
if (!contentType || !contentType.startsWith("multipart/form-data")) {
|
|
return;
|
|
}
|
|
const boundary = contentType.match(/boundary=([^;]*)(;|$)/i)?.[1];
|
|
if (!boundary) {
|
|
return;
|
|
}
|
|
const body = await readRawBody(event, false);
|
|
if (!body) {
|
|
return;
|
|
}
|
|
return parse(body, boundary);
|
|
}
|
|
|
|
function handleCacheHeaders(event, opts) {
|
|
const cacheControls = ["public", ...opts.cacheControls || []];
|
|
let cacheMatched = false;
|
|
if (opts.maxAge !== void 0) {
|
|
cacheControls.push(`max-age=${+opts.maxAge}`, `s-maxage=${+opts.maxAge}`);
|
|
}
|
|
if (opts.modifiedTime) {
|
|
const modifiedTime = new Date(opts.modifiedTime);
|
|
const ifModifiedSince = event.node.req.headers["if-modified-since"];
|
|
event.node.res.setHeader("last-modified", modifiedTime.toUTCString());
|
|
if (ifModifiedSince && new Date(ifModifiedSince) >= opts.modifiedTime) {
|
|
cacheMatched = true;
|
|
}
|
|
}
|
|
if (opts.etag) {
|
|
event.node.res.setHeader("etag", opts.etag);
|
|
const ifNonMatch = event.node.req.headers["if-none-match"];
|
|
if (ifNonMatch === opts.etag) {
|
|
cacheMatched = true;
|
|
}
|
|
}
|
|
event.node.res.setHeader("cache-control", cacheControls.join(", "));
|
|
if (cacheMatched) {
|
|
event.node.res.statusCode = 304;
|
|
if (!event.handled) {
|
|
event.node.res.end();
|
|
}
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
const MIMES = {
|
|
html: "text/html",
|
|
json: "application/json"
|
|
};
|
|
|
|
function parseCookies(event) {
|
|
return parse$1(event.node.req.headers.cookie || "");
|
|
}
|
|
function getCookie(event, name) {
|
|
return parseCookies(event)[name];
|
|
}
|
|
function setCookie(event, name, value, serializeOptions) {
|
|
const cookieStr = serialize(name, value, {
|
|
path: "/",
|
|
...serializeOptions
|
|
});
|
|
let setCookies = event.node.res.getHeader("set-cookie");
|
|
if (!Array.isArray(setCookies)) {
|
|
setCookies = [setCookies];
|
|
}
|
|
setCookies = setCookies.filter((cookieValue) => {
|
|
return cookieValue && !cookieValue.startsWith(name + "=");
|
|
});
|
|
event.node.res.setHeader("set-cookie", [...setCookies, cookieStr]);
|
|
}
|
|
function deleteCookie(event, name, serializeOptions) {
|
|
setCookie(event, name, "", {
|
|
...serializeOptions,
|
|
maxAge: 0
|
|
});
|
|
}
|
|
function splitCookiesString(cookiesString) {
|
|
if (typeof cookiesString !== "string") {
|
|
return [];
|
|
}
|
|
const cookiesStrings = [];
|
|
let pos = 0;
|
|
let start;
|
|
let ch;
|
|
let lastComma;
|
|
let nextStart;
|
|
let cookiesSeparatorFound;
|
|
function skipWhitespace() {
|
|
while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) {
|
|
pos += 1;
|
|
}
|
|
return pos < cookiesString.length;
|
|
}
|
|
function notSpecialChar() {
|
|
ch = cookiesString.charAt(pos);
|
|
return ch !== "=" && ch !== ";" && ch !== ",";
|
|
}
|
|
while (pos < cookiesString.length) {
|
|
start = pos;
|
|
cookiesSeparatorFound = false;
|
|
while (skipWhitespace()) {
|
|
ch = cookiesString.charAt(pos);
|
|
if (ch === ",") {
|
|
lastComma = pos;
|
|
pos += 1;
|
|
skipWhitespace();
|
|
nextStart = pos;
|
|
while (pos < cookiesString.length && notSpecialChar()) {
|
|
pos += 1;
|
|
}
|
|
if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") {
|
|
cookiesSeparatorFound = true;
|
|
pos = nextStart;
|
|
cookiesStrings.push(cookiesString.slice(start, lastComma));
|
|
start = pos;
|
|
} else {
|
|
pos = lastComma + 1;
|
|
}
|
|
} else {
|
|
pos += 1;
|
|
}
|
|
}
|
|
if (!cookiesSeparatorFound || pos >= cookiesString.length) {
|
|
cookiesStrings.push(cookiesString.slice(start, cookiesString.length));
|
|
}
|
|
}
|
|
return cookiesStrings;
|
|
}
|
|
|
|
const DISALLOWED_STATUS_CHARS = /[^\u0009\u0020-\u007E]/g;
|
|
function sanitizeStatusMessage(statusMessage = "") {
|
|
return statusMessage.replace(DISALLOWED_STATUS_CHARS, "");
|
|
}
|
|
function sanitizeStatusCode(statusCode, defaultStatusCode = 200) {
|
|
if (!statusCode) {
|
|
return defaultStatusCode;
|
|
}
|
|
if (typeof statusCode === "string") {
|
|
statusCode = Number.parseInt(statusCode, 10);
|
|
}
|
|
if (statusCode < 100 || statusCode > 999) {
|
|
return defaultStatusCode;
|
|
}
|
|
return statusCode;
|
|
}
|
|
|
|
const PayloadMethods = /* @__PURE__ */ new Set(["PATCH", "POST", "PUT", "DELETE"]);
|
|
const ignoredHeaders = /* @__PURE__ */ new Set([
|
|
"transfer-encoding",
|
|
"connection",
|
|
"keep-alive",
|
|
"upgrade",
|
|
"expect",
|
|
"host"
|
|
]);
|
|
async function proxyRequest(event, target, opts = {}) {
|
|
const method = getMethod(event);
|
|
let body;
|
|
if (PayloadMethods.has(method)) {
|
|
body = await readRawBody(event).catch(() => void 0);
|
|
}
|
|
const headers = getProxyRequestHeaders(event);
|
|
if (opts.fetchOptions?.headers) {
|
|
Object.assign(headers, opts.fetchOptions.headers);
|
|
}
|
|
if (opts.headers) {
|
|
Object.assign(headers, opts.headers);
|
|
}
|
|
return sendProxy(event, target, {
|
|
...opts,
|
|
fetchOptions: {
|
|
headers,
|
|
method,
|
|
body,
|
|
...opts.fetchOptions
|
|
}
|
|
});
|
|
}
|
|
async function sendProxy(event, target, opts = {}) {
|
|
const response = await _getFetch(opts.fetch)(target, {
|
|
headers: opts.headers,
|
|
...opts.fetchOptions
|
|
});
|
|
event.node.res.statusCode = sanitizeStatusCode(
|
|
response.status,
|
|
event.node.res.statusCode
|
|
);
|
|
event.node.res.statusMessage = sanitizeStatusMessage(response.statusText);
|
|
const cookies = [];
|
|
for (const [key, value] of response.headers.entries()) {
|
|
if (key === "content-encoding") {
|
|
continue;
|
|
}
|
|
if (key === "content-length") {
|
|
continue;
|
|
}
|
|
if (key === "set-cookie") {
|
|
cookies.push(...splitCookiesString(value));
|
|
continue;
|
|
}
|
|
event.node.res.setHeader(key, value);
|
|
}
|
|
if (cookies.length > 0) {
|
|
event.node.res.setHeader(
|
|
"set-cookie",
|
|
cookies.map((cookie) => {
|
|
if (opts.cookieDomainRewrite) {
|
|
cookie = rewriteCookieProperty(
|
|
cookie,
|
|
opts.cookieDomainRewrite,
|
|
"domain"
|
|
);
|
|
}
|
|
if (opts.cookiePathRewrite) {
|
|
cookie = rewriteCookieProperty(
|
|
cookie,
|
|
opts.cookiePathRewrite,
|
|
"path"
|
|
);
|
|
}
|
|
return cookie;
|
|
})
|
|
);
|
|
}
|
|
if (opts.onResponse) {
|
|
await opts.onResponse(event, response);
|
|
}
|
|
if (response._data !== void 0) {
|
|
return response._data;
|
|
}
|
|
if (event.handled) {
|
|
return;
|
|
}
|
|
if (opts.sendStream === false) {
|
|
const data = new Uint8Array(await response.arrayBuffer());
|
|
return event.node.res.end(data);
|
|
}
|
|
for await (const chunk of response.body) {
|
|
event.node.res.write(chunk);
|
|
}
|
|
return event.node.res.end();
|
|
}
|
|
function getProxyRequestHeaders(event) {
|
|
const headers = /* @__PURE__ */ Object.create(null);
|
|
const reqHeaders = getRequestHeaders(event);
|
|
for (const name in reqHeaders) {
|
|
if (!ignoredHeaders.has(name)) {
|
|
headers[name] = reqHeaders[name];
|
|
}
|
|
}
|
|
return headers;
|
|
}
|
|
function fetchWithEvent(event, req, init, options) {
|
|
return _getFetch(options?.fetch)(req, {
|
|
...init,
|
|
context: init?.context || event.context,
|
|
headers: {
|
|
...getProxyRequestHeaders(event),
|
|
...init?.headers
|
|
}
|
|
});
|
|
}
|
|
function _getFetch(_fetch) {
|
|
if (_fetch) {
|
|
return _fetch;
|
|
}
|
|
if (globalThis.fetch) {
|
|
return globalThis.fetch;
|
|
}
|
|
throw new Error(
|
|
"fetch is not available. Try importing `node-fetch-native/polyfill` for Node.js."
|
|
);
|
|
}
|
|
function rewriteCookieProperty(header, map, property) {
|
|
const _map = typeof map === "string" ? { "*": map } : map;
|
|
return header.replace(
|
|
new RegExp(`(;\\s*${property}=)([^;]+)`, "gi"),
|
|
(match, prefix, previousValue) => {
|
|
let newValue;
|
|
if (previousValue in _map) {
|
|
newValue = _map[previousValue];
|
|
} else if ("*" in _map) {
|
|
newValue = _map["*"];
|
|
} else {
|
|
return match;
|
|
}
|
|
return newValue ? prefix + newValue : "";
|
|
}
|
|
);
|
|
}
|
|
|
|
const defer = typeof setImmediate === "undefined" ? (fn) => fn() : setImmediate;
|
|
function send(event, data, type) {
|
|
if (type) {
|
|
defaultContentType(event, type);
|
|
}
|
|
return new Promise((resolve) => {
|
|
defer(() => {
|
|
if (!event.handled) {
|
|
event.node.res.end(data);
|
|
}
|
|
resolve();
|
|
});
|
|
});
|
|
}
|
|
function sendNoContent(event, code = 204) {
|
|
event.node.res.statusCode = sanitizeStatusCode(code, 204);
|
|
if (event.node.res.statusCode === 204) {
|
|
event.node.res.removeHeader("content-length");
|
|
}
|
|
if (!event.handled) {
|
|
event.node.res.end();
|
|
}
|
|
}
|
|
function setResponseStatus(event, code, text) {
|
|
if (code) {
|
|
event.node.res.statusCode = sanitizeStatusCode(
|
|
code,
|
|
event.node.res.statusCode
|
|
);
|
|
}
|
|
if (text) {
|
|
event.node.res.statusMessage = sanitizeStatusMessage(text);
|
|
}
|
|
}
|
|
function getResponseStatus(event) {
|
|
return event.node.res.statusCode;
|
|
}
|
|
function getResponseStatusText(event) {
|
|
return event.node.res.statusMessage;
|
|
}
|
|
function defaultContentType(event, type) {
|
|
if (type && !event.node.res.getHeader("content-type")) {
|
|
event.node.res.setHeader("content-type", type);
|
|
}
|
|
}
|
|
function sendRedirect(event, location, code = 302) {
|
|
event.node.res.statusCode = sanitizeStatusCode(
|
|
code,
|
|
event.node.res.statusCode
|
|
);
|
|
event.node.res.setHeader("location", location);
|
|
const encodedLoc = location.replace(/"/g, "%22");
|
|
const html = `<!DOCTYPE html><html><head><meta http-equiv="refresh" content="0; url=${encodedLoc}"></head></html>`;
|
|
return send(event, html, MIMES.html);
|
|
}
|
|
function getResponseHeaders(event) {
|
|
return event.node.res.getHeaders();
|
|
}
|
|
function getResponseHeader(event, name) {
|
|
return event.node.res.getHeader(name);
|
|
}
|
|
function setResponseHeaders(event, headers) {
|
|
for (const [name, value] of Object.entries(headers)) {
|
|
event.node.res.setHeader(name, value);
|
|
}
|
|
}
|
|
const setHeaders = (/* unused pure expression or super */ null && (setResponseHeaders));
|
|
function setResponseHeader(event, name, value) {
|
|
event.node.res.setHeader(name, value);
|
|
}
|
|
const setHeader = (/* unused pure expression or super */ null && (setResponseHeader));
|
|
function appendResponseHeaders(event, headers) {
|
|
for (const [name, value] of Object.entries(headers)) {
|
|
appendResponseHeader(event, name, value);
|
|
}
|
|
}
|
|
const appendHeaders = (/* unused pure expression or super */ null && (appendResponseHeaders));
|
|
function appendResponseHeader(event, name, value) {
|
|
let current = event.node.res.getHeader(name);
|
|
if (!current) {
|
|
event.node.res.setHeader(name, value);
|
|
return;
|
|
}
|
|
if (!Array.isArray(current)) {
|
|
current = [current.toString()];
|
|
}
|
|
event.node.res.setHeader(name, [...current, value]);
|
|
}
|
|
const appendHeader = (/* unused pure expression or super */ null && (appendResponseHeader));
|
|
function isStream(data) {
|
|
return data && typeof data === "object" && typeof data.pipe === "function" && typeof data.on === "function";
|
|
}
|
|
function sendStream(event, data) {
|
|
return new Promise((resolve, reject) => {
|
|
data.pipe(event.node.res);
|
|
data.on("end", () => resolve());
|
|
data.on("error", (error) => reject(createError(error)));
|
|
});
|
|
}
|
|
const noop = () => {
|
|
};
|
|
function writeEarlyHints(event, hints, cb = noop) {
|
|
if (!event.node.res.socket) {
|
|
cb();
|
|
return;
|
|
}
|
|
if (typeof hints === "string" || Array.isArray(hints)) {
|
|
hints = { link: hints };
|
|
}
|
|
if (hints.link) {
|
|
hints.link = Array.isArray(hints.link) ? hints.link : hints.link.split(",");
|
|
}
|
|
const headers = Object.entries(hints).map(
|
|
(e) => [e[0].toLowerCase(), e[1]]
|
|
);
|
|
if (headers.length === 0) {
|
|
cb();
|
|
return;
|
|
}
|
|
let hint = "HTTP/1.1 103 Early Hints";
|
|
if (hints.link) {
|
|
hint += `\r
|
|
Link: ${hints.link.join(", ")}`;
|
|
}
|
|
for (const [header, value] of headers) {
|
|
if (header === "link") {
|
|
continue;
|
|
}
|
|
hint += `\r
|
|
${header}: ${value}`;
|
|
}
|
|
if (event.node.res.socket) {
|
|
event.node.res.socket.write(
|
|
`${hint}\r
|
|
\r
|
|
`,
|
|
"utf8",
|
|
cb
|
|
);
|
|
} else {
|
|
cb();
|
|
}
|
|
}
|
|
|
|
const DEFAULT_NAME = "h3";
|
|
const DEFAULT_COOKIE = {
|
|
path: "/",
|
|
secure: true,
|
|
httpOnly: true
|
|
};
|
|
async function useSession(event, config) {
|
|
const sessionName = config.name || DEFAULT_NAME;
|
|
await getSession(event, config);
|
|
const sessionManager = {
|
|
get id() {
|
|
return event.context.sessions?.[sessionName]?.id;
|
|
},
|
|
get data() {
|
|
return event.context.sessions?.[sessionName]?.data || {};
|
|
},
|
|
update: async (update) => {
|
|
await updateSession(event, config, update);
|
|
return sessionManager;
|
|
},
|
|
clear: async () => {
|
|
await clearSession(event, config);
|
|
return sessionManager;
|
|
}
|
|
};
|
|
return sessionManager;
|
|
}
|
|
async function getSession(event, config) {
|
|
const sessionName = config.name || DEFAULT_NAME;
|
|
if (!event.context.sessions) {
|
|
event.context.sessions = /* @__PURE__ */ Object.create(null);
|
|
}
|
|
if (event.context.sessions[sessionName]) {
|
|
return event.context.sessions[sessionName];
|
|
}
|
|
const session = {
|
|
id: "",
|
|
createdAt: 0,
|
|
data: /* @__PURE__ */ Object.create(null)
|
|
};
|
|
event.context.sessions[sessionName] = session;
|
|
let sealedSession;
|
|
if (config.sessionHeader !== false) {
|
|
const headerName = typeof config.sessionHeader === "string" ? config.sessionHeader.toLowerCase() : `x-${sessionName.toLowerCase()}-session`;
|
|
const headerValue = event.node.req.headers[headerName];
|
|
if (typeof headerValue === "string") {
|
|
sealedSession = headerValue;
|
|
}
|
|
}
|
|
if (!sealedSession) {
|
|
sealedSession = getCookie(event, sessionName);
|
|
}
|
|
if (sealedSession) {
|
|
const unsealed = await unsealSession(event, config, sealedSession).catch(
|
|
() => {
|
|
}
|
|
);
|
|
Object.assign(session, unsealed);
|
|
}
|
|
if (!session.id) {
|
|
session.id = config.generateId?.() ?? (config.crypto || crypto).randomUUID();
|
|
session.createdAt = Date.now();
|
|
await updateSession(event, config);
|
|
}
|
|
return session;
|
|
}
|
|
async function updateSession(event, config, update) {
|
|
const sessionName = config.name || DEFAULT_NAME;
|
|
const session = event.context.sessions?.[sessionName] || await getSession(event, config);
|
|
if (typeof update === "function") {
|
|
update = update(session.data);
|
|
}
|
|
if (update) {
|
|
Object.assign(session.data, update);
|
|
}
|
|
if (config.cookie !== false) {
|
|
const sealed = await sealSession(event, config);
|
|
setCookie(event, sessionName, sealed, {
|
|
...DEFAULT_COOKIE,
|
|
expires: config.maxAge ? new Date(session.createdAt + config.maxAge * 1e3) : void 0,
|
|
...config.cookie
|
|
});
|
|
}
|
|
return session;
|
|
}
|
|
async function sealSession(event, config) {
|
|
const sessionName = config.name || DEFAULT_NAME;
|
|
const session = event.context.sessions?.[sessionName] || await getSession(event, config);
|
|
const sealed = await seal(config.crypto || crypto, session, config.password, {
|
|
...defaults,
|
|
ttl: config.maxAge ? config.maxAge * 1e3 : 0,
|
|
...config.seal
|
|
});
|
|
return sealed;
|
|
}
|
|
async function unsealSession(_event, config, sealed) {
|
|
const unsealed = await unseal(
|
|
config.crypto || crypto,
|
|
sealed,
|
|
config.password,
|
|
{
|
|
...defaults,
|
|
ttl: config.maxAge ? config.maxAge * 1e3 : 0,
|
|
...config.seal
|
|
}
|
|
);
|
|
if (config.maxAge) {
|
|
const age = Date.now() - (unsealed.createdAt || Number.NEGATIVE_INFINITY);
|
|
if (age > config.maxAge * 1e3) {
|
|
throw new Error("Session expired!");
|
|
}
|
|
}
|
|
return unsealed;
|
|
}
|
|
async function clearSession(event, config) {
|
|
const sessionName = config.name || DEFAULT_NAME;
|
|
if (event.context.sessions?.[sessionName]) {
|
|
delete event.context.sessions[sessionName];
|
|
}
|
|
await setCookie(event, sessionName, "", {
|
|
...DEFAULT_COOKIE,
|
|
...config.cookie
|
|
});
|
|
}
|
|
|
|
function resolveCorsOptions(options = {}) {
|
|
const defaultOptions = {
|
|
origin: "*",
|
|
methods: "*",
|
|
allowHeaders: "*",
|
|
exposeHeaders: "*",
|
|
credentials: false,
|
|
maxAge: false,
|
|
preflight: {
|
|
statusCode: 204
|
|
}
|
|
};
|
|
return defu(options, defaultOptions);
|
|
}
|
|
function isPreflightRequest(event) {
|
|
const method = getMethod(event);
|
|
const origin = getRequestHeader(event, "origin");
|
|
const accessControlRequestMethod = getRequestHeader(
|
|
event,
|
|
"access-control-request-method"
|
|
);
|
|
return method === "OPTIONS" && !!origin && !!accessControlRequestMethod;
|
|
}
|
|
function isCorsOriginAllowed(origin, options) {
|
|
const { origin: originOption } = options;
|
|
if (!origin || !originOption || originOption === "*" || originOption === "null") {
|
|
return true;
|
|
}
|
|
if (Array.isArray(originOption)) {
|
|
return originOption.some((_origin) => {
|
|
if (_origin instanceof RegExp) {
|
|
return _origin.test(origin);
|
|
}
|
|
return origin === _origin;
|
|
});
|
|
}
|
|
return originOption(origin);
|
|
}
|
|
function createOriginHeaders(event, options) {
|
|
const { origin: originOption } = options;
|
|
const origin = getRequestHeader(event, "origin");
|
|
if (!origin || !originOption || originOption === "*") {
|
|
return { "access-control-allow-origin": "*" };
|
|
}
|
|
if (typeof originOption === "string") {
|
|
return { "access-control-allow-origin": originOption, vary: "origin" };
|
|
}
|
|
return isCorsOriginAllowed(origin, options) ? { "access-control-allow-origin": origin, vary: "origin" } : {};
|
|
}
|
|
function createMethodsHeaders(options) {
|
|
const { methods } = options;
|
|
if (!methods) {
|
|
return {};
|
|
}
|
|
if (methods === "*") {
|
|
return { "access-control-allow-methods": "*" };
|
|
}
|
|
return methods.length > 0 ? { "access-control-allow-methods": methods.join(",") } : {};
|
|
}
|
|
function createCredentialsHeaders(options) {
|
|
const { credentials } = options;
|
|
if (credentials) {
|
|
return { "access-control-allow-credentials": "true" };
|
|
}
|
|
return {};
|
|
}
|
|
function createAllowHeaderHeaders(event, options) {
|
|
const { allowHeaders } = options;
|
|
if (!allowHeaders || allowHeaders === "*" || allowHeaders.length === 0) {
|
|
const header = getRequestHeader(event, "access-control-request-headers");
|
|
return header ? {
|
|
"access-control-allow-headers": header,
|
|
vary: "access-control-request-headers"
|
|
} : {};
|
|
}
|
|
return {
|
|
"access-control-allow-headers": allowHeaders.join(","),
|
|
vary: "access-control-request-headers"
|
|
};
|
|
}
|
|
function createExposeHeaders(options) {
|
|
const { exposeHeaders } = options;
|
|
if (!exposeHeaders) {
|
|
return {};
|
|
}
|
|
if (exposeHeaders === "*") {
|
|
return { "access-control-expose-headers": exposeHeaders };
|
|
}
|
|
return { "access-control-expose-headers": exposeHeaders.join(",") };
|
|
}
|
|
function appendCorsPreflightHeaders(event, options) {
|
|
appendHeaders(event, createOriginHeaders(event, options));
|
|
appendHeaders(event, createCredentialsHeaders(options));
|
|
appendHeaders(event, createExposeHeaders(options));
|
|
appendHeaders(event, createMethodsHeaders(options));
|
|
appendHeaders(event, createAllowHeaderHeaders(event, options));
|
|
}
|
|
function appendCorsHeaders(event, options) {
|
|
appendHeaders(event, createOriginHeaders(event, options));
|
|
appendHeaders(event, createCredentialsHeaders(options));
|
|
appendHeaders(event, createExposeHeaders(options));
|
|
}
|
|
|
|
function handleCors(event, options) {
|
|
const _options = resolveCorsOptions(options);
|
|
if (isPreflightRequest(event)) {
|
|
appendCorsPreflightHeaders(event, options);
|
|
sendNoContent(event, _options.preflight.statusCode);
|
|
return true;
|
|
}
|
|
appendCorsHeaders(event, options);
|
|
return false;
|
|
}
|
|
|
|
class H3Headers {
|
|
constructor(init) {
|
|
if (!init) {
|
|
this._headers = {};
|
|
} else if (Array.isArray(init)) {
|
|
this._headers = Object.fromEntries(
|
|
init.map(([key, value]) => [key.toLowerCase(), value])
|
|
);
|
|
} else if (init && "append" in init) {
|
|
this._headers = Object.fromEntries(init.entries());
|
|
} else {
|
|
this._headers = Object.fromEntries(
|
|
Object.entries(init).map(([key, value]) => [key.toLowerCase(), value])
|
|
);
|
|
}
|
|
}
|
|
[Symbol.iterator]() {
|
|
return this.entries();
|
|
}
|
|
entries() {
|
|
throw Object.entries(this._headers)[Symbol.iterator]();
|
|
}
|
|
keys() {
|
|
return Object.keys(this._headers)[Symbol.iterator]();
|
|
}
|
|
values() {
|
|
throw Object.values(this._headers)[Symbol.iterator]();
|
|
}
|
|
append(name, value) {
|
|
const _name = name.toLowerCase();
|
|
this.set(_name, [this.get(_name), value].filter(Boolean).join(", "));
|
|
}
|
|
delete(name) {
|
|
delete this._headers[name.toLowerCase()];
|
|
}
|
|
get(name) {
|
|
return this._headers[name.toLowerCase()];
|
|
}
|
|
has(name) {
|
|
return name.toLowerCase() in this._headers;
|
|
}
|
|
set(name, value) {
|
|
this._headers[name.toLowerCase()] = String(value);
|
|
}
|
|
forEach(callbackfn) {
|
|
for (const [key, value] of Object.entries(this._headers)) {
|
|
callbackfn(value, key, this);
|
|
}
|
|
}
|
|
}
|
|
|
|
class H3Response {
|
|
constructor(body = null, init = {}) {
|
|
// TODO: yet to implement
|
|
this.body = null;
|
|
this.type = "default";
|
|
this.bodyUsed = false;
|
|
this.headers = new H3Headers(init.headers);
|
|
this.status = init.status ?? 200;
|
|
this.statusText = init.statusText || "";
|
|
this.redirected = !!init.status && [301, 302, 307, 308].includes(init.status);
|
|
this._body = body;
|
|
this.url = "";
|
|
this.ok = this.status < 300 && this.status > 199;
|
|
}
|
|
clone() {
|
|
return new H3Response(this.body, {
|
|
headers: this.headers,
|
|
status: this.status,
|
|
statusText: this.statusText
|
|
});
|
|
}
|
|
arrayBuffer() {
|
|
return Promise.resolve(this._body);
|
|
}
|
|
blob() {
|
|
return Promise.resolve(this._body);
|
|
}
|
|
formData() {
|
|
return Promise.resolve(this._body);
|
|
}
|
|
json() {
|
|
return Promise.resolve(this._body);
|
|
}
|
|
text() {
|
|
return Promise.resolve(this._body);
|
|
}
|
|
}
|
|
|
|
class H3Event {
|
|
constructor(req, res) {
|
|
this["__is_event__"] = true;
|
|
this._handled = false;
|
|
this.context = {};
|
|
this.node = { req, res };
|
|
}
|
|
get path() {
|
|
return getRequestPath(this);
|
|
}
|
|
get handled() {
|
|
return this._handled || this.node.res.writableEnded || this.node.res.headersSent;
|
|
}
|
|
/** @deprecated Please use `event.node.req` instead. **/
|
|
get req() {
|
|
return this.node.req;
|
|
}
|
|
/** @deprecated Please use `event.node.res` instead. **/
|
|
get res() {
|
|
return this.node.res;
|
|
}
|
|
// Implementation of FetchEvent
|
|
respondWith(r) {
|
|
Promise.resolve(r).then((_response) => {
|
|
if (this.handled) {
|
|
return;
|
|
}
|
|
const response = _response instanceof H3Response ? _response : new H3Response(_response);
|
|
for (const [key, value] of response.headers.entries()) {
|
|
this.node.res.setHeader(key, value);
|
|
}
|
|
if (response.status) {
|
|
this.node.res.statusCode = sanitizeStatusCode(
|
|
response.status,
|
|
this.node.res.statusCode
|
|
);
|
|
}
|
|
if (response.statusText) {
|
|
this.node.res.statusMessage = sanitizeStatusMessage(
|
|
response.statusText
|
|
);
|
|
}
|
|
if (response.redirected) {
|
|
this.node.res.setHeader("location", response.url);
|
|
}
|
|
if (!response._body) {
|
|
return this.node.res.end();
|
|
}
|
|
if (typeof response._body === "string" || "buffer" in response._body || "byteLength" in response._body) {
|
|
return this.node.res.end(response._body);
|
|
}
|
|
if (!response.headers.has("content-type")) {
|
|
response.headers.set("content-type", MIMES.json);
|
|
}
|
|
this.node.res.end(JSON.stringify(response._body));
|
|
});
|
|
}
|
|
}
|
|
function isEvent(input) {
|
|
return "__is_event__" in input;
|
|
}
|
|
function createEvent(req, res) {
|
|
return new H3Event(req, res);
|
|
}
|
|
|
|
function defineEventHandler(handler) {
|
|
handler.__is_handler__ = true;
|
|
return handler;
|
|
}
|
|
const eventHandler = defineEventHandler;
|
|
function isEventHandler(input) {
|
|
return "__is_handler__" in input;
|
|
}
|
|
function toEventHandler(input, _, _route) {
|
|
if (!isEventHandler(input)) {
|
|
console.warn(
|
|
"[h3] Implicit event handler conversion is deprecated. Use `eventHandler()` or `fromNodeMiddleware()` to define event handlers.",
|
|
_route && _route !== "/" ? `
|
|
Route: ${_route}` : "",
|
|
`
|
|
Handler: ${input}`
|
|
);
|
|
}
|
|
return input;
|
|
}
|
|
function dynamicEventHandler(initial) {
|
|
let current = initial;
|
|
const wrapper = eventHandler((event) => {
|
|
if (current) {
|
|
return current(event);
|
|
}
|
|
});
|
|
wrapper.set = (handler) => {
|
|
current = handler;
|
|
};
|
|
return wrapper;
|
|
}
|
|
function defineLazyEventHandler(factory) {
|
|
let _promise;
|
|
let _resolved;
|
|
const resolveHandler = () => {
|
|
if (_resolved) {
|
|
return Promise.resolve(_resolved);
|
|
}
|
|
if (!_promise) {
|
|
_promise = Promise.resolve(factory()).then((r) => {
|
|
const handler = r.default || r;
|
|
if (typeof handler !== "function") {
|
|
throw new TypeError(
|
|
"Invalid lazy handler result. It should be a function:",
|
|
handler
|
|
);
|
|
}
|
|
_resolved = toEventHandler(r.default || r);
|
|
return _resolved;
|
|
});
|
|
}
|
|
return _promise;
|
|
};
|
|
return eventHandler((event) => {
|
|
if (_resolved) {
|
|
return _resolved(event);
|
|
}
|
|
return resolveHandler().then((handler) => handler(event));
|
|
});
|
|
}
|
|
const lazyEventHandler = defineLazyEventHandler;
|
|
|
|
function createApp(options = {}) {
|
|
const stack = [];
|
|
const handler = createAppEventHandler(stack, options);
|
|
const app = {
|
|
// @ts-ignore
|
|
use: (arg1, arg2, arg3) => use(app, arg1, arg2, arg3),
|
|
handler,
|
|
stack,
|
|
options
|
|
};
|
|
return app;
|
|
}
|
|
function use(app, arg1, arg2, arg3) {
|
|
if (Array.isArray(arg1)) {
|
|
for (const i of arg1) {
|
|
use(app, i, arg2, arg3);
|
|
}
|
|
} else if (Array.isArray(arg2)) {
|
|
for (const i of arg2) {
|
|
use(app, arg1, i, arg3);
|
|
}
|
|
} else if (typeof arg1 === "string") {
|
|
app.stack.push(
|
|
normalizeLayer({ ...arg3, route: arg1, handler: arg2 })
|
|
);
|
|
} else if (typeof arg1 === "function") {
|
|
app.stack.push(
|
|
normalizeLayer({ ...arg2, route: "/", handler: arg1 })
|
|
);
|
|
} else {
|
|
app.stack.push(normalizeLayer({ ...arg1 }));
|
|
}
|
|
return app;
|
|
}
|
|
function createAppEventHandler(stack, options) {
|
|
const spacing = options.debug ? 2 : void 0;
|
|
return eventHandler(async (event) => {
|
|
event.node.req.originalUrl = event.node.req.originalUrl || event.node.req.url || "/";
|
|
const reqUrl = event.node.req.url || "/";
|
|
for (const layer of stack) {
|
|
if (layer.route.length > 1) {
|
|
if (!reqUrl.startsWith(layer.route)) {
|
|
continue;
|
|
}
|
|
event.node.req.url = reqUrl.slice(layer.route.length) || "/";
|
|
} else {
|
|
event.node.req.url = reqUrl;
|
|
}
|
|
if (layer.match && !layer.match(event.node.req.url, event)) {
|
|
continue;
|
|
}
|
|
const val = await layer.handler(event);
|
|
if (event.handled) {
|
|
return;
|
|
}
|
|
const type = typeof val;
|
|
if (type === "string") {
|
|
return send(event, val, MIMES.html);
|
|
} else if (isStream(val)) {
|
|
return sendStream(event, val);
|
|
} else if (val === null) {
|
|
event.node.res.statusCode = 204;
|
|
return send(event);
|
|
} else if (type === "object" || type === "boolean" || type === "number") {
|
|
if (val.buffer) {
|
|
return send(event, val);
|
|
} else if (val instanceof Error) {
|
|
throw createError(val);
|
|
} else {
|
|
return send(
|
|
event,
|
|
JSON.stringify(val, void 0, spacing),
|
|
MIMES.json
|
|
);
|
|
}
|
|
}
|
|
}
|
|
if (!event.handled) {
|
|
throw createError({
|
|
statusCode: 404,
|
|
statusMessage: `Cannot find any path matching ${event.node.req.url || "/"}.`
|
|
});
|
|
}
|
|
});
|
|
}
|
|
function normalizeLayer(input) {
|
|
let handler = input.handler;
|
|
if (handler.handler) {
|
|
handler = handler.handler;
|
|
}
|
|
if (input.lazy) {
|
|
handler = lazyEventHandler(handler);
|
|
} else if (!isEventHandler(handler)) {
|
|
handler = toEventHandler(handler, void 0, input.route);
|
|
}
|
|
return {
|
|
route: dist_withoutTrailingSlash(input.route),
|
|
match: input.match,
|
|
handler
|
|
};
|
|
}
|
|
|
|
const defineNodeListener = (handler) => handler;
|
|
const defineNodeMiddleware = (middleware) => middleware;
|
|
function fromNodeMiddleware(handler) {
|
|
if (isEventHandler(handler)) {
|
|
return handler;
|
|
}
|
|
if (typeof handler !== "function") {
|
|
throw new TypeError(
|
|
"Invalid handler. It should be a function:",
|
|
handler
|
|
);
|
|
}
|
|
return eventHandler((event) => {
|
|
return callNodeListener(
|
|
handler,
|
|
event.node.req,
|
|
event.node.res
|
|
);
|
|
});
|
|
}
|
|
function toNodeListener(app) {
|
|
const toNodeHandle = async function(req, res) {
|
|
const event = createEvent(req, res);
|
|
try {
|
|
await app.handler(event);
|
|
} catch (_error) {
|
|
const error = createError(_error);
|
|
if (!isError(_error)) {
|
|
error.unhandled = true;
|
|
}
|
|
if (app.options.onError) {
|
|
await app.options.onError(error, event);
|
|
} else {
|
|
if (error.unhandled || error.fatal) {
|
|
console.error("[h3]", error.fatal ? "[fatal]" : "[unhandled]", error);
|
|
}
|
|
await sendError(event, error, !!app.options.debug);
|
|
}
|
|
}
|
|
};
|
|
return toNodeHandle;
|
|
}
|
|
function promisifyNodeListener(handler) {
|
|
return function(req, res) {
|
|
return callNodeListener(handler, req, res);
|
|
};
|
|
}
|
|
function callNodeListener(handler, req, res) {
|
|
const isMiddleware = handler.length > 2;
|
|
return new Promise((resolve, reject) => {
|
|
const next = (err) => {
|
|
if (isMiddleware) {
|
|
res.off("close", next);
|
|
res.off("error", next);
|
|
}
|
|
return err ? reject(createError(err)) : resolve(void 0);
|
|
};
|
|
try {
|
|
const returned = handler(req, res, next);
|
|
if (isMiddleware && returned === void 0) {
|
|
res.once("close", next);
|
|
res.once("error", next);
|
|
} else {
|
|
resolve(returned);
|
|
}
|
|
} catch (error) {
|
|
next(error);
|
|
}
|
|
});
|
|
}
|
|
|
|
const RouterMethods = [
|
|
"connect",
|
|
"delete",
|
|
"get",
|
|
"head",
|
|
"options",
|
|
"post",
|
|
"put",
|
|
"trace",
|
|
"patch"
|
|
];
|
|
function dist_createRouter(opts = {}) {
|
|
const _router = createRouter({});
|
|
const routes = {};
|
|
const router = {};
|
|
const addRoute = (path, handler, method) => {
|
|
let route = routes[path];
|
|
if (!route) {
|
|
routes[path] = route = { handlers: {} };
|
|
_router.insert(path, route);
|
|
}
|
|
if (Array.isArray(method)) {
|
|
for (const m of method) {
|
|
addRoute(path, handler, m);
|
|
}
|
|
} else {
|
|
route.handlers[method] = toEventHandler(handler, void 0, path);
|
|
}
|
|
return router;
|
|
};
|
|
router.use = router.add = (path, handler, method) => addRoute(path, handler, method || "all");
|
|
for (const method of RouterMethods) {
|
|
router[method] = (path, handle) => router.add(path, handle, method);
|
|
}
|
|
router.handler = eventHandler((event) => {
|
|
let path = event.node.req.url || "/";
|
|
const qIndex = path.indexOf("?");
|
|
if (qIndex !== -1) {
|
|
path = path.slice(0, Math.max(0, qIndex));
|
|
}
|
|
const matched = _router.lookup(path);
|
|
if (!matched || !matched.handlers) {
|
|
if (opts.preemptive || opts.preemtive) {
|
|
throw createError({
|
|
statusCode: 404,
|
|
name: "Not Found",
|
|
statusMessage: `Cannot find any route matching ${event.node.req.url || "/"}.`
|
|
});
|
|
} else {
|
|
return;
|
|
}
|
|
}
|
|
const method = (event.node.req.method || "get").toLowerCase();
|
|
const handler = matched.handlers[method] || matched.handlers.all;
|
|
if (!handler) {
|
|
if (opts.preemptive || opts.preemtive) {
|
|
throw createError({
|
|
statusCode: 405,
|
|
name: "Method Not Allowed",
|
|
statusMessage: `Method ${method} is not allowed on this route.`
|
|
});
|
|
} else {
|
|
return;
|
|
}
|
|
}
|
|
const params = matched.params || {};
|
|
event.context.params = params;
|
|
return Promise.resolve(handler(event)).then((res) => {
|
|
if (res === void 0 && (opts.preemptive || opts.preemtive)) {
|
|
setResponseStatus(event, 204);
|
|
return "";
|
|
}
|
|
return res;
|
|
});
|
|
});
|
|
return router;
|
|
}
|
|
|
|
|
|
|
|
;// CONCATENATED MODULE: external "node:http"
|
|
const external_node_http_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:http");
|
|
;// CONCATENATED MODULE: external "node:https"
|
|
const external_node_https_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:https");
|
|
// EXTERNAL MODULE: external "node:util"
|
|
var external_node_util_ = __nccwpck_require__(7261);
|
|
;// CONCATENATED MODULE: external "node:fs"
|
|
const external_node_fs_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:fs");
|
|
;// CONCATENATED MODULE: external "node:os"
|
|
const external_node_os_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:os");
|
|
;// CONCATENATED MODULE: external "tty"
|
|
const external_tty_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("tty");
|
|
var external_tty_namespaceObject_0 = /*#__PURE__*/__nccwpck_require__.t(external_tty_namespaceObject, 2);
|
|
;// CONCATENATED MODULE: ./node_modules/colorette/index.js
|
|
|
|
|
|
const {
|
|
env = {},
|
|
argv = [],
|
|
platform = "",
|
|
} = typeof process === "undefined" ? {} : process
|
|
|
|
const isDisabled = "NO_COLOR" in env || argv.includes("--no-color")
|
|
const isForced = "FORCE_COLOR" in env || argv.includes("--color")
|
|
const isWindows = platform === "win32"
|
|
const isDumbTerminal = env.TERM === "dumb"
|
|
|
|
const isCompatibleTerminal =
|
|
external_tty_namespaceObject_0 && external_tty_namespaceObject.isatty && external_tty_namespaceObject.isatty(1) && env.TERM && !isDumbTerminal
|
|
|
|
const isCI =
|
|
"CI" in env &&
|
|
("GITHUB_ACTIONS" in env || "GITLAB_CI" in env || "CIRCLECI" in env)
|
|
|
|
const isColorSupported =
|
|
!isDisabled &&
|
|
(isForced || (isWindows && !isDumbTerminal) || isCompatibleTerminal || isCI)
|
|
|
|
const replaceClose = (
|
|
index,
|
|
string,
|
|
close,
|
|
replace,
|
|
head = string.substring(0, index) + replace,
|
|
tail = string.substring(index + close.length),
|
|
next = tail.indexOf(close)
|
|
) => head + (next < 0 ? tail : replaceClose(next, tail, close, replace))
|
|
|
|
const clearBleed = (index, string, open, close, replace) =>
|
|
index < 0
|
|
? open + string + close
|
|
: open + replaceClose(index, string, close, replace) + close
|
|
|
|
const filterEmpty =
|
|
(open, close, replace = open, at = open.length + 1) =>
|
|
(string) =>
|
|
string || !(string === "" || string === undefined)
|
|
? clearBleed(
|
|
("" + string).indexOf(close, at),
|
|
string,
|
|
open,
|
|
close,
|
|
replace
|
|
)
|
|
: ""
|
|
|
|
const init = (open, close, replace) =>
|
|
filterEmpty(`\x1b[${open}m`, `\x1b[${close}m`, replace)
|
|
|
|
const colors = {
|
|
reset: init(0, 0),
|
|
bold: init(1, 22, "\x1b[22m\x1b[1m"),
|
|
dim: init(2, 22, "\x1b[22m\x1b[2m"),
|
|
italic: init(3, 23),
|
|
underline: init(4, 24),
|
|
inverse: init(7, 27),
|
|
hidden: init(8, 28),
|
|
strikethrough: init(9, 29),
|
|
black: init(30, 39),
|
|
red: init(31, 39),
|
|
green: init(32, 39),
|
|
yellow: init(33, 39),
|
|
blue: init(34, 39),
|
|
magenta: init(35, 39),
|
|
cyan: init(36, 39),
|
|
white: init(37, 39),
|
|
gray: init(90, 39),
|
|
bgBlack: init(40, 49),
|
|
bgRed: init(41, 49),
|
|
bgGreen: init(42, 49),
|
|
bgYellow: init(43, 49),
|
|
bgBlue: init(44, 49),
|
|
bgMagenta: init(45, 49),
|
|
bgCyan: init(46, 49),
|
|
bgWhite: init(47, 49),
|
|
blackBright: init(90, 39),
|
|
redBright: init(91, 39),
|
|
greenBright: init(92, 39),
|
|
yellowBright: init(93, 39),
|
|
blueBright: init(94, 39),
|
|
magentaBright: init(95, 39),
|
|
cyanBright: init(96, 39),
|
|
whiteBright: init(97, 39),
|
|
bgBlackBright: init(100, 49),
|
|
bgRedBright: init(101, 49),
|
|
bgGreenBright: init(102, 49),
|
|
bgYellowBright: init(103, 49),
|
|
bgBlueBright: init(104, 49),
|
|
bgMagentaBright: init(105, 49),
|
|
bgCyanBright: init(106, 49),
|
|
bgWhiteBright: init(107, 49),
|
|
}
|
|
|
|
const createColors = ({ useColor = isColorSupported } = {}) =>
|
|
useColor
|
|
? colors
|
|
: Object.keys(colors).reduce(
|
|
(colors, key) => ({ ...colors, [key]: String }),
|
|
{}
|
|
)
|
|
|
|
const {
|
|
reset: colorette_reset,
|
|
bold,
|
|
dim,
|
|
italic,
|
|
underline,
|
|
inverse,
|
|
hidden: colorette_hidden,
|
|
strikethrough,
|
|
black,
|
|
red,
|
|
green,
|
|
yellow,
|
|
blue,
|
|
magenta,
|
|
cyan,
|
|
white,
|
|
gray,
|
|
bgBlack,
|
|
bgRed,
|
|
bgGreen,
|
|
bgYellow,
|
|
bgBlue,
|
|
bgMagenta,
|
|
bgCyan,
|
|
bgWhite,
|
|
blackBright,
|
|
redBright,
|
|
greenBright,
|
|
yellowBright,
|
|
blueBright,
|
|
magentaBright,
|
|
cyanBright,
|
|
whiteBright,
|
|
bgBlackBright,
|
|
bgRedBright,
|
|
bgGreenBright,
|
|
bgYellowBright,
|
|
bgBlueBright,
|
|
bgMagentaBright,
|
|
bgCyanBright,
|
|
bgWhiteBright,
|
|
} = createColors()
|
|
|
|
;// CONCATENATED MODULE: external "node:net"
|
|
const external_node_net_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:net");
|
|
;// CONCATENATED MODULE: ./node_modules/get-port-please/dist/index.mjs
|
|
|
|
|
|
|
|
const unsafePorts = /* @__PURE__ */ new Set([
|
|
1,
|
|
7,
|
|
9,
|
|
11,
|
|
13,
|
|
15,
|
|
17,
|
|
19,
|
|
20,
|
|
21,
|
|
22,
|
|
23,
|
|
25,
|
|
37,
|
|
42,
|
|
43,
|
|
53,
|
|
69,
|
|
77,
|
|
79,
|
|
87,
|
|
95,
|
|
101,
|
|
102,
|
|
103,
|
|
104,
|
|
109,
|
|
110,
|
|
111,
|
|
113,
|
|
115,
|
|
117,
|
|
119,
|
|
123,
|
|
135,
|
|
137,
|
|
139,
|
|
143,
|
|
161,
|
|
179,
|
|
389,
|
|
427,
|
|
465,
|
|
512,
|
|
513,
|
|
514,
|
|
515,
|
|
526,
|
|
530,
|
|
531,
|
|
532,
|
|
540,
|
|
548,
|
|
554,
|
|
556,
|
|
563,
|
|
587,
|
|
601,
|
|
636,
|
|
989,
|
|
990,
|
|
993,
|
|
995,
|
|
1719,
|
|
1720,
|
|
1723,
|
|
2049,
|
|
3659,
|
|
4045,
|
|
5060,
|
|
5061,
|
|
6e3,
|
|
6566,
|
|
6665,
|
|
6666,
|
|
6667,
|
|
6668,
|
|
6669,
|
|
6697,
|
|
10080
|
|
]);
|
|
function isUnsafePort(port) {
|
|
return unsafePorts.has(port);
|
|
}
|
|
function isSafePort(port) {
|
|
return !isUnsafePort(port);
|
|
}
|
|
|
|
function log(...arguments_) {
|
|
console.log("[get-port]", ...arguments_);
|
|
}
|
|
async function getPort(config = {}) {
|
|
if (typeof config === "number" || typeof config === "string") {
|
|
config = { port: Number.parseInt(config + "") || 0 };
|
|
}
|
|
const options = {
|
|
name: "default",
|
|
random: false,
|
|
ports: [],
|
|
portRange: [],
|
|
alternativePortRange: config.port ? [] : [3e3, 3100],
|
|
host: void 0,
|
|
verbose: false,
|
|
...config,
|
|
port: config.port || Number.parseInt(process.env.PORT || "") || 3e3
|
|
};
|
|
if (options.random) {
|
|
return getRandomPort(options.host);
|
|
}
|
|
const portsToCheck = [
|
|
options.port,
|
|
...options.ports,
|
|
...generateRange(...options.portRange)
|
|
].filter((port) => {
|
|
if (!port) {
|
|
return false;
|
|
}
|
|
if (!isSafePort(port)) {
|
|
if (options.verbose) {
|
|
log("Ignoring unsafe port:", port);
|
|
}
|
|
return false;
|
|
}
|
|
return true;
|
|
});
|
|
let availablePort = await findPort(
|
|
portsToCheck,
|
|
options.host,
|
|
options.verbose,
|
|
false
|
|
);
|
|
if (!availablePort) {
|
|
availablePort = await findPort(
|
|
generateRange(...options.alternativePortRange),
|
|
options.host,
|
|
options.verbose
|
|
);
|
|
if (options.verbose) {
|
|
log(
|
|
`Unable to find an available port (tried ${portsToCheck.join(", ") || "-"}). Using alternative port:`,
|
|
availablePort
|
|
);
|
|
}
|
|
}
|
|
return availablePort;
|
|
}
|
|
async function getRandomPort(host) {
|
|
const port = await checkPort(0, host);
|
|
if (port === false) {
|
|
throw new Error("Unable to obtain an available random port number!");
|
|
}
|
|
return port;
|
|
}
|
|
async function waitForPort(port, options = {}) {
|
|
const delay = options.delay || 500;
|
|
const retries = options.retries || 4;
|
|
for (let index = retries; index > 0; index--) {
|
|
if (await checkPort(port, options.host) === false) {
|
|
return;
|
|
}
|
|
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
}
|
|
throw new Error(
|
|
`Timeout waiting for port ${port} after ${retries} retries with ${delay}ms interval.`
|
|
);
|
|
}
|
|
async function checkPort(port, host = process.env.HOST, _verbose) {
|
|
if (!host) {
|
|
host = getLocalHosts([void 0, "0.0.0.0"]);
|
|
}
|
|
if (!Array.isArray(host)) {
|
|
return _checkPort(port, host);
|
|
}
|
|
for (const _host of host) {
|
|
const _port = await _checkPort(port, _host);
|
|
if (_port === false) {
|
|
if (port < 1024 && _verbose) {
|
|
log("Unable to listen to priviliged port:", `${_host}:${port}`);
|
|
}
|
|
return false;
|
|
}
|
|
if (port === 0 && _port !== 0) {
|
|
port = _port;
|
|
}
|
|
}
|
|
return port;
|
|
}
|
|
function generateRange(from, to) {
|
|
if (to < from) {
|
|
return [];
|
|
}
|
|
const r = [];
|
|
for (let index = from; index < to; index++) {
|
|
r.push(index);
|
|
}
|
|
return r;
|
|
}
|
|
function _checkPort(port, host) {
|
|
return new Promise((resolve) => {
|
|
const server = (0,external_node_net_namespaceObject.createServer)();
|
|
server.unref();
|
|
server.on("error", (error) => {
|
|
if (error.code === "EINVAL" || error.code === "EADDRNOTAVAIL") {
|
|
resolve(port !== 0 && isSafePort(port) && port);
|
|
} else {
|
|
resolve(false);
|
|
}
|
|
});
|
|
server.listen({ port, host }, () => {
|
|
const { port: port2 } = server.address();
|
|
server.close(() => {
|
|
resolve(isSafePort(port2) && port2);
|
|
});
|
|
});
|
|
});
|
|
}
|
|
function getLocalHosts(additional) {
|
|
const hosts = new Set(additional);
|
|
for (const _interface of Object.values((0,external_node_os_namespaceObject.networkInterfaces)())) {
|
|
for (const config of _interface || []) {
|
|
hosts.add(config.address);
|
|
}
|
|
}
|
|
return [...hosts];
|
|
}
|
|
async function findPort(ports, host, _verbose = false, _random = true) {
|
|
for (const port of ports) {
|
|
const r = await checkPort(port, host, _verbose);
|
|
if (r) {
|
|
return r;
|
|
}
|
|
}
|
|
if (_random) {
|
|
const randomPort = await getRandomPort(host);
|
|
if (_verbose) {
|
|
log(
|
|
`Unable to find an available port (tried ${ports.join(", ") || "-"}). Using random port:`,
|
|
randomPort
|
|
);
|
|
}
|
|
return randomPort;
|
|
} else {
|
|
return 0;
|
|
}
|
|
}
|
|
|
|
|
|
|
|
// EXTERNAL MODULE: ./node_modules/http-shutdown/index.js
|
|
var http_shutdown = __nccwpck_require__(2182);
|
|
;// CONCATENATED MODULE: external "node:child_process"
|
|
const external_node_child_process_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:child_process");
|
|
// EXTERNAL MODULE: external "node:path"
|
|
var external_node_path_ = __nccwpck_require__(9411);
|
|
;// CONCATENATED MODULE: ./node_modules/listhen/dist/index.mjs
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
const { platform: dist_platform, arch } = process;
|
|
const getWslDrivesMountPoint = (() => {
|
|
const defaultMountPoint = "/mnt/";
|
|
let mountPoint;
|
|
return async function() {
|
|
if (mountPoint) {
|
|
return mountPoint;
|
|
}
|
|
const configFilePath = "/etc/wsl.conf";
|
|
let isConfigFileExists = false;
|
|
try {
|
|
await external_node_fs_namespaceObject.promises.access(configFilePath, external_node_fs_namespaceObject.constants.F_OK);
|
|
isConfigFileExists = true;
|
|
} catch {
|
|
}
|
|
if (!isConfigFileExists) {
|
|
return defaultMountPoint;
|
|
}
|
|
const configContent = await external_node_fs_namespaceObject.promises.readFile(configFilePath, {
|
|
encoding: "utf8"
|
|
});
|
|
const configMountPoint = /(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(
|
|
configContent
|
|
);
|
|
if (!configMountPoint) {
|
|
return defaultMountPoint;
|
|
}
|
|
mountPoint = configMountPoint.groups.mountPoint.trim();
|
|
mountPoint = mountPoint.endsWith("/") ? mountPoint : `${mountPoint}/`;
|
|
return mountPoint;
|
|
};
|
|
})();
|
|
const pTryEach = async (array, mapper) => {
|
|
let latestError;
|
|
for (const item of array) {
|
|
try {
|
|
return await mapper(item);
|
|
} catch (error) {
|
|
latestError = error;
|
|
}
|
|
}
|
|
throw latestError;
|
|
};
|
|
const baseOpen = async (options) => {
|
|
options = {
|
|
wait: false,
|
|
background: false,
|
|
newInstance: false,
|
|
allowNonzeroExitCode: false,
|
|
...options
|
|
};
|
|
if (Array.isArray(options.app)) {
|
|
return pTryEach(
|
|
options.app,
|
|
(singleApp) => baseOpen({
|
|
...options,
|
|
app: singleApp
|
|
})
|
|
);
|
|
}
|
|
let { name: app, arguments: appArguments = [] } = options.app || {};
|
|
appArguments = [...appArguments];
|
|
if (Array.isArray(app)) {
|
|
return pTryEach(
|
|
app,
|
|
(appName) => baseOpen({
|
|
...options,
|
|
app: {
|
|
name: appName,
|
|
arguments: appArguments
|
|
}
|
|
})
|
|
);
|
|
}
|
|
let command;
|
|
const cliArguments = [];
|
|
const childProcessOptions = {};
|
|
if (dist_platform === "darwin") {
|
|
command = "open";
|
|
if (options.wait) {
|
|
cliArguments.push("--wait-apps");
|
|
}
|
|
if (options.background) {
|
|
cliArguments.push("--background");
|
|
}
|
|
if (options.newInstance) {
|
|
cliArguments.push("--new");
|
|
}
|
|
if (app) {
|
|
cliArguments.push("-a", app);
|
|
}
|
|
} else if (dist_platform === "win32" || isWsl() && !isDocker()) {
|
|
const mountPoint = await getWslDrivesMountPoint();
|
|
command = isWsl() ? `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe` : `${process.env.SYSTEMROOT}\\System32\\WindowsPowerShell\\v1.0\\powershell`;
|
|
cliArguments.push(
|
|
"-NoProfile",
|
|
"-NonInteractive",
|
|
"\u2013ExecutionPolicy",
|
|
"Bypass",
|
|
"-EncodedCommand"
|
|
);
|
|
if (!isWsl()) {
|
|
childProcessOptions.windowsVerbatimArguments = true;
|
|
}
|
|
const encodedArguments = ["Start"];
|
|
if (options.wait) {
|
|
encodedArguments.push("-Wait");
|
|
}
|
|
if (app) {
|
|
encodedArguments.push(`"\`"${app}\`""`, "-ArgumentList");
|
|
if (options.target) {
|
|
appArguments.unshift(options.target);
|
|
}
|
|
} else if (options.target) {
|
|
encodedArguments.push(`"${options.target}"`);
|
|
}
|
|
if (appArguments.length > 0) {
|
|
appArguments = appArguments.map((argument) => `"\`"${argument}\`""`);
|
|
encodedArguments.push(appArguments.join(","));
|
|
}
|
|
options.target = Buffer.from(
|
|
encodedArguments.join(" "),
|
|
"utf16le"
|
|
).toString("base64");
|
|
} else {
|
|
if (app) {
|
|
command = app;
|
|
} else {
|
|
command = "xdg-open";
|
|
const useSystemXdgOpen = process.versions.electron || dist_platform === "android";
|
|
if (!useSystemXdgOpen) {
|
|
command = (0,external_node_path_.join)(external_node_os_namespaceObject.tmpdir(), "xdg-open");
|
|
if (!(0,external_node_fs_namespaceObject.existsSync)(command)) {
|
|
try {
|
|
(0,external_node_fs_namespaceObject.writeFileSync)(
|
|
(0,external_node_path_.join)(external_node_os_namespaceObject.tmpdir(), "xdg-open"),
|
|
await __nccwpck_require__.e(/* import() */ 358).then(__nccwpck_require__.bind(__nccwpck_require__, 4358)).then((r) => r.xdgOpenScript()),
|
|
"utf8"
|
|
);
|
|
(0,external_node_fs_namespaceObject.chmodSync)(
|
|
command,
|
|
493
|
|
/* rwx r-x r-x */
|
|
);
|
|
} catch {
|
|
command = "xdg-open";
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if (appArguments.length > 0) {
|
|
cliArguments.push(...appArguments);
|
|
}
|
|
if (!options.wait) {
|
|
childProcessOptions.stdio = "ignore";
|
|
childProcessOptions.detached = true;
|
|
}
|
|
}
|
|
if (options.target) {
|
|
cliArguments.push(options.target);
|
|
}
|
|
if (dist_platform === "darwin" && appArguments.length > 0) {
|
|
cliArguments.push("--args", ...appArguments);
|
|
}
|
|
const subprocess = external_node_child_process_namespaceObject.spawn(
|
|
command,
|
|
cliArguments,
|
|
childProcessOptions
|
|
);
|
|
if (options.wait) {
|
|
return new Promise((resolve, reject) => {
|
|
subprocess.once("error", reject);
|
|
subprocess.once("close", (exitCode) => {
|
|
if (options.allowNonzeroExitCode && exitCode > 0) {
|
|
reject(new Error(`Exited with code ${exitCode}`));
|
|
return;
|
|
}
|
|
resolve(subprocess);
|
|
});
|
|
});
|
|
}
|
|
subprocess.unref();
|
|
return subprocess;
|
|
};
|
|
const dist_open = (target, options = {}) => {
|
|
if (typeof target !== "string") {
|
|
throw new TypeError("Expected a `target`");
|
|
}
|
|
return baseOpen({
|
|
...options,
|
|
target
|
|
});
|
|
};
|
|
const openApp = (name, options) => {
|
|
if (typeof name !== "string") {
|
|
throw new TypeError("Expected a `name`");
|
|
}
|
|
const { arguments: appArguments = [] } = options || {};
|
|
if (appArguments !== void 0 && appArguments !== null && !Array.isArray(appArguments)) {
|
|
throw new TypeError("Expected `appArguments` as Array type");
|
|
}
|
|
return baseOpen({
|
|
...options,
|
|
app: {
|
|
name,
|
|
arguments: appArguments
|
|
}
|
|
});
|
|
};
|
|
function detectArchBinary(binary) {
|
|
if (typeof binary === "string" || Array.isArray(binary)) {
|
|
return binary;
|
|
}
|
|
const { [arch]: archBinary } = binary;
|
|
if (!archBinary) {
|
|
throw new Error(`${arch} is not supported`);
|
|
}
|
|
return archBinary;
|
|
}
|
|
function detectPlatformBinary({ [dist_platform]: platformBinary }, { wsl }) {
|
|
if (wsl && isWsl()) {
|
|
return detectArchBinary(wsl);
|
|
}
|
|
if (!platformBinary) {
|
|
throw new Error(`${dist_platform} is not supported`);
|
|
}
|
|
return detectArchBinary(platformBinary);
|
|
}
|
|
const apps = {};
|
|
defineLazyProperty(
|
|
apps,
|
|
"chrome",
|
|
() => detectPlatformBinary(
|
|
{
|
|
darwin: "google chrome",
|
|
win32: "chrome",
|
|
linux: ["google-chrome", "google-chrome-stable", "chromium"]
|
|
},
|
|
{
|
|
wsl: {
|
|
ia32: "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",
|
|
x64: [
|
|
"/mnt/c/Program Files/Google/Chrome/Application/chrome.exe",
|
|
"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"
|
|
]
|
|
}
|
|
}
|
|
)
|
|
);
|
|
defineLazyProperty(
|
|
apps,
|
|
"firefox",
|
|
() => detectPlatformBinary(
|
|
{
|
|
darwin: "firefox",
|
|
win32: "C:\\Program Files\\Mozilla Firefox\\firefox.exe",
|
|
linux: "firefox"
|
|
},
|
|
{
|
|
wsl: "/mnt/c/Program Files/Mozilla Firefox/firefox.exe"
|
|
}
|
|
)
|
|
);
|
|
defineLazyProperty(
|
|
apps,
|
|
"edge",
|
|
() => detectPlatformBinary(
|
|
{
|
|
darwin: "microsoft edge",
|
|
win32: "msedge",
|
|
linux: ["microsoft-edge", "microsoft-edge-dev"]
|
|
},
|
|
{
|
|
wsl: "/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"
|
|
}
|
|
)
|
|
);
|
|
dist_open.apps = apps;
|
|
dist_open.openApp = openApp;
|
|
function defineLazyProperty(object, propertyName, valueGetter) {
|
|
const define = (value) => Object.defineProperty(object, propertyName, {
|
|
value,
|
|
enumerable: true,
|
|
writable: true
|
|
});
|
|
Object.defineProperty(object, propertyName, {
|
|
configurable: true,
|
|
enumerable: true,
|
|
get() {
|
|
const result = valueGetter();
|
|
define(result);
|
|
return result;
|
|
},
|
|
set(value) {
|
|
define(value);
|
|
}
|
|
});
|
|
return object;
|
|
}
|
|
function _isWsl() {
|
|
if (process.platform !== "linux") {
|
|
return false;
|
|
}
|
|
if (external_node_os_namespaceObject.release().toLowerCase().includes("microsoft")) {
|
|
if (isDocker()) {
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
try {
|
|
return (0,external_node_fs_namespaceObject.readFileSync)("/proc/version", "utf8").toLowerCase().includes("microsoft") ? !isDocker() : false;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
let isWSLCached;
|
|
function isWsl() {
|
|
if (isWSLCached === void 0) {
|
|
isWSLCached = _isWsl();
|
|
}
|
|
return isWSLCached;
|
|
}
|
|
function hasDockerEnvironment() {
|
|
try {
|
|
(0,external_node_fs_namespaceObject.statSync)("/.dockerenv");
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
function hasDockerCGroup() {
|
|
try {
|
|
return (0,external_node_fs_namespaceObject.readFileSync)("/proc/self/cgroup", "utf8").includes("docker");
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
let isDockerCached;
|
|
function isDocker() {
|
|
if (isDockerCached === void 0) {
|
|
isDockerCached = hasDockerEnvironment() || hasDockerCGroup();
|
|
}
|
|
return isDockerCached;
|
|
}
|
|
|
|
async function listen(handle, options_ = {}) {
|
|
options_ = defu_defu(options_, {
|
|
port: process.env.PORT || 3e3,
|
|
hostname: process.env.HOST || "",
|
|
showURL: true,
|
|
baseURL: "/",
|
|
open: false,
|
|
clipboard: false,
|
|
isTest: process.env.NODE_ENV === "test",
|
|
isProd: process.env.NODE_ENV === "production",
|
|
autoClose: true
|
|
});
|
|
if (options_.isTest) {
|
|
options_.showURL = false;
|
|
}
|
|
if (options_.isProd || options_.isTest) {
|
|
options_.open = false;
|
|
options_.clipboard = false;
|
|
}
|
|
const port = await getPort({
|
|
port: Number(options_.port),
|
|
verbose: !options_.isTest,
|
|
host: options_.hostname,
|
|
alternativePortRange: [3e3, 3100],
|
|
...typeof options_.port === "object" && options_.port
|
|
});
|
|
let server;
|
|
let addr;
|
|
const getURL = (host, baseURL) => {
|
|
const anyV4 = addr?.addr === "0.0.0.0";
|
|
const anyV6 = addr?.addr === "[::]";
|
|
return `${addr.proto}://${host || options_.hostname || (anyV4 || anyV6 ? "localhost" : addr.addr)}:${addr.port}${baseURL || options_.baseURL}`;
|
|
};
|
|
let https = false;
|
|
if (options_.https) {
|
|
const { key, cert } = await resolveCert(
|
|
{ ...options_.https },
|
|
options_.hostname
|
|
);
|
|
https = { key, cert };
|
|
server = (0,external_node_https_namespaceObject.createServer)({ key, cert }, handle);
|
|
http_shutdown(server);
|
|
await (0,external_node_util_.promisify)(server.listen.bind(server))(port, options_.hostname);
|
|
const _addr = server.address();
|
|
addr = { proto: "https", addr: formatAddress(_addr), port: _addr.port };
|
|
} else {
|
|
server = (0,external_node_http_namespaceObject.createServer)(handle);
|
|
http_shutdown(server);
|
|
await (0,external_node_util_.promisify)(server.listen.bind(server))(port, options_.hostname);
|
|
const _addr = server.address();
|
|
addr = { proto: "http", addr: formatAddress(_addr), port: _addr.port };
|
|
}
|
|
let _closed = false;
|
|
const close = () => {
|
|
if (_closed) {
|
|
return Promise.resolve();
|
|
}
|
|
_closed = true;
|
|
return (0,external_node_util_.promisify)(server.shutdown)();
|
|
};
|
|
if (options_.clipboard) {
|
|
const clipboardy = await __nccwpck_require__.e(/* import() */ 902).then(__nccwpck_require__.bind(__nccwpck_require__, 9902)).then((r) => r.default || r);
|
|
await clipboardy.write(getURL()).catch(() => {
|
|
options_.clipboard = false;
|
|
});
|
|
}
|
|
const showURL = (options) => {
|
|
const add = options_.clipboard ? gray("(copied to clipboard)") : "";
|
|
const lines = [];
|
|
const baseURL = options?.baseURL || options_.baseURL || "";
|
|
const name = options?.name ? ` (${options.name})` : "";
|
|
const anyV4 = addr?.addr === "0.0.0.0";
|
|
const anyV6 = addr?.addr === "[::]";
|
|
if (anyV4 || anyV6) {
|
|
lines.push(
|
|
` > Local${name}: ${formatURL(getURL("localhost", baseURL))} ${add}`
|
|
);
|
|
for (const addr2 of getNetworkInterfaces(anyV4)) {
|
|
lines.push(` > Network${name}: ${formatURL(getURL(addr2, baseURL))}`);
|
|
}
|
|
} else {
|
|
lines.push(
|
|
` > Listening${name}: ${formatURL(
|
|
getURL(void 0, baseURL)
|
|
)} ${add}`
|
|
);
|
|
}
|
|
console.log("\n" + lines.join("\n") + "\n");
|
|
};
|
|
if (options_.showURL) {
|
|
showURL();
|
|
}
|
|
const _open = async () => {
|
|
await dist_open(getURL()).catch(() => {
|
|
});
|
|
};
|
|
if (options_.open) {
|
|
await _open();
|
|
}
|
|
if (options_.autoClose) {
|
|
process.on("exit", () => close());
|
|
}
|
|
return {
|
|
url: getURL(),
|
|
https,
|
|
server,
|
|
open: _open,
|
|
showURL,
|
|
close
|
|
};
|
|
}
|
|
async function resolveCert(options, host) {
|
|
if (options.key && options.cert) {
|
|
const isInline = (s = "") => s.startsWith("--");
|
|
const r = (s) => isInline(s) ? s : external_node_fs_namespaceObject.promises.readFile(s, "utf8");
|
|
return {
|
|
key: await r(options.key),
|
|
cert: await r(options.cert)
|
|
};
|
|
}
|
|
const { generateCA, generateSSLCert } = await __nccwpck_require__.e(/* import() */ 32).then(__nccwpck_require__.bind(__nccwpck_require__, 6032));
|
|
const ca = await generateCA();
|
|
const cert = await generateSSLCert({
|
|
caCert: ca.cert,
|
|
caKey: ca.key,
|
|
domains: options.domains || ["localhost", "127.0.0.1", "::1", host].filter(Boolean),
|
|
validityDays: options.validityDays || 1
|
|
});
|
|
return cert;
|
|
}
|
|
function getNetworkInterfaces(v4Only = true) {
|
|
const addrs = /* @__PURE__ */ new Set();
|
|
for (const details of Object.values((0,external_node_os_namespaceObject.networkInterfaces)())) {
|
|
if (details) {
|
|
for (const d of details) {
|
|
if (!d.internal && !(d.mac === "00:00:00:00:00:00") && !d.address.startsWith("fe80::") && !(v4Only && (d.family === "IPv6" || +d.family === 6))) {
|
|
addrs.add(formatAddress(d));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return [...addrs].sort();
|
|
}
|
|
function formatAddress(addr) {
|
|
return addr.family === "IPv6" || addr.family === 6 ? `[${addr.address}]` : addr.address;
|
|
}
|
|
function formatURL(url) {
|
|
return cyan(
|
|
underline(decodeURI(url).replace(/:(\d+)\//g, `:${bold("$1")}/`))
|
|
);
|
|
}
|
|
|
|
|
|
|
|
;// CONCATENATED MODULE: ./node_modules/zod/lib/index.mjs
|
|
var util;
|
|
(function (util) {
|
|
util.assertEqual = (val) => val;
|
|
function assertIs(_arg) { }
|
|
util.assertIs = assertIs;
|
|
function assertNever(_x) {
|
|
throw new Error();
|
|
}
|
|
util.assertNever = assertNever;
|
|
util.arrayToEnum = (items) => {
|
|
const obj = {};
|
|
for (const item of items) {
|
|
obj[item] = item;
|
|
}
|
|
return obj;
|
|
};
|
|
util.getValidEnumValues = (obj) => {
|
|
const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
|
|
const filtered = {};
|
|
for (const k of validKeys) {
|
|
filtered[k] = obj[k];
|
|
}
|
|
return util.objectValues(filtered);
|
|
};
|
|
util.objectValues = (obj) => {
|
|
return util.objectKeys(obj).map(function (e) {
|
|
return obj[e];
|
|
});
|
|
};
|
|
util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban
|
|
? (obj) => Object.keys(obj) // eslint-disable-line ban/ban
|
|
: (object) => {
|
|
const keys = [];
|
|
for (const key in object) {
|
|
if (Object.prototype.hasOwnProperty.call(object, key)) {
|
|
keys.push(key);
|
|
}
|
|
}
|
|
return keys;
|
|
};
|
|
util.find = (arr, checker) => {
|
|
for (const item of arr) {
|
|
if (checker(item))
|
|
return item;
|
|
}
|
|
return undefined;
|
|
};
|
|
util.isInteger = typeof Number.isInteger === "function"
|
|
? (val) => Number.isInteger(val) // eslint-disable-line ban/ban
|
|
: (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val;
|
|
function joinValues(array, separator = " | ") {
|
|
return array
|
|
.map((val) => (typeof val === "string" ? `'${val}'` : val))
|
|
.join(separator);
|
|
}
|
|
util.joinValues = joinValues;
|
|
util.jsonStringifyReplacer = (_, value) => {
|
|
if (typeof value === "bigint") {
|
|
return value.toString();
|
|
}
|
|
return value;
|
|
};
|
|
})(util || (util = {}));
|
|
var objectUtil;
|
|
(function (objectUtil) {
|
|
objectUtil.mergeShapes = (first, second) => {
|
|
return {
|
|
...first,
|
|
...second, // second overwrites first
|
|
};
|
|
};
|
|
})(objectUtil || (objectUtil = {}));
|
|
const ZodParsedType = util.arrayToEnum([
|
|
"string",
|
|
"nan",
|
|
"number",
|
|
"integer",
|
|
"float",
|
|
"boolean",
|
|
"date",
|
|
"bigint",
|
|
"symbol",
|
|
"function",
|
|
"undefined",
|
|
"null",
|
|
"array",
|
|
"object",
|
|
"unknown",
|
|
"promise",
|
|
"void",
|
|
"never",
|
|
"map",
|
|
"set",
|
|
]);
|
|
const getParsedType = (data) => {
|
|
const t = typeof data;
|
|
switch (t) {
|
|
case "undefined":
|
|
return ZodParsedType.undefined;
|
|
case "string":
|
|
return ZodParsedType.string;
|
|
case "number":
|
|
return 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;
|
|
}
|
|
};
|
|
|
|
const 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",
|
|
]);
|
|
const quotelessJson = (obj) => {
|
|
const json = JSON.stringify(obj, null, 2);
|
|
return json.replace(/"([^"]+)":/g, "$1:");
|
|
};
|
|
class ZodError extends Error {
|
|
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) {
|
|
// eslint-disable-next-line ban/ban
|
|
Object.setPrototypeOf(this, actualProto);
|
|
}
|
|
else {
|
|
this.__proto__ = actualProto;
|
|
}
|
|
this.name = "ZodError";
|
|
this.issues = issues;
|
|
}
|
|
get errors() {
|
|
return this.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: [] };
|
|
// if (typeof el === "string") {
|
|
// curr[el] = curr[el] || { _errors: [] };
|
|
// } else if (typeof el === "number") {
|
|
// const errorArray: any = [];
|
|
// errorArray._errors = [];
|
|
// curr[el] = curr[el] || errorArray;
|
|
// }
|
|
}
|
|
else {
|
|
curr[el] = curr[el] || { _errors: [] };
|
|
curr[el]._errors.push(mapper(issue));
|
|
}
|
|
curr = curr[el];
|
|
i++;
|
|
}
|
|
}
|
|
}
|
|
};
|
|
processError(this);
|
|
return fieldErrors;
|
|
}
|
|
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;
|
|
};
|
|
|
|
const 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 };
|
|
};
|
|
|
|
let overrideErrorMap = errorMap;
|
|
function setErrorMap(map) {
|
|
overrideErrorMap = map;
|
|
}
|
|
function getErrorMap() {
|
|
return overrideErrorMap;
|
|
}
|
|
|
|
const makeIssue = (params) => {
|
|
const { data, path, errorMaps, issueData } = params;
|
|
const fullPath = [...path, ...(issueData.path || [])];
|
|
const fullIssue = {
|
|
...issueData,
|
|
path: fullPath,
|
|
};
|
|
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: issueData.message || errorMessage,
|
|
};
|
|
};
|
|
const EMPTY_PATH = [];
|
|
function addIssueToContext(ctx, issueData) {
|
|
const issue = makeIssue({
|
|
issueData: issueData,
|
|
data: ctx.data,
|
|
path: ctx.path,
|
|
errorMaps: [
|
|
ctx.common.contextualErrorMap,
|
|
ctx.schemaErrorMap,
|
|
getErrorMap(),
|
|
errorMap, // then global default map
|
|
].filter((x) => !!x),
|
|
});
|
|
ctx.common.issues.push(issue);
|
|
}
|
|
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) {
|
|
syncPairs.push({
|
|
key: await pair.key,
|
|
value: await pair.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 (typeof value.value !== "undefined" || pair.alwaysSet) {
|
|
finalObject[key.value] = value.value;
|
|
}
|
|
}
|
|
return { status: status.value, value: finalObject };
|
|
}
|
|
}
|
|
const INVALID = Object.freeze({
|
|
status: "aborted",
|
|
});
|
|
const DIRTY = (value) => ({ status: "dirty", value });
|
|
const OK = (value) => ({ status: "valid", value });
|
|
const isAborted = (x) => x.status === "aborted";
|
|
const isDirty = (x) => x.status === "dirty";
|
|
const isValid = (x) => x.status === "valid";
|
|
const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
|
|
|
|
var errorUtil;
|
|
(function (errorUtil) {
|
|
errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {};
|
|
errorUtil.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
|
|
})(errorUtil || (errorUtil = {}));
|
|
|
|
class ParseInputLazyPath {
|
|
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 (this._key instanceof Array) {
|
|
this._cachedPath.push(...this._path, ...this._key);
|
|
}
|
|
else {
|
|
this._cachedPath.push(...this._path, this._key);
|
|
}
|
|
}
|
|
return this._cachedPath;
|
|
}
|
|
}
|
|
const 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, invalid_type_error, required_error, description } = params;
|
|
if (errorMap && (invalid_type_error || required_error)) {
|
|
throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
|
|
}
|
|
if (errorMap)
|
|
return { errorMap: errorMap, description };
|
|
const customMap = (iss, ctx) => {
|
|
if (iss.code !== "invalid_type")
|
|
return { message: ctx.defaultError };
|
|
if (typeof ctx.data === "undefined") {
|
|
return { message: required_error !== null && required_error !== void 0 ? required_error : ctx.defaultError };
|
|
}
|
|
return { message: invalid_type_error !== null && invalid_type_error !== void 0 ? invalid_type_error : ctx.defaultError };
|
|
};
|
|
return { errorMap: customMap, description };
|
|
}
|
|
class ZodType {
|
|
constructor(def) {
|
|
/** Alias of safeParseAsync */
|
|
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.isNullable = this.isNullable.bind(this);
|
|
this.isOptional = this.isOptional.bind(this);
|
|
}
|
|
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) {
|
|
var _a;
|
|
const ctx = {
|
|
common: {
|
|
issues: [],
|
|
async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false,
|
|
contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
|
|
},
|
|
path: (params === null || params === void 0 ? void 0 : 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);
|
|
}
|
|
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 === null || params === void 0 ? void 0 : params.errorMap,
|
|
async: true,
|
|
},
|
|
path: (params === null || params === void 0 ? void 0 : 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);
|
|
}
|
|
optional() {
|
|
return ZodOptional.create(this, this._def);
|
|
}
|
|
nullable() {
|
|
return ZodNullable.create(this, this._def);
|
|
}
|
|
nullish() {
|
|
return this.nullable().optional();
|
|
}
|
|
array() {
|
|
return ZodArray.create(this, this._def);
|
|
}
|
|
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);
|
|
}
|
|
isOptional() {
|
|
return this.safeParse(undefined).success;
|
|
}
|
|
isNullable() {
|
|
return this.safeParse(null).success;
|
|
}
|
|
}
|
|
const cuidRegex = /^c[^\s-]{8,}$/i;
|
|
const cuid2Regex = /^[a-z][a-z0-9]*$/;
|
|
const ulidRegex = /[0-9A-HJKMNP-TV-Z]{26}/;
|
|
const uuidRegex = /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;
|
|
// from https://stackoverflow.com/a/46181/1550155
|
|
// old version: too slow, didn't support unicode
|
|
// const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i;
|
|
//old email regex
|
|
// const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i;
|
|
// eslint-disable-next-line
|
|
const emailRegex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/;
|
|
// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression
|
|
const emojiRegex = /^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u;
|
|
const ipv4Regex = /^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/;
|
|
const ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;
|
|
// Adapted from https://stackoverflow.com/a/3143231
|
|
const datetimeRegex = (args) => {
|
|
if (args.precision) {
|
|
if (args.offset) {
|
|
return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
|
|
}
|
|
else {
|
|
return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$`);
|
|
}
|
|
}
|
|
else if (args.precision === 0) {
|
|
if (args.offset) {
|
|
return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
|
|
}
|
|
else {
|
|
return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$`);
|
|
}
|
|
}
|
|
else {
|
|
if (args.offset) {
|
|
return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
|
|
}
|
|
else {
|
|
return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$`);
|
|
}
|
|
}
|
|
};
|
|
function isValidIP(ip, version) {
|
|
if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
|
|
return true;
|
|
}
|
|
if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
class ZodString extends ZodType {
|
|
constructor() {
|
|
super(...arguments);
|
|
this._regex = (regex, validation, message) => this.refinement((data) => regex.test(data), {
|
|
validation,
|
|
code: ZodIssueCode.invalid_string,
|
|
...errorUtil.errToObj(message),
|
|
});
|
|
/**
|
|
* @deprecated Use z.string().min(1) instead.
|
|
* @see {@link ZodString.min}
|
|
*/
|
|
this.nonempty = (message) => this.min(1, errorUtil.errToObj(message));
|
|
this.trim = () => new ZodString({
|
|
...this._def,
|
|
checks: [...this._def.checks, { kind: "trim" }],
|
|
});
|
|
this.toLowerCase = () => new ZodString({
|
|
...this._def,
|
|
checks: [...this._def.checks, { kind: "toLowerCase" }],
|
|
});
|
|
this.toUpperCase = () => new ZodString({
|
|
...this._def,
|
|
checks: [...this._def.checks, { kind: "toUpperCase" }],
|
|
});
|
|
}
|
|
_parse(input) {
|
|
if (this._def.coerce) {
|
|
input.data = String(input.data);
|
|
}
|
|
const parsedType = this._getType(input);
|
|
if (parsedType !== ZodParsedType.string) {
|
|
const ctx = this._getOrReturnCtx(input);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_type,
|
|
expected: ZodParsedType.string,
|
|
received: ctx.parsedType,
|
|
}
|
|
//
|
|
);
|
|
return INVALID;
|
|
}
|
|
const status = new ParseStatus();
|
|
let ctx = undefined;
|
|
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.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 === "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 (_a) {
|
|
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 === "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 {
|
|
util.assertNever(check);
|
|
}
|
|
}
|
|
return { status: status.value, value: input.data };
|
|
}
|
|
_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) });
|
|
}
|
|
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) });
|
|
}
|
|
ip(options) {
|
|
return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
|
|
}
|
|
datetime(options) {
|
|
var _a;
|
|
if (typeof options === "string") {
|
|
return this._addCheck({
|
|
kind: "datetime",
|
|
precision: null,
|
|
offset: false,
|
|
message: options,
|
|
});
|
|
}
|
|
return this._addCheck({
|
|
kind: "datetime",
|
|
precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
|
|
offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false,
|
|
...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),
|
|
});
|
|
}
|
|
regex(regex, message) {
|
|
return this._addCheck({
|
|
kind: "regex",
|
|
regex: regex,
|
|
...errorUtil.errToObj(message),
|
|
});
|
|
}
|
|
includes(value, options) {
|
|
return this._addCheck({
|
|
kind: "includes",
|
|
value: value,
|
|
position: options === null || options === void 0 ? void 0 : options.position,
|
|
...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),
|
|
});
|
|
}
|
|
startsWith(value, message) {
|
|
return this._addCheck({
|
|
kind: "startsWith",
|
|
value: value,
|
|
...errorUtil.errToObj(message),
|
|
});
|
|
}
|
|
endsWith(value, message) {
|
|
return this._addCheck({
|
|
kind: "endsWith",
|
|
value: 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),
|
|
});
|
|
}
|
|
get isDatetime() {
|
|
return !!this._def.checks.find((ch) => ch.kind === "datetime");
|
|
}
|
|
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 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 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) => {
|
|
var _a;
|
|
return new ZodString({
|
|
checks: [],
|
|
typeName: ZodFirstPartyTypeKind.ZodString,
|
|
coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
|
|
...processCreateParams(params),
|
|
});
|
|
};
|
|
// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034
|
|
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 = parseInt(val.toFixed(decCount).replace(".", ""));
|
|
const stepInt = parseInt(step.toFixed(decCount).replace(".", ""));
|
|
return (valInt % stepInt) / Math.pow(10, decCount);
|
|
}
|
|
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 ctx = this._getOrReturnCtx(input);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_type,
|
|
expected: ZodParsedType.number,
|
|
received: ctx.parsedType,
|
|
});
|
|
return INVALID;
|
|
}
|
|
let ctx = undefined;
|
|
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: 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, 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 === null || params === void 0 ? void 0 : params.coerce) || false,
|
|
...processCreateParams(params),
|
|
});
|
|
};
|
|
class ZodBigInt extends ZodType {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.min = this.gte;
|
|
this.max = this.lte;
|
|
}
|
|
_parse(input) {
|
|
if (this._def.coerce) {
|
|
input.data = BigInt(input.data);
|
|
}
|
|
const parsedType = this._getType(input);
|
|
if (parsedType !== ZodParsedType.bigint) {
|
|
const ctx = this._getOrReturnCtx(input);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_type,
|
|
expected: ZodParsedType.bigint,
|
|
received: ctx.parsedType,
|
|
});
|
|
return INVALID;
|
|
}
|
|
let ctx = undefined;
|
|
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 };
|
|
}
|
|
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) => {
|
|
var _a;
|
|
return new ZodBigInt({
|
|
checks: [],
|
|
typeName: ZodFirstPartyTypeKind.ZodBigInt,
|
|
coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
|
|
...processCreateParams(params),
|
|
});
|
|
};
|
|
class ZodBoolean 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 === null || params === void 0 ? void 0 : params.coerce) || false,
|
|
...processCreateParams(params),
|
|
});
|
|
};
|
|
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 ctx = this._getOrReturnCtx(input);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_type,
|
|
expected: ZodParsedType.date,
|
|
received: ctx.parsedType,
|
|
});
|
|
return INVALID;
|
|
}
|
|
if (isNaN(input.data.getTime())) {
|
|
const ctx = this._getOrReturnCtx(input);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_date,
|
|
});
|
|
return INVALID;
|
|
}
|
|
const status = new ParseStatus();
|
|
let ctx = undefined;
|
|
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 === null || params === void 0 ? void 0 : params.coerce) || false,
|
|
typeName: ZodFirstPartyTypeKind.ZodDate,
|
|
...processCreateParams(params),
|
|
});
|
|
};
|
|
class ZodSymbol 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),
|
|
});
|
|
};
|
|
class ZodUndefined 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),
|
|
});
|
|
};
|
|
class ZodNull 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),
|
|
});
|
|
};
|
|
class ZodAny extends ZodType {
|
|
constructor() {
|
|
super(...arguments);
|
|
// to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.
|
|
this._any = true;
|
|
}
|
|
_parse(input) {
|
|
return OK(input.data);
|
|
}
|
|
}
|
|
ZodAny.create = (params) => {
|
|
return new ZodAny({
|
|
typeName: ZodFirstPartyTypeKind.ZodAny,
|
|
...processCreateParams(params),
|
|
});
|
|
};
|
|
class ZodUnknown extends ZodType {
|
|
constructor() {
|
|
super(...arguments);
|
|
// required
|
|
this._unknown = true;
|
|
}
|
|
_parse(input) {
|
|
return OK(input.data);
|
|
}
|
|
}
|
|
ZodUnknown.create = (params) => {
|
|
return new ZodUnknown({
|
|
typeName: ZodFirstPartyTypeKind.ZodUnknown,
|
|
...processCreateParams(params),
|
|
});
|
|
};
|
|
class ZodNever 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),
|
|
});
|
|
};
|
|
class ZodVoid 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),
|
|
});
|
|
};
|
|
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 : undefined),
|
|
maximum: (tooBig ? def.exactLength.value : undefined),
|
|
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((result) => {
|
|
return ParseStatus.mergeArray(status, result);
|
|
});
|
|
}
|
|
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;
|
|
}
|
|
}
|
|
class ZodObject extends ZodType {
|
|
constructor() {
|
|
super(...arguments);
|
|
this._cached = null;
|
|
/**
|
|
* @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.
|
|
* If you want to pass through unknown properties, use `.passthrough()` instead.
|
|
*/
|
|
this.nonstrict = this.passthrough;
|
|
// extend<
|
|
// Augmentation extends ZodRawShape,
|
|
// NewOutput extends util.flatten<{
|
|
// [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
|
|
// ? Augmentation[k]["_output"]
|
|
// : k extends keyof Output
|
|
// ? Output[k]
|
|
// : never;
|
|
// }>,
|
|
// NewInput extends util.flatten<{
|
|
// [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
|
|
// ? Augmentation[k]["_input"]
|
|
// : k extends keyof Input
|
|
// ? Input[k]
|
|
// : never;
|
|
// }>
|
|
// >(
|
|
// augmentation: Augmentation
|
|
// ): ZodObject<
|
|
// extendShape<T, Augmentation>,
|
|
// UnknownKeys,
|
|
// Catchall,
|
|
// NewOutput,
|
|
// NewInput
|
|
// > {
|
|
// return new ZodObject({
|
|
// ...this._def,
|
|
// shape: () => ({
|
|
// ...this._def.shape(),
|
|
// ...augmentation,
|
|
// }),
|
|
// }) as any;
|
|
// }
|
|
/**
|
|
* @deprecated Use `.extend` instead
|
|
* */
|
|
this.augment = this.extend;
|
|
}
|
|
_getCached() {
|
|
if (this._cached !== null)
|
|
return this._cached;
|
|
const shape = this._def.shape();
|
|
const keys = util.objectKeys(shape);
|
|
return (this._cached = { shape, keys });
|
|
}
|
|
_parse(input) {
|
|
const parsedType = this._getType(input);
|
|
if (parsedType !== ZodParsedType.object) {
|
|
const ctx = this._getOrReturnCtx(input);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_type,
|
|
expected: ZodParsedType.object,
|
|
received: ctx.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 {
|
|
// run catchall validation
|
|
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;
|
|
syncPairs.push({
|
|
key,
|
|
value: await pair.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 !== undefined
|
|
? {
|
|
errorMap: (issue, ctx) => {
|
|
var _a, _b, _c, _d;
|
|
const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError;
|
|
if (issue.code === "unrecognized_keys")
|
|
return {
|
|
message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : 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 = {};
|
|
util.objectKeys(mask).forEach((key) => {
|
|
if (mask[key] && this.shape[key]) {
|
|
shape[key] = this.shape[key];
|
|
}
|
|
});
|
|
return new ZodObject({
|
|
...this._def,
|
|
shape: () => shape,
|
|
});
|
|
}
|
|
omit(mask) {
|
|
const shape = {};
|
|
util.objectKeys(this.shape).forEach((key) => {
|
|
if (!mask[key]) {
|
|
shape[key] = this.shape[key];
|
|
}
|
|
});
|
|
return new ZodObject({
|
|
...this._def,
|
|
shape: () => shape,
|
|
});
|
|
}
|
|
/**
|
|
* @deprecated
|
|
*/
|
|
deepPartial() {
|
|
return deepPartialify(this);
|
|
}
|
|
partial(mask) {
|
|
const newShape = {};
|
|
util.objectKeys(this.shape).forEach((key) => {
|
|
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 = {};
|
|
util.objectKeys(this.shape).forEach((key) => {
|
|
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),
|
|
});
|
|
};
|
|
class ZodUnion extends ZodType {
|
|
_parse(input) {
|
|
const { ctx } = this._processInputParams(input);
|
|
const options = this._def.options;
|
|
function handleResults(results) {
|
|
// return first issue-free validation if it exists
|
|
for (const result of results) {
|
|
if (result.result.status === "valid") {
|
|
return result.result;
|
|
}
|
|
}
|
|
for (const result of results) {
|
|
if (result.result.status === "dirty") {
|
|
// add issues from dirty option
|
|
ctx.common.issues.push(...result.ctx.common.issues);
|
|
return result.result;
|
|
}
|
|
}
|
|
// return invalid
|
|
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 = undefined;
|
|
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((issues) => new ZodError(issues));
|
|
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),
|
|
});
|
|
};
|
|
/////////////////////////////////////////////////////
|
|
/////////////////////////////////////////////////////
|
|
////////// //////////
|
|
////////// ZodDiscriminatedUnion //////////
|
|
////////// //////////
|
|
/////////////////////////////////////////////////////
|
|
/////////////////////////////////////////////////////
|
|
const 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) {
|
|
// eslint-disable-next-line ban/ban
|
|
return Object.keys(type.enum);
|
|
}
|
|
else if (type instanceof ZodDefault) {
|
|
return getDiscriminator(type._def.innerType);
|
|
}
|
|
else if (type instanceof ZodUndefined) {
|
|
return [undefined];
|
|
}
|
|
else if (type instanceof ZodNull) {
|
|
return [null];
|
|
}
|
|
else {
|
|
return null;
|
|
}
|
|
};
|
|
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) {
|
|
// Get all the valid discriminator values
|
|
const optionsMap = new Map();
|
|
// try {
|
|
for (const type of options) {
|
|
const discriminatorValues = getDiscriminator(type.shape[discriminator]);
|
|
if (!discriminatorValues) {
|
|
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 };
|
|
}
|
|
}
|
|
class ZodIntersection 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: left,
|
|
right: right,
|
|
typeName: ZodFirstPartyTypeKind.ZodIntersection,
|
|
...processCreateParams(params),
|
|
});
|
|
};
|
|
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); // filter nulls
|
|
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),
|
|
});
|
|
};
|
|
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)),
|
|
});
|
|
}
|
|
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),
|
|
});
|
|
}
|
|
}
|
|
class ZodMap extends ZodType {
|
|
_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 = 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 = 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),
|
|
});
|
|
};
|
|
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(elements) {
|
|
const parsedSet = new Set();
|
|
for (const element of elements) {
|
|
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((elements) => finalizeSet(elements));
|
|
}
|
|
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),
|
|
});
|
|
};
|
|
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(),
|
|
errorMap,
|
|
].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(),
|
|
errorMap,
|
|
].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) {
|
|
return OK(async (...args) => {
|
|
const error = new ZodError([]);
|
|
const parsedArgs = await this._def.args
|
|
.parseAsync(args, params)
|
|
.catch((e) => {
|
|
error.addIssue(makeArgsIssue(args, e));
|
|
throw error;
|
|
});
|
|
const result = await fn(...parsedArgs);
|
|
const parsedReturns = await this._def.returns._def.type
|
|
.parseAsync(result, params)
|
|
.catch((e) => {
|
|
error.addIssue(makeReturnsIssue(result, e));
|
|
throw error;
|
|
});
|
|
return parsedReturns;
|
|
});
|
|
}
|
|
else {
|
|
return OK((...args) => {
|
|
const parsedArgs = this._def.args.safeParse(args, params);
|
|
if (!parsedArgs.success) {
|
|
throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
|
|
}
|
|
const result = fn(...parsedArgs.data);
|
|
const parsedReturns = this._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),
|
|
});
|
|
}
|
|
}
|
|
class ZodLazy 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: getter,
|
|
typeName: ZodFirstPartyTypeKind.ZodLazy,
|
|
...processCreateParams(params),
|
|
});
|
|
};
|
|
class ZodLiteral 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: value,
|
|
typeName: ZodFirstPartyTypeKind.ZodLiteral,
|
|
...processCreateParams(params),
|
|
});
|
|
};
|
|
function createZodEnum(values, params) {
|
|
return new ZodEnum({
|
|
values: values,
|
|
typeName: ZodFirstPartyTypeKind.ZodEnum,
|
|
...processCreateParams(params),
|
|
});
|
|
}
|
|
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._def.values.indexOf(input.data) === -1) {
|
|
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) {
|
|
return ZodEnum.create(values);
|
|
}
|
|
exclude(values) {
|
|
return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)));
|
|
}
|
|
}
|
|
ZodEnum.create = createZodEnum;
|
|
class ZodNativeEnum 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 (nativeEnumValues.indexOf(input.data) === -1) {
|
|
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: values,
|
|
typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
|
|
...processCreateParams(params),
|
|
});
|
|
};
|
|
class ZodPromise 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),
|
|
});
|
|
};
|
|
class ZodEffects 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;
|
|
if (effect.type === "preprocess") {
|
|
const processed = effect.transform(ctx.data);
|
|
if (ctx.common.async) {
|
|
return Promise.resolve(processed).then((processed) => {
|
|
return this._def.schema._parseAsync({
|
|
data: processed,
|
|
path: ctx.path,
|
|
parent: ctx,
|
|
});
|
|
});
|
|
}
|
|
else {
|
|
return this._def.schema._parseSync({
|
|
data: processed,
|
|
path: ctx.path,
|
|
parent: ctx,
|
|
});
|
|
}
|
|
}
|
|
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 === "refinement") {
|
|
const executeRefinement = (acc
|
|
// effect: RefinementEffect<any>
|
|
) => {
|
|
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();
|
|
// return value is ignored
|
|
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 base;
|
|
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 base;
|
|
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),
|
|
});
|
|
};
|
|
class ZodOptional extends ZodType {
|
|
_parse(input) {
|
|
const parsedType = this._getType(input);
|
|
if (parsedType === ZodParsedType.undefined) {
|
|
return OK(undefined);
|
|
}
|
|
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),
|
|
});
|
|
};
|
|
class ZodNullable 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),
|
|
});
|
|
};
|
|
class ZodDefault 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),
|
|
});
|
|
};
|
|
class ZodCatch extends ZodType {
|
|
_parse(input) {
|
|
const { ctx } = this._processInputParams(input);
|
|
// newCtx is used to not collect issues from inner types in ctx
|
|
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((result) => {
|
|
return {
|
|
status: "valid",
|
|
value: result.status === "valid"
|
|
? result.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),
|
|
});
|
|
};
|
|
class ZodNaN 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),
|
|
});
|
|
};
|
|
const BRAND = Symbol("zod_brand");
|
|
class ZodBranded 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;
|
|
}
|
|
}
|
|
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,
|
|
});
|
|
}
|
|
}
|
|
const custom = (check, params = {},
|
|
/*
|
|
* @deprecated
|
|
*
|
|
* Pass `fatal` into the params object instead:
|
|
*
|
|
* ```ts
|
|
* z.string().custom((val) => val.length > 5, { fatal: false })
|
|
* ```
|
|
*
|
|
*/
|
|
fatal) => {
|
|
if (check)
|
|
return ZodAny.create().superRefine((data, ctx) => {
|
|
var _a, _b;
|
|
if (!check(data)) {
|
|
const p = typeof params === "function"
|
|
? params(data)
|
|
: typeof params === "string"
|
|
? { message: params }
|
|
: params;
|
|
const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true;
|
|
const p2 = typeof p === "string" ? { message: p } : p;
|
|
ctx.addIssue({ code: "custom", ...p2, fatal: _fatal });
|
|
}
|
|
});
|
|
return ZodAny.create();
|
|
};
|
|
const late = {
|
|
object: ZodObject.lazycreate,
|
|
};
|
|
var ZodFirstPartyTypeKind;
|
|
(function (ZodFirstPartyTypeKind) {
|
|
ZodFirstPartyTypeKind["ZodString"] = "ZodString";
|
|
ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber";
|
|
ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN";
|
|
ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt";
|
|
ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean";
|
|
ZodFirstPartyTypeKind["ZodDate"] = "ZodDate";
|
|
ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol";
|
|
ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined";
|
|
ZodFirstPartyTypeKind["ZodNull"] = "ZodNull";
|
|
ZodFirstPartyTypeKind["ZodAny"] = "ZodAny";
|
|
ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown";
|
|
ZodFirstPartyTypeKind["ZodNever"] = "ZodNever";
|
|
ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid";
|
|
ZodFirstPartyTypeKind["ZodArray"] = "ZodArray";
|
|
ZodFirstPartyTypeKind["ZodObject"] = "ZodObject";
|
|
ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion";
|
|
ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
|
|
ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection";
|
|
ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple";
|
|
ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord";
|
|
ZodFirstPartyTypeKind["ZodMap"] = "ZodMap";
|
|
ZodFirstPartyTypeKind["ZodSet"] = "ZodSet";
|
|
ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction";
|
|
ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy";
|
|
ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral";
|
|
ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum";
|
|
ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects";
|
|
ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum";
|
|
ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional";
|
|
ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable";
|
|
ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault";
|
|
ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch";
|
|
ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise";
|
|
ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
|
|
ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline";
|
|
})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
|
|
const instanceOfType = (
|
|
// const instanceOfType = <T extends new (...args: any[]) => any>(
|
|
cls, params = {
|
|
message: `Input not instance of ${cls.name}`,
|
|
}) => custom((data) => data instanceof cls, params);
|
|
const stringType = ZodString.create;
|
|
const numberType = ZodNumber.create;
|
|
const nanType = ZodNaN.create;
|
|
const bigIntType = ZodBigInt.create;
|
|
const booleanType = ZodBoolean.create;
|
|
const dateType = ZodDate.create;
|
|
const symbolType = ZodSymbol.create;
|
|
const undefinedType = ZodUndefined.create;
|
|
const nullType = ZodNull.create;
|
|
const anyType = ZodAny.create;
|
|
const unknownType = ZodUnknown.create;
|
|
const neverType = ZodNever.create;
|
|
const voidType = ZodVoid.create;
|
|
const arrayType = ZodArray.create;
|
|
const objectType = ZodObject.create;
|
|
const strictObjectType = ZodObject.strictCreate;
|
|
const unionType = ZodUnion.create;
|
|
const discriminatedUnionType = ZodDiscriminatedUnion.create;
|
|
const intersectionType = ZodIntersection.create;
|
|
const tupleType = ZodTuple.create;
|
|
const recordType = ZodRecord.create;
|
|
const mapType = ZodMap.create;
|
|
const setType = ZodSet.create;
|
|
const functionType = ZodFunction.create;
|
|
const lazyType = ZodLazy.create;
|
|
const literalType = ZodLiteral.create;
|
|
const enumType = ZodEnum.create;
|
|
const nativeEnumType = ZodNativeEnum.create;
|
|
const promiseType = ZodPromise.create;
|
|
const effectsType = ZodEffects.create;
|
|
const optionalType = ZodOptional.create;
|
|
const nullableType = ZodNullable.create;
|
|
const preprocessType = ZodEffects.createWithPreprocess;
|
|
const pipelineType = ZodPipeline.create;
|
|
const ostring = () => stringType().optional();
|
|
const onumber = () => numberType().optional();
|
|
const oboolean = () => booleanType().optional();
|
|
const 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 })),
|
|
};
|
|
const NEVER = INVALID;
|
|
|
|
var z = /*#__PURE__*/Object.freeze({
|
|
__proto__: null,
|
|
defaultErrorMap: errorMap,
|
|
setErrorMap: setErrorMap,
|
|
getErrorMap: getErrorMap,
|
|
makeIssue: makeIssue,
|
|
EMPTY_PATH: EMPTY_PATH,
|
|
addIssueToContext: addIssueToContext,
|
|
ParseStatus: ParseStatus,
|
|
INVALID: INVALID,
|
|
DIRTY: DIRTY,
|
|
OK: OK,
|
|
isAborted: isAborted,
|
|
isDirty: isDirty,
|
|
isValid: isValid,
|
|
isAsync: isAsync,
|
|
get util () { return util; },
|
|
get objectUtil () { return objectUtil; },
|
|
ZodParsedType: ZodParsedType,
|
|
getParsedType: getParsedType,
|
|
ZodType: ZodType,
|
|
ZodString: ZodString,
|
|
ZodNumber: ZodNumber,
|
|
ZodBigInt: ZodBigInt,
|
|
ZodBoolean: ZodBoolean,
|
|
ZodDate: ZodDate,
|
|
ZodSymbol: ZodSymbol,
|
|
ZodUndefined: ZodUndefined,
|
|
ZodNull: ZodNull,
|
|
ZodAny: ZodAny,
|
|
ZodUnknown: ZodUnknown,
|
|
ZodNever: ZodNever,
|
|
ZodVoid: ZodVoid,
|
|
ZodArray: ZodArray,
|
|
ZodObject: ZodObject,
|
|
ZodUnion: ZodUnion,
|
|
ZodDiscriminatedUnion: ZodDiscriminatedUnion,
|
|
ZodIntersection: ZodIntersection,
|
|
ZodTuple: ZodTuple,
|
|
ZodRecord: ZodRecord,
|
|
ZodMap: ZodMap,
|
|
ZodSet: ZodSet,
|
|
ZodFunction: ZodFunction,
|
|
ZodLazy: ZodLazy,
|
|
ZodLiteral: ZodLiteral,
|
|
ZodEnum: ZodEnum,
|
|
ZodNativeEnum: ZodNativeEnum,
|
|
ZodPromise: ZodPromise,
|
|
ZodEffects: ZodEffects,
|
|
ZodTransformer: ZodEffects,
|
|
ZodOptional: ZodOptional,
|
|
ZodNullable: ZodNullable,
|
|
ZodDefault: ZodDefault,
|
|
ZodCatch: ZodCatch,
|
|
ZodNaN: ZodNaN,
|
|
BRAND: BRAND,
|
|
ZodBranded: ZodBranded,
|
|
ZodPipeline: ZodPipeline,
|
|
custom: custom,
|
|
Schema: ZodType,
|
|
ZodSchema: ZodType,
|
|
late: late,
|
|
get ZodFirstPartyTypeKind () { return ZodFirstPartyTypeKind; },
|
|
coerce: coerce,
|
|
any: anyType,
|
|
array: arrayType,
|
|
bigint: bigIntType,
|
|
boolean: booleanType,
|
|
date: dateType,
|
|
discriminatedUnion: discriminatedUnionType,
|
|
effect: effectsType,
|
|
'enum': enumType,
|
|
'function': functionType,
|
|
'instanceof': instanceOfType,
|
|
intersection: intersectionType,
|
|
lazy: lazyType,
|
|
literal: literalType,
|
|
map: mapType,
|
|
nan: nanType,
|
|
nativeEnum: nativeEnumType,
|
|
never: neverType,
|
|
'null': nullType,
|
|
nullable: nullableType,
|
|
number: numberType,
|
|
object: objectType,
|
|
oboolean: oboolean,
|
|
onumber: onumber,
|
|
optional: optionalType,
|
|
ostring: ostring,
|
|
pipeline: pipelineType,
|
|
preprocess: preprocessType,
|
|
promise: promiseType,
|
|
record: recordType,
|
|
set: setType,
|
|
strictObject: strictObjectType,
|
|
string: stringType,
|
|
symbol: symbolType,
|
|
transformer: effectsType,
|
|
tuple: tupleType,
|
|
'undefined': undefinedType,
|
|
union: unionType,
|
|
unknown: unknownType,
|
|
'void': voidType,
|
|
NEVER: NEVER,
|
|
ZodIssueCode: ZodIssueCode,
|
|
quotelessJson: quotelessJson,
|
|
ZodError: ZodError
|
|
});
|
|
|
|
|
|
|
|
;// CONCATENATED MODULE: ./src/tests/mock-server.ts
|
|
|
|
|
|
|
|
|
|
async function run() {
|
|
const hostname = '127.0.0.1';
|
|
const app = createApp({ debug: false });
|
|
const router = dist_createRouter().post('/api/v1/functions/functionid/versions', eventHandler(async (event) => {
|
|
try {
|
|
const body = await readBody(event);
|
|
FunctionVersionRequestSchema.parse(body); // throw error if invalid
|
|
event.node.res.statusCode = 201;
|
|
event.node.res.statusMessage = 'Created';
|
|
event.node.res.setHeader('Content-Type', 'application/json');
|
|
}
|
|
catch (err) {
|
|
sendError(event, createError({
|
|
status: 422,
|
|
statusText: `Unprocessable Entity. ${err instanceof Error ? err.message : JSON.stringify(err)}`
|
|
}));
|
|
}
|
|
return {
|
|
versionId: 'minimalversionid'
|
|
};
|
|
}));
|
|
app.use(router);
|
|
const port = await getPort(3000);
|
|
listen(toNodeListener(app), {
|
|
hostname,
|
|
port
|
|
});
|
|
}
|
|
run();
|
|
// copied as of commit 2e04a81dea7f9ee079d17617d4e5fed6b2192211
|
|
const FunctionVersionRequestSchema = z.object({
|
|
commitId: z.string(),
|
|
versionTag: z.string(),
|
|
inputSchema: z.record(z.string(), z.unknown()),
|
|
command: z.array(z.string().nonempty()),
|
|
annotations: z.object({
|
|
'speckle.systems/v1alpha1/publishing/status': z["enum"](['publish', 'draft', 'archive'], {
|
|
description: 'Whether this Function is published (and should appear in the library), a draft, or archived.'
|
|
})
|
|
.default('draft'),
|
|
'speckle.systems/v1alpha1/author': z.string({
|
|
description: 'The name of the authoring organization or individual of this Function.'
|
|
})
|
|
.optional(),
|
|
'speckle.systems/v1alpha1/license': z["enum"](['MIT', 'BSD', 'Apache-2.0', 'MPL', 'CC0', 'Unlicense'], {
|
|
description: 'The license under under which this Function is made available. This must match the license in the source code repository.'
|
|
})
|
|
.optional(),
|
|
'speckle.systems/v1alpha1/website': z.string({
|
|
description: 'The marketing website for this Function or its authors.'
|
|
})
|
|
.url()
|
|
.optional(),
|
|
'speckle.systems/v1alpha1/documentation': z.string({
|
|
description: 'The documentation website for this function. For example, this could be a url to the README in the source code repository.'
|
|
})
|
|
.url()
|
|
.optional(),
|
|
'speckle.systems/v1alpha1/keywords': z.string({
|
|
description: 'Comma separated list of keywords used for categorizing this function.'
|
|
})
|
|
.optional(),
|
|
'speckle.systems/v1alpha1/description': z.string().optional()
|
|
})
|
|
.optional()
|
|
});
|
|
|
|
})();
|
|
|
|
var __webpack_exports__FunctionVersionRequestSchema = __webpack_exports__.E;
|
|
export { __webpack_exports__FunctionVersionRequestSchema as FunctionVersionRequestSchema };
|
|
|
|
//# sourceMappingURL=index.js.map
|