diff --git a/Cargo.lock b/Cargo.lock index ab4c807..d233082 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -526,6 +526,7 @@ name = "bsnext_example" version = "0.1.0" dependencies = [ "bsnext_input", + "bsnext_md", "clap", ] @@ -556,11 +557,9 @@ dependencies = [ "bsnext_tracing", "clap", "insta", - "markdown", "matchit", "miette", "mime_guess", - "nom", "random_word", "serde", "serde_json", @@ -569,6 +568,22 @@ dependencies = [ "toml", ] +[[package]] +name = "bsnext_md" +version = "0.1.0" +dependencies = [ + "anyhow", + "bsnext_input", + "insta", + "markdown", + "mime_guess", + "nom", + "serde", + "serde_json", + "serde_yaml", + "thiserror", +] + [[package]] name = "bsnext_output" version = "0.1.0" @@ -618,8 +633,10 @@ dependencies = [ "bsnext_example", "bsnext_fs", "bsnext_input", + "bsnext_md", "bsnext_output", "bsnext_tracing", + "bsnext_yaml", "clap", "insta", "rand", @@ -650,6 +667,16 @@ dependencies = [ "hyper-util", ] +[[package]] +name = "bsnext_yaml" +version = "0.1.0" +dependencies = [ + "bsnext_input", + "miette", + "serde", + "serde_yaml", +] + [[package]] name = "bumpalo" version = "3.16.0" diff --git a/Cargo.toml b/Cargo.toml index f224973..f7d1b6a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -38,7 +38,7 @@ insta = { version = "1.38.0", features = ["yaml"] } miette = { version = "7.2.0", features = ["fancy", "syntect-highlighter"] } [profile.release] -strip = true # Automatically strip symbols from the binary. +strip = true opt-level = "z" lto = true codegen-units = 1 diff --git a/crates/bsnext_client/inject/.gitignore b/crates/bsnext_client/inject/.gitignore new file mode 100644 index 0000000..5d1f533 --- /dev/null +++ b/crates/bsnext_client/inject/.gitignore @@ -0,0 +1 @@ +dist/meta.json \ No newline at end of file diff --git a/crates/bsnext_client/inject/dist/index.js b/crates/bsnext_client/inject/dist/index.js index 3316a2c..48e4ee5 100644 --- a/crates/bsnext_client/inject/dist/index.js +++ b/crates/bsnext_client/inject/dist/index.js @@ -1,6682 +1,7 @@ -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __commonJS = (cb, mod) => function __require() { - return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); - -// ../vendor/live-reload/src/timer.js -var require_timer = __commonJS({ - "../vendor/live-reload/src/timer.js"(exports) { - "use strict"; - var Timer2 = class { - constructor(func) { - this.func = func; - this.running = false; - this.id = null; - this._handler = () => { - this.running = false; - this.id = null; - return this.func(); - }; - } - start(timeout) { - if (this.running) { - clearTimeout( - /** @type {any} */ - this.id - ); - } - this.id = setTimeout(this._handler, timeout); - this.running = true; - } - stop() { - if (this.running) { - clearTimeout( - /** @type {any} */ - this.id - ); - this.running = false; - this.id = null; - } - } - }; - Timer2.start = (timeout, func) => setTimeout(func, timeout); - exports.Timer = Timer2; - } -}); - -// ../vendor/live-reload/src/reloader.js -var IMAGE_STYLES = [ - { selector: "background", styleNames: ["backgroundImage"] }, - { selector: "border", styleNames: ["borderImage", "webkitBorderImage", "MozBorderImage"] } -]; -var DEFAULT_OPTIONS = { - stylesheetReloadTimeout: 15e3 -}; -var IMAGES_REGEX = /\.(jpe?g|png|gif|svg)$/i; -var Reloader = class { - /** - * @param window - * @param {Pick} console - * @param Timer - */ - constructor(window2, console2, Timer2) { - this.window = window2; - this.console = console2; - this.Timer = Timer2; - this.document = this.window.document; - this.importCacheWaitPeriod = 200; - this.plugins = []; - } - addPlugin(plugin) { - return this.plugins.push(plugin); - } - analyze(callback) { - } - reload(path, options = {}) { - this.options = { - ...DEFAULT_OPTIONS, - ...options - }; - if (options.liveCSS && path.match(/\.css(?:\.map)?$/i)) { - if (this.reloadStylesheet(path)) { - return; - } - } - if (options.liveImg && path.match(IMAGES_REGEX)) { - this.reloadImages(path); - return; - } - if (options.isChromeExtension) { - this.reloadChromeExtension(); - return; - } - return this.reloadPage(); - } - reloadPage() { - return this.window.document.location.reload(); - } - reloadChromeExtension() { - return this.window.chrome.runtime.reload(); - } - reloadImages(path) { - let img; - const expando = this.generateUniqueString(); - for (img of Array.from(this.document.images)) { - if (pathsMatch(path, pathFromUrl(img.src))) { - img.src = this.generateCacheBustUrl(img.src, expando); - } - } - if (this.document.querySelectorAll) { - for (const { selector, styleNames } of IMAGE_STYLES) { - for (img of Array.from(this.document.querySelectorAll(`[style*=${selector}]`))) { - this.reloadStyleImages(img.style, styleNames, path, expando); - } - } - } - if (this.document.styleSheets) { - return Array.from(this.document.styleSheets).map( - (styleSheet) => this.reloadStylesheetImages(styleSheet, path, expando) - ); - } - } - reloadStylesheetImages(styleSheet, path, expando) { - let rules; - try { - rules = (styleSheet || {}).cssRules; - } catch (e) { - } - if (!rules) { - return; - } - for (const rule of Array.from(rules)) { - switch (rule.type) { - case CSSRule.IMPORT_RULE: - this.reloadStylesheetImages(rule.styleSheet, path, expando); - break; - case CSSRule.STYLE_RULE: - for (const { styleNames } of IMAGE_STYLES) { - this.reloadStyleImages(rule.style, styleNames, path, expando); - } - break; - case CSSRule.MEDIA_RULE: - this.reloadStylesheetImages(rule, path, expando); - break; - } - } - } - reloadStyleImages(style, styleNames, path, expando) { - for (const styleName of styleNames) { - const value = style[styleName]; - if (typeof value === "string") { - const newValue = value.replace(new RegExp("\\burl\\s*\\(([^)]*)\\)"), (match, src) => { - if (pathsMatch(path, pathFromUrl(src))) { - return `url(${this.generateCacheBustUrl(src, expando)})`; - } - return match; - }); - if (newValue !== value) { - style[styleName] = newValue; - } - } - } - } - reloadStylesheet(path) { - const options = this.options || DEFAULT_OPTIONS; - let style; - let link; - const links = (() => { - const result = []; - for (link of Array.from(this.document.getElementsByTagName("link"))) { - if (link.rel.match(/^stylesheet$/i) && !link.__LiveReload_pendingRemoval) { - result.push(link); - } - } - return result; - })(); - const imported = []; - for (style of Array.from(this.document.getElementsByTagName("style"))) { - if (style.sheet) { - this.collectImportedStylesheets(style, style.sheet, imported); - } - } - for (link of Array.from(links)) { - this.collectImportedStylesheets(link, link.sheet, imported); - } - if (this.window.StyleFix && this.document.querySelectorAll) { - for (style of Array.from(this.document.querySelectorAll("style[data-href]"))) { - links.push(style); - } - } - this.console.debug(`found ${links.length} LINKed stylesheets, ${imported.length} @imported stylesheets`); - const match = pickBestMatch( - path, - links.concat(imported), - (link2) => pathFromUrl(this.linkHref(link2)) - ); - if (match) { - if (match.object.rule) { - this.console.debug(`is reloading imported stylesheet: ${match.object.href}`); - this.reattachImportedRule(match.object); - } else { - this.console.debug(`is reloading stylesheet: ${this.linkHref(match.object)}`); - this.reattachStylesheetLink(match.object); - } - } else { - if (options.reloadMissingCSS) { - this.console.debug( - `will reload all stylesheets because path '${path}' did not match any specific one. To disable this behavior, set 'options.reloadMissingCSS' to 'false'.` - ); - for (link of Array.from(links)) { - this.reattachStylesheetLink(link); - } - } else { - this.console.debug( - `will not reload path '${path}' because the stylesheet was not found on the page and 'options.reloadMissingCSS' was set to 'false'.` - ); - } - } - return true; - } - collectImportedStylesheets(link, styleSheet, result) { - let rules; - try { - rules = (styleSheet || {}).cssRules; - } catch (e) { - } - if (rules && rules.length) { - for (let index = 0; index < rules.length; index++) { - const rule = rules[index]; - switch (rule.type) { - case CSSRule.CHARSET_RULE: - continue; - case CSSRule.IMPORT_RULE: - result.push({ link, rule, index, href: rule.href }); - this.collectImportedStylesheets(link, rule.styleSheet, result); - break; - default: - break; - } - } - } - } - waitUntilCssLoads(clone, func) { - const options = this.options || DEFAULT_OPTIONS; - let callbackExecuted = false; - const executeCallback = () => { - if (callbackExecuted) { - return; - } - callbackExecuted = true; - return func(); - }; - clone.onload = () => { - this.console.debug("the new stylesheet has finished loading"); - this.knownToSupportCssOnLoad = true; - return executeCallback(); - }; - if (!this.knownToSupportCssOnLoad) { - let poll; - (poll = () => { - if (clone.sheet) { - this.console.debug("is polling until the new CSS finishes loading..."); - return executeCallback(); - } - return this.Timer.start(50, poll); - })(); - } - return this.Timer.start(options.stylesheetReloadTimeout, executeCallback); - } - linkHref(link) { - return link.href || link.getAttribute && link.getAttribute("data-href"); - } - reattachStylesheetLink(link) { - let clone; - if (link.__LiveReload_pendingRemoval) { - return; - } - link.__LiveReload_pendingRemoval = true; - if (link.tagName === "STYLE") { - clone = this.document.createElement("link"); - clone.rel = "stylesheet"; - clone.media = link.media; - clone.disabled = link.disabled; - } else { - clone = link.cloneNode(false); - } - clone.href = this.generateCacheBustUrl(this.linkHref(link)); - const parent = link.parentNode; - if (parent.lastChild === link) { - parent.appendChild(clone); - } else { - parent.insertBefore(clone, link.nextSibling); - } - return this.waitUntilCssLoads(clone, () => { - let additionalWaitingTime; - if (/AppleWebKit/.test(this.window.navigator.userAgent)) { - additionalWaitingTime = 5; - } else { - additionalWaitingTime = 200; - } - return this.Timer.start(additionalWaitingTime, () => { - if (!link.parentNode) { - return; - } - link.parentNode.removeChild(link); - clone.onreadystatechange = null; - return this.window.StyleFix ? this.window.StyleFix.link(clone) : void 0; - }); - }); - } - reattachImportedRule({ rule, index, link }) { - const parent = rule.parentStyleSheet; - const href = this.generateCacheBustUrl(rule.href); - const media = rule.media.length ? [].join.call(rule.media, ", ") : ""; - const newRule = `@import url("${href}") ${media};`; - rule.__LiveReload_newHref = href; - const tempLink = this.document.createElement("link"); - tempLink.rel = "stylesheet"; - tempLink.href = href; - tempLink.__LiveReload_pendingRemoval = true; - if (link.parentNode) { - link.parentNode.insertBefore(tempLink, link); - } - return this.Timer.start(this.importCacheWaitPeriod, () => { - if (tempLink.parentNode) { - tempLink.parentNode.removeChild(tempLink); - } - if (rule.__LiveReload_newHref !== href) { - return; - } - parent.insertRule(newRule, index); - parent.deleteRule(index + 1); - rule = parent.cssRules[index]; - rule.__LiveReload_newHref = href; - return this.Timer.start(this.importCacheWaitPeriod, () => { - if (rule.__LiveReload_newHref !== href) { - return; - } - parent.insertRule(newRule, index); - return parent.deleteRule(index + 1); - }); - }); - } - generateUniqueString() { - return `livereload=${Date.now()}`; - } - generateCacheBustUrl(url2, expando) { - const options = this.options || DEFAULT_OPTIONS; - let hash, oldParams; - if (!expando) { - expando = this.generateUniqueString(); - } - ({ url: url2, hash, params: oldParams } = splitUrl(url2)); - if (options.overrideURL) { - if (url2.indexOf(options.serverURL) < 0) { - const originalUrl = url2; - url2 = options.serverURL + options.overrideURL + "?url=" + encodeURIComponent(url2); - this.console.debug(`is overriding source URL ${originalUrl} with ${url2}`); - } - } - let params = oldParams.replace(/(\?|&)livereload=(\d+)/, (match, sep) => `${sep}${expando}`); - if (params === oldParams) { - if (oldParams.length === 0) { - params = `?${expando}`; - } else { - params = `${oldParams}&${expando}`; - } - } - return url2 + params + hash; - } -}; -function splitUrl(url2) { - let hash = ""; - let params = ""; - let index = url2.indexOf("#"); - if (index >= 0) { - hash = url2.slice(index); - url2 = url2.slice(0, index); - } - const comboSign = url2.indexOf("??"); - if (comboSign >= 0) { - if (comboSign + 1 !== url2.lastIndexOf("?")) { - index = url2.lastIndexOf("?"); - } - } else { - index = url2.indexOf("?"); - } - if (index >= 0) { - params = url2.slice(index); - url2 = url2.slice(0, index); - } - return { url: url2, params, hash }; -} -function pathFromUrl(url2) { - if (!url2) { - return ""; - } - let path; - ({ url: url2 } = splitUrl(url2)); - if (url2.indexOf("file://") === 0) { - path = url2.replace(new RegExp("^file://(localhost)?"), ""); - } else { - path = url2.replace(new RegExp("^([^:]+:)?//([^:/]+)(:\\d*)?/"), "/"); - } - return decodeURIComponent(path); -} -function numberOfMatchingSegments(left, right) { - left = left.replace(/^\/+/, "").toLowerCase(); - right = right.replace(/^\/+/, "").toLowerCase(); - if (left === right) { - return 1e4; - } - const comps1 = left.split(/\/|\\/).reverse(); - const comps2 = right.split(/\/|\\/).reverse(); - const len = Math.min(comps1.length, comps2.length); - let eqCount = 0; - while (eqCount < len && comps1[eqCount] === comps2[eqCount]) { - ++eqCount; - } - return eqCount; -} -function pickBestMatch(path, objects, pathFunc = (s) => s) { - let score; - let bestMatch = { score: 0 }; - for (const object of objects) { - score = numberOfMatchingSegments(path, pathFunc(object)); - if (score > bestMatch.score) { - bestMatch = { object, score }; - } - } - if (bestMatch.score === 0) { - return null; - } - return bestMatch; -} -function pathsMatch(left, right) { - return numberOfMatchingSegments(left, right) > 0; -} - -// src/index.ts -var import_timer2 = __toESM(require_timer()); - -// ../../../node_modules/tslib/tslib.es6.mjs -var extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) { - d2.__proto__ = b2; - } || function(d2, b2) { - for (var p in b2) - if (Object.prototype.hasOwnProperty.call(b2, p)) - d2[p] = b2[p]; - }; - return extendStatics(d, b); -}; -function __extends(d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { - this.constructor = d; - } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -} -var __assign = function() { - __assign = Object.assign || function __assign2(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) - if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); -}; -function __awaiter(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -} -function __generator(thisArg, body) { - var _ = { label: 0, sent: function() { - if (t[0] & 1) - throw t[1]; - return t[1]; - }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { - return this; - }), g; - function verb(n) { - return function(v) { - return step([n, v]); - }; - } - function step(op) { - if (f) - throw new TypeError("Generator is already executing."); - while (g && (g = 0, op[0] && (_ = 0)), _) - try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) - return t; - if (y = 0, t) - op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: - case 1: - t = op; - break; - case 4: - _.label++; - return { value: op[1], done: false }; - case 5: - _.label++; - y = op[1]; - op = [0]; - continue; - case 7: - op = _.ops.pop(); - _.trys.pop(); - continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { - _ = 0; - continue; - } - if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { - _.label = op[1]; - break; - } - if (op[0] === 6 && _.label < t[1]) { - _.label = t[1]; - t = op; - break; - } - if (t && _.label < t[2]) { - _.label = t[2]; - _.ops.push(op); - break; - } - if (t[2]) - _.ops.pop(); - _.trys.pop(); - continue; - } - op = body.call(thisArg, _); - } catch (e) { - op = [6, e]; - y = 0; - } finally { - f = t = 0; - } - if (op[0] & 5) - throw op[1]; - return { value: op[0] ? op[1] : void 0, done: true }; - } -} -function __values(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) - return m.call(o); - if (o && typeof o.length === "number") - return { - next: function() { - if (o && i >= o.length) - o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); -} -function __read(o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) - return o; - var i = m.call(o), r2, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r2 = i.next()).done) - ar.push(r2.value); - } catch (error) { - e = { error }; - } finally { - try { - if (r2 && !r2.done && (m = i["return"])) - m.call(i); - } finally { - if (e) - throw e.error; - } - } - return ar; -} -function __spreadArray(to, from, pack) { - if (pack || arguments.length === 2) - for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) - ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); -} -function __await(v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); -} -function __asyncGenerator(thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) - throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function() { - return this; - }, i; - function awaitReturn(f) { - return function(v) { - return Promise.resolve(v).then(f, reject); - }; - } - function verb(n, f) { - if (g[n]) { - i[n] = function(v) { - return new Promise(function(a, b) { - q.push([n, v, a, b]) > 1 || resume(n, v); - }); - }; - if (f) - i[n] = f(i[n]); - } - } - function resume(n, v) { - try { - step(g[n](v)); - } catch (e) { - settle(q[0][3], e); - } - } - function step(r2) { - r2.value instanceof __await ? Promise.resolve(r2.value.v).then(fulfill, reject) : settle(q[0][2], r2); - } - function fulfill(value) { - resume("next", value); - } - function reject(value) { - resume("throw", value); - } - function settle(f, v) { - if (f(v), q.shift(), q.length) - resume(q[0][0], q[0][1]); - } -} -function __asyncValues(o) { - if (!Symbol.asyncIterator) - throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { - return this; - }, i); - function verb(n) { - i[n] = o[n] && function(v) { - return new Promise(function(resolve, reject) { - v = o[n](v), settle(resolve, reject, v.done, v.value); - }); - }; - } - function settle(resolve, reject, d, v) { - Promise.resolve(v).then(function(v2) { - resolve({ value: v2, done: d }); - }, reject); - } -} - -// ../../../node_modules/rxjs/dist/esm5/internal/util/isFunction.js -function isFunction(value) { - return typeof value === "function"; -} - -// ../../../node_modules/rxjs/dist/esm5/internal/util/createErrorClass.js -function createErrorClass(createImpl) { - var _super = function(instance) { - Error.call(instance); - instance.stack = new Error().stack; - }; - var ctorFunc = createImpl(_super); - ctorFunc.prototype = Object.create(Error.prototype); - ctorFunc.prototype.constructor = ctorFunc; - return ctorFunc; -} - -// ../../../node_modules/rxjs/dist/esm5/internal/util/UnsubscriptionError.js -var UnsubscriptionError = createErrorClass(function(_super) { - return function UnsubscriptionErrorImpl(errors) { - _super(this); - this.message = errors ? errors.length + " errors occurred during unsubscription:\n" + errors.map(function(err, i) { - return i + 1 + ") " + err.toString(); - }).join("\n ") : ""; - this.name = "UnsubscriptionError"; - this.errors = errors; - }; -}); - -// ../../../node_modules/rxjs/dist/esm5/internal/util/arrRemove.js -function arrRemove(arr, item) { - if (arr) { - var index = arr.indexOf(item); - 0 <= index && arr.splice(index, 1); - } -} - -// ../../../node_modules/rxjs/dist/esm5/internal/Subscription.js -var Subscription = function() { - function Subscription2(initialTeardown) { - this.initialTeardown = initialTeardown; - this.closed = false; - this._parentage = null; - this._finalizers = null; - } - Subscription2.prototype.unsubscribe = function() { - var e_1, _a, e_2, _b; - var errors; - if (!this.closed) { - this.closed = true; - var _parentage = this._parentage; - if (_parentage) { - this._parentage = null; - if (Array.isArray(_parentage)) { - try { - for (var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) { - var parent_1 = _parentage_1_1.value; - parent_1.remove(this); - } - } catch (e_1_1) { - e_1 = { error: e_1_1 }; - } finally { - try { - if (_parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return)) - _a.call(_parentage_1); - } finally { - if (e_1) - throw e_1.error; - } - } - } else { - _parentage.remove(this); - } - } - var initialFinalizer = this.initialTeardown; - if (isFunction(initialFinalizer)) { - try { - initialFinalizer(); - } catch (e) { - errors = e instanceof UnsubscriptionError ? e.errors : [e]; - } - } - var _finalizers = this._finalizers; - if (_finalizers) { - this._finalizers = null; - try { - for (var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) { - var finalizer = _finalizers_1_1.value; - try { - execFinalizer(finalizer); - } catch (err) { - errors = errors !== null && errors !== void 0 ? errors : []; - if (err instanceof UnsubscriptionError) { - errors = __spreadArray(__spreadArray([], __read(errors)), __read(err.errors)); - } else { - errors.push(err); - } - } - } - } catch (e_2_1) { - e_2 = { error: e_2_1 }; - } finally { - try { - if (_finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return)) - _b.call(_finalizers_1); - } finally { - if (e_2) - throw e_2.error; - } - } - } - if (errors) { - throw new UnsubscriptionError(errors); - } - } - }; - Subscription2.prototype.add = function(teardown) { - var _a; - if (teardown && teardown !== this) { - if (this.closed) { - execFinalizer(teardown); - } else { - if (teardown instanceof Subscription2) { - if (teardown.closed || teardown._hasParent(this)) { - return; - } - teardown._addParent(this); - } - (this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown); - } - } - }; - Subscription2.prototype._hasParent = function(parent) { - var _parentage = this._parentage; - return _parentage === parent || Array.isArray(_parentage) && _parentage.includes(parent); - }; - Subscription2.prototype._addParent = function(parent) { - var _parentage = this._parentage; - this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent; - }; - Subscription2.prototype._removeParent = function(parent) { - var _parentage = this._parentage; - if (_parentage === parent) { - this._parentage = null; - } else if (Array.isArray(_parentage)) { - arrRemove(_parentage, parent); - } - }; - Subscription2.prototype.remove = function(teardown) { - var _finalizers = this._finalizers; - _finalizers && arrRemove(_finalizers, teardown); - if (teardown instanceof Subscription2) { - teardown._removeParent(this); - } - }; - Subscription2.EMPTY = function() { - var empty = new Subscription2(); - empty.closed = true; - return empty; - }(); - return Subscription2; -}(); -var EMPTY_SUBSCRIPTION = Subscription.EMPTY; -function isSubscription(value) { - return value instanceof Subscription || value && "closed" in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe); -} -function execFinalizer(finalizer) { - if (isFunction(finalizer)) { - finalizer(); - } else { - finalizer.unsubscribe(); - } -} - -// ../../../node_modules/rxjs/dist/esm5/internal/config.js -var config = { - onUnhandledError: null, - onStoppedNotification: null, - Promise: void 0, - useDeprecatedSynchronousErrorHandling: false, - useDeprecatedNextContext: false -}; - -// ../../../node_modules/rxjs/dist/esm5/internal/scheduler/timeoutProvider.js -var timeoutProvider = { - setTimeout: function(handler, timeout) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var delegate = timeoutProvider.delegate; - if (delegate === null || delegate === void 0 ? void 0 : delegate.setTimeout) { - return delegate.setTimeout.apply(delegate, __spreadArray([handler, timeout], __read(args))); - } - return setTimeout.apply(void 0, __spreadArray([handler, timeout], __read(args))); - }, - clearTimeout: function(handle) { - var delegate = timeoutProvider.delegate; - return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearTimeout) || clearTimeout)(handle); - }, - delegate: void 0 -}; - -// ../../../node_modules/rxjs/dist/esm5/internal/util/reportUnhandledError.js -function reportUnhandledError(err) { - timeoutProvider.setTimeout(function() { - var onUnhandledError = config.onUnhandledError; - if (onUnhandledError) { - onUnhandledError(err); - } else { - throw err; - } - }); -} - -// ../../../node_modules/rxjs/dist/esm5/internal/util/noop.js -function noop() { -} - -// ../../../node_modules/rxjs/dist/esm5/internal/NotificationFactories.js -var COMPLETE_NOTIFICATION = function() { - return createNotification("C", void 0, void 0); -}(); -function errorNotification(error) { - return createNotification("E", void 0, error); -} -function nextNotification(value) { - return createNotification("N", value, void 0); -} -function createNotification(kind, value, error) { - return { - kind, - value, - error - }; -} - -// ../../../node_modules/rxjs/dist/esm5/internal/util/errorContext.js -var context = null; -function errorContext(cb) { - if (config.useDeprecatedSynchronousErrorHandling) { - var isRoot = !context; - if (isRoot) { - context = { errorThrown: false, error: null }; - } - cb(); - if (isRoot) { - var _a = context, errorThrown = _a.errorThrown, error = _a.error; - context = null; - if (errorThrown) { - throw error; - } - } - } else { - cb(); - } -} -function captureError(err) { - if (config.useDeprecatedSynchronousErrorHandling && context) { - context.errorThrown = true; - context.error = err; - } -} - -// ../../../node_modules/rxjs/dist/esm5/internal/Subscriber.js -var Subscriber = function(_super) { - __extends(Subscriber2, _super); - function Subscriber2(destination) { - var _this = _super.call(this) || this; - _this.isStopped = false; - if (destination) { - _this.destination = destination; - if (isSubscription(destination)) { - destination.add(_this); - } - } else { - _this.destination = EMPTY_OBSERVER; - } - return _this; - } - Subscriber2.create = function(next, error, complete) { - return new SafeSubscriber(next, error, complete); - }; - Subscriber2.prototype.next = function(value) { - if (this.isStopped) { - handleStoppedNotification(nextNotification(value), this); - } else { - this._next(value); - } - }; - Subscriber2.prototype.error = function(err) { - if (this.isStopped) { - handleStoppedNotification(errorNotification(err), this); - } else { - this.isStopped = true; - this._error(err); - } - }; - Subscriber2.prototype.complete = function() { - if (this.isStopped) { - handleStoppedNotification(COMPLETE_NOTIFICATION, this); - } else { - this.isStopped = true; - this._complete(); - } - }; - Subscriber2.prototype.unsubscribe = function() { - if (!this.closed) { - this.isStopped = true; - _super.prototype.unsubscribe.call(this); - this.destination = null; - } - }; - Subscriber2.prototype._next = function(value) { - this.destination.next(value); - }; - Subscriber2.prototype._error = function(err) { - try { - this.destination.error(err); - } finally { - this.unsubscribe(); - } - }; - Subscriber2.prototype._complete = function() { - try { - this.destination.complete(); - } finally { - this.unsubscribe(); - } - }; - return Subscriber2; -}(Subscription); -var _bind = Function.prototype.bind; -function bind(fn, thisArg) { - return _bind.call(fn, thisArg); -} -var ConsumerObserver = function() { - function ConsumerObserver2(partialObserver) { - this.partialObserver = partialObserver; - } - ConsumerObserver2.prototype.next = function(value) { - var partialObserver = this.partialObserver; - if (partialObserver.next) { - try { - partialObserver.next(value); - } catch (error) { - handleUnhandledError(error); - } - } - }; - ConsumerObserver2.prototype.error = function(err) { - var partialObserver = this.partialObserver; - if (partialObserver.error) { - try { - partialObserver.error(err); - } catch (error) { - handleUnhandledError(error); - } - } else { - handleUnhandledError(err); - } - }; - ConsumerObserver2.prototype.complete = function() { - var partialObserver = this.partialObserver; - if (partialObserver.complete) { - try { - partialObserver.complete(); - } catch (error) { - handleUnhandledError(error); - } - } - }; - return ConsumerObserver2; -}(); -var SafeSubscriber = function(_super) { - __extends(SafeSubscriber2, _super); - function SafeSubscriber2(observerOrNext, error, complete) { - var _this = _super.call(this) || this; - var partialObserver; - if (isFunction(observerOrNext) || !observerOrNext) { - partialObserver = { - next: observerOrNext !== null && observerOrNext !== void 0 ? observerOrNext : void 0, - error: error !== null && error !== void 0 ? error : void 0, - complete: complete !== null && complete !== void 0 ? complete : void 0 - }; - } else { - var context_1; - if (_this && config.useDeprecatedNextContext) { - context_1 = Object.create(observerOrNext); - context_1.unsubscribe = function() { - return _this.unsubscribe(); - }; - partialObserver = { - next: observerOrNext.next && bind(observerOrNext.next, context_1), - error: observerOrNext.error && bind(observerOrNext.error, context_1), - complete: observerOrNext.complete && bind(observerOrNext.complete, context_1) - }; - } else { - partialObserver = observerOrNext; - } - } - _this.destination = new ConsumerObserver(partialObserver); - return _this; - } - return SafeSubscriber2; -}(Subscriber); -function handleUnhandledError(error) { - if (config.useDeprecatedSynchronousErrorHandling) { - captureError(error); - } else { - reportUnhandledError(error); - } -} -function defaultErrorHandler(err) { - throw err; -} -function handleStoppedNotification(notification, subscriber) { - var onStoppedNotification = config.onStoppedNotification; - onStoppedNotification && timeoutProvider.setTimeout(function() { - return onStoppedNotification(notification, subscriber); - }); -} -var EMPTY_OBSERVER = { - closed: true, - next: noop, - error: defaultErrorHandler, - complete: noop -}; - -// ../../../node_modules/rxjs/dist/esm5/internal/symbol/observable.js -var observable = function() { - return typeof Symbol === "function" && Symbol.observable || "@@observable"; -}(); - -// ../../../node_modules/rxjs/dist/esm5/internal/util/identity.js -function identity(x) { - return x; -} - -// ../../../node_modules/rxjs/dist/esm5/internal/util/pipe.js -function pipeFromArray(fns) { - if (fns.length === 0) { - return identity; - } - if (fns.length === 1) { - return fns[0]; - } - return function piped(input) { - return fns.reduce(function(prev, fn) { - return fn(prev); - }, input); - }; -} - -// ../../../node_modules/rxjs/dist/esm5/internal/Observable.js -var Observable = function() { - function Observable2(subscribe) { - if (subscribe) { - this._subscribe = subscribe; - } - } - Observable2.prototype.lift = function(operator) { - var observable2 = new Observable2(); - observable2.source = this; - observable2.operator = operator; - return observable2; - }; - Observable2.prototype.subscribe = function(observerOrNext, error, complete) { - var _this = this; - var subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete); - errorContext(function() { - var _a = _this, operator = _a.operator, source = _a.source; - subscriber.add(operator ? operator.call(subscriber, source) : source ? _this._subscribe(subscriber) : _this._trySubscribe(subscriber)); - }); - return subscriber; - }; - Observable2.prototype._trySubscribe = function(sink) { - try { - return this._subscribe(sink); - } catch (err) { - sink.error(err); - } - }; - Observable2.prototype.forEach = function(next, promiseCtor) { - var _this = this; - promiseCtor = getPromiseCtor(promiseCtor); - return new promiseCtor(function(resolve, reject) { - var subscriber = new SafeSubscriber({ - next: function(value) { - try { - next(value); - } catch (err) { - reject(err); - subscriber.unsubscribe(); - } - }, - error: reject, - complete: resolve - }); - _this.subscribe(subscriber); - }); - }; - Observable2.prototype._subscribe = function(subscriber) { - var _a; - return (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber); - }; - Observable2.prototype[observable] = function() { - return this; - }; - Observable2.prototype.pipe = function() { - var operations = []; - for (var _i = 0; _i < arguments.length; _i++) { - operations[_i] = arguments[_i]; - } - return pipeFromArray(operations)(this); - }; - Observable2.prototype.toPromise = function(promiseCtor) { - var _this = this; - promiseCtor = getPromiseCtor(promiseCtor); - return new promiseCtor(function(resolve, reject) { - var value; - _this.subscribe(function(x) { - return value = x; - }, function(err) { - return reject(err); - }, function() { - return resolve(value); - }); - }); - }; - Observable2.create = function(subscribe) { - return new Observable2(subscribe); - }; - return Observable2; -}(); -function getPromiseCtor(promiseCtor) { - var _a; - return (_a = promiseCtor !== null && promiseCtor !== void 0 ? promiseCtor : config.Promise) !== null && _a !== void 0 ? _a : Promise; -} -function isObserver(value) { - return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete); -} -function isSubscriber(value) { - return value && value instanceof Subscriber || isObserver(value) && isSubscription(value); -} - -// ../../../node_modules/rxjs/dist/esm5/internal/util/ObjectUnsubscribedError.js -var ObjectUnsubscribedError = createErrorClass(function(_super) { - return function ObjectUnsubscribedErrorImpl() { - _super(this); - this.name = "ObjectUnsubscribedError"; - this.message = "object unsubscribed"; - }; -}); - -// ../../../node_modules/rxjs/dist/esm5/internal/Subject.js -var Subject = function(_super) { - __extends(Subject2, _super); - function Subject2() { - var _this = _super.call(this) || this; - _this.closed = false; - _this.currentObservers = null; - _this.observers = []; - _this.isStopped = false; - _this.hasError = false; - _this.thrownError = null; - return _this; - } - Subject2.prototype.lift = function(operator) { - var subject = new AnonymousSubject(this, this); - subject.operator = operator; - return subject; - }; - Subject2.prototype._throwIfClosed = function() { - if (this.closed) { - throw new ObjectUnsubscribedError(); - } - }; - Subject2.prototype.next = function(value) { - var _this = this; - errorContext(function() { - var e_1, _a; - _this._throwIfClosed(); - if (!_this.isStopped) { - if (!_this.currentObservers) { - _this.currentObservers = Array.from(_this.observers); - } - try { - for (var _b = __values(_this.currentObservers), _c = _b.next(); !_c.done; _c = _b.next()) { - var observer = _c.value; - observer.next(value); - } - } catch (e_1_1) { - e_1 = { error: e_1_1 }; - } finally { - try { - if (_c && !_c.done && (_a = _b.return)) - _a.call(_b); - } finally { - if (e_1) - throw e_1.error; - } - } - } - }); - }; - Subject2.prototype.error = function(err) { - var _this = this; - errorContext(function() { - _this._throwIfClosed(); - if (!_this.isStopped) { - _this.hasError = _this.isStopped = true; - _this.thrownError = err; - var observers = _this.observers; - while (observers.length) { - observers.shift().error(err); - } - } - }); - }; - Subject2.prototype.complete = function() { - var _this = this; - errorContext(function() { - _this._throwIfClosed(); - if (!_this.isStopped) { - _this.isStopped = true; - var observers = _this.observers; - while (observers.length) { - observers.shift().complete(); - } - } - }); - }; - Subject2.prototype.unsubscribe = function() { - this.isStopped = this.closed = true; - this.observers = this.currentObservers = null; - }; - Object.defineProperty(Subject2.prototype, "observed", { - get: function() { - var _a; - return ((_a = this.observers) === null || _a === void 0 ? void 0 : _a.length) > 0; - }, - enumerable: false, - configurable: true - }); - Subject2.prototype._trySubscribe = function(subscriber) { - this._throwIfClosed(); - return _super.prototype._trySubscribe.call(this, subscriber); - }; - Subject2.prototype._subscribe = function(subscriber) { - this._throwIfClosed(); - this._checkFinalizedStatuses(subscriber); - return this._innerSubscribe(subscriber); - }; - Subject2.prototype._innerSubscribe = function(subscriber) { - var _this = this; - var _a = this, hasError = _a.hasError, isStopped = _a.isStopped, observers = _a.observers; - if (hasError || isStopped) { - return EMPTY_SUBSCRIPTION; - } - this.currentObservers = null; - observers.push(subscriber); - return new Subscription(function() { - _this.currentObservers = null; - arrRemove(observers, subscriber); - }); - }; - Subject2.prototype._checkFinalizedStatuses = function(subscriber) { - var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, isStopped = _a.isStopped; - if (hasError) { - subscriber.error(thrownError); - } else if (isStopped) { - subscriber.complete(); - } - }; - Subject2.prototype.asObservable = function() { - var observable2 = new Observable(); - observable2.source = this; - return observable2; - }; - Subject2.create = function(destination, source) { - return new AnonymousSubject(destination, source); - }; - return Subject2; -}(Observable); -var AnonymousSubject = function(_super) { - __extends(AnonymousSubject2, _super); - function AnonymousSubject2(destination, source) { - var _this = _super.call(this) || this; - _this.destination = destination; - _this.source = source; - return _this; - } - AnonymousSubject2.prototype.next = function(value) { - var _a, _b; - (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.next) === null || _b === void 0 ? void 0 : _b.call(_a, value); - }; - AnonymousSubject2.prototype.error = function(err) { - var _a, _b; - (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.error) === null || _b === void 0 ? void 0 : _b.call(_a, err); - }; - AnonymousSubject2.prototype.complete = function() { - var _a, _b; - (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.complete) === null || _b === void 0 ? void 0 : _b.call(_a); - }; - AnonymousSubject2.prototype._subscribe = function(subscriber) { - var _a, _b; - return (_b = (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber)) !== null && _b !== void 0 ? _b : EMPTY_SUBSCRIPTION; - }; - return AnonymousSubject2; -}(Subject); - -// ../../../node_modules/rxjs/dist/esm5/internal/scheduler/dateTimestampProvider.js -var dateTimestampProvider = { - now: function() { - return (dateTimestampProvider.delegate || Date).now(); - }, - delegate: void 0 -}; - -// ../../../node_modules/rxjs/dist/esm5/internal/ReplaySubject.js -var ReplaySubject = function(_super) { - __extends(ReplaySubject2, _super); - function ReplaySubject2(_bufferSize, _windowTime, _timestampProvider) { - if (_bufferSize === void 0) { - _bufferSize = Infinity; - } - if (_windowTime === void 0) { - _windowTime = Infinity; - } - if (_timestampProvider === void 0) { - _timestampProvider = dateTimestampProvider; - } - var _this = _super.call(this) || this; - _this._bufferSize = _bufferSize; - _this._windowTime = _windowTime; - _this._timestampProvider = _timestampProvider; - _this._buffer = []; - _this._infiniteTimeWindow = true; - _this._infiniteTimeWindow = _windowTime === Infinity; - _this._bufferSize = Math.max(1, _bufferSize); - _this._windowTime = Math.max(1, _windowTime); - return _this; - } - ReplaySubject2.prototype.next = function(value) { - var _a = this, isStopped = _a.isStopped, _buffer = _a._buffer, _infiniteTimeWindow = _a._infiniteTimeWindow, _timestampProvider = _a._timestampProvider, _windowTime = _a._windowTime; - if (!isStopped) { - _buffer.push(value); - !_infiniteTimeWindow && _buffer.push(_timestampProvider.now() + _windowTime); - } - this._trimBuffer(); - _super.prototype.next.call(this, value); - }; - ReplaySubject2.prototype._subscribe = function(subscriber) { - this._throwIfClosed(); - this._trimBuffer(); - var subscription = this._innerSubscribe(subscriber); - var _a = this, _infiniteTimeWindow = _a._infiniteTimeWindow, _buffer = _a._buffer; - var copy = _buffer.slice(); - for (var i = 0; i < copy.length && !subscriber.closed; i += _infiniteTimeWindow ? 1 : 2) { - subscriber.next(copy[i]); - } - this._checkFinalizedStatuses(subscriber); - return subscription; - }; - ReplaySubject2.prototype._trimBuffer = function() { - var _a = this, _bufferSize = _a._bufferSize, _timestampProvider = _a._timestampProvider, _buffer = _a._buffer, _infiniteTimeWindow = _a._infiniteTimeWindow; - var adjustedBufferSize = (_infiniteTimeWindow ? 1 : 2) * _bufferSize; - _bufferSize < Infinity && adjustedBufferSize < _buffer.length && _buffer.splice(0, _buffer.length - adjustedBufferSize); - if (!_infiniteTimeWindow) { - var now = _timestampProvider.now(); - var last2 = 0; - for (var i = 1; i < _buffer.length && _buffer[i] <= now; i += 2) { - last2 = i; - } - last2 && _buffer.splice(0, last2 + 1); - } - }; - return ReplaySubject2; -}(Subject); - -// ../../../node_modules/rxjs/dist/esm5/internal/observable/dom/WebSocketSubject.js -var DEFAULT_WEBSOCKET_CONFIG = { - url: "", - deserializer: function(e) { - return JSON.parse(e.data); - }, - serializer: function(value) { - return JSON.stringify(value); - } -}; -var WEBSOCKETSUBJECT_INVALID_ERROR_OBJECT = "WebSocketSubject.error must be called with an object with an error code, and an optional reason: { code: number, reason: string }"; -var WebSocketSubject = function(_super) { - __extends(WebSocketSubject2, _super); - function WebSocketSubject2(urlConfigOrSource, destination) { - var _this = _super.call(this) || this; - _this._socket = null; - if (urlConfigOrSource instanceof Observable) { - _this.destination = destination; - _this.source = urlConfigOrSource; - } else { - var config2 = _this._config = __assign({}, DEFAULT_WEBSOCKET_CONFIG); - _this._output = new Subject(); - if (typeof urlConfigOrSource === "string") { - config2.url = urlConfigOrSource; - } else { - for (var key in urlConfigOrSource) { - if (urlConfigOrSource.hasOwnProperty(key)) { - config2[key] = urlConfigOrSource[key]; - } - } - } - if (!config2.WebSocketCtor && WebSocket) { - config2.WebSocketCtor = WebSocket; - } else if (!config2.WebSocketCtor) { - throw new Error("no WebSocket constructor can be found"); - } - _this.destination = new ReplaySubject(); - } - return _this; - } - WebSocketSubject2.prototype.lift = function(operator) { - var sock = new WebSocketSubject2(this._config, this.destination); - sock.operator = operator; - sock.source = this; - return sock; - }; - WebSocketSubject2.prototype._resetState = function() { - this._socket = null; - if (!this.source) { - this.destination = new ReplaySubject(); - } - this._output = new Subject(); - }; - WebSocketSubject2.prototype.multiplex = function(subMsg, unsubMsg, messageFilter) { - var self = this; - return new Observable(function(observer) { - try { - self.next(subMsg()); - } catch (err) { - observer.error(err); - } - var subscription = self.subscribe({ - next: function(x) { - try { - if (messageFilter(x)) { - observer.next(x); - } - } catch (err) { - observer.error(err); - } - }, - error: function(err) { - return observer.error(err); - }, - complete: function() { - return observer.complete(); - } - }); - return function() { - try { - self.next(unsubMsg()); - } catch (err) { - observer.error(err); - } - subscription.unsubscribe(); - }; - }); - }; - WebSocketSubject2.prototype._connectSocket = function() { - var _this = this; - var _a = this._config, WebSocketCtor = _a.WebSocketCtor, protocol = _a.protocol, url2 = _a.url, binaryType = _a.binaryType; - var observer = this._output; - var socket2 = null; - try { - socket2 = protocol ? new WebSocketCtor(url2, protocol) : new WebSocketCtor(url2); - this._socket = socket2; - if (binaryType) { - this._socket.binaryType = binaryType; - } - } catch (e) { - observer.error(e); - return; - } - var subscription = new Subscription(function() { - _this._socket = null; - if (socket2 && socket2.readyState === 1) { - socket2.close(); - } - }); - socket2.onopen = function(evt) { - var _socket = _this._socket; - if (!_socket) { - socket2.close(); - _this._resetState(); - return; - } - var openObserver = _this._config.openObserver; - if (openObserver) { - openObserver.next(evt); - } - var queue = _this.destination; - _this.destination = Subscriber.create(function(x) { - if (socket2.readyState === 1) { - try { - var serializer = _this._config.serializer; - socket2.send(serializer(x)); - } catch (e) { - _this.destination.error(e); - } - } - }, function(err) { - var closingObserver = _this._config.closingObserver; - if (closingObserver) { - closingObserver.next(void 0); - } - if (err && err.code) { - socket2.close(err.code, err.reason); - } else { - observer.error(new TypeError(WEBSOCKETSUBJECT_INVALID_ERROR_OBJECT)); - } - _this._resetState(); - }, function() { - var closingObserver = _this._config.closingObserver; - if (closingObserver) { - closingObserver.next(void 0); - } - socket2.close(); - _this._resetState(); - }); - if (queue && queue instanceof ReplaySubject) { - subscription.add(queue.subscribe(_this.destination)); - } - }; - socket2.onerror = function(e) { - _this._resetState(); - observer.error(e); - }; - socket2.onclose = function(e) { - if (socket2 === _this._socket) { - _this._resetState(); - } - var closeObserver = _this._config.closeObserver; - if (closeObserver) { - closeObserver.next(e); - } - if (e.wasClean) { - observer.complete(); - } else { - observer.error(e); - } - }; - socket2.onmessage = function(e) { - try { - var deserializer = _this._config.deserializer; - observer.next(deserializer(e)); - } catch (err) { - observer.error(err); - } - }; - }; - WebSocketSubject2.prototype._subscribe = function(subscriber) { - var _this = this; - var source = this.source; - if (source) { - return source.subscribe(subscriber); - } - if (!this._socket) { - this._connectSocket(); - } - this._output.subscribe(subscriber); - subscriber.add(function() { - var _socket = _this._socket; - if (_this._output.observers.length === 0) { - if (_socket && (_socket.readyState === 1 || _socket.readyState === 0)) { - _socket.close(); - } - _this._resetState(); - } - }); - return subscriber; - }; - WebSocketSubject2.prototype.unsubscribe = function() { - var _socket = this._socket; - if (_socket && (_socket.readyState === 1 || _socket.readyState === 0)) { - _socket.close(); - } - this._resetState(); - _super.prototype.unsubscribe.call(this); - }; - return WebSocketSubject2; -}(AnonymousSubject); - -// ../../../node_modules/rxjs/dist/esm5/internal/observable/dom/webSocket.js -function webSocket(urlConfigOrSource) { - return new WebSocketSubject(urlConfigOrSource); -} - -// ../../../node_modules/rxjs/dist/esm5/internal/util/lift.js -function hasLift(source) { - return isFunction(source === null || source === void 0 ? void 0 : source.lift); -} -function operate(init) { - return function(source) { - if (hasLift(source)) { - return source.lift(function(liftedSource) { - try { - return init(liftedSource, this); - } catch (err) { - this.error(err); - } - }); - } - throw new TypeError("Unable to lift unknown Observable type"); - }; -} - -// ../../../node_modules/rxjs/dist/esm5/internal/operators/OperatorSubscriber.js -function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) { - return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize); -} -var OperatorSubscriber = function(_super) { - __extends(OperatorSubscriber2, _super); - function OperatorSubscriber2(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) { - var _this = _super.call(this, destination) || this; - _this.onFinalize = onFinalize; - _this.shouldUnsubscribe = shouldUnsubscribe; - _this._next = onNext ? function(value) { - try { - onNext(value); - } catch (err) { - destination.error(err); - } - } : _super.prototype._next; - _this._error = onError ? function(err) { - try { - onError(err); - } catch (err2) { - destination.error(err2); - } finally { - this.unsubscribe(); - } - } : _super.prototype._error; - _this._complete = onComplete ? function() { - try { - onComplete(); - } catch (err) { - destination.error(err); - } finally { - this.unsubscribe(); - } - } : _super.prototype._complete; - return _this; - } - OperatorSubscriber2.prototype.unsubscribe = function() { - var _a; - if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) { - var closed_1 = this.closed; - _super.prototype.unsubscribe.call(this); - !closed_1 && ((_a = this.onFinalize) === null || _a === void 0 ? void 0 : _a.call(this)); - } - }; - return OperatorSubscriber2; -}(Subscriber); - -// ../../../node_modules/rxjs/dist/esm5/internal/scheduler/Action.js -var Action = function(_super) { - __extends(Action2, _super); - function Action2(scheduler, work) { - return _super.call(this) || this; - } - Action2.prototype.schedule = function(state, delay) { - if (delay === void 0) { - delay = 0; - } - return this; - }; - return Action2; -}(Subscription); - -// ../../../node_modules/rxjs/dist/esm5/internal/scheduler/intervalProvider.js -var intervalProvider = { - setInterval: function(handler, timeout) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var delegate = intervalProvider.delegate; - if (delegate === null || delegate === void 0 ? void 0 : delegate.setInterval) { - return delegate.setInterval.apply(delegate, __spreadArray([handler, timeout], __read(args))); - } - return setInterval.apply(void 0, __spreadArray([handler, timeout], __read(args))); - }, - clearInterval: function(handle) { - var delegate = intervalProvider.delegate; - return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearInterval) || clearInterval)(handle); - }, - delegate: void 0 -}; - -// ../../../node_modules/rxjs/dist/esm5/internal/scheduler/AsyncAction.js -var AsyncAction = function(_super) { - __extends(AsyncAction2, _super); - function AsyncAction2(scheduler, work) { - var _this = _super.call(this, scheduler, work) || this; - _this.scheduler = scheduler; - _this.work = work; - _this.pending = false; - return _this; - } - AsyncAction2.prototype.schedule = function(state, delay) { - var _a; - if (delay === void 0) { - delay = 0; - } - if (this.closed) { - return this; - } - this.state = state; - var id = this.id; - var scheduler = this.scheduler; - if (id != null) { - this.id = this.recycleAsyncId(scheduler, id, delay); - } - this.pending = true; - this.delay = delay; - this.id = (_a = this.id) !== null && _a !== void 0 ? _a : this.requestAsyncId(scheduler, this.id, delay); - return this; - }; - AsyncAction2.prototype.requestAsyncId = function(scheduler, _id, delay) { - if (delay === void 0) { - delay = 0; - } - return intervalProvider.setInterval(scheduler.flush.bind(scheduler, this), delay); - }; - AsyncAction2.prototype.recycleAsyncId = function(_scheduler, id, delay) { - if (delay === void 0) { - delay = 0; - } - if (delay != null && this.delay === delay && this.pending === false) { - return id; - } - if (id != null) { - intervalProvider.clearInterval(id); - } - return void 0; - }; - AsyncAction2.prototype.execute = function(state, delay) { - if (this.closed) { - return new Error("executing a cancelled action"); - } - this.pending = false; - var error = this._execute(state, delay); - if (error) { - return error; - } else if (this.pending === false && this.id != null) { - this.id = this.recycleAsyncId(this.scheduler, this.id, null); - } - }; - AsyncAction2.prototype._execute = function(state, _delay) { - var errored = false; - var errorValue; - try { - this.work(state); - } catch (e) { - errored = true; - errorValue = e ? e : new Error("Scheduled action threw falsy error"); - } - if (errored) { - this.unsubscribe(); - return errorValue; - } - }; - AsyncAction2.prototype.unsubscribe = function() { - if (!this.closed) { - var _a = this, id = _a.id, scheduler = _a.scheduler; - var actions = scheduler.actions; - this.work = this.state = this.scheduler = null; - this.pending = false; - arrRemove(actions, this); - if (id != null) { - this.id = this.recycleAsyncId(scheduler, id, null); - } - this.delay = null; - _super.prototype.unsubscribe.call(this); - } - }; - return AsyncAction2; -}(Action); - -// ../../../node_modules/rxjs/dist/esm5/internal/Scheduler.js -var Scheduler = function() { - function Scheduler2(schedulerActionCtor, now) { - if (now === void 0) { - now = Scheduler2.now; - } - this.schedulerActionCtor = schedulerActionCtor; - this.now = now; - } - Scheduler2.prototype.schedule = function(work, delay, state) { - if (delay === void 0) { - delay = 0; - } - return new this.schedulerActionCtor(this, work).schedule(state, delay); - }; - Scheduler2.now = dateTimestampProvider.now; - return Scheduler2; -}(); - -// ../../../node_modules/rxjs/dist/esm5/internal/scheduler/AsyncScheduler.js -var AsyncScheduler = function(_super) { - __extends(AsyncScheduler2, _super); - function AsyncScheduler2(SchedulerAction, now) { - if (now === void 0) { - now = Scheduler.now; - } - var _this = _super.call(this, SchedulerAction, now) || this; - _this.actions = []; - _this._active = false; - return _this; - } - AsyncScheduler2.prototype.flush = function(action) { - var actions = this.actions; - if (this._active) { - actions.push(action); - return; - } - var error; - this._active = true; - do { - if (error = action.execute(action.state, action.delay)) { - break; - } - } while (action = actions.shift()); - this._active = false; - if (error) { - while (action = actions.shift()) { - action.unsubscribe(); - } - throw error; - } - }; - return AsyncScheduler2; -}(Scheduler); - -// ../../../node_modules/rxjs/dist/esm5/internal/scheduler/async.js -var asyncScheduler = new AsyncScheduler(AsyncAction); -var async = asyncScheduler; - -// ../../../node_modules/rxjs/dist/esm5/internal/util/isScheduler.js -function isScheduler(value) { - return value && isFunction(value.schedule); -} - -// ../../../node_modules/rxjs/dist/esm5/internal/util/args.js -function last(arr) { - return arr[arr.length - 1]; -} -function popResultSelector(args) { - return isFunction(last(args)) ? args.pop() : void 0; -} - -// ../../../node_modules/rxjs/dist/esm5/internal/util/isArrayLike.js -var isArrayLike = function(x) { - return x && typeof x.length === "number" && typeof x !== "function"; -}; - -// ../../../node_modules/rxjs/dist/esm5/internal/util/isPromise.js -function isPromise(value) { - return isFunction(value === null || value === void 0 ? void 0 : value.then); -} - -// ../../../node_modules/rxjs/dist/esm5/internal/util/isInteropObservable.js -function isInteropObservable(input) { - return isFunction(input[observable]); -} - -// ../../../node_modules/rxjs/dist/esm5/internal/util/isAsyncIterable.js -function isAsyncIterable(obj) { - return Symbol.asyncIterator && isFunction(obj === null || obj === void 0 ? void 0 : obj[Symbol.asyncIterator]); -} - -// ../../../node_modules/rxjs/dist/esm5/internal/util/throwUnobservableError.js -function createInvalidObservableTypeError(input) { - return new TypeError("You provided " + (input !== null && typeof input === "object" ? "an invalid object" : "'" + input + "'") + " where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable."); -} - -// ../../../node_modules/rxjs/dist/esm5/internal/symbol/iterator.js -function getSymbolIterator() { - if (typeof Symbol !== "function" || !Symbol.iterator) { - return "@@iterator"; - } - return Symbol.iterator; -} -var iterator = getSymbolIterator(); - -// ../../../node_modules/rxjs/dist/esm5/internal/util/isIterable.js -function isIterable(input) { - return isFunction(input === null || input === void 0 ? void 0 : input[iterator]); -} - -// ../../../node_modules/rxjs/dist/esm5/internal/util/isReadableStreamLike.js -function readableStreamLikeToAsyncGenerator(readableStream) { - return __asyncGenerator(this, arguments, function readableStreamLikeToAsyncGenerator_1() { - var reader, _a, value, done; - return __generator(this, function(_b) { - switch (_b.label) { - case 0: - reader = readableStream.getReader(); - _b.label = 1; - case 1: - _b.trys.push([1, , 9, 10]); - _b.label = 2; - case 2: - if (false) - return [3, 8]; - return [4, __await(reader.read())]; - case 3: - _a = _b.sent(), value = _a.value, done = _a.done; - if (!done) - return [3, 5]; - return [4, __await(void 0)]; - case 4: - return [2, _b.sent()]; - case 5: - return [4, __await(value)]; - case 6: - return [4, _b.sent()]; - case 7: - _b.sent(); - return [3, 2]; - case 8: - return [3, 10]; - case 9: - reader.releaseLock(); - return [7]; - case 10: - return [2]; - } - }); - }); -} -function isReadableStreamLike(obj) { - return isFunction(obj === null || obj === void 0 ? void 0 : obj.getReader); -} - -// ../../../node_modules/rxjs/dist/esm5/internal/observable/innerFrom.js -function innerFrom(input) { - if (input instanceof Observable) { - return input; - } - if (input != null) { - if (isInteropObservable(input)) { - return fromInteropObservable(input); - } - if (isArrayLike(input)) { - return fromArrayLike(input); - } - if (isPromise(input)) { - return fromPromise(input); - } - if (isAsyncIterable(input)) { - return fromAsyncIterable(input); - } - if (isIterable(input)) { - return fromIterable(input); - } - if (isReadableStreamLike(input)) { - return fromReadableStreamLike(input); - } - } - throw createInvalidObservableTypeError(input); -} -function fromInteropObservable(obj) { - return new Observable(function(subscriber) { - var obs = obj[observable](); - if (isFunction(obs.subscribe)) { - return obs.subscribe(subscriber); - } - throw new TypeError("Provided object does not correctly implement Symbol.observable"); - }); -} -function fromArrayLike(array) { - return new Observable(function(subscriber) { - for (var i = 0; i < array.length && !subscriber.closed; i++) { - subscriber.next(array[i]); - } - subscriber.complete(); - }); -} -function fromPromise(promise) { - return new Observable(function(subscriber) { - promise.then(function(value) { - if (!subscriber.closed) { - subscriber.next(value); - subscriber.complete(); - } - }, function(err) { - return subscriber.error(err); - }).then(null, reportUnhandledError); - }); -} -function fromIterable(iterable) { - return new Observable(function(subscriber) { - var e_1, _a; - try { - for (var iterable_1 = __values(iterable), iterable_1_1 = iterable_1.next(); !iterable_1_1.done; iterable_1_1 = iterable_1.next()) { - var value = iterable_1_1.value; - subscriber.next(value); - if (subscriber.closed) { - return; - } - } - } catch (e_1_1) { - e_1 = { error: e_1_1 }; - } finally { - try { - if (iterable_1_1 && !iterable_1_1.done && (_a = iterable_1.return)) - _a.call(iterable_1); - } finally { - if (e_1) - throw e_1.error; - } - } - subscriber.complete(); - }); -} -function fromAsyncIterable(asyncIterable) { - return new Observable(function(subscriber) { - process(asyncIterable, subscriber).catch(function(err) { - return subscriber.error(err); - }); - }); -} -function fromReadableStreamLike(readableStream) { - return fromAsyncIterable(readableStreamLikeToAsyncGenerator(readableStream)); -} -function process(asyncIterable, subscriber) { - var asyncIterable_1, asyncIterable_1_1; - var e_2, _a; - return __awaiter(this, void 0, void 0, function() { - var value, e_2_1; - return __generator(this, function(_b) { - switch (_b.label) { - case 0: - _b.trys.push([0, 5, 6, 11]); - asyncIterable_1 = __asyncValues(asyncIterable); - _b.label = 1; - case 1: - return [4, asyncIterable_1.next()]; - case 2: - if (!(asyncIterable_1_1 = _b.sent(), !asyncIterable_1_1.done)) - return [3, 4]; - value = asyncIterable_1_1.value; - subscriber.next(value); - if (subscriber.closed) { - return [2]; - } - _b.label = 3; - case 3: - return [3, 1]; - case 4: - return [3, 11]; - case 5: - e_2_1 = _b.sent(); - e_2 = { error: e_2_1 }; - return [3, 11]; - case 6: - _b.trys.push([6, , 9, 10]); - if (!(asyncIterable_1_1 && !asyncIterable_1_1.done && (_a = asyncIterable_1.return))) - return [3, 8]; - return [4, _a.call(asyncIterable_1)]; - case 7: - _b.sent(); - _b.label = 8; - case 8: - return [3, 10]; - case 9: - if (e_2) - throw e_2.error; - return [7]; - case 10: - return [7]; - case 11: - subscriber.complete(); - return [2]; - } - }); - }); -} - -// ../../../node_modules/rxjs/dist/esm5/internal/util/isDate.js -function isValidDate(value) { - return value instanceof Date && !isNaN(value); -} - -// ../../../node_modules/rxjs/dist/esm5/internal/operators/map.js -function map(project, thisArg) { - return operate(function(source, subscriber) { - var index = 0; - source.subscribe(createOperatorSubscriber(subscriber, function(value) { - subscriber.next(project.call(thisArg, value, index++)); - })); - }); -} - -// ../../../node_modules/rxjs/dist/esm5/internal/observable/timer.js -function timer(dueTime, intervalOrScheduler, scheduler) { - if (dueTime === void 0) { - dueTime = 0; - } - if (scheduler === void 0) { - scheduler = async; - } - var intervalDuration = -1; - if (intervalOrScheduler != null) { - if (isScheduler(intervalOrScheduler)) { - scheduler = intervalOrScheduler; - } else { - intervalDuration = intervalOrScheduler; - } - } - return new Observable(function(subscriber) { - var due = isValidDate(dueTime) ? +dueTime - scheduler.now() : dueTime; - if (due < 0) { - due = 0; - } - var n = 0; - return scheduler.schedule(function() { - if (!subscriber.closed) { - subscriber.next(n++); - if (0 <= intervalDuration) { - this.schedule(void 0, intervalDuration); - } else { - subscriber.complete(); - } - } - }, due); - }); -} - -// ../../../node_modules/rxjs/dist/esm5/internal/operators/filter.js -function filter(predicate, thisArg) { - return operate(function(source, subscriber) { - var index = 0; - source.subscribe(createOperatorSubscriber(subscriber, function(value) { - return predicate.call(thisArg, value, index++) && subscriber.next(value); - })); - }); -} - -// ../../../node_modules/rxjs/dist/esm5/internal/operators/retry.js -function retry(configOrCount) { - if (configOrCount === void 0) { - configOrCount = Infinity; - } - var config2; - if (configOrCount && typeof configOrCount === "object") { - config2 = configOrCount; - } else { - config2 = { - count: configOrCount - }; - } - var _a = config2.count, count = _a === void 0 ? Infinity : _a, delay = config2.delay, _b = config2.resetOnSuccess, resetOnSuccess = _b === void 0 ? false : _b; - return count <= 0 ? identity : operate(function(source, subscriber) { - var soFar = 0; - var innerSub; - var subscribeForRetry = function() { - var syncUnsub = false; - innerSub = source.subscribe(createOperatorSubscriber(subscriber, function(value) { - if (resetOnSuccess) { - soFar = 0; - } - subscriber.next(value); - }, void 0, function(err) { - if (soFar++ < count) { - var resub_1 = function() { - if (innerSub) { - innerSub.unsubscribe(); - innerSub = null; - subscribeForRetry(); - } else { - syncUnsub = true; - } - }; - if (delay != null) { - var notifier = typeof delay === "number" ? timer(delay) : innerFrom(delay(err, soFar)); - var notifierSubscriber_1 = createOperatorSubscriber(subscriber, function() { - notifierSubscriber_1.unsubscribe(); - resub_1(); - }, function() { - subscriber.complete(); - }); - notifier.subscribe(notifierSubscriber_1); - } else { - resub_1(); - } - } else { - subscriber.error(err); - } - })); - if (syncUnsub) { - innerSub.unsubscribe(); - innerSub = null; - subscribeForRetry(); - } - }; - subscribeForRetry(); - }); -} - -// ../../../node_modules/rxjs/dist/esm5/internal/operators/withLatestFrom.js -function withLatestFrom() { - var inputs = []; - for (var _i = 0; _i < arguments.length; _i++) { - inputs[_i] = arguments[_i]; - } - var project = popResultSelector(inputs); - return operate(function(source, subscriber) { - var len = inputs.length; - var otherValues = new Array(len); - var hasValue = inputs.map(function() { - return false; - }); - var ready = false; - var _loop_1 = function(i2) { - innerFrom(inputs[i2]).subscribe(createOperatorSubscriber(subscriber, function(value) { - otherValues[i2] = value; - if (!ready && !hasValue[i2]) { - hasValue[i2] = true; - (ready = hasValue.every(identity)) && (hasValue = null); - } - }, noop)); - }; - for (var i = 0; i < len; i++) { - _loop_1(i); - } - source.subscribe(createOperatorSubscriber(subscriber, function(value) { - if (ready) { - var values = __spreadArray([value], __read(otherValues)); - subscriber.next(project ? project.apply(void 0, __spreadArray([], __read(values))) : values); - } - })); - }); -} - -// ../../../node_modules/zod/lib/index.mjs -var util; -(function(util2) { - util2.assertEqual = (val) => val; - function assertIs(_arg) { - } - util2.assertIs = assertIs; - function assertNever(_x) { - throw new Error(); - } - util2.assertNever = assertNever; - util2.arrayToEnum = (items) => { - const obj = {}; - for (const item of items) { - obj[item] = item; - } - return obj; - }; - util2.getValidEnumValues = (obj) => { - const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); - const filtered = {}; - for (const k of validKeys) { - filtered[k] = obj[k]; - } - return util2.objectValues(filtered); - }; - util2.objectValues = (obj) => { - return util2.objectKeys(obj).map(function(e) { - return obj[e]; - }); - }; - util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => { - const keys = []; - for (const key in object) { - if (Object.prototype.hasOwnProperty.call(object, key)) { - keys.push(key); - } - } - return keys; - }; - util2.find = (arr, checker) => { - for (const item of arr) { - if (checker(item)) - return item; - } - return void 0; - }; - util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val; - function joinValues(array, separator = " | ") { - return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); - } - util2.joinValues = joinValues; - util2.jsonStringifyReplacer = (_, value) => { - if (typeof value === "bigint") { - return value.toString(); - } - return value; - }; -})(util || (util = {})); -var objectUtil; -(function(objectUtil2) { - objectUtil2.mergeShapes = (first, second) => { - return { - ...first, - ...second - // second overwrites first - }; - }; -})(objectUtil || (objectUtil = {})); -var ZodParsedType = util.arrayToEnum([ - "string", - "nan", - "number", - "integer", - "float", - "boolean", - "date", - "bigint", - "symbol", - "function", - "undefined", - "null", - "array", - "object", - "unknown", - "promise", - "void", - "never", - "map", - "set" -]); -var getParsedType = (data) => { - const t = typeof data; - switch (t) { - case "undefined": - return ZodParsedType.undefined; - case "string": - return ZodParsedType.string; - case "number": - return 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; - } -}; -var ZodIssueCode = util.arrayToEnum([ - "invalid_type", - "invalid_literal", - "custom", - "invalid_union", - "invalid_union_discriminator", - "invalid_enum_value", - "unrecognized_keys", - "invalid_arguments", - "invalid_return_type", - "invalid_date", - "invalid_string", - "too_small", - "too_big", - "invalid_intersection_types", - "not_multiple_of", - "not_finite" -]); -var quotelessJson = (obj) => { - const json = JSON.stringify(obj, null, 2); - return json.replace(/"([^"]+)":/g, "$1:"); -}; -var ZodError = class _ZodError extends Error { - constructor(issues) { - super(); - this.issues = []; - this.addIssue = (sub) => { - this.issues = [...this.issues, sub]; - }; - this.addIssues = (subs = []) => { - this.issues = [...this.issues, ...subs]; - }; - const actualProto = new.target.prototype; - if (Object.setPrototypeOf) { - Object.setPrototypeOf(this, actualProto); - } else { - this.__proto__ = actualProto; - } - this.name = "ZodError"; - this.issues = issues; - } - 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: [] }; - } else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue)); - } - curr = curr[el]; - i++; - } - } - } - }; - processError(this); - return fieldErrors; - } - static assert(value) { - if (!(value instanceof _ZodError)) { - throw new Error(`Not a ZodError: ${value}`); - } - } - toString() { - return this.message; - } - get message() { - return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); - } - get isEmpty() { - return this.issues.length === 0; - } - flatten(mapper = (issue) => issue.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of this.issues) { - if (sub.path.length > 0) { - fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; - fieldErrors[sub.path[0]].push(mapper(sub)); - } else { - formErrors.push(mapper(sub)); - } - } - return { formErrors, fieldErrors }; - } - get formErrors() { - return this.flatten(); - } -}; -ZodError.create = (issues) => { - const error = new ZodError(issues); - return error; -}; -var errorMap = (issue, _ctx) => { - let message; - switch (issue.code) { - case ZodIssueCode.invalid_type: - if (issue.received === ZodParsedType.undefined) { - message = "Required"; - } else { - message = `Expected ${issue.expected}, received ${issue.received}`; - } - break; - case ZodIssueCode.invalid_literal: - message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`; - break; - case ZodIssueCode.unrecognized_keys: - message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`; - break; - case ZodIssueCode.invalid_union: - message = `Invalid input`; - break; - case ZodIssueCode.invalid_union_discriminator: - message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`; - break; - case ZodIssueCode.invalid_enum_value: - message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`; - break; - case ZodIssueCode.invalid_arguments: - message = `Invalid function arguments`; - break; - case ZodIssueCode.invalid_return_type: - message = `Invalid function return type`; - break; - case ZodIssueCode.invalid_date: - message = `Invalid date`; - break; - case ZodIssueCode.invalid_string: - if (typeof issue.validation === "object") { - if ("includes" in issue.validation) { - message = `Invalid input: must include "${issue.validation.includes}"`; - if (typeof issue.validation.position === "number") { - message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; - } - } else if ("startsWith" in issue.validation) { - message = `Invalid input: must start with "${issue.validation.startsWith}"`; - } else if ("endsWith" in issue.validation) { - message = `Invalid input: must end with "${issue.validation.endsWith}"`; - } else { - util.assertNever(issue.validation); - } - } else if (issue.validation !== "regex") { - message = `Invalid ${issue.validation}`; - } else { - message = "Invalid"; - } - break; - case ZodIssueCode.too_small: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode.too_big: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; - else if (issue.type === "bigint") - message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode.custom: - message = `Invalid input`; - break; - case ZodIssueCode.invalid_intersection_types: - message = `Intersection results could not be merged`; - break; - case ZodIssueCode.not_multiple_of: - message = `Number must be a multiple of ${issue.multipleOf}`; - break; - case ZodIssueCode.not_finite: - message = "Number must be finite"; - break; - default: - message = _ctx.defaultError; - util.assertNever(issue); - } - return { message }; -}; -var overrideErrorMap = errorMap; -function setErrorMap(map2) { - overrideErrorMap = map2; -} -function getErrorMap() { - return overrideErrorMap; -} -var makeIssue = (params) => { - const { data, path, errorMaps, issueData } = params; - const fullPath = [...path, ...issueData.path || []]; - const fullIssue = { - ...issueData, - path: fullPath - }; - if (issueData.message !== void 0) { - return { - ...issueData, - path: fullPath, - message: issueData.message - }; - } - let errorMessage = ""; - const maps = errorMaps.filter((m) => !!m).slice().reverse(); - for (const map2 of maps) { - errorMessage = map2(fullIssue, { data, defaultError: errorMessage }).message; - } - return { - ...issueData, - path: fullPath, - message: errorMessage - }; -}; -var EMPTY_PATH = []; -function addIssueToContext(ctx, issueData) { - const overrideMap = getErrorMap(); - const issue = makeIssue({ - issueData, - data: ctx.data, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - overrideMap, - overrideMap === errorMap ? void 0 : errorMap - // then global default map - ].filter((x) => !!x) - }); - ctx.common.issues.push(issue); -} -var ParseStatus = class _ParseStatus { - constructor() { - this.value = "valid"; - } - dirty() { - if (this.value === "valid") - this.value = "dirty"; - } - abort() { - if (this.value !== "aborted") - this.value = "aborted"; - } - static mergeArray(status, results) { - const arrayValue = []; - for (const s of results) { - if (s.status === "aborted") - return INVALID; - if (s.status === "dirty") - status.dirty(); - arrayValue.push(s.value); - } - return { status: status.value, value: arrayValue }; - } - static async mergeObjectAsync(status, pairs) { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value - }); - } - return _ParseStatus.mergeObjectSync(status, syncPairs); - } - static mergeObjectSync(status, pairs) { - const finalObject = {}; - for (const pair of pairs) { - const { key, value } = pair; - if (key.status === "aborted") - return INVALID; - if (value.status === "aborted") - return INVALID; - if (key.status === "dirty") - status.dirty(); - if (value.status === "dirty") - status.dirty(); - if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { - finalObject[key.value] = value.value; - } - } - return { status: status.value, value: finalObject }; - } -}; -var INVALID = Object.freeze({ - status: "aborted" -}); -var DIRTY = (value) => ({ status: "dirty", value }); -var OK = (value) => ({ status: "valid", value }); -var isAborted = (x) => x.status === "aborted"; -var isDirty = (x) => x.status === "dirty"; -var isValid = (x) => x.status === "valid"; -var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; -function __classPrivateFieldGet(receiver, state, kind, f) { - if (kind === "a" && !f) - throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) - throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -} -function __classPrivateFieldSet(receiver, state, value, kind, f) { - if (kind === "m") - throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) - throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) - throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; -} -var errorUtil; -(function(errorUtil2) { - errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {}; - errorUtil2.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message; -})(errorUtil || (errorUtil = {})); -var _ZodEnum_cache; -var _ZodNativeEnum_cache; -var ParseInputLazyPath = class { - constructor(parent, value, path, key) { - this._cachedPath = []; - this.parent = parent; - this.data = value; - this._path = path; - this._key = key; - } - get path() { - if (!this._cachedPath.length) { - if (this._key instanceof Array) { - this._cachedPath.push(...this._path, ...this._key); - } else { - this._cachedPath.push(...this._path, this._key); - } - } - return this._cachedPath; - } -}; -var handleResult = (ctx, result) => { - if (isValid(result)) { - return { success: true, data: result.value }; - } else { - if (!ctx.common.issues.length) { - throw new Error("Validation failed but no issues detected."); - } - return { - success: false, - get error() { - if (this._error) - return this._error; - const error = new ZodError(ctx.common.issues); - this._error = error; - return this._error; - } - }; - } -}; -function processCreateParams(params) { - if (!params) - return {}; - const { errorMap: errorMap2, invalid_type_error, required_error, description } = params; - if (errorMap2 && (invalid_type_error || required_error)) { - throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); - } - if (errorMap2) - return { errorMap: errorMap2, description }; - const customMap = (iss, ctx) => { - var _a, _b; - const { message } = params; - if (iss.code === "invalid_enum_value") { - return { message: message !== null && message !== void 0 ? message : ctx.defaultError }; - } - if (typeof ctx.data === "undefined") { - return { message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError }; - } - if (iss.code !== "invalid_type") - return { message: ctx.defaultError }; - return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError }; - }; - return { errorMap: customMap, description }; -} -var ZodType = class { - constructor(def) { - this.spa = this.safeParseAsync; - this._def = def; - this.parse = this.parse.bind(this); - this.safeParse = this.safeParse.bind(this); - this.parseAsync = this.parseAsync.bind(this); - this.safeParseAsync = this.safeParseAsync.bind(this); - this.spa = this.spa.bind(this); - this.refine = this.refine.bind(this); - this.refinement = this.refinement.bind(this); - this.superRefine = this.superRefine.bind(this); - this.optional = this.optional.bind(this); - this.nullable = this.nullable.bind(this); - this.nullish = this.nullish.bind(this); - this.array = this.array.bind(this); - this.promise = this.promise.bind(this); - this.or = this.or.bind(this); - this.and = this.and.bind(this); - this.transform = this.transform.bind(this); - this.brand = this.brand.bind(this); - this.default = this.default.bind(this); - this.catch = this.catch.bind(this); - this.describe = this.describe.bind(this); - this.pipe = this.pipe.bind(this); - this.readonly = this.readonly.bind(this); - this.isNullable = this.isNullable.bind(this); - this.isOptional = this.isOptional.bind(this); - } - 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); - } - readonly() { - return ZodReadonly.create(this); - } - isOptional() { - return this.safeParse(void 0).success; - } - isNullable() { - return this.safeParse(null).success; - } -}; -var cuidRegex = /^c[^\s-]{8,}$/i; -var cuid2Regex = /^[0-9a-z]+$/; -var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/; -var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; -var nanoidRegex = /^[a-z0-9_-]{21}$/i; -var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; -var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; -var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; -var emojiRegex; -var ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; -var 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})))$/; -var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; -var dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; -var dateRegex = new RegExp(`^${dateRegexSource}$`); -function timeRegexSource(args) { - let regex = `([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d`; - if (args.precision) { - regex = `${regex}\\.\\d{${args.precision}}`; - } else if (args.precision == null) { - regex = `${regex}(\\.\\d+)?`; - } - return regex; -} -function timeRegex(args) { - return new RegExp(`^${timeRegexSource(args)}$`); -} -function datetimeRegex(args) { - let regex = `${dateRegexSource}T${timeRegexSource(args)}`; - const opts = []; - opts.push(args.local ? `Z?` : `Z`); - if (args.offset) - opts.push(`([+-]\\d{2}:?\\d{2})`); - regex = `${regex}(${opts.join("|")})`; - return new RegExp(`^${regex}$`); -} -function isValidIP(ip, version) { - if ((version === "v4" || !version) && ipv4Regex.test(ip)) { - return true; - } - if ((version === "v6" || !version) && ipv6Regex.test(ip)) { - return true; - } - return false; -} -var ZodString = class _ZodString extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = String(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.string) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.string, - received: ctx2.parsedType - }); - return INVALID; - } - const status = new ParseStatus(); - let ctx = void 0; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.length < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - if (input.data.length > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "length") { - const tooBig = input.data.length > check.value; - const tooSmall = input.data.length < check.value; - if (tooBig || tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - if (tooBig) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message - }); - } else if (tooSmall) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message - }); - } - status.dirty(); - } - } else if (check.kind === "email") { - if (!emailRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "email", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "emoji") { - if (!emojiRegex) { - emojiRegex = new RegExp(_emojiRegex, "u"); - } - if (!emojiRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "emoji", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "uuid") { - if (!uuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "uuid", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "nanoid") { - if (!nanoidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "nanoid", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cuid") { - if (!cuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cuid2") { - if (!cuid2Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid2", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "ulid") { - if (!ulidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "ulid", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "url") { - try { - new URL(input.data); - } catch (_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 === "date") { - const regex = dateRegex; - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "date", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "time") { - const regex = timeRegex(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "time", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "duration") { - if (!durationRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "duration", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "ip") { - if (!isValidIP(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "ip", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "base64") { - if (!base64Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "base64", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else { - util.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - _regex(regex, validation, message) { - return this.refinement((data) => regex.test(data), { - validation, - code: ZodIssueCode.invalid_string, - ...errorUtil.errToObj(message) - }); - } - _addCheck(check) { - return new _ZodString({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - email(message) { - return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); - } - url(message) { - return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); - } - emoji(message) { - return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); - } - uuid(message) { - return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); - } - nanoid(message) { - return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) }); - } - cuid(message) { - return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); - } - cuid2(message) { - return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); - } - ulid(message) { - return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); - } - base64(message) { - return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) }); - } - ip(options) { - return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); - } - datetime(options) { - var _a, _b; - if (typeof options === "string") { - return this._addCheck({ - kind: "datetime", - precision: null, - offset: false, - local: false, - message: options - }); - } - return this._addCheck({ - kind: "datetime", - precision: typeof (options === 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, - local: (_b = options === null || options === void 0 ? void 0 : options.local) !== null && _b !== void 0 ? _b : false, - ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message) - }); - } - date(message) { - return this._addCheck({ kind: "date", message }); - } - time(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "time", - precision: null, - message: options - }); - } - return this._addCheck({ - kind: "time", - precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision, - ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message) - }); - } - duration(message) { - return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) }); - } - regex(regex, message) { - return this._addCheck({ - kind: "regex", - regex, - ...errorUtil.errToObj(message) - }); - } - includes(value, options) { - return this._addCheck({ - kind: "includes", - value, - position: options === 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, - ...errorUtil.errToObj(message) - }); - } - endsWith(value, message) { - return this._addCheck({ - kind: "endsWith", - value, - ...errorUtil.errToObj(message) - }); - } - min(minLength, message) { - return this._addCheck({ - kind: "min", - value: minLength, - ...errorUtil.errToObj(message) - }); - } - max(maxLength, message) { - return this._addCheck({ - kind: "max", - value: maxLength, - ...errorUtil.errToObj(message) - }); - } - length(len, message) { - return this._addCheck({ - kind: "length", - value: len, - ...errorUtil.errToObj(message) - }); - } - /** - * @deprecated Use z.string().min(1) instead. - * @see {@link ZodString.min} - */ - nonempty(message) { - return this.min(1, errorUtil.errToObj(message)); - } - trim() { - return new _ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "trim" }] - }); - } - toLowerCase() { - return new _ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "toLowerCase" }] - }); - } - toUpperCase() { - return new _ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "toUpperCase" }] - }); - } - get isDatetime() { - return !!this._def.checks.find((ch) => ch.kind === "datetime"); - } - get isDate() { - return !!this._def.checks.find((ch) => ch.kind === "date"); - } - get isTime() { - return !!this._def.checks.find((ch) => ch.kind === "time"); - } - get isDuration() { - return !!this._def.checks.find((ch) => ch.kind === "duration"); - } - get isEmail() { - return !!this._def.checks.find((ch) => ch.kind === "email"); - } - get isURL() { - return !!this._def.checks.find((ch) => ch.kind === "url"); - } - get isEmoji() { - return !!this._def.checks.find((ch) => ch.kind === "emoji"); - } - get isUUID() { - return !!this._def.checks.find((ch) => ch.kind === "uuid"); - } - get isNANOID() { - return !!this._def.checks.find((ch) => ch.kind === "nanoid"); - } - get isCUID() { - return !!this._def.checks.find((ch) => ch.kind === "cuid"); - } - get isCUID2() { - return !!this._def.checks.find((ch) => ch.kind === "cuid2"); - } - get isULID() { - return !!this._def.checks.find((ch) => ch.kind === "ulid"); - } - get isIP() { - return !!this._def.checks.find((ch) => ch.kind === "ip"); - } - get isBase64() { - return !!this._def.checks.find((ch) => ch.kind === "base64"); - } - 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) - }); -}; -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); -} -var ZodNumber = class _ZodNumber extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - this.step = this.multipleOf; - } - _parse(input) { - if (this._def.coerce) { - input.data = Number(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.number) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.number, - received: ctx2.parsedType - }); - return INVALID; - } - let ctx = void 0; - const status = new ParseStatus(); - for (const check of this._def.checks) { - if (check.kind === "int") { - if (!util.isInteger(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: "integer", - received: "float", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "min") { - const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "multipleOf") { - if (floatSafeRemainder(input.data, check.value) !== 0) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_multiple_of, - multipleOf: check.value, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "finite") { - if (!Number.isFinite(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_finite, - message: check.message - }); - status.dirty(); - } - } else { - util.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new _ZodNumber({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil.toString(message) - } - ] - }); - } - _addCheck(check) { - return new _ZodNumber({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - int(message) { - return this._addCheck({ - kind: "int", - message: errorUtil.toString(message) - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: false, - message: errorUtil.toString(message) - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: false, - message: errorUtil.toString(message) - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: true, - message: errorUtil.toString(message) - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: true, - message: errorUtil.toString(message) - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil.toString(message) - }); - } - finite(message) { - return this._addCheck({ - kind: "finite", - message: errorUtil.toString(message) - }); - } - safe(message) { - return this._addCheck({ - kind: "min", - inclusive: true, - value: Number.MIN_SAFE_INTEGER, - message: errorUtil.toString(message) - })._addCheck({ - kind: "max", - inclusive: true, - value: Number.MAX_SAFE_INTEGER, - message: errorUtil.toString(message) - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } - get isInt() { - return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value)); - } - get isFinite() { - let max = null, 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) - }); -}; -var ZodBigInt = 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 ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.bigint, - received: ctx2.parsedType - }); - return INVALID; - } - let ctx = void 0; - const status = new ParseStatus(); - for (const check of this._def.checks) { - if (check.kind === "min") { - const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - type: "bigint", - minimum: check.value, - inclusive: check.inclusive, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - type: "bigint", - maximum: check.value, - inclusive: check.inclusive, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "multipleOf") { - if (input.data % check.value !== BigInt(0)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_multiple_of, - multipleOf: check.value, - message: check.message - }); - status.dirty(); - } - } else { - util.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - 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) - }); -}; -var ZodBoolean = class extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = Boolean(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.boolean) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.boolean, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodBoolean.create = (params) => { - return new ZodBoolean({ - typeName: ZodFirstPartyTypeKind.ZodBoolean, - coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, - ...processCreateParams(params) - }); -}; -var ZodDate = class _ZodDate extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = new Date(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.date) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.date, - received: ctx2.parsedType - }); - return INVALID; - } - if (isNaN(input.data.getTime())) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_date - }); - return INVALID; - } - const status = new ParseStatus(); - let ctx = void 0; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.getTime() < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - message: check.message, - inclusive: true, - exact: false, - minimum: check.value, - type: "date" - }); - status.dirty(); - } - } else if (check.kind === "max") { - if (input.data.getTime() > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - message: check.message, - inclusive: true, - exact: false, - maximum: check.value, - type: "date" - }); - status.dirty(); - } - } else { - util.assertNever(check); - } - } - return { - status: status.value, - value: new Date(input.data.getTime()) - }; - } - _addCheck(check) { - return new _ZodDate({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - min(minDate, message) { - return this._addCheck({ - kind: "min", - value: minDate.getTime(), - message: errorUtil.toString(message) - }); - } - max(maxDate, message) { - return this._addCheck({ - kind: "max", - value: maxDate.getTime(), - message: errorUtil.toString(message) - }); - } - get minDate() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min != null ? new Date(min) : null; - } - get maxDate() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max != null ? new Date(max) : null; - } -}; -ZodDate.create = (params) => { - return new ZodDate({ - checks: [], - coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, - typeName: ZodFirstPartyTypeKind.ZodDate, - ...processCreateParams(params) - }); -}; -var ZodSymbol = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.symbol) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.symbol, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodSymbol.create = (params) => { - return new ZodSymbol({ - typeName: ZodFirstPartyTypeKind.ZodSymbol, - ...processCreateParams(params) - }); -}; -var ZodUndefined = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.undefined, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodUndefined.create = (params) => { - return new ZodUndefined({ - typeName: ZodFirstPartyTypeKind.ZodUndefined, - ...processCreateParams(params) - }); -}; -var ZodNull = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.null) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.null, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodNull.create = (params) => { - return new ZodNull({ - typeName: ZodFirstPartyTypeKind.ZodNull, - ...processCreateParams(params) - }); -}; -var ZodAny = class extends ZodType { - constructor() { - super(...arguments); - this._any = true; - } - _parse(input) { - return OK(input.data); - } -}; -ZodAny.create = (params) => { - return new ZodAny({ - typeName: ZodFirstPartyTypeKind.ZodAny, - ...processCreateParams(params) - }); -}; -var ZodUnknown = class extends ZodType { - constructor() { - super(...arguments); - this._unknown = true; - } - _parse(input) { - return OK(input.data); - } -}; -ZodUnknown.create = (params) => { - return new ZodUnknown({ - typeName: ZodFirstPartyTypeKind.ZodUnknown, - ...processCreateParams(params) - }); -}; -var ZodNever = class extends ZodType { - _parse(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.never, - received: ctx.parsedType - }); - return INVALID; - } -}; -ZodNever.create = (params) => { - return new ZodNever({ - typeName: ZodFirstPartyTypeKind.ZodNever, - ...processCreateParams(params) - }); -}; -var ZodVoid = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.void, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodVoid.create = (params) => { - return new ZodVoid({ - typeName: ZodFirstPartyTypeKind.ZodVoid, - ...processCreateParams(params) - }); -}; -var ZodArray = class _ZodArray extends ZodType { - _parse(input) { - const { ctx, status } = this._processInputParams(input); - const def = this._def; - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType - }); - return INVALID; - } - if (def.exactLength !== null) { - const tooBig = ctx.data.length > def.exactLength.value; - const tooSmall = ctx.data.length < def.exactLength.value; - if (tooBig || tooSmall) { - addIssueToContext(ctx, { - code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, - minimum: tooSmall ? def.exactLength.value : void 0, - maximum: tooBig ? def.exactLength.value : void 0, - type: "array", - inclusive: true, - exact: true, - message: def.exactLength.message - }); - status.dirty(); - } - } - if (def.minLength !== null) { - if (ctx.data.length < def.minLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: def.minLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.minLength.message - }); - status.dirty(); - } - } - if (def.maxLength !== null) { - if (ctx.data.length > def.maxLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: def.maxLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.maxLength.message - }); - status.dirty(); - } - } - if (ctx.common.async) { - return Promise.all([...ctx.data].map((item, i) => { - return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - })).then((result2) => { - return ParseStatus.mergeArray(status, result2); - }); - } - const result = [...ctx.data].map((item, i) => { - return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - }); - return ParseStatus.mergeArray(status, result); - } - get element() { - return this._def.type; - } - min(minLength, message) { - return new _ZodArray({ - ...this._def, - minLength: { value: minLength, message: errorUtil.toString(message) } - }); - } - max(maxLength, message) { - return new _ZodArray({ - ...this._def, - maxLength: { value: maxLength, message: errorUtil.toString(message) } - }); - } - length(len, message) { - return new _ZodArray({ - ...this._def, - exactLength: { value: len, message: errorUtil.toString(message) } - }); - } - nonempty(message) { - return this.min(1, message); - } -}; -ZodArray.create = (schema, params) => { - return new ZodArray({ - type: schema, - minLength: null, - maxLength: null, - exactLength: null, - typeName: ZodFirstPartyTypeKind.ZodArray, - ...processCreateParams(params) - }); -}; -function deepPartialify(schema) { - if (schema instanceof ZodObject) { - const newShape = {}; - for (const key in schema.shape) { - const fieldSchema = schema.shape[key]; - newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); - } - return new ZodObject({ - ...schema._def, - shape: () => newShape - }); - } else if (schema instanceof ZodArray) { - return new ZodArray({ - ...schema._def, - type: deepPartialify(schema.element) - }); - } else if (schema instanceof ZodOptional) { - return ZodOptional.create(deepPartialify(schema.unwrap())); - } else if (schema instanceof ZodNullable) { - return ZodNullable.create(deepPartialify(schema.unwrap())); - } else if (schema instanceof ZodTuple) { - return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); - } else { - return schema; - } -} -var ZodObject = class _ZodObject extends ZodType { - constructor() { - super(...arguments); - this._cached = null; - this.nonstrict = this.passthrough; - this.augment = this.extend; - } - _getCached() { - if (this._cached !== null) - return this._cached; - const shape = this._def.shape(); - const keys = util.objectKeys(shape); - return this._cached = { shape, keys }; - } - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.object) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx2.parsedType - }); - return INVALID; - } - const { status, ctx } = this._processInputParams(input); - const { shape, keys: shapeKeys } = this._getCached(); - const extraKeys = []; - if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { - for (const key in ctx.data) { - if (!shapeKeys.includes(key)) { - extraKeys.push(key); - } - } - } - const pairs = []; - for (const key of shapeKeys) { - const keyValidator = shape[key]; - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - if (this._def.catchall instanceof ZodNever) { - const unknownKeys = this._def.unknownKeys; - if (unknownKeys === "passthrough") { - for (const key of extraKeys) { - pairs.push({ - key: { status: "valid", value: key }, - value: { status: "valid", value: ctx.data[key] } - }); - } - } else if (unknownKeys === "strict") { - if (extraKeys.length > 0) { - addIssueToContext(ctx, { - code: ZodIssueCode.unrecognized_keys, - keys: extraKeys - }); - status.dirty(); - } - } else if (unknownKeys === "strip") - ; - else { - throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); - } - } else { - const catchall = this._def.catchall; - for (const key of extraKeys) { - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: catchall._parse( - new ParseInputLazyPath(ctx, value, ctx.path, key) - //, ctx.child(key), value, getParsedType(value) - ), - alwaysSet: key in ctx.data - }); - } - } - if (ctx.common.async) { - return Promise.resolve().then(async () => { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value, - alwaysSet: pair.alwaysSet - }); - } - return syncPairs; - }).then((syncPairs) => { - return ParseStatus.mergeObjectSync(status, syncPairs); - }); - } else { - return ParseStatus.mergeObjectSync(status, pairs); - } - } - get shape() { - return this._def.shape(); - } - strict(message) { - errorUtil.errToObj; - return new _ZodObject({ - ...this._def, - unknownKeys: "strict", - ...message !== void 0 ? { - errorMap: (issue, ctx) => { - 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: Def) => - // ( - // augmentation: Augmentation - // ): ZodObject< - // extendShape, 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>, - // 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( - // merging: Incoming - // ): //ZodObject = (merging) => { - // ZodObject< - // extendShape>, - // 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) - }); -}; -var ZodUnion = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const options = this._def.options; - function handleResults(results) { - for (const result of results) { - if (result.result.status === "valid") { - return result.result; - } - } - for (const result of results) { - if (result.result.status === "dirty") { - ctx.common.issues.push(...result.ctx.common.issues); - return result.result; - } - } - const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union, - unionErrors - }); - return INVALID; - } - if (ctx.common.async) { - return Promise.all(options.map(async (option) => { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - return { - result: await option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }), - ctx: childCtx - }; - })).then(handleResults); - } else { - let dirty = void 0; - const issues = []; - for (const option of options) { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - const result = option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }); - if (result.status === "valid") { - return result; - } else if (result.status === "dirty" && !dirty) { - dirty = { result, ctx: childCtx }; - } - if (childCtx.common.issues.length) { - issues.push(childCtx.common.issues); - } - } - if (dirty) { - ctx.common.issues.push(...dirty.ctx.common.issues); - return dirty.result; - } - const unionErrors = issues.map((issues2) => new ZodError(issues2)); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union, - unionErrors - }); - return INVALID; - } - } - get options() { - return this._def.options; - } -}; -ZodUnion.create = (types, params) => { - return new ZodUnion({ - options: types, - typeName: ZodFirstPartyTypeKind.ZodUnion, - ...processCreateParams(params) - }); -}; -var getDiscriminator = (type) => { - if (type instanceof ZodLazy) { - return getDiscriminator(type.schema); - } else if (type instanceof ZodEffects) { - return getDiscriminator(type.innerType()); - } else if (type instanceof ZodLiteral) { - return [type.value]; - } else if (type instanceof ZodEnum) { - return type.options; - } else if (type instanceof ZodNativeEnum) { - return util.objectValues(type.enum); - } else if (type instanceof ZodDefault) { - return getDiscriminator(type._def.innerType); - } else if (type instanceof ZodUndefined) { - return [void 0]; - } else if (type instanceof ZodNull) { - return [null]; - } else if (type instanceof ZodOptional) { - return [void 0, ...getDiscriminator(type.unwrap())]; - } else if (type instanceof ZodNullable) { - return [null, ...getDiscriminator(type.unwrap())]; - } else if (type instanceof ZodBranded) { - return getDiscriminator(type.unwrap()); - } else if (type instanceof ZodReadonly) { - return getDiscriminator(type.unwrap()); - } else if (type instanceof ZodCatch) { - return getDiscriminator(type._def.innerType); - } else { - return []; - } -}; -var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.object) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType - }); - return INVALID; - } - const discriminator = this.discriminator; - const discriminatorValue = ctx.data[discriminator]; - const option = this.optionsMap.get(discriminatorValue); - if (!option) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union_discriminator, - options: Array.from(this.optionsMap.keys()), - path: [discriminator] - }); - return INVALID; - } - if (ctx.common.async) { - return option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } else { - return option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } - } - get discriminator() { - return this._def.discriminator; - } - get options() { - return this._def.options; - } - get optionsMap() { - return this._def.optionsMap; - } - /** - * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. - * However, it only allows a union of objects, all of which need to share a discriminator property. This property must - * have a different value for each object in the union. - * @param discriminator the name of the discriminator property - * @param types an array of object schemas - * @param params - */ - static create(discriminator, options, params) { - const optionsMap = /* @__PURE__ */ new Map(); - for (const type of options) { - const discriminatorValues = getDiscriminator(type.shape[discriminator]); - if (!discriminatorValues.length) { - throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); - } - for (const value of discriminatorValues) { - if (optionsMap.has(value)) { - throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); - } - optionsMap.set(value, type); - } - } - return new _ZodDiscriminatedUnion({ - typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, - discriminator, - options, - optionsMap, - ...processCreateParams(params) - }); - } -}; -function mergeValues(a, b) { - const aType = getParsedType(a); - const bType = getParsedType(b); - if (a === b) { - return { valid: true, data: a }; - } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { - const bKeys = util.objectKeys(b); - const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - for (const key of sharedKeys) { - const sharedValue = mergeValues(a[key], b[key]); - if (!sharedValue.valid) { - return { valid: false }; - } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; - } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { - if (a.length !== b.length) { - return { valid: false }; - } - const newArray = []; - for (let index = 0; index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = mergeValues(itemA, itemB); - if (!sharedValue.valid) { - return { valid: false }; - } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; - } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { - return { valid: true, data: a }; - } else { - return { valid: false }; - } -} -var ZodIntersection = class extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const handleParsed = (parsedLeft, parsedRight) => { - if (isAborted(parsedLeft) || isAborted(parsedRight)) { - return INVALID; - } - const merged = mergeValues(parsedLeft.value, parsedRight.value); - if (!merged.valid) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_intersection_types - }); - return INVALID; - } - if (isDirty(parsedLeft) || isDirty(parsedRight)) { - status.dirty(); - } - return { status: status.value, value: merged.data }; - }; - if (ctx.common.async) { - return Promise.all([ - this._def.left._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), - this._def.right._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }) - ]).then(([left, right]) => handleParsed(left, right)); - } else { - return handleParsed(this._def.left._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), this._def.right._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - })); - } - } -}; -ZodIntersection.create = (left, right, params) => { - return new ZodIntersection({ - left, - right, - typeName: ZodFirstPartyTypeKind.ZodIntersection, - ...processCreateParams(params) - }); -}; -var ZodTuple = class _ZodTuple extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType - }); - return INVALID; - } - if (ctx.data.length < this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - return INVALID; - } - const rest = this._def.rest; - if (!rest && ctx.data.length > this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - status.dirty(); - } - const items = [...ctx.data].map((item, itemIndex) => { - const schema = this._def.items[itemIndex] || this._def.rest; - if (!schema) - return null; - return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); - }).filter((x) => !!x); - if (ctx.common.async) { - return Promise.all(items).then((results) => { - return ParseStatus.mergeArray(status, results); - }); - } else { - return ParseStatus.mergeArray(status, items); - } - } - get items() { - return this._def.items; - } - rest(rest) { - return new _ZodTuple({ - ...this._def, - rest - }); - } -}; -ZodTuple.create = (schemas, params) => { - if (!Array.isArray(schemas)) { - throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); - } - return new ZodTuple({ - items: schemas, - typeName: ZodFirstPartyTypeKind.ZodTuple, - rest: null, - ...processCreateParams(params) - }); -}; -var ZodRecord = class _ZodRecord extends ZodType { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.object) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType - }); - return INVALID; - } - const pairs = []; - const keyType = this._def.keyType; - const valueType = this._def.valueType; - for (const key in ctx.data) { - pairs.push({ - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), - value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - if (ctx.common.async) { - return ParseStatus.mergeObjectAsync(status, pairs); - } else { - return ParseStatus.mergeObjectSync(status, pairs); - } - } - get element() { - return this._def.valueType; - } - static create(first, second, third) { - if (second instanceof ZodType) { - return new _ZodRecord({ - keyType: first, - valueType: second, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(third) - }); - } - return new _ZodRecord({ - keyType: ZodString.create(), - valueType: first, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(second) - }); - } -}; -var ZodMap = class extends ZodType { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.map) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.map, - received: ctx.parsedType - }); - return INVALID; - } - const keyType = this._def.keyType; - const valueType = this._def.valueType; - const pairs = [...ctx.data.entries()].map(([key, value], index) => { - return { - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), - value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])) - }; - }); - if (ctx.common.async) { - const finalMap = /* @__PURE__ */ new Map(); - return Promise.resolve().then(async () => { - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - }); - } else { - const finalMap = /* @__PURE__ */ new Map(); - for (const pair of pairs) { - const key = pair.key; - const value = pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - } - } -}; -ZodMap.create = (keyType, valueType, params) => { - return new ZodMap({ - valueType, - keyType, - typeName: ZodFirstPartyTypeKind.ZodMap, - ...processCreateParams(params) - }); -}; -var ZodSet = class _ZodSet extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.set) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.set, - received: ctx.parsedType - }); - return INVALID; - } - const def = this._def; - if (def.minSize !== null) { - if (ctx.data.size < def.minSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: def.minSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.minSize.message - }); - status.dirty(); - } - } - if (def.maxSize !== null) { - if (ctx.data.size > def.maxSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: def.maxSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.maxSize.message - }); - status.dirty(); - } - } - const valueType = this._def.valueType; - function finalizeSet(elements2) { - const parsedSet = /* @__PURE__ */ new Set(); - for (const element of elements2) { - if (element.status === "aborted") - return INVALID; - if (element.status === "dirty") - status.dirty(); - parsedSet.add(element.value); - } - return { status: status.value, value: parsedSet }; - } - const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); - if (ctx.common.async) { - return Promise.all(elements).then((elements2) => finalizeSet(elements2)); - } else { - return finalizeSet(elements); - } - } - min(minSize, message) { - return new _ZodSet({ - ...this._def, - minSize: { value: minSize, message: errorUtil.toString(message) } - }); - } - max(maxSize, message) { - return new _ZodSet({ - ...this._def, - maxSize: { value: maxSize, message: errorUtil.toString(message) } - }); - } - size(size, message) { - return this.min(size, message).max(size, message); - } - nonempty(message) { - return this.min(1, message); - } -}; -ZodSet.create = (valueType, params) => { - return new ZodSet({ - valueType, - minSize: null, - maxSize: null, - typeName: ZodFirstPartyTypeKind.ZodSet, - ...processCreateParams(params) - }); -}; -var ZodFunction = class _ZodFunction extends ZodType { - constructor() { - super(...arguments); - this.validate = this.implement; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.function) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.function, - received: ctx.parsedType - }); - return INVALID; - } - function makeArgsIssue(args, error) { - return makeIssue({ - data: args, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - getErrorMap(), - 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) { - const me = this; - return OK(async function(...args) { - const error = new ZodError([]); - const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { - error.addIssue(makeArgsIssue(args, e)); - throw error; - }); - const result = await Reflect.apply(fn, this, parsedArgs); - const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => { - error.addIssue(makeReturnsIssue(result, e)); - throw error; - }); - return parsedReturns; - }); - } else { - const me = this; - return OK(function(...args) { - const parsedArgs = me._def.args.safeParse(args, params); - if (!parsedArgs.success) { - throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); - } - const result = Reflect.apply(fn, this, parsedArgs.data); - const parsedReturns = me._def.returns.safeParse(result, params); - if (!parsedReturns.success) { - throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); - } - return parsedReturns.data; - }); - } - } - parameters() { - return this._def.args; - } - returnType() { - return this._def.returns; - } - args(...items) { - return new _ZodFunction({ - ...this._def, - args: ZodTuple.create(items).rest(ZodUnknown.create()) - }); - } - returns(returnType) { - return new _ZodFunction({ - ...this._def, - returns: returnType - }); - } - implement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - strictImplement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - static create(args, returns, params) { - return new _ZodFunction({ - args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()), - returns: returns || ZodUnknown.create(), - typeName: ZodFirstPartyTypeKind.ZodFunction, - ...processCreateParams(params) - }); - } -}; -var ZodLazy = class extends ZodType { - get schema() { - return this._def.getter(); - } - _parse(input) { - const { ctx } = this._processInputParams(input); - const lazySchema = this._def.getter(); - return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); - } -}; -ZodLazy.create = (getter, params) => { - return new ZodLazy({ - getter, - typeName: ZodFirstPartyTypeKind.ZodLazy, - ...processCreateParams(params) - }); -}; -var ZodLiteral = class extends ZodType { - _parse(input) { - if (input.data !== this._def.value) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_literal, - expected: this._def.value - }); - return INVALID; - } - return { status: "valid", value: input.data }; - } - get value() { - return this._def.value; - } -}; -ZodLiteral.create = (value, params) => { - return new ZodLiteral({ - value, - typeName: ZodFirstPartyTypeKind.ZodLiteral, - ...processCreateParams(params) - }); -}; -function createZodEnum(values, params) { - return new ZodEnum({ - values, - typeName: ZodFirstPartyTypeKind.ZodEnum, - ...processCreateParams(params) - }); -} -var ZodEnum = class _ZodEnum extends ZodType { - constructor() { - super(...arguments); - _ZodEnum_cache.set(this, void 0); - } - _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 (!__classPrivateFieldGet(this, _ZodEnum_cache, "f")) { - __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), "f"); - } - if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f").has(input.data)) { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_enum_value, - options: expectedValues - }); - return INVALID; - } - return OK(input.data); - } - get options() { - return this._def.values; - } - get enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Values() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - extract(values, newDef = this._def) { - return _ZodEnum.create(values, { - ...this._def, - ...newDef - }); - } - exclude(values, newDef = this._def) { - return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { - ...this._def, - ...newDef - }); - } -}; -_ZodEnum_cache = /* @__PURE__ */ new WeakMap(); -ZodEnum.create = createZodEnum; -var ZodNativeEnum = class extends ZodType { - constructor() { - super(...arguments); - _ZodNativeEnum_cache.set(this, void 0); - } - _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 (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f")) { - __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)), "f"); - } - if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f").has(input.data)) { - const expectedValues = util.objectValues(nativeEnumValues); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_enum_value, - options: expectedValues - }); - return INVALID; - } - return OK(input.data); - } - get enum() { - return this._def.values; - } -}; -_ZodNativeEnum_cache = /* @__PURE__ */ new WeakMap(); -ZodNativeEnum.create = (values, params) => { - return new ZodNativeEnum({ - values, - typeName: ZodFirstPartyTypeKind.ZodNativeEnum, - ...processCreateParams(params) - }); -}; -var ZodPromise = class extends ZodType { - unwrap() { - return this._def.type; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.promise, - received: ctx.parsedType - }); - return INVALID; - } - const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); - return OK(promisified.then((data) => { - return this._def.type.parseAsync(data, { - path: ctx.path, - errorMap: ctx.common.contextualErrorMap - }); - })); - } -}; -ZodPromise.create = (schema, params) => { - return new ZodPromise({ - type: schema, - typeName: ZodFirstPartyTypeKind.ZodPromise, - ...processCreateParams(params) - }); -}; -var ZodEffects = class extends ZodType { - innerType() { - return this._def.schema; - } - sourceType() { - return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const effect = this._def.effect || null; - const checkCtx = { - addIssue: (arg) => { - addIssueToContext(ctx, arg); - if (arg.fatal) { - status.abort(); - } else { - status.dirty(); - } - }, - get path() { - return ctx.path; - } - }; - checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); - if (effect.type === "preprocess") { - const processed = effect.transform(ctx.data, checkCtx); - if (ctx.common.async) { - return Promise.resolve(processed).then(async (processed2) => { - if (status.value === "aborted") - return INVALID; - const result = await this._def.schema._parseAsync({ - data: processed2, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID; - if (result.status === "dirty") - return DIRTY(result.value); - if (status.value === "dirty") - return DIRTY(result.value); - return result; - }); - } else { - if (status.value === "aborted") - return INVALID; - const result = this._def.schema._parseSync({ - data: processed, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID; - if (result.status === "dirty") - return DIRTY(result.value); - if (status.value === "dirty") - return DIRTY(result.value); - return result; - } - } - if (effect.type === "refinement") { - const executeRefinement = (acc) => { - const result = effect.refinement(acc, checkCtx); - if (ctx.common.async) { - return Promise.resolve(result); - } - if (result instanceof Promise) { - throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); - } - return acc; - }; - if (ctx.common.async === false) { - const inner = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inner.status === "aborted") - return INVALID; - if (inner.status === "dirty") - status.dirty(); - executeRefinement(inner.value); - return { status: status.value, value: inner.value }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { - if (inner.status === "aborted") - return INVALID; - if (inner.status === "dirty") - status.dirty(); - return executeRefinement(inner.value).then(() => { - return { status: status.value, value: inner.value }; - }); - }); - } - } - if (effect.type === "transform") { - if (ctx.common.async === false) { - const base = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (!isValid(base)) - return 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) - }); -}; -var ZodOptional = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType.undefined) { - return OK(void 0); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -}; -ZodOptional.create = (type, params) => { - return new ZodOptional({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodOptional, - ...processCreateParams(params) - }); -}; -var ZodNullable = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType.null) { - return OK(null); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -}; -ZodNullable.create = (type, params) => { - return new ZodNullable({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodNullable, - ...processCreateParams(params) - }); -}; -var ZodDefault = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - let data = ctx.data; - if (ctx.parsedType === ZodParsedType.undefined) { - data = this._def.defaultValue(); - } - return this._def.innerType._parse({ - data, - path: ctx.path, - parent: ctx - }); - } - removeDefault() { - return this._def.innerType; - } -}; -ZodDefault.create = (type, params) => { - return new ZodDefault({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodDefault, - defaultValue: typeof params.default === "function" ? params.default : () => params.default, - ...processCreateParams(params) - }); -}; -var ZodCatch = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const newCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - } - }; - const result = this._def.innerType._parse({ - data: newCtx.data, - path: newCtx.path, - parent: { - ...newCtx - } - }); - if (isAsync(result)) { - return result.then((result2) => { - return { - status: "valid", - value: result2.status === "valid" ? result2.value : this._def.catchValue({ - get error() { - return new ZodError(newCtx.common.issues); - }, - input: newCtx.data - }) - }; - }); - } else { - return { - status: "valid", - value: result.status === "valid" ? result.value : this._def.catchValue({ - get error() { - return new ZodError(newCtx.common.issues); - }, - input: newCtx.data - }) - }; - } - } - removeCatch() { - return this._def.innerType; - } -}; -ZodCatch.create = (type, params) => { - return new ZodCatch({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodCatch, - catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, - ...processCreateParams(params) - }); -}; -var ZodNaN = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.nan) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.nan, - received: ctx.parsedType - }); - return INVALID; - } - return { status: "valid", value: input.data }; - } -}; -ZodNaN.create = (params) => { - return new ZodNaN({ - typeName: ZodFirstPartyTypeKind.ZodNaN, - ...processCreateParams(params) - }); -}; -var BRAND = Symbol("zod_brand"); -var ZodBranded = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const data = ctx.data; - return this._def.type._parse({ - data, - path: ctx.path, - parent: ctx - }); - } - unwrap() { - return this._def.type; - } -}; -var ZodPipeline = class _ZodPipeline extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.common.async) { - const handleAsync = async () => { - const inResult = await this._def.in._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return DIRTY(inResult.value); - } else { - return this._def.out._parseAsync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - }; - return handleAsync(); - } else { - const inResult = this._def.in._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return { - status: "dirty", - value: inResult.value - }; - } else { - return this._def.out._parseSync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - } - } - static create(a, b) { - return new _ZodPipeline({ - in: a, - out: b, - typeName: ZodFirstPartyTypeKind.ZodPipeline - }); - } -}; -var ZodReadonly = class extends ZodType { - _parse(input) { - const result = this._def.innerType._parse(input); - const freeze = (data) => { - if (isValid(data)) { - data.value = Object.freeze(data.value); - } - return data; - }; - return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result); - } - unwrap() { - return this._def.innerType; - } -}; -ZodReadonly.create = (type, params) => { - return new ZodReadonly({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodReadonly, - ...processCreateParams(params) - }); -}; -function custom(check, params = {}, 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(); -} -var late = { - object: ZodObject.lazycreate -}; -var ZodFirstPartyTypeKind; -(function(ZodFirstPartyTypeKind2) { - ZodFirstPartyTypeKind2["ZodString"] = "ZodString"; - ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber"; - ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN"; - ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt"; - ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean"; - ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate"; - ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol"; - ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined"; - ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull"; - ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny"; - ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown"; - ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever"; - ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid"; - ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray"; - ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject"; - ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion"; - ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; - ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection"; - ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple"; - ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord"; - ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap"; - ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet"; - ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction"; - ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy"; - ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral"; - ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum"; - ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects"; - ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum"; - ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional"; - ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable"; - ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault"; - ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch"; - ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise"; - ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded"; - ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline"; - ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly"; -})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); -var instanceOfType = (cls, params = { - message: `Input not instance of ${cls.name}` -}) => custom((data) => data instanceof cls, params); -var stringType = ZodString.create; -var numberType = ZodNumber.create; -var nanType = ZodNaN.create; -var bigIntType = ZodBigInt.create; -var booleanType = ZodBoolean.create; -var dateType = ZodDate.create; -var symbolType = ZodSymbol.create; -var undefinedType = ZodUndefined.create; -var nullType = ZodNull.create; -var anyType = ZodAny.create; -var unknownType = ZodUnknown.create; -var neverType = ZodNever.create; -var voidType = ZodVoid.create; -var arrayType = ZodArray.create; -var objectType = ZodObject.create; -var strictObjectType = ZodObject.strictCreate; -var unionType = ZodUnion.create; -var discriminatedUnionType = ZodDiscriminatedUnion.create; -var intersectionType = ZodIntersection.create; -var tupleType = ZodTuple.create; -var recordType = ZodRecord.create; -var mapType = ZodMap.create; -var setType = ZodSet.create; -var functionType = ZodFunction.create; -var lazyType = ZodLazy.create; -var literalType = ZodLiteral.create; -var enumType = ZodEnum.create; -var nativeEnumType = ZodNativeEnum.create; -var promiseType = ZodPromise.create; -var effectsType = ZodEffects.create; -var optionalType = ZodOptional.create; -var nullableType = ZodNullable.create; -var preprocessType = ZodEffects.createWithPreprocess; -var pipelineType = ZodPipeline.create; -var ostring = () => stringType().optional(); -var onumber = () => numberType().optional(); -var oboolean = () => booleanType().optional(); -var coerce = { - string: (arg) => ZodString.create({ ...arg, coerce: true }), - number: (arg) => ZodNumber.create({ ...arg, coerce: true }), - boolean: (arg) => ZodBoolean.create({ - ...arg, - coerce: true - }), - bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }), - date: (arg) => ZodDate.create({ ...arg, coerce: true }) -}; -var NEVER = INVALID; -var z = /* @__PURE__ */ Object.freeze({ - __proto__: null, - defaultErrorMap: errorMap, - setErrorMap, - getErrorMap, - makeIssue, - EMPTY_PATH, - addIssueToContext, - ParseStatus, - INVALID, - DIRTY, - OK, - isAborted, - isDirty, - isValid, - isAsync, - get util() { - return util; - }, - get objectUtil() { - return objectUtil; - }, - ZodParsedType, - getParsedType, - ZodType, - datetimeRegex, - ZodString, - ZodNumber, - ZodBigInt, - ZodBoolean, - ZodDate, - ZodSymbol, - ZodUndefined, - ZodNull, - ZodAny, - ZodUnknown, - ZodNever, - ZodVoid, - ZodArray, - ZodObject, - ZodUnion, - ZodDiscriminatedUnion, - ZodIntersection, - ZodTuple, - ZodRecord, - ZodMap, - ZodSet, - ZodFunction, - ZodLazy, - ZodLiteral, - ZodEnum, - ZodNativeEnum, - ZodPromise, - ZodEffects, - ZodTransformer: ZodEffects, - ZodOptional, - ZodNullable, - ZodDefault, - ZodCatch, - ZodNaN, - BRAND, - ZodBranded, - ZodPipeline, - ZodReadonly, - custom, - Schema: ZodType, - ZodSchema: ZodType, - late, - get ZodFirstPartyTypeKind() { - return ZodFirstPartyTypeKind; - }, - 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, - onumber, - optional: optionalType, - 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, - ZodIssueCode, - quotelessJson, - ZodError -}); - -// ../generated/schema.js -var LogLevelDTO = /* @__PURE__ */ ((LogLevelDTO22) => { - LogLevelDTO22["Info"] = "info"; - LogLevelDTO22["Debug"] = "debug"; - LogLevelDTO22["Trace"] = "trace"; - LogLevelDTO22["Error"] = "error"; - return LogLevelDTO22; -})(LogLevelDTO || {}); -var EventLevel = /* @__PURE__ */ ((EventLevel2) => { - EventLevel2["External"] = "BSLIVE_EXTERNAL"; - return EventLevel2; -})(EventLevel || {}); -var ChangeKind = /* @__PURE__ */ ((ChangeKind2) => { - ChangeKind2["Changed"] = "Changed"; - ChangeKind2["Added"] = "Added"; - ChangeKind2["Removed"] = "Removed"; - return ChangeKind2; -})(ChangeKind || {}); -var routeKindDTOSchema = z.union([ - z.object({ - kind: z.literal("Html"), - payload: z.object({ - html: z.string() - }) - }), - z.object({ - kind: z.literal("Json"), - payload: z.object({ - json_str: z.string() - }) - }), - z.object({ - kind: z.literal("Raw"), - payload: z.object({ - raw: z.string() - }) - }), - z.object({ - kind: z.literal("Sse"), - payload: z.object({ - sse: z.string() - }) - }), - z.object({ - kind: z.literal("Proxy"), - payload: z.object({ - proxy: z.string() - }) - }), - z.object({ - kind: z.literal("Dir"), - payload: z.object({ - dir: z.string(), - base: z.string().optional() - }) - }) -]); -var routeDTOSchema = z.object({ - path: z.string(), - kind: routeKindDTOSchema -}); -var serverDescSchema = z.object({ - routes: z.array(routeDTOSchema), - id: z.string() -}); -var serverIdentityDTOSchema = z.union([ - z.object({ - kind: z.literal("Both"), - payload: z.object({ - name: z.string(), - bind_address: z.string() - }) - }), - z.object({ - kind: z.literal("Address"), - payload: z.object({ - bind_address: z.string() - }) - }), - z.object({ - kind: z.literal("Named"), - payload: z.object({ - name: z.string() - }) - }) -]); -var serverDTOSchema = z.object({ - id: z.string(), - identity: serverIdentityDTOSchema, - socket_addr: z.string() -}); -var getServersMessageResponseDTOSchema = z.object({ - servers: z.array(serverDTOSchema) -}); -var serversChangedDTOSchema = z.object({ - servers_resp: getServersMessageResponseDTOSchema -}); -var inputAcceptedDTOSchema = z.object({ - path: z.string() -}); -var fileChangedDTOSchema = z.object({ - path: z.string() -}); -var filesChangedDTOSchema = z.object({ - paths: z.array(z.string()) -}); -var debounceDTOSchema = z.object({ - kind: z.string(), - ms: z.string() -}); -var watchingDTOSchema = z.object({ - paths: z.array(z.string()), - debounce: debounceDTOSchema -}); -var stoppedWatchingDTOSchema = z.object({ - paths: z.array(z.string()) -}); -var serverChangeSchema = z.union([ - z.object({ - kind: z.literal("Stopped"), - payload: z.object({ - bind_address: z.string() - }) - }), - z.object({ - kind: z.literal("Started"), - payload: z.undefined().optional() - }), - z.object({ - kind: z.literal("Patched"), - payload: z.undefined().optional() - }), - z.object({ - kind: z.literal("Errored"), - payload: z.object({ - error: z.string() - }) - }) -]); -var serverChangeSetItemSchema = z.object({ - identity: serverIdentityDTOSchema, - change: serverChangeSchema -}); -var serverChangeSetSchema = z.object({ - items: z.array(serverChangeSetItemSchema) -}); -var logLevelDTOSchema = z.nativeEnum(LogLevelDTO); -var clientConfigDTOSchema = z.object({ - log_level: logLevelDTOSchema -}); -var internalEventsDTOSchema = z.object({ - kind: z.literal("ServersChanged"), - payload: getServersMessageResponseDTOSchema -}); -var eventLevelSchema = z.nativeEnum(EventLevel); -var externalEventsDTOSchema = z.union([ - z.object({ - kind: z.literal("ServersChanged"), - payload: serversChangedDTOSchema - }), - z.object({ - kind: z.literal("Watching"), - payload: watchingDTOSchema - }), - z.object({ - kind: z.literal("WatchingStopped"), - payload: stoppedWatchingDTOSchema - }), - z.object({ - kind: z.literal("FileChanged"), - payload: fileChangedDTOSchema - }), - z.object({ - kind: z.literal("FilesChanged"), - payload: filesChangedDTOSchema - }), - z.object({ - kind: z.literal("InputFileChanged"), - payload: fileChangedDTOSchema - }), - z.object({ - kind: z.literal("InputAccepted"), - payload: inputAcceptedDTOSchema - }) -]); -var startupEventDTOSchema = z.union([ - z.object({ - kind: z.literal("Started"), - payload: z.undefined().optional() - }), - z.object({ - kind: z.literal("FailedStartup"), - payload: z.string() - }) -]); -var inputErrorDTOSchema = z.union([ - z.object({ - kind: z.literal("MissingInputs"), - payload: z.string() - }), - z.object({ - kind: z.literal("InvalidInput"), - payload: z.string() - }), - z.object({ - kind: z.literal("NotFound"), - payload: z.string() - }), - z.object({ - kind: z.literal("InputWriteError"), - payload: z.string() - }), - z.object({ - kind: z.literal("PathError"), - payload: z.string() - }), - z.object({ - kind: z.literal("PortError"), - payload: z.string() - }), - z.object({ - kind: z.literal("DirError"), - payload: z.string() - }), - z.object({ - kind: z.literal("YamlError"), - payload: z.string() - }), - z.object({ - kind: z.literal("MarkdownError"), - payload: z.string() - }), - z.object({ - kind: z.literal("Io"), - payload: z.string() - }), - z.object({ - kind: z.literal("UnsupportedExtension"), - payload: z.string() - }), - z.object({ - kind: z.literal("MissingExtension"), - payload: z.string() - }), - z.object({ - kind: z.literal("EmptyInput"), - payload: z.string() - }), - z.object({ - kind: z.literal("BsLiveRules"), - payload: z.string() - }) -]); -var changeKindSchema = z.nativeEnum(ChangeKind); -var changeDTOSchema = z.lazy( - () => z.union([ - z.object({ - kind: z.literal("Fs"), - payload: z.object({ - path: z.string(), - change_kind: changeKindSchema - }) - }), - z.object({ - kind: z.literal("FsMany"), - payload: z.array(changeDTOSchema) - }) - ]) -); -var clientEventSchema = z.union([ - z.object({ - kind: z.literal("Change"), - payload: changeDTOSchema - }), - z.object({ - kind: z.literal("Config"), - payload: clientConfigDTOSchema - }) -]); - -// src/console.ts -function createLRConsoleObserver() { - const subject = new Subject(); - return [subject, { - debug: function(...data) { - subject.next({ - level: "debug" /* Debug */, - text: data.join("\n") - }); - }, - info: function(...data) { - subject.next({ - level: "info" /* Info */, - text: data.join("\n") - }); - }, - trace: function(...data) { - subject.next({ - level: "trace" /* Trace */, - text: data.join("\n") - }); - }, - error: function(...data) { - subject.next({ - level: "error" /* Error */, - text: data.join("\n") - }); - } - }]; -} - -// src/index.ts -var [consoleSubject, consoleApi] = createLRConsoleObserver(); -var r = new Reloader(window, consoleApi, import_timer2.Timer); -var url = new URL(window.location.href); -url.protocol = url.protocol === "http:" ? "ws" : "wss"; -url.pathname = "/__bs_ws"; -var socket = webSocket(url.origin + url.pathname); -var sub$ = socket.pipe(retry({ delay: 5e3 })); -var change$ = sub$.pipe(filter((x) => x.kind === "Change")); -var config$ = sub$.pipe(filter((x) => x.kind === "Config"), map((x) => x.payload)); -change$.pipe(withLatestFrom(config$)).subscribe(([change, config2]) => { - consoleApi.trace("incoming message", JSON.stringify({ change, config: config2 }, null, 2)); - const parsed = clientEventSchema.parse(change); - switch (parsed.kind) { - case "Change": { - changedPath(parsed.payload); - break; - } - default: { - console.warn("unhandled client event"); - } - } -}); -var IMAGES_REGEX2 = /\.(jpe?g|png|gif|svg)$/i; -function changedPath(change) { - switch (change.kind) { - case "FsMany": { - const hasNoneInjectable = change.payload.some((changeDTO) => { - switch (changeDTO.kind) { - case "Fs": - if (changeDTO.payload.path.match(/\.css(?:\.map)?$/i)) { - return false; - } - if (changeDTO.payload.path.match(IMAGES_REGEX2)) { - return false; - } - return true; - case "FsMany": - throw new Error("unreachable"); - } - }); - if (hasNoneInjectable) { - if (window.__playwright?.record) { - return window.__playwright?.record({ - kind: "reloadPage" - }); - } else { - return r.reloadPage(); - } - } - for (let changeDTO of change.payload) { - changedPath(changeDTO); - } - break; - } - case "Fs": { - let path = change.payload.path; - const opts = { - liveCSS: true, - liveImg: true, - reloadMissingCSS: true, - originalPath: "", - overrideURL: "", - serverURL: `` - }; - if (window.__playwright?.record) { - window.__playwright?.record({ - kind: "reload", - args: { - path, - opts - } - }); - } else { - consoleApi.trace("will reload a file with path ", path); - r.reload(path, opts); - } - } - } -} -consoleSubject.pipe(withLatestFrom(config$)).subscribe(([evt, config2]) => { - const levelOrder = ["trace" /* Trace */, "debug" /* Debug */, "info" /* Info */, "error" /* Error */]; - const currentLevelIndex = levelOrder.indexOf(evt.level); - const configLevelIndex = levelOrder.indexOf(config2.log_level); - if (currentLevelIndex >= configLevelIndex) { - console.log(`[${evt.level}] ${evt.text}`); - } -}); -function logMessage(message, level, config2) { -} -export { - logMessage -}; +var Mr=Object.create;var Ot=Object.defineProperty;var Lr=Object.getOwnPropertyDescriptor;var Zr=Object.getOwnPropertyNames;var $r=Object.getPrototypeOf,Ur=Object.prototype.hasOwnProperty;var Vr=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var Wr=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Zr(e))!Ur.call(r,i)&&i!==t&&Ot(r,i,{get:()=>e[i],enumerable:!(n=Lr(e,i))||n.enumerable});return r};var Fr=(r,e,t)=>(t=r!=null?Mr($r(r)):{},Wr(e||!r||!r.__esModule?Ot(t,"default",{value:r,enumerable:!0}):t,r));var Nt=Vr(At=>{"use strict";var Be=class{constructor(e){this.func=e,this.running=!1,this.id=null,this._handler=()=>(this.running=!1,this.id=null,this.func())}start(e){this.running&&clearTimeout(this.id),this.id=setTimeout(this._handler,e),this.running=!0}stop(){this.running&&(clearTimeout(this.id),this.running=!1,this.id=null)}};Be.start=(r,e)=>setTimeout(e,r);At.Timer=Be});var jt=[{selector:"background",styleNames:["backgroundImage"]},{selector:"border",styleNames:["borderImage","webkitBorderImage","MozBorderImage"]}],We={stylesheetReloadTimeout:15e3},Br=/\.(jpe?g|png|gif|svg)$/i,Fe=class{constructor(e,t,n){this.window=e,this.console=t,this.Timer=n,this.document=this.window.document,this.importCacheWaitPeriod=200,this.plugins=[]}addPlugin(e){return this.plugins.push(e)}analyze(e){}reload(e,t={}){if(this.options={...We,...t},!(t.liveCSS&&e.match(/\.css(?:\.map)?$/i)&&this.reloadStylesheet(e))){if(t.liveImg&&e.match(Br)){this.reloadImages(e);return}if(t.isChromeExtension){this.reloadChromeExtension();return}return this.reloadPage()}}reloadPage(){return this.window.document.location.reload()}reloadChromeExtension(){return this.window.chrome.runtime.reload()}reloadImages(e){let t,n=this.generateUniqueString();for(t of Array.from(this.document.images))Ct(e,dt(t.src))&&(t.src=this.generateCacheBustUrl(t.src,n));if(this.document.querySelectorAll)for(let{selector:i,styleNames:o}of jt)for(t of Array.from(this.document.querySelectorAll(`[style*=${i}]`)))this.reloadStyleImages(t.style,o,e,n);if(this.document.styleSheets)return Array.from(this.document.styleSheets).map(i=>this.reloadStylesheetImages(i,e,n))}reloadStylesheetImages(e,t,n){let i;try{i=(e||{}).cssRules}catch{}if(i)for(let o of Array.from(i))switch(o.type){case CSSRule.IMPORT_RULE:this.reloadStylesheetImages(o.styleSheet,t,n);break;case CSSRule.STYLE_RULE:for(let{styleNames:s}of jt)this.reloadStyleImages(o.style,s,t,n);break;case CSSRule.MEDIA_RULE:this.reloadStylesheetImages(o,t,n);break}}reloadStyleImages(e,t,n,i){for(let o of t){let s=e[o];if(typeof s=="string"){let a=s.replace(new RegExp("\\burl\\s*\\(([^)]*)\\)"),(u,l)=>Ct(n,dt(l))?`url(${this.generateCacheBustUrl(l,i)})`:u);a!==s&&(e[o]=a)}}}reloadStylesheet(e){let t=this.options||We,n,i,o=(()=>{let u=[];for(i of Array.from(this.document.getElementsByTagName("link")))i.rel.match(/^stylesheet$/i)&&!i.__LiveReload_pendingRemoval&&u.push(i);return u})(),s=[];for(n of Array.from(this.document.getElementsByTagName("style")))n.sheet&&this.collectImportedStylesheets(n,n.sheet,s);for(i of Array.from(o))this.collectImportedStylesheets(i,i.sheet,s);if(this.window.StyleFix&&this.document.querySelectorAll)for(n of Array.from(this.document.querySelectorAll("style[data-href]")))o.push(n);this.console.debug(`found ${o.length} LINKed stylesheets, ${s.length} @imported stylesheets`);let a=zr(e,o.concat(s),u=>dt(this.linkHref(u)));if(a)a.object.rule?(this.console.debug(`is reloading imported stylesheet: ${a.object.href}`),this.reattachImportedRule(a.object)):(this.console.debug(`is reloading stylesheet: ${this.linkHref(a.object)}`),this.reattachStylesheetLink(a.object));else if(t.reloadMissingCSS){this.console.debug(`will reload all stylesheets because path '${e}' did not match any specific one. To disable this behavior, set 'options.reloadMissingCSS' to 'false'.`);for(i of Array.from(o))this.reattachStylesheetLink(i)}else this.console.debug(`will not reload path '${e}' because the stylesheet was not found on the page and 'options.reloadMissingCSS' was set to 'false'.`);return!0}collectImportedStylesheets(e,t,n){let i;try{i=(t||{}).cssRules}catch{}if(i&&i.length)for(let o=0;o{if(!i)return i=!0,t()};if(e.onload=()=>(this.console.debug("the new stylesheet has finished loading"),this.knownToSupportCssOnLoad=!0,o()),!this.knownToSupportCssOnLoad){let s;(s=()=>e.sheet?(this.console.debug("is polling until the new CSS finishes loading..."),o()):this.Timer.start(50,s))()}return this.Timer.start(n.stylesheetReloadTimeout,o)}linkHref(e){return e.href||e.getAttribute&&e.getAttribute("data-href")}reattachStylesheetLink(e){let t;if(e.__LiveReload_pendingRemoval)return;e.__LiveReload_pendingRemoval=!0,e.tagName==="STYLE"?(t=this.document.createElement("link"),t.rel="stylesheet",t.media=e.media,t.disabled=e.disabled):t=e.cloneNode(!1),t.href=this.generateCacheBustUrl(this.linkHref(e));let n=e.parentNode;return n.lastChild===e?n.appendChild(t):n.insertBefore(t,e.nextSibling),this.waitUntilCssLoads(t,()=>{let i;return/AppleWebKit/.test(this.window.navigator.userAgent)?i=5:i=200,this.Timer.start(i,()=>{if(e.parentNode)return e.parentNode.removeChild(e),t.onreadystatechange=null,this.window.StyleFix?this.window.StyleFix.link(t):void 0})})}reattachImportedRule({rule:e,index:t,link:n}){let i=e.parentStyleSheet,o=this.generateCacheBustUrl(e.href),s=e.media.length?[].join.call(e.media,", "):"",a=`@import url("${o}") ${s};`;e.__LiveReload_newHref=o;let u=this.document.createElement("link");return u.rel="stylesheet",u.href=o,u.__LiveReload_pendingRemoval=!0,n.parentNode&&n.parentNode.insertBefore(u,n),this.Timer.start(this.importCacheWaitPeriod,()=>{if(u.parentNode&&u.parentNode.removeChild(u),e.__LiveReload_newHref===o)return i.insertRule(a,t),i.deleteRule(t+1),e=i.cssRules[t],e.__LiveReload_newHref=o,this.Timer.start(this.importCacheWaitPeriod,()=>{if(e.__LiveReload_newHref===o)return i.insertRule(a,t),i.deleteRule(t+1)})})}generateUniqueString(){return`livereload=${Date.now()}`}generateCacheBustUrl(e,t){let n=this.options||We,i,o;if(t||(t=this.generateUniqueString()),{url:e,hash:i,params:o}=It(e),n.overrideURL&&e.indexOf(n.serverURL)<0){let a=e;e=n.serverURL+n.overrideURL+"?url="+encodeURIComponent(e),this.console.debug(`is overriding source URL ${a} with ${e}`)}let s=o.replace(/(\?|&)livereload=(\d+)/,(a,u)=>`${u}${t}`);return s===o&&(o.length===0?s=`?${t}`:s=`${o}&${t}`),e+s+i}};function It(r){let e="",t="",n=r.indexOf("#");n>=0&&(e=r.slice(n),r=r.slice(0,n));let i=r.indexOf("??");return i>=0?i+1!==r.lastIndexOf("?")&&(n=r.lastIndexOf("?")):n=r.indexOf("?"),n>=0&&(t=r.slice(n),r=r.slice(0,n)),{url:r,params:t,hash:e}}function dt(r){if(!r)return"";let e;return{url:r}=It(r),r.indexOf("file://")===0?e=r.replace(new RegExp("^file://(localhost)?"),""):e=r.replace(new RegExp("^([^:]+:)?//([^:/]+)(:\\d*)?/"),"/"),decodeURIComponent(e)}function Rt(r,e){if(r=r.replace(/^\/+/,"").toLowerCase(),e=e.replace(/^\/+/,"").toLowerCase(),r===e)return 1e4;let t=r.split(/\/|\\/).reverse(),n=e.split(/\/|\\/).reverse(),i=Math.min(t.length,n.length),o=0;for(;on){let n,i={score:0};for(let o of e)n=Rt(r,t(o)),n>i.score&&(i={object:o,score:n});return i.score===0?null:i}function Ct(r,e){return Rt(r,e)>0}var Ar=Fr(Nt());var ft=function(r,e){return ft=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(t[i]=n[i])},ft(r,e)};function E(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");ft(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}var ze=function(){return ze=Object.assign||function(e){for(var t,n=1,i=arguments.length;n0&&o[o.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!o||l[1]>o[0]&&l[1]=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function P(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),i,o=[],s;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(a){s={error:a}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(s)throw s.error}}return o}function D(r,e,t){if(t||arguments.length===2)for(var n=0,i=e.length,o;n1||u(x,k)})},O&&(i[x]=O(i[x])))}function u(x,O){try{l(n[x](O))}catch(k){T(o[0][3],k)}}function l(x){x.value instanceof te?Promise.resolve(x.value.v).then(f,g):T(o[0][2],x)}function f(x){u("next",x)}function g(x){u("throw",x)}function T(x,O){x(O),o.shift(),o.length&&u(o[0][0],o[0][1])}}function Mt(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof z=="function"?z(r):r[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(o){t[o]=r[o]&&function(s){return new Promise(function(a,u){s=r[o](s),i(a,u,s.done,s.value)})}}function i(o,s,a,u){Promise.resolve(u).then(function(l){o({value:l,done:a})},s)}}function S(r){return typeof r=="function"}function He(r){var e=function(n){Error.call(n),n.stack=new Error().stack},t=r(e);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var Ye=He(function(r){return function(t){r(this),this.message=t?t.length+` errors occurred during unsubscription: +`+t.map(function(n,i){return i+1+") "+n.toString()}).join(` + `):"",this.name="UnsubscriptionError",this.errors=t}});function re(r,e){if(r){var t=r.indexOf(e);0<=t&&r.splice(t,1)}}var U=function(){function r(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return r.prototype.unsubscribe=function(){var e,t,n,i,o;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var a=z(s),u=a.next();!u.done;u=a.next()){var l=u.value;l.remove(this)}}catch(k){e={error:k}}finally{try{u&&!u.done&&(t=a.return)&&t.call(a)}finally{if(e)throw e.error}}else s.remove(this);var f=this.initialTeardown;if(S(f))try{f()}catch(k){o=k instanceof Ye?k.errors:[k]}var g=this._finalizers;if(g){this._finalizers=null;try{for(var T=z(g),x=T.next();!x.done;x=T.next()){var O=x.value;try{Lt(O)}catch(k){o=o??[],k instanceof Ye?o=D(D([],P(o)),P(k.errors)):o.push(k)}}}catch(k){n={error:k}}finally{try{x&&!x.done&&(i=T.return)&&i.call(T)}finally{if(n)throw n.error}}}if(o)throw new Ye(o)}},r.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)Lt(e);else{if(e instanceof r){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},r.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},r.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},r.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&re(t,e)},r.prototype.remove=function(e){var t=this._finalizers;t&&re(t,e),e instanceof r&&e._removeParent(this)},r.EMPTY=function(){var e=new r;return e.closed=!0,e}(),r}();var pt=U.EMPTY;function Ge(r){return r instanceof U||r&&"closed"in r&&S(r.remove)&&S(r.add)&&S(r.unsubscribe)}function Lt(r){S(r)?r():r.unsubscribe()}var Z={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var be={setTimeout:function(r,e){for(var t=[],n=2;n0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(t){return this._throwIfClosed(),r.prototype._trySubscribe.call(this,t)},e.prototype._subscribe=function(t){return this._throwIfClosed(),this._checkFinalizedStatuses(t),this._innerSubscribe(t)},e.prototype._innerSubscribe=function(t){var n=this,i=this,o=i.hasError,s=i.isStopped,a=i.observers;return o||s?pt:(this.currentObservers=null,a.push(t),new U(function(){n.currentObservers=null,re(a,t)}))},e.prototype._checkFinalizedStatuses=function(t){var n=this,i=n.hasError,o=n.thrownError,s=n.isStopped;i?t.error(o):s&&t.complete()},e.prototype.asObservable=function(){var t=new C;return t.source=this,t},e.create=function(t,n){return new Qe(t,n)},e}(C);var Qe=function(r){E(e,r);function e(t,n){var i=r.call(this)||this;return i.destination=t,i.source=n,i}return e.prototype.next=function(t){var n,i;(i=(n=this.destination)===null||n===void 0?void 0:n.next)===null||i===void 0||i.call(n,t)},e.prototype.error=function(t){var n,i;(i=(n=this.destination)===null||n===void 0?void 0:n.error)===null||i===void 0||i.call(n,t)},e.prototype.complete=function(){var t,n;(n=(t=this.destination)===null||t===void 0?void 0:t.complete)===null||n===void 0||n.call(t)},e.prototype._subscribe=function(t){var n,i;return(i=(n=this.source)===null||n===void 0?void 0:n.subscribe(t))!==null&&i!==void 0?i:pt},e}(q);var Ne={now:function(){return(Ne.delegate||Date).now()},delegate:void 0};var et=function(r){E(e,r);function e(t,n,i){t===void 0&&(t=1/0),n===void 0&&(n=1/0),i===void 0&&(i=Ne);var o=r.call(this)||this;return o._bufferSize=t,o._windowTime=n,o._timestampProvider=i,o._buffer=[],o._infiniteTimeWindow=!0,o._infiniteTimeWindow=n===1/0,o._bufferSize=Math.max(1,t),o._windowTime=Math.max(1,n),o}return e.prototype.next=function(t){var n=this,i=n.isStopped,o=n._buffer,s=n._infiniteTimeWindow,a=n._timestampProvider,u=n._windowTime;i||(o.push(t),!s&&o.push(a.now()+u)),this._trimBuffer(),r.prototype.next.call(this,t)},e.prototype._subscribe=function(t){this._throwIfClosed(),this._trimBuffer();for(var n=this._innerSubscribe(t),i=this,o=i._infiniteTimeWindow,s=i._buffer,a=s.slice(),u=0;ui;function e(i){}r.assertIs=e;function t(i){throw new Error}r.assertNever=t,r.arrayToEnum=i=>{let o={};for(let s of i)o[s]=s;return o},r.getValidEnumValues=i=>{let o=r.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),s={};for(let a of o)s[a]=i[a];return r.objectValues(s)},r.objectValues=i=>r.objectKeys(i).map(function(o){return i[o]}),r.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let s in i)Object.prototype.hasOwnProperty.call(i,s)&&o.push(s);return o},r.find=(i,o)=>{for(let s of i)if(o(s))return s},r.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&isFinite(i)&&Math.floor(i)===i;function n(i,o=" | "){return i.map(s=>typeof s=="string"?`'${s}'`:s).join(o)}r.joinValues=n,r.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(w||(w={}));var wt;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(wt||(wt={}));var h=w.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),K=r=>{switch(typeof r){case"undefined":return h.undefined;case"string":return h.string;case"number":return isNaN(r)?h.nan:h.number;case"boolean":return h.boolean;case"function":return h.function;case"bigint":return h.bigint;case"symbol":return h.symbol;case"object":return Array.isArray(r)?h.array:r===null?h.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?h.promise:typeof Map<"u"&&r instanceof Map?h.map:typeof Set<"u"&&r instanceof Set?h.set:typeof Date<"u"&&r instanceof Date?h.date:h.object;default:return h.unknown}},d=w.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"]),fn=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),A=class r extends Error{constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}get errors(){return this.issues}format(e){let t=e||function(o){return o.message},n={_errors:[]},i=o=>{for(let s of o.issues)if(s.code==="invalid_union")s.unionErrors.map(i);else if(s.code==="invalid_return_type")i(s.returnTypeError);else if(s.code==="invalid_arguments")i(s.argumentsError);else if(s.path.length===0)n._errors.push(t(s));else{let a=n,u=0;for(;ut.message){let t={},n=[];for(let i of this.issues)i.path.length>0?(t[i.path[0]]=t[i.path[0]]||[],t[i.path[0]].push(e(i))):n.push(e(i));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};A.create=r=>new A(r);var Ee=(r,e)=>{let t;switch(r.code){case d.invalid_type:r.received===h.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case d.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,w.jsonStringifyReplacer)}`;break;case d.unrecognized_keys:t=`Unrecognized key(s) in object: ${w.joinValues(r.keys,", ")}`;break;case d.invalid_union:t="Invalid input";break;case d.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${w.joinValues(r.options)}`;break;case d.invalid_enum_value:t=`Invalid enum value. Expected ${w.joinValues(r.options)}, received '${r.received}'`;break;case d.invalid_arguments:t="Invalid function arguments";break;case d.invalid_return_type:t="Invalid function return type";break;case d.invalid_date:t="Invalid date";break;case d.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:w.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case d.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case d.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case d.custom:t="Invalid input";break;case d.invalid_intersection_types:t="Intersection results could not be merged";break;case d.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case d.not_finite:t="Number must be finite";break;default:t=e.defaultError,w.assertNever(r)}return{message:t}},fr=Ee;function pn(r){fr=r}function it(){return fr}var ot=r=>{let{data:e,path:t,errorMaps:n,issueData:i}=r,o=[...t,...i.path||[]],s={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let a="",u=n.filter(l=>!!l).slice().reverse();for(let l of u)a=l(s,{data:e,defaultError:a}).message;return{...i,path:o,message:a}},hn=[];function p(r,e){let t=it(),n=ot({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===Ee?void 0:Ee].filter(i=>!!i)});r.common.issues.push(n)}var j=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let n=[];for(let i of t){if(i.status==="aborted")return v;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let i of t){let o=await i.key,s=await i.value;n.push({key:o,value:s})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let i of t){let{key:o,value:s}=i;if(o.status==="aborted"||s.status==="aborted")return v;o.status==="dirty"&&e.dirty(),s.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof s.value<"u"||i.alwaysSet)&&(n[o.value]=s.value)}return{status:e.value,value:n}}},v=Object.freeze({status:"aborted"}),Te=r=>({status:"dirty",value:r}),I=r=>({status:"valid",value:r}),St=r=>r.status==="aborted",kt=r=>r.status==="dirty",Le=r=>r.status==="valid",Ze=r=>typeof Promise<"u"&&r instanceof Promise;function st(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)}function pr(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t}var m;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(m||(m={}));var De,Me,L=class{constructor(e,t,n,i){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=i}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},lr=(r,e)=>{if(Le(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new A(r.common.issues);return this._error=t,this._error}}};function _(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:i}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(s,a)=>{var u,l;let{message:f}=r;return s.code==="invalid_enum_value"?{message:f??a.defaultError}:typeof a.data>"u"?{message:(u=f??n)!==null&&u!==void 0?u:a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:(l=f??t)!==null&&l!==void 0?l:a.defaultError}},description:i}}var b=class{constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(e){return K(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:K(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new j,ctx:{common:e.parent.common,data:e.data,parsedType:K(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Ze(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){var n;let i={common:{issues:[],async:(n=t?.async)!==null&&n!==void 0?n:!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:K(e)},o=this._parseSync({data:e,path:i.path,parent:i});return lr(i,o)}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:K(e)},i=this._parse({data:e,path:n.path,parent:n}),o=await(Ze(i)?i:Promise.resolve(i));return lr(n,o)}refine(e,t){let n=i=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(i):t;return this._refinement((i,o)=>{let s=e(i),a=()=>o.addIssue({code:d.custom,...n(i)});return typeof Promise<"u"&&s instanceof Promise?s.then(u=>u?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof t=="function"?t(n,i):t),!1))}_refinement(e){return new N({schema:this,typeName:y.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return M.create(this,this._def)}nullable(){return F.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return G.create(this,this._def)}promise(){return ee.create(this,this._def)}or(e){return de.create([this,e],this._def)}and(e){return fe.create(this,e,this._def)}transform(e){return new N({..._(this._def),schema:this,typeName:y.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new ve({..._(this._def),innerType:this,defaultValue:t,typeName:y.ZodDefault})}brand(){return new $e({typeName:y.ZodBranded,type:this,..._(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new ge({..._(this._def),innerType:this,catchValue:t,typeName:y.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Ue.create(this,e)}readonly(){return _e.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},mn=/^c[^\s-]{8,}$/i,yn=/^[0-9a-z]+$/,vn=/^[0-9A-HJKMNP-TV-Z]{26}$/,gn=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,_n=/^[a-z0-9_-]{21}$/i,bn=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,xn=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,wn="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",xt,Sn=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,kn=/^(([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})))$/,Tn=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,hr="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",En=new RegExp(`^${hr}$`);function mr(r){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`),e}function On(r){return new RegExp(`^${mr(r)}$`)}function yr(r){let e=`${hr}T${mr(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function jn(r,e){return!!((e==="v4"||!e)&&Sn.test(r)||(e==="v6"||!e)&&kn.test(r))}var X=class r extends b{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==h.string){let o=this._getOrReturnCtx(e);return p(o,{code:d.invalid_type,expected:h.string,received:o.parsedType}),v}let n=new j,i;for(let o of this._def.checks)if(o.kind==="min")e.data.lengtho.value&&(i=this._getOrReturnCtx(e,i),p(i,{code:d.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let s=e.data.length>o.value,a=e.data.lengthe.test(i),{validation:t,code:d.invalid_string,...m.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...m.errToObj(e)})}url(e){return this._addCheck({kind:"url",...m.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...m.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...m.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...m.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...m.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...m.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...m.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...m.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...m.errToObj(e)})}datetime(e){var t,n;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:(t=e?.offset)!==null&&t!==void 0?t:!1,local:(n=e?.local)!==null&&n!==void 0?n:!1,...m.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...m.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...m.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...m.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...m.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...m.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...m.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...m.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...m.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...m.errToObj(t)})}nonempty(e){return this.min(1,m.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value{var e;return new X({checks:[],typeName:y.ZodString,coerce:(e=r?.coerce)!==null&&e!==void 0?e:!1,..._(r)})};function Cn(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=t>n?t:n,o=parseInt(r.toFixed(i).replace(".","")),s=parseInt(e.toFixed(i).replace(".",""));return o%s/Math.pow(10,i)}var oe=class r extends b{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==h.number){let o=this._getOrReturnCtx(e);return p(o,{code:d.invalid_type,expected:h.number,received:o.parsedType}),v}let n,i=new j;for(let o of this._def.checks)o.kind==="int"?w.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:d.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?e.datao.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?Cn(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:d.not_finite,message:o.message}),i.dirty()):w.assertNever(o);return{status:i.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,m.toString(t))}gt(e,t){return this.setLimit("min",e,!1,m.toString(t))}lte(e,t){return this.setLimit("max",e,!0,m.toString(t))}lt(e,t){return this.setLimit("max",e,!1,m.toString(t))}setLimit(e,t,n,i){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:m.toString(i)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:m.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:m.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:m.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:m.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:m.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:m.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.valuee.kind==="int"||e.kind==="multipleOf"&&w.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.valuenew oe({checks:[],typeName:y.ZodNumber,coerce:r?.coerce||!1,..._(r)});var se=class r extends b{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce&&(e.data=BigInt(e.data)),this._getType(e)!==h.bigint){let o=this._getOrReturnCtx(e);return p(o,{code:d.invalid_type,expected:h.bigint,received:o.parsedType}),v}let n,i=new j;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.datao.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):w.assertNever(o);return{status:i.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,m.toString(t))}gt(e,t){return this.setLimit("min",e,!1,m.toString(t))}lte(e,t){return this.setLimit("max",e,!0,m.toString(t))}lt(e,t){return this.setLimit("max",e,!1,m.toString(t))}setLimit(e,t,n,i){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:m.toString(i)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:m.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:m.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value{var e;return new se({checks:[],typeName:y.ZodBigInt,coerce:(e=r?.coerce)!==null&&e!==void 0?e:!1,..._(r)})};var ae=class extends b{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==h.boolean){let n=this._getOrReturnCtx(e);return p(n,{code:d.invalid_type,expected:h.boolean,received:n.parsedType}),v}return I(e.data)}};ae.create=r=>new ae({typeName:y.ZodBoolean,coerce:r?.coerce||!1,..._(r)});var ce=class r extends b{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==h.date){let o=this._getOrReturnCtx(e);return p(o,{code:d.invalid_type,expected:h.date,received:o.parsedType}),v}if(isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return p(o,{code:d.invalid_date}),v}let n=new j,i;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()o.value&&(i=this._getOrReturnCtx(e,i),p(i,{code:d.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):w.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:m.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:m.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.valuenew ce({checks:[],coerce:r?.coerce||!1,typeName:y.ZodDate,..._(r)});var Oe=class extends b{_parse(e){if(this._getType(e)!==h.symbol){let n=this._getOrReturnCtx(e);return p(n,{code:d.invalid_type,expected:h.symbol,received:n.parsedType}),v}return I(e.data)}};Oe.create=r=>new Oe({typeName:y.ZodSymbol,..._(r)});var ue=class extends b{_parse(e){if(this._getType(e)!==h.undefined){let n=this._getOrReturnCtx(e);return p(n,{code:d.invalid_type,expected:h.undefined,received:n.parsedType}),v}return I(e.data)}};ue.create=r=>new ue({typeName:y.ZodUndefined,..._(r)});var le=class extends b{_parse(e){if(this._getType(e)!==h.null){let n=this._getOrReturnCtx(e);return p(n,{code:d.invalid_type,expected:h.null,received:n.parsedType}),v}return I(e.data)}};le.create=r=>new le({typeName:y.ZodNull,..._(r)});var Q=class extends b{constructor(){super(...arguments),this._any=!0}_parse(e){return I(e.data)}};Q.create=r=>new Q({typeName:y.ZodAny,..._(r)});var Y=class extends b{constructor(){super(...arguments),this._unknown=!0}_parse(e){return I(e.data)}};Y.create=r=>new Y({typeName:y.ZodUnknown,..._(r)});var $=class extends b{_parse(e){let t=this._getOrReturnCtx(e);return p(t,{code:d.invalid_type,expected:h.never,received:t.parsedType}),v}};$.create=r=>new $({typeName:y.ZodNever,..._(r)});var je=class extends b{_parse(e){if(this._getType(e)!==h.undefined){let n=this._getOrReturnCtx(e);return p(n,{code:d.invalid_type,expected:h.void,received:n.parsedType}),v}return I(e.data)}};je.create=r=>new je({typeName:y.ZodVoid,..._(r)});var G=class r extends b{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),i=this._def;if(t.parsedType!==h.array)return p(t,{code:d.invalid_type,expected:h.array,received:t.parsedType}),v;if(i.exactLength!==null){let s=t.data.length>i.exactLength.value,a=t.data.lengthi.maxLength.value&&(p(t,{code:d.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((s,a)=>i.type._parseAsync(new L(t,s,t.path,a)))).then(s=>j.mergeArray(n,s));let o=[...t.data].map((s,a)=>i.type._parseSync(new L(t,s,t.path,a)));return j.mergeArray(n,o)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:m.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:m.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:m.toString(t)}})}nonempty(e){return this.min(1,e)}};G.create=(r,e)=>new G({type:r,minLength:null,maxLength:null,exactLength:null,typeName:y.ZodArray,..._(e)});function ke(r){if(r instanceof R){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=M.create(ke(n))}return new R({...r._def,shape:()=>e})}else return r instanceof G?new G({...r._def,type:ke(r.element)}):r instanceof M?M.create(ke(r.unwrap())):r instanceof F?F.create(ke(r.unwrap())):r instanceof W?W.create(r.items.map(e=>ke(e))):r}var R=class r extends b{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=w.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==h.object){let l=this._getOrReturnCtx(e);return p(l,{code:d.invalid_type,expected:h.object,received:l.parsedType}),v}let{status:n,ctx:i}=this._processInputParams(e),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof $&&this._def.unknownKeys==="strip"))for(let l in i.data)s.includes(l)||a.push(l);let u=[];for(let l of s){let f=o[l],g=i.data[l];u.push({key:{status:"valid",value:l},value:f._parse(new L(i,g,i.path,l)),alwaysSet:l in i.data})}if(this._def.catchall instanceof $){let l=this._def.unknownKeys;if(l==="passthrough")for(let f of a)u.push({key:{status:"valid",value:f},value:{status:"valid",value:i.data[f]}});else if(l==="strict")a.length>0&&(p(i,{code:d.unrecognized_keys,keys:a}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let f of a){let g=i.data[f];u.push({key:{status:"valid",value:f},value:l._parse(new L(i,g,i.path,f)),alwaysSet:f in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let l=[];for(let f of u){let g=await f.key,T=await f.value;l.push({key:g,value:T,alwaysSet:f.alwaysSet})}return l}).then(l=>j.mergeObjectSync(n,l)):j.mergeObjectSync(n,u)}get shape(){return this._def.shape()}strict(e){return m.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{var i,o,s,a;let u=(s=(o=(i=this._def).errorMap)===null||o===void 0?void 0:o.call(i,t,n).message)!==null&&s!==void 0?s:n.defaultError;return t.code==="unrecognized_keys"?{message:(a=m.errToObj(e).message)!==null&&a!==void 0?a:u}:{message:u}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:y.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};return w.objectKeys(e).forEach(n=>{e[n]&&this.shape[n]&&(t[n]=this.shape[n])}),new r({...this._def,shape:()=>t})}omit(e){let t={};return w.objectKeys(this.shape).forEach(n=>{e[n]||(t[n]=this.shape[n])}),new r({...this._def,shape:()=>t})}deepPartial(){return ke(this)}partial(e){let t={};return w.objectKeys(this.shape).forEach(n=>{let i=this.shape[n];e&&!e[n]?t[n]=i:t[n]=i.optional()}),new r({...this._def,shape:()=>t})}required(e){let t={};return w.objectKeys(this.shape).forEach(n=>{if(e&&!e[n])t[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof M;)o=o._def.innerType;t[n]=o}}),new r({...this._def,shape:()=>t})}keyof(){return vr(w.objectKeys(this.shape))}};R.create=(r,e)=>new R({shape:()=>r,unknownKeys:"strip",catchall:$.create(),typeName:y.ZodObject,..._(e)});R.strictCreate=(r,e)=>new R({shape:()=>r,unknownKeys:"strict",catchall:$.create(),typeName:y.ZodObject,..._(e)});R.lazycreate=(r,e)=>new R({shape:r,unknownKeys:"strip",catchall:$.create(),typeName:y.ZodObject,..._(e)});var de=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function i(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return t.common.issues.push(...a.ctx.common.issues),a.result;let s=o.map(a=>new A(a.ctx.common.issues));return p(t,{code:d.invalid_union,unionErrors:s}),v}if(t.common.async)return Promise.all(n.map(async o=>{let s={...t,common:{...t.common,issues:[]},parent:null};return{result:await o._parseAsync({data:t.data,path:t.path,parent:s}),ctx:s}})).then(i);{let o,s=[];for(let u of n){let l={...t,common:{...t.common,issues:[]},parent:null},f=u._parseSync({data:t.data,path:t.path,parent:l});if(f.status==="valid")return f;f.status==="dirty"&&!o&&(o={result:f,ctx:l}),l.common.issues.length&&s.push(l.common.issues)}if(o)return t.common.issues.push(...o.ctx.common.issues),o.result;let a=s.map(u=>new A(u));return p(t,{code:d.invalid_union,unionErrors:a}),v}}get options(){return this._def.options}};de.create=(r,e)=>new de({options:r,typeName:y.ZodUnion,..._(e)});var H=r=>r instanceof pe?H(r.schema):r instanceof N?H(r.innerType()):r instanceof he?[r.value]:r instanceof me?r.options:r instanceof ye?w.objectValues(r.enum):r instanceof ve?H(r._def.innerType):r instanceof ue?[void 0]:r instanceof le?[null]:r instanceof M?[void 0,...H(r.unwrap())]:r instanceof F?[null,...H(r.unwrap())]:r instanceof $e||r instanceof _e?H(r.unwrap()):r instanceof ge?H(r._def.innerType):[],at=class r extends b{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==h.object)return p(t,{code:d.invalid_type,expected:h.object,received:t.parsedType}),v;let n=this.discriminator,i=t.data[n],o=this.optionsMap.get(i);return o?t.common.async?o._parseAsync({data:t.data,path:t.path,parent:t}):o._parseSync({data:t.data,path:t.path,parent:t}):(p(t,{code:d.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),v)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let i=new Map;for(let o of t){let s=H(o.shape[e]);if(!s.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of s){if(i.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);i.set(a,o)}}return new r({typeName:y.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:i,..._(n)})}};function Tt(r,e){let t=K(r),n=K(e);if(r===e)return{valid:!0,data:r};if(t===h.object&&n===h.object){let i=w.objectKeys(e),o=w.objectKeys(r).filter(a=>i.indexOf(a)!==-1),s={...r,...e};for(let a of o){let u=Tt(r[a],e[a]);if(!u.valid)return{valid:!1};s[a]=u.data}return{valid:!0,data:s}}else if(t===h.array&&n===h.array){if(r.length!==e.length)return{valid:!1};let i=[];for(let o=0;o{if(St(o)||St(s))return v;let a=Tt(o.value,s.value);return a.valid?((kt(o)||kt(s))&&t.dirty(),{status:t.value,value:a.data}):(p(n,{code:d.invalid_intersection_types}),v)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,s])=>i(o,s)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};fe.create=(r,e,t)=>new fe({left:r,right:e,typeName:y.ZodIntersection,..._(t)});var W=class r extends b{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==h.array)return p(n,{code:d.invalid_type,expected:h.array,received:n.parsedType}),v;if(n.data.lengththis._def.items.length&&(p(n,{code:d.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let o=[...n.data].map((s,a)=>{let u=this._def.items[a]||this._def.rest;return u?u._parse(new L(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>j.mergeArray(t,s)):j.mergeArray(t,o)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};W.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new W({items:r,typeName:y.ZodTuple,rest:null,..._(e)})};var ct=class r extends b{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==h.object)return p(n,{code:d.invalid_type,expected:h.object,received:n.parsedType}),v;let i=[],o=this._def.keyType,s=this._def.valueType;for(let a in n.data)i.push({key:o._parse(new L(n,a,n.path,a)),value:s._parse(new L(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?j.mergeObjectAsync(t,i):j.mergeObjectSync(t,i)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof b?new r({keyType:e,valueType:t,typeName:y.ZodRecord,..._(n)}):new r({keyType:X.create(),valueType:e,typeName:y.ZodRecord,..._(t)})}},Ce=class extends b{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==h.map)return p(n,{code:d.invalid_type,expected:h.map,received:n.parsedType}),v;let i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([a,u],l)=>({key:i._parse(new L(n,a,n.path,[l,"key"])),value:o._parse(new L(n,u,n.path,[l,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let u of s){let l=await u.key,f=await u.value;if(l.status==="aborted"||f.status==="aborted")return v;(l.status==="dirty"||f.status==="dirty")&&t.dirty(),a.set(l.value,f.value)}return{status:t.value,value:a}})}else{let a=new Map;for(let u of s){let l=u.key,f=u.value;if(l.status==="aborted"||f.status==="aborted")return v;(l.status==="dirty"||f.status==="dirty")&&t.dirty(),a.set(l.value,f.value)}return{status:t.value,value:a}}}};Ce.create=(r,e,t)=>new Ce({valueType:e,keyType:r,typeName:y.ZodMap,..._(t)});var Ie=class r extends b{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==h.set)return p(n,{code:d.invalid_type,expected:h.set,received:n.parsedType}),v;let i=this._def;i.minSize!==null&&n.data.sizei.maxSize.value&&(p(n,{code:d.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),t.dirty());let o=this._def.valueType;function s(u){let l=new Set;for(let f of u){if(f.status==="aborted")return v;f.status==="dirty"&&t.dirty(),l.add(f.value)}return{status:t.value,value:l}}let a=[...n.data.values()].map((u,l)=>o._parse(new L(n,u,n.path,l)));return n.common.async?Promise.all(a).then(u=>s(u)):s(a)}min(e,t){return new r({...this._def,minSize:{value:e,message:m.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:m.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Ie.create=(r,e)=>new Ie({valueType:r,minSize:null,maxSize:null,typeName:y.ZodSet,..._(e)});var ut=class r extends b{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==h.function)return p(t,{code:d.invalid_type,expected:h.function,received:t.parsedType}),v;function n(a,u){return ot({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,it(),Ee].filter(l=>!!l),issueData:{code:d.invalid_arguments,argumentsError:u}})}function i(a,u){return ot({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,it(),Ee].filter(l=>!!l),issueData:{code:d.invalid_return_type,returnTypeError:u}})}let o={errorMap:t.common.contextualErrorMap},s=t.data;if(this._def.returns instanceof ee){let a=this;return I(async function(...u){let l=new A([]),f=await a._def.args.parseAsync(u,o).catch(x=>{throw l.addIssue(n(u,x)),l}),g=await Reflect.apply(s,this,f);return await a._def.returns._def.type.parseAsync(g,o).catch(x=>{throw l.addIssue(i(g,x)),l})})}else{let a=this;return I(function(...u){let l=a._def.args.safeParse(u,o);if(!l.success)throw new A([n(u,l.error)]);let f=Reflect.apply(s,this,l.data),g=a._def.returns.safeParse(f,o);if(!g.success)throw new A([i(f,g.error)]);return g.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:W.create(e).rest(Y.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||W.create([]).rest(Y.create()),returns:t||Y.create(),typeName:y.ZodFunction,..._(n)})}},pe=class extends b{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};pe.create=(r,e)=>new pe({getter:r,typeName:y.ZodLazy,..._(e)});var he=class extends b{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return p(t,{received:t.data,code:d.invalid_literal,expected:this._def.value}),v}return{status:"valid",value:e.data}}get value(){return this._def.value}};he.create=(r,e)=>new he({value:r,typeName:y.ZodLiteral,..._(e)});function vr(r,e){return new me({values:r,typeName:y.ZodEnum,..._(e)})}var me=class r extends b{constructor(){super(...arguments),De.set(this,void 0)}_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return p(t,{expected:w.joinValues(n),received:t.parsedType,code:d.invalid_type}),v}if(st(this,De,"f")||pr(this,De,new Set(this._def.values),"f"),!st(this,De,"f").has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return p(t,{received:t.data,code:d.invalid_enum_value,options:n}),v}return I(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};De=new WeakMap;me.create=vr;var ye=class extends b{constructor(){super(...arguments),Me.set(this,void 0)}_parse(e){let t=w.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==h.string&&n.parsedType!==h.number){let i=w.objectValues(t);return p(n,{expected:w.joinValues(i),received:n.parsedType,code:d.invalid_type}),v}if(st(this,Me,"f")||pr(this,Me,new Set(w.getValidEnumValues(this._def.values)),"f"),!st(this,Me,"f").has(e.data)){let i=w.objectValues(t);return p(n,{received:n.data,code:d.invalid_enum_value,options:i}),v}return I(e.data)}get enum(){return this._def.values}};Me=new WeakMap;ye.create=(r,e)=>new ye({values:r,typeName:y.ZodNativeEnum,..._(e)});var ee=class extends b{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==h.promise&&t.common.async===!1)return p(t,{code:d.invalid_type,expected:h.promise,received:t.parsedType}),v;let n=t.parsedType===h.promise?t.data:Promise.resolve(t.data);return I(n.then(i=>this._def.type.parseAsync(i,{path:t.path,errorMap:t.common.contextualErrorMap})))}};ee.create=(r,e)=>new ee({type:r,typeName:y.ZodPromise,..._(e)});var N=class extends b{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===y.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),i=this._def.effect||null,o={addIssue:s=>{p(n,s),s.fatal?t.abort():t.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let s=i.transform(n.data,o);if(n.common.async)return Promise.resolve(s).then(async a=>{if(t.value==="aborted")return v;let u=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return u.status==="aborted"?v:u.status==="dirty"||t.value==="dirty"?Te(u.value):u});{if(t.value==="aborted")return v;let a=this._def.schema._parseSync({data:s,path:n.path,parent:n});return a.status==="aborted"?v:a.status==="dirty"||t.value==="dirty"?Te(a.value):a}}if(i.type==="refinement"){let s=a=>{let u=i.refinement(a,o);if(n.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?v:(a.status==="dirty"&&t.dirty(),s(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?v:(a.status==="dirty"&&t.dirty(),s(a.value).then(()=>({status:t.value,value:a.value}))))}if(i.type==="transform")if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Le(s))return s;let a=i.transform(s.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>Le(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:t.value,value:a})):s);w.assertNever(i)}};N.create=(r,e,t)=>new N({schema:r,typeName:y.ZodEffects,effect:e,..._(t)});N.createWithPreprocess=(r,e,t)=>new N({schema:e,effect:{type:"preprocess",transform:r},typeName:y.ZodEffects,..._(t)});var M=class extends b{_parse(e){return this._getType(e)===h.undefined?I(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};M.create=(r,e)=>new M({innerType:r,typeName:y.ZodOptional,..._(e)});var F=class extends b{_parse(e){return this._getType(e)===h.null?I(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};F.create=(r,e)=>new F({innerType:r,typeName:y.ZodNullable,..._(e)});var ve=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===h.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ve.create=(r,e)=>new ve({innerType:r,typeName:y.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,..._(e)});var ge=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Ze(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new A(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new A(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};ge.create=(r,e)=>new ge({innerType:r,typeName:y.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,..._(e)});var Re=class extends b{_parse(e){if(this._getType(e)!==h.nan){let n=this._getOrReturnCtx(e);return p(n,{code:d.invalid_type,expected:h.nan,received:n.parsedType}),v}return{status:"valid",value:e.data}}};Re.create=r=>new Re({typeName:y.ZodNaN,..._(r)});var In=Symbol("zod_brand"),$e=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},Ue=class r extends b{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?v:o.status==="dirty"?(t.dirty(),Te(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?v:i.status==="dirty"?(t.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:y.ZodPipeline})}},_e=class extends b{_parse(e){let t=this._def.innerType._parse(e),n=i=>(Le(i)&&(i.value=Object.freeze(i.value)),i);return Ze(t)?t.then(i=>n(i)):n(t)}unwrap(){return this._def.innerType}};_e.create=(r,e)=>new _e({innerType:r,typeName:y.ZodReadonly,..._(e)});function gr(r,e={},t){return r?Q.create().superRefine((n,i)=>{var o,s;if(!r(n)){let a=typeof e=="function"?e(n):typeof e=="string"?{message:e}:e,u=(s=(o=a.fatal)!==null&&o!==void 0?o:t)!==null&&s!==void 0?s:!0,l=typeof a=="string"?{message:a}:a;i.addIssue({code:"custom",...l,fatal:u})}}):Q.create()}var Rn={object:R.lazycreate},y;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(y||(y={}));var An=(r,e={message:`Input not instance of ${r.name}`})=>gr(t=>t instanceof r,e),_r=X.create,br=oe.create,Nn=Re.create,Pn=se.create,xr=ae.create,Dn=ce.create,Mn=Oe.create,Ln=ue.create,Zn=le.create,$n=Q.create,Un=Y.create,Vn=$.create,Wn=je.create,Fn=G.create,Bn=R.create,zn=R.strictCreate,qn=de.create,Hn=at.create,Yn=fe.create,Gn=W.create,Jn=ct.create,Kn=Ce.create,Xn=Ie.create,Qn=ut.create,ei=pe.create,ti=he.create,ri=me.create,ni=ye.create,ii=ee.create,dr=N.create,oi=M.create,si=F.create,ai=N.createWithPreprocess,ci=Ue.create,ui=()=>_r().optional(),li=()=>br().optional(),di=()=>xr().optional(),fi={string:r=>X.create({...r,coerce:!0}),number:r=>oe.create({...r,coerce:!0}),boolean:r=>ae.create({...r,coerce:!0}),bigint:r=>se.create({...r,coerce:!0}),date:r=>ce.create({...r,coerce:!0})},pi=v,c=Object.freeze({__proto__:null,defaultErrorMap:Ee,setErrorMap:pn,getErrorMap:it,makeIssue:ot,EMPTY_PATH:hn,addIssueToContext:p,ParseStatus:j,INVALID:v,DIRTY:Te,OK:I,isAborted:St,isDirty:kt,isValid:Le,isAsync:Ze,get util(){return w},get objectUtil(){return wt},ZodParsedType:h,getParsedType:K,ZodType:b,datetimeRegex:yr,ZodString:X,ZodNumber:oe,ZodBigInt:se,ZodBoolean:ae,ZodDate:ce,ZodSymbol:Oe,ZodUndefined:ue,ZodNull:le,ZodAny:Q,ZodUnknown:Y,ZodNever:$,ZodVoid:je,ZodArray:G,ZodObject:R,ZodUnion:de,ZodDiscriminatedUnion:at,ZodIntersection:fe,ZodTuple:W,ZodRecord:ct,ZodMap:Ce,ZodSet:Ie,ZodFunction:ut,ZodLazy:pe,ZodLiteral:he,ZodEnum:me,ZodNativeEnum:ye,ZodPromise:ee,ZodEffects:N,ZodTransformer:N,ZodOptional:M,ZodNullable:F,ZodDefault:ve,ZodCatch:ge,ZodNaN:Re,BRAND:In,ZodBranded:$e,ZodPipeline:Ue,ZodReadonly:_e,custom:gr,Schema:b,ZodSchema:b,late:Rn,get ZodFirstPartyTypeKind(){return y},coerce:fi,any:$n,array:Fn,bigint:Pn,boolean:xr,date:Dn,discriminatedUnion:Hn,effect:dr,enum:ri,function:Qn,instanceof:An,intersection:Yn,lazy:ei,literal:ti,map:Kn,nan:Nn,nativeEnum:ni,never:Vn,null:Zn,nullable:si,number:br,object:Bn,oboolean:di,onumber:li,optional:oi,ostring:ui,pipeline:ci,preprocess:ai,promise:ii,record:Jn,set:Xn,strictObject:zn,string:_r,symbol:Mn,transformer:dr,tuple:Gn,undefined:Ln,union:qn,unknown:Un,void:Wn,NEVER:pi,ZodIssueCode:d,quotelessJson:fn,ZodError:A});var Sr=(r=>(r.Info="info",r.Debug="debug",r.Trace="trace",r.Error="error",r))(Sr||{}),kr=(r=>(r.External="BSLIVE_EXTERNAL",r))(kr||{}),Tr=(r=>(r.Changed="Changed",r.Added="Added",r.Removed="Removed",r))(Tr||{}),hi=c.union([c.object({kind:c.literal("Html"),payload:c.object({html:c.string()})}),c.object({kind:c.literal("Json"),payload:c.object({json_str:c.string()})}),c.object({kind:c.literal("Raw"),payload:c.object({raw:c.string()})}),c.object({kind:c.literal("Sse"),payload:c.object({sse:c.string()})}),c.object({kind:c.literal("Proxy"),payload:c.object({proxy:c.string()})}),c.object({kind:c.literal("Dir"),payload:c.object({dir:c.string(),base:c.string().optional()})})]),mi=c.object({path:c.string(),kind:hi}),Pa=c.object({routes:c.array(mi),id:c.string()}),Er=c.union([c.object({kind:c.literal("Both"),payload:c.object({name:c.string(),bind_address:c.string()})}),c.object({kind:c.literal("Address"),payload:c.object({bind_address:c.string()})}),c.object({kind:c.literal("Named"),payload:c.object({name:c.string()})})]),yi=c.object({id:c.string(),identity:Er,socket_addr:c.string()}),Or=c.object({servers:c.array(yi)}),vi=c.object({servers_resp:Or}),gi=c.object({path:c.string()}),wr=c.object({path:c.string()}),_i=c.object({paths:c.array(c.string())}),bi=c.object({kind:c.string(),ms:c.string()}),xi=c.object({paths:c.array(c.string()),debounce:bi}),wi=c.object({paths:c.array(c.string())}),Si=c.union([c.object({kind:c.literal("Stopped"),payload:c.object({bind_address:c.string()})}),c.object({kind:c.literal("Started"),payload:c.undefined().optional()}),c.object({kind:c.literal("Patched"),payload:c.undefined().optional()}),c.object({kind:c.literal("Errored"),payload:c.object({error:c.string()})})]),ki=c.object({identity:Er,change:Si}),Da=c.object({items:c.array(ki)}),Ti=c.nativeEnum(Sr),Ei=c.object({log_level:Ti}),Ma=c.object({kind:c.literal("ServersChanged"),payload:Or}),La=c.nativeEnum(kr),Za=c.union([c.object({kind:c.literal("ServersChanged"),payload:vi}),c.object({kind:c.literal("Watching"),payload:xi}),c.object({kind:c.literal("WatchingStopped"),payload:wi}),c.object({kind:c.literal("FileChanged"),payload:wr}),c.object({kind:c.literal("FilesChanged"),payload:_i}),c.object({kind:c.literal("InputFileChanged"),payload:wr}),c.object({kind:c.literal("InputAccepted"),payload:gi})]),$a=c.union([c.object({kind:c.literal("Started"),payload:c.undefined().optional()}),c.object({kind:c.literal("FailedStartup"),payload:c.string()})]),Ua=c.union([c.object({kind:c.literal("MissingInputs"),payload:c.string()}),c.object({kind:c.literal("InvalidInput"),payload:c.string()}),c.object({kind:c.literal("NotFound"),payload:c.string()}),c.object({kind:c.literal("InputWriteError"),payload:c.string()}),c.object({kind:c.literal("PathError"),payload:c.string()}),c.object({kind:c.literal("PortError"),payload:c.string()}),c.object({kind:c.literal("DirError"),payload:c.string()}),c.object({kind:c.literal("YamlError"),payload:c.string()}),c.object({kind:c.literal("MarkdownError"),payload:c.string()}),c.object({kind:c.literal("Io"),payload:c.string()}),c.object({kind:c.literal("UnsupportedExtension"),payload:c.string()}),c.object({kind:c.literal("MissingExtension"),payload:c.string()}),c.object({kind:c.literal("EmptyInput"),payload:c.string()}),c.object({kind:c.literal("BsLiveRules"),payload:c.string()})]),Oi=c.nativeEnum(Tr),jr=c.lazy(()=>c.union([c.object({kind:c.literal("Fs"),payload:c.object({path:c.string(),change_kind:Oi})}),c.object({kind:c.literal("FsMany"),payload:c.array(jr)})])),Cr=c.union([c.object({kind:c.literal("Change"),payload:jr}),c.object({kind:c.literal("Config"),payload:Ei})]);function Ir(){let r=new q;return[r,{debug:function(...e){r.next({level:"debug",text:e.join(` +`)})},info:function(...e){r.next({level:"info",text:e.join(` +`)})},trace:function(...e){r.next({level:"trace",text:e.join(` +`)})},error:function(...e){r.next({level:"error",text:e.join(` +`)})}}]}var[Ci,Et]=Ir(),Rr=new Fe(window,Et,Ar.Timer),Ve=new URL(window.location.href);Ve.protocol=Ve.protocol==="http:"?"ws":"wss";Ve.pathname="/__bs_ws";var Ii=vt(Ve.origin+Ve.pathname),Nr=Ii.pipe(bt({delay:5e3})),Ri=Nr.pipe(rt(r=>r.kind==="Change")),Pr=Nr.pipe(rt(r=>r.kind==="Config"),_t(r=>r.payload));Ri.pipe(nt(Pr)).subscribe(([r,e])=>{Et.trace("incoming message",JSON.stringify({change:r,config:e},null,2));let t=Cr.parse(r);switch(t.kind){case"Change":{Dr(t.payload);break}default:console.warn("unhandled client event")}});var Ai=/\.(jpe?g|png|gif|svg)$/i;function Dr(r){switch(r.kind){case"FsMany":{if(r.payload.some(t=>{switch(t.kind){case"Fs":return!(t.payload.path.match(/\.css(?:\.map)?$/i)||t.payload.path.match(Ai));case"FsMany":throw new Error("unreachable")}}))return window.__playwright?.record?window.__playwright?.record({kind:"reloadPage"}):Rr.reloadPage();for(let t of r.payload)Dr(t);break}case"Fs":{let e=r.payload.path,t={liveCSS:!0,liveImg:!0,reloadMissingCSS:!0,originalPath:"",overrideURL:"",serverURL:""};window.__playwright?.record?window.__playwright?.record({kind:"reload",args:{path:e,opts:t}}):(Et.trace("will reload a file with path ",e),Rr.reload(e,t))}}}Ci.pipe(nt(Pr)).subscribe(([r,e])=>{let t=["trace","debug","info","error"],n=t.indexOf(r.level),i=t.indexOf(e.log_level);n>=i&&console.log(`[${r.level}] ${r.text}`)});function tc(r,e,t){}export{tc as logMessage}; diff --git a/crates/bsnext_client/inject/package.json b/crates/bsnext_client/inject/package.json index 707513d..6e2538a 100644 --- a/crates/bsnext_client/inject/package.json +++ b/crates/bsnext_client/inject/package.json @@ -4,7 +4,7 @@ "description": "", "main": "index.js", "scripts": { - "build:client": "esbuild src/index.ts --bundle --outdir=dist --format=esm", + "build:client": "esbuild src/index.ts --bundle --outdir=dist --format=esm --minify --metafile=dist/meta.json", "dev": "npm run build:client -- --sourcemap=inline --watch", "build:client:debug": "npm run build:client -- --sourcemap=inline" }, diff --git a/crates/bsnext_core/src/server/actor.rs b/crates/bsnext_core/src/server/actor.rs index 72ad5f2..6b3205d 100644 --- a/crates/bsnext_core/src/server/actor.rs +++ b/crates/bsnext_core/src/server/actor.rs @@ -22,7 +22,7 @@ pub struct ServerActor { impl ServerActor { pub fn new_from_config(config: ServerConfig) -> Self { - let routes_manifest = RoutesManifest::new(&config.routes); + let routes_manifest = RoutesManifest::new(&config.combined_routes()); Self { config, signals: None, diff --git a/crates/bsnext_core/src/server/handler_listen.rs b/crates/bsnext_core/src/server/handler_listen.rs index 9ecb82c..bdf2487 100644 --- a/crates/bsnext_core/src/server/handler_listen.rs +++ b/crates/bsnext_core/src/server/handler_listen.rs @@ -30,11 +30,11 @@ impl actix::Handler for ServerActor { let h1 = handle.clone(); let h2 = handle.clone(); - let router = RouteMap::new_from_routes(&self.config.routes).into_router(); + let router = RouteMap::new_from_routes(&self.config.combined_routes()).into_router(); let app_state = Arc::new(ServerState { // parent: , - routes: Arc::new(RwLock::new(self.config.routes.clone())), + routes: Arc::new(RwLock::new(self.config.combined_routes())), raw_router: Arc::new(RwLock::new(router)), client_config: Arc::new(RwLock::new(self.config.clients.clone())), id: self.config.identity.as_id(), diff --git a/crates/bsnext_core/src/server/handler_patch.rs b/crates/bsnext_core/src/server/handler_patch.rs index ec50df1..fd823f7 100644 --- a/crates/bsnext_core/src/server/handler_patch.rs +++ b/crates/bsnext_core/src/server/handler_patch.rs @@ -29,7 +29,7 @@ impl actix::Handler for ServerActor { let app_state_clone = app_state.clone(); // Process routes and manifests - let routes = msg.server_config.routes.clone(); + let routes = msg.server_config.combined_routes(); let next_manifest = RoutesManifest::new(&routes); let changeset = self.routes_manifest.changeset_for(&next_manifest); self.routes_manifest = RoutesManifest::new(&routes); diff --git a/crates/bsnext_core/src/server/router/common.rs b/crates/bsnext_core/src/server/router/common.rs index 8365fd6..c2d0639 100644 --- a/crates/bsnext_core/src/server/router/common.rs +++ b/crates/bsnext_core/src/server/router/common.rs @@ -22,9 +22,9 @@ use tower::ServiceExt; pub fn into_state(val: ServerConfig) -> ServerState { let (sender, _) = tokio::sync::broadcast::channel::(10); - let router = RouteMap::new_from_routes(&val.routes).into_router(); + let router = RouteMap::new_from_routes(&val.combined_routes()).into_router(); ServerState { - routes: Arc::new(RwLock::new(val.routes.clone())), + routes: Arc::new(RwLock::new(val.combined_routes())), raw_router: Arc::new(RwLock::new(router)), client_config: Arc::new(RwLock::new(val.clients.clone())), id: val.identity.as_id(), diff --git a/crates/bsnext_core/tests/delays.rs b/crates/bsnext_core/tests/delays.rs index edcc96d..3936e12 100644 --- a/crates/bsnext_core/tests/delays.rs +++ b/crates/bsnext_core/tests/delays.rs @@ -20,7 +20,7 @@ async fn test_delays() -> Result<(), anyhow::Error> { let dur3_ms = dur3.as_millis(); assert!(dur1_ms > 200 && dur1_ms < 210); - assert!(dur2_ms > 500 && dur2_ms < 510); + assert!(dur2_ms > 500 && dur2_ms < 600); assert!( dur3_ms > 300 && dur3_ms < 310, "dir delay should be over 300ms" diff --git a/crates/bsnext_example/Cargo.toml b/crates/bsnext_example/Cargo.toml index dce365d..f587e15 100644 --- a/crates/bsnext_example/Cargo.toml +++ b/crates/bsnext_example/Cargo.toml @@ -7,4 +7,5 @@ edition = "2021" [dependencies] bsnext_input = { path = "../bsnext_input" } +bsnext_md = { path = "../bsnext_md" } clap = { workspace = true } diff --git a/crates/bsnext_example/src/basic.rs b/crates/bsnext_example/src/basic.rs index 58e6f6f..b953097 100644 --- a/crates/bsnext_example/src/basic.rs +++ b/crates/bsnext_example/src/basic.rs @@ -2,14 +2,14 @@ use bsnext_input::route::{Route, RouteKind}; use bsnext_input::server_config::ServerIdentity; use bsnext_input::{ server_config::{self}, - Input, + Input, InputSource, InputSourceKind, }; #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct BasicExample; -impl BasicExample { - pub fn into_input(self, identity: Option) -> Input { +impl InputSource for BasicExample { + fn into_input(&self, identity: Option) -> InputSourceKind { let server = server_config::ServerConfig { identity: identity.unwrap_or_else(ServerIdentity::named), routes: vec![ @@ -44,8 +44,8 @@ impl BasicExample { ], ..Default::default() }; - Input { + InputSourceKind::Type(Input { servers: vec![server], - } + }) } } diff --git a/crates/bsnext_example/src/lib.rs b/crates/bsnext_example/src/lib.rs index 231da7b..14ac4e7 100644 --- a/crates/bsnext_example/src/lib.rs +++ b/crates/bsnext_example/src/lib.rs @@ -1,26 +1,31 @@ use crate::basic::BasicExample; use crate::lit::LitExample; use crate::md::MdExample; +use crate::playground::PlaygroundExample; use bsnext_input::server_config::ServerIdentity; -use bsnext_input::Input; +use bsnext_input::{InputSource, InputSourceKind}; pub mod basic; pub mod lit; pub mod md; +pub mod playground; + #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, clap::ValueEnum)] pub enum Example { Basic, Lit, Md, + Playground, } -impl Example { - pub fn into_input(self, identity: ServerIdentity) -> Input { +impl InputSource for Example { + fn into_input(&self, identity: Option) -> InputSourceKind { match self { - Example::Basic => BasicExample.into_input(Some(identity)), - Example::Lit => LitExample.into_input(Some(identity)), - Example::Md => MdExample.into_input(Some(identity)), + Example::Basic => BasicExample.into_input(identity), + Example::Lit => LitExample.into_input(identity), + Example::Md => MdExample.into_input(identity), + Example::Playground => PlaygroundExample.into_input(identity), } } } diff --git a/crates/bsnext_example/src/lit.rs b/crates/bsnext_example/src/lit.rs index 8e9242c..5efcb23 100644 --- a/crates/bsnext_example/src/lit.rs +++ b/crates/bsnext_example/src/lit.rs @@ -2,14 +2,14 @@ use bsnext_input::route::{Route, RouteKind}; use bsnext_input::server_config::ServerIdentity; use bsnext_input::{ server_config::{self}, - Input, + Input, InputSource, InputSourceKind, }; #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct LitExample; -impl LitExample { - pub fn into_input(self, identity: Option) -> Input { +impl InputSource for LitExample { + fn into_input(&self, identity: Option) -> InputSourceKind { let server = server_config::ServerConfig { identity: identity.unwrap_or_else(ServerIdentity::named), routes: vec![ @@ -26,8 +26,8 @@ impl LitExample { ], ..Default::default() }; - Input { + InputSourceKind::Type(Input { servers: vec![server], - } + }) } } diff --git a/crates/bsnext_example/src/md.rs b/crates/bsnext_example/src/md.rs index d062bea..9436d88 100644 --- a/crates/bsnext_example/src/md.rs +++ b/crates/bsnext_example/src/md.rs @@ -1,18 +1,19 @@ use bsnext_input::server_config::ServerIdentity; -use bsnext_input::{md, Input}; +use bsnext_input::{InputSource, InputSourceKind}; +use bsnext_md::md_to_input; #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct MdExample; -impl MdExample { - pub fn into_input(self, identity: Option) -> Input { - let input_str = include_str!("../../../examples/md-single/md-single.md"); - let mut input = md::md_to_input(input_str).expect("example cannot fail?"); +impl InputSource for MdExample { + fn into_input(&self, identity: Option) -> InputSourceKind { + let input_str = include_str!("../../../examples/markdown/single.md"); + let mut input = md_to_input(input_str).expect("example cannot fail?"); let server = input .servers .first_mut() .expect("example must have 1 server"); server.identity = identity.unwrap_or_else(ServerIdentity::named); - input + InputSourceKind::Type(input) } } diff --git a/crates/bsnext_example/src/playground.rs b/crates/bsnext_example/src/playground.rs new file mode 100644 index 0000000..e108f21 --- /dev/null +++ b/crates/bsnext_example/src/playground.rs @@ -0,0 +1,20 @@ +use bsnext_input::server_config::ServerIdentity; +use bsnext_input::{InputCreation, InputSource, InputSourceKind}; +use bsnext_md::md_fs::MdFs; + +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub struct PlaygroundExample; + +impl InputSource for PlaygroundExample { + fn into_input(&self, identity: Option) -> InputSourceKind { + let input_str = include_str!("../../../examples/markdown/playground.md"); + let mut input = MdFs::from_input_str(input_str).unwrap(); + + // update the server identity if it was provided + if let (Some(server), Some(identity)) = (input.servers.get_mut(0), identity) { + server.identity = identity; + } + + InputSourceKind::Type(input) + } +} diff --git a/crates/bsnext_input/Cargo.toml b/crates/bsnext_input/Cargo.toml index 09dc8da..6a8f908 100644 --- a/crates/bsnext_input/Cargo.toml +++ b/crates/bsnext_input/Cargo.toml @@ -9,7 +9,6 @@ edition = "2021" bsnext_resp = { path = "../bsnext_resp" } bsnext_tracing = { path = "../bsnext_tracing" } -markdown = { version = "1.0.0-alpha.16" } miette = { workspace = true } random_word = { workspace = true } @@ -22,7 +21,6 @@ serde_yaml = { workspace = true } serde_json = { workspace = true } toml = { workspace = true } thiserror = { workspace = true } -nom = "7.1.3" [dev-dependencies] insta = { workspace = true } diff --git a/crates/bsnext_input/src/lib.rs b/crates/bsnext_input/src/lib.rs index 3044c90..a664f4d 100644 --- a/crates/bsnext_input/src/lib.rs +++ b/crates/bsnext_input/src/lib.rs @@ -1,11 +1,7 @@ -use crate::target::TargetKind; - -use crate::md::MarkdownError; +use crate::server_config::ServerIdentity; use crate::yml::YamlError; -use miette::{JSONReportHandler, NamedSource}; +use miette::JSONReportHandler; use std::fmt::{Display, Formatter}; -use std::fs; -use std::fs::read_to_string; use std::net::AddrParseError; use std::path::{Path, PathBuf}; use std::str::FromStr; @@ -13,9 +9,9 @@ use std::str::FromStr; pub mod client_config; #[cfg(test)] pub mod input_test; -pub mod md; pub mod path_def; pub mod paths; +pub mod playground; pub mod route; pub mod route_manifest; pub mod server_config; @@ -54,51 +50,52 @@ impl FromStr for Input { } } -impl Input { - pub fn from_input_path>(path: P) -> Result> { - match path.as_ref().extension().and_then(|x| x.to_str()) { - None => Err(Box::new(InputError::MissingExtension( - path.as_ref().to_owned(), - ))), - Some("yml") | Some("yaml") => Input::from_yaml_path(path), - Some("md") | Some("markdown") => Input::from_md_path(path), - Some(other) => Err(Box::new(InputError::UnsupportedExtension( - other.to_string(), - ))), +#[derive(Debug)] +pub struct InputSourceFile { + path: PathBuf, + content: String, +} + +impl InputSourceFile { + pub fn new(path: impl Into, content: impl Into) -> Self { + Self { + path: path.into(), + content: content.into(), } } - fn from_yaml_path>(path: P) -> Result> { - let str = read_to_string(&path).map_err(|e| Box::new(e.into()))?; - if str.trim().is_empty() { - return Err(Box::new(InputError::YamlError(YamlError::EmptyError { - path: path.as_ref().to_string_lossy().to_string(), - }))); - } - let output = serde_yaml::from_str::(str.as_str()) - .map_err(move |e| { - if let Some(loc) = e.location() { - BsLiveRulesError { - err_span: (loc.index()..loc.index() + 1).into(), - src: NamedSource::new(path.as_ref().to_string_lossy().to_string(), str), - message: e.to_string(), - summary: None, - } - } else { - unreachable!("handle later") - } - }) - .map_err(|e| Box::new(e.into()))?; - // todo: don't allow duplicates?. - Ok(output) + + pub fn path(&self) -> &'_ Path { + &self.path + } + pub fn content(&self) -> &str { + &self.content } - fn from_md_path>(path: P) -> Result> { - let str = read_to_string(path).map_err(|e| Box::new(e.into()))?; - let input = md::md_to_input(&str).map_err(|e| Box::new(e.into()))?; - // todo: don't allow duplicates. - Ok(input) +} + +#[derive(Debug)] +pub enum InputSourceKind { + Type(Input), + File { + src_file: InputSourceFile, + input: Input, + }, +} + +pub trait InputSource { + fn into_input(&self, _identity: Option) -> InputSourceKind { + InputSourceKind::Type(Default::default()) } } +pub trait InputCreation { + fn from_input_path>(path: P) -> Result>; + fn from_input_str>(content: P) -> Result>; +} + +pub trait InputWriter { + fn input_to_str(&self, input: &Input) -> String; +} + #[derive(Debug, miette::Diagnostic, thiserror::Error)] pub enum InputError { #[error("no suitable inputs could be found")] @@ -124,7 +121,7 @@ pub enum InputError { #[error("{0}")] DirError(#[from] DirError), #[error("Markdown error: {0}")] - MarkdownError(#[from] MarkdownError), + MarkdownError(String), #[error("{0}")] YamlError(#[from] YamlError), #[error(transparent)] @@ -144,6 +141,10 @@ pub enum WatchError { pub enum InputWriteError { #[error("couldn't write input to {path}")] FailedWrite { path: PathBuf }, + #[error("couldn't read the status of {path}")] + CannotQueryStatus { path: PathBuf }, + #[error("input already exists, override with --force (dangerous) {path}")] + Exists { path: PathBuf }, } #[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)] @@ -166,6 +167,16 @@ pub enum DirError { CannotCreate { path: PathBuf }, #[error("could not change the process CWD to: {path}")] CannotMove { path: PathBuf }, + #[error("could not query the status")] + CannotQueryStatus { path: PathBuf }, + #[error("directory already exists, override with --force (dangerous) {path}")] + Exists { path: PathBuf }, +} + +impl From for Box { + fn from(value: DirError) -> Self { + Box::new(InputError::DirError(value)) + } } #[derive(miette::Diagnostic, Debug, thiserror::Error)] @@ -174,12 +185,12 @@ pub enum DirError { pub struct BsLiveRulesError { // Note: label but no source code #[label = "{message}"] - err_span: miette::SourceSpan, + pub err_span: miette::SourceSpan, #[source_code] - src: miette::NamedSource, - message: String, + pub src: miette::NamedSource, + pub message: String, #[help] - summary: Option, + pub summary: Option, } impl BsLiveRulesError { @@ -227,24 +238,3 @@ impl Display for PathDefinition { pub fn rand_word() -> String { random_word::gen(random_word::Lang::En).to_string() } - -pub fn fs_write_input( - cwd: &Path, - input: &Input, - target_kind: TargetKind, -) -> Result { - let string = match target_kind { - TargetKind::Yaml => serde_yaml::to_string(&input).expect("create yaml?"), - TargetKind::Toml => toml::to_string_pretty(&input).expect("create toml?"), - TargetKind::Md => md::input_to_str(input), - }; - let name = match target_kind { - TargetKind::Yaml => "bslive.yml", - TargetKind::Toml => "bslive.toml", - TargetKind::Md => "bslive.md", - }; - let next_path = cwd.join(name); - fs::write(&next_path, string) - .map(|()| next_path.clone()) - .map_err(|_e| InputWriteError::FailedWrite { path: next_path }) -} diff --git a/crates/bsnext_input/src/md.rs b/crates/bsnext_input/src/md.rs deleted file mode 100644 index 53f21da..0000000 --- a/crates/bsnext_input/src/md.rs +++ /dev/null @@ -1,544 +0,0 @@ -use crate::route::{RawRoute, Route, RouteKind}; -use crate::server_config::ServerConfig; -use crate::Input; - -use crate::path_def::PathDef; -use markdown::mdast::Node; -use markdown::{Constructs, ParseOptions}; -use mime_guess::get_mime_extensions_str; -use nom::branch::alt; -use nom::combinator::map; -use nom::multi::many0; -use nom::sequence::separated_pair; -use nom::{error::ParseError, IResult}; -use serde_json::json; -use std::cmp::PartialEq; -use std::str::FromStr; - -fn parser_for(k: BsLiveKinds) -> impl Fn(&[Node]) -> IResult<&[Node], &Node> { - move |input: &[Node]| { - if input.is_empty() || input[0].kind() != k { - Err(nom::Err::Error(ParseError::from_error_kind( - input, - nom::error::ErrorKind::Tag, - ))) - } else { - Ok((&input[1..], &input[0])) - } - } -} - -#[derive(Debug, PartialEq, PartialOrd)] -pub enum BsLiveKinds { - Input, - Route, - Body, - Ignored, -} - -#[derive(Debug, thiserror::Error)] -#[error(transparent)] -pub enum MarkdownError { - #[error("could not parse Markdown: {0}")] - ParseError(String), - #[error("invalid markdown format: {0}")] - InvalidFormat(String), -} - -trait BsLive { - fn kind(&self) -> BsLiveKinds; - fn is_input(&self) -> bool; - fn is_route(&self) -> bool; - fn is_body(&self) -> bool; - #[allow(dead_code)] - fn raw_value(&self) -> Option; -} - -impl TryInto for &Node { - type Error = anyhow::Error; - - fn try_into(self) -> Result { - if !self.is_input() { - return Err(anyhow::anyhow!("not an input type")); - } - match self { - Node::Code(code) => { - let config: Input = serde_yaml::from_str(&code.value)?; - Ok(config) - } - Node::Yaml(yaml) => { - let config: Input = serde_yaml::from_str(&yaml.value)?; - Ok(config) - } - _ => Err(anyhow::anyhow!("unreachable")), - } - } -} - -impl TryInto for Vec { - type Error = MarkdownError; - fn try_into(self) -> Result { - nodes_to_input(&self) - } -} - -impl TryInto for (&Node, &Node) { - type Error = anyhow::Error; - - fn try_into(self) -> Result { - match (self.0.is_route(), self.1.is_body()) { - (true, true) => match self.0 { - Node::Code(code) - if code - .lang - .as_ref() - .is_some_and(|l| l == "yaml" || l == "yml") => - { - #[derive(serde::Deserialize)] - struct PathOnly { - path: String, - } - let r: PathOnly = serde_yaml::from_str(&code.value)?; - let route_kind = route_kind_from_body_node(self.1)?; - let route = Route { - path: PathDef::from_str(&r.path)?, - kind: route_kind, - ..Default::default() - }; - Ok(route) - } - _ => Err(anyhow::anyhow!("unreachlable")), - }, - _ => Err(anyhow::anyhow!("cannot create")), - } - } -} - -fn route_kind_from_body_node(node: &Node) -> anyhow::Result { - match node { - Node::Code(code) => { - let value = code.value.clone(); - let rk = match code.lang.as_deref() { - Some("html") => RouteKind::new_html(&value), - Some("json") => RouteKind::new_json(serde_json::from_str(&value)?), - Some("sse") => RouteKind::new_sse(value), - Some(..) | None => RouteKind::new_raw(value), - }; - Ok(rk) - } - _ => Err(anyhow::anyhow!("unsupported route kind")), - } -} - -impl BsLive for Node { - fn kind(&self) -> BsLiveKinds { - if self.is_input() { - return BsLiveKinds::Input; - } - if self.is_route() { - return BsLiveKinds::Route; - } - if self.is_body() { - return BsLiveKinds::Body; - } - BsLiveKinds::Ignored - } - fn is_input(&self) -> bool { - match self { - // this is from front matter - Node::Yaml(_yaml) => true, - // code block with annotations - Node::Code(code) => code - .meta - .as_ref() - .is_some_and(|v| v.contains("bslive_input")), - _ => false, - } - } - - fn is_route(&self) -> bool { - match self { - Node::Code(code) => code - .meta - .as_ref() - .is_some_and(|v| v.contains("bslive_route")), - _ => false, - } - } - - fn is_body(&self) -> bool { - if self.is_input() || self.is_route() { - return false; - } - matches!(self, Node::Code(..)) - } - - fn raw_value(&self) -> Option { - if self.is_body() { - let Node::Code(code) = self else { - unreachable!("shouldnt get here"); - }; - Some(code.value.clone()) - } else { - None - } - } -} - -enum Convert { - None, - Input(Input), - Route(Route), -} - -pub fn nodes_to_input(nodes: &[Node]) -> Result { - let mut routes = vec![]; - let mut server_config: Option = None; - let mut parser = many0(alt(( - map(parser_for(BsLiveKinds::Ignored), |_v| Convert::None), - map(parser_for(BsLiveKinds::Input), |v: &Node| { - let as_config: Result = v.try_into(); - match as_config { - Ok(config) => Convert::Input(config), - Err(e) => unreachable!("? creating server config {:?}", e), - } - }), - map( - separated_pair( - parser_for(BsLiveKinds::Route), - many0(parser_for(BsLiveKinds::Ignored)), - parser_for(BsLiveKinds::Body), - ), - |pair| { - let as_route: Result = pair.try_into(); - match as_route { - Ok(route) => Convert::Route(route), - Err(e) => unreachable!("? {:?}", e), - } - }, - ), - ))); - - let results = parser(nodes); - - match results { - Ok((_rest, matched)) => { - for item in matched { - match item { - Convert::None => {} - Convert::Input(input_from_md) => { - // todo: handle server config - if server_config.is_none() { - server_config = Some(input_from_md) - } else { - unreachable!("todo: support multiple 'input' blocks") - } - } - Convert::Route(route) => { - routes.push(route); - } - } - } - } - Err(e) => return Err(MarkdownError::InvalidFormat(e.to_string())), - } - - match server_config.take() { - // config was not set, use default - None => { - let mut input = Input::default(); - let server = ServerConfig { - routes, - ..Default::default() - }; - input.servers.push(server); - Ok(input) - } - // got some server config, use it. - Some(mut input) => { - if let Some(server) = input.servers.first_mut() { - server.routes.extend(routes) - } - Ok(input) - } - } -} - -fn str_to_nodes(input: &str) -> Result, MarkdownError> { - let opts = ParseOptions { - constructs: Constructs { - frontmatter: true, - ..Default::default() - }, - ..Default::default() - }; - let root = - markdown::to_mdast(input, &opts).map_err(|e| MarkdownError::ParseError(e.to_string()))?; - match root { - Node::Root(root) => Ok(root.children), - _ => { - unreachable!("?"); - } - } -} - -pub fn md_to_input(input: &str) -> Result { - let root = str_to_nodes(input)?; - nodes_to_input(&root) -} - -#[cfg(test)] -mod test { - use super::*; - use crate::server_config::ServerIdentity; - - #[test] - fn test_single() -> anyhow::Result<()> { - // let input = include_str!("../../examples/md-single/md-single.md"); - let input = r#" - -# Demo 2 - -```yaml bslive_route -path: /app.css -``` - -```css -body { - background: blue -} -``` - "#; - let config = md_to_input(&input).expect("unwrap"); - let server_1 = config.servers.first().unwrap(); - assert_eq!( - server_1.routes[0], - Route { - path: "/app.css".parse()?, - kind: RouteKind::new_raw("body {\n background: blue\n}"), - ..Default::default() - } - ); - Ok(()) - } - - #[test] - fn test_2_consecutive() -> anyhow::Result<()> { - // let input = include_str!("../../examples/md-single/md-single.md"); - let input = r#" - -```yaml bslive_route -path: /app.css -``` - -```css -body { - background: blue -} -``` - -Some other text - -```yaml bslive_route -path: /app2.css -``` - -```css -body { - background: blue -} -``` - "#; - let config = md_to_input(&input).expect("unwrap"); - let server_1 = config.servers.first().unwrap(); - assert_eq!( - server_1.routes[0], - Route { - path: PathDef::from_str("/app.css")?, - kind: RouteKind::new_raw("body {\n background: blue\n}"), - ..Default::default() - } - ); - assert_eq!( - server_1.routes[1], - Route { - path: PathDef::from_str("/app2.css")?, - kind: RouteKind::new_raw("body {\n background: blue\n}"), - ..Default::default() - } - ); - Ok(()) - } - - #[test] - fn test_parse_with_elements_in_gaps() -> anyhow::Result<()> { - let input = r#" -# Before - -```yaml bslive_input -servers: - - bind_address: 0.0.0.0:3001 - routes: - - path: /health - raw: OK -``` - -```yaml bslive_route -path: / -``` - -in between? - -```html -

hello world

-``` - -```yaml bslive_route -path: /abc -``` -```html -

hello world 2

-``` - -# Before - "#; - let config = md_to_input(&input).expect("unwrap"); - let server_1 = config.servers.first().unwrap(); - let expected_id = ServerIdentity::Address { - bind_address: "0.0.0.0:3001".into(), - }; - assert_eq!(server_1.identity, expected_id); - assert_eq!(server_1.routes.len(), 3); - assert_eq!( - server_1.routes[0], - Route { - path: PathDef::from_str("/health")?, - kind: RouteKind::new_raw("OK"), - ..Default::default() - } - ); - assert_eq!( - server_1.routes[1], - Route { - path: PathDef::from_str("/")?, - kind: RouteKind::new_html("

hello world

"), - ..Default::default() - } - ); - assert_eq!( - server_1.routes[2], - Route { - path: PathDef::from_str("/abc")?, - kind: RouteKind::new_html("

hello world 2

"), - ..Default::default() - } - ); - Ok(()) - } - - fn default_md_assertions(input: &str) -> anyhow::Result<()> { - let input = md_to_input(&input).expect("unwrap"); - let server_1 = input.servers.first().unwrap(); - let expected_id = ServerIdentity::Address { - bind_address: "0.0.0.0:5001".into(), - }; - assert_eq!(server_1.identity, expected_id); - assert_eq!(server_1.routes.len(), 2); - let paths = server_1 - .routes - .iter() - .map(|r| r.path.as_str()) - .collect::>(); - - assert_eq!(paths, vec!["/app.css", "/"]); - Ok(()) - } - - #[test] - fn test_from_example_str() -> anyhow::Result<()> { - let input_str = include_str!("../../../examples/md-single/md-single.md"); - default_md_assertions(input_str) - } - - #[test] - fn test_from_example_str_frontmatter() -> anyhow::Result<()> { - let input_str = include_str!("../../../examples/md-single/frontmatter.md"); - default_md_assertions(input_str) - } -} - -pub fn input_to_str(input: &Input) -> String { - let mut chunks = vec![]; - if let Some(server_config) = input.servers.first() { - let without_routes = Input { - servers: vec![ServerConfig { - identity: server_config.identity.clone(), - routes: vec![], - ..Default::default() - }], - }; - let yml = serde_yaml::to_string(&without_routes).expect("never fail here"); - - chunks.push(fenced_input(&yml)); - - for route in &server_config.routes { - let path_only = json!({"path": route.path.as_str()}); - let route_yaml = serde_yaml::to_string(&path_only).expect("never fail here on route?"); - chunks.push(fenced_route(&route_yaml)); - chunks.push(route_to_markdown(&route.kind, route.path.as_str())); - } - } - for _x in input.servers.iter().skip(1) { - todo!("not supported yet!") - } - chunks.join("\n") -} - -fn route_to_markdown(kind: &RouteKind, path: &str) -> String { - match kind { - RouteKind::Raw(raw) => match raw { - RawRoute::Html { html } => fenced_body("html", html), - RawRoute::Json { .. } => todo!("unsupported json"), - RawRoute::Raw { raw } => { - let mime = mime_guess::from_path(path); - let as_str = mime.first_or_text_plain(); - let as_str = get_mime_extensions_str(as_str.as_ref()); - if let Some(v) = as_str.and_then(|x| x.first()) { - fenced_body(v, raw) - } else { - fenced_body("", raw) - } - } - RawRoute::Sse { .. } => todo!("unsupported"), - }, - RouteKind::Proxy(_) => todo!("unsupported"), - RouteKind::Dir(_) => todo!("unsupported"), - } -} - -fn fenced_input(code: &str) -> String { - format!("```yaml bslive_input\n{}```", code) -} - -fn fenced_route(code: &str) -> String { - format!("```yaml bslive_route\n{}```", code) -} - -fn fenced_body(lang: &str, code: &str) -> String { - format!("```{lang}\n{code}\n```") -} - -#[cfg(test)] -mod test_serialize { - use super::*; - #[test] - fn test_input_to_str() -> anyhow::Result<()> { - let input_str = include_str!("../../../examples/md-single/md-single.md"); - let input = md_to_input(&input_str).expect("unwrap"); - let _output = input_to_str(&input); - let input = md_to_input(&input_str).expect("unwrapped 2"); - assert_eq!(input.servers.len(), 1); - assert_eq!(input.servers.first().unwrap().routes.len(), 2); - Ok(()) - } -} diff --git a/crates/bsnext_input/src/playground.rs b/crates/bsnext_input/src/playground.rs new file mode 100644 index 0000000..270ae40 --- /dev/null +++ b/crates/bsnext_input/src/playground.rs @@ -0,0 +1,110 @@ +use crate::path_def::PathDef; +use crate::route::{FallbackRoute, Opts, Route, RouteKind}; +use bsnext_resp::builtin_strings::{BuiltinStringDef, BuiltinStrings}; +use bsnext_resp::inject_addition::{AdditionPosition, InjectAddition}; +use bsnext_resp::inject_opts::{InjectOpts, Injection, InjectionItem, MatcherList}; +use bsnext_resp::path_matcher::PathMatcher; + +#[derive(Debug, PartialEq, Default, Hash, Clone, serde::Deserialize, serde::Serialize)] +pub struct Playground { + pub html: String, + pub js: Option, + pub css: Option, +} + +const FALLBACK_HTML: &str = "This is a BSLIVE playground"; + +impl Playground { + pub fn as_routes(&self) -> Vec { + let home_path = PathDef::try_new("/"); + let js_path = PathDef::try_new("/__bslive_playground.js"); + let css_path = PathDef::try_new("/__bslive_playground.css"); + let reset_path = PathDef::try_new("/reset.css"); + + let (Ok(home), Ok(js), Ok(css), Ok(reset_path)) = + (home_path, js_path, css_path, reset_path) + else { + return vec![]; + }; + + let home_route = Route { + path: home, + kind: RouteKind::new_html(self.html.clone()), + opts: Opts { + cors: None, + delay: None, + watch: Default::default(), + inject: playground_wrap(), + headers: None, + compression: None, + }, + fallback: Some(FallbackRoute { + kind: RouteKind::new_html(FALLBACK_HTML), + opts: Default::default(), + }), + }; + let js_route = Route { + path: js, + kind: RouteKind::new_raw( + self.js + .as_ref() + .unwrap_or(&"// playground js is absent".to_string()), + ), + ..Default::default() + }; + let css_route = Route { + path: css, + kind: RouteKind::new_raw( + self.css + .as_ref() + .unwrap_or(&"/* playground css is absent */".to_string()), + ), + ..Default::default() + }; + let reset_route = Route { + path: reset_path, + kind: RouteKind::new_raw(include_str!("../../bsnext_client/ui/styles/reset.css")), + ..Default::default() + }; + vec![home_route, js_route, css_route, reset_route] + } +} + +fn playground_wrap() -> InjectOpts { + let prepend = r#" + + + + + + Document + + + +"#; + let append = r#" + + + +"#; + InjectOpts::Items(vec![ + InjectionItem { + inner: Injection::Addition(InjectAddition { + addition_position: AdditionPosition::Prepend(prepend.to_string()), + }), + only: Some(MatcherList::Item(PathMatcher::Str("/".to_string()))), + }, + InjectionItem { + inner: Injection::Addition(InjectAddition { + addition_position: AdditionPosition::Append(append.to_string()), + }), + only: Some(MatcherList::Item(PathMatcher::Str("/".to_string()))), + }, + InjectionItem { + inner: Injection::BsLive(BuiltinStringDef { + name: BuiltinStrings::Connector, + }), + only: Some(MatcherList::Item(PathMatcher::Str("/".to_string()))), + }, + ]) +} diff --git a/crates/bsnext_input/src/server_config.rs b/crates/bsnext_input/src/server_config.rs index 2e862fb..e008a48 100644 --- a/crates/bsnext_input/src/server_config.rs +++ b/crates/bsnext_input/src/server_config.rs @@ -1,4 +1,5 @@ use crate::client_config::ClientConfig; +use crate::playground::Playground; use crate::route::{Route, Watcher}; use crate::{rand_word, PortError}; use std::hash::{DefaultHasher, Hash, Hasher}; @@ -14,9 +15,27 @@ pub struct ServerConfig { #[serde(default)] pub watchers: Vec, #[serde(default)] + pub playground: Option, + #[serde(default)] pub clients: ClientConfig, } +impl ServerConfig { + /// + /// All regular routes, plus dynamically added ones (for example, through a playground) + /// + pub fn combined_routes(&self) -> Vec { + let mut routes = self.routes.clone(); + if let Some(playground) = &self.playground { + routes.extend(playground.as_routes()) + } + routes + } + pub fn routes(&self) -> &[Route] { + &self.routes + } +} + #[derive( Debug, Ord, PartialOrd, PartialEq, Hash, Eq, Clone, serde::Deserialize, serde::Serialize, )] diff --git a/crates/bsnext_md/Cargo.toml b/crates/bsnext_md/Cargo.toml new file mode 100644 index 0000000..e8ad7c6 --- /dev/null +++ b/crates/bsnext_md/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "bsnext_md" +version = "0.1.0" +edition = "2021" + +[dependencies] +markdown = { version = "1.0.0-alpha.16" } +nom = "7.1.3" +bsnext_input = { path = "../bsnext_input" } + +mime_guess = { workspace = true } +anyhow = { workspace = true } +serde = { workspace = true } +serde_yaml = { workspace = true } +serde_json = { workspace = true } +thiserror = { workspace = true } +insta = { workspace = true } diff --git a/crates/bsnext_md/src/lib.rs b/crates/bsnext_md/src/lib.rs new file mode 100644 index 0000000..d3f73f2 --- /dev/null +++ b/crates/bsnext_md/src/lib.rs @@ -0,0 +1,384 @@ +pub mod md_fs; +pub mod md_writer; + +use bsnext_input::path_def::PathDef; +use bsnext_input::playground::Playground; +use bsnext_input::route::{Route, RouteKind}; +use bsnext_input::server_config::ServerConfig; +use bsnext_input::Input; +use markdown::mdast::Node; +use markdown::{Constructs, ParseOptions}; +use nom::branch::alt; +use nom::combinator::map; +use nom::multi::many0; +use nom::sequence::{pair, separated_pair}; +use nom::{error::ParseError, IResult}; +use std::cmp::PartialEq; +use std::str::FromStr; + +fn parser_for(k: BsLiveKinds) -> impl Fn(&[Node]) -> IResult<&[Node], &Node> { + move |input: &[Node]| { + if input.is_empty() || input[0].kind() != k { + Err(nom::Err::Error(ParseError::from_error_kind( + input, + nom::error::ErrorKind::Tag, + ))) + } else { + Ok((&input[1..], &input[0])) + } + } +} + +#[derive(Debug, PartialEq, PartialOrd)] +pub enum BsLiveKinds { + Input, + Route, + PlaygroundHtml, + PlaygroundCSS, + PlaygroundJS, + Body, + Ignored, +} + +#[derive(Debug, thiserror::Error)] +#[error(transparent)] +pub enum MarkdownError { + #[error("could not parse Markdown: {0}")] + ParseError(String), + #[error("invalid markdown format: {0}")] + InvalidFormat(String), +} + +fn node_to_input(node: &Node) -> Result { + if !node.is_input() { + return Err(anyhow::anyhow!("not an input type")); + } + match node { + Node::Code(code) => { + let config: Input = serde_yaml::from_str(&code.value)?; + Ok(config) + } + Node::Yaml(yaml) => { + let config: Input = serde_yaml::from_str(&yaml.value)?; + Ok(config) + } + _ => Err(anyhow::anyhow!("unreachable")), + } +} + +fn pair_to_route((first, second): (&Node, &Node)) -> Result { + match (first.is_route(), second.is_body()) { + (true, true) => match first { + Node::Code(code) + if code + .lang + .as_ref() + .is_some_and(|l| l == "yaml" || l == "yml") => + { + #[derive(serde::Deserialize)] + struct PathOnly { + path: String, + } + let r: PathOnly = serde_yaml::from_str(&code.value)?; + let route_kind = route_kind_from_body_node(second)?; + let route = Route { + path: PathDef::from_str(&r.path)?, + kind: route_kind, + ..Default::default() + }; + Ok(route) + } + _ => Err(anyhow::anyhow!("unreachlable")), + }, + _ => Err(anyhow::anyhow!("cannot create")), + } +} + +fn route_kind_from_body_node(node: &Node) -> anyhow::Result { + match node { + Node::Code(code) => { + let value = code.value.clone(); + let rk = match code.lang.as_deref() { + Some("html") => RouteKind::new_html(&value), + Some("json") => RouteKind::new_json(serde_json::from_str(&value)?), + Some("sse") => RouteKind::new_sse(value), + Some(..) | None => RouteKind::new_raw(value), + }; + Ok(rk) + } + _ => Err(anyhow::anyhow!("unsupported route kind")), + } +} + +trait BsLive { + fn kind(&self) -> BsLiveKinds; + fn is_input(&self) -> bool; + fn is_route(&self) -> bool; + fn is_body(&self) -> bool; + fn is_playground_html(&self) -> bool; + fn is_playground_css(&self) -> bool; + fn is_playground_js(&self) -> bool; + #[allow(dead_code)] + fn raw_value(&self) -> Option; +} + +impl BsLive for Node { + fn kind(&self) -> BsLiveKinds { + if self.is_playground_html() { + return BsLiveKinds::PlaygroundHtml; + } + if self.is_input() { + return BsLiveKinds::Input; + } + if self.is_route() { + return BsLiveKinds::Route; + } + if self.is_playground_css() { + return BsLiveKinds::PlaygroundCSS; + } + if self.is_playground_js() { + return BsLiveKinds::PlaygroundJS; + } + if self.is_body() { + return BsLiveKinds::Body; + } + BsLiveKinds::Ignored + } + fn is_input(&self) -> bool { + match self { + // this is from front matter + Node::Yaml(_yaml) => true, + // code block with annotations + Node::Code(code) => code + .meta + .as_ref() + .is_some_and(|v| v.contains("bslive_input")), + _ => false, + } + } + + fn is_route(&self) -> bool { + match self { + Node::Code(code) => code + .meta + .as_ref() + .is_some_and(|v| v.contains("bslive_route")), + _ => false, + } + } + + fn is_body(&self) -> bool { + if self.is_input() || self.is_route() { + return false; + } + matches!(self, Node::Code(..)) + } + + fn is_playground_html(&self) -> bool { + match self { + Node::Code(code) => { + code.lang.as_ref().is_some_and(|v| v == "html") + && code.meta.as_ref().is_some_and(|v| v.contains("playground")) + } + _ => false, + } + } + + fn is_playground_css(&self) -> bool { + match self { + Node::Code(code) => code.lang.as_ref().is_some_and(|v| v == "css"), + _ => false, + } + } + + fn is_playground_js(&self) -> bool { + match self { + Node::Code(code) => code + .lang + .as_ref() + .is_some_and(|v| v == "js" || v == "javascript"), + _ => false, + } + } + + fn raw_value(&self) -> Option { + if self.is_body() { + let Node::Code(code) = self else { + unreachable!("shouldnt get here"); + }; + Some(code.value.clone()) + } else { + None + } + } +} + +enum Convert { + None, + Input(Input), + Route(Route), + Playground(Playground), +} + +pub fn nodes_to_input(nodes: &[Node]) -> Result { + let mut routes = vec![]; + let mut input: Option = None; + let mut parser = many0(alt(( + map(parser_for(BsLiveKinds::Ignored), |_v| Convert::None), + map(parser_for(BsLiveKinds::Input), |v: &Node| { + let as_config: Result = node_to_input(v); + match as_config { + Ok(config) => Convert::Input(config), + Err(e) => unreachable!("? creating server config {:?}", e), + } + }), + map( + separated_pair( + parser_for(BsLiveKinds::Route), + many0(parser_for(BsLiveKinds::Ignored)), + alt(( + parser_for(BsLiveKinds::Body), + parser_for(BsLiveKinds::PlaygroundCSS), + parser_for(BsLiveKinds::PlaygroundJS), + )), + ), + |route_body_pair| { + let as_route: Result = pair_to_route(route_body_pair); + match as_route { + Ok(route) => Convert::Route(route), + Err(_e) => { + // todo: add error handling here? + Convert::None + } + } + }, + ), + map( + pair( + parser_for(BsLiveKinds::PlaygroundHtml), + many0(alt(( + parser_for(BsLiveKinds::PlaygroundCSS), + parser_for(BsLiveKinds::PlaygroundJS), + ))), + ), + |(a, nodes): (&Node, Vec<&Node>)| { + let mut pl = Playground { + html: code_val(a).to_string(), + js: None, + css: None, + }; + + for node in nodes { + if let Node::Code(code) = &node { + match code.lang.as_ref() { + None => {} + Some(lang) if lang == "js" => { + if let Some(js) = pl.js.as_mut() { + *js = code.value.clone(); + } else { + pl.js = Some(code.value.clone()); + } + } + Some(lang) if lang == "css" => { + if let Some(css) = pl.css.as_mut() { + *css = code.value.clone(); + } else { + pl.css = Some(code.value.clone()); + } + } + Some(_) => { + unreachable!("unsupposted"); + } + } + } + } + + Convert::Playground(pl) + }, + ), + ))); + + let results = parser(nodes); + let mut playground: Option = None; + + match results { + Ok((_rest, matched)) => { + for item in matched { + match item { + Convert::None => {} + Convert::Input(input_from_md) => { + // todo: handle server config + if input.is_none() { + input = Some(input_from_md) + } else { + unreachable!("todo: support multiple 'input' blocks") + } + } + Convert::Route(route) => { + routes.push(route); + } + Convert::Playground(pl) => { + if playground.is_none() { + playground = Some(pl) + } + } + } + } + } + Err(e) => return Err(MarkdownError::InvalidFormat(e.to_string())), + } + + match input.take() { + // config was not set, use default + None => { + let mut input = Input::default(); + let server = ServerConfig { + routes, + ..Default::default() + }; + input.servers.push(server); + if let Some(s) = input.servers.get_mut(0) { + s.playground = playground + } + Ok(input) + } + // got some server config, use it. + Some(mut input) => { + if let Some(server) = input.servers.first_mut() { + server.routes.extend(routes); + server.playground = playground; + } + Ok(input) + } + } +} + +fn code_val(n: &Node) -> &str { + match n { + Node::Code(code) => code.value.as_str(), + _ => "", + } +} + +fn str_to_nodes(input: &str) -> Result, MarkdownError> { + let opts = ParseOptions { + constructs: Constructs { + frontmatter: true, + ..Default::default() + }, + ..Default::default() + }; + let root = + markdown::to_mdast(input, &opts).map_err(|e| MarkdownError::ParseError(e.to_string()))?; + match root { + Node::Root(root) => Ok(root.children), + _ => { + unreachable!("?"); + } + } +} + +pub fn md_to_input(input: &str) -> Result { + let root = str_to_nodes(input)?; + nodes_to_input(&root) +} diff --git a/crates/bsnext_md/src/md_fs.rs b/crates/bsnext_md/src/md_fs.rs new file mode 100644 index 0000000..b63e1fc --- /dev/null +++ b/crates/bsnext_md/src/md_fs.rs @@ -0,0 +1,20 @@ +use crate::md_to_input; +use bsnext_input::{Input, InputCreation, InputError}; +use std::fs::read_to_string; +use std::path::Path; + +pub struct MdFs; + +impl InputCreation for MdFs { + fn from_input_path>(path: P) -> Result> { + let str = read_to_string(path).map_err(|e| Box::new(e.into()))?; + let input = + md_to_input(&str).map_err(|e| Box::new(InputError::MarkdownError(e.to_string())))?; + Ok(input) + } + fn from_input_str>(content: P) -> Result> { + let input = md_to_input(&content.as_ref()) + .map_err(|e| Box::new(InputError::MarkdownError(e.to_string())))?; + Ok(input) + } +} diff --git a/crates/bsnext_md/src/md_writer.rs b/crates/bsnext_md/src/md_writer.rs new file mode 100644 index 0000000..68385b0 --- /dev/null +++ b/crates/bsnext_md/src/md_writer.rs @@ -0,0 +1,95 @@ +use bsnext_input::route::{RawRoute, RouteKind}; +use bsnext_input::server_config::ServerIdentity; +use bsnext_input::{Input, InputWriter}; +use mime_guess::get_mime_extensions_str; +use serde_json::json; + +pub struct MdWriter; + +impl InputWriter for MdWriter { + fn input_to_str(&self, input: &Input) -> String { + _input_to_str(input) + } +} + +pub fn _input_to_str(input: &Input) -> String { + let mut chunks = vec![]; + if let Some(server_config) = input.servers.first() { + #[derive(Debug, serde::Serialize)] + struct FakeServerConfig { + #[serde(flatten)] + identity: ServerIdentity, + } + #[derive(Debug, serde::Serialize)] + struct FakeInput { + servers: Vec, + } + let just_identity = FakeInput { + servers: vec![FakeServerConfig { + identity: server_config.identity.clone(), + }], + }; + let yml = serde_yaml::to_string(&just_identity).expect("never fail here"); + + chunks.push(fenced_input(&yml)); + + if let Some(playground) = &server_config.playground { + chunks.push(fenced_playground(&playground.html)); + if let Some(css) = &playground.css { + chunks.push(fenced_body("css", &css)); + } + if let Some(js) = &playground.js { + chunks.push(fenced_body("js", &js)); + } + } + + for route in server_config.routes() { + let path_only = json!({"path": route.path.as_str()}); + let route_yaml = serde_yaml::to_string(&path_only).expect("never fail here on route?"); + chunks.push(fenced_route(&route_yaml)); + chunks.push(route_to_markdown(&route.kind, route.path.as_str())); + } + } + for _x in input.servers.iter().skip(1) { + todo!("not supported yet!") + } + chunks.join("\n") +} + +fn route_to_markdown(kind: &RouteKind, path: &str) -> String { + match kind { + RouteKind::Raw(raw) => match raw { + RawRoute::Html { html } => fenced_body("html", html), + RawRoute::Json { .. } => todo!("unsupported json"), + RawRoute::Raw { raw } => { + let mime = mime_guess::from_path(path); + let as_str = mime.first_or_text_plain(); + let as_str = get_mime_extensions_str(as_str.as_ref()); + if let Some(v) = as_str.and_then(|x| x.first()) { + fenced_body(v, raw) + } else { + fenced_body("", raw) + } + } + RawRoute::Sse { .. } => todo!("unsupported"), + }, + RouteKind::Proxy(_) => todo!("unsupported"), + RouteKind::Dir(_) => todo!("unsupported"), + } +} + +fn fenced_input(code: &str) -> String { + format!("```yaml bslive_input\n{}```", code) +} + +fn fenced_route(code: &str) -> String { + format!("```yaml bslive_route\n{}```", code) +} + +fn fenced_playground(code: &str) -> String { + format!("```html playground\n{}\n```", code) +} + +fn fenced_body(lang: &str, code: &str) -> String { + format!("```{lang}\n{code}\n```") +} diff --git a/crates/bsnext_md/tests/md.rs b/crates/bsnext_md/tests/md.rs new file mode 100644 index 0000000..3cc73b4 --- /dev/null +++ b/crates/bsnext_md/tests/md.rs @@ -0,0 +1,179 @@ +use bsnext_input::path_def::PathDef; +use bsnext_input::route::{Route, RouteKind}; +use bsnext_input::server_config::ServerIdentity; +use bsnext_md::md_to_input; +use std::str::FromStr; + +#[test] +fn test_single() -> anyhow::Result<()> { + // let input = include_str!("../../examples/markdown/markdown.md"); + let input = r#" + +# Demo 2 + +```yaml bslive_route +path: /app.css +``` + +```css +body { + background: blue +} +``` + "#; + let config = md_to_input(&input).expect("unwrap"); + let server_1 = config.servers.first().unwrap(); + assert_eq!( + server_1.routes[0], + Route { + path: "/app.css".parse()?, + kind: RouteKind::new_raw("body {\n background: blue\n}"), + ..Default::default() + } + ); + Ok(()) +} + +#[test] +fn test_2_consecutive() -> anyhow::Result<()> { + // let input = include_str!("../../examples/markdown/markdown.md"); + let input = r#" + +```yaml bslive_route +path: /app.css +``` + +```css +body { + background: blue +} +``` + +Some other text + +```yaml bslive_route +path: /app2.css +``` + +```css +body { + background: blue +} +``` + "#; + let config = md_to_input(&input).expect("unwrap"); + let server_1 = config.servers.first().unwrap(); + assert_eq!( + server_1.routes[0], + Route { + path: PathDef::from_str("/app.css")?, + kind: RouteKind::new_raw("body {\n background: blue\n}"), + ..Default::default() + } + ); + assert_eq!( + server_1.routes[1], + Route { + path: PathDef::from_str("/app2.css")?, + kind: RouteKind::new_raw("body {\n background: blue\n}"), + ..Default::default() + } + ); + Ok(()) +} + +#[test] +fn test_parse_with_elements_in_gaps() -> anyhow::Result<()> { + let markdown = r#" +# Before + +```yaml bslive_input +servers: + - bind_address: 0.0.0.0:3001 + routes: + - path: /health + raw: OK +``` + +```yaml bslive_route +path: / +``` + +in between? + +```html +

hello world

+``` + +```yaml bslive_route +path: /abc +``` +```html +

hello world 2

+``` + +# Before + "#; + let input = md_to_input(&markdown).expect("unwrap"); + let server_1 = input.servers.first().unwrap(); + let expected_id = ServerIdentity::Address { + bind_address: "0.0.0.0:3001".into(), + }; + assert_eq!(server_1.identity, expected_id); + assert_eq!(server_1.routes.len(), 3); + assert_eq!( + server_1.routes[0], + Route { + path: PathDef::from_str("/health")?, + kind: RouteKind::new_raw("OK"), + ..Default::default() + } + ); + assert_eq!( + server_1.routes[1], + Route { + path: PathDef::from_str("/")?, + kind: RouteKind::new_html("

hello world

"), + ..Default::default() + } + ); + assert_eq!( + server_1.routes[2], + Route { + path: PathDef::from_str("/abc")?, + kind: RouteKind::new_html("

hello world 2

"), + ..Default::default() + } + ); + Ok(()) +} + +fn default_md_assertions(input: &str) -> anyhow::Result<()> { + let input = md_to_input(&input).expect("unwrap"); + let server_1 = input.servers.first().unwrap(); + let expected_id = ServerIdentity::Address { + bind_address: "0.0.0.0:5001".into(), + }; + assert_eq!(server_1.identity, expected_id); + assert_eq!(server_1.routes.len(), 2); + let paths = server_1 + .routes + .iter() + .map(|r| r.path.as_str()) + .collect::>(); + + assert_eq!(paths, vec!["/app.css", "/"]); + Ok(()) +} + +#[test] +fn test_from_example_str() -> anyhow::Result<()> { + let input_str = include_str!("../../../examples/markdown/single.md"); + default_md_assertions(input_str) +} + +#[test] +fn test_from_example_str_frontmatter() -> anyhow::Result<()> { + let input_str = include_str!("../../../examples/markdown/frontmatter.md"); + default_md_assertions(input_str) +} diff --git a/crates/bsnext_md/tests/md_playground.rs b/crates/bsnext_md/tests/md_playground.rs new file mode 100644 index 0000000..841f5c1 --- /dev/null +++ b/crates/bsnext_md/tests/md_playground.rs @@ -0,0 +1,39 @@ +use bsnext_md::md_to_input; + +#[test] +fn test_md_playground() -> anyhow::Result<()> { + // let input = include_str!("../../examples/markdown/markdown.md"); + let input = r#" + +```html playground + +
+ Hello world! +
+``` + +```css +@import url("/reset.css"); + +:root { + border: 50px solid pink; + height: 100vh; + overflow: hidden; +} +``` + +```js +console.log("hello world") +``` + + "#; + let config = md_to_input(&input).expect("unwrap"); + let first_server = config.servers.get(0).unwrap(); + let routes = first_server + .playground + .as_ref() + .map(|x| x.as_routes()) + .unwrap(); + insta::assert_debug_snapshot!(routes); + Ok(()) +} diff --git a/crates/bsnext_md/tests/md_serialize.rs b/crates/bsnext_md/tests/md_serialize.rs new file mode 100644 index 0000000..ab53ceb --- /dev/null +++ b/crates/bsnext_md/tests/md_serialize.rs @@ -0,0 +1,16 @@ +use bsnext_input::InputWriter; +use bsnext_md::md_to_input; +use bsnext_md::md_writer::MdWriter; + +#[test] +fn test_input_to_str() -> anyhow::Result<()> { + let input_str = include_str!("../../../examples/markdown/single.md"); + let input = md_to_input(&input_str).expect("unwrap"); + let output = MdWriter.input_to_str(&input); + println!("{}", output); + let input = md_to_input(&output).expect("unwrapped 2"); + println!("{:#?}", input); + assert_eq!(input.servers.len(), 1); + assert_eq!(input.servers.first().unwrap().routes.len(), 2); + Ok(()) +} diff --git a/crates/bsnext_md/tests/snapshots/md_playground__md_playground.snap b/crates/bsnext_md/tests/snapshots/md_playground__md_playground.snap new file mode 100644 index 0000000..19ec386 --- /dev/null +++ b/crates/bsnext_md/tests/snapshots/md_playground__md_playground.snap @@ -0,0 +1,165 @@ +--- +source: crates/bsnext_md/tests/md_playground.rs +expression: routes +--- +[ + Route { + path: PathDef { + inner: "/", + }, + kind: Raw( + Html { + html: "\n
\n Hello world!\n
", + }, + ), + opts: Opts { + cors: None, + delay: None, + watch: Bool( + true, + ), + inject: Items( + [ + InjectionItem { + inner: Addition( + InjectAddition { + addition_position: Prepend( + "\n\n \n \n \n \n Document\n \n \n \n", + ), + }, + ), + only: Some( + Item( + Str( + "/", + ), + ), + ), + }, + InjectionItem { + inner: Addition( + InjectAddition { + addition_position: Append( + "\n \n \n\n", + ), + }, + ), + only: Some( + Item( + Str( + "/", + ), + ), + ), + }, + InjectionItem { + inner: BsLive( + BuiltinStringDef { + name: Connector, + }, + ), + only: Some( + Item( + Str( + "/", + ), + ), + ), + }, + ], + ), + headers: None, + compression: None, + }, + fallback: Some( + FallbackRoute { + kind: Raw( + Html { + html: "This is a BSLIVE playground", + }, + ), + opts: Opts { + cors: None, + delay: None, + watch: Bool( + true, + ), + inject: Bool( + true, + ), + headers: None, + compression: None, + }, + }, + ), + }, + Route { + path: PathDef { + inner: "/__bslive_playground.js", + }, + kind: Raw( + Raw { + raw: "console.log(\"hello world\")", + }, + ), + opts: Opts { + cors: None, + delay: None, + watch: Bool( + true, + ), + inject: Bool( + true, + ), + headers: None, + compression: None, + }, + fallback: None, + }, + Route { + path: PathDef { + inner: "/__bslive_playground.css", + }, + kind: Raw( + Raw { + raw: "@import url(\"/reset.css\");\n\n:root {\n border: 50px solid pink;\n height: 100vh;\n overflow: hidden;\n}", + }, + ), + opts: Opts { + cors: None, + delay: None, + watch: Bool( + true, + ), + inject: Bool( + true, + ), + headers: None, + compression: None, + }, + fallback: None, + }, + Route { + path: PathDef { + inner: "/reset.css", + }, + kind: Raw( + Raw { + raw: "/*\n 1. Use a more-intuitive box-sizing model.\n*/\n*, *::before, *::after {\n box-sizing: border-box;\n}\n\n/*\n 2. Remove default margin\n*/\n* {\n margin: 0;\n}\n\n/*\n Typographic tweaks!\n 3. Add accessible line-height\n 4. Improve text rendering\n*/\nbody {\n line-height: 1.5;\n -webkit-font-smoothing: antialiased;\n}\n\n/*\n 5. Improve media defaults\n*/\nimg, picture, video, canvas, svg {\n display: block;\n max-width: 100%;\n}\n\n/*\n 6. Remove built-in form typography styles\n*/\ninput, button, textarea, select {\n font: inherit;\n}\n\n/*\n 7. Avoid text overflows\n*/\np, h1, h2, h3, h4, h5, h6 {\n overflow-wrap: break-word;\n}\n\n/*\n 8. Create a root stacking context\n*/\n#root, #__next {\n isolation: isolate;\n}", + }, + ), + opts: Opts { + cors: None, + delay: None, + watch: Bool( + true, + ), + inject: Bool( + true, + ), + headers: None, + compression: None, + }, + fallback: None, + }, +] diff --git a/crates/bsnext_resp/src/inject_opt_test/mod.rs b/crates/bsnext_resp/src/inject_opt_test/mod.rs index 0b54e17..1674dd8 100644 --- a/crates/bsnext_resp/src/inject_opt_test/mod.rs +++ b/crates/bsnext_resp/src/inject_opt_test/mod.rs @@ -68,12 +68,21 @@ fn test_inject_builtin() { let input = r#" inject: - name: bslive:connector + - append: 'other' "#; let expected = A { - inject: InjectOpts::Items(vec![InjectionItem { - inner: Injection::BsLive(BuiltinStringDef { name: Connector }), - only: None, - }]), + inject: InjectOpts::Items(vec![ + InjectionItem { + inner: Injection::BsLive(BuiltinStringDef { name: Connector }), + only: None, + }, + InjectionItem { + inner: Injection::Addition(InjectAddition { + addition_position: AdditionPosition::Append(String::from("other")), + }), + only: None, + }, + ]), }; let actual: Result = serde_yaml::from_str(input); assert_eq!(actual.unwrap().inject, expected.inject); diff --git a/crates/bsnext_system/Cargo.toml b/crates/bsnext_system/Cargo.toml index fe06be8..d066b36 100644 --- a/crates/bsnext_system/Cargo.toml +++ b/crates/bsnext_system/Cargo.toml @@ -7,6 +7,8 @@ edition = "2021" [dependencies] bsnext_input = { path = "../bsnext_input" } +bsnext_md = { path = "../bsnext_md" } +bsnext_yaml = { path = "../bsnext_yaml" } bsnext_tracing = { path = "../bsnext_tracing" } bsnext_core = { path = "../bsnext_core" } bsnext_fs = { path = "../bsnext_fs" } diff --git a/crates/bsnext_system/src/args.rs b/crates/bsnext_system/src/args.rs index 6598d69..12782c5 100644 --- a/crates/bsnext_system/src/args.rs +++ b/crates/bsnext_system/src/args.rs @@ -25,6 +25,10 @@ pub struct Args { #[arg(long)] pub write: bool, + /// Force write over directories or files (dangerous) + #[arg(long, requires = "write")] + pub force: bool, + /// Write input to disk #[arg(long, requires = "write")] pub target: Option, @@ -36,8 +40,12 @@ pub struct Args { #[arg(long, requires = "example")] pub temp: bool, + /// Override output folder (not compatible with 'temp') + #[arg(long, requires = "example", conflicts_with = "temp")] + pub dir: Option, + /// create a temp folder for examples instead of using the current dir - #[arg(long, requires = "example")] + #[arg(long, requires = "example", conflicts_with = "dir")] pub name: Option, /// Only works with `--example` - specify a port instead of a random one diff --git a/crates/bsnext_system/src/cli.rs b/crates/bsnext_system/src/cli.rs index 8a3086f..84c8804 100644 --- a/crates/bsnext_system/src/cli.rs +++ b/crates/bsnext_system/src/cli.rs @@ -44,6 +44,8 @@ where let start_kind = StartKind::from_args(args); + tracing::debug!(?start_kind); + let start = Start { kind: start_kind, cwd: Some(cwd), diff --git a/crates/bsnext_system/src/input_fs.rs b/crates/bsnext_system/src/input_fs.rs new file mode 100644 index 0000000..02a25e5 --- /dev/null +++ b/crates/bsnext_system/src/input_fs.rs @@ -0,0 +1,15 @@ +use bsnext_input::{Input, InputCreation, InputError}; +use std::path::Path; + +pub fn from_input_path>(path: P) -> Result> { + match path.as_ref().extension().and_then(|x| x.to_str()) { + None => Err(Box::new(InputError::MissingExtension( + path.as_ref().to_owned(), + ))), + Some("yml") | Some("yaml") => bsnext_yaml::yaml_fs::YamlFs::from_input_path(path), + Some("md") | Some("markdown") => bsnext_md::md_fs::MdFs::from_input_path(path), + Some(other) => Err(Box::new(InputError::UnsupportedExtension( + other.to_string(), + ))), + } +} diff --git a/crates/bsnext_system/src/lib.rs b/crates/bsnext_system/src/lib.rs index 4230e12..932d729 100644 --- a/crates/bsnext_system/src/lib.rs +++ b/crates/bsnext_system/src/lib.rs @@ -34,6 +34,7 @@ use tracing::{debug_span, Instrument}; pub mod args; pub mod cli; +pub mod input_fs; pub mod monitor; mod monitor_any_watchables; pub mod start_kind; @@ -280,12 +281,16 @@ impl Handler for BsSystem { unreachable!("?") }; + tracing::debug!("{:?}", self.cwd); + let servers = ServersSupervisor::new(msg.ack); // store the servers addr for later self.servers_addr = Some(servers.start()); let start_context = StartupContext::from_cwd(self.cwd.as_ref()); + tracing::debug!(?start_context); + match msg.kind.input(&start_context) { Ok(SystemStartArgs::PathWithInput { path, input }) => { tracing::debug!("PathWithInput"); @@ -313,10 +318,7 @@ impl Handler for BsSystem { self.publish_any_event(AnyEvent::Internal(InternalEvents::InputError(input_error))); Ok(DidStart::Started) } - Err(e) => { - tracing::error!(%e); - Err(StartupError::InputError(*e)) - } + Err(e) => Err(StartupError::InputError(*e)), } } } diff --git a/crates/bsnext_system/src/monitor.rs b/crates/bsnext_system/src/monitor.rs index b765825..07186d9 100644 --- a/crates/bsnext_system/src/monitor.rs +++ b/crates/bsnext_system/src/monitor.rs @@ -17,6 +17,7 @@ use std::time::Duration; use bsnext_fs::actor::FsWatcher; +use crate::input_fs::from_input_path; use bsnext_dto::internal::{AnyEvent, InternalEvents}; use bsnext_input::watch_opts::WatchOpts; use tracing::trace_span; @@ -92,7 +93,7 @@ impl BsSystem { match msg.ctx.id() { 0 => { tracing::info!(?inner, "InputFile file changed"); - let input = Input::from_input_path(&inner.absolute_path); + let input = from_input_path(&inner.absolute_path); let Ok(input) = input else { let err = input.unwrap_err(); diff --git a/crates/bsnext_system/src/start_kind.rs b/crates/bsnext_system/src/start_kind.rs index 4579401..fbd38e0 100644 --- a/crates/bsnext_system/src/start_kind.rs +++ b/crates/bsnext_system/src/start_kind.rs @@ -3,7 +3,6 @@ use crate::start_kind::start_from_example::StartFromExample; use crate::start_kind::start_from_inputs::{StartFromInput, StartFromInputPaths}; use crate::start_kind::start_from_paths::StartFromPaths; use bsnext_input::startup::{StartupContext, SystemStart, SystemStartArgs}; - use bsnext_input::{Input, InputError}; pub mod start_from_example; @@ -28,6 +27,8 @@ impl StartKind { temp: args.temp, name: args.name, target_kind: args.target.unwrap_or_default(), + dir: args.dir.clone(), + force: args.force, }); } @@ -36,6 +37,7 @@ impl StartKind { paths: args.paths, write_input: args.write, port: args.port, + force: args.force, }) } else { StartKind::FromInputPaths(StartFromInputPaths { @@ -58,3 +60,96 @@ impl SystemStart for StartKind { } } } + +pub mod start_fs { + + use std::fs; + use std::path::{Path, PathBuf}; + + use bsnext_input::target::TargetKind; + use bsnext_input::{DirError, Input, InputWriteError}; + + #[derive(Default, Debug, PartialEq)] + pub enum WriteMode { + #[default] + Safe, + Override, + } + pub fn fs_write_input( + cwd: &Path, + input: &Input, + target_kind: TargetKind, + write_mode: &WriteMode, + ) -> Result { + let string = match target_kind { + TargetKind::Yaml => bsnext_yaml::input_to_str(input), + TargetKind::Toml => todo!("toml missing"), + TargetKind::Md => bsnext_md::md_writer::_input_to_str(input), + }; + let name = match target_kind { + TargetKind::Yaml => "bslive.yml", + TargetKind::Toml => todo!("toml missing"), + TargetKind::Md => "bslive.md", + }; + let next_path = cwd.join(name); + tracing::info!( + "✏️ writing {} bytes to {}", + string.len(), + next_path.display() + ); + + let exists = fs::exists(&next_path).map_err(|_e| InputWriteError::CannotQueryStatus { + path: next_path.clone(), + })?; + + if exists && *write_mode == WriteMode::Safe { + return Err(InputWriteError::Exists { path: next_path }); + } + + fs::write(&next_path, string) + .map(|()| next_path.clone()) + .map_err(|_e| InputWriteError::FailedWrite { path: next_path }) + } + pub fn fs_write_input_src( + cwd: &Path, + path: &Path, + string: &str, + write_mode: &WriteMode, + ) -> Result { + let next_path = cwd.join(path); + tracing::info!( + "✏️ writing {} bytes to {}", + string.len(), + next_path.display() + ); + + let exists = fs::exists(&next_path).map_err(|_e| InputWriteError::CannotQueryStatus { + path: next_path.clone(), + })?; + + if exists && *write_mode == WriteMode::Safe { + return Err(InputWriteError::Exists { path: next_path }); + } + + fs::write(&next_path, string) + .map(|()| next_path.clone()) + .map_err(|_e| InputWriteError::FailedWrite { path: next_path }) + } + + pub fn create_dir(dir: &PathBuf, write_mode: &WriteMode) -> Result { + let exists = + fs::exists(dir).map_err(|_e| DirError::CannotQueryStatus { path: dir.clone() })?; + + if exists && *write_mode == WriteMode::Safe { + return Err(DirError::Exists { path: dir.clone() }); + } + + fs::create_dir_all(dir) + .map_err(|_e| DirError::CannotCreate { path: dir.clone() }) + .and_then(|_pb| { + std::env::set_current_dir(dir) + .map_err(|_e| DirError::CannotMove { path: dir.clone() }) + }) + .map(|_| dir.clone()) + } +} diff --git a/crates/bsnext_system/src/start_kind/snapshots/bsnext_system__start_kind__start_from_paths__test__test-2.snap b/crates/bsnext_system/src/start_kind/snapshots/bsnext_system__start_kind__start_from_paths__test__test-2.snap index fc10141..ae8ed35 100644 --- a/crates/bsnext_system/src/start_kind/snapshots/bsnext_system__start_kind__start_from_paths__test__test-2.snap +++ b/crates/bsnext_system/src/start_kind/snapshots/bsnext_system__start_kind__start_from_paths__test__test-2.snap @@ -14,5 +14,6 @@ servers: compression: ~ fallback: ~ watchers: [] + playground: ~ clients: log: info diff --git a/crates/bsnext_system/src/start_kind/snapshots/bsnext_system__start_kind__start_from_paths__test__test.snap b/crates/bsnext_system/src/start_kind/snapshots/bsnext_system__start_kind__start_from_paths__test__test.snap index bb031ef..643f235 100644 --- a/crates/bsnext_system/src/start_kind/snapshots/bsnext_system__start_kind__start_from_paths__test__test.snap +++ b/crates/bsnext_system/src/start_kind/snapshots/bsnext_system__start_kind__start_from_paths__test__test.snap @@ -35,6 +35,7 @@ Input { }, ], watchers: [], + playground: None, clients: ClientConfig { log: Info, }, diff --git a/crates/bsnext_system/src/start_kind/start_from_example.rs b/crates/bsnext_system/src/start_kind/start_from_example.rs index f43be5d..885940d 100644 --- a/crates/bsnext_system/src/start_kind/start_from_example.rs +++ b/crates/bsnext_system/src/start_kind/start_from_example.rs @@ -1,9 +1,9 @@ +use crate::start_kind::start_fs; use bsnext_example::Example; use bsnext_input::server_config::ServerIdentity; use bsnext_input::startup::{StartupContext, SystemStart, SystemStartArgs}; use bsnext_input::target::TargetKind; -use bsnext_input::{fs_write_input, rand_word, DirError, InputError}; -use std::fs; +use bsnext_input::{rand_word, InputError, InputSource, InputSourceKind}; #[derive(Debug)] pub struct StartFromExample { @@ -12,41 +12,73 @@ pub struct StartFromExample { pub target_kind: TargetKind, pub port: Option, pub temp: bool, + pub force: bool, pub name: Option, + pub dir: Option, } impl SystemStart for StartFromExample { fn input(&self, ctx: &StartupContext) -> Result> { let identity = ServerIdentity::from_port_or_named(self.port).map_err(|e| Box::new(e.into()))?; - let input = self.example.into_input(identity); - let name = self.name.clone(); - let dir = if self.temp { + let input_source_kind = self.example.into_input(Some(identity)); + + let write_mode = if self.force { + start_fs::WriteMode::Override + } else { + start_fs::WriteMode::Safe + }; + + let target_dir = if self.temp { let temp_dir = std::env::temp_dir(); + let name = self.name.clone(); let word = name.unwrap_or_else(rand_word); let num = rand::random::(); let next_dir = temp_dir.join(format!("bslive-{word}-{num}")); - fs::create_dir_all(&next_dir) - .map_err(|_e| DirError::CannotCreate { - path: next_dir.clone(), - }) - .and_then(|_pb| { - std::env::set_current_dir(&next_dir).map_err(|_e| DirError::CannotMove { - path: next_dir.clone(), - }) - }) - .map(|_| next_dir.clone()) - .map_err(|e| Box::new(e.into()))? + start_fs::create_dir(&next_dir, &write_mode)? + } else if let Some(dir) = &self.dir { + let next_dir = ctx.cwd.join(dir); + start_fs::create_dir(&next_dir, &write_mode)? } else { ctx.cwd.to_path_buf() }; - if self.write_input { - let path = fs_write_input(&dir, &input, self.target_kind.clone()) - .map_err(|e| Box::new(e.into()))?; - Ok(SystemStartArgs::PathWithInput { path, input }) - } else { - Ok(SystemStartArgs::InputOnly { input }) + if !self.write_input { + tracing::info!("NOT writing input..."); + return match input_source_kind { + InputSourceKind::Type(input) => Ok(SystemStartArgs::InputOnly { input }), + InputSourceKind::File { input, .. } => Ok(SystemStartArgs::InputOnly { input }), + }; } + + tracing::info!( + "will write to {} because write_input was true.", + target_dir.display() + ); + + let (path, input) = match input_source_kind { + InputSourceKind::Type(input) => { + let path = start_fs::fs_write_input( + &target_dir, + &input, + self.target_kind.clone(), + &write_mode, + ) + .map_err(|e| Box::new(e.into()))?; + (path, input) + } + InputSourceKind::File { src_file, input } => { + let path = start_fs::fs_write_input_src( + &target_dir, + &src_file.path(), + &src_file.content(), + &write_mode, + ) + .map_err(|e| Box::new(e.into()))?; + (path, input) + } + }; + + Ok(SystemStartArgs::PathWithInput { path, input }) } } diff --git a/crates/bsnext_system/src/start_kind/start_from_inputs.rs b/crates/bsnext_system/src/start_kind/start_from_inputs.rs index 7870c40..9be6874 100644 --- a/crates/bsnext_system/src/start_kind/start_from_inputs.rs +++ b/crates/bsnext_system/src/start_kind/start_from_inputs.rs @@ -1,5 +1,6 @@ use bsnext_input::startup::{StartupContext, SystemStart, SystemStartArgs}; +use crate::input_fs::from_input_path; use bsnext_input::{Input, InputError}; use std::path::{Path, PathBuf}; @@ -36,7 +37,7 @@ fn from_yml_paths>( .map(|path| cwd.join(path.as_ref())) .collect::>(); - let lookups = ["bslive.yml", "bslive.yaml"] + let lookups = ["bslive.yml", "bslive.yaml", "bslive.md"] .iter() .map(|path| cwd.join(path)) .collect::>(); @@ -74,7 +75,7 @@ fn from_yml_paths>( tracing::info!(?input_path); - let result = Input::from_input_path(input_path); + let result = from_input_path(input_path); match result { Ok(input) => Ok(SystemStartArgs::PathWithInput { path: input_path.to_path_buf(), diff --git a/crates/bsnext_system/src/start_kind/start_from_paths.rs b/crates/bsnext_system/src/start_kind/start_from_paths.rs index 1cb3576..88114c5 100644 --- a/crates/bsnext_system/src/start_kind/start_from_paths.rs +++ b/crates/bsnext_system/src/start_kind/start_from_paths.rs @@ -1,14 +1,17 @@ +use crate::start_kind::start_fs; +use crate::start_kind::start_fs::WriteMode; use bsnext_input::paths::from_paths; use bsnext_input::server_config::ServerIdentity; use bsnext_input::startup::{StartupContext, SystemStart, SystemStartArgs}; use bsnext_input::target::TargetKind; -use bsnext_input::{fs_write_input, InputError}; +use bsnext_input::InputError; #[derive(Debug)] pub struct StartFromPaths { pub paths: Vec, pub write_input: bool, pub port: Option, + pub force: bool, } impl SystemStart for StartFromPaths { @@ -16,8 +19,13 @@ impl SystemStart for StartFromPaths { let identity = ServerIdentity::from_port_or_named(self.port).map_err(|e| Box::new(e.into()))?; let input = from_paths(&ctx.cwd, &self.paths, identity).map_err(|e| Box::new(e.into()))?; + let write_mode = if self.force { + WriteMode::Override + } else { + WriteMode::Safe + }; if self.write_input { - let path = fs_write_input(&ctx.cwd, &input, TargetKind::Yaml) + let path = start_fs::fs_write_input(&ctx.cwd, &input, TargetKind::Yaml, &write_mode) .map_err(|e| Box::new(e.into()))?; Ok(SystemStartArgs::PathWithInput { input, path }) } else { @@ -37,6 +45,7 @@ mod test { paths: vec![".".into()], write_input: false, port: Some(3000), + force: false, }; let ctx = StartupContext { cwd: tmp_dir.path().to_path_buf(), diff --git a/crates/bsnext_yaml/Cargo.toml b/crates/bsnext_yaml/Cargo.toml new file mode 100644 index 0000000..97ee548 --- /dev/null +++ b/crates/bsnext_yaml/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "bsnext_yaml" +version = "0.1.0" +edition = "2021" + +[dependencies] +serde = { workspace = true } +serde_yaml = { workspace = true } +bsnext_input = { path = "../bsnext_input" } +miette = { workspace = true } \ No newline at end of file diff --git a/crates/bsnext_yaml/src/lib.rs b/crates/bsnext_yaml/src/lib.rs new file mode 100644 index 0000000..5768f57 --- /dev/null +++ b/crates/bsnext_yaml/src/lib.rs @@ -0,0 +1,6 @@ +pub mod yaml_fs; +use bsnext_input::Input; + +pub fn input_to_str(input: &Input) -> String { + serde_yaml::to_string(&input).expect("create yaml?") +} diff --git a/crates/bsnext_yaml/src/yaml_fs.rs b/crates/bsnext_yaml/src/yaml_fs.rs new file mode 100644 index 0000000..0df1d03 --- /dev/null +++ b/crates/bsnext_yaml/src/yaml_fs.rs @@ -0,0 +1,38 @@ +use bsnext_input::yml::YamlError; +use bsnext_input::{BsLiveRulesError, Input, InputCreation, InputError}; +use miette::NamedSource; +use std::fs::read_to_string; +use std::path::Path; + +pub struct YamlFs; + +impl InputCreation for YamlFs { + fn from_input_path>(path: P) -> Result> { + let str = read_to_string(&path).map_err(|e| Box::new(e.into()))?; + if str.trim().is_empty() { + return Err(Box::new(InputError::YamlError(YamlError::EmptyError { + path: path.as_ref().to_string_lossy().to_string(), + }))); + } + let output = serde_yaml::from_str::(str.as_str()) + .map_err(move |e| { + if let Some(loc) = e.location() { + BsLiveRulesError { + err_span: (loc.index()..loc.index() + 1).into(), + src: NamedSource::new(path.as_ref().to_string_lossy(), str), + message: e.to_string(), + summary: None, + } + } else { + unreachable!("handle later") + } + }) + .map_err(|e| Box::new(e.into()))?; + // todo: don't allow duplicates?. + Ok(output) + } + + fn from_input_str>(_content: P) -> Result> { + todo!() + } +} diff --git a/examples/basic/playground.yml b/examples/basic/playground.yml new file mode 100644 index 0000000..8673ac2 --- /dev/null +++ b/examples/basic/playground.yml @@ -0,0 +1,15 @@ +servers: + - name: playground + playground: + html: | +
+ Hello world! +
+ css: | + @import url("/reset.css"); + + :root { + border: 50px solid pink; + height: 100vh; + overflow: hidden; + } diff --git a/examples/basic/playground_raw.yml b/examples/basic/playground_raw.yml new file mode 100644 index 0000000..8242c5a --- /dev/null +++ b/examples/basic/playground_raw.yml @@ -0,0 +1,30 @@ +servers: + - bind_address: 0.0.0.0:3000 + clients: + log: trace + routes: + - path: /__bslive_playground.js + raw: console.log("haha!") + - path: /__bslive_playground.css + raw: 'body { background: oops }' + - path: / + html: Hello world + inject: + - prepend: | + + + + + + Document + + + + only: '/' + - append: | + + + + only: '/' + - name: bslive:connector + only: '/' diff --git a/examples/md-single/frontmatter.md b/examples/markdown/frontmatter.md similarity index 100% rename from examples/md-single/frontmatter.md rename to examples/markdown/frontmatter.md diff --git a/examples/markdown/playground.md b/examples/markdown/playground.md new file mode 100644 index 0000000..9242404 --- /dev/null +++ b/examples/markdown/playground.md @@ -0,0 +1,28 @@ +--- +servers: + - name: playground +--- + +```html playground + +
+ Hello world! +
+``` + +```css +@import url("reset.css"); + +:root { + border: 1px dotted red; +} + +* { + font-family: system-ui +} +``` + +```js +console.log('Hello from playground.md') +``` + diff --git a/examples/md-single/md-single.md b/examples/markdown/single.md similarity index 93% rename from examples/md-single/md-single.md rename to examples/markdown/single.md index ee75643..df8bd4f 100644 --- a/examples/md-single/md-single.md +++ b/examples/markdown/single.md @@ -1,6 +1,8 @@ ```yaml bslive_input servers: - bind_address: 0.0.0.0:5001 + clients: + log: trace ``` CSS path: diff --git a/tests/live-reload.spec.ts b/tests/live-reload.spec.ts index 8f0c75c..1fe2c23 100644 --- a/tests/live-reload.spec.ts +++ b/tests/live-reload.spec.ts @@ -33,7 +33,6 @@ test.describe('examples/basic/live-reload.yml', { // Trigger the live-reload by touching the CSS file bs.touch('examples/basic/public/styles.css'); await requestPromise; - await page.pause(); // Filter the log messages for specific content and assert const log = messages.filter(([, text]) => text === "[debug] found 1 LINKed stylesheets, 1 @imported stylesheets"); diff --git a/tests/playground.spec.ts b/tests/playground.spec.ts new file mode 100644 index 0000000..2c40873 --- /dev/null +++ b/tests/playground.spec.ts @@ -0,0 +1,18 @@ +import {bstest, test} from './utils'; +import {expect} from "@playwright/test"; + +test.describe('examples/markdown/playground.md', { + annotation: { + type: bstest({ + input: 'examples/markdown/playground.md' + }), + description: '' + } +}, () => { + test('playground', async ({page, bs}) => { + const text: string[] = []; + page.on('console', (msg) => text.push(msg.text())); + await page.goto(bs.path('/'), {waitUntil: 'networkidle'}) + expect(text).toContain('Hello from playground.md') + }); +}) \ No newline at end of file